diff options
author | Sven Gothel <[email protected]> | 2022-07-08 03:29:47 +0200 |
---|---|---|
committer | Sven Gothel <[email protected]> | 2022-07-08 03:29:47 +0200 |
commit | 1ad1d7b5b0dab7e1b36f86f08e209045abeb5b3c (patch) | |
tree | 9a09265843355f99e2f4cd0cf7d0b92c318c7ef0 | |
parent | b16e20dfabfd152c0ad69ce94b72c8c713993b69 (diff) |
Use jaulib's BasicTypes, PrintUtil and Clock, drop duplicates in BTUtil
26 files changed, 504 insertions, 689 deletions
@@ -1,6 +1,7 @@ <?xml version="1.0" encoding="UTF-8"?> <classpath> <classpathentry kind="src" path="examples/java"/> + <classpathentry kind="src" path="jaulib/java_jni"/> <classpathentry kind="src" path="jaulib/java_pkg"/> <classpathentry kind="src" path="jaulib/test/java"/> <classpathentry kind="src" path="test/java"/> diff --git a/examples/java/DBTPeripheral00.java b/examples/java/DBTPeripheral00.java index 72e8d388..9712e9c3 100644 --- a/examples/java/DBTPeripheral00.java +++ b/examples/java/DBTPeripheral00.java @@ -60,7 +60,10 @@ import org.direct_bt.PairingMode; import org.direct_bt.SMPIOCapability; import org.direct_bt.SMPPairingState; import org.direct_bt.ScanType; +import org.jau.io.PrintUtil; import org.jau.net.EUI48; +import org.jau.sys.Clock; +import org.jau.util.BasicTypes; /** * This Java peripheral {@link BTRole::Slave} GATT server example uses an event driven workflow. @@ -237,12 +240,12 @@ public class DBTPeripheral00 { final AdapterSettings newmask, final AdapterSettings changedmask, final long timestamp) { final boolean initialSetting = oldmask.isEmpty(); if( initialSetting ) { - BTUtils.println(System.err, "****** SETTINGS: "+oldmask+" -> "+newmask+", initial "+changedmask); + PrintUtil.println(System.err, "****** SETTINGS: "+oldmask+" -> "+newmask+", initial "+changedmask); } else { - BTUtils.println(System.err, "****** SETTINGS: "+oldmask+" -> "+newmask+", changed "+changedmask); + PrintUtil.println(System.err, "****** SETTINGS: "+oldmask+" -> "+newmask+", changed "+changedmask); } - BTUtils.println(System.err, "Status Adapter:"); - BTUtils.println(System.err, adapter.toString()); + PrintUtil.println(System.err, "Status Adapter:"); + PrintUtil.println(System.err, adapter.toString()); if( !initialSetting && changedmask.isSet(AdapterSettings.SettingType.POWERED) && newmask.isSet(AdapterSettings.SettingType.POWERED) ) @@ -255,25 +258,25 @@ public class DBTPeripheral00 { @Override public void discoveringChanged(final BTAdapter adapter, final ScanType currentMeta, final ScanType changedType, final boolean changedEnabled, final DiscoveryPolicy policy, final long timestamp) { - BTUtils.println(System.err, "****** DISCOVERING: meta "+currentMeta+", changed["+changedType+", enabled "+changedEnabled+", policy "+policy+"] on "+adapter); + PrintUtil.println(System.err, "****** DISCOVERING: meta "+currentMeta+", changed["+changedType+", enabled "+changedEnabled+", policy "+policy+"] on "+adapter); } @Override public boolean deviceFound(final BTDevice device, final long timestamp) { - BTUtils.println(System.err, "****** FOUND__-1: NOP "+device.toString()); + PrintUtil.println(System.err, "****** FOUND__-1: NOP "+device.toString()); return false; } @Override public void deviceUpdated(final BTDevice device, final EIRDataTypeSet updateMask, final long timestamp) { if( SHOW_UPDATE_EVENTS ) { - BTUtils.println(System.err, "****** UPDATED: "+updateMask+" of "+device); + PrintUtil.println(System.err, "****** UPDATED: "+updateMask+" of "+device); } } @Override public void deviceConnected(final BTDevice device, final boolean discovered, final long timestamp) { - BTUtils.println(System.err, "****** CONNECTED (discovered "+discovered+"): "+device.toString()); + PrintUtil.println(System.err, "****** CONNECTED (discovered "+discovered+"): "+device.toString()); final boolean available = null == getDevice(); if( available ) { setDevice(device); @@ -282,7 +285,7 @@ public class DBTPeripheral00 { @Override public void devicePairingState(final BTDevice device, final SMPPairingState state, final PairingMode mode, final long timestamp) { - BTUtils.println(System.err, "****** PAIRING_STATE: state "+state+", mode "+mode+": "+device); + PrintUtil.println(System.err, "****** PAIRING_STATE: state "+state+", mode "+mode+": "+device); switch( state ) { case NONE: // next: deviceReady(..) @@ -334,13 +337,13 @@ public class DBTPeripheral00 { @Override public void deviceReady(final BTDevice device, final long timestamp) { - BTUtils.println(System.err, "****** READY-1: NOP " + device.toString()); + PrintUtil.println(System.err, "****** READY-1: NOP " + device.toString()); } @Override public void deviceDisconnected(final BTDevice device, final HCIStatusCode reason, final short handle, final long timestamp) { servedConnections++; - BTUtils.println(System.err, "****** DISCONNECTED (count "+servedConnections+"): Reason "+reason+", old handle 0x"+Integer.toHexString(handle)+": "+device+" on "+device.getAdapter()); + PrintUtil.println(System.err, "****** DISCONNECTED (count "+servedConnections+"): Reason "+reason+", old handle 0x"+Integer.toHexString(handle)+": "+device+" on "+device.getAdapter()); final boolean match = matches(device); if( match ) { setDevice(null); @@ -389,15 +392,15 @@ public class DBTPeripheral00 { final BTDevice connectedDevice_ = getDevice(); if( null != connectedDevice_ && connectedDevice_.getConnected() ) { if( 0 != handlePulseDataNotify || 0 != handlePulseDataIndicate ) { - final String data = String.format("Dynamic Data Example. Elapsed Milliseconds: %,9d", BTUtils.elapsedTimeMillis()); + final String data = String.format("Dynamic Data Example. Elapsed Milliseconds: %,9d", Clock.elapsedTimeMillis()); final byte[] v = data.getBytes(StandardCharsets.UTF_8); if( 0 != handlePulseDataNotify ) { final boolean res = connectedDevice_.sendNotification(handlePulseDataNotify, v); - BTUtils.fprintf_td(System.err, "****** GATT::sendNotification: PULSE (res %b) to %s\n", res, connectedDevice_.toString()); + PrintUtil.fprintf_td(System.err, "****** GATT::sendNotification: PULSE (res %b) to %s\n", res, connectedDevice_.toString()); } if( 0 != handlePulseDataIndicate ) { final boolean res = connectedDevice_.sendIndication(handlePulseDataIndicate, v); - BTUtils.fprintf_td(System.err, "****** GATT::sendIndication: PULSE (res %b) to %s\n", res, connectedDevice_.toString()); + PrintUtil.fprintf_td(System.err, "****** GATT::sendIndication: PULSE (res %b) to %s\n", res, connectedDevice_.toString()); } } } @@ -417,13 +420,13 @@ public class DBTPeripheral00 { if( 0 != handleResponseDataNotify || 0 != handleResponseDataIndicate ) { if( 0 != handleResponseDataNotify ) { final boolean res = connectedDevice_.sendNotification(handleResponseDataNotify, data); - BTUtils.fprintf_td(System.err, "****** GATT::sendNotification (res %b): %s to %s\n", - res, BTUtils.bytesHexString(data, 0, data.length, true /* lsb */), connectedDevice_.toString()); + PrintUtil.fprintf_td(System.err, "****** GATT::sendNotification (res %b): %s to %s\n", + res, BasicTypes.bytesHexString(data, 0, data.length, true /* lsb */), connectedDevice_.toString()); } if( 0 != handleResponseDataIndicate ) { final boolean res = connectedDevice_.sendIndication(handleResponseDataIndicate, data); - BTUtils.fprintf_td(System.err, "****** GATT::sendIndication (res %b): %s to %s\n", - res, BTUtils.bytesHexString(data, 0, data.length, true /* lsb */), connectedDevice_.toString()); + PrintUtil.fprintf_td(System.err, "****** GATT::sendIndication (res %b): %s to %s\n", + res, BasicTypes.bytesHexString(data, 0, data.length, true /* lsb */), connectedDevice_.toString()); } } } @@ -449,7 +452,7 @@ public class DBTPeripheral00 { @Override public void connected(final BTDevice device, final int initialMTU) { final boolean match = matches(device); - BTUtils.fprintf_td(System.err, "****** GATT::connected(match %b): initMTU %d, %s\n", + PrintUtil.fprintf_td(System.err, "****** GATT::connected(match %b): initMTU %d, %s\n", match, initialMTU, device.toString()); if( match ) { synchronized( sync_lock ) { @@ -461,7 +464,7 @@ public class DBTPeripheral00 { @Override public void disconnected(final BTDevice device) { final boolean match = matches(device); - BTUtils.fprintf_td(System.err, "****** GATT::disconnected(match %b): %s\n", match, device.toString()); + PrintUtil.fprintf_td(System.err, "****** GATT::disconnected(match %b): %s\n", match, device.toString()); if( match ) { clear(); } @@ -470,7 +473,7 @@ public class DBTPeripheral00 { @Override public void mtuChanged(final BTDevice device, final int mtu) { final boolean match = matches(device); - BTUtils.fprintf_td(System.err, "****** GATT::mtuChanged(match %b): %d -> %d, %s\n", + PrintUtil.fprintf_td(System.err, "****** GATT::mtuChanged(match %b): %d -> %d, %s\n", match, match ? (int)usedMTU : 0, mtu, device.toString()); if( match ) { synchronized( sync_lock ) { @@ -482,7 +485,7 @@ public class DBTPeripheral00 { @Override public boolean readCharValue(final BTDevice device, final DBGattService s, final DBGattChar c) { final boolean match = matches(device); - BTUtils.fprintf_td(System.err, "****** GATT::readCharValue(match %b): to %s, from\n %s\n %s\n", + PrintUtil.fprintf_td(System.err, "****** GATT::readCharValue(match %b): to %s, from\n %s\n %s\n", match, device.toString(), s.toString(), c.toString()); return match; } @@ -490,7 +493,7 @@ public class DBTPeripheral00 { @Override public boolean readDescValue(final BTDevice device, final DBGattService s, final DBGattChar c, final DBGattDesc d) { final boolean match = matches(device); - BTUtils.fprintf_td(System.err, "****** GATT::readDescValue(match %b): to %s, from\n %s\n %s\n %s\n", + PrintUtil.fprintf_td(System.err, "****** GATT::readDescValue(match %b): to %s, from\n %s\n %s\n %s\n", match, device.toString(), s.toString(), c.toString(), d.toString()); return match; } @@ -498,9 +501,9 @@ public class DBTPeripheral00 { @Override public boolean writeCharValue(final BTDevice device, final DBGattService s, final DBGattChar c, final byte[] value, final int value_offset) { final boolean match = matches(device); - final String value_s = BTUtils.bytesHexString(value, 0, value.length, true /* lsbFirst */)+ + final String value_s = BasicTypes.bytesHexString(value, 0, value.length, true /* lsbFirst */)+ " '"+BTUtils.decodeUTF8String(value, 0, value.length)+"'"; - BTUtils.fprintf_td(System.err, "****** GATT::writeCharValue(match %b): %s @ %d from %s, to\n %s\n %s\n", + PrintUtil.fprintf_td(System.err, "****** GATT::writeCharValue(match %b): %s @ %d from %s, to\n %s\n %s\n", match, value_s, value_offset, device.toString(), s.toString(), c.toString()); @@ -511,7 +514,7 @@ public class DBTPeripheral00 { public void writeCharValueDone(final BTDevice device, final DBGattService s, final DBGattChar c) { final boolean match = matches(device); final DBGattValue value = c.getValue(); - BTUtils.fprintf_td(System.err, "****** GATT::writeCharValueDone(match %b): From %s, to\n %s\n %s\n Char-Value: %s\n", + PrintUtil.fprintf_td(System.err, "****** GATT::writeCharValueDone(match %b): From %s, to\n %s\n %s\n Char-Value: %s\n", match, device.toString(), s.toString(), c.toString(), value.toString()); if( match && @@ -527,9 +530,9 @@ public class DBTPeripheral00 { final byte[] value, final int value_offset) { final boolean match = matches(device); - final String value_s = BTUtils.bytesHexString(value, 0, value.length, true /* lsbFirst */)+ + final String value_s = BasicTypes.bytesHexString(value, 0, value.length, true /* lsbFirst */)+ " '"+BTUtils.decodeUTF8String(value, 0, value.length)+"'"; - BTUtils.fprintf_td(System.err, "****** GATT::writeDescValue(match %b): %s @ %d from %s\n %s\n %s\n %s\n", + PrintUtil.fprintf_td(System.err, "****** GATT::writeDescValue(match %b): %s @ %d from %s\n %s\n %s\n %s\n", match, value_s, value_offset, device.toString(), s.toString(), c.toString(), d.toString()); return match; @@ -539,7 +542,7 @@ public class DBTPeripheral00 { public void writeDescValueDone(final BTDevice device, final DBGattService s, final DBGattChar c, final DBGattDesc d) { final boolean match = matches(device); final DBGattValue value = d.getValue(); - BTUtils.fprintf_td(System.err, "****** GATT::writeDescValueDone(match %b): From %s\n %s\n %s\n %s\n Desc-Value: %s\n", + PrintUtil.fprintf_td(System.err, "****** GATT::writeDescValueDone(match %b): From %s\n %s\n %s\n %s\n Desc-Value: %s\n", match, device.toString(), s.toString(), c.toString(), d.toString(), value.toString()); } @@ -549,7 +552,7 @@ public class DBTPeripheral00 { { final boolean match = matches(device); final DBGattValue value = d.getValue(); - BTUtils.fprintf_td(System.err, "****** GATT::clientCharConfigChanged(match %b): notify %b, indicate %b from %s\n %s\n %s\n %s\n Desc-Value: %s\n", + PrintUtil.fprintf_td(System.err, "****** GATT::clientCharConfigChanged(match %b): notify %b, indicate %b from %s\n %s\n %s\n %s\n Desc-Value: %s\n", match, notificationEnabled, indicationEnabled, device.toString(), s.toString(), c.toString(), d.toString(), value.toString()); @@ -578,17 +581,17 @@ public class DBTPeripheral00 { private boolean stopAdvertising(final BTAdapter adapter, final String msg) { if( !useAdapter.equals(EUI48.ALL_DEVICE) && !useAdapter.equals(adapter.getAddressAndType().address) ) { - BTUtils.fprintf_td(System.err, "****** Stop advertising (%s): Adapter not selected: %s\n", msg, adapter.toString()); + PrintUtil.fprintf_td(System.err, "****** Stop advertising (%s): Adapter not selected: %s\n", msg, adapter.toString()); return false; } final HCIStatusCode status = adapter.stopAdvertising(); - BTUtils.println(System.err, "****** Stop advertising ("+msg+") result: "+status+": "+adapter.toString()); + PrintUtil.println(System.err, "****** Stop advertising ("+msg+") result: "+status+": "+adapter.toString()); return HCIStatusCode.SUCCESS == status; } private boolean startAdvertising(final BTAdapter adapter, final String msg) { if( !useAdapter.equals(EUI48.ALL_DEVICE) && !useAdapter.equals(adapter.getAddressAndType().address) ) { - BTUtils.fprintf_td(System.err, "****** Start advertising (%s): Adapter not selected: %s\n", msg, adapter.toString()); + PrintUtil.fprintf_td(System.err, "****** Start advertising (%s): Adapter not selected: %s\n", msg, adapter.toString()); return false; } final EInfoReport eir = new EInfoReport(); @@ -616,19 +619,19 @@ public class DBTPeripheral00 { gattDevNameChar.setValue(aname_bytes, 0, aname_bytes.length, 0); } - BTUtils.println(System.err, "****** Start advertising ("+msg+"): EIR "+eir.toString()); - BTUtils.println(System.err, "****** Start advertising ("+msg+"): adv "+adv_mask.toString()+", scanrsp "+scanrsp_mask.toString()); + PrintUtil.println(System.err, "****** Start advertising ("+msg+"): EIR "+eir.toString()); + PrintUtil.println(System.err, "****** Start advertising ("+msg+"): adv "+adv_mask.toString()+", scanrsp "+scanrsp_mask.toString()); final HCIStatusCode status = adapter.startAdvertising(dbGattServer, eir, adv_mask, scanrsp_mask, adv_interval_min, adv_interval_max, adv_type, adv_chan_map, filter_policy); - BTUtils.println(System.err, "****** Start advertising ("+msg+") result: "+status+": "+adapter.toString()); - BTUtils.println(System.err, dbGattServer.toFullString()); + PrintUtil.println(System.err, "****** Start advertising ("+msg+") result: "+status+": "+adapter.toString()); + PrintUtil.println(System.err, dbGattServer.toFullString()); return HCIStatusCode.SUCCESS == status; } private void processDisconnectedDevice(final BTDevice device) { - BTUtils.println(System.err, "****** Disconnected Device (count "+servedConnections+"): Start "+device.toString()); + PrintUtil.println(System.err, "****** Disconnected Device (count "+servedConnections+"): Start "+device.toString()); // already unpaired stopAdvertising(device.getAdapter(), "device-disconnected"); @@ -642,43 +645,43 @@ public class DBTPeripheral00 { startAdvertising(device.getAdapter(), "device-disconnected"); } - BTUtils.println(System.err, "****** Disonnected Device: End "+device.toString()); + PrintUtil.println(System.err, "****** Disonnected Device: End "+device.toString()); } private boolean initAdapter(final BTAdapter adapter) { if( !useAdapter.equals(EUI48.ALL_DEVICE) && !useAdapter.equals(adapter.getAddressAndType().address) ) { - BTUtils.fprintf_td(System.err, "initAdapter: Adapter not selected: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initAdapter: Adapter not selected: %s\n", adapter.toString()); return false; } if( !adapter.isInitialized() ) { // Initialize with defaults and power-on final HCIStatusCode status = adapter.initialize( btMode ); if( HCIStatusCode.SUCCESS != status ) { - BTUtils.fprintf_td(System.err, "initAdapter: initialization failed: %s: %s\n", + PrintUtil.fprintf_td(System.err, "initAdapter: initialization failed: %s: %s\n", status.toString(), adapter.toString()); return false; } } else if( !adapter.setPowered( true ) ) { - BTUtils.fprintf_td(System.err, "initAdapter: setPower.1 on failed: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initAdapter: setPower.1 on failed: %s\n", adapter.toString()); return false; } // adapter is powered-on - BTUtils.println(System.err, "initAdapter.1: "+adapter.toString()); + PrintUtil.println(System.err, "initAdapter.1: "+adapter.toString()); if( adapter.setPowered(false) ) { HCIStatusCode status = adapter.setName(adapter_name, adapter_short_name); if( HCIStatusCode.SUCCESS == status ) { - BTUtils.fprintf_td(System.err, "initAdapter: setLocalName OK: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initAdapter: setLocalName OK: %s\n", adapter.toString()); } else { - BTUtils.fprintf_td(System.err, "initAdapter: setLocalName failed: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initAdapter: setLocalName failed: %s\n", adapter.toString()); return false; } status = adapter.setSecureConnections( use_SC ); if( HCIStatusCode.SUCCESS == status ) { - BTUtils.fprintf_td(System.err, "initAdapter: setSecureConnections OK: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initAdapter: setSecureConnections OK: %s\n", adapter.toString()); } else { - BTUtils.fprintf_td(System.err, "initAdapter: setSecureConnections failed: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initAdapter: setSecureConnections failed: %s\n", adapter.toString()); return false; } @@ -688,32 +691,32 @@ public class DBTPeripheral00 { final short supervision_timeout = 50; // 500ms status = adapter.setDefaultConnParam(conn_min_interval, conn_max_interval, conn_latency, supervision_timeout); if( HCIStatusCode.SUCCESS == status ) { - BTUtils.fprintf_td(System.err, "initAdapter: setDefaultConnParam OK: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initAdapter: setDefaultConnParam OK: %s\n", adapter.toString()); } else if( HCIStatusCode.UNKNOWN_COMMAND == status ) { - BTUtils.fprintf_td(System.err, "initAdapter: setDefaultConnParam UNKNOWN_COMMAND (ignored): %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initAdapter: setDefaultConnParam UNKNOWN_COMMAND (ignored): %s\n", adapter.toString()); } else { - BTUtils.fprintf_td(System.err, "initAdapter: setDefaultConnParam failed: %s, %s\n", status.toString(), adapter.toString()); + PrintUtil.fprintf_td(System.err, "initAdapter: setDefaultConnParam failed: %s, %s\n", status.toString(), adapter.toString()); return false; } if( !adapter.setPowered( true ) ) { - BTUtils.fprintf_td(System.err, "initAdapter: setPower.2 on failed: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initAdapter: setPower.2 on failed: %s\n", adapter.toString()); return false; } } else { - BTUtils.fprintf_td(System.err, "initAdapter: setPowered.2 off failed: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initAdapter: setPowered.2 off failed: %s\n", adapter.toString()); } - BTUtils.println(System.err, "initAdapter.2: "+adapter.toString()); + PrintUtil.println(System.err, "initAdapter.2: "+adapter.toString()); { final LE_Features le_feats = adapter.getLEFeatures(); - BTUtils.fprintf_td(System.err, "initAdapter: LE_Features %s\n", le_feats.toString()); + PrintUtil.fprintf_td(System.err, "initAdapter: LE_Features %s\n", le_feats.toString()); } if( adapter.getBTMajorVersion() > 4 ) { final LE_PHYs Tx = new LE_PHYs( LE_PHYs.PHY.LE_2M ); final LE_PHYs Rx = new LE_PHYs( LE_PHYs.PHY.LE_2M ); final HCIStatusCode res = adapter.setDefaultLE_PHY(Tx, Rx); - BTUtils.fprintf_td(System.err, "initAdapter: Set Default LE PHY: status %s: Tx %s, Rx %s\n", + PrintUtil.fprintf_td(System.err, "initAdapter: Set Default LE PHY: status %s: Tx %s, Rx %s\n", res.toString(), Tx.toString(), Rx.toString()); } adapter.setSMPKeyPath(DBTConstants.SERVER_KEY_PATH); @@ -738,12 +741,12 @@ public class DBTPeripheral00 { if( null == chosenAdapter ) { if( initAdapter( adapter ) ) { chosenAdapter = adapter; - BTUtils.println(System.err, "****** Adapter ADDED__: InitOK: " + adapter); + PrintUtil.println(System.err, "****** Adapter ADDED__: InitOK: " + adapter); } else { - BTUtils.println(System.err, "****** Adapter ADDED__: Ignored: " + adapter); + PrintUtil.println(System.err, "****** Adapter ADDED__: Ignored: " + adapter); } } else { - BTUtils.println(System.err, "****** Adapter ADDED__: Ignored (other): " + adapter); + PrintUtil.println(System.err, "****** Adapter ADDED__: Ignored (other): " + adapter); } } @@ -751,17 +754,17 @@ public class DBTPeripheral00 { public void adapterRemoved(final BTAdapter adapter) { if( null != chosenAdapter && adapter == chosenAdapter ) { chosenAdapter = null; - BTUtils.println(System.err, "****** Adapter REMOVED: " + adapter); + PrintUtil.println(System.err, "****** Adapter REMOVED: " + adapter); } else { - BTUtils.println(System.err, "****** Adapter REMOVED (other): " + adapter); + PrintUtil.println(System.err, "****** Adapter REMOVED (other): " + adapter); } } }; public void runTest(final BTManager manager) { - timestamp_t0 = BTUtils.currentTimeMillis(); + timestamp_t0 = Clock.currentTimeMillis(); - BTUtils.println(System.err, "****** Test Start"); + PrintUtil.println(System.err, "****** Test Start"); final MyGATTServerListener listener = new MyGATTServerListener(); dbGattServer.addListener( listener ); @@ -776,18 +779,18 @@ public class DBTPeripheral00 { } } - BTUtils.println(System.err, "****** Shutdown.01 (DBGattServer.remove-listener)"); + PrintUtil.println(System.err, "****** Shutdown.01 (DBGattServer.remove-listener)"); dbGattServer.removeListener( listener ); - BTUtils.println(System.err, "****** Test Shutdown.02 (listener.close)"); + PrintUtil.println(System.err, "****** Test Shutdown.02 (listener.close)"); listener.close(); - BTUtils.println(System.err, "****** Test Shutdown.03 (DBGattServer.close)"); + PrintUtil.println(System.err, "****** Test Shutdown.03 (DBGattServer.close)"); dbGattServer.close(); // chosenAdapter = null; - BTUtils.println(System.err, "****** Test End"); + PrintUtil.println(System.err, "****** Test End"); } public static void main(final String[] args) throws InterruptedException { @@ -823,9 +826,9 @@ public class DBTPeripheral00 { System.exit(-1); return; } - BTUtils.println(System.err, "Direct-BT BluetoothManager initialized!"); - BTUtils.println(System.err, "Direct-BT Native Version "+BTFactory.getNativeVersion()+" (API "+BTFactory.getNativeAPIVersion()+")"); - BTUtils.println(System.err, "Direct-BT Java Version "+BTFactory.getImplVersion()+" (API "+BTFactory.getAPIVersion()+")"); + PrintUtil.println(System.err, "Direct-BT BluetoothManager initialized!"); + PrintUtil.println(System.err, "Direct-BT Native Version "+BTFactory.getNativeVersion()+" (API "+BTFactory.getNativeAPIVersion()+")"); + PrintUtil.println(System.err, "Direct-BT Java Version "+BTFactory.getImplVersion()+" (API "+BTFactory.getAPIVersion()+")"); final DBTPeripheral00 test = new DBTPeripheral00(); @@ -858,7 +861,7 @@ public class DBTPeripheral00 { test.RUN_ONLY_ONCE = true; } } - BTUtils.println(System.err, "Run with '[-btmode LE|BREDR|DUAL] [-use_sc 0|1] "+ + PrintUtil.println(System.err, "Run with '[-btmode LE|BREDR|DUAL] [-use_sc 0|1] "+ "[-adapter <adapter_address>] "+ "[-name <adapter_name>] "+ "[-short_name <adapter_short_name>] "+ @@ -875,18 +878,18 @@ public class DBTPeripheral00 { "[-shutdown <int>]'"); } - BTUtils.println(System.err, "SHOW_UPDATE_EVENTS "+test.SHOW_UPDATE_EVENTS); - BTUtils.println(System.err, "adapter "+test.useAdapter); - BTUtils.println(System.err, "adapter btmode "+test.btMode.toString()); - BTUtils.println(System.err, "adapter SC "+test.use_SC); - BTUtils.fprintf_td(System.err, "name %s (short %s)\n", test.adapter_name, test.adapter_short_name); - BTUtils.println(System.err, "adapter mtu "+test.dbGattServer.getMaxAttMTU()); - BTUtils.println(System.err, "adapter sec_level "+test.adapter_sec_level); - BTUtils.println(System.err, "once "+test.RUN_ONLY_ONCE); - BTUtils.println(System.err, "GattServer "+test.dbGattServer.toString()); + PrintUtil.println(System.err, "SHOW_UPDATE_EVENTS "+test.SHOW_UPDATE_EVENTS); + PrintUtil.println(System.err, "adapter "+test.useAdapter); + PrintUtil.println(System.err, "adapter btmode "+test.btMode.toString()); + PrintUtil.println(System.err, "adapter SC "+test.use_SC); + PrintUtil.fprintf_td(System.err, "name %s (short %s)\n", test.adapter_name, test.adapter_short_name); + PrintUtil.println(System.err, "adapter mtu "+test.dbGattServer.getMaxAttMTU()); + PrintUtil.println(System.err, "adapter sec_level "+test.adapter_sec_level); + PrintUtil.println(System.err, "once "+test.RUN_ONLY_ONCE); + PrintUtil.println(System.err, "GattServer "+test.dbGattServer.toString()); if( waitForEnter ) { - BTUtils.println(System.err, "Press ENTER to continue\n"); + PrintUtil.println(System.err, "Press ENTER to continue\n"); try{ System.in.read(); } catch(final Exception e) { } } diff --git a/examples/java/DBTScanner10.java b/examples/java/DBTScanner10.java index 138a5d34..954a9012 100644 --- a/examples/java/DBTScanner10.java +++ b/examples/java/DBTScanner10.java @@ -58,7 +58,10 @@ import org.direct_bt.SMPIOCapability; import org.direct_bt.SMPKeyBin; import org.direct_bt.SMPPairingState; import org.direct_bt.ScanType; +import org.jau.io.PrintUtil; import org.jau.net.EUI48; +import org.jau.sys.Clock; +import org.jau.util.BasicTypes; import jau.direct_bt.DBTManager; @@ -121,12 +124,12 @@ public class DBTScanner10 { final AdapterSettings newmask, final AdapterSettings changedmask, final long timestamp) { final boolean initialSetting = oldmask.isEmpty(); if( initialSetting ) { - BTUtils.println(System.err, "****** SETTINGS: "+oldmask+" -> "+newmask+", initial "+changedmask); + PrintUtil.println(System.err, "****** SETTINGS: "+oldmask+" -> "+newmask+", initial "+changedmask); } else { - BTUtils.println(System.err, "****** SETTINGS: "+oldmask+" -> "+newmask+", changed "+changedmask); + PrintUtil.println(System.err, "****** SETTINGS: "+oldmask+" -> "+newmask+", changed "+changedmask); } - BTUtils.println(System.err, "Status Adapter:"); - BTUtils.println(System.err, adapter.toString()); + PrintUtil.println(System.err, "Status Adapter:"); + PrintUtil.println(System.err, adapter.toString()); if( !initialSetting && changedmask.isSet(AdapterSettings.SettingType.POWERED) && newmask.isSet(AdapterSettings.SettingType.POWERED) ) @@ -139,7 +142,7 @@ public class DBTScanner10 { @Override public void discoveringChanged(final BTAdapter adapter, final ScanType currentMeta, final ScanType changedType, final boolean changedEnabled, final DiscoveryPolicy policy, final long timestamp) { - BTUtils.println(System.err, "****** DISCOVERING: meta "+currentMeta+", changed["+changedType+", enabled "+changedEnabled+", policy "+policy+"] on "+adapter); + PrintUtil.println(System.err, "****** DISCOVERING: meta "+currentMeta+", changed["+changedType+", enabled "+changedEnabled+", policy "+policy+"] on "+adapter); } @Override @@ -150,17 +153,17 @@ public class DBTScanner10 { ) ) { - BTUtils.println(System.err, "****** FOUND__-0: Connecting "+device.toString()); + PrintUtil.println(System.err, "****** FOUND__-0: Connecting "+device.toString()); { - final long td = BTUtils.currentTimeMillis() - timestamp_t0; // adapter-init -> now - BTUtils.println(System.err, "PERF: adapter-init -> FOUND__-0 " + td + " ms"); + final long td = Clock.currentTimeMillis() - timestamp_t0; // adapter-init -> now + PrintUtil.println(System.err, "PERF: adapter-init -> FOUND__-0 " + td + " ms"); } executeOffThread( () -> { connectDiscoveredDevice(device); }, "DBT-Connect-"+device.getAddressAndType(), true /* detach */); return true; } else { if( !QUIET ) { - BTUtils.println(System.err, "****** FOUND__-1: NOP "+device.toString()); + PrintUtil.println(System.err, "****** FOUND__-1: NOP "+device.toString()); } return false; } @@ -169,25 +172,25 @@ public class DBTScanner10 { @Override public void deviceUpdated(final BTDevice device, final EIRDataTypeSet updateMask, final long timestamp) { if( !QUIET && SHOW_UPDATE_EVENTS ) { - BTUtils.println(System.err, "****** UPDATED: "+updateMask+" of "+device); + PrintUtil.println(System.err, "****** UPDATED: "+updateMask+" of "+device); } } @Override public void deviceConnected(final BTDevice device, final boolean discovered, final long timestamp) { - BTUtils.println(System.err, "****** CONNECTED (discovered "+discovered+"): "+device.toString()); + PrintUtil.println(System.err, "****** CONNECTED (discovered "+discovered+"): "+device.toString()); } @Override public void devicePairingState(final BTDevice device, final SMPPairingState state, final PairingMode mode, final long timestamp) { - BTUtils.println(System.err, "****** PAIRING_STATE: state "+state+", mode "+mode+": "+device); + PrintUtil.println(System.err, "****** PAIRING_STATE: state "+state+", mode "+mode+": "+device); switch( state ) { case NONE: // next: deviceReady(..) break; case FAILED: { final boolean res = SMPKeyBin.remove(DBTConstants.CLIENT_KEY_PATH, device); - BTUtils.println(System.err, "****** PAIRING_STATE: state "+state+"; Remove key file "+SMPKeyBin.getFilename(DBTConstants.CLIENT_KEY_PATH, device)+", res "+res); + PrintUtil.println(System.err, "****** PAIRING_STATE: state "+state+"; Remove key file "+SMPKeyBin.getFilename(DBTConstants.CLIENT_KEY_PATH, device)+", res "+res); // next: deviceReady() or deviceDisconnected(..) } break; case REQUESTED_BY_RESPONDER: @@ -235,17 +238,17 @@ public class DBTScanner10 { @Override public void deviceReady(final BTDevice device, final long timestamp) { deviceReadyCount.incrementAndGet(); - BTUtils.println(System.err, "****** READY-0: Processing["+deviceReadyCount.get()+"] "+device.toString()); + PrintUtil.println(System.err, "****** READY-0: Processing["+deviceReadyCount.get()+"] "+device.toString()); { - final long td = BTUtils.currentTimeMillis() - timestamp_t0; // adapter-init -> now - BTUtils.println(System.err, "PERF: adapter-init -> READY-0 " + td + " ms"); + final long td = Clock.currentTimeMillis() - timestamp_t0; // adapter-init -> now + PrintUtil.println(System.err, "PERF: adapter-init -> READY-0 " + td + " ms"); } processReadyDevice(device); // AdapterStatusListener::deviceReady() explicitly allows prolonged and complex code execution! } @Override public void deviceDisconnected(final BTDevice device, final HCIStatusCode reason, final short handle, final long timestamp) { - BTUtils.println(System.err, "****** DISCONNECTED: Reason "+reason+", old handle 0x"+Integer.toHexString(handle)+": "+device+" on "+device.getAdapter()); + PrintUtil.println(System.err, "****** DISCONNECTED: Reason "+reason+", old handle 0x"+Integer.toHexString(handle)+": "+device+" on "+device.getAdapter()); if( REMOVE_DEVICE ) { executeOffThread( () -> { removeDevice(device); }, "DBT-Remove-"+device.getAddressAndType(), true /* detach */); @@ -270,12 +273,12 @@ public class DBTScanner10 { @Override public void notificationReceived(final BTGattChar charDecl, final byte[] value, final long timestamp) { - final long tR = BTUtils.currentTimeMillis(); - BTUtils.fprintf_td(System.err, "**[%02d.%02d] Characteristic-Notify: UUID %s, td %d ******\n", + final long tR = Clock.currentTimeMillis(); + PrintUtil.fprintf_td(System.err, "**[%02d.%02d] Characteristic-Notify: UUID %s, td %d ******\n", i, j, charDecl.getUUID(), (tR-timestamp)); - BTUtils.fprintf_td(System.err, "**[%02d.%02d] Characteristic: %s ******\n", i, j, charDecl.toString()); - BTUtils.fprintf_td(System.err, "**[%02d.%02d] Value R: size %d, ro: %s ******\n", i, j, value.length, BTUtils.bytesHexString(value, 0, -1, true)); - BTUtils.fprintf_td(System.err, "**[%02d.%02d] Value S: %s ******\n", i, j, BTUtils.decodeUTF8String(value, 0, value.length)); + PrintUtil.fprintf_td(System.err, "**[%02d.%02d] Characteristic: %s ******\n", i, j, charDecl.toString()); + PrintUtil.fprintf_td(System.err, "**[%02d.%02d] Value R: size %d, ro: %s ******\n", i, j, value.length, BasicTypes.bytesHexString(value, 0, -1, true)); + PrintUtil.fprintf_td(System.err, "**[%02d.%02d] Value S: %s ******\n", i, j, BTUtils.decodeUTF8String(value, 0, value.length)); shutdownTest(); } @@ -283,31 +286,31 @@ public class DBTScanner10 { @Override public void indicationReceived(final BTGattChar charDecl, final byte[] value, final long timestamp, final boolean confirmationSent) { - final long tR = BTUtils.currentTimeMillis(); - BTUtils.fprintf_td(System.err, "**[%02d.%02d] Characteristic-Indication: UUID %s, td %d, confirmed %b ******\n", + final long tR = Clock.currentTimeMillis(); + PrintUtil.fprintf_td(System.err, "**[%02d.%02d] Characteristic-Indication: UUID %s, td %d, confirmed %b ******\n", i, j, charDecl.getUUID(), (tR-timestamp), confirmationSent); - BTUtils.fprintf_td(System.err, "**[%02d.%02d] Characteristic: %s ******\n", i, j, charDecl.toString()); - BTUtils.fprintf_td(System.err, "**[%02d.%02d] Value R: size %d, ro: %s ******\n", i, j, value.length, BTUtils.bytesHexString(value, 0, -1, true)); - BTUtils.fprintf_td(System.err, "**[%02d.%02d] Value S: %s ******\n", i, j, BTUtils.decodeUTF8String(value, 0, value.length)); + PrintUtil.fprintf_td(System.err, "**[%02d.%02d] Characteristic: %s ******\n", i, j, charDecl.toString()); + PrintUtil.fprintf_td(System.err, "**[%02d.%02d] Value R: size %d, ro: %s ******\n", i, j, value.length, BasicTypes.bytesHexString(value, 0, -1, true)); + PrintUtil.fprintf_td(System.err, "**[%02d.%02d] Value S: %s ******\n", i, j, BTUtils.decodeUTF8String(value, 0, value.length)); shutdownTest(); } } private void connectDiscoveredDevice(final BTDevice device) { - BTUtils.println(System.err, "****** Connecting Device: Start " + device.toString()); + PrintUtil.println(System.err, "****** Connecting Device: Start " + device.toString()); // Testing listener lifecycle @ device dtor device.addStatusListener(new AdapterStatusListener() { @Override public void deviceUpdated(final BTDevice device, final EIRDataTypeSet updateMask, final long timestamp) { if( SHOW_UPDATE_EVENTS ) { - BTUtils.println(System.err, "****** UPDATED(2): "+updateMask+" of "+device); + PrintUtil.println(System.err, "****** UPDATED(2): "+updateMask+" of "+device); } } @Override public void deviceConnected(final BTDevice device, final boolean discovered, final long timestamp) { - BTUtils.println(System.err, "****** CONNECTED(2) (discovered "+discovered+"): "+device.toString()); + PrintUtil.println(System.err, "****** CONNECTED(2) (discovered "+discovered+"): "+device.toString()); } @Override @@ -317,34 +320,34 @@ public class DBTScanner10 { final BTSecurityRegistry.Entry sec = BTSecurityRegistry.getStartOf(device.getAddressAndType().address, device.getName()); if( null != sec ) { - BTUtils.println(System.err, "****** Connecting Device: Found SecurityDetail "+sec.toString()+" for "+device.toString()); + PrintUtil.println(System.err, "****** Connecting Device: Found SecurityDetail "+sec.toString()+" for "+device.toString()); } else { - BTUtils.println(System.err, "****** Connecting Device: No SecurityDetail for "+device.toString()); + PrintUtil.println(System.err, "****** Connecting Device: No SecurityDetail for "+device.toString()); } final BTSecurityLevel req_sec_level = null != sec ? sec.getSecLevel() : BTSecurityLevel.UNSET; HCIStatusCode res = device.uploadKeys(DBTConstants.CLIENT_KEY_PATH, req_sec_level, true /* verbose_ */); - BTUtils.fprintf_td(System.err, "****** Connecting Device: BTDevice::uploadKeys(...) result %s\n", res.toString()); + PrintUtil.fprintf_td(System.err, "****** Connecting Device: BTDevice::uploadKeys(...) result %s\n", res.toString()); if( HCIStatusCode.SUCCESS != res ) { if( null != sec ) { if( sec.isSecurityAutoEnabled() ) { final boolean r = device.setConnSecurityAuto( sec.getSecurityAutoIOCap() ); - BTUtils.println(System.err, "****** Connecting Device: Using SecurityDetail.SEC AUTO "+sec+" -> set OK "+r); + PrintUtil.println(System.err, "****** Connecting Device: Using SecurityDetail.SEC AUTO "+sec+" -> set OK "+r); } else if( sec.isSecLevelOrIOCapSet() ) { final boolean r = device.setConnSecurity(sec.getSecLevel(), sec.getIOCap()); - BTUtils.println(System.err, "****** Connecting Device: Using SecurityDetail.Level+IOCap "+sec+" -> set OK "+r); + PrintUtil.println(System.err, "****** Connecting Device: Using SecurityDetail.Level+IOCap "+sec+" -> set OK "+r); } else { final boolean r = device.setConnSecurityAuto( SMPIOCapability.KEYBOARD_ONLY ); - BTUtils.println(System.err, "****** Connecting Device: Setting SEC AUTO security detail w/ KEYBOARD_ONLY ("+sec+") -> set OK "+r); + PrintUtil.println(System.err, "****** Connecting Device: Setting SEC AUTO security detail w/ KEYBOARD_ONLY ("+sec+") -> set OK "+r); } } else { final boolean r = device.setConnSecurityAuto( SMPIOCapability.KEYBOARD_ONLY ); - BTUtils.println(System.err, "****** Connecting Device: Setting SEC AUTO security detail w/ KEYBOARD_ONLY -> set OK "+r); + PrintUtil.println(System.err, "****** Connecting Device: Setting SEC AUTO security detail w/ KEYBOARD_ONLY -> set OK "+r); } } final EInfoReport eir = device.getEIR(); - BTUtils.println(System.err, "EIR-1 "+device.getEIRInd().toString()); - BTUtils.println(System.err, "EIR-2 "+device.getEIRScanRsp().toString()); - BTUtils.println(System.err, "EIR-+ "+eir.toString()); + PrintUtil.println(System.err, "EIR-1 "+device.getEIRInd().toString()); + PrintUtil.println(System.err, "EIR-2 "+device.getEIRScanRsp().toString()); + PrintUtil.println(System.err, "EIR-+ "+eir.toString()); short conn_interval_min = (short)8; // 10ms short conn_interval_max = (short)12; // 15ms @@ -357,7 +360,7 @@ public class DBTScanner10 { } final short supervision_timeout = BTUtils.getHCIConnSupervisorTimeout(conn_latency, (int) ( conn_interval_max * 1.25 ) /* ms */); res = device.connectLE(le_scan_interval, le_scan_window, conn_interval_min, conn_interval_max, conn_latency, supervision_timeout); - BTUtils.println(System.err, "****** Connecting Device Command, res "+res+": End result "+res+" of " + device.toString()); + PrintUtil.println(System.err, "****** Connecting Device Command, res "+res+": End result "+res+" of " + device.toString()); } void shutdownTest() { @@ -385,11 +388,11 @@ public class DBTScanner10 { } private void processReadyDevice(final BTDevice device) { - BTUtils.println(System.err, "****** Processing Ready Device: Start " + device.toString()); - final long t1 = BTUtils.currentTimeMillis(); + PrintUtil.println(System.err, "****** Processing Ready Device: Start " + device.toString()); + final long t1 = Clock.currentTimeMillis(); SMPKeyBin.createAndWrite(device, DBTConstants.CLIENT_KEY_PATH, true /* verbose */); - final long t2 = BTUtils.currentTimeMillis(); + final long t2 = Clock.currentTimeMillis(); boolean success = false; @@ -398,17 +401,17 @@ public class DBTScanner10 { final LE_PHYs Rx = new LE_PHYs(LE_PHYs.PHY.LE_2M); final HCIStatusCode res = device.setConnectedLE_PHY(Tx, Rx); - BTUtils.fprintf_td(System.err, "****** Set Connected LE PHY: status %s: Tx %s, Rx %s\n", + PrintUtil.fprintf_td(System.err, "****** Set Connected LE PHY: status %s: Tx %s, Rx %s\n", res.toString(), Tx.toString(), Rx.toString()); } { final LE_PHYs resTx[] = { new LE_PHYs() }; final LE_PHYs resRx[] = { new LE_PHYs() }; final HCIStatusCode res = device.getConnectedLE_PHY(resTx, resRx); - BTUtils.fprintf_td(System.err, "****** Got Connected LE PHY: status %s: Tx %s, Rx %s\n", + PrintUtil.fprintf_td(System.err, "****** Got Connected LE PHY: status %s: Tx %s, Rx %s\n", res.toString(), resTx[0].toString(), resRx[0].toString()); } - final long t3 = BTUtils.currentTimeMillis(); + final long t3 = Clock.currentTimeMillis(); // // GATT Service Processing @@ -420,7 +423,7 @@ public class DBTScanner10 { // And it is an error case nonetheless ;-) throw new RuntimeException("Processing Ready Device: getServices() failed " + device.toString()); } - final long t5 = BTUtils.currentTimeMillis(); + final long t5 = Clock.currentTimeMillis(); { final long td00 = device.getLastDiscoveryTimestamp() - timestamp_t0; // adapter-init to discovered final long td01 = t1 - timestamp_t0; // adapter-init to processing-start @@ -431,8 +434,8 @@ public class DBTScanner10 { final long td23 = t3 - t2; // LE_PHY final long td13 = t3 - t1; // SMPKeyBin + LE_PHY final long td35 = t5 - t3; // get-gatt-services - BTUtils.println(System.err, System.lineSeparator()+System.lineSeparator()); - BTUtils.println(System.err, "PERF: GATT primary-services completed"+System.lineSeparator()+ + PrintUtil.println(System.err, System.lineSeparator()+System.lineSeparator()); + PrintUtil.println(System.err, "PERF: GATT primary-services completed"+System.lineSeparator()+ "PERF: adapter-init to discovered " + td00 + " ms,"+System.lineSeparator()+ "PERF: adapter-init to processing-start " + td01 + " ms,"+System.lineSeparator()+ "PERF: adapter-init to gatt-complete " + td05 + " ms,"+System.lineSeparator()+ @@ -447,22 +450,22 @@ public class DBTScanner10 { : new BTGattCmd(device, "TestCmd", null /* service_uuid */, cmd_uuid); cmd.setVerbose(true); final boolean cmd_resolved = cmd.isResolved(); - BTUtils.println(System.err, "Command test: "+cmd.toString()+", resolved "+cmd_resolved); + PrintUtil.println(System.err, "Command test: "+cmd.toString()+", resolved "+cmd_resolved); final byte[] cmd_data = { cmd_arg }; final HCIStatusCode cmd_res = cmd.send(true /* prefNoAck */, cmd_data, 3000 /* timeoutMS */); if( HCIStatusCode.SUCCESS == cmd_res ) { if( cmd.hasResponseSet() ) { final byte[] resp = cmd.getResponse(); if( 1 == resp.length && resp[0] == cmd_arg ) { - BTUtils.fprintf_td(System.err, "Success: %s -> %s (echo response)\n", cmd.toString(), BTUtils.bytesHexString(resp, 0, resp.length, true /* lsb */)); + PrintUtil.fprintf_td(System.err, "Success: %s -> %s (echo response)\n", cmd.toString(), BasicTypes.bytesHexString(resp, 0, resp.length, true /* lsb */)); } else { - BTUtils.fprintf_td(System.err, "Success: %s -> %s (different response)\n", cmd.toString(), BTUtils.bytesHexString(resp, 0, resp.length, true /* lsb */)); + PrintUtil.fprintf_td(System.err, "Success: %s -> %s (different response)\n", cmd.toString(), BasicTypes.bytesHexString(resp, 0, resp.length, true /* lsb */)); } } else { - BTUtils.fprintf_td(System.err, "Success: %s -> no response\n", cmd.toString()); + PrintUtil.fprintf_td(System.err, "Success: %s -> no response\n", cmd.toString()); } } else { - BTUtils.fprintf_td(System.err, "Failure: %s -> %s\n", cmd.toString(), cmd_res.toString()); + PrintUtil.fprintf_td(System.err, "Failure: %s -> %s\n", cmd.toString(), cmd_res.toString()); } cmd.close(); } @@ -472,23 +475,23 @@ public class DBTScanner10 { for(final Iterator<BTGattService> srvIter = primServices.iterator(); srvIter.hasNext(); i++) { final BTGattService primService = srvIter.next(); { - BTUtils.fprintf_td(System.err, " [%02d] Service UUID %s\n", i, primService.getUUID()); - BTUtils.fprintf_td(System.err, " [%02d] %s\n", i, primService.toString()); + PrintUtil.fprintf_td(System.err, " [%02d] Service UUID %s\n", i, primService.getUUID()); + PrintUtil.fprintf_td(System.err, " [%02d] %s\n", i, primService.toString()); } int j=0; final List<BTGattChar> serviceCharacteristics = primService.getChars(); for(final Iterator<BTGattChar> charIter = serviceCharacteristics.iterator(); charIter.hasNext(); j++) { final BTGattChar serviceChar = charIter.next(); { - BTUtils.fprintf_td(System.err, " [%02d.%02d] Characteristic: UUID %s\n", i, j, serviceChar.getUUID()); - BTUtils.fprintf_td(System.err, " [%02d.%02d] %s\n", i, j, serviceChar.toString()); + PrintUtil.fprintf_td(System.err, " [%02d.%02d] Characteristic: UUID %s\n", i, j, serviceChar.getUUID()); + PrintUtil.fprintf_td(System.err, " [%02d.%02d] %s\n", i, j, serviceChar.toString()); } final GattCharPropertySet properties = serviceChar.getProperties(); if( properties.isSet(GattCharPropertySet.Type.Read) ) { final byte[] value = serviceChar.readValue(); final String svalue = BTUtils.decodeUTF8String(value, 0, value.length); { - BTUtils.fprintf_td(System.err, " [%02d.%02d] value: %s ('%s')\n", i, j, BTUtils.bytesHexString(value, 0, -1, true), svalue); + PrintUtil.fprintf_td(System.err, " [%02d.%02d] value: %s ('%s')\n", i, j, BasicTypes.bytesHexString(value, 0, -1, true), svalue); } } int k=0; @@ -496,8 +499,8 @@ public class DBTScanner10 { for(final Iterator<BTGattDesc> descIter = charDescList.iterator(); descIter.hasNext(); k++) { final BTGattDesc charDesc = descIter.next(); { - BTUtils.fprintf_td(System.err, " [%02d.%02d.%02d] Descriptor: UUID %s\n", i, j, k, charDesc.getUUID()); - BTUtils.fprintf_td(System.err, " [%02d.%02d.%02d] %s\n", i, j, k, charDesc.toString()); + PrintUtil.fprintf_td(System.err, " [%02d.%02d.%02d] Descriptor: UUID %s\n", i, j, k, charDesc.getUUID()); + PrintUtil.fprintf_td(System.err, " [%02d.%02d.%02d] %s\n", i, j, k, charDesc.toString()); } } final boolean cccdEnableResult[] = { false, false }; @@ -505,16 +508,16 @@ public class DBTScanner10 { // ClientCharConfigDescriptor (CCD) is available final boolean clAdded = serviceChar.addCharListener( new MyGATTEventListener(i, j) ); { - BTUtils.fprintf_td(System.err, " [%02d.%02d] Characteristic-Listener: Notification(%b), Indication(%b): Added %b\n", + PrintUtil.fprintf_td(System.err, " [%02d.%02d] Characteristic-Listener: Notification(%b), Indication(%b): Added %b\n", i, j, cccdEnableResult[0], cccdEnableResult[1], clAdded); - BTUtils.fprintf_td(System.err, "\n"); + PrintUtil.fprintf_td(System.err, "\n"); } } } - BTUtils.fprintf_td(System.err, "\n"); + PrintUtil.fprintf_td(System.err, "\n"); } } catch( final Exception ex) { - BTUtils.println(System.err, "Caught "+ex.getMessage()); + PrintUtil.println(System.err, "Caught "+ex.getMessage()); ex.printStackTrace(); } // FIXME sleep 1s for potential callbacks .. @@ -525,11 +528,11 @@ public class DBTScanner10 { } success = true; } catch (final Throwable t ) { - BTUtils.println(System.err, "****** Processing Ready Device: Exception caught for " + device.toString() + ": "+t.getMessage()); + PrintUtil.println(System.err, "****** Processing Ready Device: Exception caught for " + device.toString() + ": "+t.getMessage()); t.printStackTrace(); } - BTUtils.println(System.err, "****** Processing Ready Device: End-1: Success " + success + " on " + device.toString()); + PrintUtil.println(System.err, "****** Processing Ready Device: End-1: Success " + success + " on " + device.toString()); if( DiscoveryPolicy.PAUSE_CONNECTED_UNTIL_DISCONNECTED == discoveryPolicy ) { device.getAdapter().removeDevicePausingDiscovery(device); @@ -537,18 +540,18 @@ public class DBTScanner10 { if( KEEP_CONNECTED && GATT_PING_ENABLED && success ) { while( device.pingGATT() ) { - BTUtils.println(System.err, "****** Processing Ready Device: pingGATT OK: "+device.getAddressAndType()); + PrintUtil.println(System.err, "****** Processing Ready Device: pingGATT OK: "+device.getAddressAndType()); try { Thread.sleep(1000); } catch (final InterruptedException e) { e.printStackTrace(); } } - BTUtils.println(System.err, "****** Processing Ready Device: pingGATT failed, waiting for disconnect: "+device.getAddressAndType()); + PrintUtil.println(System.err, "****** Processing Ready Device: pingGATT failed, waiting for disconnect: "+device.getAddressAndType()); // Even w/ GATT_PING_ENABLED, we utilize disconnect event to clean up -> remove } - BTUtils.println(System.err, "****** Processing Ready Device: End-2: Success " + success + " on " + device.toString()); + PrintUtil.println(System.err, "****** Processing Ready Device: End-2: Success " + success + " on " + device.toString()); if( success ) { BTDeviceRegistry.addToProcessedDevices(device.getAddressAndType(), device.getName()); } @@ -565,20 +568,20 @@ public class DBTScanner10 { if( 0 < MULTI_MEASUREMENTS.get() ) { MULTI_MEASUREMENTS.decrementAndGet(); - BTUtils.println(System.err, "****** Processing Ready Device: MULTI_MEASUREMENTS left "+MULTI_MEASUREMENTS.get()+": "+device.getAddressAndType()); + PrintUtil.println(System.err, "****** Processing Ready Device: MULTI_MEASUREMENTS left "+MULTI_MEASUREMENTS.get()+": "+device.getAddressAndType()); } } private void removeDevice(final BTDevice device) { - BTUtils.println(System.err, "****** Remove Device: removing: "+device.getAddressAndType()); + PrintUtil.println(System.err, "****** Remove Device: removing: "+device.getAddressAndType()); device.remove(); } private void resetAdapter(final BTAdapter adapter, final int mode) { - BTUtils.println(System.err, "****** Reset Adapter: reset["+mode+"] start: "+adapter.toString()); + PrintUtil.println(System.err, "****** Reset Adapter: reset["+mode+"] start: "+adapter.toString()); final HCIStatusCode res = adapter.reset(); - BTUtils.println(System.err, "****** Reset Adapter: reset["+mode+"] end: "+res+", "+adapter.toString()); + PrintUtil.println(System.err, "****** Reset Adapter: reset["+mode+"] end: "+res+", "+adapter.toString()); } DiscoveryPolicy discoveryPolicy = DiscoveryPolicy.PAUSE_CONNECTED_UNTIL_READY; // default value @@ -590,43 +593,43 @@ public class DBTScanner10 { private boolean startDiscovery(final BTAdapter adapter, final String msg) { if( !useAdapter.equals(EUI48.ALL_DEVICE) && !useAdapter.equals(adapter.getAddressAndType().address) ) { - BTUtils.fprintf_td(System.err, "****** Start discovery (%s): Adapter not selected: %s\n", msg, adapter.toString()); + PrintUtil.fprintf_td(System.err, "****** Start discovery (%s): Adapter not selected: %s\n", msg, adapter.toString()); return false; } final HCIStatusCode status = adapter.startDiscovery( discoveryPolicy, le_scan_active, le_scan_interval, le_scan_window, filter_policy, filter_dup ); - BTUtils.println(System.err, "****** Start discovery ("+msg+") result: "+status); + PrintUtil.println(System.err, "****** Start discovery ("+msg+") result: "+status); return HCIStatusCode.SUCCESS == status; } private boolean initAdapter(final BTAdapter adapter) { if( !useAdapter.equals(EUI48.ALL_DEVICE) && !useAdapter.equals(adapter.getAddressAndType().address) ) { - BTUtils.fprintf_td(System.err, "initAdapter: Adapter not selected: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initAdapter: Adapter not selected: %s\n", adapter.toString()); return false; } // Initialize with defaults and power-on if( !adapter.isInitialized() ) { final HCIStatusCode status = adapter.initialize( btMode ); if( HCIStatusCode.SUCCESS != status ) { - BTUtils.fprintf_td(System.err, "initAdapter: Adapter initialization failed: %s: %s\n", + PrintUtil.fprintf_td(System.err, "initAdapter: Adapter initialization failed: %s: %s\n", status.toString(), adapter.toString()); return false; } } else if( !adapter.setPowered( true ) ) { - BTUtils.fprintf_td(System.err, "initAdapter: Already initialized adapter power-on failed:: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initAdapter: Already initialized adapter power-on failed:: %s\n", adapter.toString()); return false; } // adapter is powered-on - BTUtils.fprintf_td(System.err, "initAdapter: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initAdapter: %s\n", adapter.toString()); { final LE_Features le_feats = adapter.getLEFeatures(); - BTUtils.fprintf_td(System.err, "initAdapter: LE_Features %s\n", le_feats.toString()); + PrintUtil.fprintf_td(System.err, "initAdapter: LE_Features %s\n", le_feats.toString()); } if( adapter.getBTMajorVersion() > 4 ) { final LE_PHYs Tx = new LE_PHYs(LE_PHYs.PHY.LE_2M); final LE_PHYs Rx = new LE_PHYs(LE_PHYs.PHY.LE_2M); final HCIStatusCode res = adapter.setDefaultLE_PHY(Tx, Rx); - BTUtils.fprintf_td(System.err, "initAdapter: Set Default LE PHY: status %s: Tx %s, Rx %s\n", + PrintUtil.fprintf_td(System.err, "initAdapter: Set Default LE PHY: status %s: Tx %s, Rx %s\n", res.toString(), Tx.toString(), Rx.toString()); } final AdapterStatusListener asl = new MyAdapterStatusListener(); @@ -646,12 +649,12 @@ public class DBTScanner10 { if( null == chosenAdapter ) { if( initAdapter( adapter ) ) { chosenAdapter = adapter; - BTUtils.println(System.err, "****** Adapter ADDED__: InitOK: " + adapter); + PrintUtil.println(System.err, "****** Adapter ADDED__: InitOK: " + adapter); } else { - BTUtils.println(System.err, "****** Adapter ADDED__: Ignored: " + adapter); + PrintUtil.println(System.err, "****** Adapter ADDED__: Ignored: " + adapter); } } else { - BTUtils.println(System.err, "****** Adapter ADDED__: Ignored (other): " + adapter); + PrintUtil.println(System.err, "****** Adapter ADDED__: Ignored (other): " + adapter); } } @@ -659,15 +662,15 @@ public class DBTScanner10 { public void adapterRemoved(final BTAdapter adapter) { if( null != chosenAdapter && adapter == chosenAdapter ) { chosenAdapter = null; - BTUtils.println(System.err, "****** Adapter REMOVED: " + adapter); + PrintUtil.println(System.err, "****** Adapter REMOVED: " + adapter); } else { - BTUtils.println(System.err, "****** Adapter REMOVED (other): " + adapter); + PrintUtil.println(System.err, "****** Adapter REMOVED (other): " + adapter); } } }; public void runTest(final BTManager manager) { - timestamp_t0 = BTUtils.currentTimeMillis(); + timestamp_t0 = Clock.currentTimeMillis(); boolean done = false; @@ -678,10 +681,10 @@ public class DBTScanner10 { ( -1 == MULTI_MEASUREMENTS.get() && !BTDeviceRegistry.isWaitingForAnyDevice() && BTDeviceRegistry.areAllDevicesProcessed() ) ) { - BTUtils.println(System.err, "****** EOL Test MULTI_MEASUREMENTS left "+MULTI_MEASUREMENTS.get()+ + PrintUtil.println(System.err, "****** EOL Test MULTI_MEASUREMENTS left "+MULTI_MEASUREMENTS.get()+ ", processed "+BTDeviceRegistry.getProcessedDeviceCount()+"/"+BTDeviceRegistry.getWaitForDevicesCount()); - BTUtils.println(System.err, "****** WaitForDevices "+BTDeviceRegistry.getWaitForDevicesString()); - BTUtils.println(System.err, "****** DevicesProcessed "+BTDeviceRegistry.getProcessedDevicesString()); + PrintUtil.println(System.err, "****** WaitForDevices "+BTDeviceRegistry.getWaitForDevicesString()); + PrintUtil.println(System.err, "****** DevicesProcessed "+BTDeviceRegistry.getProcessedDevicesString()); done = true; } else { try { @@ -701,11 +704,11 @@ public class DBTScanner10 { adapters.forEach(new Consumer<BTAdapter>() { @Override public void accept(final BTAdapter a) { - BTUtils.println(System.err, "****** EOL Adapter's Devices - pre_ close: " + a); + PrintUtil.println(System.err, "****** EOL Adapter's Devices - pre_ close: " + a); } } ); { final int count = manager.removeChangedAdapterSetListener(myChangedAdapterSetListener); - BTUtils.println(System.err, "****** EOL Removed ChangedAdapterSetCallback " + count); + PrintUtil.println(System.err, "****** EOL Removed ChangedAdapterSetCallback " + count); // All implicit via destructor or shutdown hook! manager.shutdown(); /* implies: adapter.close(); */ @@ -713,7 +716,7 @@ public class DBTScanner10 { adapters.forEach(new Consumer<BTAdapter>() { @Override public void accept(final BTAdapter a) { - BTUtils.println(System.err, "****** EOL Adapter's Devices - post close: " + a); + PrintUtil.println(System.err, "****** EOL Adapter's Devices - post close: " + a); } } ); } @@ -751,9 +754,9 @@ public class DBTScanner10 { System.exit(-1); return; } - BTUtils.println(System.err, "Direct-BT BluetoothManager initialized!"); - BTUtils.println(System.err, "Direct-BT Native Version "+BTFactory.getNativeVersion()+" (API "+BTFactory.getNativeAPIVersion()+")"); - BTUtils.println(System.err, "Direct-BT Java Version "+BTFactory.getImplVersion()+" (API "+BTFactory.getAPIVersion()+")"); + PrintUtil.println(System.err, "Direct-BT BluetoothManager initialized!"); + PrintUtil.println(System.err, "Direct-BT Native Version "+BTFactory.getNativeVersion()+" (API "+BTFactory.getNativeAPIVersion()+")"); + PrintUtil.println(System.err, "Direct-BT Java Version "+BTFactory.getImplVersion()+" (API "+BTFactory.getAPIVersion()+")"); final DBTScanner10 test = new DBTScanner10(); @@ -823,7 +826,7 @@ public class DBTScanner10 { test.RESET_ADAPTER_EACH_CONN = Integer.valueOf(args[++i]).intValue(); } } - BTUtils.println(System.err, "Run with '[-btmode LE|BREDR|DUAL] "+ + PrintUtil.println(System.err, "Run with '[-btmode LE|BREDR|DUAL] "+ "[-disconnect] [-enableGATTPing] [-count <number>] [-single] [-show_update_events] [-quiet] "+ "[-discoveryPolicy <0-4>] "+ "[-scanPassive] "+ @@ -845,24 +848,24 @@ public class DBTScanner10 { "[-shutdown <int>]'"); } - BTUtils.println(System.err, "MULTI_MEASUREMENTS "+test.MULTI_MEASUREMENTS.get()); - BTUtils.println(System.err, "KEEP_CONNECTED "+test.KEEP_CONNECTED); - BTUtils.println(System.err, "RESET_ADAPTER_EACH_CONN "+test.RESET_ADAPTER_EACH_CONN); - BTUtils.println(System.err, "GATT_PING_ENABLED "+test.GATT_PING_ENABLED); - BTUtils.println(System.err, "REMOVE_DEVICE "+test.REMOVE_DEVICE); - BTUtils.println(System.err, "SHOW_UPDATE_EVENTS "+test.SHOW_UPDATE_EVENTS); - BTUtils.println(System.err, "QUIET "+test.QUIET); - BTUtils.println(System.err, "adapter "+test.useAdapter); - BTUtils.println(System.err, "btmode "+test.btMode.toString()); - BTUtils.println(System.err, "discoveryPolicy "+test.discoveryPolicy.toString()); - BTUtils.println(System.err, "le_scan_active "+test.le_scan_active); - BTUtils.println(System.err, "Command: cmd "+test.cmd_uuid+", arg 0x"+Integer.toHexString(test.cmd_arg)); - BTUtils.println(System.err, " rsp "+test.cmd_rsp_uuid); - BTUtils.println(System.err, "security-details: "+BTSecurityRegistry.allToString() ); - BTUtils.println(System.err, "waitForDevices: "+BTDeviceRegistry.getWaitForDevicesString()); + PrintUtil.println(System.err, "MULTI_MEASUREMENTS "+test.MULTI_MEASUREMENTS.get()); + PrintUtil.println(System.err, "KEEP_CONNECTED "+test.KEEP_CONNECTED); + PrintUtil.println(System.err, "RESET_ADAPTER_EACH_CONN "+test.RESET_ADAPTER_EACH_CONN); + PrintUtil.println(System.err, "GATT_PING_ENABLED "+test.GATT_PING_ENABLED); + PrintUtil.println(System.err, "REMOVE_DEVICE "+test.REMOVE_DEVICE); + PrintUtil.println(System.err, "SHOW_UPDATE_EVENTS "+test.SHOW_UPDATE_EVENTS); + PrintUtil.println(System.err, "QUIET "+test.QUIET); + PrintUtil.println(System.err, "adapter "+test.useAdapter); + PrintUtil.println(System.err, "btmode "+test.btMode.toString()); + PrintUtil.println(System.err, "discoveryPolicy "+test.discoveryPolicy.toString()); + PrintUtil.println(System.err, "le_scan_active "+test.le_scan_active); + PrintUtil.println(System.err, "Command: cmd "+test.cmd_uuid+", arg 0x"+Integer.toHexString(test.cmd_arg)); + PrintUtil.println(System.err, " rsp "+test.cmd_rsp_uuid); + PrintUtil.println(System.err, "security-details: "+BTSecurityRegistry.allToString() ); + PrintUtil.println(System.err, "waitForDevices: "+BTDeviceRegistry.getWaitForDevicesString()); if( waitForEnter ) { - BTUtils.println(System.err, "Press ENTER to continue\n"); + PrintUtil.println(System.err, "Press ENTER to continue\n"); try{ System.in.read(); } catch(final Exception e) { } } diff --git a/java/CMakeLists.txt b/java/CMakeLists.txt index 8c52088c..1d6783d6 100644 --- a/java/CMakeLists.txt +++ b/java/CMakeLists.txt @@ -9,6 +9,8 @@ file(GLOB_RECURSE JAVA_SOURCES "*.java") add_jar(direct_bt_jar ${JAVA_SOURCES} ${PROJECT_SOURCE_DIR}/jaulib/java_base/org/jau/util/BasicTypes.java + ${PROJECT_SOURCE_DIR}/jaulib/java_jni/org/jau/sys/Clock.java + ${PROJECT_SOURCE_DIR}/jaulib/java_jni/org/jau/io/PrintUtil.java ${PROJECT_SOURCE_DIR}/jaulib/java_net/org/jau/net/EUI48.java ${PROJECT_SOURCE_DIR}/jaulib/java_net/org/jau/net/EUI48Sub.java INCLUDE_JARS ${jaulib_fat_jar_file} diff --git a/java/jau/direct_bt/DBTAdapter.java b/java/jau/direct_bt/DBTAdapter.java index d57ef664..ec30efe1 100644 --- a/java/jau/direct_bt/DBTAdapter.java +++ b/java/jau/direct_bt/DBTAdapter.java @@ -45,7 +45,6 @@ import org.direct_bt.BTManager; import org.direct_bt.BTMode; import org.direct_bt.BTRole; import org.direct_bt.BTSecurityLevel; -import org.direct_bt.BTUtils; import org.direct_bt.DBGattServer; import org.direct_bt.DiscoveryPolicy; import org.direct_bt.EIRDataTypeSet; @@ -58,6 +57,7 @@ import org.direct_bt.PairingMode; import org.direct_bt.SMPIOCapability; import org.direct_bt.SMPPairingState; import org.direct_bt.ScanType; +import org.jau.io.PrintUtil; import org.jau.net.EUI48; public class DBTAdapter extends DBTObject implements BTAdapter @@ -388,7 +388,7 @@ public class DBTAdapter extends DBTObject implements BTAdapter final HCIStatusCode res = HCIStatusCode.get( startDiscoveryImpl(policy.value, le_scan_active, le_scan_interval, le_scan_window, filter_policy, filter_dup) ); if( PRINT_DEVICE_LISTS || DEBUG ) { - BTUtils.fprintf_td(System.err, "BTAdapter::startDiscovery: res %s, %s", res, toString()); + PrintUtil.fprintf_td(System.err, "BTAdapter::startDiscovery: res %s, %s", res, toString()); printDeviceLists(); } return res; @@ -405,7 +405,7 @@ public class DBTAdapter extends DBTObject implements BTAdapter // Ignoring 'isDiscovering', be consistent with startDiscovery final HCIStatusCode res = HCIStatusCode.get( stopDiscoveryImpl() ); // event callbacks will be generated by implementation if( PRINT_DEVICE_LISTS || DEBUG ) { - BTUtils.fprintf_td(System.err, "BTAdapter::stopDiscovery: res %s, %s", res, toString()); + PrintUtil.fprintf_td(System.err, "BTAdapter::stopDiscovery: res %s, %s", res, toString()); printDeviceLists(); } return res; @@ -431,7 +431,7 @@ public class DBTAdapter extends DBTObject implements BTAdapter final int cn = removeDiscoveredDevicesImpl1(); if( DEBUG ) { if( cj != cn ) { - BTUtils.println(System.err, "DBTAdapter::removeDevices: Unexpected discovered device count: Native "+cn+", callback "+cj); + PrintUtil.println(System.err, "DBTAdapter::removeDevices: Unexpected discovered device count: Native "+cn+", callback "+cj); } } return cn; @@ -454,7 +454,7 @@ public class DBTAdapter extends DBTObject implements BTAdapter final boolean cn = removeDiscoveredDeviceImpl1(addressAndType.address.b, addressAndType.type.value); if( DEBUG ) { if( cj != cn ) { - BTUtils.println(System.err, "DBTAdapter::removeDevices("+addressAndType+"): Unexpected discovered device count: Native "+cn+", callback "+cj); + PrintUtil.println(System.err, "DBTAdapter::removeDevices("+addressAndType+"): Unexpected discovered device count: Native "+cn+", callback "+cj); } } return cn; @@ -505,7 +505,7 @@ public class DBTAdapter extends DBTObject implements BTAdapter public final boolean addStatusListener(final AdapterStatusListener l) { final boolean added = addStatusListenerImpl(null, l); if( PRINT_DEVICE_LISTS || DEBUG ) { - BTUtils.fprintf_td(System.err, "BTAdapter::addStatusListener: added %b, %s", added, toString()); + PrintUtil.fprintf_td(System.err, "BTAdapter::addStatusListener: added %b, %s", added, toString()); printDeviceLists(); } return added; @@ -519,7 +519,7 @@ public class DBTAdapter extends DBTObject implements BTAdapter res = removeStatusListenerImpl(l); } if( PRINT_DEVICE_LISTS || DEBUG ) { - BTUtils.fprintf_td(System.err, "BTAdapter::removeStatusListener: removed %b, %s", res, toString()); + PrintUtil.fprintf_td(System.err, "BTAdapter::removeStatusListener: removed %b, %s", res, toString()); printDeviceLists(); } return res; @@ -543,14 +543,14 @@ public class DBTAdapter extends DBTObject implements BTAdapter _discoveredDevices = new ArrayList<WeakReference<BTDevice>>(discoveredDevices); } final int sz = _discoveredDevices.size(); - BTUtils.fprintf_td(System.err, "- BTAdapter::DiscoveredDevicesJ: %d elements%s", sz, System.lineSeparator()); + PrintUtil.fprintf_td(System.err, "- BTAdapter::DiscoveredDevicesJ: %d elements%s", sz, System.lineSeparator()); int idx = 0; for(final Iterator<WeakReference<BTDevice>> it = _discoveredDevices.iterator(); it.hasNext(); ++idx) { final BTDevice d = it.next().get(); if( null == d ) { - BTUtils.fprintf_td(System.err, " - %d / %d: nil%s", (idx+1), sz, System.lineSeparator()); + PrintUtil.fprintf_td(System.err, " - %d / %d: nil%s", (idx+1), sz, System.lineSeparator()); } else { - BTUtils.fprintf_td(System.err, " - %d / %d: %s, name '%s'%s", (idx+1), sz, + PrintUtil.fprintf_td(System.err, " - %d / %d: %s, name '%s'%s", (idx+1), sz, d.getAddressAndType().toString(), d.getName(), System.lineSeparator()); } } @@ -566,9 +566,9 @@ public class DBTAdapter extends DBTObject implements BTAdapter final boolean initialSetting = oldmask.isEmpty(); if( DEBUG ) { if( initialSetting ) { - BTUtils.println(System.err, "Adapter.StatusListener.SETTINGS: "+oldmask+" -> "+newmask+", initial "+changedmask+" on "+a); + PrintUtil.println(System.err, "Adapter.StatusListener.SETTINGS: "+oldmask+" -> "+newmask+", initial "+changedmask+" on "+a); } else { - BTUtils.println(System.err, "Adapter.StatusListener.SETTINGS: "+oldmask+" -> "+newmask+", changed "+changedmask+" on "+a); + PrintUtil.println(System.err, "Adapter.StatusListener.SETTINGS: "+oldmask+" -> "+newmask+", changed "+changedmask+" on "+a); } } if( initialSetting ) { @@ -587,7 +587,7 @@ public class DBTAdapter extends DBTObject implements BTAdapter @Override public void discoveringChanged(final BTAdapter adapter, final ScanType currentMeta, final ScanType changedType, final boolean changedEnabled, final DiscoveryPolicy policy, final long timestamp) { if( DEBUG ) { - BTUtils.println(System.err, "Adapter.StatusListener.DISCOVERING: meta "+currentMeta+", changed["+changedType+", enabled "+changedEnabled+", keepAlive "+policy+"] on "+adapter); + PrintUtil.println(System.err, "Adapter.StatusListener.DISCOVERING: meta "+currentMeta+", changed["+changedType+", enabled "+changedEnabled+", keepAlive "+policy+"] on "+adapter); } // meta ignores changes on temp disabled discovery currentMetaScanType.set(currentMeta); @@ -599,7 +599,7 @@ public class DBTAdapter extends DBTObject implements BTAdapter discoveredDevices.add(new WeakReference<BTDevice>(device)); } if( PRINT_DEVICE_LISTS || DEBUG ) { - BTUtils.println(System.err, "Adapter.FOUND: discoveredDevices "+ discoveredDevices.size() + ": "+device+", on "+device.getAdapter()); + PrintUtil.println(System.err, "Adapter.FOUND: discoveredDevices "+ discoveredDevices.size() + ": "+device+", on "+device.getAdapter()); } return false; } @@ -609,7 +609,7 @@ public class DBTAdapter extends DBTObject implements BTAdapter final boolean rssiUpdated = updateMask.isSet( EIRDataTypeSet.DataType.RSSI ); final boolean mdUpdated = updateMask.isSet( EIRDataTypeSet.DataType.MANUF_DATA ); if( DEBUG && !rssiUpdated && !mdUpdated) { - BTUtils.println(System.err, "Adapter.UPDATED: "+updateMask+" of "+device+" on "+device.getAdapter()); + PrintUtil.println(System.err, "Adapter.UPDATED: "+updateMask+" of "+device+" on "+device.getAdapter()); } // nop on discoveredDevices } @@ -617,7 +617,7 @@ public class DBTAdapter extends DBTObject implements BTAdapter @Override public void deviceConnected(final BTDevice device, final boolean discovered, final long timestamp) { if( DEBUG ) { - BTUtils.println(System.err, "Adapter.CONNECTED (discovered "+discovered+"): "+device+" on "+device.getAdapter()); + PrintUtil.println(System.err, "Adapter.CONNECTED (discovered "+discovered+"): "+device+" on "+device.getAdapter()); } final DBTDevice device_ = (DBTDevice)device; if( device_.isConnected.compareAndSet(false, true) ) { @@ -628,21 +628,21 @@ public class DBTAdapter extends DBTObject implements BTAdapter @Override public void devicePairingState(final BTDevice device, final SMPPairingState state, final PairingMode mode, final long timestamp) { if( DEBUG ) { - BTUtils.println(System.err, "Adapter.PAIRING_STATE: state "+state+", mode "+mode+": "+device); + PrintUtil.println(System.err, "Adapter.PAIRING_STATE: state "+state+", mode "+mode+": "+device); } } @Override public void deviceReady(final BTDevice device, final long timestamp) { if( DEBUG ) { - BTUtils.println(System.err, "Adapter.READY: "+device); + PrintUtil.println(System.err, "Adapter.READY: "+device); } } @Override public void deviceDisconnected(final BTDevice device, final HCIStatusCode reason, final short handle, final long timestamp) { if( DEBUG ) { - BTUtils.println(System.err, "Adapter.DISCONNECTED: Reason "+reason+", old handle 0x"+Integer.toHexString(handle)+": "+device+" on "+device.getAdapter()); + PrintUtil.println(System.err, "Adapter.DISCONNECTED: Reason "+reason+", old handle 0x"+Integer.toHexString(handle)+": "+device+" on "+device.getAdapter()); } gattServerData = null; diff --git a/java/jau/direct_bt/DBTDevice.java b/java/jau/direct_bt/DBTDevice.java index 1184b808..c475ed98 100644 --- a/java/jau/direct_bt/DBTDevice.java +++ b/java/jau/direct_bt/DBTDevice.java @@ -40,7 +40,6 @@ import org.direct_bt.BTException; import org.direct_bt.BTGattChar; import org.direct_bt.BTGattService; import org.direct_bt.BTRole; -import org.direct_bt.BTUtils; import org.direct_bt.EInfoReport; import org.direct_bt.BTGattCharListener; import org.direct_bt.HCIStatusCode; @@ -54,6 +53,7 @@ import org.direct_bt.SMPLinkKey; import org.direct_bt.SMPLongTermKey; import org.direct_bt.SMPPairingState; import org.direct_bt.SMPSignatureResolvingKey; +import org.jau.io.PrintUtil; import org.jau.net.EUI48; public class DBTDevice extends DBTObject implements BTDevice @@ -315,7 +315,7 @@ public class DBTDevice extends DBTObject implements BTDevice public final boolean setSMPKeyBin(final SMPKeyBin bin) { if( !isValid() ) { if( DEBUG ) { - BTUtils.fprintf_td(System.err, "BTDevice::setSMPKeyBin(): Apply SMPKeyBin failed, device invalid: %s, %s", + PrintUtil.fprintf_td(System.err, "BTDevice::setSMPKeyBin(): Apply SMPKeyBin failed, device invalid: %s, %s", bin.toString(), toString()); } return false; @@ -323,14 +323,14 @@ public class DBTDevice extends DBTObject implements BTDevice if( !bin.getLocalAddrAndType().equals( getAdapter().getAddressAndType() ) ) { if( DEBUG ) { - BTUtils.println(System.err, "SMPKeyBin::readAndApply: Local address mismatch: Has "+getAdapter().getAddressAndType().toString()+ + PrintUtil.println(System.err, "SMPKeyBin::readAndApply: Local address mismatch: Has "+getAdapter().getAddressAndType().toString()+ ", read "+bin.getLocalAddrAndType().toString()+": "+bin.toString()); } return false; } if( !bin.getRemoteAddrAndType().equals( getAddressAndType() ) ) { if( DEBUG ) { - BTUtils.println(System.err, "SMPKeyBin::readAndApply: Remote address mismatch: Has "+getAddressAndType().toString()+ + PrintUtil.println(System.err, "SMPKeyBin::readAndApply: Remote address mismatch: Has "+getAddressAndType().toString()+ ", read "+bin.getRemoteAddrAndType().toString()+": "+bin.toString()); } return false; @@ -339,7 +339,7 @@ public class DBTDevice extends DBTObject implements BTDevice // Must be a valid SMPKeyBin instance and at least one LTK key if using encryption. if( !bin.isValid() || ( BTSecurityLevel.NONE != bin.getSecLevel() && !bin.hasLTKInit() && !bin.hasLTKResp() ) ) { if( DEBUG ) { - BTUtils.fprintf_td(System.err, "BTDevice::setSMPKeyBin(): Apply SMPKeyBin failed, all invalid or sec level w/o LTK: %s, %s", + PrintUtil.fprintf_td(System.err, "BTDevice::setSMPKeyBin(): Apply SMPKeyBin failed, all invalid or sec level w/o LTK: %s, %s", bin.toString(), toString()); } return false; @@ -358,7 +358,7 @@ public class DBTDevice extends DBTObject implements BTDevice */ if( getConnected() ) { if( DEBUG ) { - BTUtils.println(System.err, "BTDevice::setSMPKeyBin: Failure, device connected: "+toString()); + PrintUtil.println(System.err, "BTDevice::setSMPKeyBin: Failure, device connected: "+toString()); } return false; } @@ -369,7 +369,7 @@ public class DBTDevice extends DBTObject implements BTDevice if( !setConnSecurity(applySecLevel, SMPIOCapability.NO_INPUT_NO_OUTPUT) ) { if( DEBUG ) { - BTUtils.println(System.err, "BTDevice::setSMPKeyBin: Apply SMPKeyBin failed: Device Connected/ing: "+bin.toString()+", "+toString()); + PrintUtil.println(System.err, "BTDevice::setSMPKeyBin: Apply SMPKeyBin failed: Device Connected/ing: "+bin.toString()+", "+toString()); } return false; } @@ -573,7 +573,7 @@ public class DBTDevice extends DBTObject implements BTDevice close(); // return removeImpl(); if( DBTAdapter.PRINT_DEVICE_LISTS || DEBUG ) { - BTUtils.fprintf_td(System.err, "BTDevice::remove: %s", toString()); + PrintUtil.fprintf_td(System.err, "BTDevice::remove: %s", toString()); getAdapter().printDeviceLists(); } return true; diff --git a/java/jau/direct_bt/DBTGattChar.java b/java/jau/direct_bt/DBTGattChar.java index afa9c7d4..ac8cf2fe 100644 --- a/java/jau/direct_bt/DBTGattChar.java +++ b/java/jau/direct_bt/DBTGattChar.java @@ -32,8 +32,8 @@ import org.direct_bt.BTException; import org.direct_bt.BTGattChar; import org.direct_bt.BTGattDesc; import org.direct_bt.BTGattService; -import org.direct_bt.BTUtils; import org.direct_bt.GattCharPropertySet; +import org.jau.util.BasicTypes; import org.direct_bt.BTGattCharListener; public class DBTGattChar extends DBTObject implements BTGattChar @@ -101,13 +101,13 @@ public class DBTGattChar extends DBTObject implements BTGattChar @Override public void notificationReceived(final BTGattChar charDecl, final byte[] value, final long timestamp) { System.err.println("GATTCharacteristicListener.notificationReceived: "+charDecl+ - ", value[len "+value.length+": "+BTUtils.bytesHexString(value, 0, -1, true)+"]"); + ", value[len "+value.length+": "+BasicTypes.bytesHexString(value, 0, -1, true)+"]"); } @Override public void indicationReceived(final BTGattChar charDecl, final byte[] value, final long timestamp, final boolean confirmationSent) { System.err.println("GATTCharacteristicListener.indicationReceived: "+charDecl+ - ", value[len "+value.length+": "+BTUtils.bytesHexString(value, 0, -1, true)+ + ", value[len "+value.length+": "+BasicTypes.bytesHexString(value, 0, -1, true)+ "], confirmationSent "+confirmationSent); } }; diff --git a/java/jni/direct_bt/BTUtils.cxx b/java/jni/direct_bt/BTUtils.cxx deleted file mode 100644 index 565e105d..00000000 --- a/java/jni/direct_bt/BTUtils.cxx +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Author: Sven Gothel <[email protected]> - * Copyright (c) 2020 Gothel Software e.K. - * Copyright (c) 2020 ZAFENA AB - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "org_direct_bt_BTUtils.h" - -#include <cstdint> -#include <cinttypes> - -#include <time.h> - -#include <jau/dfa_utf8_decode.hpp> -#include <jau/environment.hpp> - -#include "helper_base.hpp" - -static const uint64_t NanoPerMilli = 1000000UL; -static const uint64_t MilliPerOne = 1000UL; - -/** - * See <http://man7.org/linux/man-pages/man2/clock_gettime.2.html> - * <p> - * Regarding avoiding kernel via VDSO, - * see <http://man7.org/linux/man-pages/man7/vdso.7.html>, - * clock_gettime seems to be well supported at least on kernel >= 4.4. - * Only bfin and sh are missing, while ia64 seems to be complicated. - */ -jlong Java_org_direct_1bt_BTUtils_currentTimeMillis(JNIEnv *env, jclass clazz) { - (void)env; - (void)clazz; - - struct timespec t; - clock_gettime(CLOCK_MONOTONIC, &t); - uint64_t res = static_cast<uint64_t>( t.tv_sec ) * MilliPerOne + - static_cast<uint64_t>( t.tv_nsec ) / NanoPerMilli; - return (jlong)res; -} - -jlong Java_org_direct_1bt_BTUtils_wallClockSeconds(JNIEnv *env, jclass clazz) { - (void)env; - (void)clazz; - - struct timespec t; - clock_gettime(CLOCK_REALTIME, &t); - return (jlong)( static_cast<uint64_t>( t.tv_sec ) ); -} - - -jlong Java_org_direct_1bt_BTUtils_startupTimeMillisImpl(JNIEnv *env, jclass clazz) { - (void)env; - (void)clazz; - - return jau::environment::startupTimeMilliseconds; -} - -jstring Java_org_direct_1bt_BTUtils_decodeUTF8String(JNIEnv *env, jclass clazz, jbyteArray jbuffer, jint offset, jint size) { - (void)clazz; - - const int buffer_size = env->GetArrayLength(jbuffer); - if( 0 == buffer_size ) { - return env->NewStringUTF(""); - } - if( buffer_size < offset+size ) { - std::string msg("buffer.length "+std::to_string(buffer_size)+ - " < offset "+std::to_string(offset)+ - " + size "+std::to_string(size)); - throw jau::IllegalArgumentException(msg, E_FILE_LINE); - } - - std::string sres; - { - jau::jni::JNICriticalArray<uint8_t, jbyteArray> criticalArray(env); // RAII - release - uint8_t * buffer_ptr = criticalArray.get(jbuffer, criticalArray.Mode::NO_UPDATE_AND_RELEASE); - if( NULL == buffer_ptr ) { - throw jau::IllegalArgumentException("GetPrimitiveArrayCritical(byte array) is null", E_FILE_LINE); - } - sres = jau::dfa_utf8_decode(buffer_ptr+offset, static_cast<size_t>(size)); - } - return jau::jni::from_string_to_jstring(env, sres); -} diff --git a/java/jni/direct_bt/CMakeLists.txt b/java/jni/direct_bt/CMakeLists.txt index eab53367..4e912cb5 100644 --- a/java/jni/direct_bt/CMakeLists.txt +++ b/java/jni/direct_bt/CMakeLists.txt @@ -22,10 +22,10 @@ include_directories( set (direct_bt_JNI_SRCS ${PROJECT_SOURCE_DIR}/jaulib/java_jni/jni/jni_mem.cxx ${PROJECT_SOURCE_DIR}/jaulib/java_jni/jni/helper_jni.cxx + ${PROJECT_SOURCE_DIR}/jaulib/java_jni/jni/jau/jau_sys_Clock.cxx ${PROJECT_SOURCE_DIR}/java/jni/helper_base.cxx ${PROJECT_SOURCE_DIR}/java/jni/direct_bt/helper_dbt.cxx ${PROJECT_SOURCE_DIR}/java/jni/direct_bt/BTFactory.cxx - ${PROJECT_SOURCE_DIR}/java/jni/direct_bt/BTUtils.cxx ${PROJECT_SOURCE_DIR}/java/jni/direct_bt/DBTAdapter.cxx ${PROJECT_SOURCE_DIR}/java/jni/direct_bt/DBTDevice.cxx ${PROJECT_SOURCE_DIR}/java/jni/direct_bt/DBTGattChar.cxx diff --git a/java/org/direct_bt/BTGattCmd.java b/java/org/direct_bt/BTGattCmd.java index 1576756b..0a575ecd 100644 --- a/java/org/direct_bt/BTGattCmd.java +++ b/java/org/direct_bt/BTGattCmd.java @@ -25,6 +25,9 @@ package org.direct_bt; +import org.jau.io.PrintUtil; +import org.jau.util.BasicTypes; + /** * Class maps a GATT command and optionally its asynchronous response * to a synchronous atomic operation. @@ -75,8 +78,8 @@ public class BTGattCmd implements AutoCloseable final byte[] value, final long timestamp) { synchronized( source.mtxRspReceived ) { if( DEBUG ) { - BTUtils.fprintf_td(System.err, "BTGattCmd.notificationReceived: Resp %s, value[%s]\n", - charDecl.toString(), BTUtils.bytesHexString(value, 0, value.length, true /* lsbFirst */)); + PrintUtil.fprintf_td(System.err, "BTGattCmd.notificationReceived: Resp %s, value[%s]\n", + charDecl.toString(), BasicTypes.bytesHexString(value, 0, value.length, true /* lsbFirst */)); } source.rsp_data = value; source.mtxRspReceived.notifyAll(); @@ -89,8 +92,8 @@ public class BTGattCmd implements AutoCloseable final boolean confirmationSent) { synchronized( source.mtxRspReceived ) { if( DEBUG ) { - BTUtils.fprintf_td(System.err, "BTGattCmd.indicationReceived: Resp %s, value[%s]\n", - charDecl.toString(), BTUtils.bytesHexString(value, 0, value.length, true /* lsbFirst */)); + PrintUtil.fprintf_td(System.err, "BTGattCmd.indicationReceived: Resp %s, value[%s]\n", + charDecl.toString(), BasicTypes.bytesHexString(value, 0, value.length, true /* lsbFirst */)); } source.rsp_data = value; source.mtxRspReceived.notifyAll(); @@ -117,7 +120,7 @@ public class BTGattCmd implements AutoCloseable : dev.findGattChar(cmd_uuid); if( null == cmdCharRef ) { if( verbose ) { - BTUtils.fprintf_td(System.err, "Command not found: service %s, char %s\n", service_uuid, cmd_uuid); + PrintUtil.fprintf_td(System.err, "Command not found: service %s, char %s\n", service_uuid, cmd_uuid); } return HCIStatusCode.NOT_SUPPORTED; } @@ -125,7 +128,7 @@ public class BTGattCmd implements AutoCloseable if( !cmdCharRef.getProperties().isSet(GattCharPropertySet.Type.WriteNoAck) && !cmdCharRef.getProperties().isSet(GattCharPropertySet.Type.WriteWithAck) ) { if( verbose ) { - BTUtils.fprintf_td(System.err, "Command has no write property: %s\n", cmdCharRef.toString()); + PrintUtil.fprintf_td(System.err, "Command has no write property: %s\n", cmdCharRef.toString()); } cmdCharRef = null; return HCIStatusCode.NOT_SUPPORTED; @@ -136,7 +139,7 @@ public class BTGattCmd implements AutoCloseable : dev.findGattChar(rsp_uuid); if( null == rspCharRef ) { if( verbose ) { - BTUtils.fprintf_td(System.err, "Response not found: service %s, char %s\n", service_uuid, rsp_uuid); + PrintUtil.fprintf_td(System.err, "Response not found: service %s, char %s\n", service_uuid, rsp_uuid); } cmdCharRef = null; return HCIStatusCode.NOT_SUPPORTED; @@ -147,14 +150,14 @@ public class BTGattCmd implements AutoCloseable return HCIStatusCode.SUCCESS; } else { if( verbose ) { - BTUtils.fprintf_td(System.err, "CCCD Notify/Indicate not supported on response %s\n", rspCharRef.toString()); + PrintUtil.fprintf_td(System.err, "CCCD Notify/Indicate not supported on response %s\n", rspCharRef.toString()); } cmdCharRef = null; rspCharRef = null; return HCIStatusCode.NOT_SUPPORTED; } } catch ( final Exception e ) { - BTUtils.fprintf_td(System.err, "Exception caught for %s: %s\n", e.toString(), toString()); + PrintUtil.fprintf_td(System.err, "Exception caught for %s: %s\n", e.toString(), toString()); cmdCharRef = null; rspCharRef = null; return HCIStatusCode.TIMEOUT; @@ -206,7 +209,7 @@ public class BTGattCmd implements AutoCloseable return HCIStatusCode.FAILED; } } catch (final Exception e ) { - BTUtils.fprintf_td(System.err, "Exception caught for %s: %s\n", e.toString(), toString()); + PrintUtil.fprintf_td(System.err, "Exception caught for %s: %s\n", e.toString(), toString()); return HCIStatusCode.TIMEOUT; } } else { @@ -293,7 +296,7 @@ public class BTGattCmd implements AutoCloseable public byte[] getResponse() { return rsp_data; } private String rspDataToString() { - return null == rsp_data ? "null" : BTUtils.bytesHexString(rsp_data, 0, rsp_data.length, true /* lsbFirst */); + return null == rsp_data ? "null" : BasicTypes.bytesHexString(rsp_data, 0, rsp_data.length, true /* lsbFirst */); } /** @@ -338,7 +341,7 @@ public class BTGattCmd implements AutoCloseable rsp_data = null; if( DEBUG ) { - BTUtils.fprintf_td(System.err, "BTGattCmd.sendBlocking: Start: Cmd %s, args[%s], Resp %s, result[%s]", + PrintUtil.fprintf_td(System.err, "BTGattCmd.sendBlocking: Start: Cmd %s, args[%s], Resp %s, result[%s]", cmdCharRef.toString(), cmd_data.toString(), rspCharStr(), rspDataToString()); } @@ -351,29 +354,29 @@ public class BTGattCmd implements AutoCloseable if( prefWriteNoAck ) { try { if( !cmdCharRef.writeValue(cmd_data, false /* withResponse */) ) { - BTUtils.fprintf_td(System.err, "Write (noAck) to command failed: Cmd %s, args[%s]\n", - cmdCharRef.toString(), BTUtils.bytesHexString(cmd_data, 0, cmd_data.length, true /* lsbFirst */)); + PrintUtil.fprintf_td(System.err, "Write (noAck) to command failed: Cmd %s, args[%s]\n", + cmdCharRef.toString(), BasicTypes.bytesHexString(cmd_data, 0, cmd_data.length, true /* lsbFirst */)); res = HCIStatusCode.FAILED; } } catch ( final Throwable t ) { - BTUtils.fprintf_td(System.err, "Exception caught @ Write (noAck) to command failed: Cmd %s, args[%s]: %s\n", - cmdCharRef.toString(), BTUtils.bytesHexString(cmd_data, 0, cmd_data.length, true /* lsbFirst */), t.toString()); + PrintUtil.fprintf_td(System.err, "Exception caught @ Write (noAck) to command failed: Cmd %s, args[%s]: %s\n", + cmdCharRef.toString(), BasicTypes.bytesHexString(cmd_data, 0, cmd_data.length, true /* lsbFirst */), t.toString()); res = HCIStatusCode.TIMEOUT; } } else if( hasWriteWithAck ) { try { if( !cmdCharRef.writeValue(cmd_data, true /* withResponse */) ) { - BTUtils.fprintf_td(System.err, "Write (withAck) to command failed: Cmd %s, args[%s]\n", - cmdCharRef.toString(), BTUtils.bytesHexString(cmd_data, 0, cmd_data.length, true /* lsbFirst */)); + PrintUtil.fprintf_td(System.err, "Write (withAck) to command failed: Cmd %s, args[%s]\n", + cmdCharRef.toString(), BasicTypes.bytesHexString(cmd_data, 0, cmd_data.length, true /* lsbFirst */)); res = HCIStatusCode.TIMEOUT; } } catch ( final Throwable t ) { - BTUtils.fprintf_td(System.err, "Exception caught @ Write (withAck) to command failed: Cmd %s, args[%s]: %s\n", - cmdCharRef.toString(), BTUtils.bytesHexString(cmd_data, 0, cmd_data.length, true /* lsbFirst */), t.toString()); + PrintUtil.fprintf_td(System.err, "Exception caught @ Write (withAck) to command failed: Cmd %s, args[%s]: %s\n", + cmdCharRef.toString(), BasicTypes.bytesHexString(cmd_data, 0, cmd_data.length, true /* lsbFirst */), t.toString()); res = HCIStatusCode.TIMEOUT; } } else { - BTUtils.fprintf_td(System.err, "Command has no write property: %s\n", cmdCharRef.toString()); + PrintUtil.fprintf_td(System.err, "Command has no write property: %s\n", cmdCharRef.toString()); res = HCIStatusCode.FAILED; } @@ -388,8 +391,8 @@ public class BTGattCmd implements AutoCloseable mtxRspReceived.wait(timeoutMS); } catch (final Throwable t) {} if( null == rsp_data ) { - BTUtils.fprintf_td(System.err, "BTGattCmd.sendBlocking: Timeout: Cmd %s, args[%s]\n", - cmdCharRef.toString(), BTUtils.bytesHexString(cmd_data, 0, cmd_data.length, true /* lsbFirst */)); + PrintUtil.fprintf_td(System.err, "BTGattCmd.sendBlocking: Timeout: Cmd %s, args[%s]\n", + cmdCharRef.toString(), BasicTypes.bytesHexString(cmd_data, 0, cmd_data.length, true /* lsbFirst */)); res = HCIStatusCode.TIMEOUT; } } @@ -397,8 +400,8 @@ public class BTGattCmd implements AutoCloseable } } // mtxRspReceived if( DEBUG && HCIStatusCode.SUCCESS == res ) { - BTUtils.fprintf_td(System.err, "BTGattCmd.sendBlocking: OK: Cmd %s, args[%s], Resp %s, result[%s]\n", - cmdCharRef.toString(), BTUtils.bytesHexString(cmd_data, 0, cmd_data.length, true /* lsbFirst */), + PrintUtil.fprintf_td(System.err, "BTGattCmd.sendBlocking: OK: Cmd %s, args[%s], Resp %s, result[%s]\n", + cmdCharRef.toString(), BasicTypes.bytesHexString(cmd_data, 0, cmd_data.length, true /* lsbFirst */), rspCharStr(), rspDataToString()); } return res; diff --git a/java/org/direct_bt/BTUtils.java b/java/org/direct_bt/BTUtils.java index d8a74418..cdf60009 100644 --- a/java/org/direct_bt/BTUtils.java +++ b/java/org/direct_bt/BTUtils.java @@ -24,9 +24,7 @@ */ package org.direct_bt; -import java.io.PrintStream; - -import org.jau.util.BasicTypes; +import java.nio.charset.StandardCharsets; public class BTUtils { /** @@ -47,65 +45,6 @@ public class BTUtils { } } - private static long t0; - static { - t0 = startupTimeMillisImpl(); - } - private static native long startupTimeMillisImpl(); - - /** - * Returns current monotonic time in milliseconds. - */ - public static native long currentTimeMillis(); - - /** - * Returns current wall-clock system `time of day` in seconds since Unix Epoch - * `00:00:00 UTC on 1 January 1970`. - */ - public static native long wallClockSeconds(); - - /** - * Returns the startup time in monotonic time in milliseconds of the native module. - */ - public static long startupTimeMillis() { return t0; } - - /** - * Returns current elapsed monotonic time in milliseconds since module startup, see {@link #startupTimeMillis()}. - */ - public static long elapsedTimeMillis() { return currentTimeMillis() - t0; } - - /** - * Returns elapsed monotonic time in milliseconds since module startup comparing against the given timestamp, see {@link #startupTimeMillis()}. - */ - public static long elapsedTimeMillis(final long current_ts) { return current_ts - t0; } - - /** - * Convenient {@link PrintStream#printf(String, Object...)} invocation, prepending the {@link #elapsedTimeMillis()} timestamp. - * @param out the output stream - * @param format the format - * @param args the arguments - */ - public static void fprintf_td(final PrintStream out, final String format, final Object ... args) { - out.printf("[%,9d] ", elapsedTimeMillis()); - out.printf(format, args); - } - /** - * Convenient {@link PrintStream#println(String)} invocation, prepending the {@link #elapsedTimeMillis()} timestamp. - * @param out the output stream - * @param msg the string message - */ - public static void println(final PrintStream out, final String msg) { - out.printf("[%,9d] %s%s", elapsedTimeMillis(), msg, System.lineSeparator()); - } - /** - * Convenient {@link PrintStream#print(String)} invocation, prepending the {@link #elapsedTimeMillis()} timestamp. - * @param out the output stream - * @param msg the string message - */ - public static void print(final PrintStream out, final String msg) { - out.printf("[%,9d] %s", elapsedTimeMillis(), msg); - } - /** * Defining the supervising timeout for LE connections to be a multiple of the maximum connection interval as follows: * <pre> @@ -147,63 +86,9 @@ public class BTUtils { } /** - * Converts a given hexadecimal string representation to a byte array. - * - * In case a non valid hexadecimal digit appears in the given string, - * conversion ends and returns the byte array up until the violation. - * - * @param hexstr the hexadecimal string representation - * @param lsbFirst low significant byte first - * @param checkLeading0x if true, checks for a leading `0x` and removes it, otherwise not. - * @return the matching byte array + * Decodes the given consecutive UTF-8 characters within buffer to String. */ - public static byte[] hexStringBytes(final String hexstr, final boolean lsbFirst, final boolean checkLeading0x) { - return BasicTypes.hexStringBytes(hexstr, lsbFirst, checkLeading0x); + public static String decodeUTF8String(final byte[] buffer, final int offset, final int size) { + return new String(buffer, offset, size, StandardCharsets.UTF_8); } - - /** - * Produce a lower-case hexadecimal string representation of the given byte values. - * <p> - * If lsbFirst is true, orders LSB left -> MSB right, usual for byte streams.<br> - * Otherwise orders MSB left -> LSB right, usual for readable integer values. - * </p> - * @param bytes the byte array to represent - * @param offset offset in byte array to the first byte to print. - * @param length number of bytes to print. If negative, will use {@code bytes.length - offset}. - * @param lsbFirst true having the least significant byte printed first (lowest addressed byte to highest), - * otherwise have the most significant byte printed first (highest addressed byte to lowest). - * @return the hex-string representation of the data - */ - public static String bytesHexString(final byte[] bytes, final int offset, final int length, - final boolean lsbFirst) - { - return BasicTypes.bytesHexString(bytes, offset, length, lsbFirst); - } - - /** - * Produce a hexadecimal string representation of the given byte value. - * @param sb the StringBuilder destination to append - * @param value the byte value to represent - * @param lowerCase true to use lower case hex-chars, otherwise capital letters are being used. - * @return the given StringBuilder for chaining - */ - public static StringBuilder byteHexString(final StringBuilder sb, final byte value, final boolean lowerCase) - { - return BasicTypes.byteHexString(sb, value, lowerCase); - } - - /** - * Returns all valid consecutive UTF-8 characters within buffer - * in the range offset -> size or until EOS. - * <p> - * In case a non UTF-8 character has been detected, - * the content will be cut off and the decoding loop ends. - * </p> - * <p> - * Method utilizes a finite state machine detecting variable length UTF-8 codes. - * See <a href="http://bjoern.hoehrmann.de/utf-8/decoder/dfa/">Bjoern Hoehrmann's site</a> for details. - * </p> - */ - public static native String decodeUTF8String(final byte[] buffer, final int offset, final int size); - } diff --git a/java/org/direct_bt/DBGattValue.java b/java/org/direct_bt/DBGattValue.java index e59baeef..fd808733 100644 --- a/java/org/direct_bt/DBGattValue.java +++ b/java/org/direct_bt/DBGattValue.java @@ -25,6 +25,8 @@ package org.direct_bt; +import org.jau.util.BasicTypes; + /** * A copy of the native GATT value of DBGattChar or DBGattDesc. * @@ -142,7 +144,7 @@ public class DBGattValue public String toString() { final String len = hasVariableLength() ? "var" : "fixed"; return "len "+len+", size "+size()+", capacity "+capacity()+", "+ - BTUtils.bytesHexString(value_, 0, size(), true /* lsbFirst */) + + BasicTypes.bytesHexString(value_, 0, size(), true /* lsbFirst */) + " '"+BTUtils.decodeUTF8String(value_, 0, size())+"'"; } } diff --git a/java/org/direct_bt/DirectBTVersion.java b/java/org/direct_bt/DirectBTVersion.java index da1fec4a..c8938598 100644 --- a/java/org/direct_bt/DirectBTVersion.java +++ b/java/org/direct_bt/DirectBTVersion.java @@ -38,6 +38,7 @@ import java.util.jar.Manifest; import java.util.regex.Pattern; import org.jau.base.JaulibVersion; +import org.jau.io.PrintUtil; import org.jau.pkg.TempJarSHASum; import org.jau.sec.SHASum; import org.jau.util.JauVersion; @@ -59,17 +60,17 @@ public class DirectBTVersion extends JauVersion { public static final void printVersionInfo(final PrintStream out) { BTFactory.initDirectBTLibrary(); - BTUtils.println(out, "BTFactory: Jaulib: Available "+BTFactory.JAULIB_AVAILABLE+", JarCache in use "+BTFactory.JAULIB_JARCACHE_USED); + PrintUtil.println(out, "BTFactory: Jaulib: Available "+BTFactory.JAULIB_AVAILABLE+", JarCache in use "+BTFactory.JAULIB_JARCACHE_USED); if( BTFactory.JAULIB_AVAILABLE ) { out.println(VersionUtil.getPlatformInfo()); - BTUtils.println(out, "Version Info:"); + PrintUtil.println(out, "Version Info:"); final DirectBTVersion v = DirectBTVersion.getInstance(); out.println(v.toString()); - BTUtils.println(out, ""); - BTUtils.println(out, "Full Manifest:"); + PrintUtil.println(out, ""); + PrintUtil.println(out, "Full Manifest:"); out.println(v.getFullManifestInfo(null).toString()); } else { - BTUtils.println(out, "Full Manifest:"); + PrintUtil.println(out, "Full Manifest:"); final Manifest manifest = BTFactory.getManifest(BTFactory.class.getClassLoader(), new String[] { "org.direct_bt" } ); final Attributes attr = manifest.getMainAttributes(); final Set<Object> keys = attr.keySet(); @@ -86,8 +87,8 @@ public class DirectBTVersion extends JauVersion { out.println(sb.toString()); } - BTUtils.println(out, "Direct-BT Native Version "+BTFactory.getNativeVersion()+" (API "+BTFactory.getNativeAPIVersion()+")"); - BTUtils.println(out, "Direct-BT Java Version "+BTFactory.getImplVersion()+" (API "+BTFactory.getAPIVersion()+")"); + PrintUtil.println(out, "Direct-BT Native Version "+BTFactory.getNativeVersion()+" (API "+BTFactory.getNativeAPIVersion()+")"); + PrintUtil.println(out, "Direct-BT Java Version "+BTFactory.getImplVersion()+" (API "+BTFactory.getAPIVersion()+")"); } protected DirectBTVersion(final String packageName, final Manifest mf) { diff --git a/java/org/direct_bt/SMPIdentityResolvingKey.java b/java/org/direct_bt/SMPIdentityResolvingKey.java index 180f7c8c..ee5bbed9 100644 --- a/java/org/direct_bt/SMPIdentityResolvingKey.java +++ b/java/org/direct_bt/SMPIdentityResolvingKey.java @@ -25,6 +25,8 @@ package org.direct_bt; +import org.jau.util.BasicTypes; + /** * SMP Identity Resolving Key, used for platform agnostic persistence. * <p> @@ -179,7 +181,7 @@ public class SMPIdentityResolvingKey { @Override public String toString() { // hex-fmt aligned with btmon return "IRK[props "+properties.toString()+ - ", irk "+BTUtils.bytesHexString(irk, 0, -1, true /* lsbFirst */)+ + ", irk "+BasicTypes.bytesHexString(irk, 0, -1, true /* lsbFirst */)+ "]"; } diff --git a/java/org/direct_bt/SMPKeyBin.java b/java/org/direct_bt/SMPKeyBin.java index a76e79f9..9503cd43 100644 --- a/java/org/direct_bt/SMPKeyBin.java +++ b/java/org/direct_bt/SMPKeyBin.java @@ -35,7 +35,9 @@ import java.text.SimpleDateFormat; import java.util.Date; import org.direct_bt.SMPKeyMask.KeyType; +import org.jau.io.PrintUtil; import org.jau.net.EUI48; +import org.jau.sys.Clock; /** * Storage for SMP keys including required connection parameter per local adapter and remote device. @@ -232,7 +234,7 @@ public class SMPKeyBin { return smpKeyBin.write( path, overwrite ); } else { if( verbose_ ) { - BTUtils.println(System.err, "Create SMPKeyBin: Invalid "+smpKeyBin+", "+device); + PrintUtil.println(System.err, "Create SMPKeyBin: Invalid "+smpKeyBin+", "+device); } return false; } @@ -287,7 +289,7 @@ public class SMPKeyBin { { version = VERSION; this.size = 0; - this.ts_creation_sec = BTUtils.wallClockSeconds(); + this.ts_creation_sec = Clock.wallClockSeconds(); this.localAddress = localAddress_; this.remoteAddress = remoteAddress_; this.sec_level = sec_level_; @@ -533,7 +535,7 @@ public class SMPKeyBin { try { return file.delete(); // alternative to truncate, if existing } catch (final Exception ex) { - BTUtils.println(System.err, "Remove SMPKeyBin: Failed "+fname+": "+ex.getMessage()); + PrintUtil.println(System.err, "Remove SMPKeyBin: Failed "+fname+": "+ex.getMessage()); ex.printStackTrace(); return false; } @@ -550,7 +552,7 @@ public class SMPKeyBin { final public boolean write(final String path, final boolean overwrite) { if( !isValid() ) { - BTUtils.println(System.err, "Write SMPKeyBin: Invalid (skipped) "+toString()); + PrintUtil.println(System.err, "Write SMPKeyBin: Invalid (skipped) "+toString()); return false; } final String fname = getFilename(path); @@ -560,11 +562,11 @@ public class SMPKeyBin { if( file.exists() ) { if( overwrite ) { if( !file.delete() ) { - BTUtils.println(System.err, "Write SMPKeyBin: Failed deletion of existing file "+fname+": "+toString()); + PrintUtil.println(System.err, "Write SMPKeyBin: Failed deletion of existing file "+fname+": "+toString()); return false; } } else { - BTUtils.println(System.err, "Write SMPKeyBin: Not overwriting existing file "+fname+": "+toString()); + PrintUtil.println(System.err, "Write SMPKeyBin: Not overwriting existing file "+fname+": "+toString()); return false; } } @@ -628,11 +630,11 @@ public class SMPKeyBin { } if( verbose ) { - BTUtils.println(System.err, "Write SMPKeyBin: "+fname+": "+toString()); + PrintUtil.println(System.err, "Write SMPKeyBin: "+fname+": "+toString()); } return true; } catch (final Exception ex) { - BTUtils.println(System.err, "Write SMPKeyBin: Failed "+fname+": "+toString()+": "+ex.getMessage()); + PrintUtil.println(System.err, "Write SMPKeyBin: Failed "+fname+": "+toString()+": "+ex.getMessage()); ex.printStackTrace(); } finally { try { @@ -654,7 +656,7 @@ public class SMPKeyBin { try { if( !file.canRead() ) { if( verbose ) { - BTUtils.println(System.err, "Read SMPKeyBin: Failed "+fname+": Not existing or readable: "+toString()); + PrintUtil.println(System.err, "Read SMPKeyBin: Failed "+fname+": Not existing or readable: "+toString()); } size = 0; // explicitly mark invalid return false; @@ -769,7 +771,7 @@ public class SMPKeyBin { err = !isValid(); } } catch (final Exception ex) { - BTUtils.println(System.err, "Read SMPKeyBin: Failed "+fname+": "+toString()+": "+ex.getMessage()); + PrintUtil.println(System.err, "Read SMPKeyBin: Failed "+fname+": "+toString()+": "+ex.getMessage()); ex.printStackTrace(); err = true; } finally { @@ -784,12 +786,12 @@ public class SMPKeyBin { if( err ) { file.delete(); if( verbose ) { - BTUtils.println(System.err, "Read SMPKeyBin: Failed "+fname+" (removed): "+toString()+", remaining "+remaining); + PrintUtil.println(System.err, "Read SMPKeyBin: Failed "+fname+" (removed): "+toString()+", remaining "+remaining); } size = 0; // explicitly mark invalid } else { if( verbose ) { - BTUtils.println(System.err, "Read SMPKeyBin: OK "+fname+": "+toString()+", remaining "+remaining); + PrintUtil.println(System.err, "Read SMPKeyBin: OK "+fname+": "+toString()+", remaining "+remaining); } } return err; diff --git a/java/org/direct_bt/SMPLinkKey.java b/java/org/direct_bt/SMPLinkKey.java index 2392b6fe..88832b4f 100644 --- a/java/org/direct_bt/SMPLinkKey.java +++ b/java/org/direct_bt/SMPLinkKey.java @@ -25,6 +25,7 @@ package org.direct_bt; +import org.jau.util.BasicTypes; /** * Local SMP Link Key, used for platform agnostic persistence, @@ -186,7 +187,7 @@ public class SMPLinkKey { @Override public String toString() { // hex-fmt aligned with btmon return "LK[res "+responder+", type "+type.toString()+ - ", key "+BTUtils.bytesHexString(key, 0, -1, true /* lsbFirst */)+ + ", key "+BasicTypes.bytesHexString(key, 0, -1, true /* lsbFirst */)+ ", plen "+pin_length+ "]"; } diff --git a/java/org/direct_bt/SMPLongTermKey.java b/java/org/direct_bt/SMPLongTermKey.java index b68dd11e..06bc709f 100644 --- a/java/org/direct_bt/SMPLongTermKey.java +++ b/java/org/direct_bt/SMPLongTermKey.java @@ -25,6 +25,8 @@ package org.direct_bt; +import org.jau.util.BasicTypes; + /** * SMP Long Term Key, used for platform agnostic persistence. * <p> @@ -207,9 +209,9 @@ public class SMPLongTermKey { @Override public String toString() { // hex-fmt aligned with btmon return "LTK[props "+properties.toString()+", enc_size "+enc_size+ - ", ediv "+BTUtils.bytesHexString(ediv, 0, -1, false /* lsbFirst */)+ - ", rand "+BTUtils.bytesHexString(rand, 0, -1, false /* lsbFirst */)+ - ", ltk "+BTUtils.bytesHexString(ltk, 0, -1, true /* lsbFirst */)+ + ", ediv "+BasicTypes.bytesHexString(ediv, 0, -1, false /* lsbFirst */)+ + ", rand "+BasicTypes.bytesHexString(rand, 0, -1, false /* lsbFirst */)+ + ", ltk "+BasicTypes.bytesHexString(ltk, 0, -1, true /* lsbFirst */)+ ", valid "+isValid()+ "]"; } diff --git a/java/org/direct_bt/SMPSignatureResolvingKey.java b/java/org/direct_bt/SMPSignatureResolvingKey.java index 747e12f5..358c71ce 100644 --- a/java/org/direct_bt/SMPSignatureResolvingKey.java +++ b/java/org/direct_bt/SMPSignatureResolvingKey.java @@ -25,6 +25,8 @@ package org.direct_bt; +import org.jau.util.BasicTypes; + /** * SMP Signature Resolving Key, used for platform agnostic persistence. * <p> @@ -179,7 +181,7 @@ public class SMPSignatureResolvingKey { @Override public String toString() { // hex-fmt aligned with btmon return "CSRK[props "+properties.toString()+ - ", csrk "+BTUtils.bytesHexString(csrk, 0, -1, true /* lsbFirst */)+ + ", csrk "+BasicTypes.bytesHexString(csrk, 0, -1, true /* lsbFirst */)+ "]"; } diff --git a/test/java/test/org/direct_bt/TestBringup00.java b/test/java/test/org/direct_bt/TestBringup00.java index 84a93211..b9b7ba71 100644 --- a/test/java/test/org/direct_bt/TestBringup00.java +++ b/test/java/test/org/direct_bt/TestBringup00.java @@ -34,8 +34,8 @@ import org.direct_bt.BTDeviceRegistry; import org.direct_bt.BTException; import org.direct_bt.BTFactory; import org.direct_bt.BTManager; -import org.direct_bt.BTUtils; import org.direct_bt.DirectBTVersion; +import org.jau.io.PrintUtil; import org.junit.Assert; import org.junit.FixMethodOrder; import org.junit.Test; @@ -61,7 +61,7 @@ public class TestBringup00 extends SingletonJunitCase { | IllegalAccessException | IllegalArgumentException | InvocationTargetException | ClassNotFoundException e) { e.printStackTrace(); - BTUtils.println(System.err, "Unable to instantiate Direct-BT BluetoothManager: "+e.getMessage()); + PrintUtil.println(System.err, "Unable to instantiate Direct-BT BluetoothManager: "+e.getMessage()); e.printStackTrace(); } if( null != manager ) { @@ -106,9 +106,9 @@ public class TestBringup00 extends SingletonJunitCase { return; } final List<BTAdapter> adapters = manager.getAdapters(); - BTUtils.println(System.err, "Adapter: Count "+adapters.size()); + PrintUtil.println(System.err, "Adapter: Count "+adapters.size()); for(int i=0; i<adapters.size(); i++) { - BTUtils.println(System.err, i+": "+adapters.get(i).toString()); + PrintUtil.println(System.err, i+": "+adapters.get(i).toString()); } for(final BTAdapter a : adapters) { // test runs w/o elevated permissions diff --git a/trial/java/trial/org/direct_bt/BaseDBTClientServer.java b/trial/java/trial/org/direct_bt/BaseDBTClientServer.java index ea69e475..a652f47d 100644 --- a/trial/java/trial/org/direct_bt/BaseDBTClientServer.java +++ b/trial/java/trial/org/direct_bt/BaseDBTClientServer.java @@ -34,7 +34,7 @@ import org.direct_bt.BTException; import org.direct_bt.BTFactory; import org.direct_bt.BTManager; import org.direct_bt.BTSecurityRegistry; -import org.direct_bt.BTUtils; +import org.jau.io.PrintUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; @@ -61,7 +61,7 @@ public abstract class BaseDBTClientServer extends SingletonJunitCase { BTFactory.initDirectBTLibrary(); final Class<?> ThisClazz = MethodHandles.lookup().lookupClass(); - BTUtils.println(System.err, "++++ Test "+ThisClazz.getSimpleName()+".setupAll()"); + PrintUtil.println(System.err, "++++ Test "+ThisClazz.getSimpleName()+".setupAll()"); Assert.assertTrue( DBTUtils.rmKeyFolder() ); Assert.assertTrue( DBTUtils.mkdirKeyFolder() ); @@ -75,7 +75,7 @@ public abstract class BaseDBTClientServer extends SingletonJunitCase { @AfterClass public static final void cleanupAll() { final Class<?> ThisClazz = MethodHandles.lookup().lookupClass(); - BTUtils.println(System.err, "++++ Test "+ThisClazz.getSimpleName()+".cleanupAll()"); + PrintUtil.println(System.err, "++++ Test "+ThisClazz.getSimpleName()+".cleanupAll()"); BTManager manager = null; try { @@ -84,7 +84,7 @@ public abstract class BaseDBTClientServer extends SingletonJunitCase { | IllegalAccessException | IllegalArgumentException | InvocationTargetException | ClassNotFoundException e) { e.printStackTrace(); - BTUtils.println(System.err, "Unable to instantiate Direct-BT BluetoothManager: "+e.getMessage()); + PrintUtil.println(System.err, "Unable to instantiate Direct-BT BluetoothManager: "+e.getMessage()); e.printStackTrace(); } if( null != manager ) { @@ -107,7 +107,7 @@ public abstract class BaseDBTClientServer extends SingletonJunitCase { | IllegalAccessException | IllegalArgumentException | InvocationTargetException | ClassNotFoundException e) { e.printStackTrace(); - BTUtils.println(System.err, "Unable to instantiate Direct-BT BluetoothManager: "+e.getMessage()); + PrintUtil.println(System.err, "Unable to instantiate Direct-BT BluetoothManager: "+e.getMessage()); e.printStackTrace(); } if( null != manager ) { @@ -132,7 +132,7 @@ public abstract class BaseDBTClientServer extends SingletonJunitCase { @Before public final void setupTest() { final Class<?> ThisClazz = MethodHandles.lookup().lookupClass(); - BTUtils.println(System.err, "++++ Test "+ThisClazz.getSimpleName()+".setupTest()"); + PrintUtil.println(System.err, "++++ Test "+ThisClazz.getSimpleName()+".setupTest()"); resetStates(); } @@ -147,7 +147,7 @@ public abstract class BaseDBTClientServer extends SingletonJunitCase { @After public final void cleanupTest() { final Class<?> ThisClazz = MethodHandles.lookup().lookupClass(); - BTUtils.println(System.err, "++++ Test "+ThisClazz.getSimpleName()+".cleanupTest()"); + PrintUtil.println(System.err, "++++ Test "+ThisClazz.getSimpleName()+".cleanupTest()"); resetStates(); } diff --git a/trial/java/trial/org/direct_bt/DBTClient01.java b/trial/java/trial/org/direct_bt/DBTClient01.java index b7ac4b0f..c10d6450 100644 --- a/trial/java/trial/org/direct_bt/DBTClient01.java +++ b/trial/java/trial/org/direct_bt/DBTClient01.java @@ -56,7 +56,10 @@ import org.direct_bt.SMPIOCapability; import org.direct_bt.SMPKeyBin; import org.direct_bt.SMPPairingState; import org.direct_bt.ScanType; +import org.jau.io.PrintUtil; import org.jau.net.EUI48; +import org.jau.sys.Clock; +import org.jau.util.BasicTypes; import org.junit.Assert; /** @@ -65,7 +68,7 @@ import org.junit.Assert; public class DBTClient01 implements DBTClientTest { private final boolean GATT_VERBOSE = false; - private final long timestamp_t0 = BTUtils.startupTimeMillis(); + private final long timestamp_t0 = Clock.startupTimeMillis(); private final String adapterShortName = "TDev2Clt"; @@ -169,17 +172,17 @@ public class DBTClient01 implements DBTClientTest { final AdapterSettings newmask, final AdapterSettings changedmask, final long timestamp) { final boolean initialSetting = oldmask.isEmpty(); if( initialSetting ) { - BTUtils.println(System.err, "****** Client SETTINGS: "+oldmask+" -> "+newmask+", initial "+changedmask); + PrintUtil.println(System.err, "****** Client SETTINGS: "+oldmask+" -> "+newmask+", initial "+changedmask); } else { - BTUtils.println(System.err, "****** Client SETTINGS: "+oldmask+" -> "+newmask+", changed "+changedmask); + PrintUtil.println(System.err, "****** Client SETTINGS: "+oldmask+" -> "+newmask+", changed "+changedmask); } - BTUtils.println(System.err, "Client Status Adapter:"); - BTUtils.println(System.err, adapter.toString()); + PrintUtil.println(System.err, "Client Status Adapter:"); + PrintUtil.println(System.err, adapter.toString()); } @Override public void discoveringChanged(final BTAdapter adapter, final ScanType currentMeta, final ScanType changedType, final boolean changedEnabled, final DiscoveryPolicy policy, final long timestamp) { - BTUtils.println(System.err, "****** Client DISCOVERING: meta "+currentMeta+", changed["+changedType+", enabled "+changedEnabled+", policy "+policy+"] on "+adapter); + PrintUtil.println(System.err, "****** Client DISCOVERING: meta "+currentMeta+", changed["+changedType+", enabled "+changedEnabled+", policy "+policy+"] on "+adapter); } @Override @@ -188,16 +191,16 @@ public class DBTClient01 implements DBTClientTest { 0 < measurementsLeft.get() ) { - BTUtils.println(System.err, "****** Client FOUND__-0: Connecting "+device.toString()); + PrintUtil.println(System.err, "****** Client FOUND__-0: Connecting "+device.toString()); { - final long td = BTUtils.currentTimeMillis() - timestamp_t0; // adapter-init -> now - BTUtils.println(System.err, "PERF: adapter-init -> FOUND__-0 " + td + " ms"); + final long td = Clock.currentTimeMillis() - timestamp_t0; // adapter-init -> now + PrintUtil.println(System.err, "PERF: adapter-init -> FOUND__-0 " + td + " ms"); } executeOffThread( () -> { connectDiscoveredDevice(device); }, "Client DBT-Connect-"+device.getAddressAndType(), true /* detach */); return true; } else { - BTUtils.println(System.err, "****** Client FOUND__-1: NOP "+device.toString()); + PrintUtil.println(System.err, "****** Client FOUND__-1: NOP "+device.toString()); return false; } } @@ -208,19 +211,19 @@ public class DBTClient01 implements DBTClientTest { @Override public void deviceConnected(final BTDevice device, final boolean discovered, final long timestamp) { - BTUtils.println(System.err, "****** Client CONNECTED (discovered "+discovered+"): "+device.toString()); + PrintUtil.println(System.err, "****** Client CONNECTED (discovered "+discovered+"): "+device.toString()); } @Override public void devicePairingState(final BTDevice device, final SMPPairingState state, final PairingMode mode, final long timestamp) { - BTUtils.println(System.err, "****** Client PAIRING_STATE: state "+state+", mode "+mode+": "+device); + PrintUtil.println(System.err, "****** Client PAIRING_STATE: state "+state+", mode "+mode+": "+device); switch( state ) { case NONE: // next: deviceReady(..) break; case FAILED: { final boolean res = SMPKeyBin.remove(DBTConstants.CLIENT_KEY_PATH, device); - BTUtils.println(System.err, "****** Client PAIRING_STATE: state "+state+"; Remove key file "+SMPKeyBin.getFilename(DBTConstants.CLIENT_KEY_PATH, device)+", res "+res); + PrintUtil.println(System.err, "****** Client PAIRING_STATE: state "+state+"; Remove key file "+SMPKeyBin.getFilename(DBTConstants.CLIENT_KEY_PATH, device)+", res "+res); // next: deviceReady() or deviceDisconnected(..) } break; case REQUESTED_BY_RESPONDER: @@ -274,7 +277,7 @@ public class DBTClient01 implements DBTClientTest { Thread.sleep(sleep_dur); // wait a little (FIXME: Fast restart of advertising error) } catch (final InterruptedException e) { } - BTUtils.fprintf_td(System.err, "****** Client i470 disconnectDevice(delayed %d ms): client %s\n", sleep_dur, device.toString()); + PrintUtil.fprintf_td(System.err, "****** Client i470 disconnectDevice(delayed %d ms): client %s\n", sleep_dur, device.toString()); device.disconnect(); } @@ -282,10 +285,10 @@ public class DBTClient01 implements DBTClientTest { public void deviceReady(final BTDevice device, final long timestamp) { { deviceReadyCount.incrementAndGet(); - BTUtils.println(System.err, "****** Client READY-0: Processing["+deviceReadyCount.get()+"] "+device.toString()); + PrintUtil.println(System.err, "****** Client READY-0: Processing["+deviceReadyCount.get()+"] "+device.toString()); { - final long td = BTUtils.currentTimeMillis() - timestamp_t0; // adapter-init -> now - BTUtils.println(System.err, "PERF: adapter-init -> READY-0 " + td + " ms"); + final long td = Clock.currentTimeMillis() - timestamp_t0; // adapter-init -> now + PrintUtil.println(System.err, "PERF: adapter-init -> READY-0 " + td + " ms"); } // Be nice to Test* case, allowing to reach its own listener.deviceReady() added later @@ -302,7 +305,7 @@ public class DBTClient01 implements DBTClientTest { @Override public void deviceDisconnected(final BTDevice device, final HCIStatusCode reason, final short handle, final long timestamp) { - BTUtils.println(System.err, "****** Client DISCONNECTED: Reason "+reason+", old handle 0x"+Integer.toHexString(handle)+": "+device+" on "+device.getAdapter()); + PrintUtil.println(System.err, "****** Client DISCONNECTED: Reason "+reason+", old handle 0x"+Integer.toHexString(handle)+": "+device+" on "+device.getAdapter()); disconnectCount.addAndGet(1); @@ -320,12 +323,12 @@ public class DBTClient01 implements DBTClientTest { public void notificationReceived(final BTGattChar charDecl, final byte[] value, final long timestamp) { if( GATT_VERBOSE ) { - final long tR = BTUtils.currentTimeMillis(); - BTUtils.fprintf_td(System.err, "** Characteristic-Notify: UUID %s, td %d ******\n", + final long tR = Clock.currentTimeMillis(); + PrintUtil.fprintf_td(System.err, "** Characteristic-Notify: UUID %s, td %d ******\n", charDecl.getUUID(), (tR-timestamp)); - BTUtils.fprintf_td(System.err, "** Characteristic: %s ******\n", charDecl.toString()); - BTUtils.fprintf_td(System.err, "** Value R: size %d, ro: %s ******\n", value.length, BTUtils.bytesHexString(value, 0, -1, true)); - BTUtils.fprintf_td(System.err, "** Value S: %s ******\n", BTUtils.decodeUTF8String(value, 0, value.length)); + PrintUtil.fprintf_td(System.err, "** Characteristic: %s ******\n", charDecl.toString()); + PrintUtil.fprintf_td(System.err, "** Value R: size %d, ro: %s ******\n", value.length, BasicTypes.bytesHexString(value, 0, -1, true)); + PrintUtil.fprintf_td(System.err, "** Value S: %s ******\n", BTUtils.decodeUTF8String(value, 0, value.length)); } notificationsReceived.incrementAndGet(); } @@ -334,12 +337,12 @@ public class DBTClient01 implements DBTClientTest { public void indicationReceived(final BTGattChar charDecl, final byte[] value, final long timestamp, final boolean confirmationSent) { if( GATT_VERBOSE ) { - final long tR = BTUtils.currentTimeMillis(); - BTUtils.fprintf_td(System.err, "** Characteristic-Indication: UUID %s, td %d, confirmed %b ******\n", + final long tR = Clock.currentTimeMillis(); + PrintUtil.fprintf_td(System.err, "** Characteristic-Indication: UUID %s, td %d, confirmed %b ******\n", charDecl.getUUID(), (tR-timestamp), confirmationSent); - BTUtils.fprintf_td(System.err, "** Characteristic: %s ******\n", charDecl.toString()); - BTUtils.fprintf_td(System.err, "** Value R: size %d, ro: %s ******\n", value.length, BTUtils.bytesHexString(value, 0, -1, true)); - BTUtils.fprintf_td(System.err, "** Value S: %s ******\n", BTUtils.decodeUTF8String(value, 0, value.length)); + PrintUtil.fprintf_td(System.err, "** Characteristic: %s ******\n", charDecl.toString()); + PrintUtil.fprintf_td(System.err, "** Value R: size %d, ro: %s ******\n", value.length, BasicTypes.bytesHexString(value, 0, -1, true)); + PrintUtil.fprintf_td(System.err, "** Value S: %s ******\n", BTUtils.decodeUTF8String(value, 0, value.length)); } indicationsReceived.incrementAndGet(); } @@ -352,40 +355,40 @@ public class DBTClient01 implements DBTClientTest { } private void connectDiscoveredDevice(final BTDevice device) { - BTUtils.println(System.err, "****** Client Connecting Device: Start " + device.toString()); + PrintUtil.println(System.err, "****** Client Connecting Device: Start " + device.toString()); resetLastProcessingStats(); final BTSecurityRegistry.Entry sec = BTSecurityRegistry.getStartOf(device.getAddressAndType().address, device.getName()); if( null != sec ) { - BTUtils.println(System.err, "****** Client Connecting Device: Found SecurityDetail "+sec.toString()+" for "+device.toString()); + PrintUtil.println(System.err, "****** Client Connecting Device: Found SecurityDetail "+sec.toString()+" for "+device.toString()); } else { - BTUtils.println(System.err, "****** Client Connecting Device: No SecurityDetail for "+device.toString()); + PrintUtil.println(System.err, "****** Client Connecting Device: No SecurityDetail for "+device.toString()); } final BTSecurityLevel req_sec_level = null != sec ? sec.getSecLevel() : BTSecurityLevel.UNSET; HCIStatusCode res = device.uploadKeys(DBTConstants.CLIENT_KEY_PATH, req_sec_level, true /* verbose_ */); - BTUtils.fprintf_td(System.err, "****** Client Connecting Device: BTDevice::uploadKeys(...) result %s\n", res.toString()); + PrintUtil.fprintf_td(System.err, "****** Client Connecting Device: BTDevice::uploadKeys(...) result %s\n", res.toString()); if( HCIStatusCode.SUCCESS != res ) { if( null != sec ) { if( sec.isSecurityAutoEnabled() ) { final boolean r = device.setConnSecurityAuto( sec.getSecurityAutoIOCap() ); - BTUtils.println(System.err, "****** Client Connecting Device: Using SecurityDetail.SEC AUTO "+sec+" -> set OK "+r); + PrintUtil.println(System.err, "****** Client Connecting Device: Using SecurityDetail.SEC AUTO "+sec+" -> set OK "+r); } else if( sec.isSecLevelOrIOCapSet() ) { final boolean r = device.setConnSecurity(sec.getSecLevel(), sec.getIOCap()); - BTUtils.println(System.err, "****** Client Connecting Device: Using SecurityDetail.Level+IOCap "+sec+" -> set OK "+r); + PrintUtil.println(System.err, "****** Client Connecting Device: Using SecurityDetail.Level+IOCap "+sec+" -> set OK "+r); } else { final boolean r = device.setConnSecurityAuto( SMPIOCapability.KEYBOARD_ONLY ); - BTUtils.println(System.err, "****** Client Connecting Device: Setting SEC AUTO security detail w/ KEYBOARD_ONLY ("+sec+") -> set OK "+r); + PrintUtil.println(System.err, "****** Client Connecting Device: Setting SEC AUTO security detail w/ KEYBOARD_ONLY ("+sec+") -> set OK "+r); } } else { final boolean r = device.setConnSecurityAuto( SMPIOCapability.KEYBOARD_ONLY ); - BTUtils.println(System.err, "****** Client Connecting Device: Setting SEC AUTO security detail w/ KEYBOARD_ONLY -> set OK "+r); + PrintUtil.println(System.err, "****** Client Connecting Device: Setting SEC AUTO security detail w/ KEYBOARD_ONLY -> set OK "+r); } } final EInfoReport eir = device.getEIR(); - BTUtils.println(System.err, "Client EIR-1 "+device.getEIRInd().toString()); - BTUtils.println(System.err, "Client EIR-2 "+device.getEIRScanRsp().toString()); - BTUtils.println(System.err, "Client EIR-+ "+eir.toString()); + PrintUtil.println(System.err, "Client EIR-1 "+device.getEIRInd().toString()); + PrintUtil.println(System.err, "Client EIR-2 "+device.getEIRScanRsp().toString()); + PrintUtil.println(System.err, "Client EIR-+ "+eir.toString()); short conn_interval_min = (short)8; // 10ms short conn_interval_max = (short)12; // 15ms @@ -399,15 +402,15 @@ public class DBTClient01 implements DBTClientTest { final short supervision_timeout = BTUtils.getHCIConnSupervisorTimeout(conn_latency, (int) ( conn_interval_max * 1.25 ) /* ms */); res = device.connectLE(le_scan_interval, le_scan_window, conn_interval_min, conn_interval_max, conn_latency, supervision_timeout); // res = device.connectDefault(); - BTUtils.println(System.err, "****** Client Connecting Device Command, res "+res+": End result "+res+" of " + device.toString()); + PrintUtil.println(System.err, "****** Client Connecting Device Command, res "+res+": End result "+res+" of " + device.toString()); } private void processReadyDevice(final BTDevice device) { - BTUtils.println(System.err, "****** Client Processing Ready Device: Start " + device.toString()); - final long t1 = BTUtils.currentTimeMillis(); + PrintUtil.println(System.err, "****** Client Processing Ready Device: Start " + device.toString()); + final long t1 = Clock.currentTimeMillis(); SMPKeyBin.createAndWrite(device, DBTConstants.CLIENT_KEY_PATH, true /* verbose */); - final long t2 = BTUtils.currentTimeMillis(); + final long t2 = Clock.currentTimeMillis(); boolean success = false; @@ -415,10 +418,10 @@ public class DBTClient01 implements DBTClientTest { final LE_PHYs resTx[] = { new LE_PHYs() }; final LE_PHYs resRx[] = { new LE_PHYs() }; final HCIStatusCode res = device.getConnectedLE_PHY(resTx, resRx); - BTUtils.fprintf_td(System.err, "****** Client Got Connected LE PHY: status %s: Tx %s, Rx %s\n", + PrintUtil.fprintf_td(System.err, "****** Client Got Connected LE PHY: status %s: Tx %s, Rx %s\n", res.toString(), resTx[0].toString(), resRx[0].toString()); } - final long t3 = BTUtils.currentTimeMillis(); + final long t3 = Clock.currentTimeMillis(); // // GATT Service Processing @@ -430,7 +433,7 @@ public class DBTClient01 implements DBTClientTest { // And it is an error case nonetheless ;-) throw new RuntimeException("Processing Ready Device: getServices() failed " + device.toString()); } - final long t5 = BTUtils.currentTimeMillis(); + final long t5 = Clock.currentTimeMillis(); { final long td00 = device.getLastDiscoveryTimestamp() - timestamp_t0; // adapter-init to discovered final long td01 = t1 - timestamp_t0; // adapter-init to processing-start @@ -441,8 +444,8 @@ public class DBTClient01 implements DBTClientTest { final long td23 = t3 - t2; // LE_PHY final long td13 = t3 - t1; // SMPKeyBin + LE_PHY final long td35 = t5 - t3; // get-gatt-services - BTUtils.println(System.err, System.lineSeparator()+System.lineSeparator()); - BTUtils.println(System.err, "PERF: GATT primary-services completed"+System.lineSeparator()+ + PrintUtil.println(System.err, System.lineSeparator()+System.lineSeparator()); + PrintUtil.println(System.err, "PERF: GATT primary-services completed"+System.lineSeparator()+ "PERF: adapter-init to discovered " + td00 + " ms,"+System.lineSeparator()+ "PERF: adapter-init to processing-start " + td01 + " ms,"+System.lineSeparator()+ "PERF: adapter-init to gatt-complete " + td05 + " ms,"+System.lineSeparator()+ @@ -456,19 +459,19 @@ public class DBTClient01 implements DBTClientTest { final BTGattCmd cmd = new BTGattCmd(device, "TestCmd", null /* service_uuid */, DBTConstants.CommandUUID, DBTConstants.ResponseUUID); cmd.setVerbose(true); final boolean cmd_resolved = cmd.isResolved(); - BTUtils.println(System.err, "Client Command test: "+cmd.toString()+", resolved "+cmd_resolved); + PrintUtil.println(System.err, "Client Command test: "+cmd.toString()+", resolved "+cmd_resolved); final byte[] cmd_data = { cmd_arg }; final HCIStatusCode cmd_res = cmd.send(true /* prefNoAck */, cmd_data, 3000 /* timeoutMS */); if( HCIStatusCode.SUCCESS == cmd_res ) { final byte[] resp = cmd.getResponse(); if( 1 == resp.length && resp[0] == cmd_arg ) { - BTUtils.fprintf_td(System.err, "Client Success: %s -> %s (echo response)\n", cmd.toString(), BTUtils.bytesHexString(resp, 0, resp.length, true /* lsb */)); + PrintUtil.fprintf_td(System.err, "Client Success: %s -> %s (echo response)\n", cmd.toString(), BasicTypes.bytesHexString(resp, 0, resp.length, true /* lsb */)); completedGATTCommands.incrementAndGet(); } else { - BTUtils.fprintf_td(System.err, "Client Failure: %s -> %s (different response)\n", cmd.toString(), BTUtils.bytesHexString(resp, 0, resp.length, true /* lsb */)); + PrintUtil.fprintf_td(System.err, "Client Failure: %s -> %s (different response)\n", cmd.toString(), BasicTypes.bytesHexString(resp, 0, resp.length, true /* lsb */)); } } else { - BTUtils.fprintf_td(System.err, "Client Failure: %s -> %s\n", cmd.toString(), cmd_res.toString()); + PrintUtil.fprintf_td(System.err, "Client Failure: %s -> %s\n", cmd.toString(), cmd_res.toString()); } cmd.close(); } @@ -482,23 +485,23 @@ public class DBTClient01 implements DBTClientTest { for(final Iterator<BTGattService> srvIter = primServices.iterator(); srvIter.hasNext(); i++) { final BTGattService primService = srvIter.next(); if( GATT_VERBOSE ) { - BTUtils.fprintf_td(System.err, " [%02d] Service UUID %s\n", i, primService.getUUID()); - BTUtils.fprintf_td(System.err, " [%02d] %s\n", i, primService.toString()); + PrintUtil.fprintf_td(System.err, " [%02d] Service UUID %s\n", i, primService.getUUID()); + PrintUtil.fprintf_td(System.err, " [%02d] %s\n", i, primService.toString()); } int j=0; final List<BTGattChar> serviceCharacteristics = primService.getChars(); for(final Iterator<BTGattChar> charIter = serviceCharacteristics.iterator(); charIter.hasNext(); j++) { final BTGattChar serviceChar = charIter.next(); if( GATT_VERBOSE ) { - BTUtils.fprintf_td(System.err, " [%02d.%02d] Characteristic: UUID %s\n", i, j, serviceChar.getUUID()); - BTUtils.fprintf_td(System.err, " [%02d.%02d] %s\n", i, j, serviceChar.toString()); + PrintUtil.fprintf_td(System.err, " [%02d.%02d] Characteristic: UUID %s\n", i, j, serviceChar.getUUID()); + PrintUtil.fprintf_td(System.err, " [%02d.%02d] %s\n", i, j, serviceChar.toString()); } final GattCharPropertySet properties = serviceChar.getProperties(); if( properties.isSet(GattCharPropertySet.Type.Read) ) { final byte[] value = serviceChar.readValue(); final String svalue = BTUtils.decodeUTF8String(value, 0, value.length); if( GATT_VERBOSE ) { - BTUtils.fprintf_td(System.err, " [%02d.%02d] value: %s ('%s')\n", i, j, BTUtils.bytesHexString(value, 0, -1, true), svalue); + PrintUtil.fprintf_td(System.err, " [%02d.%02d] value: %s ('%s')\n", i, j, BasicTypes.bytesHexString(value, 0, -1, true), svalue); } } int k=0; @@ -506,8 +509,8 @@ public class DBTClient01 implements DBTClientTest { for(final Iterator<BTGattDesc> descIter = charDescList.iterator(); descIter.hasNext(); k++) { final BTGattDesc charDesc = descIter.next(); if( GATT_VERBOSE ) { - BTUtils.fprintf_td(System.err, " [%02d.%02d.%02d] Descriptor: UUID %s\n", i, j, k, charDesc.getUUID()); - BTUtils.fprintf_td(System.err, " [%02d.%02d.%02d] %s\n", i, j, k, charDesc.toString()); + PrintUtil.fprintf_td(System.err, " [%02d.%02d.%02d] Descriptor: UUID %s\n", i, j, k, charDesc.getUUID()); + PrintUtil.fprintf_td(System.err, " [%02d.%02d.%02d] %s\n", i, j, k, charDesc.toString()); } } if( 0 == loop ) { @@ -520,25 +523,25 @@ public class DBTClient01 implements DBTClientTest { gattListener.add(gattEventListener); } else { gattListenerError = true; - BTUtils.fprintf_td(System.err, "Client Error: Failed to add GattListener: %s @ %s, gattListener %d\n", + PrintUtil.fprintf_td(System.err, "Client Error: Failed to add GattListener: %s @ %s, gattListener %d\n", gattEventListener.toString(), serviceChar.toString(), gattListener.size()); } if( GATT_VERBOSE ) { - BTUtils.fprintf_td(System.err, " [%02d.%02d] Characteristic-Listener: Notification(%b), Indication(%b): Added %b\n", + PrintUtil.fprintf_td(System.err, " [%02d.%02d] Characteristic-Listener: Notification(%b), Indication(%b): Added %b\n", i, j, cccdEnableResult[0], cccdEnableResult[1], clAdded); - BTUtils.fprintf_td(System.err, "\n"); + PrintUtil.fprintf_td(System.err, "\n"); } } } } if( GATT_VERBOSE ) { - BTUtils.fprintf_td(System.err, "\n"); + PrintUtil.fprintf_td(System.err, "\n"); } } success = notificationsReceived.get() >= 2 || indicationsReceived.get() >= 2; ++loop; } catch( final Exception ex) { - BTUtils.println(System.err, "****** Client Processing Ready Device: Exception.2 caught for " + device.toString() + ": "+ex.getMessage()); + PrintUtil.println(System.err, "****** Client Processing Ready Device: Exception.2 caught for " + device.toString() + ": "+ex.getMessage()); ex.printStackTrace(); } } while( !success && device.getConnected() && !gattListenerError ); @@ -552,7 +555,7 @@ public class DBTClient01 implements DBTClientTest { int i = 0; for(final BTGattCharListener gcl : gattListener) { if( !device.removeCharListener(gcl) ) { - BTUtils.fprintf_td(System.err, "Client Error: Failed to remove GattListener[%d/%d]: %s @ %s\n", + PrintUtil.fprintf_td(System.err, "Client Error: Failed to remove GattListener[%d/%d]: %s @ %s\n", i, gattListener.size(), gcl.toString(), device.toString()); success = false; } @@ -565,35 +568,35 @@ public class DBTClient01 implements DBTClientTest { final BTGattCmd cmd = new BTGattCmd(device, "FinalHandshake", null /* service_uuid */, DBTConstants.CommandUUID, DBTConstants.ResponseUUID); cmd.setVerbose(true); final boolean cmd_resolved = cmd.isResolved(); - BTUtils.println(System.err, "Client FinalCommand test: "+cmd.toString()+", resolved "+cmd_resolved); + PrintUtil.println(System.err, "Client FinalCommand test: "+cmd.toString()+", resolved "+cmd_resolved); final byte[] cmd_data = success ? DBTConstants.SuccessHandshakeCommandData : DBTConstants.FailHandshakeCommandData; final HCIStatusCode cmd_res = cmd.send(true /* prefNoAck */, cmd_data, 3000 /* timeoutMS */); if( HCIStatusCode.SUCCESS == cmd_res ) { final byte[] resp = cmd.getResponse(); if( Arrays.equals(cmd_data, resp) ) { - BTUtils.fprintf_td(System.err, "Client Success: %s -> %s (echo response)\n", cmd.toString(), BTUtils.bytesHexString(resp, 0, resp.length, true /* lsb */)); + PrintUtil.fprintf_td(System.err, "Client Success: %s -> %s (echo response)\n", cmd.toString(), BasicTypes.bytesHexString(resp, 0, resp.length, true /* lsb */)); } else { - BTUtils.fprintf_td(System.err, "Client Failure: %s -> %s (different response)\n", cmd.toString(), BTUtils.bytesHexString(resp, 0, resp.length, true /* lsb */)); + PrintUtil.fprintf_td(System.err, "Client Failure: %s -> %s (different response)\n", cmd.toString(), BasicTypes.bytesHexString(resp, 0, resp.length, true /* lsb */)); success = false; } } else { - BTUtils.fprintf_td(System.err, "Client Failure: %s -> %s\n", cmd.toString(), cmd_res.toString()); + PrintUtil.fprintf_td(System.err, "Client Failure: %s -> %s\n", cmd.toString(), cmd_res.toString()); success = false; } cmd.close(); } } catch (final Throwable t ) { - BTUtils.println(System.err, "****** Client Processing Ready Device: Exception.2 caught for " + device.toString() + ": "+t.getMessage()); + PrintUtil.println(System.err, "****** Client Processing Ready Device: Exception.2 caught for " + device.toString() + ": "+t.getMessage()); t.printStackTrace(); } - BTUtils.println(System.err, "****** Client Processing Ready Device: End-1: Success " + success + " on " + device.toString()); + PrintUtil.println(System.err, "****** Client Processing Ready Device: End-1: Success " + success + " on " + device.toString()); if( DiscoveryPolicy.PAUSE_CONNECTED_UNTIL_DISCONNECTED == discoveryPolicy ) { device.getAdapter().removeDevicePausingDiscovery(device); } - BTUtils.println(System.err, "****** Client Processing Ready Device: End-2: Success " + success + " on " + device.toString()); + PrintUtil.println(System.err, "****** Client Processing Ready Device: End-2: Success " + success + " on " + device.toString()); device.removeAllCharListener(); if( !KEEP_CONNECTED ) { @@ -611,7 +614,7 @@ public class DBTClient01 implements DBTClientTest { measurementsLeft.decrementAndGet(); } } - BTUtils.println(System.err, "****** Client Processing Ready Device: Success "+success+ + PrintUtil.println(System.err, "****** Client Processing Ready Device: Success "+success+ "; Measurements completed "+completedMeasurementsSuccess.get()+ ", left "+measurementsLeft.get()+ "; Received notitifications "+notificationsReceived.get()+", indications "+indicationsReceived.get()+ @@ -620,7 +623,7 @@ public class DBTClient01 implements DBTClientTest { } private void removeDevice(final BTDevice device) { - BTUtils.println(System.err, "****** Client Remove Device: removing: "+device.getAddressAndType()); + PrintUtil.println(System.err, "****** Client Remove Device: removing: "+device.getAddressAndType()); if( REMOVE_DEVICE ) { device.remove(); @@ -638,20 +641,20 @@ public class DBTClient01 implements DBTClientTest { resetLastProcessingStats(); final HCIStatusCode status = clientAdapter.startDiscovery( discoveryPolicy, le_scan_active, le_scan_interval, le_scan_window, filter_policy, filter_dup ); - BTUtils.println(System.err, "****** Client Start discovery ("+msg+") result: "+status); + PrintUtil.println(System.err, "****** Client Start discovery ("+msg+") result: "+status); return status; } @Override public HCIStatusCode stopDiscovery(final String msg) { final HCIStatusCode status = clientAdapter.stopDiscovery(); - BTUtils.println(System.err, "****** Client Stop discovery ("+msg+") result: "+status); + PrintUtil.println(System.err, "****** Client Stop discovery ("+msg+") result: "+status); return status; } @Override public void close(final String msg) { - BTUtils.println(System.err, "****** Client Close: "+msg); + PrintUtil.println(System.err, "****** Client Close: "+msg); clientAdapter.stopDiscovery(); Assert.assertTrue( clientAdapter.removeStatusListener( myAdapterStatusListener ) ); } @@ -659,7 +662,7 @@ public class DBTClient01 implements DBTClientTest { @Override public boolean initAdapter(final BTAdapter adapter) { if( !useAdapter.equals(EUI48.ALL_DEVICE) && !useAdapter.equals(adapter.getAddressAndType().address) ) { - BTUtils.fprintf_td(System.err, "initClientAdapter: Adapter not selected: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initClientAdapter: Adapter not selected: %s\n", adapter.toString()); return false; } adapterName = adapterName + "-" + adapter.getAddressAndType().address.toString().replace(":", ""); @@ -668,38 +671,38 @@ public class DBTClient01 implements DBTClientTest { if( !adapter.isInitialized() ) { final HCIStatusCode status = adapter.initialize( btMode ); if( HCIStatusCode.SUCCESS != status ) { - BTUtils.fprintf_td(System.err, "initClientAdapter: Adapter initialization failed: %s: %s\n", + PrintUtil.fprintf_td(System.err, "initClientAdapter: Adapter initialization failed: %s: %s\n", status.toString(), adapter.toString()); return false; } } else if( !adapter.setPowered( true ) ) { - BTUtils.fprintf_td(System.err, "initClientAdapter: Already initialized adapter power-on failed:: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initClientAdapter: Already initialized adapter power-on failed:: %s\n", adapter.toString()); return false; } // adapter is powered-on - BTUtils.fprintf_td(System.err, "initClientAdapter.1: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initClientAdapter.1: %s\n", adapter.toString()); if( adapter.setPowered(false) ) { final HCIStatusCode status = adapter.setName(adapterName, adapterShortName); if( HCIStatusCode.SUCCESS == status ) { - BTUtils.fprintf_td(System.err, "initClientAdapter: setLocalName OK: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initClientAdapter: setLocalName OK: %s\n", adapter.toString()); } else { - BTUtils.fprintf_td(System.err, "initClientAdapter: setLocalName failed: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initClientAdapter: setLocalName failed: %s\n", adapter.toString()); return false; } if( !adapter.setPowered( true ) ) { - BTUtils.fprintf_td(System.err, "initClientAdapter: setPower.2 on failed: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initClientAdapter: setPower.2 on failed: %s\n", adapter.toString()); return false; } } else { - BTUtils.fprintf_td(System.err, "initClientAdapter: setPowered.2 off failed: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initClientAdapter: setPowered.2 off failed: %s\n", adapter.toString()); } // adapter is powered-on - BTUtils.println(System.err, "initClientAdapter.2: "+adapter.toString()); + PrintUtil.println(System.err, "initClientAdapter.2: "+adapter.toString()); { final LE_Features le_feats = adapter.getLEFeatures(); - BTUtils.fprintf_td(System.err, "initClientAdapter: LE_Features %s\n", le_feats.toString()); + PrintUtil.fprintf_td(System.err, "initClientAdapter: LE_Features %s\n", le_feats.toString()); } if( adapter.getBTMajorVersion() > 4 ) { // BT5 specific @@ -707,7 +710,7 @@ public class DBTClient01 implements DBTClientTest { final LE_PHYs Rx = new LE_PHYs(LE_PHYs.PHY.LE_2M); final HCIStatusCode res = adapter.setDefaultLE_PHY(Tx, Rx); - BTUtils.fprintf_td(System.err, "initClientAdapter: Set Default LE PHY: status %s: Tx %s, Rx %s\n", + PrintUtil.fprintf_td(System.err, "initClientAdapter: Set Default LE PHY: status %s: Tx %s, Rx %s\n", res.toString(), Tx.toString(), Rx.toString()); } Assert.assertTrue( adapter.addStatusListener( myAdapterStatusListener ) ); diff --git a/trial/java/trial/org/direct_bt/DBTClientServer1x.java b/trial/java/trial/org/direct_bt/DBTClientServer1x.java index 70452cae..48a89caf 100644 --- a/trial/java/trial/org/direct_bt/DBTClientServer1x.java +++ b/trial/java/trial/org/direct_bt/DBTClientServer1x.java @@ -38,13 +38,14 @@ import org.direct_bt.BTException; import org.direct_bt.BTFactory; import org.direct_bt.BTManager; import org.direct_bt.BTSecurityRegistry; -import org.direct_bt.BTUtils; import org.direct_bt.DiscoveryPolicy; import org.direct_bt.EIRDataTypeSet; import org.direct_bt.EInfoReport; import org.direct_bt.PairingMode; import org.direct_bt.SMPKeyBin; +import org.jau.io.PrintUtil; import org.jau.net.EUI48; +import org.jau.sys.Clock; import org.junit.Assert; /** @@ -87,7 +88,7 @@ public abstract class DBTClientServer1x extends BaseDBTClientServer { final DBTServerTest server, final BTSecurityLevel secLevelServer, final ExpectedPairing serverExpPairing, final DBTClientTest client, final BTSecurityLevel secLevelClient, final ExpectedPairing clientExpPairing) { - final long t0 = BTUtils.currentTimeMillis(); + final long t0 = Clock.currentTimeMillis(); BTManager manager = null; try { @@ -103,7 +104,7 @@ public abstract class DBTClientServer1x extends BaseDBTClientServer { } { final List<BTAdapter> adapters = manager.getAdapters(); - BTUtils.println(System.err, "Adapter: Count "+adapters.size()+": "+adapters.toString()); + PrintUtil.println(System.err, "Adapter: Count "+adapters.size()+": "+adapters.toString()); Assert.assertTrue("Adapter count not >= 2 but "+adapters.size(), adapters.size() >= 2); } @@ -138,7 +139,7 @@ public abstract class DBTClientServer1x extends BaseDBTClientServer { lastCompletedDevicePairingMode = device.getPairingMode(); lastCompletedDeviceSecurityLevel = device.getConnSecurityLevel(); lastCompletedDeviceEIR = device.getEIR().clone(); - BTUtils.println(System.err, "XXXXXX Client Ready: "+device); + PrintUtil.println(System.err, "XXXXXX Client Ready: "+device); } } }; @@ -168,24 +169,24 @@ public abstract class DBTClientServer1x extends BaseDBTClientServer { lastCompletedDevice.getConnected() ); } max_connections_hit = ( protocolSessionCount * max_connections_per_session ) <= server.getDisconnectCount(); - test_duration = BTUtils.currentTimeMillis() - t0; + test_duration = Clock.currentTimeMillis() - t0; timeout = 0 < timeout_value && timeout_value <= test_duration + timeout_preempt_diff; // let's timeout here before our timeout timer if( !done && !max_connections_hit && !timeout ) { try { Thread.sleep(88); } catch (final InterruptedException e) { e.printStackTrace(); } } } while( !done && !max_connections_hit && !timeout ); - test_duration = BTUtils.currentTimeMillis() - t0; + test_duration = Clock.currentTimeMillis() - t0; - BTUtils.fprintf_td(System.err, "\n\n"); - BTUtils.fprintf_td(System.err, "****** Test Stats: duration %d ms, timeout[hit %b, value %d ms], max_connections hit %b\n", + PrintUtil.fprintf_td(System.err, "\n\n"); + PrintUtil.fprintf_td(System.err, "****** Test Stats: duration %d ms, timeout[hit %b, value %d ms], max_connections hit %b\n", test_duration, timeout, timeout_value, max_connections_hit); - BTUtils.fprintf_td(System.err, " Server ProtocolSessions[success %d/%d total, requested %d], disconnects %d of %d max\n", + PrintUtil.fprintf_td(System.err, " Server ProtocolSessions[success %d/%d total, requested %d], disconnects %d of %d max\n", server.getProtocolSessionsDoneSuccess(), server.getProtocolSessionsDoneTotal(), protocolSessionCount, server.getDisconnectCount(), ( protocolSessionCount * max_connections_per_session )); - BTUtils.fprintf_td(System.err, " Client ProtocolSessions[success %d/%d total, requested %d], disconnects %d of %d max\n", + PrintUtil.fprintf_td(System.err, " Client ProtocolSessions[success %d/%d total, requested %d], disconnects %d of %d max\n", client.getProtocolSessionsDoneSuccess(), client.getProtocolSessionsDoneTotal(), protocolSessionCount, client.getDisconnectCount(), ( protocolSessionCount * max_connections_per_session )); - BTUtils.fprintf_td(System.err, "\n\n"); + PrintUtil.fprintf_td(System.err, "\n\n"); if( expSuccess ) { Assert.assertFalse( max_connections_hit ); @@ -248,7 +249,7 @@ public abstract class DBTClientServer1x extends BaseDBTClientServer { // Validating EIR // synchronized( mtx_sync ) { - BTUtils.println(System.err, "lastCompletedDevice.connectedEIR: "+lastCompletedDeviceEIR.toString()); + PrintUtil.println(System.err, "lastCompletedDevice.connectedEIR: "+lastCompletedDeviceEIR.toString()); Assert.assertNotEquals(0, lastCompletedDeviceEIR.getEIRDataMask().mask); Assert.assertTrue( lastCompletedDeviceEIR.isSet(EIRDataTypeSet.DataType.FLAGS) ); Assert.assertTrue( lastCompletedDeviceEIR.isSet(EIRDataTypeSet.DataType.SERVICE_UUID) ); @@ -257,7 +258,7 @@ public abstract class DBTClientServer1x extends BaseDBTClientServer { Assert.assertEquals(serverName, lastCompletedDeviceEIR.getName()); { final EInfoReport eir = lastCompletedDevice.getEIR().clone(); - BTUtils.println(System.err, "lastCompletedDevice.currentEIR: "+eir.toString()); + PrintUtil.println(System.err, "lastCompletedDevice.currentEIR: "+eir.toString()); Assert.assertEquals(0, eir.getEIRDataMask().mask); Assert.assertEquals(0, eir.getName().length()); } @@ -278,6 +279,6 @@ public abstract class DBTClientServer1x extends BaseDBTClientServer { } } final int count = manager.removeChangedAdapterSetListener(myChangedAdapterSetListener); - BTUtils.println(System.err, "****** EOL Removed ChangedAdapterSetCallback " + count); + PrintUtil.println(System.err, "****** EOL Removed ChangedAdapterSetCallback " + count); } } diff --git a/trial/java/trial/org/direct_bt/DBTEndpoint.java b/trial/java/trial/org/direct_bt/DBTEndpoint.java index 6ea07e18..bc851ff8 100644 --- a/trial/java/trial/org/direct_bt/DBTEndpoint.java +++ b/trial/java/trial/org/direct_bt/DBTEndpoint.java @@ -30,8 +30,8 @@ import java.util.concurrent.atomic.AtomicInteger; import org.direct_bt.BTAdapter; import org.direct_bt.BTManager; import org.direct_bt.BTRole; -import org.direct_bt.BTUtils; import org.direct_bt.HCIStatusCode; +import org.jau.io.PrintUtil; import org.junit.Assert; public interface DBTEndpoint { @@ -108,12 +108,12 @@ public interface DBTEndpoint { if( null == endpt.getAdapter() ) { if( endpt.initAdapter( adapter ) ) { endpt.setAdapter(adapter); - BTUtils.println(System.err, "****** Adapter-"+endpt.getClass().getSimpleName()+" ADDED__: InitOK: " + adapter); + PrintUtil.println(System.err, "****** Adapter-"+endpt.getClass().getSimpleName()+" ADDED__: InitOK: " + adapter); return; } } } - BTUtils.println(System.err, "****** Adapter ADDED__: Ignored: " + adapter); + PrintUtil.println(System.err, "****** Adapter ADDED__: Ignored: " + adapter); } @Override @@ -121,11 +121,11 @@ public interface DBTEndpoint { for(final DBTEndpoint endpt : endpts ) { if( null != endpt.getAdapter() && adapter.equals( endpt.getAdapter() ) ) { endpt.setAdapter(null); - BTUtils.println(System.err, "****** Adapter-"+endpt.getClass().getSimpleName()+" REMOVED: " + adapter); + PrintUtil.println(System.err, "****** Adapter-"+endpt.getClass().getSimpleName()+" REMOVED: " + adapter); return; } } - BTUtils.println(System.err, "****** Adapter REMOVED: Ignored " + adapter); + PrintUtil.println(System.err, "****** Adapter REMOVED: Ignored " + adapter); } }; diff --git a/trial/java/trial/org/direct_bt/DBTServer01.java b/trial/java/trial/org/direct_bt/DBTServer01.java index 59d6b2b6..917c8142 100644 --- a/trial/java/trial/org/direct_bt/DBTServer01.java +++ b/trial/java/trial/org/direct_bt/DBTServer01.java @@ -58,7 +58,10 @@ import org.direct_bt.PairingMode; import org.direct_bt.SMPIOCapability; import org.direct_bt.SMPPairingState; import org.direct_bt.ScanType; +import org.jau.io.PrintUtil; import org.jau.net.EUI48; +import org.jau.sys.Clock; +import org.jau.util.BasicTypes; import org.junit.Assert; /** @@ -266,35 +269,35 @@ public class DBTServer01 implements DBTServerTest { final AdapterSettings newmask, final AdapterSettings changedmask, final long timestamp) { final boolean initialSetting = oldmask.isEmpty(); if( initialSetting ) { - BTUtils.println(System.err, "****** Server SETTINGS: "+oldmask+" -> "+newmask+", initial "+changedmask); + PrintUtil.println(System.err, "****** Server SETTINGS: "+oldmask+" -> "+newmask+", initial "+changedmask); } else { - BTUtils.println(System.err, "****** Server SETTINGS: "+oldmask+" -> "+newmask+", changed "+changedmask); + PrintUtil.println(System.err, "****** Server SETTINGS: "+oldmask+" -> "+newmask+", changed "+changedmask); } - BTUtils.println(System.err, "Server Status Adapter:"); - BTUtils.println(System.err, adapter.toString()); + PrintUtil.println(System.err, "Server Status Adapter:"); + PrintUtil.println(System.err, adapter.toString()); } @Override public void discoveringChanged(final BTAdapter adapter, final ScanType currentMeta, final ScanType changedType, final boolean changedEnabled, final DiscoveryPolicy policy, final long timestamp) { - BTUtils.println(System.err, "****** Server DISCOVERING: meta "+currentMeta+", changed["+changedType+", enabled "+changedEnabled+", policy "+policy+"] on "+adapter); + PrintUtil.println(System.err, "****** Server DISCOVERING: meta "+currentMeta+", changed["+changedType+", enabled "+changedEnabled+", policy "+policy+"] on "+adapter); } @Override public boolean deviceFound(final BTDevice device, final long timestamp) { - BTUtils.println(System.err, "****** Server FOUND__-1: NOP "+device.toString()); + PrintUtil.println(System.err, "****** Server FOUND__-1: NOP "+device.toString()); return false; } @Override public void deviceUpdated(final BTDevice device, final EIRDataTypeSet updateMask, final long timestamp) { if( SHOW_UPDATE_EVENTS ) { - BTUtils.println(System.err, "****** Server UPDATED: "+updateMask+" of "+device); + PrintUtil.println(System.err, "****** Server UPDATED: "+updateMask+" of "+device); } } @Override public void deviceConnected(final BTDevice device, final boolean discovered, final long timestamp) { - BTUtils.println(System.err, "****** Server CONNECTED (served "+disconnectCount.get()+", left "+servingProtocolSessionsLeft.get()+"): discovered "+discovered+": "+device+" on "+device.getAdapter()); + PrintUtil.println(System.err, "****** Server CONNECTED (served "+disconnectCount.get()+", left "+servingProtocolSessionsLeft.get()+"): discovered "+discovered+": "+device+" on "+device.getAdapter()); final boolean available = null == getDevice(); if( available ) { setDevice(device); @@ -303,7 +306,7 @@ public class DBTServer01 implements DBTServerTest { @Override public void devicePairingState(final BTDevice device, final SMPPairingState state, final PairingMode mode, final long timestamp) { - BTUtils.println(System.err, "****** Server PAIRING_STATE: state "+state+", mode "+mode+": "+device); + PrintUtil.println(System.err, "****** Server PAIRING_STATE: state "+state+", mode "+mode+": "+device); switch( state ) { case NONE: // next: deviceReady(..) @@ -355,12 +358,12 @@ public class DBTServer01 implements DBTServerTest { @Override public void deviceReady(final BTDevice device, final long timestamp) { - BTUtils.println(System.err, "****** Server READY-1: NOP " + device.toString()); + PrintUtil.println(System.err, "****** Server READY-1: NOP " + device.toString()); } @Override public void deviceDisconnected(final BTDevice device, final HCIStatusCode reason, final short handle, final long timestamp) { - BTUtils.println(System.err, "****** Server DISCONNECTED (served "+(1+disconnectCount.get())+", left "+servingProtocolSessionsLeft.get()+"): Reason "+reason+", old handle 0x"+Integer.toHexString(handle)+": "+device+" on "+device.getAdapter()); + PrintUtil.println(System.err, "****** Server DISCONNECTED (served "+(1+disconnectCount.get())+", left "+servingProtocolSessionsLeft.get()+"): Reason "+reason+", old handle 0x"+Integer.toHexString(handle)+": "+device+" on "+device.getAdapter()); final boolean match = matches(device); if( match ) { setDevice(null); @@ -407,23 +410,23 @@ public class DBTServer01 implements DBTServerTest { { final BTDevice connectedDevice_ = getDevice(); final String connectedDeviceStr = null != connectedDevice_ ? connectedDevice_.toString() : "n/a"; - BTUtils.fprintf_td(System.err, "****** Server GATT::PULSE Start %s\n", connectedDeviceStr); + PrintUtil.fprintf_td(System.err, "****** Server GATT::PULSE Start %s\n", connectedDeviceStr); } while( !shallStopPulseSender() ) { final BTDevice connectedDevice_ = getDevice(); if( null != connectedDevice_ && connectedDevice_.getConnected() ) { if( 0 != handlePulseDataNotify || 0 != handlePulseDataIndicate ) { - final String data = String.format("Dynamic Data Example. Elapsed Milliseconds: %,9d", BTUtils.elapsedTimeMillis()); + final String data = String.format("Dynamic Data Example. Elapsed Milliseconds: %,9d", Clock.elapsedTimeMillis()); final byte[] v = data.getBytes(StandardCharsets.UTF_8); if( 0 != handlePulseDataNotify ) { if( GATT_VERBOSE ) { - BTUtils.fprintf_td(System.err, "****** Server GATT::sendNotification: PULSE to %s\n", connectedDevice_.toString()); + PrintUtil.fprintf_td(System.err, "****** Server GATT::sendNotification: PULSE to %s\n", connectedDevice_.toString()); } connectedDevice_.sendNotification(handlePulseDataNotify, v); } if( 0 != handlePulseDataIndicate ) { if( GATT_VERBOSE ) { - BTUtils.fprintf_td(System.err, "****** Server GATT::sendIndication: PULSE to %s\n", connectedDevice_.toString()); + PrintUtil.fprintf_td(System.err, "****** Server GATT::sendIndication: PULSE to %s\n", connectedDevice_.toString()); } connectedDevice_.sendIndication(handlePulseDataIndicate, v); } @@ -438,7 +441,7 @@ public class DBTServer01 implements DBTServerTest { { final BTDevice connectedDevice_ = getDevice(); final String connectedDeviceStr = null != connectedDevice_ ? connectedDevice_.toString() : "n/a"; - BTUtils.fprintf_td(System.err, "****** Server GATT::PULSE End %s\n", connectedDeviceStr); + PrintUtil.fprintf_td(System.err, "****** Server GATT::PULSE End %s\n", connectedDeviceStr); } } @@ -448,15 +451,15 @@ public class DBTServer01 implements DBTServerTest { if( 0 != handleResponseDataNotify || 0 != handleResponseDataIndicate ) { if( 0 != handleResponseDataNotify ) { if( GATT_VERBOSE ) { - BTUtils.fprintf_td(System.err, "****** Server GATT::sendNotification: %s to %s\n", - BTUtils.bytesHexString(data, 0, data.length, true /* lsb */), connectedDevice_.toString()); + PrintUtil.fprintf_td(System.err, "****** Server GATT::sendNotification: %s to %s\n", + BasicTypes.bytesHexString(data, 0, data.length, true /* lsb */), connectedDevice_.toString()); } connectedDevice_.sendNotification(handleResponseDataNotify, data); } if( 0 != handleResponseDataIndicate ) { if( GATT_VERBOSE ) { - BTUtils.fprintf_td(System.err, "****** Server GATT::sendIndication: %s to %s\n", - BTUtils.bytesHexString(data, 0, data.length, true /* lsb */), connectedDevice_.toString()); + PrintUtil.fprintf_td(System.err, "****** Server GATT::sendIndication: %s to %s\n", + BasicTypes.bytesHexString(data, 0, data.length, true /* lsb */), connectedDevice_.toString()); } connectedDevice_.sendIndication(handleResponseDataIndicate, data); } @@ -475,10 +478,10 @@ public class DBTServer01 implements DBTServerTest { final BTDevice connectedDevice_ = getDevice(); if( null != connectedDevice_ ) { - BTUtils.fprintf_td(System.err, "****** Server i470 disconnectDevice(delayed %d ms): client %s\n", sleep_dur, connectedDevice_.toString()); + PrintUtil.fprintf_td(System.err, "****** Server i470 disconnectDevice(delayed %d ms): client %s\n", sleep_dur, connectedDevice_.toString()); connectedDevice_.disconnect(); } else { - BTUtils.fprintf_td(System.err, "****** Server i470 disconnectDevice(delayed %d ms): client null\n", sleep_dur); + PrintUtil.fprintf_td(System.err, "****** Server i470 disconnectDevice(delayed %d ms): client null\n", sleep_dur); } } @@ -501,7 +504,7 @@ public class DBTServer01 implements DBTServerTest { @Override public void connected(final BTDevice device, final int initialMTU) { final boolean match = matches(device); - BTUtils.fprintf_td(System.err, "****** Server GATT::connected(match %b): initMTU %d, %s\n", + PrintUtil.fprintf_td(System.err, "****** Server GATT::connected(match %b): initMTU %d, %s\n", match, initialMTU, device.toString()); if( match ) { synchronized( sync_lock ) { @@ -513,7 +516,7 @@ public class DBTServer01 implements DBTServerTest { @Override public void disconnected(final BTDevice device) { final boolean match = matches(device); - BTUtils.fprintf_td(System.err, "****** Server GATT::disconnected(match %b): %s\n", match, device.toString()); + PrintUtil.fprintf_td(System.err, "****** Server GATT::disconnected(match %b): %s\n", match, device.toString()); if( match ) { clear(); } @@ -528,7 +531,7 @@ public class DBTServer01 implements DBTServerTest { usedMTU = mtu; } } - BTUtils.fprintf_td(System.err, "****** Server GATT::mtuChanged(match %b, served %d, left %d): %d -> %d, %s\n", + PrintUtil.fprintf_td(System.err, "****** Server GATT::mtuChanged(match %b, served %d, left %d): %d -> %d, %s\n", match, servedProtocolSessionsTotal.get(), servingProtocolSessionsLeft.get(), match ? usedMTU_old : 0, mtu, device.toString()); if( do_disconnect ) { @@ -540,7 +543,7 @@ public class DBTServer01 implements DBTServerTest { public boolean readCharValue(final BTDevice device, final DBGattService s, final DBGattChar c) { final boolean match = matches(device); if( GATT_VERBOSE ) { - BTUtils.fprintf_td(System.err, "****** Server GATT::readCharValue(match %b): to %s, from\n %s\n %s\n", + PrintUtil.fprintf_td(System.err, "****** Server GATT::readCharValue(match %b): to %s, from\n %s\n %s\n", match, device.toString(), s.toString(), c.toString()); } return match; @@ -550,7 +553,7 @@ public class DBTServer01 implements DBTServerTest { public boolean readDescValue(final BTDevice device, final DBGattService s, final DBGattChar c, final DBGattDesc d) { final boolean match = matches(device); if( GATT_VERBOSE ) { - BTUtils.fprintf_td(System.err, "****** Server GATT::readDescValue(match %b): to %s, from\n %s\n %s\n %s\n", + PrintUtil.fprintf_td(System.err, "****** Server GATT::readDescValue(match %b): to %s, from\n %s\n %s\n %s\n", match, device.toString(), s.toString(), c.toString(), d.toString()); } return match; @@ -560,9 +563,9 @@ public class DBTServer01 implements DBTServerTest { public boolean writeCharValue(final BTDevice device, final DBGattService s, final DBGattChar c, final byte[] value, final int value_offset) { final boolean match = matches(device); if( GATT_VERBOSE ) { - final String value_s = BTUtils.bytesHexString(value, 0, value.length, true /* lsbFirst */)+ + final String value_s = BasicTypes.bytesHexString(value, 0, value.length, true /* lsbFirst */)+ " '"+BTUtils.decodeUTF8String(value, 0, value.length)+"'"; - BTUtils.fprintf_td(System.err, "****** Server GATT::writeCharValue(match %b): %s @ %d from %s, to\n %s\n %s\n", + PrintUtil.fprintf_td(System.err, "****** Server GATT::writeCharValue(match %b): %s @ %d from %s, to\n %s\n %s\n", match, value_s, value_offset, device.toString(), s.toString(), c.toString()); } @@ -597,7 +600,7 @@ public class DBTServer01 implements DBTServerTest { executeOffThread( () -> { sendResponse( data ); }, true /* detach */); } if( GATT_VERBOSE || isFinalHandshake ) { - BTUtils.fprintf_td(System.err, "****** Server GATT::writeCharValueDone(match %b, finalCmd %b, sessions [%d ok / %d total], left %d): From %s, to\n %s\n %s\n Char-Value: %s\n", + PrintUtil.fprintf_td(System.err, "****** Server GATT::writeCharValueDone(match %b, finalCmd %b, sessions [%d ok / %d total], left %d): From %s, to\n %s\n %s\n Char-Value: %s\n", match, isFinalHandshake, servedProtocolSessionsSuccess.get(), servedProtocolSessionsTotal.get(), servingProtocolSessionsLeft.get(), device.toString(), s.toString(), c.toString(), value.toString()); } @@ -609,9 +612,9 @@ public class DBTServer01 implements DBTServerTest { { final boolean match = matches(device); if( GATT_VERBOSE ) { - final String value_s = BTUtils.bytesHexString(value, 0, value.length, true /* lsbFirst */)+ + final String value_s = BasicTypes.bytesHexString(value, 0, value.length, true /* lsbFirst */)+ " '"+BTUtils.decodeUTF8String(value, 0, value.length)+"'"; - BTUtils.fprintf_td(System.err, "****** Server GATT::writeDescValue(match %b): %s @ %d from %s\n %s\n %s\n %s\n", + PrintUtil.fprintf_td(System.err, "****** Server GATT::writeDescValue(match %b): %s @ %d from %s\n %s\n %s\n %s\n", match, value_s, value_offset, device.toString(), s.toString(), c.toString(), d.toString()); } @@ -623,7 +626,7 @@ public class DBTServer01 implements DBTServerTest { if( GATT_VERBOSE ) { final boolean match = matches(device); final DBGattValue value = d.getValue(); - BTUtils.fprintf_td(System.err, "****** Server GATT::writeDescValueDone(match %b): From %s\n %s\n %s\n %s\n Desc-Value: %s\n", + PrintUtil.fprintf_td(System.err, "****** Server GATT::writeDescValueDone(match %b): From %s\n %s\n %s\n %s\n Desc-Value: %s\n", match, device.toString(), s.toString(), c.toString(), d.toString(), value.toString()); } } @@ -635,7 +638,7 @@ public class DBTServer01 implements DBTServerTest { final boolean match = matches(device); if( GATT_VERBOSE ) { final DBGattValue value = d.getValue(); - BTUtils.fprintf_td(System.err, "****** Server GATT::clientCharConfigChanged(match %b): notify %b, indicate %b from %s\n %s\n %s\n %s\n Desc-Value: %s\n", + PrintUtil.fprintf_td(System.err, "****** Server GATT::clientCharConfigChanged(match %b): notify %b, indicate %b from %s\n %s\n %s\n %s\n Desc-Value: %s\n", match, notificationEnabled, indicationEnabled, device.toString(), s.toString(), c.toString(), d.toString(), value.toString()); } @@ -664,7 +667,7 @@ public class DBTServer01 implements DBTServerTest { @Override public void close(final String msg) { - BTUtils.println(System.err, "****** Server Close.0: "+msg); + PrintUtil.println(System.err, "****** Server Close.0: "+msg); Assert.assertTrue( serverAdapter.removeStatusListener( myAdapterStatusListener ) ); { stopAdvertising(msg); @@ -677,12 +680,12 @@ public class DBTServer01 implements DBTServerTest { gattServerListener.close(); // dbGattServer.close(); // keep alive stopAdvertising(msg); // try once more in case of already started AdapterStatusListener - BTUtils.println(System.err, "****** Server Close.X: "+msg); + PrintUtil.println(System.err, "****** Server Close.X: "+msg); } private HCIStatusCode stopAdvertising(final String msg) { final HCIStatusCode status = serverAdapter.stopAdvertising(); - BTUtils.println(System.err, "****** Server Stop advertising ("+msg+") result: "+status+": "+serverAdapter.toString()); + PrintUtil.println(System.err, "****** Server Stop advertising ("+msg+") result: "+status+": "+serverAdapter.toString()); return status; } @@ -713,21 +716,21 @@ public class DBTServer01 implements DBTServerTest { gattDevNameChar.setValue(aname_bytes, 0, aname_bytes.length, 0); } - BTUtils.println(System.err, "****** Server Start advertising ("+msg+"): EIR "+eir.toString()); - BTUtils.println(System.err, "****** Server Start advertising ("+msg+"): adv "+adv_mask.toString()+", scanrsp "+scanrsp_mask.toString()); + PrintUtil.println(System.err, "****** Server Start advertising ("+msg+"): EIR "+eir.toString()); + PrintUtil.println(System.err, "****** Server Start advertising ("+msg+"): adv "+adv_mask.toString()+", scanrsp "+scanrsp_mask.toString()); final HCIStatusCode status = serverAdapter.startAdvertising(dbGattServer, eir, adv_mask, scanrsp_mask, adv_interval_min, adv_interval_max, adv_type, adv_chan_map, filter_policy); - BTUtils.println(System.err, "****** Server Start advertising ("+msg+") result: "+status+": "+serverAdapter.toString()); + PrintUtil.println(System.err, "****** Server Start advertising ("+msg+") result: "+status+": "+serverAdapter.toString()); if( GATT_VERBOSE ) { - BTUtils.println(System.err, dbGattServer.toFullString()); + PrintUtil.println(System.err, dbGattServer.toFullString()); } return status; } private void processDisconnectedDevice(final BTDevice device) { - BTUtils.println(System.err, "****** Server Disconnected Device (count "+(1+disconnectCount.get())+ + PrintUtil.println(System.err, "****** Server Disconnected Device (count "+(1+disconnectCount.get())+ ", served "+servedProtocolSessionsTotal.get()+", left "+servingProtocolSessionsLeft.get()+"): Start "+device.toString()); // already unpaired @@ -744,13 +747,13 @@ public class DBTServer01 implements DBTServerTest { startAdvertising("device-disconnected"); } - BTUtils.println(System.err, "****** Server Disonnected Device: End "+device.toString()); + PrintUtil.println(System.err, "****** Server Disonnected Device: End "+device.toString()); } @Override public boolean initAdapter(final BTAdapter adapter) { if( !useAdapter.equals(EUI48.ALL_DEVICE) && !useAdapter.equals(adapter.getAddressAndType().address) ) { - BTUtils.fprintf_td(System.err, "initServerAdapter: Adapter not selected: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initServerAdapter: Adapter not selected: %s\n", adapter.toString()); return false; } adapterName = adapterName + "-" + adapter.getAddressAndType().address.toString().replace(":", ""); @@ -759,31 +762,31 @@ public class DBTServer01 implements DBTServerTest { // Initialize with defaults and power-on final HCIStatusCode status = adapter.initialize( btMode ); if( HCIStatusCode.SUCCESS != status ) { - BTUtils.fprintf_td(System.err, "initServerAdapter: initialization failed: %s: %s\n", + PrintUtil.fprintf_td(System.err, "initServerAdapter: initialization failed: %s: %s\n", status.toString(), adapter.toString()); return false; } } else if( !adapter.setPowered( true ) ) { - BTUtils.fprintf_td(System.err, "initServerAdapter: setPower.1 on failed: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initServerAdapter: setPower.1 on failed: %s\n", adapter.toString()); return false; } // adapter is powered-on - BTUtils.println(System.err, "initServerAdapter.1: "+adapter.toString()); + PrintUtil.println(System.err, "initServerAdapter.1: "+adapter.toString()); if( adapter.setPowered(false) ) { HCIStatusCode status = adapter.setName(adapterName, adapterShortName); if( HCIStatusCode.SUCCESS == status ) { - BTUtils.fprintf_td(System.err, "initServerAdapter: setLocalName OK: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initServerAdapter: setLocalName OK: %s\n", adapter.toString()); } else { - BTUtils.fprintf_td(System.err, "initServerAdapter: setLocalName failed: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initServerAdapter: setLocalName failed: %s\n", adapter.toString()); return false; } status = adapter.setSecureConnections( use_SC ); if( HCIStatusCode.SUCCESS == status ) { - BTUtils.fprintf_td(System.err, "initServerAdapter: setSecureConnections OK: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initServerAdapter: setSecureConnections OK: %s\n", adapter.toString()); } else { - BTUtils.fprintf_td(System.err, "initServerAdapter: setSecureConnections failed: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initServerAdapter: setSecureConnections failed: %s\n", adapter.toString()); return false; } @@ -793,34 +796,34 @@ public class DBTServer01 implements DBTServerTest { final short supervision_timeout = 50; // 500ms status = adapter.setDefaultConnParam(conn_min_interval, conn_max_interval, conn_latency, supervision_timeout); if( HCIStatusCode.SUCCESS == status ) { - BTUtils.fprintf_td(System.err, "initServerAdapter: setDefaultConnParam OK: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initServerAdapter: setDefaultConnParam OK: %s\n", adapter.toString()); } else if( HCIStatusCode.UNKNOWN_COMMAND == status ) { - BTUtils.fprintf_td(System.err, "initServerAdapter: setDefaultConnParam UNKNOWN_COMMAND (ignored): %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initServerAdapter: setDefaultConnParam UNKNOWN_COMMAND (ignored): %s\n", adapter.toString()); } else { - BTUtils.fprintf_td(System.err, "initServerAdapter: setDefaultConnParam failed: %s, %s\n", status.toString(), adapter.toString()); + PrintUtil.fprintf_td(System.err, "initServerAdapter: setDefaultConnParam failed: %s, %s\n", status.toString(), adapter.toString()); return false; } if( !adapter.setPowered( true ) ) { - BTUtils.fprintf_td(System.err, "initServerAdapter: setPower.2 on failed: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initServerAdapter: setPower.2 on failed: %s\n", adapter.toString()); return false; } } else { - BTUtils.fprintf_td(System.err, "initServerAdapter: setPowered.2 off failed: %s\n", adapter.toString()); + PrintUtil.fprintf_td(System.err, "initServerAdapter: setPowered.2 off failed: %s\n", adapter.toString()); } // adapter is powered-on - BTUtils.println(System.err, "initServerAdapter.2: "+adapter.toString()); + PrintUtil.println(System.err, "initServerAdapter.2: "+adapter.toString()); { final LE_Features le_feats = adapter.getLEFeatures(); - BTUtils.fprintf_td(System.err, "initServerAdapter: LE_Features %s\n", le_feats.toString()); + PrintUtil.fprintf_td(System.err, "initServerAdapter: LE_Features %s\n", le_feats.toString()); } if( adapter.getBTMajorVersion() > 4 ) { // BT5 specific final LE_PHYs Tx = new LE_PHYs( LE_PHYs.PHY.LE_2M ); final LE_PHYs Rx = new LE_PHYs( LE_PHYs.PHY.LE_2M ); final HCIStatusCode res = adapter.setDefaultLE_PHY(Tx, Rx); - BTUtils.fprintf_td(System.err, "initServerAdapter: Set Default LE PHY: status %s: Tx %s, Rx %s\n", + PrintUtil.fprintf_td(System.err, "initServerAdapter: Set Default LE PHY: status %s: Tx %s, Rx %s\n", res.toString(), Tx.toString(), Rx.toString()); } adapter.setSMPKeyPath(DBTConstants.SERVER_KEY_PATH); diff --git a/trial/java/trial/org/direct_bt/DBTUtils.java b/trial/java/trial/org/direct_bt/DBTUtils.java index fe55a52d..43fbecd0 100644 --- a/trial/java/trial/org/direct_bt/DBTUtils.java +++ b/trial/java/trial/org/direct_bt/DBTUtils.java @@ -28,7 +28,7 @@ import java.io.File; import java.nio.file.Files; import org.direct_bt.BTFactory; -import org.direct_bt.BTUtils; +import org.jau.io.PrintUtil; public class DBTUtils { public static final boolean mkdirKeyFolder() { @@ -39,13 +39,13 @@ public class DBTUtils { try { if( !file.isDirectory() ) { final boolean res2 = file.mkdirs(); - BTUtils.println(System.err, "****** KEY_PATH '"+file.toString()+"': mkdir: "+res2); + PrintUtil.println(System.err, "****** KEY_PATH '"+file.toString()+"': mkdir: "+res2); res = res && res2; } else { - BTUtils.println(System.err, "****** KEY_PATH '"+file.toString()+"': already exists"); + PrintUtil.println(System.err, "****** KEY_PATH '"+file.toString()+"': already exists"); } } catch(final Throwable t) { - BTUtils.println(System.err, "****** KEY_PATH '"+file.toString()+"': Caught "+t.getMessage()); + PrintUtil.println(System.err, "****** KEY_PATH '"+file.toString()+"': Caught "+t.getMessage()); res = false; } } @@ -54,13 +54,13 @@ public class DBTUtils { try { if( !file.isDirectory() ) { final boolean res2 = file.mkdirs(); - BTUtils.println(System.err, "****** KEY_PATH '"+file.toString()+"': mkdir: "+res2); + PrintUtil.println(System.err, "****** KEY_PATH '"+file.toString()+"': mkdir: "+res2); res = res && res2; } else { - BTUtils.println(System.err, "****** KEY_PATH '"+file.toString()+"': already exists"); + PrintUtil.println(System.err, "****** KEY_PATH '"+file.toString()+"': already exists"); } } catch(final Throwable t) { - BTUtils.println(System.err, "****** KEY_PATH '"+file.toString()+"': Caught "+t.getMessage()); + PrintUtil.println(System.err, "****** KEY_PATH '"+file.toString()+"': Caught "+t.getMessage()); res = false; } } @@ -112,10 +112,10 @@ public class DBTUtils { if( file.isDirectory() ) { final boolean res2 = delete(file, false /* recursive */); res = res2 && res; - BTUtils.println(System.err, "****** KEY_PATH '"+file.toString()+"': delete: "+res2); + PrintUtil.println(System.err, "****** KEY_PATH '"+file.toString()+"': delete: "+res2); } } catch(final Throwable t) { - BTUtils.println(System.err, "****** KEY_PATH '"+file.toString()+"': Caught "+t.getMessage()); + PrintUtil.println(System.err, "****** KEY_PATH '"+file.toString()+"': Caught "+t.getMessage()); res = false; } } @@ -125,10 +125,10 @@ public class DBTUtils { if( file.isDirectory() ) { final boolean res2 = delete(file, false /* recursive */); res = res2 && res; - BTUtils.println(System.err, "****** KEY_PATH '"+file.toString()+"': delete: "+res2); + PrintUtil.println(System.err, "****** KEY_PATH '"+file.toString()+"': delete: "+res2); } } catch(final Throwable t) { - BTUtils.println(System.err, "****** KEY_PATH '"+file.toString()+"': Caught "+t.getMessage()); + PrintUtil.println(System.err, "****** KEY_PATH '"+file.toString()+"': Caught "+t.getMessage()); res = false; } } diff --git a/trial/java/trial/org/direct_bt/TestDBTClientServer00.java b/trial/java/trial/org/direct_bt/TestDBTClientServer00.java index e34d1cdd..a945d038 100644 --- a/trial/java/trial/org/direct_bt/TestDBTClientServer00.java +++ b/trial/java/trial/org/direct_bt/TestDBTClientServer00.java @@ -35,8 +35,8 @@ import org.direct_bt.BTAdapter; import org.direct_bt.BTException; import org.direct_bt.BTFactory; import org.direct_bt.BTManager; -import org.direct_bt.BTUtils; import org.direct_bt.DirectBTVersion; +import org.jau.io.PrintUtil; import org.jau.net.EUI48; import org.junit.Assert; import org.junit.FixMethodOrder; @@ -77,9 +77,9 @@ public class TestDBTClientServer00 extends BaseDBTClientServer { return; } final List<BTAdapter> adapters = manager.getAdapters(); - BTUtils.println(System.err, "Adapter: Count "+adapters.size()); + PrintUtil.println(System.err, "Adapter: Count "+adapters.size()); for(int i=0; i<adapters.size(); i++) { - BTUtils.println(System.err, i+": "+adapters.get(i).toString()); + PrintUtil.println(System.err, i+": "+adapters.get(i).toString()); } Assert.assertTrue("Adapter count not >= 1 but "+adapters.size(), adapters.size() >= 1); @@ -139,7 +139,7 @@ public class TestDBTClientServer00 extends BaseDBTClientServer { } final int count = manager.removeChangedAdapterSetListener(myChangedAdapterSetListener); - BTUtils.println(System.err, "****** EOL Removed ChangedAdapterSetCallback " + count); + PrintUtil.println(System.err, "****** EOL Removed ChangedAdapterSetCallback " + count); } public static void main(final String args[]) { |