Skip to content

Instantly share code, notes, and snippets.

@geoaxis
Last active November 22, 2021 23:46
Show Gist options
  • Save geoaxis/2e79008bd4941ec4a77acf4f916d57bb to your computer and use it in GitHub Desktop.
Save geoaxis/2e79008bd4941ec4a77acf4f916d57bb to your computer and use it in GitHub Desktop.
@Slf4j
@AllArgsConstructor
public class CentralManagerCallback extends BluetoothCentralManagerCallback {
private final ObjectProperty<BLEState> bleStateProperty;
private final ObjectProperty<BluetoothPeripheral> connectedPeripheral;
private final ObservableList<String> discoveredDevices;
private final Map<String, BluetoothPeripheral> peripheralMap;
@Override
public void onConnectedPeripheral(@NotNull BluetoothPeripheral peripheral) {
log.info("Connected peripheral {}" + peripheral.getAddress());
connectedPeripheral.set(peripheral);
Platform.runLater(() -> bleStateProperty.setValue(BLEState.CONNECTED));
}
@Override
public void onConnectionFailed(@NotNull BluetoothPeripheral peripheral, @NotNull BluetoothCommandStatus status) {
log.error("Failed to connect peripheral {}" + peripheral.getAddress());
Platform.runLater(() -> bleStateProperty.setValue(BLEState.READY));
}
@Override
public void onDisconnectedPeripheral(@NotNull BluetoothPeripheral peripheral,
@NotNull BluetoothCommandStatus status) {
log.info("Disconnected peripheral {}" + peripheral.getAddress());
Platform.runLater(() -> {
bleStateProperty.setValue(BLEState.READY);
connectedPeripheral.set(null);
});
}
@Override
public void onDiscoveredPeripheral(@NotNull BluetoothPeripheral peripheral,
@NotNull ScanResult scanResult) {
log.info("Discovered device" + peripheral.getAddress());
if (!discoveredDevices.contains(peripheral.getAddress()) && bleStateProperty.getValue()
.equals(BLEState.SCANNING)) {
Platform.runLater(() -> {
discoveredDevices.add(peripheral.getAddress());
peripheralMap.put(peripheral.getAddress(), peripheral);
});
}
}
@Override
public void onScanFailed(int errorCode) {
Platform.runLater(() -> bleStateProperty.setValue(BLEState.READY));
log.error("Scan failed");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment