package io.trygvis.android.bt; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.Date; public class BtDevice> { private final static String TAG = BtDevice.class.getSimpleName(); private final DefaultBtService btService; private final BluetoothDevice bluetoothDevice; private BluetoothGatt gatt; private Integer rssi; private BtScanResult scanResult; private A tag; private final long id; private final boolean seenBefore; private final Date firstSeen; private Date lastSeen; private boolean connected; public static interface BtDeviceWrapper> { BtDevice getBtDevice(); } BtDevice(DefaultBtService btService, BluetoothDevice bluetoothDevice, SQLiteDatabase db, BtService.BtDbIntegration btDbIntegration, long id, Integer rssi, BtScanResult scanResult, boolean seenBefore, Date firstSeen, Date lastSeen) { this.btService = btService; this.bluetoothDevice = bluetoothDevice; this.id = id; this.rssi = rssi; this.scanResult = scanResult; this.seenBefore = seenBefore; this.firstSeen = firstSeen; this.lastSeen = lastSeen; this.tag = btDbIntegration.createTag(db, this); } public long getId() { return id; } public A getTag() { return tag; } public String getAddress() { return bluetoothDevice.getAddress(); } public String getName() { return bluetoothDevice.getName(); } public int getRssi() { return rssi; } public BtScanResult getScanResult() { return scanResult; } public boolean isSeenBefore() { return seenBefore; } public Date getFirstSeen() { return firstSeen; } public Date getLastSeen() { return lastSeen; } public void setLastSeen(Date lastSeen) { this.lastSeen = lastSeen; } public synchronized boolean connect(BtPromise executor) { Log.i(TAG, "connect(), address=" + bluetoothDevice.getAddress()); BluetoothGattCallback callback = executor.asCallback(bluetoothDevice.getAddress()); gatt = bluetoothDevice.connectGatt(btService, false, new WrappingBluetoothGattCallback(callback) { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { BtDevice.this.connected = newState == BluetoothGatt.STATE_CONNECTED; super.onConnectionStateChange(gatt, status, newState); } }); return true; } public synchronized void disconnect() { if (gatt != null) { gatt.disconnect(); gatt = null; } } public boolean connected() { return connected; } @Override public String toString() { return "BtDevice{address=" + bluetoothDevice.getAddress() + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BtDevice other = (BtDevice) o; return getAddress().equals(other.getAddress()); } @Override public int hashCode() { return getAddress().hashCode(); } }