Android_SDK Quick Start

Android_SDK quick start

Applicable Model

BWT61CL

BWT901CL

Routine download

Please download sample program

https://github.com/WITMOTION/WitStandardProtocol_JY901

Introduction to routines

Routine introduction

1. This example demonstrates how to use the Android Bluetooth 2.0 SDK developed by WITMOTION

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

3. Please be familiar with the use of Wit-motion Bluetooth 2.0 before using the routine, and understand the protocol of the sensor

Routine directory

libs: Project dependencies

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

build.gradle Add the following dependencies to

// This dependencies must be added

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>

2.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();
    });
    // 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 then 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 onFoundSPP method of register Observer

    public void startDiscovery() {

        // 关闭所有设备
        // Turn off all device
        for (int i = 0; i < bwt901clList.size(); i++) {
            Bwt901cl bwt901cl = bwt901clList.get(i);
            bwt901cl.removeRecordObserver(this);
            bwt901cl.close();
        }

        // 清除所有设备
        // Erase all devices
        bwt901clList.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("HC-06");
            // 开始搜索
            // start search
            bluetoothManager.startDiscovery();
        } catch (BluetoothBLEException e) {
            e.printStackTrace();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

After starting the search, the onFoundDual 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 data needs to be recorded
     *
     * @author huangyajun
     * @date 2022/6/29 8:46
     */
    @Override
    public void onFoundDual(BluetoothBLE bluetoothBLE) {
        // 创建蓝牙2.0传感器连接对象
        // Create a Bluetooth 2.0 sensor connection object
        Bwt901cl bwt901cl = new Bwt901cl(bluetoothBLE);
        // 避免重复连接
        // Avoid duplicate connections
        for(int i = 0; i < bwt901clList.size(); i++){
            if(Objects.equals(bwt901clList.get(i).getDeviceName(), bwt901cl.getDeviceName())){
                return;
            }
        }
        // 添加到设备列表
        // add to device list
        bwt901clList.add(bwt901cl);

        // 注册数据记录
        // Registration data record
        bwt901cl.registerRecordObserver(this);

        // 打开设备
        // Turn on the device
        try {
            bwt901cl.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 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(Bwt901cl bwt901cl) {
    StringBuilder builder = new StringBuilder();
    builder.append(bwt901cl.getDeviceName()).append("\n");
    builder.append(getString(R.string.accX)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.AccX)).append("g \t");
    builder.append(getString(R.string.accY)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.AccY)).append("g \t");
    builder.append(getString(R.string.accZ)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.AccZ)).append("g \n");
    builder.append(getString(R.string.asX)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.AsX)).append("°/s \t");
    builder.append(getString(R.string.asY)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.AsY)).append("°/s \t");
    builder.append(getString(R.string.asZ)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.AsZ)).append("°/s \n");
    builder.append(getString(R.string.angleX)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.AngleX)).append("° \t");
    builder.append(getString(R.string.angleY)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.AngleY)).append("° \t");
    builder.append(getString(R.string.angleZ)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.AngleZ)).append("° \n");
    builder.append(getString(R.string.hX)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.HX)).append("\t");
    builder.append(getString(R.string.hY)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.HY)).append("\t");
    builder.append(getString(R.string.hZ)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.HZ)).append("\n");
    builder.append(getString(R.string.t)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.T)).append("\n");
    builder.append(getString(R.string.electricQuantityPercentage)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.ElectricQuantityPercentage)).append("\n");
    builder.append(getString(R.string.versionNumber)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.VersionNumber)).append("\n");
    return builder.toString();j
}

Record data

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

/**
* This method will be called back when a Bluetooth 2.0 device is found
*
* @author huangyajun
* @date 2022/6/29 10:01
*/
@Override
public void onFoundSPP(BluetoothSPP bluetoothSPP) {
    // Create a Bluetooth 2.0 sensor connection object
    Bwt901cl bwt901cl = new Bwt901cl(bluetoothSPP);
    // Avoid duplicate connections
    for(int i = 0; i < bwt901clList.size(); i++){
        if(Objects.equals(bwt901clList.get(i).getDeviceName(), bwt901cl.getDeviceName())){
        return;
    }
    }
    // Add to device list
    bwt901clList.add(bwt901cl);
    // Registration data record
    bwt901cl.registerRecordObserver(this);
    // Turn on the device
    try {
        bwt901cl.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(Bwt901cl bwt901cl) {
    String deviceData = getDeviceData(bwt901cl);
    Log.d(TAG, "device data [ " + bwt901cl.getDeviceName() + "] = " + deviceData);
}

Set sensor

Accelerometer Calibration

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

/**
* Have all devices accelerometer calibrated
*
* @author huangyajun
* @date 2022/6/29 10:25
*/
private void handleAppliedCalibration() {
    for (int i = 0; i < bwt901clList.size(); i++) {
        Bwt901cl bwt901cl = bwt901clList.get(i);
        // Unlock register
        bwt901cl.unlockReg();
        // Send command
        bwt901cl.appliedCalibration();
    }
    Toast.makeText(this, "OK", Toast.LENGTH_LONG).show()
}

Magnetic Field Calibration

You can control the start and end of magnetic field calibration by calling the startFieldCalibration and endFieldCalibration methods of Bwt901cl. 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

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

End magnetic field calibration

/**
* Let all devices end the magnetic field calibration
*
* @author huangyajun
* @date 2022/6/29 10:25
*/
private void handleEndFieldCalibration() {
    for (int i = 0; i < bwt901clList.size(); i++) {
        Bwt901cl bwt901cl = bwt901clList.get(i);
        // Unlock register
        bwt901cl.unlockReg();
        // Send command
        bwt901cl.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 < bwt901clList.size(); i++) {
        Bwt901cl bwt901cl = bwt901clList.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
        bwt901cl.sendProtocolData(new byte[]{(byte) 0xff, (byte) 0xAA, (byte) 0x27, (byte) 0x03, (byte) 0x00}, waitTime);
        // Get the value of register 03
        String reg03Value = bwt901cl.getDeviceData("03");
        // If it is read up, reg03Value is the value of the register, if not read up, you can enlarge the waitTime, or read it several times
        Toast.makeText(this, bwt901cl.getDeviceName() + " reg03Value: " + reg03Value, Toast.LENGTH_LONG).show();
    }
}

Last updated