使用ble蓝牙开发
在写入数据之后 设备返回的数据证明发送成功了
但是在广播中也会返回数据,我这边接收不到 使用别人的demo 可以接收到数据
这里有demo 哪位大哥帮忙看看代码有没有什么问题。
package com.example.andysong.nuclearradiation.Ble;
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.BluetoothProfile;
import android.companion.BluetoothDeviceFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.example.andysong.nuclearradiation.Ble.Adapter.MyAdapter;
import com.example.andysong.nuclearradiation.Ble.BleTool.MyBluetoothDevice;
import com.example.andysong.nuclearradiation.Ble.Entity.BleData;
import com.example.andysong.nuclearradiation.R;
import com.example.andysong.nuclearradiation.Uitl.Progess.DialProgress;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
public class BleActivityTest extends AppCompatActivity implements View.OnClickListener, MyAdapter.OnScan {
private static final String TAG = BleActivityTest.class.getName();
private Button btn_scan;
private Button btn_w;
private RecyclerView rv_list;
private MyAdapter myAdapter;
private BluetoothAdapter bAdapter;
private BluetoothGatt bluetoothGatt;
private Map<String, UUID> uuidMap;
//private UUID uNotify = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e");
//private UUID N_Notify = UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb");
private UUID N_Notify = UUID.fromString("00001000-0000-1000-8000-00805f9b34fb");
//private UUID uNotify = UUID.fromString("0000ffe4-0000-1000-8000-00805f9b34fb");
private UUID uNotify = UUID.fromString("00001002-0000-1000-8000-00805f9b34fb");
//private UUID uRead = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e");
//private UUID uWrite = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e");
//private UUID N_Write = UUID.fromString("0000ffe5-0000-1000-8000-00805f9b34fb");
private UUID N_Write = UUID.fromString("00001000-0000-1000-8000-00805f9b34fb");
private static final UUID CLIENT_CHARACTERISTIC_CONFIG = UUID.fromString(
"00002902-0000-1000-8000-00805f9b34fb");
//private UUID uWrite = UUID.fromString("0000ffe9-0000-1000-8000-00805f9b34fb");
private UUID uWrite = UUID.fromString("00001001-0000-1000-8000-00805f9b34fb");
private String READ = "read";
private String WRITE = "write";
private String NOTICE = "notice";
private Button btn_r;
private Button btn_n;
private Button btn_c;
private DialProgress dialProgress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ble);
initView();
initData();
}
private void initView() {
btn_scan = findViewById(R.id.btn_scan);
btn_w = findViewById(R.id.btn_w);
btn_r = findViewById(R.id.btn_r);
btn_n = findViewById(R.id.btn_n);
btn_c = findViewById(R.id.btn_c);
btn_scan.setOnClickListener(this);
btn_w.setOnClickListener(this);
btn_r.setOnClickListener(this);
btn_n.setOnClickListener(this);
btn_c.setOnClickListener(this);
rv_list = findViewById(R.id.rv_list);
rv_list.setLayoutManager(new LinearLayoutManager(this, LinearLayout.VERTICAL, false));
myAdapter = new MyAdapter(this);
myAdapter.setOnScan(this);
rv_list.setAdapter(myAdapter);
dialProgress = findViewById(R.id.dialprog);
}
private void initData() {
bAdapter = BluetoothAdapter.getDefaultAdapter();
uuidMap = new HashMap<>();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_scan:
scan();
break;
case R.id.btn_w:
writeData();
break;
case R.id.btn_r:
readData();
break;
case R.id.btn_n:
notifyData();
break;
case R.id.btn_c:
closeNotifyData();
break;
}
}
/*关闭广播通知*/
private void closeNotifyData() {
BluetoothGattCharacteristic characteristic = bluetoothGatt.getService(N_Notify).getCharacteristic(uNotify);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
bluetoothGatt.writeDescriptor(descriptor);
}
/*打开广播通知*/
private void notifyData() {
BluetoothGattCharacteristic characteristic = bluetoothGatt.getService(N_Notify).getCharacteristic(uNotify);
boolean b = bluetoothGatt.setCharacteristicNotification(characteristic, true);
int originalWriteType = characteristic.getWriteType();
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG);
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
boolean b1 = bluetoothGatt.writeDescriptor(descriptor);
characteristic.setWriteType(originalWriteType);
}
/*read 读取数据 返回的数据需要在监听事件接收*/
private void readData() {
if (bluetoothGatt == null) {
return;
}
BluetoothGattCharacteristic characteristic = bluetoothGatt.getService(UUID.fromString("00001000-0000-1000-8000-00805f9b34fb")).
getCharacteristic(UUID.fromString("00001001-0000-1000-8000-00805f9b34fb"));
bluetoothGatt.readCharacteristic(characteristic);
}
/*扫描设备*/
private void scan() {
if (!bAdapter.isEnabled()) {
Toast.makeText(this, "请打开蓝牙", Toast.LENGTH_SHORT).show();
return;
}
bAdapter.startLeScan(scanCallback);
btn_scan.setText("扫描中");
btn_scan.setEnabled(false);
}
/*扫描到新的设备*/
private BluetoothAdapter.LeScanCallback scanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
MyBluetoothDevice bluetoothDevice = new MyBluetoothDevice(device, rssi);
addDevice(bluetoothDevice);
// Log.e(TAG, "onLeScan: " + device.getAddress() + device.getName());
if (device.getAddress().equals("F6:6D:83:80:D6:8D")) {
conn(bluetoothDevice);
}
//F6:6D:83:80:D6:8D
}
};
/*添加扫描的新设备*/
private void addDevice(MyBluetoothDevice bluetoothDevice) {
List<MyBluetoothDevice> devices = myAdapter.getDevices();
for (MyBluetoothDevice device : devices) {
if (device.getDevice().getAddress().equals(bluetoothDevice.getDevice().getAddress())) {
return;
}
}
myAdapter.upDate(bluetoothDevice);
}
/*item点击链接的方法*/
@Override
public void conn(MyBluetoothDevice device) {
bluetoothGatt = device.getDevice().connectGatt(this, false, mBluetoothGattCallback);
}
/*写数据 数据不会直接返回 需要在监听事件中回调*/
public void writeData() {
if (bluetoothGatt == null) {
return;
}
// bluetoothGatt.readRemoteRssi();
BluetoothGattCharacteristic characteristic = bluetoothGatt.getService(N_Write).getCharacteristic(uWrite);
//characteristic.setValue("E5015101003420");
characteristic.setValue("EF52FFFAFFFF");
//characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
bluetoothGatt.writeCharacteristic(characteristic);
}
/*链接状态—ready—write-*/
BluetoothGattCallback mBluetoothGattCallback = new BluetoothGattCallback() {
//链接状态更改时
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
if (newState == BluetoothProfile.STATE_CONNECTED) {
gatt.discoverServices(); //查询支持的服务
bluetoothGatt = gatt;
BleActivityTest.this.runOnUiThread(new Runnable() {
@Override
public void run() {
btn_scan.setVisibility(View.GONE);
btn_w.setVisibility(View.VISIBLE);
btn_r.setVisibility(View.VISIBLE);
btn_n.setVisibility(View.VISIBLE);
btn_c.setVisibility(View.VISIBLE);
}
});
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.e(TAG, "onConnectionStateChange: 断开");
BleActivityTest.this.runOnUiThread(new Runnable() {
@Override
public void run() {
btn_scan.setEnabled(true);
}
});
}
btn_scan.setText("扫描");
}
//读取数据
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
bluetoothGatt = gatt;
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.e(TAG, "读取成功");
printALL(characteristic.getValue());
} else {
Log.e(TAG, "读取失败");
}
}
//写出数据返回状态
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
bluetoothGatt = gatt;
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.e(TAG, "onCharacteristicWrite发送成功");
printALL(characteristic.getValue());
} else {
Log.e(TAG, "onCharacteristicWrite发送失败");
}
}
/*一般情况是 给设备发送指令使用应该*/
@Override
public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorRead(gatt, descriptor, status);
bluetoothGatt = gatt;
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.e(TAG, "onDescriptorRead读取成功");
printALL(descriptor.getValue());
} else {
Log.e(TAG, "onDescriptorRead读取失败");
}
}
/*一般情况是 给设备发送指令使用应该*/
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorWrite(gatt, descriptor, status);
bluetoothGatt = gatt;
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.e(TAG, "onDescriptorWrite发送成功");
printALL(descriptor.getValue());
} else {
Log.e(TAG, "onDescriptorWrite发送失败");
}
}
/*接收通知 广播后 接收到的数据在这里*/
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
//super.onCharacteristicChanged(gatt, characteristic);
//bluetoothGatt = gatt;
byte[] value = characteristic.getValue();
try {
String s=new String(value,"UTF-8");
Log.e(TAG, "onCharacteristicChanged: "+s);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
printNotify(value);
}
//返回信号强度的
@Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
super.onReadRemoteRssi(gatt, rssi, status);
bluetoothGatt = gatt;
Log.e(TAG, "onReadRemoteRssi: " + rssi);
}
//返回支持的服务滴
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
bluetoothGatt = gatt;
read(gatt);
}
};
public void read(BluetoothGatt gatt) {
List<BluetoothGattService> services = gatt.getServices();
for (BluetoothGattService service : services) {
Log.e(TAG, "服务: " + service.getUuid() + "-----");
List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
for (BluetoothGattCharacteristic characteristic : characteristics) {
if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
uuidMap.put(READ, characteristic.getUuid());
Log.e(TAG, "读写属性: " + characteristic.getUuid());
for (BluetoothGattDescriptor bluetoothGattDescriptor:characteristic.getDescriptors()){
Log.e(TAG, "蓝牙描述符+++: " + bluetoothGattDescriptor.getUuid());
}
}
if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {
uuidMap.put(WRITE, characteristic.getUuid());
Log.e(TAG, "写属性: " + characteristic.getUuid());
}
if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
uuidMap.put(NOTICE, characteristic.getUuid());
Log.e(TAG, "通知属性: " + characteristic.getUuid());
for (BluetoothGattDescriptor bluetoothGattDescriptor : characteristic.getDescriptors()) {
Log.e(TAG, "蓝牙描述符: " + bluetoothGattDescriptor.getUuid());
}
}
}
}
Set<String> strings = uuidMap.keySet();
for (String key : strings) {
UUID uuid = uuidMap.get(key);
Log.e(TAG, "list: " + uuid.toString());
}
}
private void printALL(byte[] b) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < b.length; i++) {
sb.append(Integer.toHexString(b[i]) + " ");
}
Log.e(TAG, "printALL--------: " + sb.toString());
}
private void printALL2(final byte[] b) {
Log.e(TAG, "printALL2--------: " + byteToString(b));
BleActivityTest.this.runOnUiThread(new Runnable() {
@Override
public void run() {
dialProgress.setValue2(Double.parseDouble(formatString(byteToString(b)).getData()));
}
});
}
private void printNotify(final byte[] b) {
Log.e(TAG, "printNotify--------: " + byteToString(b));
BleActivityTest.this.runOnUiThread(new Runnable() {
@Override
public void run() {
dialProgress.setValue2(Double.parseDouble(formatString(byteToString(b)).getData()));
}
});
}
/*显示给客户*/
private String byteToString(byte[] b) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < b.length; i++) {
String s = String.valueOf(b[i]).replace("-", "");
String s1 = Integer.toHexString(Integer.valueOf(s));
if (i == 0 || i == 1) {
char c = asciiToChar(Integer.valueOf(s));
sb.append(c + " ");
continue;
} else if (s1.length() == 1) {
sb.append("0" + s1 + " ");
continue;
}
sb.append(s1 + " ");
}
return sb.toString();
}
/*ascii 转 字符*/
private char asciiToChar(int a) {
return (char) a;
}
/*代码用来计算的数据*/
private BleData formatString(String v) {
String value = v.replace(" ", "");
String command = value.substring(0, 2);
String date = value.substring(2, 8);
String company = value.substring(8, 10);
String d = value.substring(10, 18);
StringBuffer data = new StringBuffer();
boolean flag = true;
for (int i = 0; i < d.length(); i++) {
if (i == 0) {
continue;
}
if (i % 2 != 0) {
if (flag) {
data.append(Integer.valueOf(d.substring(0, i + 1)) + ".");
flag = false;
} else {
data.append(Integer.valueOf(d.substring(i - 1, i + 1)));
}
}
}
String crc = value.substring(18, value.length());
return new BleData(command, date, company, data.toString(), crc);
}
};