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
package nodomain.freeyourgadget.gadgetbridge.service.btle;
 
import static nodomain.freeyourgadget.gadgetbridge.activities.devicesettings.DeviceSettingsPreferenceConst.PREFS_KEY_DEVICE_BLE_API_DEVICE_NOTIFY;
import static nodomain.freeyourgadget.gadgetbridge.activities.devicesettings.DeviceSettingsPreferenceConst.PREFS_KEY_DEVICE_BLE_API_DEVICE_READ_WRITE;
import static nodomain.freeyourgadget.gadgetbridge.activities.devicesettings.DeviceSettingsPreferenceConst.PREFS_KEY_DEVICE_BLE_API_DEVICE_STATE;
import static nodomain.freeyourgadget.gadgetbridge.activities.devicesettings.DeviceSettingsPreferenceConst.PREFS_KEY_DEVICE_BLE_API_PACKAGE;
 
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattServer;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;
 
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.util.HashMap;
import java.util.UUID;
 
import nodomain.freeyourgadget.gadgetbridge.GBApplication;
import nodomain.freeyourgadget.gadgetbridge.R;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.util.GB;
import nodomain.freeyourgadget.gadgetbridge.util.Prefs;
import nodomain.freeyourgadget.gadgetbridge.util.StringUtils;
 
public class BleIntentApi {
    private Context context;
    GBDevice device;
    BtLEQueue queue;
    Logger logger;
 
    private boolean intentApiEnabledDeviceState = false;
    private boolean intentApiEnabledReadWrite= false;
    private boolean intentApiEnabledNotifications= false;
    private String intentApiPackage = "";
    private boolean intentApiCharacteristicReceiverRegistered = false;
    private boolean intentApiDeviceStateReceiverRegistered = false;
    private String lastReportedState = null;
 
    private final HashMap<String, BluetoothGattCharacteristic> characteristics = new HashMap<>();
 
    public static final String BLE_API_COMMAND_READ = "nodomain.freeyourgadget.gadgetbridge.ble_api.commands.CHARACTERISTIC_READ";
    public static final String BLE_API_COMMAND_WRITE = "nodomain.freeyourgadget.gadgetbridge.ble_api.commands.CHARACTERISTIC_WRITE";
    public static final String BLE_API_EVENT_CHARACTERISTIC_CHANGED = "nodomain.freeyourgadget.gadgetbridge.ble_api.events.CHARACTERISTIC_CHANGED";
 
 
    BroadcastReceiver intentApiReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
 
            boolean isWrite = BLE_API_COMMAND_WRITE.equals(action);
 
            boolean isRead = BLE_API_COMMAND_READ.equals(action);
 
            if((!isWrite) && (!isRead)) {
                return;
            }
 
            if (!concernsThisDevice(intent)) {
                return;
            }
 
            if(!getDevice().getState().equalsOrHigherThan(GBDevice.State.INITIALIZED)) {
                logger.error(String.format("BLE API: Device %s not initialized.", getDevice()));
                return;
            }
 
            String uuid = intent.getStringExtra("EXTRA_CHARACTERISTIC_UUID");
            if (StringUtils.isNullOrEmpty(uuid)) {
                logger.error("BLE API: missing EXTRA_CHARACTERISTIC_UUID");
                return;
            }
 
            String hexData = intent.getStringExtra("EXTRA_PAYLOAD");
            if (isWrite && (hexData == null)) {
                logger.error("BLE API: missing EXTRA_PAYLOAD");
                return;
            }
 
            BluetoothGattCharacteristic characteristic = characteristics.get(uuid);
 
            if(characteristic == null) {
                logger.error("Characteristic {} not found", uuid);
                return;
            }
 
            if(isWrite) {
                new TransactionBuilder("BLE API write")
                        .write(characteristic, StringUtils.hexToBytes(hexData))
                        .queue(getQueue());
                return;
            }
 
            if(isRead) {
                new TransactionBuilder("BLE API read")
                        .read(characteristic)
                        .queue(getQueue());
                return;
            }
        }
    };
 
    public static boolean isEnabled(GBDevice device) {
        Prefs devicePrefs = GBApplication.getDevicePrefs(device);
 
        boolean intentApiEnabledReadWrite = devicePrefs.getBoolean(PREFS_KEY_DEVICE_BLE_API_DEVICE_READ_WRITE, false);
        boolean intentApiEnabledNotifications = devicePrefs.getBoolean(PREFS_KEY_DEVICE_BLE_API_DEVICE_NOTIFY, false);
        boolean intentApiEnabledDeviceState = devicePrefs.getBoolean(PREFS_KEY_DEVICE_BLE_API_DEVICE_STATE, false);
 
        return intentApiEnabledReadWrite | intentApiEnabledNotifications | intentApiEnabledDeviceState;
    }
 
    public void onCharacteristicChanged(BluetoothGattCharacteristic characteristic) {
        if(!intentApiEnabledNotifications) {
            return;
        }
        Intent intent = getBleApiIntent(BLE_API_EVENT_CHARACTERISTIC_CHANGED);
        if(!StringUtils.isNullOrEmpty(intentApiPackage)) {
            intent.setPackage(intentApiPackage);
        }
        intent.putExtra("EXTRA_CHARACTERISTIC", characteristic.getUuid().toString());
        intent.putExtra("EXTRA_PAYLOAD", StringUtils.bytesToHex(characteristic.getValue()));
 
        getContext().sendBroadcast(intent);
    }
 
    public void initializeDevice(TransactionBuilder builder) {
        if(intentApiEnabledNotifications) {
            for (BluetoothGattCharacteristic characteristic : characteristics.values()) {
                builder.notify(characteristic, true);
            }
        }
    }
 
    public void dispose() {
        registerBleApiCharacteristicReceivers(false);
    }
 
    public void onSendConfiguration(String config) {
        if(StringUtils.isNullOrEmpty(config)) {
            return;
        }
        if(config.startsWith("prefs_device_ble_api_")) {
            // could subscribe here, but there is more setup to do than that...
            // handleBLEApiPrefs();
            GB.toast(
                    getContext().getString(R.string.toast_setting_requires_reconnect),
                    Toast.LENGTH_SHORT,
                    GB.INFO
            );
        };
    }
 
    public Context getContext() {
        return context;
    }
 
    public BtLEQueue getQueue() {
        return queue;
    }
 
    public void setQueue(BtLEQueue queue) {
        this.queue = queue;
    }
 
    private void registerBleApiCharacteristicReceivers(boolean enable){
        if(enable == intentApiCharacteristicReceiverRegistered) {
            return;
        }
 
        if(enable){
            IntentFilter filter = new IntentFilter();
            filter.addAction(BLE_API_COMMAND_READ);
            filter.addAction(BLE_API_COMMAND_WRITE);
 
            ContextCompat.registerReceiver(
                    getContext(),
                    intentApiReceiver,
                    filter,
                    ContextCompat.RECEIVER_EXPORTED
            );
        }else{
            getContext().unregisterReceiver(intentApiReceiver);
        }
        intentApiCharacteristicReceiverRegistered = intentApiEnabledReadWrite;
    }
 
    public void addService(BluetoothGattService service) {
        for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()) {
            this.characteristics.put(characteristic.getUuid().toString(), characteristic);
        }
    }
 
    public void handleBLEApiPrefs(){
        Prefs devicePrefs = GBApplication.getDevicePrefs(getDevice());
        this.intentApiEnabledReadWrite = devicePrefs.getBoolean(PREFS_KEY_DEVICE_BLE_API_DEVICE_READ_WRITE, false);
        this.intentApiEnabledNotifications = devicePrefs.getBoolean(PREFS_KEY_DEVICE_BLE_API_DEVICE_NOTIFY, false);
        this.intentApiEnabledDeviceState = devicePrefs.getBoolean(PREFS_KEY_DEVICE_BLE_API_DEVICE_STATE, false);
        this.intentApiPackage = devicePrefs.getString(PREFS_KEY_DEVICE_BLE_API_PACKAGE, "");
 
        registerBleApiCharacteristicReceivers(this.intentApiEnabledReadWrite);
    }
 
    public static Intent getBleApiIntent(String deviceAddress, String action) {
        Intent updateIntent = new Intent(action);
        updateIntent.putExtra("EXTRA_DEVICE_ADDRESS", deviceAddress);
        return updateIntent;
    }
 
    private Intent getBleApiIntent(String action) {
        return getBleApiIntent(getDevice().getAddress(), action);
    }
 
    public BleIntentApi(Context context, GBDevice device) {
        this.context = context;
        this.device = device;
 
        this.logger = LoggerFactory.getLogger(BleIntentApi.class);
    }
 
    public GBDevice getDevice() {
        return device;
    }
 
    private boolean concernsThisDevice(Intent intent) {
        String deviceAddress = intent.getStringExtra("EXTRA_DEVICE_ADDRESS");
        if (StringUtils.isNullOrEmpty(deviceAddress)) {
            logger.error("BLE API: missing EXTRA_DEVICE_ADDRESS");
            return false;
        }
        return deviceAddress.equalsIgnoreCase(getDevice().getAddress());
    }
}