summaryrefslogtreecommitdiffstats
path: root/java/direct_bt/tinyb/DBTGattCharacteristic.java
blob: bd7f0deabf33156d64e690256a8c5bae50a22a7d (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
/**
 * 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 direct_bt.tinyb;

import java.lang.ref.WeakReference;
import java.util.Arrays;
import java.util.List;

import org.tinyb.BluetoothException;
import org.tinyb.BluetoothGattCharacteristic;
import org.tinyb.BluetoothGattDescriptor;
import org.tinyb.BluetoothGattService;
import org.tinyb.BluetoothManager;
import org.tinyb.BluetoothNotification;
import org.tinyb.BluetoothType;
import org.tinyb.BluetoothUtils;
import org.tinyb.GATTCharacteristicListener;

public class DBTGattCharacteristic extends DBTObject implements BluetoothGattCharacteristic
{
    private static final boolean DEBUG = DBTManager.DEBUG;

    /** Characteristics's service weak back-reference */
    final WeakReference<DBTGattService> wbr_service;

    /**
     * Characteristic Handle of this instance.
     * <p>
     * Attribute handles are unique for each device (server) (BT Core Spec v5.2: Vol 3, Part F Protocol..: 3.2.2 Attribute Handle).
     * </p>
     */
    private final short handle;

    /* Characteristics Property */
    private final String[] properties;
    // private final boolean hasNotify;
    // private final boolean hasIndicate;

    /* Characteristics Value Type UUID */
    private final String value_type_uuid;

    /**
     * Characteristics Value Handle.
     * <p>
     * Attribute handles are unique for each device (server) (BT Core Spec v5.2: Vol 3, Part F Protocol..: 3.2.2 Attribute Handle).
     * </p>
     */
    private final short value_handle;

    /* Optional Client Characteristic Configuration index within descriptorList */
    private final int clientCharacteristicsConfigIndex;

    private final List<BluetoothGattDescriptor> descriptorList;

    private byte[] cachedValue = null;
    private BluetoothNotification<byte[]> valueNotificationCB = null;

    private boolean updateCachedValue(final byte[] value, final boolean notify) {
        boolean valueChanged = false;
        if( null == cachedValue || cachedValue.length != value.length ) {
            cachedValue = new byte[value.length];
            valueChanged = true;
        } else if( !Arrays.equals(value, cachedValue) ) {
            valueChanged = true;
        }
        if( valueChanged ) {
            System.arraycopy(value, 0, cachedValue, 0, value.length);
            if( notify && null != valueNotificationCB ) {
                valueNotificationCB.run(cachedValue);
            }
        }
        return valueChanged;
    }

    private final GATTCharacteristicListener characteristicListener = new GATTCharacteristicListener() {

        @Override
        public void notificationReceived(final BluetoothGattCharacteristic charDecl, final byte[] value, final long timestamp) {
            final DBTGattCharacteristic cd = (DBTGattCharacteristic)charDecl;
            if( !cd.equals(DBTGattCharacteristic.this) ) {
                throw new InternalError("Filtered GATTCharacteristicListener.notificationReceived: Wrong Characteristic: Got "+charDecl+
                                        ", expected "+DBTGattCharacteristic.this.toString());
            }
            final boolean valueChanged = updateCachedValue(value, true);
            if( DEBUG ) {
                System.err.println("GATTCharacteristicListener.notificationReceived: "+charDecl+
                                   ", value[changed "+valueChanged+", data "+BluetoothUtils.bytesHexString(value, true, true)+"]");
            }
        }

        @Override
        public void indicationReceived(final BluetoothGattCharacteristic charDecl, final byte[] value, final long timestamp,
                                       final boolean confirmationSent) {
            final DBTGattCharacteristic cd = (DBTGattCharacteristic)charDecl;
            if( !cd.equals(DBTGattCharacteristic.this) ) {
                throw new InternalError("Filtered GATTCharacteristicListener.indicationReceived: Wrong Characteristic: Got "+charDecl+
                                        ", expected "+DBTGattCharacteristic.this.toString());
            }
            final boolean valueChanged = updateCachedValue(value, true);
            if( DEBUG ) {
                System.err.println("GATTCharacteristicListener.indicationReceived: "+charDecl+
                                   ", value[changed "+valueChanged+", data "+BluetoothUtils.bytesHexString(value, true, true)+"]");
            }
        }

    };

   /* pp */ DBTGattCharacteristic(final long nativeInstance, final DBTGattService service,
                                  final short handle, final String[] properties,
                                  final String value_type_uuid, final short value_handle,
                                  final int clientCharacteristicsConfigIndex)
    {
        super(nativeInstance, handle /* hash */);
        this.wbr_service = new WeakReference<DBTGattService>(service);
        this.handle = handle;

        this.properties = properties;
        /** {
            boolean hasNotify = false;
            boolean hasIndicate = false;
            for(int i=0; !hasNotify && !hasIndicate && i<properties.length; i++) {
                if( "notify".equals(properties[i]) ) {
                    hasNotify = true;
                }
                if( "indicate".equals(properties[i]) ) {
                    hasIndicate = true;
                }
            }
            this.hasNotify = hasNotify;
            this.hasIndicate = hasIndicate;
        } */

        this.value_type_uuid = value_type_uuid;
        this.value_handle = value_handle;
        this.clientCharacteristicsConfigIndex = clientCharacteristicsConfigIndex;
        this.descriptorList = getDescriptorsImpl();
        this.addCharacteristicListener(characteristicListener, false); // silent, don't enable native GATT ourselves
    }

    @Override
    public synchronized void close() {
        if( !isValid() ) {
            return;
        }
        removeAllCharacteristicListener();
        disableValueNotifications();
        super.close();
    }

    @Override
    public boolean equals(final Object obj)
    {
        if (obj == null || !(obj instanceof DBTGattCharacteristic)) {
            return false;
        }
        final DBTGattCharacteristic other = (DBTGattCharacteristic)obj;
        return handle == other.handle; /** unique attribute handles */
    }

    @Override
    public String getUUID() { return value_type_uuid; }

    @Override
    public BluetoothType getBluetoothType() { return class_type(); }

    static BluetoothType class_type() { return BluetoothType.GATT_CHARACTERISTIC; }

    @Override
    public BluetoothGattCharacteristic clone()
    { throw new UnsupportedOperationException(); } // FIXME

    @Override
    public BluetoothGattDescriptor find(final String UUID, final long timeoutMS) {
        final BluetoothManager manager = DBTManager.getBluetoothManager();
        return (BluetoothGattDescriptor) manager.find(BluetoothType.GATT_DESCRIPTOR,
                null, UUID, this, timeoutMS);
    }

    @Override
    public BluetoothGattDescriptor find(final String UUID) {
        return find(UUID, 0);
    }

    @Override
    public final BluetoothGattService getService() { return wbr_service.get(); }

    @Override
    public final String[] getFlags() { return properties; }

    @Override
    public final byte[] getValue() { return cachedValue; }

    @Override
    public final byte[] readValue() throws BluetoothException {
        final byte[] value = readValueImpl();
        updateCachedValue(value, true);
        return cachedValue;
    }

    @Override
    public final boolean writeValue(final byte[] value) throws BluetoothException {
        final boolean res = writeValueImpl(value);
        if( res ) {
            updateCachedValue(value, false);
        }
        return res;
    }

    @Override
    public final List<BluetoothGattDescriptor> getDescriptors() { return descriptorList; }

    @Override
    public final synchronized void enableValueNotifications(final BluetoothNotification<byte[]> callback) {
        final boolean res = enableValueNotificationsImpl(true);
        if( DEBUG ) {
            System.err.println("GATTCharacteristicListener.enableValueNotifications: GATT Native: "+res);
        }
        valueNotificationCB = callback;
    }

    @Override
    public final synchronized void disableValueNotifications() {
        final boolean res = enableValueNotificationsImpl(false);
        if( DEBUG ) {
            System.err.println("GATTCharacteristicListener.disableValueNotifications: GATT Native: "+res);
        }
        valueNotificationCB = null;
    }

    @Override
    public final boolean getNotifying() {
        return null != valueNotificationCB;
    }

    @Override
    public final boolean addCharacteristicListener(final GATTCharacteristicListener listener) {
        return addCharacteristicListener(listener, true);
    }
    private final boolean addCharacteristicListener(final GATTCharacteristicListener listener, final boolean nativeEnable) {
        if( nativeEnable ) {
            final boolean res = enableValueNotificationsImpl(true);
            if( DEBUG ) {
                System.err.println("GATTCharacteristicListener.addCharacteristicListener: GATT Native: "+res);
            }
        }
        return getService().getDevice().addCharacteristicListener(listener, this);
    }

    @Override
    public final boolean removeCharacteristicListener(final GATTCharacteristicListener l) {
        return getService().getDevice().removeCharacteristicListener(l);
    }

    @Override
    public final int removeAllCharacteristicListener() {
        return getService().getDevice().removeAllCharacteristicListener();
    }

    /**
     * Characteristic Handle of this instance.
     * <p>
     * Attribute handles are unique for each device (server) (BT Core Spec v5.2: Vol 3, Part F Protocol..: 3.2.2 Attribute Handle).
     * </p>
     */
    public final short getHandle() { return handle; }

    /**
     * Returns Characteristics Value Handle.
     * <p>
     * Attribute handles are unique for each device (server) (BT Core Spec v5.2: Vol 3, Part F Protocol..: 3.2.2 Attribute Handle).
     * </p>
     */
    public final short getValueHandle() { return value_handle; }

    /** Returns optional Client Characteristic Configuration index within descriptorList */
    public final int getClientCharacteristicsConfigIndex() { return clientCharacteristicsConfigIndex; }

    @Override
    public final String toString() {
        if( !isValid() ) {
            return "Characteristic" + "\u271D" + "[handle 0x"+Integer.toHexString(handle)+"]";
        }
        return toStringImpl();
    }

    /* Native method calls: */

    private native String toStringImpl();

    private native byte[] readValueImpl() throws BluetoothException;

    private native boolean writeValueImpl(byte[] argValue) throws BluetoothException;

    private native List<BluetoothGattDescriptor> getDescriptorsImpl();

    /**
     * Enables disables GATT notification and/or indication.
     */
    private native boolean enableValueNotificationsImpl(boolean v);

    @Override
    protected native void deleteImpl(long nativeInstance);

}