Android_SDK Quick Start

Android_SDK-quick start

Applicable Model

WT901BLECL

WT9011DCL

Where to download

Please download sample program

https://github.com/WITMOTION/WitBluetooth_BWT901BLE5_0

Introduction to routines

Routine introduction

  1. This example demonstrates how to use the Android Bluetooth 5.0 SDK developed by WitMotion

  2. This routine will demonstrate how to search and connect Bluetooth 5.0 sensors, and control the sensors

  3. Please be familiar with the use of WitMotion Bluetooth 5.0 before using the routine, and understand the protocol of the sensor

Routine directory

libs:Project dependencies the file

java:Project source code

MainActivity: On the main page of the project, the routine has only one activity, and all logic codes are in this activity

Routine dependency

This routine depends on the wit-sdk project. If you want to port it to your own app, please port the wit-sdk.aar under the lib folder in the routine to your app

Add the following dependencies in" build.gradle"

// Must add this dependency:

implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')
implementation 'com.inuker.bluetooth:library:1.4.0'

Project permissions

This project needs to be connected to Bluetooth, so you need to obtain permission from the customer. If you need to port it to your app, please make sure that your app also applies for the following permissions

  1. AndroidManifest.xml Main manifest file permission statement

Please declare the following permissions in your program's main manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.wit.example">
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>
    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Witexampleble5"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
  1. Code application permission

Before using Bluetooth, please call WitBluetoothManager.initInstance to initialize the Bluetooth manager. When initializing the Bluetooth manager, the Bluetooth manager will apply for permission from the user

/**
* activity when created
*
* @author huangyajun
* @date 2022/6/29 8:43
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Initialize the Bluetooth manager, here will apply for Bluetooth permissions
    WitBluetoothManager.initInstance(this);
    // start search button
    Button startSearchButton = findViewById(R.id.startSearchButton);
    startSearchButton.setOnClickListener((v) -> {
        startDiscovery();
    });
    // stop search button
    Button stopSearchButton = findViewById(R.id.stopSearchButton);
    stopSearchButton.setOnClickListener((v) -> {
        stopDiscovery();
    });
    // Accelerometer calibration button
    Button appliedCalibrationButton = findViewById(R.id.appliedCalibrationButton);
    appliedCalibrationButton.setOnClickListener((v) -> {
        handleAppliedCalibration();
    });
    // Start field calibration button
    Button startFieldCalibrationButton = findViewById(R.id.startFieldCalibrationButton);
    startFieldCalibrationButton.setOnClickListener((v) -> {
        handleStartFieldCalibration();
    });
    // End magnetic field calibration button
    Button endFieldCalibrationButton = findViewById(R.id.endFieldCalibrationButton);
    endFieldCalibrationButton.setOnClickListener((v) -> {
        handleEndFieldCalibration();
    });
    // Read 03 register button
    Button readReg03Button = findViewById(R.id.readReg03Button);
    readReg03Button.setOnClickListener((v) -> {
        handleReadReg03();
    });
    // Automatically refresh the data thread
    Thread thread = new Thread(this::refreshDataTh);
    destroyed = false;
    thread.start();
}

Search device

After applying for permission, you can let the Bluetooth manager start searching for Bluetooth devices

Search Bluetooth

The following is the code for searching Bluetooth. You need to get the Bluetooth manager, and jthen call the startDiscovery method. If you need to get the device found by the Bluetooth manager, you need to call registerObserver. After finding the device, you will be notified of the found Bluetooth device through the onFoundBle method of registerObserver

    public void startDiscovery() {

        // 开始搜索设备
        // Turn off all device
        for (int i = 0; i < bwt901bleList.size(); i++) {
            Bwt901ble bwt901ble = bwt901bleList.get(i);
            bwt901ble.removeRecordObserver(this);
            bwt901ble.close();
        }

        // 清除所有设备
        // Erase all devices
        bwt901bleList.clear();

        // 开始搜索蓝牙
        // Start searching for bluetooth
        try {
            // 获得蓝牙管理器
            // get bluetooth manager
            WitBluetoothManager bluetoothManager = WitBluetoothManager.getInstance();
            // 注册监听蓝牙
            // Monitor communication signals
            bluetoothManager.registerObserver(this);
            // 指定要搜索的蓝牙名称
            // Specify the Bluetooth name to search for
            WitBluetoothManager.DeviceNameFilter = Arrays.asList("WT");
            // 开始搜索
            // start search
            bluetoothManager.startDiscovery();
        } catch (BluetoothBLEException e) {
            e.printStackTrace();
        }
    }

After starting the search, the onFoundBle method will be called when the device is found. Here, the device is connected immediately after the device is found.

/**
* This method will be called back when a Bluetooth 5.0 device is found
*
* @author huangyajun
* @date 2022/6/29 8:46
*/
@Override
public void onFoundBle(BluetoothBLE bluetoothBLE) {
    // Create a Bluetooth 5.0 sensor connection object
    Bwt901ble bwt901ble = new Bwt901ble(bluetoothBLE);
    // Avoid duplicate connections
    for (int i = 0; i < bwt901bleList.size(); i++) {
        if (Objects.equals(bwt901bleList.get(i).getDeviceName(), bwt901ble.getDeviceName())) {
            return;
        }
    }
    // add to device list
    bwt901bleList.add(bwt901ble);
    // registration data record
    bwt901ble.registerRecordObserver(this);
    // turn on the device
    try {
        bwt901ble.open();
    } catch (OpenDeviceException e) {
        // Failed to open device
        e.printStackTrace();
    }
}

Stop searching

After starting the search, the Bluetooth manager will not stop the search by itself, you need to call its stopDiscovery method to stop the search

/**
* Stop searching for devices
*
* @author huangyajun
* @date 2022/6/29 10:04
*/
public void stopDiscovery() {
    // stop searching bluetooth
    try {
        // get bluetooth manager
        WitBluetoothManager bluetoothManager = WitBluetoothManager.getInstance();
        // Unregister listening bluetooth
        bluetoothManager.removeObserver(this);
        // stop searching
        bluetoothManager.stopDiscovery();
    } catch (BluetoothBLEException e) {
        e.printStackTrace();
    }
}

Receive the sensor data

Get data

The data of the sensor can be obtained through the getDeviceData method, getDeviceData needs to receive a key value, and this key value is stored in the WitSensorKey class

/**
* get data from a device
*
* @author huangyajun
* @date 2022/6/29 11:37
*/
private String getDeviceData(Bwt901ble bwt901ble) {
    StringBuilder builder = new StringBuilder();
    builder.append(bwt901ble.getDeviceName()).append("\n");
    builder.append(getString(R.string.accX)).append(":").append(bwt901ble.getDeviceData(WitSensorKey.AccX)).append("g \t");
    builder.append(getString(R.string.accY)).append(":").append(bwt901ble.getDeviceData(WitSensorKey.AccY)).append("g \t");
    builder.append(getString(R.string.accZ)).append(":").append(bwt901ble.getDeviceData(WitSensorKey.AccZ)).append("g \n");
    builder.append(getString(R.string.asX)).append(":").append(bwt901ble.getDeviceData(WitSensorKey.AsX)).append("°/s \t");
    builder.append(getString(R.string.asY)).append(":").append(bwt901ble.getDeviceData(WitSensorKey.AsY)).append("°/s \t");
    builder.append(getString(R.string.asZ)).append(":").append(bwt901ble.getDeviceData(WitSensorKey.AsZ)).append("°/s \n");
    builder.append(getString(R.string.angleX)).append(":").append(bwt901ble.getDeviceData(WitSensorKey.AngleX)).append("° \t");
    builder.append(getString(R.string.angleY)).append(":").append(bwt901ble.getDeviceData(WitSensorKey.AngleY)).append("° \t");
    builder.append(getString(R.string.angleZ)).append(":").append(bwt901ble.getDeviceData(WitSensorKey.AngleZ)).append("° \n");
    builder.append(getString(R.string.hX)).append(":").append(bwt901ble.getDeviceData(WitSensorKey.HX)).append("\t");
    builder.append(getString(R.string.hY)).append(":").append(bwt901ble.getDeviceData(WitSensorKey.HY)).append("\t");
    builder.append(getString(R.string.hZ)).append(":").append(bwt901ble.getDeviceData(WitSensorKey.HZ)).append("\n");
    builder.append(getString(R.string.versionNumber)).append(":").append(bwt901ble.getDeviceData(            WitSensorKey.VersionNumber)).append("\n");
    return builder.toString();
}

Record data

When the device is turned on, you can call the registerRecordObserver method of bwt901ble, and when the sensor data is updated, bwt901ble will call the onRecord method to notify you of the recorded data

/**
* This method will be called back when a Bluetooth 5.0 device is found
*
* @author huangyajun
* @date 2022/6/29 8:46
*/
@Override
public void onFoundBle(BluetoothBLE bluetoothBLE) {
    // Create a Bluetooth 5.0 sensor connection object
    Bwt901ble bwt901ble = new Bwt901ble(bluetoothBLE);
    // Avoid duplicate connections
    for (int i = 0; i < bwt901bleList.size(); i++) {
        if (Objects.equals(bwt901bleList.get(i).getDeviceName(), bwt901ble.getDeviceName())) {
            return;
        }
    }
    // add to device list
    bwt901bleList.add(bwt901ble);
    // registration data record
    bwt901ble.registerRecordObserver(this);
    // turn on the device
    try {
        bwt901ble.open();
    } catch (OpenDeviceException e) {
        // Failed to open device
        e.printStackTrace();
    }
}

/**
* This method will be called back when data needs to be recorded
*
* @author huangyajun
* @date 2022/6/29 8:46
*/
@Override
public void onRecord(Bwt901ble bwt901ble) {
    String deviceData = getDeviceData(bwt901ble);
    Log.d(TAG, "device data [ " + bwt901ble.getDeviceName() + "] = " + deviceData);
}

Set sensor

Accelerometer calibration

Addition calibration can be done by calling AppliedCalibration of Bwt901ble. Remember to unlock the register before accumulator calibration

/**
* Make all devices do acceleration calibration
*
* @author huangyajun
* @date 2022/6/29 10:25
*/
private void handleAppliedCalibration() {
    for (int i = 0; i < bwt901bleList.size(); i++) {
        Bwt901ble bwt901ble = bwt901bleList.get(i);
        // unlock register
        bwt901ble.unlockReg();
        // send command
        bwt901ble.appliedCalibration();
    }
    Toast.makeText(this, "OK", Toast.LENGTH_LONG).show();
}

Magnetic calibration

You can control the start and end of magnetic field calibration by calling the startFieldCalibration and endFieldCalibration methods of Bwt901ble. After starting the magnetic field calibration, please rotate 2-3 circles around each of the x y z axes of the sensor. If you don’t know the magnetic field calibration, you can consult our technical staff support.

Start magnetic field calibration

/**
* Let all devices start magnetic field calibration
*
* @author huangyajun
* @date 2022/6/29 10:25
*/
private void handleStartFieldCalibration() {
    for (int i = 0; i < bwt901bleList.size(); i++) {
        Bwt901ble bwt901ble = bwt901bleList.get(i);
        // unlock register
        bwt901ble.unlockReg();
        // send command
        bwt901ble.startFieldCalibration();
    }
    Toast.makeText(this, "OK", Toast.LENGTH_LONG).show();
}

End magnetic field calibration

/**
* End magnetic field calibration
*
* @author huangyajun
* @date 2022/6/29 10:25
*/
private void handleEndFieldCalibration() {
    for (int i = 0; i < bwt901bleList.size(); i++) {
        Bwt901ble bwt901ble = bwt901bleList.get(i);
        // unlock register
        bwt901ble.unlockReg();
        // send command
        bwt901ble.endFieldCalibration();
    }
    Toast.makeText(this, "OK", Toast.LENGTH_LONG).show();
}

Read sensor register

This time demonstrates how to read the 03 register of the sensor, use the sendProtocolData method to read the sensor data, and get the data of the register through getDeviceData after reading.

/**
* Read the data of register 03
*
* @author huangyajun
* @date 2022/6/29 10:25
*/
private void handleReadReg03() {
    for (int i = 0; i < bwt901bleList.size(); i++) {
        Bwt901ble bwt901ble = bwt901bleList.get(i);
        // The sendProtocolData method must be used, and the device will read the register value using this method
        int waitTime = 200;
        // Send the command of the command and wait for 200ms
        bwt901ble.sendProtocolData(new byte[]{(byte) 0xff, (byte) 0xAA, (byte) 0x27, (byte) 0x03, (byte) 0x00}, waitTime);
        //Get the value of register 03
        String reg03Value = bwt901ble.getDeviceData("03");
        // If you read reg03Value is the value of the register, if you don’t read it, you can enlarge the             waitTime, or read it several times
        Toast.makeText(this, bwt901ble.getDeviceName() + " reg03Value: " + reg03Value,         Toast.LENGTH_LONG).show();
    }
}

Last updated