From 3888d7726a9db5918de644e6a6ee5ba938fb0727 Mon Sep 17 00:00:00 2001 From: Thad House Date: Tue, 6 Sep 2016 21:30:59 -0700 Subject: [PATCH] Adds connection listeners that can be called statically (#111) This way you can have a connection listener before initializing NetworkTables. --- .../wpilibj/networktables/NetworkTable.java | 39 ++++++++++++++++++- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/java/src/edu/wpi/first/wpilibj/networktables/NetworkTable.java b/java/src/edu/wpi/first/wpilibj/networktables/NetworkTable.java index 962780308f..b4650fae64 100644 --- a/java/src/edu/wpi/first/wpilibj/networktables/NetworkTable.java +++ b/java/src/edu/wpi/first/wpilibj/networktables/NetworkTable.java @@ -223,11 +223,11 @@ public class NetworkTable implements ITable, IRemote { return !client; } - private class ListenerBase { + private static class ListenerBase { public int uid; } - private class ConnectionListenerAdapter extends ListenerBase implements NetworkTablesJNI.ConnectionListenerFunction { + private static class ConnectionListenerAdapter extends ListenerBase implements NetworkTablesJNI.ConnectionListenerFunction { private final IRemote targetSource; private final IRemoteConnectionListener targetListener; @@ -243,6 +243,41 @@ public class NetworkTable implements ITable, IRemote { targetListener.disconnectedEx(targetSource, conn); } } + + private static IRemote staticRemote = new IRemote() { + public void addConnectionListener(IRemoteConnectionListener listener, boolean immediateNotify) { + NetworkTable.addGlobalConnectionListener(listener, immediateNotify); + } + public void removeConnectionListener(IRemoteConnectionListener listener) { + NetworkTable.removeGlobalConnectionListener(listener); + } + public boolean isConnected() { + ConnectionInfo[] conns = NetworkTablesJNI.getConnections(); + return conns.length > 0; + } + public boolean isServer() { + return !client; + } + }; + + private static final Hashtable globalConnectionListenerMap = new Hashtable(); + public static synchronized void addGlobalConnectionListener(IRemoteConnectionListener listener, + boolean immediateNotify) { + ConnectionListenerAdapter adapter = globalConnectionListenerMap.get(listener); + if (adapter != null) + throw new IllegalStateException("Cannot add the same listener twice"); + adapter = new ConnectionListenerAdapter(staticRemote, listener); + adapter.uid = NetworkTablesJNI.addConnectionListener(adapter, immediateNotify); + globalConnectionListenerMap.put(listener, adapter); + } + + public static synchronized void removeGlobalConnectionListener(IRemoteConnectionListener listener) { + ConnectionListenerAdapter adapter = globalConnectionListenerMap.get(listener); + if (adapter != null) { + NetworkTablesJNI.removeConnectionListener(adapter.uid); + globalConnectionListenerMap.remove(listener); + } + } private final Hashtable connectionListenerMap = new Hashtable(); public synchronized void addConnectionListener(IRemoteConnectionListener listener,