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
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
/*  Copyright (C) 2020-2024 Arjan Schrijver, Taavi Eomäe
 
    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 <https://www.gnu.org/licenses/>. */
package nodomain.freeyourgadget.gadgetbridge.service.devices.nut;
 
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.Toast;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Map;
import java.util.UUID;
 
import nodomain.freeyourgadget.gadgetbridge.GBApplication;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventBatteryInfo;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventVersionInfo;
import nodomain.freeyourgadget.gadgetbridge.devices.nut.NutConstants;
import nodomain.freeyourgadget.gadgetbridge.devices.nut.NutKey;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.service.btle.AbstractBTLEDeviceSupport;
import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder;
import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.SetDeviceStateAction;
import nodomain.freeyourgadget.gadgetbridge.service.btle.profiles.IntentListener;
import nodomain.freeyourgadget.gadgetbridge.service.btle.profiles.battery.BatteryInfo;
import nodomain.freeyourgadget.gadgetbridge.service.btle.profiles.battery.BatteryInfoProfile;
import nodomain.freeyourgadget.gadgetbridge.service.btle.profiles.deviceinfo.DeviceInfo;
import nodomain.freeyourgadget.gadgetbridge.service.btle.profiles.deviceinfo.DeviceInfoProfile;
import nodomain.freeyourgadget.gadgetbridge.util.GB;
 
public class NutSupport extends AbstractBTLEDeviceSupport {
    private static final Logger LOG = LoggerFactory.getLogger(NutSupport.class);
 
    private final GBDeviceEventBatteryInfo batteryCmd = new GBDeviceEventBatteryInfo();
 
    private final DeviceInfoProfile<NutSupport> deviceInfoProfile;
    private final BatteryInfoProfile<NutSupport> batteryInfoProfile;
    private final IntentListener listener = new IntentListener() {
        @Override
        public void notify(Intent intent) {
            String action = intent.getAction();
            if (action.equals(DeviceInfoProfile.ACTION_DEVICE_INFO)) {
                handleDeviceInfo((DeviceInfo) intent.getParcelableExtra(DeviceInfoProfile.EXTRA_DEVICE_INFO));
            } else if (action.equals(BatteryInfoProfile.ACTION_BATTERY_INFO)) {
                handleBatteryInfo((BatteryInfo) intent.getParcelableExtra(BatteryInfoProfile.EXTRA_BATTERY_INFO));
            } else {
                LOG.warn("Unhandled intent given to listener");
            }
        }
    };
    private SharedPreferences prefs = null;
    /**
     * It uses the proprietary Nut interface.
     */
    private boolean proprietary = false;
    /**
     * Proprietary Nut interface needs authentication.
     * <p>
     * Don't write characteristics until authenticated.
     * <p>
     * Will disconnect in a minute if you don't authenticate.
     */
    private boolean authenticated = true;
    /**
     * The two keys used for authentication
     */
    private BigInteger key1;
    private BigInteger key2;
 
 
    public NutSupport() {
        super(LOG);
        addSupportedService(NutConstants.SERVICE_BATTERY);
        addSupportedService(NutConstants.SERVICE_DEVICE_INFO);
        addSupportedService(NutConstants.SERVICE_IMMEDIATE_ALERT);
        addSupportedService(NutConstants.SERVICE_LINK_LOSS);
        addSupportedService(NutConstants.SERVICE_PROPRIETARY_NUT);
        addSupportedService(NutConstants.SERVICE_UNKNOWN_2);
 
        deviceInfoProfile = new DeviceInfoProfile<>(this);
        deviceInfoProfile.addListener(listener);
        addSupportedProfile(deviceInfoProfile);
 
        batteryInfoProfile = new BatteryInfoProfile<>(this);
        batteryInfoProfile.addListener(listener);
        addSupportedProfile(batteryInfoProfile);
    }
 
    private void handleBatteryInfo(BatteryInfo info) {
        LOG.info("Received Nut battery info");
        batteryCmd.level = (short) info.getPercentCharged();
        handleGBDeviceEvent(batteryCmd);
    }
 
    private void handleDeviceInfo(DeviceInfo info) {
        LOG.info("Received Nut device info");
        LOG.info(String.valueOf(info));
        GBDeviceEventVersionInfo versionInfo = new GBDeviceEventVersionInfo();
        if (info.getHardwareRevision() != null) {
            versionInfo.hwVersion = info.getHardwareRevision();
        }
        if (info.getFirmwareRevision() != null) {
            versionInfo.fwVersion = info.getFirmwareRevision();
        }
 
        handleGBDeviceEvent(versionInfo);
    }
 
    @Override
    protected TransactionBuilder initializeDevice(TransactionBuilder builder) {
        builder.add(new SetDeviceStateAction(getDevice(), GBDevice.State.INITIALIZING, getContext()));
        builder.add(new SetDeviceStateAction(getDevice(), GBDevice.State.INITIALIZED, getContext()));
 
        // Init prefs
        prefs = GBApplication.getDeviceSpecificSharedPrefs(getDevice().getAddress());
        loadKeysFromPrefs();
 
        LOG.debug("Requesting device info!");
        deviceInfoProfile.requestDeviceInfo(builder);
        batteryInfoProfile.requestBatteryInfo(builder);
 
        // If this characteristic exists, it has proprietary Nut interface
        this.proprietary = (getCharacteristic(NutConstants.CHARAC_AUTH_STATUS) != null);
 
        if (proprietary) {
            this.authenticated = false;
            /**
             * Part of {@link NutConstants.SERVICE_PROPRIETARY_NUT}
             * Enables proprietary notification
             */
            builder.notify(getCharacteristic(NutConstants.CHARAC_AUTH_STATUS), true);
            LOG.info("Enabled authentication status notify");
 
            /**
             * Part of {@link NutConstants.SERVICE_UNKNOWN_2}
             * Enables button-press notify
             */
            builder.notify(getCharacteristic(NutConstants.CHARAC_UNKNOWN_2), true);
        } else {
            /**
             * Part of {@link NutConstants.SERVICE_UNKNOWN_1_WEIRDNESS}
             * Enables button-press notify
             */
            builder.notify(getCharacteristic(NutConstants.CHARAC_CHANGE_POWER), true);
        }
 
        readDeviceInfo();
        return builder;
    }
 
    @Override
    public boolean useAutoConnect() {
        return true;
    }
 
    @Override
    public void onFindDevice(boolean enable) {
        deviceImmediateAlert(enable);
    }
 
    @Override
    public boolean onCharacteristicChanged(BluetoothGatt gatt,
                                           BluetoothGattCharacteristic characteristic) {
        if (super.onCharacteristicChanged(gatt, characteristic)) {
            return true;
        }
 
        UUID characteristicUUID = characteristic.getUuid();
        if (characteristicUUID.equals(NutConstants.CHARAC_AUTH_STATUS)) {
            handleAuthResult(characteristic.getValue());
            return true;
        }
        LOG.info("Unhandled characteristic changed: " + characteristicUUID);
        return false;
    }
 
    @Override
    public boolean onCharacteristicRead(BluetoothGatt gatt,
                                        BluetoothGattCharacteristic characteristic,
                                        int status) {
        if (super.onCharacteristicRead(gatt, characteristic, status)) {
            return true;
        }
        UUID characteristicUUID = characteristic.getUuid();
 
        if (characteristicUUID.equals(NutConstants.CHARAC_SYSTEM_ID)) {
            // TODO: Handle System ID read
            return true;
        }
        LOG.info("Unhandled characteristic read: " + characteristicUUID);
        return false;
    }
 
    /**
     * Enables or disables link loss alert
     */
    private void deviceLinkLossAlert(boolean enable) {
        UUID charac;
        if (this.proprietary) {
            /** Part of {@link NutConstants.SERVICE_PROPRIETARY_NUT} */
            charac = NutConstants.CHARAC_CHANGE_POWER;
        } else {
            /** Part of {@link NutConstants.SERVICE_IMMEDIATE_ALERT} */
            charac = NutConstants.CHARAC_LINK_LOSS_ALERT_LEVEL;
        }
 
        byte[] payload = new byte[]{(byte) (enable ? 0x00 : 0x01)};
        if (enable) {
            writeCharacteristic("Enable link loss alert", charac, payload);
        } else {
            writeCharacteristic("Disable link loss alert", charac, payload);
        }
    }
 
    /**
     * Should trigger an immediate alert
     *
     * @param enable turn on or not
     */
    private void deviceImmediateAlert(boolean enable) {
        UUID charac;
        if (this.proprietary) {
            /** Part of {@link NutConstants.SERVICE_IMMEDIATE_ALERT} */
            charac = NutConstants.CHARAC_LINK_LOSS_ALERT_LEVEL;
            if (!authenticated) {
                LOG.warn("Not authenticated, can't alert");
                return;
            }
        } else {
            /** Part of {@link NutConstants.SERVICE_PROPRIETARY_NUT} */
            charac = NutConstants.CHARAC_CHANGE_POWER;
        }
 
        if (enable) {
            writeCharacteristic("Start alert", charac, new byte[]{(byte) 0x04});
        } else {
            writeCharacteristic("Stop alert", charac, new byte[]{(byte) 0x03});
        }
    }
 
    /**
     * This will write a new key to the device
     * <p>
     * However, <b>it is irreversible</b>,
     * if you can't generate the right packets,
     * the device is basically bricked!
     * <p>
     * If you can generate the correct packets,
     * it can be reset... somehow
     *
     * @param key key
     */
    private void deviceWriteNewKey(byte[] key) {
        // TODO: Determine each nuance of how this
        //  works before using it!
        byte[] result_payload = new byte[key.length + 1];
        result_payload[0] = (byte) 0x04;
        System.arraycopy(key, 0, result_payload, 1, key.length);
 
        writeCharacteristic("Write new key",
                NutConstants.CHARAC_DFU_PW,
                result_payload);
    }
 
    /**
     * Turns the device off
     */
    private void deviceShutdown() {
        writeCharacteristic("Shutdown", NutConstants.CHARAC_CHANGE_POWER, new byte[]{0x06});
    }
 
    /**
     * Switches the device to Nordic's DFU mode
     */
    private void deviceDFU() {
        writeCharacteristic("Enable DFU mode", NutConstants.CHARAC_DFU_PW, new byte[]{0x14});
    }
 
    /**
     * Specifies how long the alert lasts
     *
     * @param duration in seconds (I think)
     */
    private void deviceWriteAlertDuration(int duration) {
        if (duration == 0) {
            duration = 15;
        }
 
        UUID charac;
        if (this.proprietary) {
            charac = NutConstants.CHARAC_DFU_PW;
        } else {
            charac = NutConstants.CHARAC_CHANGE_POWER;
        }
 
        writeCharacteristic("Write alert duration",
                charac,
                new byte[]{37, (byte) duration});
    }
 
    private void readHardwareInfo() {
        BluetoothGattCharacteristic characteristic = getCharacteristic(NutConstants.CHARAC_HARDWARE_VERSION);
        if (characteristic != null &&
                ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_READ) > 0)) {
            readCharacteristic("Device read hardware",
                    NutConstants.CHARAC_HARDWARE_VERSION);
        }
 
        BluetoothGattCharacteristic characteristic1 = getCharacteristic(NutConstants.CHARAC_MANUFACTURER_NAME);
        if (characteristic1 != null &&
                (characteristic1.getProperties() & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
            readCharacteristic("Read manufacturer",
                    NutConstants.CHARAC_MANUFACTURER_NAME);
        }
    }
 
    private void readFirmwareInfo() {
        BluetoothGattCharacteristic characteristic = getCharacteristic(NutConstants.CHARAC_FIRMWARE_VERSION);
        if (characteristic != null &&
                (characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
            readCharacteristic("Read firmware version",
                    NutConstants.CHARAC_FIRMWARE_VERSION);
        }
    }
 
    private void readBatteryInfo() {
        BluetoothGattCharacteristic characteristic = getCharacteristic(NutConstants.CHARAC_BATTERY_INFO);
        if (characteristic != null &&
                (characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
            readCharacteristic("Read battery info",
                    NutConstants.CHARAC_BATTERY_INFO);
        }
    }
 
    /**
     * Loads the three keys from device-specific shared preferences
     */
    private void loadKeysFromPrefs() {
        if (prefs != null) {
            LOG.info("Reading keys");
            key1 = new BigInteger(prefs.getString("nut_packet_key_1", "0"));
            key2 = new BigInteger(prefs.getString("nut_packet_key_2", "0"));
            if (key1.equals(BigInteger.ZERO) || key2.equals(BigInteger.ZERO)) {
                byte[] challenge = NutKey.hexStringToByteArrayNut(prefs.getString("nut_packet_challenge", "00"));
                byte[] response = NutKey.hexStringToByteArrayNut(prefs.getString("nut_response_challenge", "00"));
                if (Arrays.equals(challenge, new byte[]{0x00}) ||
                        Arrays.equals(response, new byte[]{0x00})) {
                    GB.toast("No key available for the device", Toast.LENGTH_LONG, GB.ERROR);
                    return;
                }
                Map.Entry<BigInteger, BigInteger> key = NutKey.reversePasswordGeneration(
                        challenge,
                        response,
                        gbDevice.getAddress()
                );
                if (key == null) {
                    GB.toast("No correct key available for the device", Toast.LENGTH_LONG, GB.ERROR);
                    return;
                }
                key1 = key.getKey();
                key2 = key.getValue();
                LOG.debug("Key was extracted from challenge-response packets");
            } else {
                LOG.debug("Key was preset");
            }
        }
    }
 
    /**
     * Processes the authentication flow of the proprietary Nut protocol
     * See more: {@link NutConstants#SERVICE_PROPRIETARY_NUT}
     *
     * @param received the notify characteristic's content
     */
    public final void handleAuthResult(byte[] received) {
        if (received != null && received.length != 0) {
            if (received[0] == 0x01) {
                // Password is needed
                // Preamble, counter, rotating key, static key
                byte[] payload = new byte[1 + 1 + 3 + 12];
 
                // This is a response to the challenge
                payload[0] = 0x02;
 
                // Modify the challenge
                byte[] response = NutKey.passwordGeneration(gbDevice.getAddress(), received, key1, key2);
                System.arraycopy(response, 0, payload, 1, response.length);
 
                writeCharacteristic("Authentication",
                        NutConstants.CHARAC_DFU_PW,
                        payload
                );
                LOG.debug("Successfully sent auth");
            } else if (received[0] == 0x03) {
                if (received[1] == 0x55) {
                    LOG.debug("Successful password attempt or uninitialized");
                    authenticated = true;
                    initChara();
                } else {
                    LOG.debug("Error authenticating");
                    // TODO: Disconnect
                }
            } else if (received[0] == 0x05) {
                LOG.debug("Password has been set");
            } else {
                LOG.debug("Invalid packet");
                // TODO: Disconnect
            }
        }
    }
 
    /**
     * Initializes required characteristics
     */
    private void initChara() {
        if (proprietary) {
            writeCharacteristic("Init alert 1", NutConstants.CHARAC_LINK_LOSS_ALERT_LEVEL, new byte[]{(byte) 0x00});
            writeCharacteristic("Init alert 2", NutConstants.CHARAC_LINK_LOSS_ALERT_LEVEL, new byte[]{(byte) 0x00});
            writeCharacteristic("Init alert 3", NutConstants.CHARAC_LINK_LOSS_ALERT_LEVEL, new byte[]{(byte) 0x00});
        }
    }
 
    /**
     * Initiates a read of all the device information characteristics
     */
    private void readDeviceInfo() {
        readBatteryInfo();
        readHardwareInfo();
        readFirmwareInfo();
    }
 
    /**
     * Just wraps writing into a neat little function
     *
     * @param taskName something that describes the task a bit
     * @param charac   the characteristic to write
     * @param data     the data to write
     */
    private void writeCharacteristic(String taskName, UUID charac, byte[] data) {
        BluetoothGattCharacteristic characteristic = getCharacteristic(charac);
 
        TransactionBuilder builder = new TransactionBuilder(taskName);
        builder.write(characteristic, data);
        builder.queue(getQueue());
    }
 
    /**
     * Just wraps reading into a neat little function
     *
     * @param taskName something that describes the task a bit
     * @param charac   the characteristic to read
     */
    private void readCharacteristic(String taskName, UUID charac) {
        BluetoothGattCharacteristic characteristic = getCharacteristic(charac);
 
        TransactionBuilder builder = new TransactionBuilder(taskName);
        builder.read(characteristic);
        builder.queue(getQueue());
    }
 
    @Override
    public boolean getImplicitCallbackModify() {
        return true;
    }
 
    @Override
    public boolean getSendWriteRequestResponse() {
        return false;
    }
}