forked from fyne-io/fyne-x
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbluetooth_and.go
967 lines (848 loc) · 33.1 KB
/
bluetooth_and.go
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
//go:build android
package bluetooth
/*
#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
static inline void copyToError(char* errorMsg, char** error){
*error = (char*)malloc((strlen(errorMsg) + 1) * sizeof(char));
strcpy(*error, errorMsg);
}
jobject createBluetoothServer(uintptr_t env, jobject bluetoothAdapter, char** errorMsg) {
JNIEnv *envPtr = (JNIEnv*)env;
// Find class BluetoothServerSocket
jclass serverSocketClass = (*envPtr)->FindClass(envPtr, "android/bluetooth/BluetoothServerSocket");
if (serverSocketClass == NULL) {
copyToError( "Failed to find class BluetoothServerSocket", errorMsg);
return NULL;
}
// Get method listenUsingRfcommWithServiceRecord
jmethodID listenMethod = (*envPtr)->GetMethodID(envPtr, serverSocketClass, "listenUsingRfcommWithServiceRecord", "(Ljava/lang/String;Ljava/util/UUID;)Landroid/bluetooth/BluetoothServerSocket;");
if (listenMethod == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, serverSocketClass);
copyToError("Failed to get method listenUsingRfcommWithServiceRecord", errorMsg);
return NULL;
}
// Create UUID object
jclass uuidClass = (*envPtr)->FindClass(envPtr, "java/util/UUID");
if (uuidClass == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, serverSocketClass);
copyToError("Failed to find UUID class", errorMsg);
return NULL;
}
// create UUID object
jmethodID uuidConstructor = (*envPtr)->GetMethodID(envPtr, uuidClass, "<init>", "(JJ)V");
if (uuidClass == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, uuidClass);
(*envPtr)->DeleteLocalRef(envPtr, serverSocketClass);
copyToError("Failed to find uuid constructor", errorMsg);
return NULL;
}
jobject uuidObj = (*envPtr)->NewObject(envPtr, uuidClass, uuidConstructor, (jlong) 0, (jlong) 0);
if (uuidObj == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, serverSocketClass);
(*envPtr)->DeleteLocalRef(envPtr, uuidClass);
copyToError("Failed to create UUID object", errorMsg);
return NULL;
}
// Call listenUsingRfcommWithServiceRecord method
jobject serverSocket = (*envPtr)->CallObjectMethod(envPtr, bluetoothAdapter, listenMethod, NULL, uuidObj);
if (serverSocket == NULL) {
copyToError( "Failed to call listenUsingRfcommWithServiceRecord method", errorMsg);
}
// free memory
(*envPtr)->DeleteLocalRef(envPtr, serverSocketClass);
(*envPtr)->DeleteLocalRef(envPtr, uuidClass);
(*envPtr)->DeleteLocalRef(envPtr, uuidObj);
return serverSocket;
}
void closeBluetoothServerSocket(uintptr_t env, jobject serverSocket, char** errorMsg) {
JNIEnv* envPtr = (JNIEnv*)env;
// Get the BluetoothServerSocket class
jclass serverSocketClass = (*envPtr)->GetObjectClass(envPtr, serverSocket);
// Get the close method
jmethodID closeMethod = (*envPtr)->GetMethodID(envPtr, serverSocketClass, "close", "()V");
// If the close method is available, invoke it
if (closeMethod != NULL) {
(*envPtr)->CallVoidMethod(envPtr, serverSocket, closeMethod);
} else {
copyToError("Failed to find close method", errorMsg);
}
// Release memory
(*envPtr)->DeleteLocalRef(envPtr, serverSocket);
(*envPtr)->DeleteLocalRef(envPtr, serverSocketClass);
}
char* getClientName(uintptr_t env, jobject clientSocket, char** errorMsg) {
JNIEnv* envPtr = (JNIEnv*)env;
// Get the BluetoothSocket class
jclass socketClass = (*envPtr)->GetObjectClass(envPtr, clientSocket);
if (socketClass == NULL) {
copyToError( "Failed to get getRemoteDevice method", errorMsg);
return NULL;
}
// Get the getRemoteDevice method
jmethodID remoteDeviceMethod = (*envPtr)->GetMethodID(envPtr, socketClass, "getRemoteDevice", "()Landroid/bluetooth/BluetoothDevice;");
if (remoteDeviceMethod == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, socketClass);
copyToError("Failed to get getRemoteDevice method", errorMsg);
return NULL;
}
jobject remoteDevice = (*envPtr)->CallObjectMethod(envPtr, clientSocket, remoteDeviceMethod);
if (remoteDevice == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, socketClass);
copyToError( "Failed to get remote device", errorMsg);
return NULL;
}
// Get the BluetoothDevice class
jclass deviceClass = (*envPtr)->GetObjectClass(envPtr, remoteDevice);
if (remoteDevice == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, socketClass);
(*envPtr)->DeleteLocalRef(envPtr, remoteDevice);
copyToError( "Failed to get the BluetoothDevice class", errorMsg);
return NULL;
}
// Get the getName method
jmethodID getNameMethod = (*envPtr)->GetMethodID(envPtr, deviceClass, "getName", "()Ljava/lang/String;");
if (getNameMethod == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, socketClass);
(*envPtr)->DeleteLocalRef(envPtr, deviceClass);
(*envPtr)->DeleteLocalRef(envPtr, remoteDevice);
copyToError( "Failed to get getName method", errorMsg);
return NULL;
}
jstring nameString = (*envPtr)->CallObjectMethod(envPtr, remoteDevice, getNameMethod);
if (nameString == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, socketClass);
(*envPtr)->DeleteLocalRef(envPtr, deviceClass);
(*envPtr)->DeleteLocalRef(envPtr, remoteDevice);
copyToError( "Failed to get name string", errorMsg);
return NULL;
}
// Convert the Java string to C string
const char* name = (*envPtr)->GetStringUTFChars(envPtr, nameString, NULL);
if (name == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, socketClass);
(*envPtr)->DeleteLocalRef(env, deviceClass);
(*envPtr)->DeleteLocalRef(envPtr, remoteDevice);
(*envPtr)->ReleaseStringUTFChars(envPtr, nameString, name);
copyToError( "Failed to convert name string", errorMsg);
return NULL;
}
// Allocate memory for the result
char* result = (char*)malloc((strlen(name) + 1) * sizeof(char));
// Copy the name to the result
strcpy(result, name);
// Clean up references
(*envPtr)->DeleteLocalRef(envPtr, socketClass);
(*envPtr)->DeleteLocalRef(envPtr, deviceClass);
(*envPtr)->DeleteLocalRef(envPtr, remoteDevice);
(*envPtr)->ReleaseStringUTFChars(envPtr, nameString, name);
return result;
}
jobject acceptBluetoothClient(uintptr_t env, jobject serverSocket, char** errorMsg) {
JNIEnv* envPtr = (JNIEnv*)env;
// Get the accept method from BluetoothServerSocket
jclass serverSocketClass = (*envPtr)->GetObjectClass(envPtr, serverSocket);
if (serverSocketClass == NULL) {
copyToError( "Failed to get socket class", errorMsg);
return NULL;
}
jmethodID acceptMethod = (*envPtr)->GetMethodID(envPtr, serverSocketClass, "accept", "()Landroid/bluetooth/BluetoothSocket;");
if (acceptMethod == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, serverSocketClass);
copyToError( "Failed to get accept method", errorMsg);
return NULL;
}
// Call the accept method
jobject clientSocket = (*envPtr)->CallObjectMethod(envPtr, serverSocket, acceptMethod);
if (clientSocket == NULL) {
copyToError("Failed to accept client", errorMsg);
}
(*envPtr)->DeleteLocalRef(envPtr, serverSocketClass);
return clientSocket;
}
char* getClientAddress(uintptr_t env, jobject clientSocket, char** errorMsg) {
JNIEnv* envPtr = (JNIEnv*)env;
// Get the BluetoothSocket class
jclass socketClass = (*envPtr)->GetObjectClass(envPtr, clientSocket);
if (socketClass == NULL) {
copyToError( "Failed to get socket class", errorMsg);
return NULL;
}
// Get the getRemoteDevice method
jmethodID remoteDeviceMethod = (*envPtr)->GetMethodID(envPtr, socketClass, "getRemoteDevice", "()Landroid/bluetooth/BluetoothDevice;");
if (remoteDeviceMethod == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, socketClass);
copyToError( "Failed to get getRemoteDevice method", errorMsg);
return NULL;
}
jobject remoteDevice = (*envPtr)->CallObjectMethod(envPtr, clientSocket, remoteDeviceMethod);
if (remoteDevice == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, socketClass);
(*envPtr)->DeleteLocalRef(envPtr, remoteDevice);
copyToError("Failed to get remote device", errorMsg);
return NULL;
}
// Get the BluetoothDevice class
jclass deviceClass = (*envPtr)->GetObjectClass(envPtr, remoteDevice);
if (deviceClass == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, socketClass);
(*envPtr)->DeleteLocalRef(envPtr, remoteDevice);
copyToError( "Failed to get the BluetoothDevice class", errorMsg);
return NULL;
}
// Get the getAddress method
jmethodID getAddressMethod = (*envPtr)->GetMethodID(envPtr, deviceClass, "getAddress", "()Ljava/lang/String;");
if (getAddressMethod == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, deviceClass);
(*envPtr)->DeleteLocalRef(envPtr, socketClass);
(*envPtr)->DeleteLocalRef(envPtr, remoteDevice);
copyToError( "Failed to get getAddress method", errorMsg);
return NULL;
}
jstring addressString = (*envPtr)->CallObjectMethod(envPtr, remoteDevice, getAddressMethod);
if (addressString == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, deviceClass);
(*envPtr)->DeleteLocalRef(envPtr, socketClass);
(*envPtr)->DeleteLocalRef(envPtr, remoteDevice);
copyToError("Failed to get address string", errorMsg);
return NULL;
}
// Convert the Java string to C string
const char* address = (*envPtr)->GetStringUTFChars(envPtr, addressString, NULL);
if (address == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, socketClass);
(*envPtr)->DeleteLocalRef(envPtr, deviceClass);
(*envPtr)->ReleaseStringUTFChars(envPtr, addressString, address);
copyToError("Failed to convert address string", errorMsg);
return NULL;
}
// Allocate memory for the result
char* result = (char*)malloc((strlen(address) + 1) * sizeof(char));
// Copy the address
strcpy(result, address);
// Release the Java string and local references
(*envPtr)->ReleaseStringUTFChars(envPtr, addressString, address);
(*envPtr)->DeleteLocalRef(envPtr, socketClass);
(*envPtr)->DeleteLocalRef(envPtr, deviceClass);
return result;
}
jobject connectToBluetoothServer(uintptr_t env, jobject bluetoothAdapter, const char* serverAddress, char** errorMsg) {
JNIEnv* envPtr = (JNIEnv*) env;
// Get the BluetoothDevice class
jclass bluetoothDeviceClass = (*envPtr)->FindClass(envPtr, "android/bluetooth/BluetoothDevice");
if (bluetoothDeviceClass == NULL) {
copyToError("Failed to find BluetoothDevice class", errorMsg);
return NULL;
}
// Get the getRemoteDevice method from BluetoothAdapter
jclass bluetoothAdapterClass = (*envPtr)->GetObjectClass(envPtr, bluetoothAdapter);
if (bluetoothAdapterClass == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, bluetoothDeviceClass);
copyToError("Failed to get BluetoothAdapter class", errorMsg);
return NULL;
}
jmethodID getRemoteDeviceMethod = (*envPtr)->GetMethodID(envPtr, bluetoothAdapterClass, "getRemoteDevice", "(Ljava/lang/String;)Landroid/bluetooth/BluetoothDevice;");
if (getRemoteDeviceMethod == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, bluetoothAdapterClass);
(*envPtr)->DeleteLocalRef(envPtr, bluetoothDeviceClass);
copyToError("Failed to get getRemoteDevice method", errorMsg);
return NULL;
}
// Get the BluetoothDevice object
jstring serverAddressString = (*envPtr)->NewStringUTF(envPtr, serverAddress);
jobject bluetoothDevice = (*envPtr)->CallObjectMethod(envPtr, bluetoothAdapter, getRemoteDeviceMethod, serverAddressString);
if (bluetoothDevice == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, bluetoothAdapterClass);
(*envPtr)->DeleteLocalRef(envPtr, bluetoothDeviceClass);
(*envPtr)->DeleteLocalRef(envPtr, serverAddressString);
copyToError("Failed to get the BluetoothDevice object", errorMsg);
return NULL;
}
// Get the createRfcommSocket method from BluetoothDevice
jmethodID createRfcommSocketMethod = (*envPtr)->GetMethodID(envPtr, bluetoothDeviceClass, "createRfcommSocket", "(I)Landroid/bluetooth/BluetoothSocket;");
if (createRfcommSocketMethod == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, bluetoothAdapterClass);
(*envPtr)->DeleteLocalRef(envPtr, bluetoothDeviceClass);
(*envPtr)->DeleteLocalRef(envPtr, serverAddressString);
(*envPtr)->DeleteLocalRef(envPtr, bluetoothDevice);
copyToError("Failed to get createRfcommSocket method", errorMsg);
return NULL;
}
// Create the BluetoothSocket object
jobject bluetoothSocket = (*envPtr)->CallObjectMethod(envPtr, bluetoothDevice, createRfcommSocketMethod, 1);
if (bluetoothSocket == NULL) {
copyToError("Failed: bluetoothSocket == NULL", errorMsg);
}
// Clean up local references
(*envPtr)->DeleteLocalRef(envPtr, bluetoothAdapterClass);
(*envPtr)->DeleteLocalRef(envPtr, bluetoothDeviceClass);
(*envPtr)->DeleteLocalRef(envPtr, serverAddressString);
(*envPtr)->DeleteLocalRef(envPtr, bluetoothDevice);
return bluetoothSocket;
}
jobject getBluetoothOutputStream(uintptr_t env, jobject clientSocket, char** errorMsg) {
JNIEnv *envPtr = (JNIEnv*)env;
// Get the BluetoothSocket class
jclass socketClass = (*envPtr)->GetObjectClass(envPtr, clientSocket);
if (socketClass == NULL) {
copyToError( "Failed to get the BluetoothSocket class", errorMsg);
return NULL;
}
// Get the getOutputStream method
jmethodID getOutputStreamMethod = (*envPtr)->GetMethodID(envPtr, socketClass, "getOutputStream", "()Ljava/io/OutputStream;");
if (getOutputStreamMethod == NULL) {
copyToError( "Failed to get getOutputStream method", errorMsg);
(*envPtr)->DeleteLocalRef(envPtr, socketClass);
return NULL;
}
// Call the getOutputStream method
jobject outputStream = (*envPtr)->CallObjectMethod(envPtr, clientSocket, getOutputStreamMethod);
if (outputStream == NULL) {
copyToError( "Failed to get OutputStream", errorMsg);
(*envPtr)->DeleteLocalRef(envPtr, socketClass);
}
// Release local references
(*envPtr)->DeleteLocalRef(envPtr, socketClass);
return outputStream;
}
jobject getBluetoothInputStream(uintptr_t env, jobject clientSocket, char** errorMsg) {
JNIEnv *envPtr = (JNIEnv*)env;
// Get the BluetoothSocket class
jclass socketClass = (*envPtr)->GetObjectClass(envPtr, clientSocket);
if (socketClass == NULL) {
copyToError( "Failed to get the BluetoothSocket class", errorMsg);
return NULL;
}
// Get the getInputStream method
jmethodID getInputStreamMethod = (*envPtr)->GetMethodID(envPtr, socketClass, "getInputStream", "()Ljava/io/InputStream;");
if (getInputStreamMethod == NULL) {
copyToError( "Failed to get getInputStream method", envPtr);
(*envPtr)->DeleteLocalRef(envPtr, socketClass);
return NULL;
}
// Call the getInputStream method
jobject inputStream = (*envPtr)->CallObjectMethod(envPtr, clientSocket, getInputStreamMethod);
if (inputStream == NULL) {
copyToError( "Failed to get InputStream", errorMsg);
}
// Release local references
(*envPtr)->DeleteLocalRef(envPtr, socketClass);
return inputStream;
}
void closeStream0(uintptr_t env, jobject stream, char** errorMsg) {
if (stream == NULL){
return;
copyToError("empty (null) stream is not able delete", errorMsg);
}
JNIEnv *envPtr = (JNIEnv*)env;
//get stream class
jclass streamClass = (*envPtr)->GetObjectClass(envPtr, stream);
if (streamClass == NULL) {
copyToError( "Failed to get the streamClass class", errorMsg);
return;
}
jmethodID closeMethod = (*envPtr)->GetMethodID(envPtr, streamClass, "close", "()V");
if (closeMethod != NULL) {
(*envPtr)->CallVoidMethod(envPtr, stream, closeMethod);
} else {
copyToError("Failed to close output stream", errorMsg);
}
(*envPtr)->DeleteLocalRef(env, streamClass);
(*envPtr)->DeleteLocalRef(env, stream);
}
char* readFromInputStream(uintptr_t env, jobject inputStream, int size, int* count, char** errorMsg) {
JNIEnv* envPtr = (JNIEnv*)env;
// Get the InputStream class
jclass inputStreamClass = (*envPtr)->GetObjectClass(envPtr, inputStream);
if (inputStreamClass == NULL) {
copyToError( "Failed to get the InputStream class", errorMsg);
return NULL;
}
// Get the read method from InputStream
jmethodID readMethod = (*envPtr)->GetMethodID(envPtr, inputStreamClass, "read", "([B)I");
if (readMethod == NULL) {
*count = -1;
(*envPtr)->DeleteLocalRef(envPtr, inputStreamClass);
copyToError("Failed to get read method", errorMsg);
return NULL;
}
// Create a byte array for reading data
jbyteArray byteArray = (*envPtr)->NewByteArray(envPtr, size);
if (byteArray == NULL) {
*count = -1;
(*envPtr)->DeleteLocalRef(envPtr, inputStreamClass);
copyToError( "Failed to create byte array", errorMsg);
return NULL;
}
// Call the read method
jint bytesRead = (*envPtr)->CallIntMethod(envPtr, inputStream, readMethod, byteArray);
if (bytesRead < 0) {
*count = -1;
(*envPtr)->DeleteLocalRef(envPtr, inputStreamClass);
(*envPtr)->DeleteLocalRef(envPtr, byteArray);
copyToError("Failed to read from input stream", errorMsg);
return NULL;
}
// Copy the bytes from the byte array to a new buffer
jbyte* byteBuffer = (*envPtr)->GetByteArrayElements(envPtr, byteArray, NULL);
if (byteArray == NULL) {
*count = -1;
(*envPtr)->DeleteLocalRef(envPtr, inputStreamClass);
(*envPtr)->DeleteLocalRef(envPtr, byteArray);
copyToError( "Failed to get byte array address", errorMsg);
return NULL;
}
char* buffer = (char*)malloc(bytesRead * sizeof(char));
memcpy(buffer, byteBuffer, bytesRead);
// Release memory
(*envPtr)->DeleteLocalRef(envPtr, inputStreamClass);
(*envPtr)->DeleteLocalRef(envPtr, byteArray);
(*envPtr)->ReleaseByteArrayElements(envPtr, byteArray, byteBuffer, 0);
// Set the count
*count = (int)bytesRead;
return buffer;
}
void writeToOutputStream(uintptr_t env, jobject outputStream, const char* buffer, int size, char** errorMsg) {
JNIEnv* envPtr = (JNIEnv*)env;
// Get the OutputStream class
jclass outputStreamClass = (*envPtr)->GetObjectClass(envPtr, outputStream);
if (outputStreamClass == NULL) {
copyToError( "Failed to get the OutputStream class", errorMsg);
return;
}
// Get the write method from OutputStream
jmethodID writeMethod = (*envPtr)->GetMethodID(envPtr, outputStreamClass, "write", "([B)V");
if (writeMethod == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, outputStreamClass);
copyToError("Failed to get write method", errorMsg);
return;
}
// Create a byte array from the buffer
jbyteArray byteArray = (*envPtr)->NewByteArray(envPtr, size);
if (byteArray == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, outputStreamClass);
copyToError("Failed to create byte array", errorMsg);
return;
}
(*envPtr)->SetByteArrayRegion(envPtr, byteArray, 0, size, (jbyte*)buffer);
// Call the write method
(*envPtr)->CallVoidMethod(envPtr, outputStream, writeMethod, byteArray);
// Release memory
(*envPtr)->DeleteLocalRef(envPtr, outputStreamClass);
(*envPtr)->DeleteLocalRef(envPtr, byteArray);
return;
}
jobject getBluetoothAdapter(uintptr_t env, char** errorMsg) {
JNIEnv* envPtr = (JNIEnv*)env;
// Get the BluetoothAdapter class
jclass bluetoothAdapterClass = (*envPtr)->FindClass(envPtr, "android/bluetooth/BluetoothAdapter");
if (bluetoothAdapterClass == NULL) {
copyToError("Failed to find BluetoothAdapter class", errorMsg);
return NULL;
}
// Get the getDefaultAdapter static method
jmethodID getDefaultAdapterMethod = (*envPtr)->GetStaticMethodID(envPtr, bluetoothAdapterClass, "getDefaultAdapter", "()Landroid/bluetooth/BluetoothAdapter;");
if (getDefaultAdapterMethod == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, bluetoothAdapterClass);
copyToError("Failed to find getDefaultAdapter method", errorMsg);
return NULL;
}
// Get the BluetoothAdapter object
jobject bluetoothAdapter = (*envPtr)->CallStaticObjectMethod(envPtr, bluetoothAdapterClass, getDefaultAdapterMethod);
if (bluetoothAdapter == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, bluetoothAdapterClass);
copyToError("Failed to invoke getDefaultAdapter method", errorMsg);
return NULL;
}
// Release memory
(*envPtr)->DeleteLocalRef(envPtr, bluetoothAdapterClass);
return bluetoothAdapter;
}
char* getBluetoothName(uintptr_t env, jobject bluetoothAdapter, char** errorMsg) {
JNIEnv* envPtr = (JNIEnv*)env;
// Get BluetoothAdapter class
jclass bluetoothAdapterClass = (*envPtr)->GetObjectClass(envPtr, bluetoothAdapter);
if (bluetoothAdapterClass == NULL) {
copyToError("Failed to find BluetoothAdapter class", errorMsg);
return NULL;
}
// Get the getName method
jmethodID getNameMethod = (*envPtr)->GetMethodID(envPtr, bluetoothAdapterClass, "getName", "()Ljava/lang/String;");
// If the method is not available, return NULL
if (getNameMethod == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, bluetoothAdapterClass);
copyToError("Failed to get getName method", errorMsg);
return NULL;
}
// Call the getName method
jstring bluetoothName = (jstring)(*envPtr)->CallObjectMethod(envPtr, bluetoothAdapter, getNameMethod);
if (bluetoothName == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, bluetoothAdapterClass);
copyToError("Bluetooth name is NULL", errorMsg);
return NULL;
}
// Convert jstring to char*
const char* nameChars = (*envPtr)->GetStringUTFChars(envPtr, bluetoothName, NULL);
if (bluetoothName == NULL) {
(*envPtr)->DeleteLocalRef(envPtr, bluetoothAdapterClass);
copyToError("Failed convert jstring to char*", errorMsg);
return NULL;
}
size_t length = strlen(nameChars);
char* heapString = (char*)malloc((length + 1) * sizeof(char));
strcpy(heapString, nameChars);
// Release memory
(*envPtr)->ReleaseStringUTFChars(envPtr, bluetoothName, nameChars);
(*envPtr)->DeleteLocalRef(envPtr, bluetoothAdapterClass);
(*envPtr)->DeleteLocalRef(envPtr, bluetoothName);
return heapString;
}
bool enableBluetooth(uintptr_t env, jobject bluetoothAdapter, char** errorMsg) {
JNIEnv* envPtr = (JNIEnv*)env;
// Get the enable method
jclass bluetoothAdapterClass = (*envPtr)->GetObjectClass(envPtr, bluetoothAdapter);
jmethodID enableMethod = (*envPtr)->GetMethodID(envPtr, bluetoothAdapterClass, "enable", "()Z");
if (enableMethod == NULL) {
copyToError("Failed to find enable method", errorMsg);
(*envPtr)->DeleteLocalRef(envPtr, bluetoothAdapterClass);
return false;
}
// Invoke the enable method
jboolean result = (*envPtr)->CallBooleanMethod(envPtr, bluetoothAdapter, enableMethod);
if ((*envPtr)->ExceptionCheck(envPtr)) {
copyToError("Failed to invoke enable method", errorMsg);
(*envPtr)->DeleteLocalRef(envPtr, bluetoothAdapterClass);
return false;
}
// Release memory
(*envPtr)->DeleteLocalRef(envPtr, bluetoothAdapterClass);
return result;
}
void freeBluetoothAdapter(uintptr_t env, jobject bluetoothAdapter, char** errorMsg) {
if (bluetoothAdapter != NULL) {
JNIEnv* envPtr = (JNIEnv*)env;
// Get BluetoothAdapter class
jclass bluetoothAdapterClass = (*envPtr)->GetObjectClass(envPtr, bluetoothAdapter);
// Get the close method
jmethodID closeMethod = (*envPtr)->GetMethodID(envPtr, bluetoothAdapterClass, "close", "()V");
// If the method is not available, set error and return
if (closeMethod == NULL) {
copyToError( "Failed to get close method", errorMsg);
return;
}
// Call the close method
(*envPtr)->CallVoidMethod(envPtr, bluetoothAdapter, closeMethod);
// Delete local references
(*envPtr)->DeleteLocalRef(envPtr, bluetoothAdapterClass);
(*envPtr)->DeleteLocalRef(envPtr, bluetoothAdapter);
}
}
*/
import "C"
import (
"bytes"
"errors"
"fmt"
"fyne.io/fyne/v2/internal/driver/mobile/mobileinit"
"net"
"unsafe"
)
// adapter
// adapterAndroid has references android.bluetooth.BluetoothAdapter in java on android
type adapterAndroid struct {
javaAdapter C.jobject
stop chan struct{}
}
// socket
// socketAndroid is representing bluetooth socket on android
type socketAndroid struct {
javaSocket C.jobject
rw *readWriterAndroid
}
// serverSocket
// serverSocketAndroid is representing bluetooth server socket on android
type serverSocketAndroid struct {
javaServerSocket C.jobject
}
// readWriterAndroid has java input and output stream on android
type readWriterAndroid struct {
in, out C.jobject
}
// NewBluetoothDefaultAdapter get Bluetooth adapter
func NewBluetoothDefaultAdapter() (_ Adapter, e error) {
var bb *adapterAndroid
err := mobileinit.RunOnJVM(func(vm, env, ctx uintptr) error {
var errMsgC *C.char
adapter := C.getBluetoothAdapter(C.uintptr_t(env), &errMsgC)
if errMsgC != nil {
er := errors.New(C.GoString(errMsgC))
C.free(unsafe.Pointer(errMsgC))
e = er
return nil
}
bb = &adapterAndroid{javaAdapter: adapter, stop: make(chan struct{})}
return nil
})
enable, err := bb.enable()
if err != nil {
return nil, errors.Join(err, bb.Close())
}
if !enable {
return nil, errors.Join(errors.New("not available bluetooth"), bb.Close())
}
return bb, errors.Join(e, err)
}
func (a *adapterAndroid) GetAddress() (str string, e error) {
interfaces, err := net.Interfaces()
if err == nil {
for _, i := range interfaces {
if i.Flags&net.FlagUp != 0 && bytes.Compare(i.HardwareAddr, nil) != 0 {
// Don't use random as we have a real address
return i.HardwareAddr.String(), nil
}
}
}
return "", errors.New("not found")
}
// Close clean bluetooth adapter from memory
func (a *adapterAndroid) Close() (e error) {
err := mobileinit.RunOnJVM(func(vm, env, ctx uintptr) error {
var errMsgC *C.char
C.freeBluetoothAdapter(C.uintptr_t(env), a.javaAdapter, &errMsgC)
if errMsgC != nil {
e = errors.New(C.GoString(errMsgC))
C.free(unsafe.Pointer(errMsgC))
}
return nil
})
return errors.Join(e, err)
}
// GetBluetoothServerSocket returns ServerSocket which is listening on bluetooth
func (a *adapterAndroid) GetBluetoothServerSocket() (bs ServerSocket, e error) {
err := mobileinit.RunOnJVM(func(vm, env, ctx uintptr) error {
var errMsgC *C.char
socket := C.createBluetoothServer(C.uintptr_t(env), a.javaAdapter, &errMsgC)
if errMsgC != nil {
err := errors.New(C.GoString(errMsgC))
C.free(unsafe.Pointer(errMsgC))
bs, e = nil, err
return nil
}
bs = &serverSocketAndroid{javaServerSocket: socket}
return nil
})
return bs, errors.Join(e, err)
}
// ConnectAsClientToServer take MAC address of server and
// return conection in BluetoothSocket
func (a *adapterAndroid) ConnectAsClientToServer(address string) (bs Socket, e error) {
err := mobileinit.RunOnJVM(func(vm, env, ctx uintptr) error {
var errMsgC *C.char
caddress := C.CString(address)
defer C.free(unsafe.Pointer(caddress))
sock := C.connectToBluetoothServer(C.uintptr_t(env), a.javaAdapter, caddress, &errMsgC)
if errMsgC != nil {
e = errors.New(C.GoString(errMsgC))
C.free(unsafe.Pointer(errMsgC))
return nil
}
bs = &socketAndroid{javaSocket: sock}
return nil
})
return bs, errors.Join(err, e)
}
func (a *adapterAndroid) enable() (b bool, e error) {
err := mobileinit.RunOnJVM(func(vm, env, ctx uintptr) error {
var errMsgC *C.char
b = bool(C.enableBluetooth(C.uintptr_t(env), a.javaAdapter, &errMsgC))
if errMsgC != nil {
e = errors.New(C.GoString(errMsgC))
C.free(unsafe.Pointer(errMsgC))
}
return nil
})
return b, errors.Join(e, err)
}
func (b *serverSocketAndroid) Close() (e error) {
err := mobileinit.RunOnJVM(func(vm, env, ctx uintptr) error {
var errMsgC *C.char
C.closeBluetoothServerSocket(C.uintptr_t(env), b.javaServerSocket, &errMsgC)
if errMsgC != nil {
e = errors.New(C.GoString(errMsgC))
C.free(unsafe.Pointer(errMsgC))
}
return nil
})
return errors.Join(e, err)
}
// Accept accepting client and return conection in BluetoothSocket
func (b *serverSocketAndroid) Accept() (bs Socket, e error) {
var errMsgC *C.char
err := mobileinit.RunOnJVM(func(vm, env, ctx uintptr) error {
sock := C.acceptBluetoothClient(C.uintptr_t(env), b.javaServerSocket, &errMsgC)
if errMsgC != nil {
e = errors.New(C.GoString(errMsgC))
C.free(unsafe.Pointer(errMsgC))
}
bs = &socketAndroid{javaSocket: sock}
return nil
})
return bs, errors.Join(err, e)
}
func (b *socketAndroid) StringData() (string, error) {
name, err := b.fetchName()
if err != nil {
return "", err
}
addr, err := b.fetchAddress()
if err != nil {
return "", err
}
return fmt.Sprintf("mac: %s, name: %s", addr, name), nil
}
func (b *socketAndroid) Read(bytes []byte) (int, error) {
if b.rw == nil {
var err error
b.rw, err = b.getReadWriter()
if err != nil {
return 0, err
}
}
return b.rw.Read(bytes)
}
func (b *socketAndroid) Write(bytes []byte) (int, error) {
if b.rw == nil {
var err error
b.rw, err = b.getReadWriter()
if err != nil {
return 0, err
}
}
return b.rw.Write(bytes)
}
func (b *socketAndroid) fetchName() (res string, e error) {
err := mobileinit.RunOnJVM(func(vm, env, ctx uintptr) error {
var errMsgC *C.char
nameC := C.getClientName(C.uintptr_t(env), b.javaSocket, &errMsgC)
if errMsgC != nil {
e = errors.New(C.GoString(errMsgC))
C.free(unsafe.Pointer(errMsgC))
return nil
}
res = C.GoString(nameC)
C.free(unsafe.Pointer(nameC))
return nil
})
return res, errors.Join(err, e)
}
func (b *socketAndroid) fetchAddress() (res string, e error) {
err := mobileinit.RunOnJVM(func(vm, env, ctx uintptr) error {
var errMsgC *C.char
nameC := C.getClientAddress(C.uintptr_t(env), b.javaSocket, &errMsgC)
if errMsgC != nil {
e = errors.New(C.GoString(errMsgC))
C.free(unsafe.Pointer(errMsgC))
return nil
}
res = C.GoString(nameC)
C.free(unsafe.Pointer(nameC))
return nil
})
return res, errors.Join(err, e)
}
// Close is closing socket
func (b *socketAndroid) Close() (e error) {
err := mobileinit.RunOnJVM(func(vm, env, ctx uintptr) error {
var errMsgC *C.char
C.closeBluetoothServerSocket(C.uintptr_t(env), b.javaSocket, &errMsgC)
if errMsgC != nil {
e = errors.New(C.GoString(errMsgC))
C.free(unsafe.Pointer(errMsgC))
}
return nil
})
return errors.Join(e, err, b.rw.Close())
}
func (b *socketAndroid) getReadWriter() (rw *readWriterAndroid, e error) {
var errMsgC *C.char
rw = &readWriterAndroid{}
err := mobileinit.RunOnJVM(func(vm, env, ctx uintptr) error {
inputStream := C.getBluetoothInputStream(C.uintptr_t(env), b.javaSocket, &errMsgC)
if errMsgC != nil {
e = errors.New(C.GoString(errMsgC))
C.free(unsafe.Pointer(errMsgC))
return nil
}
outputStream := C.getBluetoothOutputStream(C.uintptr_t(env), b.javaSocket, &errMsgC)
if errMsgC != nil {
e = errors.New(C.GoString(errMsgC))
C.free(unsafe.Pointer(errMsgC))
_ = rw.close(inputStream)
return nil
}
rw.in = inputStream
rw.out = outputStream
return nil
})
return rw, errors.Join(err, e)
}
func (r *readWriterAndroid) Read(p []byte) (n int, err error) {
if p == nil || len(p) == 0 {
return -1, errors.New("empty buffer")
}
er := mobileinit.RunOnJVM(func(vm, env, ctx uintptr) error {
var errMsgC *C.char
var result C.int
dataC := C.readFromInputStream(C.uintptr_t(env), r.in, C.int(cap(p)), &result, &errMsgC)
if errMsgC != nil {
err = errors.New(C.GoString(errMsgC))
C.free(unsafe.Pointer(errMsgC))
n = -1
return nil
}
n = int(result)
if n < 1 {
return nil
}
dataGo := C.GoBytes(unsafe.Pointer(dataC), C.int(n))
copy(p, dataGo)
C.free(unsafe.Pointer(dataC))
return nil
})
err = errors.Join(er, err)
return
}
func (r *readWriterAndroid) Write(p []byte) (n int, err error) {
if p == nil || len(p) == 0 {
return 0, errors.New("empty buffer")
}
er := mobileinit.RunOnJVM(func(vm, env, ctx uintptr) error {
var errMsgC *C.char
C.writeToOutputStream(C.uintptr_t(env), r.in, (*C.char)(unsafe.Pointer(&p[0])), C.int(cap(p)), &errMsgC)
if errMsgC != nil {
err = errors.New(C.GoString(errMsgC))
C.free(unsafe.Pointer(errMsgC))
}
n = len(p)
return nil
})
return n, errors.Join(er, err)
}
func (r *readWriterAndroid) Close() error {
return errors.Join(r.close(r.in), r.close(r.out))
}
func (r *readWriterAndroid) close(stream C.jobject) (e error) {
var errMsgC *C.char
err := mobileinit.RunOnJVM(func(vm, env, ctx uintptr) error {
C.closeStream0(C.uintptr_t(env), stream, &errMsgC)
return nil
})
if errMsgC != nil {
e = errors.New(C.GoString(errMsgC))
C.free(unsafe.Pointer(errMsgC))
}
return errors.Join(err, e)
}