-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWearEngineHelper.kt
More file actions
910 lines (825 loc) · 32.1 KB
/
WearEngineHelper.kt
File metadata and controls
910 lines (825 loc) · 32.1 KB
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
/**
* WearEngineHelper - A wrapper for Huawei WearEngine SDK
*
* This helper simplifies communication between a mobile app and Huawei watches,
* supporting both legacy and next-generation HarmonyOS devices.
*
* Copyright (c) 2025
* Younes Megaache
* Created 10 March 2025
*/
package com.younes.wearenginehelper
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.huawei.wearengine.HiWear
import com.huawei.wearengine.WearEngineException
import com.huawei.wearengine.auth.AuthCallback
import com.huawei.wearengine.auth.AuthClient
import com.huawei.wearengine.auth.Permission
import com.huawei.wearengine.common.WearEngineErrorCode
import com.huawei.wearengine.device.Device
import com.huawei.wearengine.device.DeviceClient
import com.huawei.wearengine.p2p.Message
import com.huawei.wearengine.p2p.P2pClient
import com.huawei.wearengine.p2p.Receiver
import com.huawei.wearengine.p2p.SendCallback
import kotlinx.coroutines.suspendCancellableCoroutine
import java.io.File
import kotlin.coroutines.resume
/**
* WearEngineHelper provides a simplified interface for communication with Huawei watches.
*
* Features:
* - Send and receive messages between mobile and watch apps
* - Support for both legacy and next-gen Huawei watch devices
* - Automatic permission handling
* - Builder pattern for configuration
*
* @param context Application context
*/
class WearEngineHelper private constructor(
private val context: Context,
private val config: WearEngineConfig
) {
/**
* Configuration class for WearEngineHelper
*/
data class WearEngineConfig(
/** Package name for legacy/lite watch devices */
val watchPackageName: String,
/** Debug fingerprint for legacy/lite devices */
val watchFingerprintDebug: String,
/** Release fingerprint for legacy/lite devices */
val watchFingerprintRelease: String,
/** Package name for next-gen watches (null uses legacy name) */
val watchPackageNameNext: String? = null,
/** App ID for next-gen watches */
val watchAppId: String? = null,
/** List of required permissions */
val permissions: Array<Permission> = arrayOf(Permission.DEVICE_MANAGER),
/** Debug mode flag (true for development, false for production) */
val isDebugMode: Boolean = false,
/** Custom log tag */
val logTag: String = DEFAULT_LOG_TAG,
/** Enable detailed logging */
val verboseLogging: Boolean = false
)
/**
* Builder for WearEngineHelper configuration
*/
class Builder(private val context: Context) {
private var watchPackageName: String? = null
private var watchFingerprintDebug: String? = null
private var watchFingerprintRelease: String? = null
private var watchPackageNameNext: String? = null
private var watchAppId: String? = null
private var permissions: Array<Permission> = arrayOf(Permission.DEVICE_MANAGER)
private var isDebugMode: Boolean = false
private var logTag: String = DEFAULT_LOG_TAG
private var verboseLogging: Boolean = false
/**
* Sets the package name for legacy/lite watch devices.
* @param packageName The watch app's package name
*/
fun setWatchPackageName(packageName: String) = apply {
this.watchPackageName = packageName
}
/**
* Sets the debug fingerprint for legacy/lite watch devices.
* @param fingerprint The debug version fingerprint
*/
fun setWatchFingerprintDebug(fingerprint: String) = apply {
this.watchFingerprintDebug = fingerprint
}
/**
* Sets the release fingerprint for legacy/lite watch devices.
* @param fingerprint The release version fingerprint
*/
fun setWatchFingerprintRelease(fingerprint: String) = apply {
this.watchFingerprintRelease = fingerprint
}
/**
* Sets the package name for next-gen watch devices.
* Required only for supporting both legacy and new watch devices.
* @param packageName The next-gen watch app's package name
*/
fun setWatchPackageNameNextGen(packageName: String) = apply {
this.watchPackageNameNext = packageName
}
/**
* Sets the app ID for next-gen watch devices.
* @param appId The next-gen watch app's ID
*/
fun setWatchAppId(appId: String) = apply {
this.watchAppId = appId
}
fun setPermissions(permissions: Array<Permission>) = apply {
this.permissions = permissions
}
/**
* Sets whether the watch app is in debug mode.
* @param isDebug True for debug mode, false for release
*/
fun setDebugMode(isDebug: Boolean) = apply {
this.isDebugMode = isDebug
}
/**
* Sets a custom log tag for the helper.
* @param tag Custom log tag
*/
fun setLogTag(tag: String) = apply {
this.logTag = tag
}
/**
* Enables or disables verbose logging.
* @param enable True to enable verbose logging
*/
fun enableVerboseLogging(enable: Boolean) = apply {
this.verboseLogging = enable
}
/**
* Builds a WearEngineHelper instance with the configured parameters.
* @throws IllegalArgumentException if required parameters are missing
*/
fun build(): WearEngineHelper {
// Validate required parameters
val packageName =
watchPackageName ?: throw IllegalArgumentException("Watch package name must be set")
val fingerprintDebug = watchFingerprintDebug
?: throw IllegalArgumentException("Debug fingerprint must be set")
val fingerprintRelease = watchFingerprintRelease
?: throw IllegalArgumentException("Release fingerprint must be set")
val config = WearEngineConfig(
watchPackageName = packageName,
watchFingerprintDebug = fingerprintDebug,
watchFingerprintRelease = fingerprintRelease,
watchPackageNameNext = watchPackageNameNext,
watchAppId = watchAppId,
permissions = permissions,
isDebugMode = isDebugMode,
logTag = logTag,
verboseLogging = verboseLogging
)
return WearEngineHelper(context, config)
}
}
// Lazy-initialized clients
private val authClient: AuthClient by lazy { HiWear.getAuthClient(context) }
private val deviceClient: DeviceClient by lazy { HiWear.getDeviceClient(context) }
private val p2pClient: P2pClient by lazy { initP2pClient() }
private var connectedDevice: Device? = null
private var receiver: Receiver? = null
// Main thread handler to dispatch callbacks
private val mainHandler = Handler(Looper.getMainLooper())
// Client initialization
private fun initP2pClient(): P2pClient {
return HiWear.getP2pClient(context).apply {
val isNextGen = connectedDevice?.let {
isNextGenDevice(it.model)
} ?: false
log("Initializing P2pClient, isNextGen: $isNextGen")
setPeerPkgName(
if (isNextGen && config.watchPackageNameNext != null)
config.watchPackageNameNext
else
config.watchPackageName
)
setPeerFingerPrint(
if (isNextGen && config.watchAppId != null)
config.watchAppId
else if (config.isDebugMode)
config.watchFingerprintDebug
else
config.watchFingerprintRelease
)
}
}
/**
* Checks if a device is a next-generation watch device.
* @param deviceModel The device model string
* @return true if it's a next-gen device, false otherwise
*/
private fun isNextGenDevice(deviceModel: String): Boolean {
val keywords = listOf("rts", "soc", "rates")
val model = deviceModel.lowercase()
return keywords.any { keyword -> model.contains(keyword) }
}
/**
* Sends a string message (max 1 KB) to the connected Huawei watch.
*
* @param data The data message to send (must be less than 1KB)
* @param onDeviceConnected Callback when device is connected, provides connected watch name
* @param onSuccess Callback on successful message delivery
* @param onError Callback when an error occurs with error message and code
*/
fun sendMessageToWatch(
data: String,
onDeviceConnected: (String) -> Unit,
onSuccess: () -> Unit,
onError: (String, Int) -> Unit
) {
// Convert data to bytes
val messageBytes = data.toByteArray()
// Check message size
if (messageBytes.size > MAX_MESSAGE_SIZE) {
runOnMainThread {
onError(
"Message size exceeds the ${MAX_MESSAGE_SIZE} byte limit",
-1
)
}
return
}
// Handle permissions and send message
checkAndRequestPermissions { permissionsGranted ->
if (permissionsGranted) {
sendMessageToWatchImpl(
messageBytes,
onDeviceConnected,
onSuccess,
onError
)
} else {
runOnMainThread {
onError(
"Permissions not granted",
WearEngineErrorCode.ERROR_CODE_USER_UNAUTHORIZED_IN_HEALTH
)
}
}
}
}
/**
* Sends a large string message (max 4KB) to the connected Huawei watch.
* if the message is less than 1KB then use the method [sendMessageToWatch] which is fasterD
*
* Important: Wait for the previous message to complete before sending another one.
* Sending multiple messages concurrently may cause data corruption.
*
* @param data The data message to send (max 4KB)
* @param onDeviceConnected Callback when device is connected, provides connected watch name
* @param onSuccess Callback on successful message delivery
* @param onError Callback when an error occurs with error message and code
*/
fun sendLargeMessageToWatch(
data: String,
onDeviceConnected: (String) -> Unit,
onSuccess: () -> Unit,
onError: (String, Int) -> Unit
) {
// Convert data to bytes
val messageBytes = data.toByteArray()
// Check message size
if (messageBytes.size > MAX_LARGE_MESSAGE_SIZE) {
runOnMainThread {
onError(
"Large message size exceeds the $MAX_LARGE_MESSAGE_SIZE byte limit",
-1
)
}
return
}
val tempFile = File(context.cacheDir, TEMP_FILE_NAME)
try {
// Create a temporary file
tempFile.writeBytes(messageBytes)
// Send the file
sendFileToWatch(
tempFile,
onDeviceConnected,
{
// Delete temp file after successful send
tempFile.delete()
runOnMainThread { onSuccess() }
},
{ errorMsg, errorCode ->
// Delete temp file on error
tempFile.delete()
runOnMainThread { onError(errorMsg, errorCode) }
}
)
} catch (e: Exception) {
if (tempFile.exists()) {
tempFile.delete()
}
logError("Error creating temporary file for large message", e)
runOnMainThread {
onError(
getErrorMessage(e, "Failed to create temporary file"),
getErrorCode(e)
)
}
}
}
/**
* Sends a file message (max 100MB) to the connected Huawei watch.
*
* @param file File message to send (must be less than 100MB)
* @param onDeviceConnected Callback when device is connected, provides connected watch name
* @param onSuccess Callback on successful message delivery
* @param onError Callback when an error occurs with error message and code
*/
fun sendFileToWatch(
file: File,
onDeviceConnected: (String) -> Unit,
onSuccess: () -> Unit,
onError: (String, Int) -> Unit,
onProgress: ((Long) -> Unit)? = null
) {
// Check file existence and size
if (!file.exists()) {
runOnMainThread { onError("File does not exist", -1) }
return
}
if (file.length() > MAX_FILE_SIZE) {
runOnMainThread { onError("File size exceeds the $MAX_FILE_SIZE byte limit", -1) }
return
}
// Handle permissions and send file
checkAndRequestPermissions { permissionsGranted ->
if (permissionsGranted) {
getConnectedDevice(
onDeviceConnected = onDeviceConnected,
onError = onError,
onSuccess = {
if (connectedDevice == null) {
runOnMainThread {
onError(
"No connected watch found",
WearEngineErrorCode.ERROR_CODE_DEVICE_IS_NOT_CONNECTED
)
}
return@getConnectedDevice
}
// Check if watch app is running
checkWatchAppStatus(
onAppRunning = {
// Send file to watch
val message = Message.Builder()
.setPayload(file)
.build()
try {
log("Sending file to watch (${file.length()} bytes)")
p2pClient.send(connectedDevice, message, object : SendCallback {
override fun onSendProgress(progress: Long) {
runOnMainThread { onProgress?.invoke(progress) }
if (config.verboseLogging) {
log("File send progress: $progress")
}
}
override fun onSendResult(code: Int) {
if (code == WearEngineErrorCode.ERROR_CODE_COMM_SUCCESS) {
log("File sent successfully")
runOnMainThread { onSuccess() }
} else {
log("Failed to send file, code: $code")
runOnMainThread {
onError(
"Failed to send file",
code
)
}
}
}
})
} catch (e: Exception) {
logError("Error sending file to device", e)
runOnMainThread { onError(getErrorMessage(e), getErrorCode(e)) }
}
},
onError = onError
)
}
)
} else {
runOnMainThread {
onError(
"Permissions not granted",
WearEngineErrorCode.ERROR_CODE_USER_UNAUTHORIZED_IN_HEALTH
)
}
}
}
}
/**
* Checks if the user has a compatible Huawei watch connected.
*
* @param onResult Callback with the result (true if available)
*/
fun hasConnectedWatch(onResult: (Boolean) -> Unit) {
deviceClient.hasAvailableDevices()
.addOnSuccessListener {
log("Has available devices: $it")
onResult(it)
}
.addOnFailureListener { e ->
logError("Failed to get available devices", e)
onResult(false)
}
}
/**
* Registers a receiver for incoming messages from the watch.
*
* @param onDeviceConnected Callback when device is connected
* @param onMessageReceived Callback for received messages
* @param onError Callback for errors
*/
fun registerReceiver(
onDeviceConnected: (String) -> Unit,
onMessageReceived: (String) -> Unit,
onError: (String, Int) -> Unit,
onFileReceived: ((File) -> Unit)? = null,
) {
checkAndRequestPermissions { permissionsGranted ->
if (permissionsGranted) {
getConnectedDevice(
onDeviceConnected = onDeviceConnected,
onError = onError,
onSuccess = {
if (connectedDevice == null) {
runOnMainThread {
onError(
"No connected watch found",
WearEngineErrorCode.ERROR_CODE_DEVICE_IS_NOT_CONNECTED
)
}
return@getConnectedDevice
}
// Unregister existing receiver if any
unregisterReceiver()
// Create new receiver
receiver = Receiver { message ->
log("Received message: $message")
runOnMainThread {
when (message.type) {
Message.MESSAGE_TYPE_FILE -> message.file?.let { onFileReceived?.invoke(it) }
else -> message.data?.let {
onMessageReceived(it.toString(Charsets.UTF_8))
}
}
}
}
// Register the receiver
p2pClient.registerReceiver(connectedDevice, receiver)
.addOnSuccessListener {
log("Receiver registered successfully")
}
.addOnFailureListener { e ->
logError("Failed to register receiver", e)
runOnMainThread {
onError(
getErrorMessage(e, "Failed to register receiver"),
getErrorCode(e)
)
}
}
}
)
} else {
runOnMainThread {
onError(
"Permissions not granted",
WearEngineErrorCode.ERROR_CODE_USER_UNAUTHORIZED_IN_HEALTH
)
}
}
}
}
/**
* Unregisters the receiver when no longer needed.
*/
fun unregisterReceiver() {
receiver?.let {
try {
p2pClient.unregisterReceiver(it)
log("Receiver unregistered")
} catch (e: Exception) {
logError("Error unregistering receiver", e)
}
receiver = null
}
}
/**
* Releases resources when the helper is no longer needed.
* Call this method in your Activity/Fragment onDestroy().
*/
fun release() {
unregisterReceiver()
connectedDevice = null
log("WearEngineHelper resources released")
}
/**
* Coroutine-friendly version of hasConnectedWatch.
* @return true if a compatible Huawei watch is connected
*/
suspend fun hasConnectedWatchAsync(): Boolean = suspendCancellableCoroutine { continuation ->
hasConnectedWatch { result ->
continuation.resume(result)
}
}
/**
* Coroutine-friendly version of checkAndRequestPermissions.
* @return true if permissions are granted
*/
suspend fun checkAndRequestPermissionsAsync(): Boolean =
suspendCancellableCoroutine { continuation ->
checkAndRequestPermissions { result ->
continuation.resume(result)
}
}
/**************************** PRIVATE METHODS ************************/
/**
* Helper method to invoke callbacks on the main thread.
* If callback is already invoked on the main thread, then its executed immediately.
*/
private fun runOnMainThread(action: () -> Unit) {
if (Looper.myLooper() == Looper.getMainLooper()) {
action()
} else {
mainHandler.post(action)
}
}
/**
* Checks and requests required permissions.
*/
private fun checkAndRequestPermissions(
onPermissionResult: (Boolean) -> Unit
) {
// Check existing permissions
checkPermissions { permissionsGranted ->
if (!permissionsGranted) {
// Request permissions if not granted
requestPermissions { permissionGranted ->
onPermissionResult(permissionGranted)
}
} else {
// Permissions already granted
onPermissionResult(true)
}
}
}
/**
* Internal implementation for sending messages to the watch.
*/
private fun sendMessageToWatchImpl(
messageBytes: ByteArray,
onDeviceConnected: (String) -> Unit,
onSuccess: () -> Unit,
onError: (String, Int) -> Unit
) {
getConnectedDevice(onDeviceConnected, onError) {
// Check if watch app is installed and running
checkWatchAppStatus(
onAppRunning = {
// Send message to watch
dispatchMessageToWatch(
messageBytes,
onSuccess,
onError
)
},
onError = onError
)
}
}
/**
* Gets the currently connected Huawei watch device.
*/
private fun getConnectedDevice(
onDeviceConnected: (String) -> Unit,
onError: (String, Int) -> Unit,
onSuccess: () -> Unit
) {
deviceClient.bondedDevices
.addOnSuccessListener { devices ->
// Get the first connected device
val device = devices.firstOrNull { it.isConnected }
if (device == null) {
runOnMainThread {
onError(
"No connected watch found",
WearEngineErrorCode.ERROR_CODE_DEVICE_IS_NOT_CONNECTED
)
}
return@addOnSuccessListener
}
log("Connected device: ${device.name} (${device.model})")
connectedDevice = device
// Notify caller about connected device
runOnMainThread {
onDeviceConnected(device.name)
onSuccess()
}
}
.addOnFailureListener { e ->
logError("Failed to get bonded devices", e)
runOnMainThread {
onError(
getErrorMessage(e, "There are no bound devices"),
getErrorCode(e)
)
}
}
}
/**
* Checks if required permissions are granted.
*/
private fun checkPermissions(callback: (Boolean) -> Unit) {
try {
authClient.checkPermissions(config.permissions)
.addOnSuccessListener { result ->
val allPermissionsGranted = result.all { it == true }
log("Permission check result: $allPermissionsGranted")
callback(allPermissionsGranted)
}
.addOnFailureListener { e ->
logError("Error checking permissions", e)
callback(false)
}
} catch (e: Exception) {
logError("Exception while checking permissions", e)
callback(false)
}
}
/**
* Requests required permissions.
*/
private fun requestPermissions(callback: (Boolean) -> Unit) {
try {
authClient.requestPermission(object : AuthCallback {
override fun onOk(permissions: Array<out Permission>?) {
log("Permissions granted: ${permissions?.joinToString()}")
callback(permissions?.isNotEmpty() == true)
}
override fun onCancel() {
log("Permission request cancelled")
callback(false)
}
}, *config.permissions)
.addOnSuccessListener {
log("Permission request initiated successfully")
}
.addOnFailureListener { e ->
logError("Error initiating permission request", e)
callback(false)
}
} catch (e: Exception) {
logError("Exception while requesting permissions", e)
callback(false)
}
}
/**
* Checks if the watch app is installed and running.
*/
private fun checkWatchAppStatus(
onAppRunning: () -> Unit,
onError: (String, Int) -> Unit
) {
if (connectedDevice == null) {
runOnMainThread {
onError(
"No connected watch found",
WearEngineErrorCode.ERROR_CODE_DEVICE_IS_NOT_CONNECTED
)
}
return
}
try {
p2pClient.ping(connectedDevice) { resultCode ->
log("Ping result: $resultCode")
when (resultCode) {
WearEngineErrorCode.ERROR_CODE_P2P_WATCH_APP_RUNNING -> {
log("Watch app is running")
runOnMainThread { onAppRunning() }
}
WearEngineErrorCode.ERROR_CODE_P2P_WATCH_APP_NOT_RUNNING -> {
log("Watch app is installed but not running")
runOnMainThread {
onError(
"Watch app is installed but not running",
WearEngineErrorCode.ERROR_CODE_P2P_WATCH_APP_NOT_RUNNING
)
}
}
WearEngineErrorCode.ERROR_CODE_P2P_WATCH_APP_NOT_EXIT -> {
log("Watch app is not installed")
runOnMainThread {
onError(
"Watch app is not installed",
WearEngineErrorCode.ERROR_CODE_P2P_WATCH_APP_NOT_EXIT
)
}
}
else -> {
log("Ping failed with code: $resultCode")
runOnMainThread { onError("Watch app check failed", resultCode) }
}
}
}.addOnFailureListener { e ->
logError("Error pinging watch app", e)
runOnMainThread {
onError(
"Error checking watch app status",
if (e is WearEngineException) e.errorCode else WearEngineErrorCode.ERROR_CODE_GENERIC
)
}
}
} catch (e: Exception) {
logError("Exception while checking watch app status", e)
runOnMainThread {
onError(
getErrorMessage(e, "Error checking watch app status"),
getErrorCode(e)
)
}
}
}
/**
* Dispatches a message to the connected watch device.
*/
private fun dispatchMessageToWatch(
messageBytes: ByteArray,
onSuccess: () -> Unit,
onError: (String, Int) -> Unit
) {
if (connectedDevice == null) {
runOnMainThread {
onError(
"No connected watch found",
WearEngineErrorCode.ERROR_CODE_DEVICE_IS_NOT_CONNECTED
)
}
return
}
try {
// Create the message
val payload = Message.Builder()
.setPayload(messageBytes)
.build()
log("Sending message to watch (${messageBytes.size} bytes)")
p2pClient.send(connectedDevice, payload, object : SendCallback {
override fun onSendProgress(progress: Long) {
if (config.verboseLogging) {
log("Send progress: $progress")
}
}
override fun onSendResult(code: Int) {
log("Message sending result: $code")
if (code == WearEngineErrorCode.ERROR_CODE_COMM_SUCCESS) {
log("Message sent successfully")
runOnMainThread { onSuccess() }
} else {
log("Failed to send message, code: $code")
runOnMainThread { onError("Failed to send message", code) }
}
}
})
} catch (e: Exception) {
logError("Error sending message to device", e)
runOnMainThread { onError(getErrorMessage(e), getErrorCode(e)) }
}
}
/**
* Returns error message from an exception.
*/
private fun getErrorMessage(
e: Exception,
defaultMessage: String = SOMETHING_WENT_WRONG
) = (if (e is WearEngineException) e.message else null) ?: defaultMessage
private fun getErrorCode(
e: Exception,
defaultCode: Int = WearEngineErrorCode.ERROR_CODE_GENERIC
) = if (e is WearEngineException) e.errorCode else defaultCode
/**
* Logs a message if logging is enabled.
*/
private fun log(message: String) {
Log.d(config.logTag, message)
}
/**
* Logs an error message with exception.
*/
private fun logError(message: String, e: Exception? = null) {
if (e != null) {
Log.e(config.logTag, message, e)
} else {
Log.e(config.logTag, message)
}
}
companion object {
/** Default tag for logging */
private const val DEFAULT_LOG_TAG = "WearEngineHelper"
/** Maximum message size in bytes (1KB) */
private const val MAX_MESSAGE_SIZE = 1024
/** Maximum large message size in bytes (4KB) */
private const val MAX_LARGE_MESSAGE_SIZE = 1024 * 4
/** Maximum file size in bytes (100MB) */
private const val MAX_FILE_SIZE = 1024 * 100 * 100
/** temprary file name used to store large message content */
private const val TEMP_FILE_NAME = "wear_message.txt"
/** Default error message */
private const val SOMETHING_WENT_WRONG = "Something went wrong"
}
}