Skip to content

Instantly share code, notes, and snippets.

@oilking143
Created April 12, 2016 23:03
Show Gist options
  • Save oilking143/b81777ab07379c703dbb933aa081224c to your computer and use it in GitHub Desktop.
Save oilking143/b81777ab07379c703dbb933aa081224c to your computer and use it in GitHub Desktop.
package oil.newtpms;
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.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import java.util.List;
import java.util.UUID;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
/**
* Created by Oil on 2016/4/12.
*/
public class Bluetoothcallback extends BluetoothGattCallback {
private int mState = 0;
private BluetoothGatt mBtGatt = null;
private final int CONNECTED = 0x01;
private final int DISCONNECTED = 0x02;
private final int CONNECTTING = 0x03;
private BluetoothGattCharacteristic commandChar;
public final static String kServiceUUID = "1688A100-5450-4D53-5631-000000000000";
public final static String kUUIDWriteCommand = "1688A101-5450-4D53-5631-000000000000";
public final static String kUUIDReadDevStatus = "1688A102-5450-4D53-5631-000000000000";
public final static String kUUIDClientConfig = "00002902-0000-1000-8000-00805F9B34FB";
private Handler mThreadHandler;
private HandlerThread mThread;
private Context context;
private BluetoothDevice mDevice;
private ActionCallback currentCallback;
public Bluetoothcallback(Context ctx,BluetoothDevice device) {
super();
context=ctx;
mThread = new HandlerThread("name");
mThread.start();
mThreadHandler=new Handler(mThread.getLooper());
mDevice=device;
}
public void connect(final Context context, BluetoothDevice device, final ActionCallback callback) {
Bluetoothcallback.this.currentCallback = callback;
device.connectGatt(context, false, Bluetoothcallback.this);
}
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
if (status == BluetoothGatt.GATT_SUCCESS) {
mState = CONNECTED;
Log.d("Connect", "connected OK");
gatt.discoverServices(); } else if (newState == BluetoothGatt.GATT_FAILURE) {
mState = DISCONNECTED;
Log.d("connect", "connect failed");
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
mBtGatt=gatt;
if (status == BluetoothGatt.GATT_SUCCESS) {
UUID UUID_SERVICE = UUID.fromString(kServiceUUID);
UUID UUID_COMMAND = UUID.fromString(kUUIDWriteCommand);
UUID UUID_CLIENTCFG = UUID.fromString(kUUIDClientConfig);
if (gatt.getServices() == null)
{
return;
}
List<BluetoothGattService> services = gatt.getServices();
Log.i("onServicesDiscovered", services.toString());
// mReadCharacteristric=services.get(1).getCharacteristics().get(0);
// gatt.readCharacteristic(mReadCharacteristric);
commandChar=gatt.getService(UUID_SERVICE).getCharacteristic(UUID_COMMAND);
BluetoothGattDescriptor commandConfigDescriptor=commandChar.getDescriptor(UUID_CLIENTCFG);
if (commandChar == null)
{
return;
}
commandConfigDescriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
gatt.writeDescriptor(commandConfigDescriptor);
// BluetoothGattCharacteristic commandChar = gatt.getService(UUID_COMMAND).getCharacteristics().get(0);
// gatt.setCharacteristicNotification(commandChar,true);
mThreadHandler.postDelayed(TPMSConnect, 600);
}
else
{
Log.i("discovered", "onServicesDiscovered received: " + status);
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
Log.i("onCharacteristicRead", bytesToHex(characteristic.getValue()));
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
Log.i("onCharacteristicWrite", bytesToHex(characteristic.getValue()));
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
Log.i("onCharacteristicChange", bytesToHex(characteristic.getValue()));
}
public void readCharacteristic(UUID serviceUUID, UUID uuid, ActionCallback callback) {
try {
if (null == mBtGatt) {
Log.e("TAG", "connect to miband first");
throw new Exception("connect to miband first");
}
this.currentCallback = callback;
BluetoothGattCharacteristic chara = mBtGatt.getService(serviceUUID).getCharacteristic(uuid);
if (null == chara) {
this.onFail(-1, "BluetoothGattCharacteristic " + uuid + " is not exsit");
return;
}
if (false == this.mBtGatt.readCharacteristic(chara)) {
this.onFail(-1, "gatt.readCharacteristic() return false");
}
} catch (Throwable tr) {
Log.e("TAG", "readCharacteristic", tr);
this.onFail(-1, tr.getMessage());
}
}
public void readCharacteristic(UUID uuid, ActionCallback callback) {
UUID UUID_SERVICE = UUID.fromString(kServiceUUID);
this.readCharacteristic(UUID_SERVICE, uuid, callback);
}
@Override
public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorRead(gatt, descriptor, status);
Log.i("onDescriptionWrite", bytesToHex(descriptor.getValue()));
}
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorWrite(gatt, descriptor, status);
Log.i("onDescriptionWrite", bytesToHex(descriptor.getValue()));
}
@Override
public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
super.onReliableWriteCompleted(gatt, status);
}
@Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
super.onReadRemoteRssi(gatt, rssi, status);
}
@Override
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
super.onMtuChanged(gatt, mtu, status);
}
Runnable TPMSConnect = new Runnable()
{ @Override
public void run()
{
if (mState!=CONNECTED)
{
mBtGatt = mDevice.connectGatt(context, false, Bluetoothcallback.this );
}
else
{ ////////////Send to RX Box 00h(Synchronize) Command
//FFB1000006AC
//FFB1000006AC00
byte[] cmdbuf = {0,0,0,0,0,0};
int SendCRC;
cmdbuf[0] = (byte)0xFF;
cmdbuf[1] = (byte)0xB1;
cmdbuf[2] = (byte)0x00;
cmdbuf[3] = (byte)0x00;
cmdbuf[4] = (byte)0x06;
cmdbuf[5] = (byte)0xAC;
commandChar.setValue(cmdbuf);
mBtGatt.writeCharacteristic(commandChar);
Log.d("TPMSCONNECT:","succed!");
// mThreadHandler.postDelayed(TPMSRun, 10000);
}
}
};
static int Calculate_CRC16(final byte[] buffer) {
int crc = 0xFFFF;
for (int j = 0; j < buffer.length ; j++) {
crc = ((crc >>> 8) | (crc << 8) )& 0xffff;
crc ^= (buffer[j] & 0xff);//byte to int, trunc sign
crc ^= ((crc & 0xff) >> 4);
crc ^= (crc << 12) & 0xffff;
crc ^= ((crc & 0xFF) << 5) & 0xffff;
}
crc &= 0xffff;
System.out.println("CRC16-CCITT = " + Integer.toHexString(crc));
return crc;
}
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
private void onSuccess(Object data) {
if (this.currentCallback != null) {
ActionCallback callback = this.currentCallback;
this.currentCallback = null;
callback.onSuccess(data);
}
}
private void onFail(int errorCode, String msg) {
if (this.currentCallback != null) {
ActionCallback callback = this.currentCallback;
this.currentCallback = null;
callback.onFail(errorCode, msg);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment