summaryrefslogtreecommitdiffstats
path: root/java/org/direct_bt/BTGattCmd.java
blob: d6c962968866e53d30ba1af8912214700d63d464 (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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
/**
 * Author: Sven Gothel <sgothel@jausoft.com>
 * Copyright (c) 2021 Gothel Software e.K.
 * Copyright (c) 2021 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 org.direct_bt;

/**
 * Class maps a GATT command and optionally its asynchronous response
 * to a synchronous atomic operation.
 *
 * The GATT command is issued by writing the associated GATT characteristic value
 * via BTGattChar.writeValueNoResp() or BTGattChar.writeValue().
 *
 * Its optional asynchronous characteristic value notification or indication response
 * is awaited and collected after command issuance.
 *
 * If a response jau.uuid_t is given, notification or indication will be enabled at first send() command
 * and disabled at close() or destruction.
 *
 * @see BTGattChar.writeValueNoResp()
 * @see BTGattChar.writeValue()
 * @since 2.4.0
 */
public class BTGattCmd implements AutoCloseable
{
    private static final boolean DEBUG = BTFactory.DEBUG;

    /** Name, representing the command */
    private final String name;
    /** Command's BTGattService jau.uuid_t, may be null. */
    private final String service_uuid;
    /** Command's BTGattChar value jau.uuid_t to write command, never null. */
    private final String cmd_uuid;
    /** Command's optional BTGattChar value jau.uuid_t for the notification or indication response, may be null. */
    private final String rsp_uuid;

    private final Object mtxRspReceived = new Object();
    private final BTDevice dev;
    private volatile byte[] rsp_data;
    private BTGattChar cmdCharRef;
    private BTGattChar rspCharRef;
    private boolean setup_done;

    private static class ResponseCharListener implements BTGattChar.Listener {
        private final BTGattCmd source;

        public ResponseCharListener(final BTGattCmd source_) {
            source = source_;
        }

        @Override
        public void notificationReceived(final BTGattChar charDecl,
                                         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 */));
                }
                source.rsp_data = value;
                source.mtxRspReceived.notifyAll();
            }
        }

        @Override
        public void indicationReceived(final BTGattChar charDecl,
                                       final byte[] value, final long timestamp,
                                       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 */));
                }
                source.rsp_data = value;
                source.mtxRspReceived.notifyAll();
            }
        }
    }
    private final ResponseCharListener rspCharListener;
    private BTGattCharListener addedRspCharListener;
    private boolean verbose;

    private boolean isConnected() { return dev.getConnected(); }

    private boolean isResolvedEq() {
        return null != cmdCharRef;
    }

    private String rspCharStr() { return null != rspCharRef ? rspCharRef.toString() : "n/a"; }

    private HCIStatusCode setup() {
        if( setup_done ) {
            return isResolvedEq() ? HCIStatusCode.SUCCESS : HCIStatusCode.NOT_SUPPORTED;
        }
        setup_done = true;
        cmdCharRef = null != service_uuid ? dev.findGattChar(service_uuid, cmd_uuid)
                                          : 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);
            }
            return HCIStatusCode.NOT_SUPPORTED;
        }

        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());
            }
            cmdCharRef = null;
            return HCIStatusCode.NOT_SUPPORTED;
        }

        if( null != rsp_uuid ) {
            rspCharRef = null != service_uuid ? dev.findGattChar(service_uuid, rsp_uuid)
                                              : 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);
                }
                cmdCharRef = null;
                return HCIStatusCode.NOT_SUPPORTED;
            }
            try {
                final boolean cccdEnableResult[] = { false, false };
                addedRspCharListener = rspCharRef.addCharListener( rspCharListener, cccdEnableResult );
                if( null != addedRspCharListener ) {
                    return HCIStatusCode.SUCCESS;
                } else {
                    if( verbose ) {
                        BTUtils.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());
                cmdCharRef = null;
                rspCharRef = null;
                addedRspCharListener = null;
                return HCIStatusCode.TIMEOUT;
            }
        } else {
            return HCIStatusCode.SUCCESS;
        }
    }

    /**
     * Close this command instance, usually called at destruction.
     * <p>
     * If a response jau.uuid_t has been given, notification or indication will be disabled.
     * </p>
     * {@inheritDoc}
     */
    @Override
    public void close() {
        close0();
    }

    /**
     * Close this command instance, usually called at destruction.
     *
     * If a response jau.uuid_t has been given, notification or indication will be disabled.
     */
    public synchronized HCIStatusCode close0() {
        final boolean wasResolved = isResolvedEq();
        final BTGattChar rspCharRefCopy = rspCharRef;
        final BTGattCharListener addedRspCharListenerCopy = addedRspCharListener;
        cmdCharRef = null;
        rspCharRef = null;
        addedRspCharListener = null;
        if( !setup_done ) {
            return HCIStatusCode.SUCCESS;
        }
        setup_done = false;
        if( !wasResolved ) {
            return HCIStatusCode.SUCCESS;
        }
        if( !isConnected() ) {
            return HCIStatusCode.DISCONNECTED;
        }
        if( null != addedRspCharListenerCopy && null != rspCharRefCopy) {
            try {
                final boolean res1 = rspCharRefCopy.removeCharListener(addedRspCharListenerCopy);
                final boolean res2 = rspCharRefCopy.disableIndicationNotification();
                if( res1 && res2 ) {
                    return HCIStatusCode.SUCCESS;
                } else {
                    return HCIStatusCode.FAILED;
                }
            } catch (final Exception e ) {
                BTUtils.fprintf_td(System.err, "Exception caught for %s: %s\n", e.toString(), toString());
                return HCIStatusCode.TIMEOUT;
            }
        } else {
            return HCIStatusCode.SUCCESS;
        }
    }

    /**
     * Constructor for commands with notification or indication response.
     *
     * @param dev_ the remote BTDevice
     * @param name_ user given name, representing the command
     * @param service_uuid_ command's BTGattService jau.uuid_t, may be null for using a less efficient BTGattChar lookup
     * @param cmd_uuid_ command's BTGattChar value jau.uuid_t to write the command
     * @param rsp_uuid_ command's BTGattChar value jau.uuid_t for the notification or indication response.
     */
    public BTGattCmd(final BTDevice dev_, final String name_,
                     final String service_uuid_, final String cmd_uuid_, final String rsp_uuid_ )
    {
        name = name_;
        service_uuid = service_uuid_;
        cmd_uuid = cmd_uuid_;
        rsp_uuid = rsp_uuid_;
        dev = dev_;
        rsp_data = null;
        cmdCharRef = null;
        rspCharRef = null;
        setup_done = false;
        rspCharListener = new ResponseCharListener(this);
        addedRspCharListener = null;
        verbose = DEBUG;
    }

    /**
     * Constructor for commands without response.
     *
     * @param dev_ the remote BTDevice
     * @param name_ user given name, representing the command
     * @param service_uuid_ command's BTGattService jau.uuid_t, may be null for using a less efficient BTGattChar lookup
     * @param cmd_uuid_ command's BTGattChar value jau.uuid_t to write the command
     */
    public BTGattCmd(final BTDevice dev_, final String name_, final String service_uuid_, final String cmd_uuid_)
    {
        name = name_;
        service_uuid = service_uuid_;
        cmd_uuid = cmd_uuid_;
        rsp_uuid = null;
        dev = dev_;
        rsp_data = null;
        cmdCharRef = null;
        rspCharRef = null;
        setup_done = false;
        rspCharListener = null;
        addedRspCharListener = null;
        verbose = DEBUG;
    }

    @Override
    public void finalize() { close(); }

    /** Return name, representing the command */
    public String getName() { return name; }

    /** Return command's BTGattService jau::uuid_t, may be null. */
    public String getServiceUUID() { return service_uuid; }

    /** Return command's BTGattChar value jau::uuid_t to write command, never null. */
    public String getCommandUUID() { return cmd_uuid; }

    /** Return true if a notification or indication response has been set via constructor, otherwise false. */
    public boolean hasResponseSet() { return null != rsp_uuid; }

    /** Return command's optional BTGattChar value jau::uuid_t for the notification or indication response, may be null. */
    public String getResponseUUID() { return rsp_uuid; }

    /** Set verbosity for UUID resolution. */
    public void setVerbose(final boolean v) { verbose = v; }

    /**
     * Returns the read-only response data object
     * for configured commands with response notification or indication.
     *
     * jau.TROOctets.size() matches the size of last received command response or zero.
     * @see #send(boolean, byte[], int)
     */
    public byte[] getResponse() { return rsp_data; }

    private String rspDataToString() {
        return null == rsp_data ? "null" : BTUtils.bytesHexString(rsp_data, 0, rsp_data.length, true /* lsbFirst */);
    }

    /**
     * Query whether all UUIDs of this commands have been resolved.
     *
     * In case no command has been issued via send() yet,
     * the UUIDs will be resolved with this call.
     *
     * @return true if all UUIDs have been resolved, otherwise false
     */
    public synchronized boolean isResolved() {
        if( !setup_done ) {
            return HCIStatusCode.SUCCESS == setup();
        } else {
            return isResolvedEq();
        }
    }

    /**
     * Send the command to the remote BTDevice.
     *
     * If a notification or indication result jau.uuid_t has been set via constructor,
     * it will be awaited and can be retrieved via {@link #getResponse()} after command returns.
     *
     * @param prefNoAck pass true to prefer command write without acknowledge, otherwise use with-ack if available
     * @param cmd_data raw command octets
     * @param timeoutMS timeout in milliseconds. Defaults to 10 seconds limited blocking for the response to become available, if any.
     * @return
     * @see #getResponse()
     */
    public synchronized HCIStatusCode send(final boolean prefNoAck, final byte[] cmd_data, final int timeoutMS) {
        HCIStatusCode res = HCIStatusCode.SUCCESS;

        if( !isConnected() ) {
            return HCIStatusCode.DISCONNECTED;
        }
        synchronized( mtxRspReceived ) {
            res = setup();
            if( HCIStatusCode.SUCCESS != res ) {
                return res;
            }
            rsp_data = null;

            if( DEBUG ) {
                BTUtils.fprintf_td(System.err, "BTGattCmd.sendBlocking: Start: Cmd %s, args[%s], Resp %s, result[%s]",
                        cmdCharRef.toString(), cmd_data.toString(),
                        rspCharStr(), rspDataToString());
            }

            final boolean hasWriteNoAck = cmdCharRef.getProperties().isSet(GattCharPropertySet.Type.WriteNoAck);
            final boolean hasWriteWithAck = cmdCharRef.getProperties().isSet(GattCharPropertySet.Type.WriteWithAck);
            // Prefer WriteNoAck, if hasWriteNoAck and ( prefNoAck -or- !hasWriteWithAck )
            final boolean prefWriteNoAck = hasWriteNoAck && ( prefNoAck || !hasWriteWithAck );

            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 */));
                        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());
                    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 */));
                        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());
                    res = HCIStatusCode.TIMEOUT;
                }
            } else {
                BTUtils.fprintf_td(System.err, "Command has no write property: %s\n", cmdCharRef.toString());
                res = HCIStatusCode.FAILED;
            }

            if( null != rspCharRef ) {
                while( HCIStatusCode.SUCCESS == res && null == rsp_data ) {
                    if( 0 == timeoutMS ) {
                        try {
                            mtxRspReceived.wait();
                        } catch (final InterruptedException e) { }
                    } else {
                        try {
                            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 */));
                            res = HCIStatusCode.TIMEOUT;
                        }
                    }
                }
            }
        } // 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 */),
                    rspCharStr(), rspDataToString());
        }
        return res;
    }

    /**
     * Send the command to the remote BTDevice.
     *
     * If a notification or indication result jau.uuid_t has been set via constructor,
     * it will be awaited and can be retrieved via getResponse() after command returns.
     *
     * If using a response, this variant uses a 10 second default timeout to limit blocking until the response becomes available.
     *
     * @param prefNoAck pass true to prefer command write without acknowledge, otherwise use default preferrence
     * @param cmd_data raw command octets
     * @return
     */
    public HCIStatusCode send(final boolean prefNoAck, final byte[] cmd_data) {
        return send(prefNoAck, cmd_data, 10000 /* timeoutMS */);
    }

    @Override
    public String toString() {
        return "BTGattCmd["+dev.getName()+":"+name+", service "+service_uuid+
               ", char[cmd "+cmd_uuid+", rsp "+rsp_uuid+
               ", set["+setup_done+", resolved "+isResolvedEq()+"]]]";
    }
}