summaryrefslogtreecommitdiffstats
path: root/java/jau/direct_bt/DBTManager.java
blob: dfc332f927c1f7e198e526dd45d64cef067e0905 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
/**
 * Author: Sven Gothel <sgothel@jausoft.com>
 * 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.
 */

package jau.direct_bt;

import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;
import java.util.function.Predicate;

import org.direct_bt.BTAdapter;
import org.direct_bt.BTException;
import org.direct_bt.BTFactory;
import org.direct_bt.BTManager;

public class DBTManager implements BTManager
{
    protected static final boolean DEBUG = BTFactory.DEBUG;
    protected static final boolean VERBOSE = BTFactory.VERBOSE;

    private static volatile boolean isJVMShuttingDown = false;
    private static final List<Runnable> userShutdownHooks = new ArrayList<Runnable>();

    static {
        BTFactory.doPrivileged(new PrivilegedAction<Object>() {
            @Override
            public Object run() {
                Runtime.getRuntime().addShutdownHook(
                    new Thread(null, new Runnable() {
                                @Override
                                public void run() {
                                    DBTManager.shutdownImpl(true);
                                } }, "DBTManager_ShutdownHook" ) ) ;
                if(DEBUG) {
                    System.err.println("DBTManager.init(): JVM ShutdownHook installed, on thread "+Thread.currentThread().getName());
                }
                return null;
            } } ) ;
    }

    private static synchronized void shutdownImpl(final boolean _isJVMShuttingDown) {
        isJVMShuttingDown = _isJVMShuttingDown;
        if(DEBUG) {
            System.err.println("DBTManager.shutdown() START: JVM ShutdownHook "+isJVMShuttingDown+", on thread "+Thread.currentThread().getName());
        }
        synchronized(userShutdownHooks) {
            final int cshCount = userShutdownHooks.size();
            for(int i=0; i < cshCount; i++) {
                try {
                    if( DEBUG ) {
                        System.err.println("DBTManager.shutdown - userShutdownHook #"+(i+1)+"/"+cshCount);
                    }
                    userShutdownHooks.get(i).run();
                } catch(final Throwable t) {
                    System.err.println("DBTManager.shutdown: Caught "+t.getClass().getName()+" during userShutdownHook #"+(i+1)+"/"+cshCount);
                    if( DEBUG ) {
                        t.printStackTrace();
                    }
                }
            }
            userShutdownHooks.clear();
        }
        if(DEBUG) {
            System.err.println("DBTManager.shutdown(): Post userShutdownHook");
        }

        try {
            final BTManager mgmt = getManager();
            mgmt.shutdown();
        } catch(final Throwable t) {
            System.err.println("DBTManager.shutdown: Caught "+t.getClass().getName()+" during DBTManager.shutdown()");
            if( DEBUG ) {
                t.printStackTrace();
            }
        }

        if(DEBUG) {
            System.err.println(Thread.currentThread().getName()+" - DBTManager.shutdown() END JVM Shutdown "+isJVMShuttingDown);
        }
    }

    /** Returns true if the JVM is shutting down, otherwise false. */
    public static final boolean isJVMShuttingDown() { return isJVMShuttingDown; }

    /**
     * Add a shutdown hook to be performed at JVM shutdown before shutting down DBTManager instance.
     *
     * @param head if true add runnable at the start, otherwise at the end
     * @param runnable runnable to be added.
     */
    public static final void addShutdownHook(final boolean head, final Runnable runnable) {
        synchronized( userShutdownHooks ) {
            if( !userShutdownHooks.contains( runnable ) ) {
                if( head ) {
                    userShutdownHooks.add(0, runnable);
                } else {
                    userShutdownHooks.add( runnable );
                }
            }
        }
    }

    private long nativeInstance;
    private final List<BTAdapter> adapters = new CopyOnWriteArrayList<BTAdapter>();
    private final List<ChangedAdapterSetListener> changedAdapterSetListenerList = new CopyOnWriteArrayList<ChangedAdapterSetListener>();

    @Override
    public final List<BTAdapter> getAdapters() { return new ArrayList<BTAdapter>(adapters); }

    @Override
    public final BTAdapter getAdapter(final int dev_id) {
        for(final Iterator<BTAdapter> iter = adapters.iterator(); iter.hasNext(); ) {
            final BTAdapter a = iter.next();
            if( dev_id == a.getDevID() ) {
                return a;
            }
        }
        return null;
    }

    @Override
    public final boolean setDefaultAdapter(final BTAdapter adapter) {
        return false;
    }

    @Override
    public final BTAdapter getDefaultAdapter() {
        for(final Iterator<BTAdapter> iter = adapters.iterator(); iter.hasNext(); ) {
            final BTAdapter a = iter.next();
            if( a.isPowered() ) {
                return a;
            }
        }
        return null;
    }

    @Override
    public final void addChangedAdapterSetListener(final ChangedAdapterSetListener l) {
        changedAdapterSetListenerList.add(l);

        adapters.forEach(new Consumer<BTAdapter>() {
            @Override
            public void accept(final BTAdapter adapter) {
                l.adapterAdded(adapter);
            }
        });
    }

    @Override
    public final int removeChangedAdapterSetListener(final ChangedAdapterSetListener l) {
        // Using removeIf allows performing test on all object and remove within one write-lock cycle
        final int count[] = { 0 };
        changedAdapterSetListenerList.removeIf(new Predicate<ChangedAdapterSetListener>() {
            @Override
            public boolean test(final ChangedAdapterSetListener t) {
                if( t.equals(l) ) {
                    count[0]++;
                    return true;
                }
                return false;
            }
        });
        return count[0];
    }

    private native List<BTAdapter> getAdapterListImpl();
    private native BTAdapter getAdapterImpl(int dev_id);

    /**
     * Removal entry for DBTAdapter.close()
     * @param adapter ref to the close'ed adapter
     * @return true if contained and removed, otherwise false
     */
    /* pp */ final boolean removeAdapter(final DBTAdapter adapter) {
        if( adapters.remove(adapter) ) {
            if( DEBUG ) {
                System.err.println("DBTManager.removeAdapter: Removed "+adapter);
            }
            return true;
        } else {
            if( DEBUG ) {
                System.err.println("DBTManager.removeAdapter: Not found "+adapter);
            }
            return false;
        }
    }

    /** callback from native adapter remove */
    /* pp */ final void removeAdapterCB(final int dev_id, final int opc_reason) {
        final BTAdapter[] removed = { null };
        final int count[] = { 0 };
        adapters.removeIf(new Predicate<BTAdapter>() {
            @Override
            public boolean test(final BTAdapter a) {
                if( 0 == count[0] && dev_id == a.getDevID() ) {
                    removed[0] = a;
                    count[0]++;
                    return true;
                } else {
                    return false;
                }
            }
        });
        if( null != removed[0] ) {
            if( DEBUG ) {
                System.err.println("DBTManager.removeAdapterCB[dev_id "+dev_id+", opc 0x"+Integer.toHexString(opc_reason)+
                        "]: removing "+removed[0].toString());
            }
            if( 0x0005 == opc_reason ) {
                // MgmtEvent::Opcode::INDEX_REMOVED = 0x0005
                changedAdapterSetListenerList.forEach(new Consumer<ChangedAdapterSetListener>() {
                    @Override
                    public void accept(final ChangedAdapterSetListener t) {
                        t.adapterRemoved( removed[0] );
                    } } );
            }
            removed[0] = null; // DBTAdapter::close() issued by DBTManager after all callbacks
        }
        if( DEBUG ) {
            System.err.println("DBTManager.removeAdapterCB[dev_id "+dev_id+", opc 0x"+Integer.toHexString(opc_reason)+
                    "]: removed "+count[0]+" adapter, size "+adapters.size());
        }
    }
    /** callback from native adapter add or POWERED on */
    private final void updatedAdapterCB(final int dev_id, final int opc_reason) {
        final BTAdapter preInstance = getAdapter(dev_id);
        if( null != preInstance ) {
            if( DEBUG ) {
                System.err.println("DBTManager.updatedAdapterCB[dev_id "+dev_id+", opc 0x"+Integer.toHexString(opc_reason)+
                        "]: existing "+preInstance.toString()+", size "+adapters.size());
            }
            return;
        }
        final BTAdapter newInstance = getAdapterImpl(dev_id);
        if( null == newInstance ) {
            if( DEBUG ) {
                System.err.println("DBTManager.updatedAdapterCB[dev_id "+dev_id+", opc 0x"+Integer.toHexString(opc_reason)+
                        "]: Adapter not found, size "+adapters.size());
            }
            return;
        }
        final boolean added = adapters.add(newInstance);
        if( DEBUG ) {
            System.err.println("DBTManager.updatedAdapterCB[dev_id "+dev_id+", opc 0x"+Integer.toHexString(opc_reason)+
                    "]: added "+added+": new "+newInstance.toString()+", size "+adapters.size());
        }
        if( added && 0x0004 == opc_reason ) {
            // MgmtEvent::Opcode::INDEX_ADDED = 0x0004
            changedAdapterSetListenerList.forEach(new Consumer<ChangedAdapterSetListener>() {
                @Override
                public void accept(final ChangedAdapterSetListener t) {
                    t.adapterAdded(newInstance);
                } } );
        }
    }

    private native void initImpl() throws BTException;
    private native void deleteImpl(long nativeInstance);
    private DBTManager()
    {
        initImpl();
        try {
            adapters.addAll(getAdapterListImpl());
        } catch (final BTException be) {
            be.printStackTrace();
        }
    }

    /** Returns an instance of BluetoothManager, to be used instead of constructor.
      * @return An initialized BluetoothManager instance.
      */
    public static final BTManager getManager() throws RuntimeException, BTException {
        return LazySingletonHolder.singleton;
    }
    /** Initialize-On-Demand Holder Class, similar to C++11's "Magic Statics". */
    private static class LazySingletonHolder {
        private static final DBTManager singleton = new DBTManager();
    }

    @Override
    protected final void finalize() {
        shutdown();
    }

    @Override
    public final void shutdown() {
        for(final Iterator<BTAdapter> ia= adapters.iterator(); ia.hasNext(); ) {
            final DBTAdapter a = (DBTAdapter)ia.next();
            a.close();
        }
        adapters.clear();
        deleteImpl(nativeInstance);
    }
}