【TL8266】向藍牙模塊發送AT指令的APP

前一篇文章寫了如何顯示BLE設備,在子項點擊事件中只彈出了一個吐司提示點擊的是哪個模塊的地址,這一篇就將它改成發送指令

public class MainActivity extends AppCompatActivity implements View.OnClickListener,AdapterView.OnItemClickListener{

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        BluetoothDevice device= (BluetoothDevice) mListViewAdapter.getItem(i);
        if (device==null)return;
        Intent intent=new Intent(this,BleAtActivity.class);
        intent.putExtra("name",device.getName());
        intent.putExtra("address",device.getAddress());
        startActivity(intent);
    }

}

跳轉到BleAtActivity後,在這個頁面放置四個按鈕用於發送,連接,斷開和改名
這裏寫圖片描述

ble_at_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/send_button"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/connect_button"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/disconnect_button"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/edit_name"/>

</LinearLayout>

延續之前的代碼風格,用init函數寫onCreate,由於只寫發送,不接收,所以代碼量很少,也沒什麼特別的,注意BluetoothLeService不是系統的類,是需要自定義的,用到了其中的一些連接的方法和發送的方法,在後面有全文(Ctrl鍵+F搜索BluetoothLeService.java和BleSppGattAttributes.java,直接複製即可),我一直沒有機會重寫它,有機會一定要自己寫一個


public class BleAtActivity extends Activity implements View.OnClickListener{

    private int mLedStatus=0;

    private Button button;
    private Button connectButton;
    private Button disconnectButton;
    private Button editNameButton;

    private String mAddressString;
    private String mNameString;
    private BluetoothLeService mBluetoothLeService;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.ble_at_layout);
        initView();
        initData();
        initEvent();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mServiceConnection);
        mBluetoothLeService = null;
    }

    private void initView(){
        button=findViewById(R.id.send_button);
        connectButton=findViewById(R.id.connect_button);
        disconnectButton=findViewById(R.id.disconnect_button);
        editNameButton=findViewById(R.id.edit_name);

    }

    private void initData(){

        mAddressString =getIntent().getStringExtra("address");
        mNameString=getIntent().getStringExtra("name");

        button.setText("開/關");
        connectButton.setText("連接");
        disconnectButton.setText("未連接");
        editNameButton.setText("改名");

    }

    private void initEvent(){

        button.setOnClickListener(this);
        connectButton.setOnClickListener(this);
        disconnectButton.setOnClickListener(this);
        editNameButton.setOnClickListener(this);

        Intent intent=new Intent(this,BluetoothLeService.class);
        bindService(intent,mServiceConnection,BIND_AUTO_CREATE);

    }

    @Override
    public void onClick(View view) {

        switch (view.getId()){
            case R.id.send_button:
                if (mLedStatus==0){
                    sendAt("AT+IO1=H");
                    mLedStatus=1;
                }else {
                    sendAt("AT+IO1=L");
                    mLedStatus=0;
                }
                break;
            case R.id.connect_button:
                mBluetoothLeService.connect(mAddressString);
                break;
            case R.id.disconnect_button:
                mBluetoothLeService.disconnect();
                break;
            case R.id.edit_name:
                dialog(mNameString);
        }
    }

    private void dialog(String name){

        final EditText et = new EditText(this);
        final AlertDialog.Builder dialog=new AlertDialog.Builder(this);
        dialog.setTitle("輸入"+name+"新名稱");
        dialog.setView(et);

        dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                sendAt("AT+NAME="+et.getText().toString());
            }
        });
        dialog.setNegativeButton("取消",null);
        dialog.create().show();

    }

    private void sendAt(String s)
    {
        byte[] buf=s.getBytes();
        mBluetoothLeService.writeAT(buf);
    }

}

如果你複製完了兩個類,而且alt加回車加了所有的類以後,發現還有兩個標紅的,那麼恭喜你,現在到了全篇文章最核心的部分

做一個ServiceConnection,用於綁定服務的第二個參數,主要就是對mBluetoothLeService的操作,根據藍牙的地址連接到相關的設備,當我們綁定服務時就執行連接方法,這是整篇文章中最複雜的部分,可以按Ctrl鍵+F鍵觀察mBluetoothLeService的位置

public class BleAtActivity extends Activity implements View.OnClickListener{

    private ServiceConnection mServiceConnection=new ServiceConnection() {
        @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {

            mBluetoothLeService=((BluetoothLeService.LocalBinder)iBinder).getService();

            if (!mBluetoothLeService.initialize())finish();

            mBluetoothLeService.connect(mAddressString);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService=null;
        }
    };    
}

附錄:
BluetoothLeService.java

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import java.util.List;
import java.util.UUID;

/**
 * Service for managing connection and data communication with a GATT server hosted on a
 * given Bluetooth LE device.
 */
public class BluetoothLeService extends Service {
    private final static String TAG = BluetoothLeService.class.getSimpleName();

    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private String mBluetoothDeviceAddress;
    private BluetoothGatt mBluetoothGatt;
    //ble characteristic
    private BluetoothGattCharacteristic mNotifyCharacteristic;
    private BluetoothGattCharacteristic mWriteCharacteristic;
    private BluetoothGattCharacteristic mATCharacteristic;

    private int mConnectionState = STATE_DISCONNECTED;

    private static final int STATE_DISCONNECTED = 0;
    private static final int STATE_CONNECTING = 1;
    private static final int STATE_CONNECTED = 2;

    public final static String ACTION_GATT_CONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
    public final static String ACTION_GATT_SERVICES_DISCOVERED =
            "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
    public final static String ACTION_DATA_AVAILABLE =
            "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
    public final static String EXTRA_DATA =
            "com.example.bluetooth.le.EXTRA_DATA";
    public final static String ACTION_WRITE_SUCCESSFUL =
            "com.example.bluetooth.le.WRITE_SUCCESSFUL";
    public final static String ACTION_GATT_SERVICES_NO_DISCOVERED =
            "com.example.bluetooth.le.GATT_SERVICES_NO_DISCOVERED";
   //

    public final static UUID UUID_BLE_SPP_NOTIFY = UUID.fromString(BleSppGattAttributes.BLE_SPP_Notify_Characteristic);
    public final static UUID UUID_BLE_SPP_NOTIFY_0 = UUID.fromString(BleSppGattAttributes.BLE_SPP_Notify_Characteristic_0);
    public final static UUID UUID_BLE_SPP_AT = UUID.fromString(BleSppGattAttributes.BLE_SPP_AT_Characteristic);
    // Implements callback methods for GATT events that the app cares about.  For example,
    // connection change and services discovered.
    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            String intentAction;
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                intentAction = ACTION_GATT_CONNECTED;
                mConnectionState = STATE_CONNECTED;
                broadcastUpdate(intentAction);
                Log.i(TAG, "Connected to GATT server.");
                // Attempts to discover services after successful connection.
                Log.i(TAG, "Attempting to start service discovery:" +
                        mBluetoothGatt.discoverServices());

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                intentAction = ACTION_GATT_DISCONNECTED;
                mConnectionState = STATE_DISCONNECTED;
                Log.i(TAG, "Disconnected from GATT server.");
                broadcastUpdate(intentAction);
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                // 默認先使用 B-0006/TL8266 服務發現
                BluetoothGattService service = gatt.getService(UUID.fromString(BleSppGattAttributes.BLE_SPP_Service));
               // service.getInstanceId()
                if (service!=null)
                {
                    //默認找到B-0006/tl8266的服務,繼續查找B-0006/tl8266的特徵值
                    mNotifyCharacteristic = service.getCharacteristic(UUID.fromString(BleSppGattAttributes.BLE_SPP_Notify_Characteristic));
                    mWriteCharacteristic  = service.getCharacteristic(UUID.fromString(BleSppGattAttributes.BLE_SPP_Write_Characteristic));
                    mATCharacteristic  = service.getCharacteristic(UUID.fromString(BleSppGattAttributes.BLE_SPP_AT_Characteristic));
                }
//                else
//                {
//                    //沒有找到,查找是否是B-002/B-0004
//                    service = gatt.getService(UUID.fromString(BleSppGattAttributes.BLE_SPP_Service_0));
//                    if (service !=null)
//                    {
//                        mNotifyCharacteristic = service.getCharacteristic(UUID.fromString(BleSppGattAttributes.BLE_SPP_Notify_Characteristic_0));
//                        mWriteCharacteristic = service.getCharacteristic(UUID.fromString(BleSppGattAttributes.BLE_SPP_Write_Characteristic_0));
//                    }
//                }

//                BluetoothGattService service = gatt.getService(UUID.fromString(BleSppGattAttributes.BLE_SPP_Service_0));
//                mNotifyCharacteristic = service.getCharacteristic(UUID.fromString(BleSppGattAttributes.BLE_SPP_Notify_Characteristic_0));
//                mWriteCharacteristic  = service.getCharacteristic(UUID.fromString(BleSppGattAttributes.BLE_SPP_Write_Characteristic_0));
                if (mNotifyCharacteristic!=null)
                {
                    broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
                    //使能Notify
                    setCharacteristicNotification(mNotifyCharacteristic,true);
                    setCharacteristicNotification(mATCharacteristic,true);
                }

                if (service==null)
                {
                    Log.v("log","service is null");
                    broadcastUpdate(ACTION_GATT_SERVICES_NO_DISCOVERED);
                   // mBluetoothGatt.discoverServices();
                }

            } else {
                Log.w(TAG, "onServicesDiscovered received: " + status);
            }
        }


        @Override
        public void onCharacteristicRead(BluetoothGatt gatt,
                                         BluetoothGattCharacteristic characteristic,
                                         int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                                            BluetoothGattCharacteristic characteristic) {
            broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
        }

        //Will call this when write successful
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_WRITE_SUCCESSFUL);
                Log.v("log","Write OK");
            }
        }
    };

    private void broadcastUpdate(final String action) {
        final Intent intent = new Intent(action);
        sendBroadcast(intent);
    }

    private void broadcastUpdate(final String action,
                                 final BluetoothGattCharacteristic characteristic) {
        final Intent intent = new Intent(action);

       // if (UUID_BLE_SPP_NOTIFY.equals(characteristic.getUuid()) || UUID_BLE_SPP_NOTIFY_0.equals(characteristic.getUuid()))
         {
             // For all other profiles, writes the data formatted in HEX.
             final byte[] data = characteristic.getValue();
             if (data != null && data.length > 0)
             {
                 intent.putExtra(EXTRA_DATA,data);
             }
        }

        sendBroadcast(intent);
    }

    public class LocalBinder extends Binder {
        BluetoothLeService getService() {
            return BluetoothLeService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        // After using a given device, you should make sure that BluetoothGatt.close() is called
        // such that resources are cleaned up properly.  In this particular example, close() is
        // invoked when the UI is disconnected from the Service.
        close();
        return super.onUnbind(intent);
    }

    private final IBinder mBinder = new LocalBinder();

    /**
     * Initializes a reference to the local Bluetooth adapter.
     *
     * @return Return true if the initialization is successful.
     */
    public boolean initialize() {
        // For API level 18 and above, get a reference to BluetoothAdapter through
        // BluetoothManager.
        if (mBluetoothManager == null) {
            mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
            if (mBluetoothManager == null) {
                Log.e(TAG, "Unable to initialize BluetoothManager.");
                return false;
            }
        }

        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
            return false;
        }

        return true;
    }

    /**
     * Connects to the GATT server hosted on the Bluetooth LE device.
     *
     * @param address The device address of the destination device.
     *
     * @return Return true if the connection is initiated successfully. The connection result
     *         is reported asynchronously through the
     *         {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
     *         callback.
     */
    public boolean connect(final String address) {
        if (mBluetoothAdapter == null || address == null) {
            Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
            return false;
        }

        // Previously connected device.  Try to reconnect.
        if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
                && mBluetoothGatt != null) {
            Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
            if (mBluetoothGatt.connect()) {
                mConnectionState = STATE_CONNECTING;
                return true;
            } else {
                return false;
            }
        }

        final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        if (device == null) {
            Log.w(TAG, "Device not found.  Unable to connect.");
            return false;
        }
        // We want to directly connect to the device, so we are setting the autoConnect
        // parameter to false.
        mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
        Log.d(TAG, "Trying to create a new connection.");
        mBluetoothDeviceAddress = address;
        mConnectionState = STATE_CONNECTING;
        return true;
    }

    /**
     * Disconnects an existing connection or cancel a pending connection. The disconnection result
     * is reported asynchronously through the
     * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
     * callback.
     */
    public void disconnect() {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.disconnect();
    }

    /**
     * After using a given BLE device, the app must call this method to ensure resources are
     * released properly.
     */
    public void close() {
        if (mBluetoothGatt == null) {
            return;
        }
        mBluetoothGatt.close();
        mBluetoothGatt = null;
    }

    /**
     * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported
     * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
     * callback.
     *
     * @param characteristic The characteristic to read from.
     */
    public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.readCharacteristic(characteristic);
    }

    /**
     * Enables or disables notification on a give characteristic.
     *
     * @param characteristic Characteristic to act on.
     * @param enabled If true, enable notification.  False otherwise.
     */
    public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                              boolean enabled) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

        // This is specific to BLE SPP Notify.
        if (UUID_BLE_SPP_NOTIFY.equals(characteristic.getUuid()) || UUID_BLE_SPP_NOTIFY_0.equals(characteristic.getUuid())) {
            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
                    UUID.fromString(BleSppGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            mBluetoothGatt.writeDescriptor(descriptor);
        }
    }


    public void writeData(byte[] data) {

        if ( mWriteCharacteristic != null &&
                data != null) {
            mWriteCharacteristic.setValue(data);
            //mBluetoothLeService.writeC
            mBluetoothGatt.writeCharacteristic(mWriteCharacteristic);
        }
    }


    public void writeAT(byte[] data) {
        if ( mATCharacteristic != null &&
                data != null) {
            mATCharacteristic.setValue(data);
            mBluetoothGatt.writeCharacteristic(mATCharacteristic);
        }
    }
    /**
     * Retrieves a list of supported GATT services on the connected device. This should be
     * invoked only after {@code BluetoothGatt#discoverServices()} completes successfully.
     *
     * @return A {@code List} of supported services.
     */
    public List<BluetoothGattService> getSupportedGattServices() {
        if (mBluetoothGatt == null) return null;

        return mBluetoothGatt.getServices();
    }
}

BleSppGattAttributes.java


import java.util.HashMap;

public class BleSppGattAttributes {
    private static HashMap<String, String> attributes = new HashMap();

    public static String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";

    //B-0002/B-0004
//    Service UUID:fee0
//    Notify:fee1
//    Write:fee1
    public static String BLE_SPP_Service_0 = "0000fee0-0000-1000-8000-00805f9b34fb";
    public static String BLE_SPP_Notify_Characteristic_0 = "0000fee1-0000-1000-8000-00805f9b34fb";
    public static String  BLE_SPP_Write_Characteristic_0 = "0000fee1-0000-1000-8000-00805f9b34fb";

    //B-0006 / TL8266 Use
//    Service UUID:1910
//    Notify:2B10
//    Write:2B11
      public static String BLE_SPP_Service = "0000fee0-0000-1000-8000-00805f9b34fb";
      public static String BLE_SPP_Notify_Characteristic = "0000fee1-0000-1000-8000-00805f9b34fb";
      public static String BLE_SPP_Write_Characteristic = "0000fee2-0000-1000-8000-00805f9b34fb";
      public static String BLE_SPP_AT_Characteristic = "0000fee3-0000-1000-8000-00805f9b34fb";
    static {
        //B-0002/B-0004 SPP Service
        attributes.put(BLE_SPP_Service_0, "BLE SPP Service_0");
        attributes.put(BLE_SPP_Notify_Characteristic_0, "BLE SPP Notify Characteristic_0");
        attributes.put(BLE_SPP_Write_Characteristic_0, "BLE SPP Write Characteristic_0");

        //B-0006/TL-8266 SPP Service
        attributes.put(BLE_SPP_Service, "BLE SPP Service");
        attributes.put(BLE_SPP_Notify_Characteristic, "BLE SPP Notify Characteristic");
        attributes.put(BLE_SPP_Write_Characteristic, "BLE SPP Write Characteristic");
        attributes.put(BLE_SPP_AT_Characteristic, "BLE SPP Write Characteristic");
    }

    public static String lookup(String uuid, String defaultName) {
        String name = attributes.get(uuid);
        return name == null ? defaultName : name;
    }
}

源碼地址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章