wangzhibo
4 天以前 ae6f40460dcd56af6c5f60ba52c883854c3bac55
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
/*  Copyright (C) 2023 José Rebelo, Yoran Vulker
 
    This file is part of Gadgetbridge.
 
    Gadgetbridge is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
 
    Gadgetbridge is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.
 
    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
package nodomain.freeyourgadget.gadgetbridge.service.devices.xiaomi;
 
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.widget.Toast;
 
import androidx.annotation.Nullable;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.util.Map;
import java.util.Set;
import java.util.UUID;
 
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.proto.xiaomi.XiaomiProto;
import nodomain.freeyourgadget.gadgetbridge.service.btle.AbstractBTLEDeviceSupport;
import nodomain.freeyourgadget.gadgetbridge.service.btle.BtLEQueue;
import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder;
import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.PlainAction;
import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.SetDeviceStateAction;
import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.SetProgressAction;
import nodomain.freeyourgadget.gadgetbridge.util.GB;
 
public class XiaomiBleSupport extends XiaomiConnectionSupport {
    private static final Logger LOG = LoggerFactory.getLogger(XiaomiBleSupport.class);
 
    private XiaomiCharacteristic characteristicCommandRead;
    private XiaomiCharacteristic characteristicCommandWrite;
    private XiaomiCharacteristic characteristicActivityData;
    private XiaomiCharacteristic characteristicDataUpload;
 
    private final XiaomiSupport mXiaomiSupport;
 
    final AbstractBTLEDeviceSupport commsSupport = new AbstractBTLEDeviceSupport(LOG) {
        @Override
        public boolean useAutoConnect() {
            return mXiaomiSupport.useAutoConnect();
        }
 
        @Override
        protected Set<UUID> getSupportedServices() {
            return XiaomiUuids.BLE_UUIDS.keySet();
        }
 
        @Override
        public boolean getAutoReconnect() {
            return mXiaomiSupport.getAutoReconnect();
        }
 
        @Override
        protected TransactionBuilder initializeDevice(final TransactionBuilder builder) {
            XiaomiUuids.XiaomiBleUuidSet uuidSet = null;
            BluetoothGattCharacteristic btCharacteristicCommandRead = null;
            BluetoothGattCharacteristic btCharacteristicCommandWrite = null;
            BluetoothGattCharacteristic btCharacteristicActivityData = null;
            BluetoothGattCharacteristic btCharacteristicDataUpload = null;
 
            // Attempt to find a known xiaomi service
            for (Map.Entry<UUID, XiaomiUuids.XiaomiBleUuidSet> xiaomiUuid : XiaomiUuids.BLE_UUIDS.entrySet()) {
                final XiaomiUuids.XiaomiBleUuidSet currentUuidSet = xiaomiUuid.getValue();
                UUID currentChar;
 
                if ((currentChar = currentUuidSet.getCharacteristicCommandRead()) == null ||
                        (btCharacteristicCommandRead = getCharacteristic(currentChar)) == null) {
                    continue;
                }
 
                if ((currentChar = currentUuidSet.getCharacteristicCommandWrite()) == null ||
                        (btCharacteristicCommandWrite = getCharacteristic(currentChar)) == null) {
                    continue;
                }
 
                if ((currentChar = currentUuidSet.getCharacteristicActivityData()) == null ||
                        (btCharacteristicActivityData = getCharacteristic(currentChar)) == null) {
                    continue;
                }
 
                if ((currentChar = currentUuidSet.getCharacteristicDataUpload()) == null ||
                        (btCharacteristicDataUpload= getCharacteristic(currentChar)) == null) {
                    LOG.warn("btCharacteristicDataUpload characteristic is null");
                    // this characteristic may not be supported by all models
                }
 
                LOG.debug("Found Xiaomi service: {}", xiaomiUuid.getKey());
                uuidSet = xiaomiUuid.getValue();
 
                break;
            }
 
            if (uuidSet == null) {
                GB.toast(getContext(), "Failed to find known Xiaomi service", Toast.LENGTH_LONG, GB.ERROR);
                LOG.warn("Failed to find known Xiaomi service");
                builder.add(new SetDeviceStateAction(getDevice(), GBDevice.State.NOT_CONNECTED, getContext()));
                return builder;
            }
 
            // FIXME unsetDynamicState unsets the fw version, which causes problems..
            if (getDevice().getFirmwareVersion() == null) {
                getDevice().setFirmwareVersion(mXiaomiSupport.getCachedFirmwareVersion() != null ?
                        mXiaomiSupport.getCachedFirmwareVersion() :
                        "N/A");
            }
 
            if (btCharacteristicCommandRead == null || btCharacteristicCommandWrite == null) {
                LOG.warn("Characteristics are null, will attempt to reconnect");
                builder.add(new SetDeviceStateAction(getDevice(), GBDevice.State.WAITING_FOR_RECONNECT, getContext()));
                return builder;
            }
 
            // FIXME:
            // Because the first handshake packet is sent before the actions in the builder are run,
            // the maximum message size is not properly initialized if the device itself does not request
            // the MTU to be upgraded. However, since we will upgrade the MTU ourselves to the highest
            // possible (512) and the device will (likely) respond with something higher than 247,
            // we will initialize the characteristics with that MTU.
            final int expectedMtu = 247;
            characteristicCommandRead = new XiaomiCharacteristic(XiaomiBleSupport.this, btCharacteristicCommandRead, mXiaomiSupport.getAuthService());
            characteristicCommandRead.setEncrypted(uuidSet.isEncrypted());
            characteristicCommandRead.setChannelHandler(mXiaomiSupport::handleCommandBytes);
            characteristicCommandRead.setMtu(expectedMtu);
            characteristicCommandWrite = new XiaomiCharacteristic(XiaomiBleSupport.this, btCharacteristicCommandWrite, mXiaomiSupport.getAuthService());
            characteristicCommandWrite.setEncrypted(uuidSet.isEncrypted());
            characteristicCommandWrite.setMtu(expectedMtu);
            characteristicActivityData = new XiaomiCharacteristic(XiaomiBleSupport.this, btCharacteristicActivityData, mXiaomiSupport.getAuthService());
            characteristicActivityData.setChannelHandler(mXiaomiSupport.getHealthService().getActivityFetcher()::addChunk);
            characteristicActivityData.setEncrypted(uuidSet.isEncrypted());
            characteristicActivityData.setMtu(expectedMtu);
            characteristicDataUpload = new XiaomiCharacteristic(XiaomiBleSupport.this, btCharacteristicDataUpload, mXiaomiSupport.getAuthService());
            characteristicDataUpload.setEncrypted(uuidSet.isEncrypted());
            characteristicDataUpload.setIncrementNonce(false);
            characteristicDataUpload.setMtu(expectedMtu);
 
            // request highest possible MTU; device should response with the highest supported MTU anyway
            builder.requestMtu(512);
            builder.add(new SetDeviceStateAction(getDevice(), GBDevice.State.INITIALIZING, getContext()));
            builder.notify(btCharacteristicCommandWrite, true);
            builder.notify(btCharacteristicCommandRead, true);
            builder.notify(btCharacteristicActivityData, true);
            builder.notify(btCharacteristicDataUpload, true);
            builder.add(new SetDeviceStateAction(getDevice(), GBDevice.State.AUTHENTICATING, getContext()));
 
            if (uuidSet.isEncrypted()) {
                builder.add(new PlainAction() {
                    @Override
                    public boolean run(BluetoothGatt gatt) {
                        mXiaomiSupport.getAuthService().startEncryptedHandshake();
                        return true;
                    }
                });
            } else {
                builder.add(new PlainAction() {
                    @Override
                    public boolean run(BluetoothGatt gatt) {
                        mXiaomiSupport.getAuthService().startClearTextHandshake();
                        return true;
                    }
                });
            }
 
            return builder;
        }
 
        @Override
        public boolean onCharacteristicChanged(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
            if (super.onCharacteristicChanged(gatt, characteristic)) {
                return true;
            }
 
            final UUID characteristicUUID = characteristic.getUuid();
            final byte[] value = characteristic.getValue();
 
            if (characteristicCommandRead.getCharacteristicUUID().equals(characteristicUUID)) {
                characteristicCommandRead.onCharacteristicChanged(value);
                return true;
            } else if (characteristicCommandWrite.getCharacteristicUUID().equals(characteristicUUID)) {
                characteristicCommandWrite.onCharacteristicChanged(value);
                return true;
            } else if (characteristicActivityData.getCharacteristicUUID().equals(characteristicUUID)) {
                characteristicActivityData.onCharacteristicChanged(value);
                return true;
            } else if (characteristicDataUpload.getCharacteristicUUID().equals(characteristicUUID)) {
                characteristicDataUpload.onCharacteristicChanged(value);
                return true;
            }
 
            LOG.warn("Unhandled characteristic changed: {} {}", characteristicUUID, GB.hexdump(value));
            return false;
        }
 
        @Override
        public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
            super.onMtuChanged(gatt, mtu, status);
 
            if (characteristicCommandRead != null)
                characteristicCommandRead.setMtu(mtu);
            if (characteristicCommandWrite != null)
                characteristicCommandWrite.setMtu(mtu);
            if (characteristicDataUpload != null)
                characteristicDataUpload.setMtu(mtu);
            if (characteristicActivityData != null)
                characteristicActivityData.setMtu(mtu);
        }
 
        @Override
        public void dispose() {
            mXiaomiSupport.onDisconnect();
            super.dispose();
        }
    };
 
    public XiaomiBleSupport(final XiaomiSupport xiaomiSupport) {
        this.mXiaomiSupport = xiaomiSupport;
    }
 
    public void onAuthSuccess() {
        characteristicCommandRead.reset();
        characteristicCommandWrite.reset();
        characteristicActivityData.reset();
        characteristicDataUpload.reset();
    }
 
    @Override
    public void setContext(GBDevice device, BluetoothAdapter adapter, Context context) {
        this.commsSupport.setContext(device, adapter, context);
    }
 
    public void sendCommand(final String taskName, final XiaomiProto.Command command) {
        if (this.characteristicCommandWrite == null) {
            // Can sometimes happen in race conditions when connecting + receiving calendar event or weather updates
            LOG.warn("characteristicCommandWrite is null!");
            return;
        }
 
        this.characteristicCommandWrite.write(taskName, command.toByteArray());
    }
 
    @Override
    public void sendDataChunk(String taskName, byte[] chunk, @Nullable XiaomiCharacteristic.SendCallback callback) {
        if (this.characteristicDataUpload == null) {
            LOG.warn("characteristicDataUpload is null!");
            return;
        }
 
        this.characteristicDataUpload.write(taskName, chunk, callback);
    }
 
    @Override
    public void setAutoReconnect(boolean enabled) {
        this.commsSupport.setAutoReconnect(enabled);
    }
 
    /**
     * Realistically, this function should only be used during auth, as we must schedule the command after
     * notifications were enabled on the characteristics, and for that we need the builder to guarantee the
     * order.
     */
    public void sendCommand(final TransactionBuilder builder, final XiaomiProto.Command command) {
        if (this.characteristicCommandWrite == null) {
            // Can sometimes happen in race conditions when connecting + receiving calendar event or weather updates
            LOG.warn("characteristicCommandWrite is null!");
            return;
        }
 
        this.characteristicCommandWrite.write(builder, command.toByteArray());
    }
 
    public TransactionBuilder createTransactionBuilder(String taskName) {
        return commsSupport.createTransactionBuilder(taskName);
    }
 
    public BtLEQueue getQueue() {
        return commsSupport.getQueue();
    }
 
    @Override
    public void onUploadProgress(int textRsrc, int progressPercent, boolean ongoing) {
        try {
            final TransactionBuilder builder = commsSupport.createTransactionBuilder("send data upload progress");
            builder.add(new SetProgressAction(
                    commsSupport.getContext().getString(textRsrc),
                    ongoing,
                    progressPercent,
                    commsSupport.getContext()
            ));
            builder.queue(commsSupport.getQueue());
        } catch (final Exception e) {
            LOG.error("Failed to update progress notification", e);
        }
    }
 
    @Override
    public boolean connect() {
        return commsSupport.connect();
    }
 
    @Override
    public void runOnQueue(String taskName, Runnable runnable) {
        final TransactionBuilder b = commsSupport.createTransactionBuilder("run task " + taskName + " on queue");
        b.add(new PlainAction() {
            @Override
            public boolean run(BluetoothGatt gatt) {
                runnable.run();
                return true;
            }
        });
        b.queue(commsSupport.getQueue());
    }
 
    @Override
    public void dispose() {
        commsSupport.dispose();
        if (characteristicCommandRead != null)
            characteristicCommandRead.dispose();
        if (characteristicCommandWrite != null)
            characteristicCommandWrite.dispose();
        if (characteristicDataUpload != null)
            characteristicDataUpload.dispose();
        if (characteristicActivityData != null)
            characteristicActivityData.dispose();
    }
}