forked from Freeyourgadget/Gadgetbridge
-
Notifications
You must be signed in to change notification settings - Fork 3
/
BangleJSDeviceSupport.java
1483 lines (1357 loc) · 66.3 KB
/
BangleJSDeviceSupport.java
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (C) 2019-2021 Andreas Shimokawa, Gordon Williams
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.banglejs;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.util.Base64;
import android.widget.Toast;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.SimpleTimeZone;
import java.util.UUID;
import java.lang.reflect.Field;
import io.wax911.emojify.Emoji;
import io.wax911.emojify.EmojiManager;
import io.wax911.emojify.EmojiUtils;
import de.greenrobot.dao.query.QueryBuilder;
import nodomain.freeyourgadget.gadgetbridge.BuildConfig;
import nodomain.freeyourgadget.gadgetbridge.GBApplication;
import nodomain.freeyourgadget.gadgetbridge.database.DBHandler;
import nodomain.freeyourgadget.gadgetbridge.database.DBHelper;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventBatteryInfo;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventCallControl;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventFindPhone;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventMusicControl;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventNotificationControl;
import nodomain.freeyourgadget.gadgetbridge.devices.banglejs.BangleJSConstants;
import nodomain.freeyourgadget.gadgetbridge.devices.banglejs.BangleJSSampleProvider;
import nodomain.freeyourgadget.gadgetbridge.externalevents.CalendarReceiver;
import nodomain.freeyourgadget.gadgetbridge.entities.BangleJSActivitySample;
import nodomain.freeyourgadget.gadgetbridge.entities.CalendarSyncState;
import nodomain.freeyourgadget.gadgetbridge.entities.CalendarSyncStateDao;
import nodomain.freeyourgadget.gadgetbridge.entities.DaoSession;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.model.Alarm;
import nodomain.freeyourgadget.gadgetbridge.model.BatteryState;
import nodomain.freeyourgadget.gadgetbridge.model.CalendarEventSpec;
import nodomain.freeyourgadget.gadgetbridge.service.btle.BtLEQueue;
import nodomain.freeyourgadget.gadgetbridge.util.calendar.CalendarEvent;
import nodomain.freeyourgadget.gadgetbridge.util.calendar.CalendarManager;
import nodomain.freeyourgadget.gadgetbridge.model.CallSpec;
import nodomain.freeyourgadget.gadgetbridge.model.CannedMessagesSpec;
import nodomain.freeyourgadget.gadgetbridge.model.DeviceService;
import nodomain.freeyourgadget.gadgetbridge.model.MusicSpec;
import nodomain.freeyourgadget.gadgetbridge.model.MusicStateSpec;
import nodomain.freeyourgadget.gadgetbridge.model.NotificationSpec;
import nodomain.freeyourgadget.gadgetbridge.model.RecordedDataTypes;
import nodomain.freeyourgadget.gadgetbridge.model.WeatherSpec;
import nodomain.freeyourgadget.gadgetbridge.service.btle.AbstractBTLEDeviceSupport;
import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder;
import nodomain.freeyourgadget.gadgetbridge.util.AlarmUtils;
import nodomain.freeyourgadget.gadgetbridge.util.EmojiConverter;
import nodomain.freeyourgadget.gadgetbridge.util.FileUtils;
import nodomain.freeyourgadget.gadgetbridge.util.GB;
import nodomain.freeyourgadget.gadgetbridge.util.LimitedQueue;
import nodomain.freeyourgadget.gadgetbridge.util.Prefs;
import static nodomain.freeyourgadget.gadgetbridge.activities.devicesettings.DeviceSettingsPreferenceConst.PREF_ALLOW_HIGH_MTU;
import static nodomain.freeyourgadget.gadgetbridge.activities.devicesettings.DeviceSettingsPreferenceConst.PREF_BANGLEJS_TEXT_BITMAP_SIZE;
import static nodomain.freeyourgadget.gadgetbridge.activities.devicesettings.DeviceSettingsPreferenceConst.PREF_DEVICE_INTERNET_ACCESS;
import static nodomain.freeyourgadget.gadgetbridge.activities.devicesettings.DeviceSettingsPreferenceConst.PREF_DEVICE_INTENTS;
import static nodomain.freeyourgadget.gadgetbridge.activities.devicesettings.DeviceSettingsPreferenceConst.PREF_BANGLEJS_TEXT_BITMAP;
import static nodomain.freeyourgadget.gadgetbridge.database.DBHelper.*;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
public class BangleJSDeviceSupport extends AbstractBTLEDeviceSupport {
private static final Logger LOG = LoggerFactory.getLogger(BangleJSDeviceSupport.class);
private BluetoothGattCharacteristic rxCharacteristic = null;
private BluetoothGattCharacteristic txCharacteristic = null;
private boolean allowHighMTU = false;
private int mtuSize = 20;
int bangleCommandSeq = 0; // to attempt to stop duplicate packets when sending Local Intents
/// Current line of data received from Bangle.js
private String receivedLine = "";
/// All characters received from Bangle.js for debug purposes (limited to MAX_RECEIVE_HISTORY_CHARS). Can be dumped with 'Fetch Device Debug Logs' from Debug menu
private String receiveHistory = "";
private boolean realtimeHRM = false;
private boolean realtimeStep = false;
private int realtimeHRMInterval = 30*60;
/// Last battery percentage reported (or -1) to help with smoothing reported battery levels
private int lastBatteryPercent = -1;
private final LimitedQueue/*Long*/ mNotificationReplyAction = new LimitedQueue(16);
/// Maximum amount of characters to store in receiveHistory
public static final int MAX_RECEIVE_HISTORY_CHARS = 100000;
// Local Intents - for app manager communication
public static final String BANGLEJS_COMMAND_TX = "banglejs_command_tx";
public static final String BANGLEJS_COMMAND_RX = "banglejs_command_rx";
// Global Intents
private static final String BANGLE_ACTION_UART_TX = "com.banglejs.uart.tx";
public BangleJSDeviceSupport() {
super(LOG);
addSupportedService(BangleJSConstants.UUID_SERVICE_NORDIC_UART);
registerLocalIntents();
registerGlobalIntents();
}
private void addReceiveHistory(String s) {
receiveHistory += s;
if (receiveHistory.length() > MAX_RECEIVE_HISTORY_CHARS)
receiveHistory = receiveHistory.substring(receiveHistory.length() - MAX_RECEIVE_HISTORY_CHARS);
}
private void registerLocalIntents() {
IntentFilter commandFilter = new IntentFilter();
commandFilter.addAction(GBDevice.ACTION_DEVICE_CHANGED);
commandFilter.addAction(BANGLEJS_COMMAND_TX);
BroadcastReceiver commandReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case BANGLEJS_COMMAND_TX: {
String data = String.valueOf(intent.getExtras().get("DATA"));
BtLEQueue queue = getQueue();
if (queue==null) {
LOG.warn("BANGLEJS_COMMAND_TX received, but getQueue()==null (state=" + gbDevice.getStateString() + ")");
} else {
try {
TransactionBuilder builder = performInitialized("TX");
uartTx(builder, data);
builder.queue(queue);
} catch (IOException e) {
GB.toast(getContext(), "Error in TX: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
break;
}
case GBDevice.ACTION_DEVICE_CHANGED: {
LOG.info("ACTION_DEVICE_CHANGED " + (gbDevice!=null ? gbDevice.getStateString():""));
addReceiveHistory("\n================================================\nACTION_DEVICE_CHANGED "+gbDevice.getStateString()+" "+(new SimpleDateFormat("yyyy-mm-dd hh:mm:ss")).format(Calendar.getInstance().getTime())+"\n================================================\n");
}
}
}
};
LocalBroadcastManager.getInstance(GBApplication.getContext()).registerReceiver(commandReceiver, commandFilter);
}
private void registerGlobalIntents() {
IntentFilter commandFilter = new IntentFilter();
commandFilter.addAction(BANGLE_ACTION_UART_TX);
BroadcastReceiver commandReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case BANGLE_ACTION_UART_TX: {
/* In Tasker:
Action: com.banglejs.uart.tx
Cat: None
Extra: line:Terminal.println(%avariable)
Target: Broadcast Receiver
Variable: Number, Configure on Import, NOT structured, Value set, Nothing Exported, NOT Same as value
*/
Prefs devicePrefs = new Prefs(GBApplication.getDeviceSpecificSharedPrefs(gbDevice.getAddress()));
if (!devicePrefs.getBoolean(PREF_DEVICE_INTENTS, false)) return;
String data = intent.getStringExtra("line");
if (data==null) {
GB.toast(getContext(), "UART TX Intent, but no 'line' supplied", Toast.LENGTH_LONG, GB.ERROR);
return;
}
if (!data.endsWith("\n")) data += "\n";
try {
TransactionBuilder builder = performInitialized("TX");
uartTx(builder, data);
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error in TX: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
break;
}
}
}
};
GBApplication.getContext().registerReceiver(commandReceiver, commandFilter);
}
@Override
protected TransactionBuilder initializeDevice(TransactionBuilder builder) {
LOG.info("Initializing");
gbDevice.setState(GBDevice.State.INITIALIZING);
gbDevice.sendDeviceUpdateIntent(getContext());
gbDevice.setBatteryThresholdPercent((short) 30);
rxCharacteristic = getCharacteristic(BangleJSConstants.UUID_CHARACTERISTIC_NORDIC_UART_RX);
txCharacteristic = getCharacteristic(BangleJSConstants.UUID_CHARACTERISTIC_NORDIC_UART_TX);
builder.setGattCallback(this);
builder.notify(rxCharacteristic, true);
Prefs devicePrefs = new Prefs(GBApplication.getDeviceSpecificSharedPrefs(gbDevice.getAddress()));
allowHighMTU = devicePrefs.getBoolean(PREF_ALLOW_HIGH_MTU, false);
uartTx(builder, " \u0003"); // clear active line
Prefs prefs = GBApplication.getPrefs();
if (prefs.getBoolean("datetime_synconconnect", true))
transmitTime(builder);
//sendSettings(builder);
// get version
gbDevice.setState(GBDevice.State.INITIALIZED);
gbDevice.sendDeviceUpdateIntent(getContext());
getDevice().setFirmwareVersion("N/A");
getDevice().setFirmwareVersion2("N/A");
lastBatteryPercent = -1;
LOG.info("Initialization Done");
return builder;
}
/// Write a string of data, and chunk it up
private void uartTx(TransactionBuilder builder, String str) {
byte[] bytes = str.getBytes(StandardCharsets.ISO_8859_1);
LOG.info("UART TX: " + str);
addReceiveHistory("\n================================================\nSENDING "+str+"\n================================================\n");
// FIXME: somehow this is still giving us UTF8 data when we put images in strings. Maybe JSON.stringify is converting to UTF-8?
for (int i=0;i<bytes.length;i+=mtuSize) {
int l = bytes.length-i;
if (l>mtuSize) l=mtuSize;
byte[] packet = new byte[l];
System.arraycopy(bytes, i, packet, 0, l);
builder.write(txCharacteristic, packet);
}
}
/// Converts an object to a JSON string. see jsonToString
private String jsonToStringInternal(Object v) {
if (v instanceof String) {
/* Convert a string, escaping chars we can't send over out UART connection */
String s = (String)v;
String json = "\"";
//String rawString = "";
for (int i=0;i<s.length();i++) {
int ch = (int)s.charAt(i); // 0..255
int nextCh = (int)(i+1<s.length() ? s.charAt(i+1) : 0); // 0..255
//rawString = rawString+ch+",";
if (ch<8) {
// if the next character is a digit, it'd be interpreted
// as a 2 digit octal character, so we can't use `\0` to escape it
if (nextCh>='0' && nextCh<='7') json += "\\x0" + ch;
else json += "\\" + ch;
} else if (ch==8) json += "\\b";
else if (ch==9) json += "\\t";
else if (ch==10) json += "\\n";
else if (ch==11) json += "\\v";
else if (ch==12) json += "\\f";
else if (ch==34) json += "\\\""; // quote
else if (ch==92) json += "\\\\"; // slash
else if (ch<32 || ch==127 || ch==173)
json += "\\x"+Integer.toHexString((ch&255)|256).substring(1);
else json += s.charAt(i);
}
// if it was less characters to send base64, do that!
if (json.length() > 5+(s.length()*4/3)) {
byte[] bytes = s.getBytes(StandardCharsets.ISO_8859_1);
return "atob(\""+Base64.encodeToString(bytes, Base64.DEFAULT).replaceAll("\n","")+"\")";
}
// for debugging...
//addReceiveHistory("\n---------------------\n"+rawString+"\n---------------------\n");
return json + "\"";
} else if (v instanceof JSONArray) {
JSONArray a = (JSONArray)v;
String json = "[";
for (int i=0;i<a.length();i++) {
if (i>0) json += ",";
Object o = null;
try {
o = a.get(i);
} catch (JSONException e) {
LOG.warn("jsonToString array error: " + e.getLocalizedMessage());
}
json += jsonToStringInternal(o);
}
return json+"]";
} else if (v instanceof JSONObject) {
JSONObject obj = (JSONObject)v;
String json = "{";
Iterator<String> iter = obj.keys();
while (iter.hasNext()) {
String key = iter.next();
Object o = null;
try {
o = obj.get(key);
} catch (JSONException e) {
LOG.warn("jsonToString object error: " + e.getLocalizedMessage());
}
json += key+":"+jsonToStringInternal(o);
if (iter.hasNext()) json+=",";
}
return json+"}";
} // else int/double/null
return v.toString();
}
/// Convert a JSON object to a JSON String (NOT 100% JSON compliant)
public String jsonToString(JSONObject jsonObj) {
/* jsonObj.toString() works but breaks char codes>128 (encodes as UTF8?) and also uses
\u0000 when just \0 would do (and so on).
So we do it manually, which can be more compact anyway.
This is JSON-ish, so not exactly as per JSON1 spec but good enough for Espruino.
*/
return jsonToStringInternal(jsonObj);
}
/// Write a JSON object of data
private void uartTxJSON(String taskName, JSONObject json) {
try {
TransactionBuilder builder = performInitialized(taskName);
uartTx(builder, "\u0010GB("+jsonToString(json)+")\n");
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error in "+taskName+": " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
/// Write JSON object of the form {t:taskName, err:message}
private void uartTxJSONError(String taskName, String message) {
uartTxJSONError(taskName,message,null);
}
private void uartTxJSONError(String taskName, String message,String id) {
JSONObject o = new JSONObject();
try {
o.put("t", taskName);
if( id!=null)
o.put("id", id);
o.put("err", message);
} catch (JSONException e) {
GB.toast(getContext(), "uartTxJSONError: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
uartTxJSON(taskName, o);
}
private void handleUartRxLine(String line) {
LOG.info("UART RX LINE: " + line);
if (line.length()==0) return;
if (">Uncaught ReferenceError: \"GB\" is not defined".equals(line))
GB.toast(getContext(), "Gadgetbridge plugin not installed on Bangle.js", Toast.LENGTH_LONG, GB.ERROR);
else if (line.charAt(0)=='{') {
// JSON - we hope!
try {
JSONObject json = new JSONObject(line);
LOG.info("UART RX JSON parsed successfully");
handleUartRxJSON(json);
} catch (JSONException e) {
LOG.info("UART RX JSON parse failure: "+ e.getLocalizedMessage());
GB.toast(getContext(), "Malformed JSON from Bangle.js: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
} else {
LOG.info("UART RX line started with "+(int)line.charAt(0)+" - ignoring");
}
}
private void handleUartRxJSON(JSONObject json) throws JSONException {
String packetType = json.getString("t");
switch (packetType) {
case "info":
GB.toast(getContext(), "Bangle.js: " + json.getString("msg"), Toast.LENGTH_LONG, GB.INFO);
break;
case "warn":
GB.toast(getContext(), "Bangle.js: " + json.getString("msg"), Toast.LENGTH_LONG, GB.WARN);
break;
case "error":
GB.toast(getContext(), "Bangle.js: " + json.getString("msg"), Toast.LENGTH_LONG, GB.ERROR);
break;
case "ver": {
if (json.has("fw1"))
getDevice().setFirmwareVersion(json.getString("fw1"));
if (json.has("fw2"))
getDevice().setFirmwareVersion2(json.getString("fw2"));
} break;
case "status": {
GBDeviceEventBatteryInfo batteryInfo = new GBDeviceEventBatteryInfo();
batteryInfo.state = BatteryState.UNKNOWN;
if (json.has("chg")) {
batteryInfo.state = (json.getInt("chg") == 1) ? BatteryState.BATTERY_CHARGING : BatteryState.BATTERY_NORMAL;
}
if (json.has("bat")) {
int b = json.getInt("bat");
if (b < 0) b = 0;
if (b > 100) b = 100;
// smooth out battery level reporting (it can only go up if charging, or down if discharging)
// http://forum.espruino.com/conversations/379294
if (lastBatteryPercent<0) lastBatteryPercent = b;
if (batteryInfo.state == BatteryState.BATTERY_NORMAL && b > lastBatteryPercent)
b = lastBatteryPercent;
if (batteryInfo.state == BatteryState.BATTERY_CHARGING && b < lastBatteryPercent)
b = lastBatteryPercent;
lastBatteryPercent = b;
batteryInfo.level = b;
}
if (json.has("volt"))
batteryInfo.voltage = (float) json.getDouble("volt");
handleGBDeviceEvent(batteryInfo);
} break;
case "findPhone": {
boolean start = json.has("n") && json.getBoolean("n");
GBDeviceEventFindPhone deviceEventFindPhone = new GBDeviceEventFindPhone();
deviceEventFindPhone.event = start ? GBDeviceEventFindPhone.Event.START : GBDeviceEventFindPhone.Event.STOP;
evaluateGBDeviceEvent(deviceEventFindPhone);
} break;
case "music": {
GBDeviceEventMusicControl deviceEventMusicControl = new GBDeviceEventMusicControl();
deviceEventMusicControl.event = GBDeviceEventMusicControl.Event.valueOf(json.getString("n").toUpperCase());
evaluateGBDeviceEvent(deviceEventMusicControl);
} break;
case "call": {
GBDeviceEventCallControl deviceEventCallControl = new GBDeviceEventCallControl();
deviceEventCallControl.event = GBDeviceEventCallControl.Event.valueOf(json.getString("n").toUpperCase());
evaluateGBDeviceEvent(deviceEventCallControl);
} break;
case "notify" : {
GBDeviceEventNotificationControl deviceEvtNotificationControl = new GBDeviceEventNotificationControl();
// .title appears unused
deviceEvtNotificationControl.event = GBDeviceEventNotificationControl.Event.valueOf(json.getString("n").toUpperCase());
if (json.has("id"))
deviceEvtNotificationControl.handle = json.getInt("id");
if (json.has("tel"))
deviceEvtNotificationControl.phoneNumber = json.getString("tel");
if (json.has("msg"))
deviceEvtNotificationControl.reply = json.getString("msg");
/* REPLY responses don't use the ID from the event (MUTE/etc seem to), but instead
* they use a handle that was provided in an action list on the onNotification.. event */
if (deviceEvtNotificationControl.event == GBDeviceEventNotificationControl.Event.REPLY) {
Long foundHandle = (Long)mNotificationReplyAction.lookup((int)deviceEvtNotificationControl.handle);
if (foundHandle!=null)
deviceEvtNotificationControl.handle = foundHandle;
}
evaluateGBDeviceEvent(deviceEvtNotificationControl);
} break;
case "act": {
BangleJSActivitySample sample = new BangleJSActivitySample();
sample.setTimestamp((int) (GregorianCalendar.getInstance().getTimeInMillis() / 1000L));
int hrm = 0;
int steps = 0;
if (json.has("hrm")) hrm = json.getInt("hrm");
if (json.has("stp")) steps = json.getInt("stp");
int activity = BangleJSSampleProvider.TYPE_ACTIVITY;
/*if (json.has("act")) {
String actName = "TYPE_" + json.getString("act").toUpperCase();
try {
Field f = ActivityKind.class.getField(actName);
try {
activity = f.getInt(null);
} catch (IllegalAccessException e) {
LOG.info("JSON activity '"+actName+"' not readable");
}
} catch (NoSuchFieldException e) {
LOG.info("JSON activity '"+actName+"' not found");
}
}*/
sample.setRawKind(activity);
sample.setHeartRate(hrm);
sample.setSteps(steps);
try (DBHandler dbHandler = GBApplication.acquireDB()) {
Long userId = getUser(dbHandler.getDaoSession()).getId();
Long deviceId = DBHelper.getDevice(getDevice(), dbHandler.getDaoSession()).getId();
BangleJSSampleProvider provider = new BangleJSSampleProvider(getDevice(), dbHandler.getDaoSession());
sample.setDeviceId(deviceId);
sample.setUserId(userId);
provider.addGBActivitySample(sample);
} catch (Exception ex) {
LOG.warn("Error saving activity: " + ex.getLocalizedMessage());
}
// push realtime data
if (realtimeHRM || realtimeStep) {
Intent intent = new Intent(DeviceService.ACTION_REALTIME_SAMPLES)
.putExtra(DeviceService.EXTRA_REALTIME_SAMPLE, sample);
LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
}
} break;
case "http": {
Prefs devicePrefs = new Prefs(GBApplication.getDeviceSpecificSharedPrefs(gbDevice.getAddress()));
String _id=null;
try {
_id = json.getString("id");
} catch (JSONException e) {
}
final String id = _id;
if (BuildConfig.INTERNET_ACCESS && devicePrefs.getBoolean(PREF_DEVICE_INTERNET_ACCESS, false)) {
RequestQueue queue = Volley.newRequestQueue(getContext());
String url = json.getString("url");
int method = Request.Method.GET;
if (json.has("method")) {
String m = json.getString("method").toLowerCase();
if (m.equals("get")) method = Request.Method.GET;
else if (m.equals("post")) method = Request.Method.POST;
else if (m.equals("head")) method = Request.Method.HEAD;
else if (m.equals("put")) method = Request.Method.PUT;
else if (m.equals("patch")) method = Request.Method.PATCH;
else if (m.equals("delete")) method = Request.Method.DELETE;
else uartTxJSONError("http", "Unknown HTTP method "+m,id);
}
byte[] _body = null;
if (json.has("body"))
_body = json.getString("body").getBytes();
final byte[] body = _body;
Map<String,String> _headers = null;
if (json.has("headers")) {
JSONObject h = json.getJSONObject("headers");
_headers = new HashMap<String,String>();
Iterator<String> iter = h.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
String value = h.getString(key);
_headers.put(key, value);
} catch (JSONException e) {
}
}
}
final Map<String,String> headers = _headers;
String _xmlPath = "";
try {
_xmlPath = json.getString("xpath");
} catch (JSONException e) {
}
final String xmlPath = _xmlPath;
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(method, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
JSONObject o = new JSONObject();
if (xmlPath.length() != 0) {
try {
InputSource inputXML = new InputSource(new StringReader(response));
XPath xPath = XPathFactory.newInstance().newXPath();
response = xPath.evaluate(xmlPath, inputXML);
} catch (Exception error) {
uartTxJSONError("http", error.toString(),id);
return;
}
}
try {
o.put("t", "http");
if( id!=null)
o.put("id", id);
o.put("resp", response);
} catch (JSONException e) {
GB.toast(getContext(), "HTTP: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
uartTxJSON("http", o);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
JSONObject o = new JSONObject();
uartTxJSONError("http", error.toString(),id);
}
}) {
@Override
public byte[] getBody() throws AuthFailureError {
if (body == null) return super.getBody();
return body;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
// clone the data from super.getHeaders() so we can write to it
Map<String, String> h = new HashMap<>(super.getHeaders());
if (headers != null) {
for (String key : headers.keySet()) {
String value = headers.get(key);
h.put(key, value);
}
}
return h;
}
};
queue.add(stringRequest);
} else {
if (BuildConfig.INTERNET_ACCESS)
uartTxJSONError("http", "Internet access not enabled, check Gadgetbridge Device Settings",id);
else
uartTxJSONError("http", "Internet access not enabled in this Gadgetbridge build",id);
}
} break;
case "intent": {
Prefs devicePrefs = new Prefs(GBApplication.getDeviceSpecificSharedPrefs(gbDevice.getAddress()));
if (devicePrefs.getBoolean(PREF_DEVICE_INTENTS, false)) {
String target = json.has("target") ? json.getString("target") : "broadcastreceiver";
Intent in = new Intent();
if (json.has("action")) in.setAction(json.getString("action"));
if (json.has("flags")) {
JSONArray flags = json.getJSONArray("flags");
for (int i = 0; i < flags.length(); i++) {
in = addIntentFlag(in, flags.getString(i));
}
}
if (json.has("categories")) {
JSONArray categories = json.getJSONArray("categories");
for (int i = 0; i < categories.length(); i++) {
in.addCategory(categories.getString(i));
}
}
if (json.has("package") && !json.has("class")) {
in = json.getString("package").equals("gadgetbridge") ?
in.setPackage(this.getContext().getPackageName()) :
in.setPackage(json.getString("package"));
}
if (json.has("package") && json.has("class")) {
in = json.getString("package").equals("gadgetbridge") ?
in.setClassName(this.getContext().getPackageName(), json.getString("class")) :
in.setClassName(json.getString("package"), json.getString("class"));
}
if (json.has("mimetype")) in.setType(json.getString("mimetype"));
if (json.has("data")) in.setData(Uri.parse(json.getString("data")));
if (json.has("extra")) {
JSONObject extra = json.getJSONObject("extra");
Iterator<String> iter = extra.keys();
while (iter.hasNext()) {
String key = iter.next();
in.putExtra(key, extra.getString(key)); // Should this be implemented for other types, e.g. extra.getInt(key)? Or will this always work even if receiving ints/doubles/etc.?
}
}
LOG.info("Executing intent:\n\t" + String.valueOf(in) + "\n\tTargeting: " + target);
//GB.toast(getContext(), String.valueOf(in), Toast.LENGTH_LONG, GB.INFO);
switch (target) {
case "broadcastreceiver":
getContext().sendBroadcast(in);
break;
case "activity": // See wakeActivity.java if you want to start activities from under the keyguard/lock sceen.
getContext().startActivity(in);
break;
case "service": // Should this be implemented differently, e.g. workManager?
getContext().startService(in);
break;
case "foregroundservice": // Should this be implemented differently, e.g. workManager?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
getContext().startForegroundService(in);
} else {
getContext().startService(in);
}
break;
default:
LOG.info("Targeting '"+target+"' isn't implemented or doesn't exist.");
GB.toast(getContext(), "Targeting '"+target+"' isn't implemented or it doesn't exist.", Toast.LENGTH_LONG, GB.INFO);
}
} else {
uartTxJSONError("intent", "Android Intents not enabled, check Gadgetbridge Device Settings");
} break;
}
case "force_calendar_sync": {
//if(!GBApplication.getPrefs().getBoolean("enable_calendar_sync", false)) return;
//pretty much like the updateEvents in CalendarReceiver, but would need a lot of libraries here
JSONArray ids = json.getJSONArray("ids");
ArrayList<Long> idsList = new ArrayList(ids.length());
try (DBHandler dbHandler = GBApplication.acquireDB()) {
DaoSession session = dbHandler.getDaoSession();
Long deviceId = DBHelper.getDevice(gbDevice, session).getId();
QueryBuilder<CalendarSyncState> qb = session.getCalendarSyncStateDao().queryBuilder();
//FIXME just use that and don't query every time?
List<CalendarSyncState> states = qb.where(
CalendarSyncStateDao.Properties.DeviceId.eq(deviceId)).build().list();
LOG.info("force_calendar_sync on banglejs: "+ ids.length() +" events on the device, "+ states.size() +" on our db");
for (int i = 0; i < ids.length(); i++) {
Long id = ids.getLong(i);
qb = session.getCalendarSyncStateDao().queryBuilder(); //is this needed again?
CalendarSyncState calendarSyncState = qb.where(
qb.and(CalendarSyncStateDao.Properties.DeviceId.eq(deviceId),
CalendarSyncStateDao.Properties.CalendarEntryId.eq(id))).build().unique();
if(calendarSyncState == null) {
onDeleteCalendarEvent((byte)0, id);
LOG.info("event id="+ id +" is on device id="+ deviceId +", removing it there");
} else {
//used for later, no need to check twice the ones that do not match
idsList.add(id);
}
}
if(idsList.size() == states.size()) return;
//remove all elements not in ids from database (we don't have them)
for(CalendarSyncState calendarSyncState : states) {
long id = calendarSyncState.getCalendarEntryId();
if(!idsList.contains(id)) {
qb = session.getCalendarSyncStateDao().queryBuilder(); //is this needed again?
qb.where(qb.and(CalendarSyncStateDao.Properties.DeviceId.eq(deviceId),
CalendarSyncStateDao.Properties.CalendarEntryId.eq(id)))
.buildDelete().executeDeleteWithoutDetachingEntities();
LOG.info("event id="+ id +" is not on device id="+ deviceId +", removing from our db");
}
}
} catch (Exception e1) {
GB.toast("Database Error while forcefully syncing Calendar", Toast.LENGTH_SHORT, GB.ERROR, e1);
}
//force a syncCalendar now, send missing events
Intent in = new Intent(this.getContext().getApplicationContext(), CalendarReceiver.class);
in.setAction("android.intent.action.PROVIDER_CHANGED");
this.getContext().getApplicationContext().sendBroadcast(in);
} break;
default : {
LOG.info("UART RX JSON packet type '"+packetType+"' not understood.");
}
}
}
private Intent addIntentFlag(Intent intent, String flag) {
try {
final Class<Intent> intentClass = Intent.class;
final Field flagField = intentClass.getDeclaredField(flag);
intent.addFlags(flagField.getInt(null));
} catch (final Exception e) {
// The user sent an invalid flag
LOG.info("Flag '"+flag+"' isn't implemented or doesn't exist and was therefore not set.");
GB.toast(getContext(), "Flag '"+flag+"' isn't implemented or it doesn't exist and was therefore not set.", Toast.LENGTH_LONG, GB.INFO);
}
return intent;
}
@Override
public boolean onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
if (super.onCharacteristicChanged(gatt, characteristic)) {
return true;
}
if (BangleJSConstants.UUID_CHARACTERISTIC_NORDIC_UART_RX.equals(characteristic.getUuid())) {
byte[] chars = characteristic.getValue();
// check to see if we get more data - if so, increase out MTU for sending
if (allowHighMTU && chars.length > mtuSize)
mtuSize = chars.length;
// Scan for flow control characters
for (int i=0;i<chars.length;i++) {
boolean ignoreChar = false;
if (chars[i]==19 /* XOFF */) {
getQueue().setPaused(true);
LOG.info("RX: XOFF");
ignoreChar = true;
}
if (chars[i]==17 /* XON */) {
getQueue().setPaused(false);
LOG.info("RX: XON");
ignoreChar = true;
}
if (ignoreChar) {
// remove char from the array. Generally only one XON/XOFF per stream so creating a new array each time is fine
byte[] c = new byte[chars.length - 1];
System.arraycopy(chars, 0, c, 0, i); // copy before
System.arraycopy(chars, i+1, c, i, chars.length - i - 1); // copy after
chars = c;
i--; // back up one (because we deleted it)
}
}
String packetStr = new String(chars);
LOG.info("RX: " + packetStr);
// logging
addReceiveHistory(packetStr);
// split into input lines
receivedLine += packetStr;
while (receivedLine.contains("\n")) {
int p = receivedLine.indexOf("\n");
String line = receivedLine.substring(0,p-1);
receivedLine = receivedLine.substring(p+1);
handleUartRxLine(line);
}
// Send an intent with new data
Intent intent = new Intent(BangleJSDeviceSupport.BANGLEJS_COMMAND_RX);
intent.putExtra("DATA", packetStr);
intent.putExtra("SEQ", bangleCommandSeq++);
LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
}
return false;
}
void transmitTime(TransactionBuilder builder) {
long ts = System.currentTimeMillis();
float tz = SimpleTimeZone.getDefault().getOffset(ts) / (1000 * 60 * 60.0f);
// set time
String cmd = "\u0010setTime("+(ts/1000)+");";
// set timezone
cmd += "E.setTimeZone("+tz+");";
// write timezone to settings
cmd += "(s=>{s&&(s.timezone="+tz+")&&require('Storage').write('setting.json',s);})(require('Storage').readJSON('setting.json',1))";
uartTx(builder, cmd+"\n");
}
@Override
public boolean useAutoConnect() {
return true;
}
private String renderUnicodeWordAsImage(String word) {
// check for emoji
boolean hasEmoji = false;
if (EmojiUtils.getAllEmojis()==null)
EmojiManager.initEmojiData(GBApplication.getContext());
for(Emoji emoji : EmojiUtils.getAllEmojis())
if (word.contains(emoji.getEmoji())) {
hasEmoji = true;
break;
}
// if we had emoji, ensure we create 3 bit color (not 1 bit B&W)
return "\0"+bitmapToEspruinoString(textToBitmap(word), hasEmoji ? BangleJSBitmapStyle.RGB_3BPP_TRANSPARENT : BangleJSBitmapStyle.MONOCHROME_TRANSPARENT);
}
public String renderUnicodeAsImage(String txt) {
if (txt==null) return null;
// Simple conversions
txt = txt.replaceAll("…", "...");
/* If we're not doing conversion, pass this right back (we use the EmojiConverter
As we would have done if BangleJSCoordinator.supportsUnicodeEmojis had reported false */
Prefs devicePrefs = new Prefs(GBApplication.getDeviceSpecificSharedPrefs(gbDevice.getAddress()));
if (!devicePrefs.getBoolean(PREF_BANGLEJS_TEXT_BITMAP, false))
return EmojiConverter.convertUnicodeEmojiToAscii(txt, GBApplication.getContext());
// Otherwise split up and check each word
String word = "", result = "";
boolean needsTranslate = false;
for (int i=0;i<txt.length();i++) {
char ch = txt.charAt(i);
if (" -_/:.,?!'\"&*()".indexOf(ch)>=0) {
// word split
if (needsTranslate) { // convert word
result += renderUnicodeWordAsImage(word)+ch;
} else { // or just copy across
result += word+ch;
}
word = "";
needsTranslate = false;
} else {
// TODO: better check?
if (ch<0 || ch>255) needsTranslate = true;
word += ch;
}
}
if (needsTranslate) { // convert word
result += renderUnicodeWordAsImage(word);
} else { // or just copy across
result += word;
}
return result;
}
@Override
public void onNotification(NotificationSpec notificationSpec) {
if (notificationSpec.attachedActions!=null)
for (int i=0;i<notificationSpec.attachedActions.size();i++) {
NotificationSpec.Action action = notificationSpec.attachedActions.get(i);
if (action.type==NotificationSpec.Action.TYPE_WEARABLE_REPLY)
mNotificationReplyAction.add(notificationSpec.getId(), ((long) notificationSpec.getId() << 4) + i + 1);
}
try {
JSONObject o = new JSONObject();
o.put("t", "notify");
o.put("id", notificationSpec.getId());
o.put("src", notificationSpec.sourceName);
o.put("title", renderUnicodeAsImage(notificationSpec.title));
o.put("subject", renderUnicodeAsImage(notificationSpec.subject));
o.put("body", renderUnicodeAsImage(notificationSpec.body));
o.put("sender", renderUnicodeAsImage(notificationSpec.sender));
o.put("tel", notificationSpec.phoneNumber);
uartTxJSON("onNotification", o);
} catch (JSONException e) {
LOG.info("JSONException: " + e.getLocalizedMessage());
}
}
@Override
public void onDeleteNotification(int id) {
try {
JSONObject o = new JSONObject();
o.put("t", "notify-");
o.put("id", id);
uartTxJSON("onDeleteNotification", o);
} catch (JSONException e) {
LOG.info("JSONException: " + e.getLocalizedMessage());
}
}
@Override
public void onSetTime() {
try {
TransactionBuilder builder = performInitialized("setTime");
transmitTime(builder);
//TODO: once we have a common strategy for sending events (e.g. EventHandler), remove this call from here. Meanwhile it does no harm.
// = we should genaralize the pebble calender code
//sendCalendarEvents(builder);
forceCalendarSync();
builder.queue(getQueue());
} catch (Exception e) {
GB.toast(getContext(), "Error setting time: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
@Override
public void onSetAlarms(ArrayList<? extends Alarm> alarms) {
try {
JSONObject o = new JSONObject();
o.put("t", "alarm");
JSONArray jsonalarms = new JSONArray();
o.put("d", jsonalarms);
for (Alarm alarm : alarms) {
if (!alarm.getEnabled()) continue;
JSONObject jsonalarm = new JSONObject();
jsonalarms.put(jsonalarm);
Calendar calendar = AlarmUtils.toCalendar(alarm);
jsonalarm.put("h", alarm.getHour());
jsonalarm.put("m", alarm.getMinute());
jsonalarm.put("rep", alarm.getRepetition());
}
uartTxJSON("onSetAlarms", o);
} catch (JSONException e) {
LOG.info("JSONException: " + e.getLocalizedMessage());
}
}
@Override
public void onSetCallState(CallSpec callSpec) {
try {
JSONObject o = new JSONObject();
o.put("t", "call");
String cmdName = "";
try {
Field[] fields = callSpec.getClass().getDeclaredFields();
for (Field field : fields)
if (field.getName().startsWith("CALL_") && field.getInt(callSpec) == callSpec.command)
cmdName = field.getName().substring(5).toLowerCase();