Project introduction

Implementation of Bluetooth intelligent door lock Android client based on multi-level security mechanism.

The client of the project is based on the Android platform and communicates with the bottom layer through CC2541 Bluetooth chip. The door lock part is controlled by HT32F1656 single chip microcomputer and realizes the function of intelligent memory door lock based on Bluetooth technology, biosensing technology, RFID technology, etc. Using biosensor technology, RFID technology to achieve a variety of identification and verification mechanisms. Select system working mode through APP to adapt to different working environment. At the same time, through the standby reset system, to solve the failure and crash problem, through the standby battery power supply system, to prevent the power supply of the main power supply.

Android client open source address: github.com/rockzhai/BL… Welcome to ask questions ~ if you like, look forward to your star

About the Android – BLE

BLE: Full name for Bluetooth Low Energy, also known as Bluetooth 4.0, is mainly promoted by Low power consumption. Therefore, BLE technology is more applicable to wearable devices and smart homes. For this reason, our team members choose BLE chips and technologies for development.

A key concept

  • Generic Attribute Profile(GATT) – THE GATT Profile is a Generic specification for sending and receiving data blocks over a BLE link. BLE application development is also based on GATT.
  • Attribute Protocol (ATT) – GATT is based on the ATT Protocol and is also called GATT/ATT. ATT is optimized to run on BLE devices, and to do so, it uses as few bytes as possible. Each attribute is identified by a unique unified identifier (UUID), and each String UUID uses the 128-bit standard format. Attributes are formatted as Characteristics and services through ATT.
  • A Characteristic variable consists of a single variable and 0-n descriptors used to describe Characteristic variables. Characteristic can be thought of as a type, similar to classes.
  • Service Services are a collection of characteristic.

Service, Characteristic, and Descriptor are all unique identifiers (UUID). A Bluetooth 4.0 terminal can contain multiple services, a Service can contain multiple Characteristic, a Characteristic can contain a Value and multiple descriptors, One Descriptor contains a Value. Generally speaking, Characteristic is the key to exchange data between mobile phones and BLE terminals. Characteristic has many fields related to permissions, such as PERMISSION and PROPERTY. Characteristic of the PROPERTY attribute can be set by an operator, speaking, reading and writing, such as READ | WRITE, READ | WRITE_NO_RESPONSE | NOTIFY, so after reading the PROPERTY used to break down into a combination of).

permissions

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>Copy the code

State that APP is only available for devices with BLE

<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>Copy the code

The value of required can be set to false as required.

BLE specific Settings

Of course, you should check whether the device supports BLE before setting it. Now mainstream models have perfect BLE support. After checking, you can directly start Bluetooth:

  1. It is important to note that in Android there is only one BluetoothAdapter that the APP uses to interact with the system. Here we use getSystemSrvice() to return to BluetoothManager.

    BluetoothManager = (BluetoothManager) getSystemService(context.bluetooth_service); mBluetoothAdapter = bluetoothManager.getAdapter(); Log.i(TAG, "mBluetoothAdapter = " + mBluetoothAdapter);Copy the code
  2. Open the bluetooth

    Mbluetoothadapter.enable (); Mactionbar. setSubtitle(" Bluetooth enabled "); myBleAddress = mBluetoothAdapter.getAddress();Copy the code
  3. Search equipment

    mBluetoothAdapter.startLeScan(mLeScanCallback);Copy the code
  4. Processing search results

    / / equipment search results private BluetoothAdapter. LeScanCallback mLeScanCallback = new BluetoothAdapter. LeScanCallback () {@ Override public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) { runOnUiThread(new Runnable() { @Override public void run() { //5F:52:CC:7F:86:55 // 20:91:48:50:5E :8E //D4: F5:13:78:e9:63 //20:91:48:50:58:DE Here is the test CC2541 Bluetooth MAC address if (device.getAddress().equals("20:91:48:50:58:DE")) { scanLeDevice(false); Log.e(TAG, device.getAddress()); Log.e(TAG, device.getName()); boolean bRet = mBLE.connect(device.getAddress()); Thread.sleep(2000); thread.sleep (2000); } catch (InterruptedException e) { e.printStackTrace(); } if (bRet) {mactionbar.setSubtitle (" Connected, please log in "); Log.e(TAG, "connect+++++success"); Log.e(TAG, Constant.HEAD_CHAR + "0B" + Constant.SEND_ADDRESS + Constant.SEVER_BLUETOOTH + myBleAddress + Constant.END_CHAR); }}}}); // rssi Log.i(TAG, "rssi = " + rssi); Log.i(TAG, "mac = " + device.getAddress()); Log.i(TAG, "scanRecord.length = " + scanRecord.length); }};Copy the code
  5. Communicate in real time

    Write data via writeCharacteristic:

    public static void writeChar(byte[] bytes) {
        Log.i(TAG, "Message = " + bytes);
        if (gattCharacteristic_char != null) {
            gattCharacteristic_char.setValue(bytes);
            mBLE.writeCharacteristic(gattCharacteristic_char);
        }
    }Copy the code

    OnCharacteristicWrite method to read data from bluetooth method:

    private BluetoothLeClass.OnDataAvailableListener mOnDataAvailable = new BluetoothLeClass.OnDataAvailableListener() { /** Override public void onCharacteristicRead(BluetoothGatt, BluetoothGatt, BluetoothGattCharacteristic characteristic, int status) { Log.e(TAG, "onCharRead " + gatt.getDevice().getName() + " read " + characteristic.getUuid().toString() + " -> " + Utils.bytesToHexString(characteristic.getValue())); } @override public void onCharacteristicWrite(BluetoothGatt, BluetoothGatt, BluetoothGattCharacteristic characteristic) { // Log.e(TAG, "onCharWrite " + gatt.getDevice().getName() + " write " // + characteristic.getUuid().toString() + " -> " // + new String(characteristic.getValue())); String str = Utils.bytesToHexString(characteristic.getValue()); Log.e(TAG, "+++++++++++++++++++++" + str); // The data sent by bluetooth is processed here... }};Copy the code

The problem summary

Connect the debugging

First of all, in client development, it is not necessary to set baud rate in the program, because it is not serial port development. BLE is highly integrated in Android and only needs to meet the above conditions to communicate, while BLE device development needs to be set, which can be designed according to their own needs. At the same time, when developing and debugging the client, Portland must be set in the serial port assistant. Of course, this value comes from our hardware development students.

The data transfer

During the development, it was found that the hardware’s data parsing was in byte stream parsing, and the data bit sent by the client was of String type at the beginning. At this time, in serial port debugging, serial port assistant could display the data sent by the client, while BLE chip could not receive it. The solution is to convert the String to a Byte stream for transmission.

/ / String byte public static byte [] hexStringToBytes (String hexString) {if (hexString = = null | | hexString. Equals (" ")) { return null; } hexString = hexString.toUpperCase(); int length = hexString.length() / 2; char[] hexChars = hexString.toCharArray(); byte[] d = new byte[length]; for (int i = 0; i < length; i++) { int pos = i * 2; d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); } return d; }Copy the code

Agreement agreed

In the development of interaction with hardware, we cannot carry out data communication through JOSN or XML and other similar data as in the development of applications. Instead, we should adopt the communication protocol based on the hexadecimal hardware base. Protocol screenshots (pictures cannot be loaded, please refer to here) :

So we do hexadecimal conversions between passed and parsed data:

Public static String toHexString(String s) {String STR = ""; for (int i = 0; i < s.length(); i++) { int ch = (int) s.charAt(i); String s4 = Integer.toHexString(ch); str = str + s4; } return str; } public static String hexToString(String s) {byte[] baKeyword = new byte[s.length() / 2]; for (int i = 0; i < baKeyword.length; i++) { try { baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring( i * 2, i * 2 + 2), 16)); } catch (Exception e) { e.printStackTrace(); } } try { s = new String(baKeyword, "utf-8"); // UTF-16le:Not } catch (Exception e1) { e1.printStackTrace(); } return s; }Copy the code

digression

In addition to the shell, the smart lock was installed and debugged by several partners. From the mechanical structure to the program development, we stayed together for a week until more than an hour before the contest defense. We encountered a fatal BUG and did not know what to do, so we urgently adjusted the program, disassembled and re-installed it. Seem to be completely forgot about our cook four or five consecutive evening all night, fortunately and defense of a live demonstration for a whole day in the process of the equipment and the program does not appear any problems, also won the first prize in chongqing and best MCU program design, before the game that a few hours, really want to give up directly, but in the end still insist on down, Thank you for your perseverance. Although I am close to graduation and this work was written a year ago, I still want to write it. The most important reason is not to share technology, but to insist on technology.

I hope I can continue to advance on the road of technology. As long as I insist on it until the last second, no one knows the result. Maybe the next is a bright future, or maybe the next is another paradise.

Attached to the effect of a real shot to everyone (pictures can not be loaded can movehere) :