forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAndroidCallbacks.cpp
903 lines (800 loc) · 46.2 KB
/
AndroidCallbacks.cpp
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
/*
*
* Copyright (c) 2020-2023 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "AndroidCallbacks.h"
#include <controller/java/AndroidConnectionFailureExceptions.h>
#include <controller/java/AndroidControllerExceptions.h>
#ifdef USE_JAVA_TLV_ENCODE_DECODE
#include <controller/java/CHIPAttributeTLVValueDecoder.h>
#include <controller/java/CHIPEventTLVValueDecoder.h>
#endif
#include <app/EventLoggingTypes.h>
#include <jni.h>
#include <lib/core/ErrorStr.h>
#include <lib/support/CHIPJNIError.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/JniReferences.h>
#include <lib/support/jsontlv/JsonToTlv.h>
#include <lib/support/jsontlv/TlvToJson.h>
#include <lib/support/logging/CHIPLogging.h>
#include <platform/PlatformManager.h>
#include <type_traits>
namespace chip {
namespace Controller {
static const int MILLIS_SINCE_BOOT = 0;
static const int MILLIS_SINCE_EPOCH = 1;
// Add the bytes for attribute tag(1:control + 8:tag + 8:length) and structure(1:struct + 1:close container)
static const int EXTRA_SPACE_FOR_ATTRIBUTE_TAG = 19;
CHIP_ERROR CreateChipAttributePath(JNIEnv * env, const app::ConcreteDataAttributePath & aPath, jobject & outObj)
{
jclass attributePathCls = nullptr;
ReturnErrorOnFailure(
JniReferences::GetInstance().GetLocalClassRef(env, "chip/devicecontroller/model/ChipAttributePath", attributePathCls));
jmethodID attributePathCtor =
env->GetStaticMethodID(attributePathCls, "newInstance", "(IJJ)Lchip/devicecontroller/model/ChipAttributePath;");
VerifyOrReturnError(attributePathCtor != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
outObj = env->CallStaticObjectMethod(attributePathCls, attributePathCtor, static_cast<jint>(aPath.mEndpointId),
static_cast<jlong>(aPath.mClusterId), static_cast<jlong>(aPath.mAttributeId));
VerifyOrReturnError(outObj != nullptr, CHIP_JNI_ERROR_NULL_OBJECT);
return CHIP_NO_ERROR;
}
GetConnectedDeviceCallback::GetConnectedDeviceCallback(jobject wrapperCallback, jobject javaCallback) :
mOnSuccess(OnDeviceConnectedFn, this), mOnFailure(OnDeviceConnectionFailureFn, this)
{
VerifyOrReturn(mWrapperCallbackRef.Init(wrapperCallback) == CHIP_NO_ERROR,
ChipLogError(Controller, "Could not init mWrapperCallbackRef in %s", __func__));
VerifyOrReturn(mJavaCallbackRef.Init(javaCallback) == CHIP_NO_ERROR,
ChipLogError(Controller, "Could not init mJavaCallbackRef in %s", __func__));
}
GetConnectedDeviceCallback::~GetConnectedDeviceCallback() {}
void GetConnectedDeviceCallback::OnDeviceConnectedFn(void * context, Messaging::ExchangeManager & exchangeMgr,
const SessionHandle & sessionHandle)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread"));
auto * self = static_cast<GetConnectedDeviceCallback *>(context);
VerifyOrReturn(self->mJavaCallbackRef.HasValidObjectRef(),
ChipLogError(Controller, "mJavaCallbackRef is not valid in %s", __func__));
jobject javaCallback = self->mJavaCallbackRef.ObjectRef();
JniLocalReferenceScope scope(env);
// Release wrapper's global ref so application can clean up the actual callback underneath.
VerifyOrReturn(self->mWrapperCallbackRef.HasValidObjectRef(),
ChipLogError(Controller, "mWrapperCallbackRef is not valid in %s", __func__));
JniGlobalReference globalRef(std::move(self->mWrapperCallbackRef));
jclass getConnectedDeviceCallbackCls = nullptr;
JniReferences::GetInstance().GetLocalClassRef(
env, "chip/devicecontroller/GetConnectedDeviceCallbackJni$GetConnectedDeviceCallback", getConnectedDeviceCallbackCls);
VerifyOrReturn(getConnectedDeviceCallbackCls != nullptr,
ChipLogError(Controller, "Could not find GetConnectedDeviceCallback class"));
jmethodID successMethod;
JniReferences::GetInstance().FindMethod(env, javaCallback, "onDeviceConnected", "(J)V", &successMethod);
VerifyOrReturn(successMethod != nullptr, ChipLogError(Controller, "Could not find onDeviceConnected method"));
static_assert(sizeof(jlong) >= sizeof(void *), "Need to store a pointer in a Java handle");
OperationalDeviceProxy * device = new OperationalDeviceProxy(&exchangeMgr, sessionHandle);
DeviceLayer::StackUnlock unlock;
env->CallVoidMethod(javaCallback, successMethod, reinterpret_cast<jlong>(device));
VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe());
}
void GetConnectedDeviceCallback::OnDeviceConnectionFailureFn(void * context,
const OperationalSessionSetup::ConnnectionFailureInfo & failureInfo)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread"));
auto * self = static_cast<GetConnectedDeviceCallback *>(context);
VerifyOrReturn(self->mJavaCallbackRef.HasValidObjectRef(),
ChipLogError(Controller, "mJavaCallbackRef is not valid in %s", __func__));
jobject javaCallback = self->mJavaCallbackRef.ObjectRef();
JniLocalReferenceScope scope(env);
jclass getConnectedDeviceCallbackCls = nullptr;
JniReferences::GetInstance().GetLocalClassRef(
env, "chip/devicecontroller/GetConnectedDeviceCallbackJni$GetConnectedDeviceCallback", getConnectedDeviceCallbackCls);
VerifyOrReturn(getConnectedDeviceCallbackCls != nullptr,
ChipLogError(Controller, "Could not find GetConnectedDeviceCallback class"));
jmethodID failureMethod;
JniReferences::GetInstance().FindMethod(env, javaCallback, "onConnectionFailure", "(JLjava/lang/Exception;)V", &failureMethod);
VerifyOrReturn(failureMethod != nullptr, ChipLogError(Controller, "Could not find onConnectionFailure method"));
jthrowable exception;
CHIP_ERROR err = AndroidConnectionFailureExceptions::GetInstance().CreateAndroidConnectionFailureException(
env, failureInfo.error.Format(), failureInfo.error.AsInteger(), failureInfo.sessionStage, exception);
VerifyOrReturn(
err == CHIP_NO_ERROR,
ChipLogError(Controller,
"Unable to create AndroidControllerException on GetConnectedDeviceCallback::OnDeviceConnectionFailureFn: %s",
ErrorStr(err)));
DeviceLayer::StackUnlock unlock;
env->CallVoidMethod(javaCallback, failureMethod, failureInfo.peerId.GetNodeId(), exception);
VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe());
}
ReportCallback::ReportCallback(jobject wrapperCallback, jobject subscriptionEstablishedCallback, jobject reportCallback,
jobject resubscriptionAttemptCallback) :
mClusterCacheAdapter(*this, Optional<EventNumber>::Missing(), false /*cacheData*/)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread"));
if (subscriptionEstablishedCallback != nullptr)
{
VerifyOrReturn(mSubscriptionEstablishedCallbackRef.Init(subscriptionEstablishedCallback) == CHIP_NO_ERROR,
ChipLogError(Controller, "Could not init mSubscriptionEstablishedCallbackRef in %s", __func__));
}
VerifyOrReturn(mReportCallbackRef.Init(reportCallback) == CHIP_NO_ERROR,
ChipLogError(Controller, "Could not init mReportCallbackRef in %s", __func__));
VerifyOrReturn(mWrapperCallbackRef.Init(wrapperCallback) == CHIP_NO_ERROR,
ChipLogError(Controller, "Could not init mWrapperCallbackRef in %s", __func__));
if (resubscriptionAttemptCallback != nullptr)
{
VerifyOrReturn(mResubscriptionAttemptCallbackRef.Init(resubscriptionAttemptCallback) == CHIP_NO_ERROR,
ChipLogError(Controller, "Could not init mResubscriptionAttemptCallbackRef in %s", __func__));
}
}
ReportCallback::~ReportCallback()
{
if (mReadClient != nullptr)
{
Platform::Delete(mReadClient);
}
}
void ReportCallback::OnReportBegin()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread"));
JniLocalReferenceScope scope(env);
jclass nodeStateCls = nullptr;
CHIP_ERROR err = JniReferences::GetInstance().GetLocalClassRef(env, "chip/devicecontroller/model/NodeState", nodeStateCls);
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Could not get NodeState class"));
jmethodID nodeStateCtor = env->GetMethodID(nodeStateCls, "<init>", "()V");
VerifyOrReturn(nodeStateCtor != nullptr, ChipLogError(Controller, "Could not find NodeState constructor"));
jobject nodeState = env->NewObject(nodeStateCls, nodeStateCtor);
VerifyOrReturn(nodeState != nullptr, ChipLogError(Controller, "Could not create local object for nodeState"));
VerifyOrReturn(mNodeStateObj.Init(nodeState) == CHIP_NO_ERROR,
ChipLogError(Controller, "Could not init mNodeStateObj in %s", __func__));
}
void ReportCallback::OnDeallocatePaths(app::ReadPrepareParams && aReadPrepareParams)
{
if (aReadPrepareParams.mpAttributePathParamsList != nullptr && aReadPrepareParams.mAttributePathParamsListSize != 0)
{
delete[] aReadPrepareParams.mpAttributePathParamsList;
aReadPrepareParams.mpAttributePathParamsList = nullptr;
aReadPrepareParams.mAttributePathParamsListSize = 0;
}
if (aReadPrepareParams.mpEventPathParamsList != nullptr && aReadPrepareParams.mEventPathParamsListSize != 0)
{
delete[] aReadPrepareParams.mpEventPathParamsList;
aReadPrepareParams.mpEventPathParamsList = nullptr;
aReadPrepareParams.mEventPathParamsListSize = 0;
}
if (aReadPrepareParams.mpDataVersionFilterList != nullptr && aReadPrepareParams.mDataVersionFilterListSize != 0)
{
delete[] aReadPrepareParams.mpDataVersionFilterList;
aReadPrepareParams.mpDataVersionFilterList = nullptr;
aReadPrepareParams.mDataVersionFilterListSize = 0;
}
}
void ReportCallback::OnReportEnd()
{
UpdateClusterDataVersion();
// Transform C++ jobject pair list to a Java HashMap, and call onReport() on the Java callback.
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread"));
JniLocalReferenceScope scope(env);
VerifyOrReturn(mReportCallbackRef.HasValidObjectRef(),
ChipLogError(Controller, "mReportCallbackRef is not valid in %s", __func__));
jobject reportCallback = mReportCallbackRef.ObjectRef();
JniGlobalReference globalRef(std::move(mNodeStateObj));
jmethodID onReportMethod;
err = JniReferences::GetInstance().FindMethod(env, reportCallback, "onReport", "(Lchip/devicecontroller/model/NodeState;)V",
&onReportMethod);
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Could not find onReport method"));
DeviceLayer::StackUnlock unlock;
env->CallVoidMethod(reportCallback, onReportMethod, globalRef.ObjectRef());
VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe());
}
// Convert TLV blob to Json with structure, the element's tag is replaced with the actual attributeId.
CHIP_ERROR ConvertReportTlvToJson(const uint32_t id, TLV::TLVReader & data, std::string & json)
{
TLV::TLVWriter writer;
TLV::TLVReader readerForJavaTLV;
uint32_t size = 0;
readerForJavaTLV.Init(data);
size_t bufferLen = readerForJavaTLV.GetTotalLength() + EXTRA_SPACE_FOR_ATTRIBUTE_TAG;
std::unique_ptr<uint8_t[]> buffer = std::unique_ptr<uint8_t[]>(new uint8_t[bufferLen]);
writer.Init(buffer.get(), bufferLen);
TLV::TLVType outer;
ReturnErrorOnFailure(writer.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outer));
TLV::Tag tag;
ReturnErrorOnFailure(ConvertTlvTag(id, tag));
ReturnErrorOnFailure(writer.CopyElement(tag, readerForJavaTLV));
ReturnErrorOnFailure(writer.EndContainer(outer));
size = writer.GetLengthWritten();
TLV::TLVReader readerForJson;
readerForJson.Init(buffer.get(), size);
ReturnErrorOnFailure(readerForJson.Next());
// Convert TLV to JSON
return TlvToJson(readerForJson, json);
}
static CHIP_ERROR CreateStatus(JNIEnv * env, const app::StatusIB & aStatus, jobject & outObj)
{
jclass statusCls = nullptr;
ReturnErrorOnFailure(JniReferences::GetInstance().GetLocalClassRef(env, "chip/devicecontroller/model/Status", statusCls));
jmethodID statusCtor = nullptr;
if (aStatus.mClusterStatus.HasValue())
{
statusCtor = env->GetStaticMethodID(statusCls, "newInstance", "(II)Lchip/devicecontroller/model/Status;");
VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN);
VerifyOrReturnError(statusCtor != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
outObj = env->CallStaticObjectMethod(statusCls, statusCtor, static_cast<jint>(aStatus.mStatus),
static_cast<jint>(aStatus.mClusterStatus.Value()));
}
else
{
statusCtor = env->GetStaticMethodID(statusCls, "newInstance", "(I)Lchip/devicecontroller/model/Status;");
VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN);
VerifyOrReturnError(statusCtor != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
outObj = env->CallStaticObjectMethod(statusCls, statusCtor, static_cast<jint>(aStatus.mStatus));
}
VerifyOrReturnError(outObj != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
return CHIP_NO_ERROR;
}
void ReportCallback::OnAttributeData(const app::ConcreteDataAttributePath & aPath, TLV::TLVReader * apData,
const app::StatusIB & aStatus)
{
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread"));
JniLocalReferenceScope scope(env);
VerifyOrReturn(!aPath.IsListItemOperation(), ChipLogError(Controller, "Expect non-list item operation"); aPath.LogPath());
jobject nodeState = mNodeStateObj.ObjectRef();
if (aStatus.IsFailure())
{
ChipLogError(Controller, "Receive bad status %s", ErrorStr(aStatus.ToChipError()));
jobject statusObj = nullptr;
err = CreateStatus(env, aStatus, statusObj);
VerifyOrReturn(err == CHIP_NO_ERROR,
ChipLogError(Controller, "Fail to create status with error %" CHIP_ERROR_FORMAT, err.Format()));
// Add Attribute Status to NodeState
jmethodID addAttributeStatusMethod = nullptr;
err = JniReferences::GetInstance().FindMethod(env, nodeState, "addAttributeStatus",
"(IJJLchip/devicecontroller/model/Status;)V", &addAttributeStatusMethod);
VerifyOrReturn(
err == CHIP_NO_ERROR,
ChipLogError(Controller, "Could not find addAttributeStatus method with error %" CHIP_ERROR_FORMAT, err.Format()));
env->CallVoidMethod(nodeState, addAttributeStatusMethod, static_cast<jint>(aPath.mEndpointId),
static_cast<jlong>(aPath.mClusterId), static_cast<jlong>(aPath.mAttributeId), statusObj);
VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe());
return;
}
VerifyOrReturn(apData != nullptr, ChipLogError(Controller, "Receive empty apData"); aPath.LogPath());
TLV::TLVReader readerForJavaTLV;
readerForJavaTLV.Init(*apData);
jobject value = nullptr;
#ifdef USE_JAVA_TLV_ENCODE_DECODE
TLV::TLVReader readerForJavaObject;
readerForJavaObject.Init(*apData);
value = DecodeAttributeValue(aPath, readerForJavaObject, &err);
// If we don't know this attribute, suppress it.
if (err == CHIP_ERROR_IM_MALFORMED_ATTRIBUTE_PATH_IB)
{
err = CHIP_NO_ERROR;
}
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Fail to decode attribute with error %s", ErrorStr(err));
aPath.LogPath());
VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe());
#endif
// Create TLV byte array to pass to Java layer
size_t bufferLen = readerForJavaTLV.GetRemainingLength() + readerForJavaTLV.GetLengthRead();
std::unique_ptr<uint8_t[]> buffer = std::unique_ptr<uint8_t[]>(new uint8_t[bufferLen]);
uint32_t size = 0;
// The TLVReader's read head is not pointing to the first element in the container, instead of the container itself, use
// a TLVWriter to get a TLV with a normalized TLV buffer (Wrapped with an anonymous tag, no extra "end of container" tag
// at the end.)
TLV::TLVWriter writer;
writer.Init(buffer.get(), bufferLen);
err = writer.CopyElement(TLV::AnonymousTag(), readerForJavaTLV);
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Fail to copy tlv element with error %s", ErrorStr(err));
aPath.LogPath());
size = writer.GetLengthWritten();
chip::ByteArray jniByteArray(env, reinterpret_cast<jbyte *>(buffer.get()), static_cast<jint>(size));
// Convert TLV to JSON
std::string json;
err = ConvertReportTlvToJson(static_cast<uint32_t>(aPath.mAttributeId), *apData, json);
VerifyOrReturn(err == CHIP_NO_ERROR,
ChipLogError(Controller, "Fail to convert report tlv to json with error %s", ErrorStr(err));
aPath.LogPath());
UtfString jsonString(env, json.c_str());
// Create AttributeState object
jclass attributeStateCls;
err = JniReferences::GetInstance().GetLocalClassRef(env, "chip/devicecontroller/model/AttributeState", attributeStateCls);
VerifyOrReturn(err == CHIP_NO_ERROR,
ChipLogError(Controller, "Could not find AttributeState class with error %s", ErrorStr(err));
aPath.LogPath());
VerifyOrReturn(attributeStateCls != nullptr, ChipLogError(Controller, "Could not find AttributeState class"); aPath.LogPath());
jmethodID attributeStateCtor = env->GetMethodID(attributeStateCls, "<init>", "(Ljava/lang/Object;[BLjava/lang/String;)V");
VerifyOrReturn(attributeStateCtor != nullptr, ChipLogError(Controller, "Could not find AttributeState constructor");
aPath.LogPath());
jobject attributeStateObj =
env->NewObject(attributeStateCls, attributeStateCtor, value, jniByteArray.jniValue(), jsonString.jniValue());
VerifyOrReturn(attributeStateObj != nullptr, ChipLogError(Controller, "Could not create AttributeState object");
aPath.LogPath());
// Add AttributeState to NodeState
jmethodID addAttributeMethod;
err = JniReferences::GetInstance().FindMethod(env, nodeState, "addAttribute",
"(IJJLchip/devicecontroller/model/AttributeState;)V", &addAttributeMethod);
VerifyOrReturn(err == CHIP_NO_ERROR,
ChipLogError(Controller, "Could not find addAttribute method with error %s", ErrorStr(err)));
env->CallVoidMethod(nodeState, addAttributeMethod, static_cast<jint>(aPath.mEndpointId), static_cast<jlong>(aPath.mClusterId),
static_cast<jlong>(aPath.mAttributeId), attributeStateObj);
VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe());
UpdateClusterDataVersion();
}
void ReportCallback::UpdateClusterDataVersion()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread"));
chip::app::ConcreteClusterPath lastConcreteClusterPath;
if (mClusterCacheAdapter.GetLastReportDataPath(lastConcreteClusterPath) != CHIP_NO_ERROR)
{
return;
}
if (!lastConcreteClusterPath.IsValidConcreteClusterPath())
{
return;
}
chip::Optional<chip::DataVersion> committedDataVersion;
if (mClusterCacheAdapter.GetVersion(lastConcreteClusterPath, committedDataVersion) != CHIP_NO_ERROR)
{
return;
}
if (!committedDataVersion.HasValue())
{
return;
}
jobject nodeState = mNodeStateObj.ObjectRef();
// SetDataVersion to NodeState
jmethodID setDataVersionMethod;
CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, nodeState, "setDataVersion", "(IJJ)V", &setDataVersionMethod);
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Could not find setDataVersion method"));
env->CallVoidMethod(nodeState, setDataVersionMethod, static_cast<jint>(lastConcreteClusterPath.mEndpointId),
static_cast<jlong>(lastConcreteClusterPath.mClusterId), static_cast<jlong>(committedDataVersion.Value()));
VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe());
}
void ReportCallback::OnEventData(const app::EventHeader & aEventHeader, TLV::TLVReader * apData, const app::StatusIB * apStatus)
{
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread"));
jobject nodeState = mNodeStateObj.ObjectRef();
if (apStatus != nullptr && apStatus->IsFailure())
{
ChipLogError(Controller, "Receive bad status %s", ErrorStr(apStatus->ToChipError()));
jobject statusObj = nullptr;
err = CreateStatus(env, *apStatus, statusObj);
VerifyOrReturn(err == CHIP_NO_ERROR,
ChipLogError(Controller, "Fail to create status with error %" CHIP_ERROR_FORMAT, err.Format()));
// Add Event Status to NodeState
jmethodID addEventStatusMethod;
err = JniReferences::GetInstance().FindMethod(env, nodeState, "addEventStatus",
"(IJJLchip/devicecontroller/model/Status;)V", &addEventStatusMethod);
VerifyOrReturn(
err == CHIP_NO_ERROR,
ChipLogError(Controller, "Could not find addEventStatus method with error %" CHIP_ERROR_FORMAT, err.Format()));
env->CallVoidMethod(nodeState, addEventStatusMethod, static_cast<jint>(aEventHeader.mPath.mEndpointId),
static_cast<jlong>(aEventHeader.mPath.mClusterId), static_cast<jlong>(aEventHeader.mPath.mEventId),
statusObj);
VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe());
return;
}
VerifyOrReturn(apData != nullptr, ChipLogError(Controller, "Receive empty apData"); aEventHeader.LogPath());
TLV::TLVReader readerForJavaTLV;
readerForJavaTLV.Init(*apData);
jlong eventNumber = static_cast<jlong>(aEventHeader.mEventNumber);
jint priorityLevel = static_cast<jint>(aEventHeader.mPriorityLevel);
jlong timestampValue = static_cast<jlong>(aEventHeader.mTimestamp.mValue);
jint timestampType = 0;
if (aEventHeader.mTimestamp.mType == app::Timestamp::Type::kSystem)
{
timestampType = static_cast<jint>(MILLIS_SINCE_BOOT);
}
else if (aEventHeader.mTimestamp.mType == app::Timestamp::Type::kEpoch)
{
timestampType = static_cast<jint>(MILLIS_SINCE_EPOCH);
}
else
{
ChipLogError(Controller, "Unsupported event timestamp type");
aEventHeader.LogPath();
return;
}
jobject value = nullptr;
#ifdef USE_JAVA_TLV_ENCODE_DECODE
TLV::TLVReader readerForJavaObject;
readerForJavaObject.Init(*apData);
value = DecodeEventValue(aEventHeader.mPath, readerForJavaObject, &err);
// If we don't know this event, just skip it.
if (err == CHIP_ERROR_IM_MALFORMED_EVENT_PATH_IB)
{
err = CHIP_NO_ERROR;
}
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Fail to decode event with error %s", ErrorStr(err));
aEventHeader.LogPath());
VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe());
#endif
// Create TLV byte array to pass to Java layer
size_t bufferLen = readerForJavaTLV.GetRemainingLength() + readerForJavaTLV.GetLengthRead();
std::unique_ptr<uint8_t[]> buffer = std::unique_ptr<uint8_t[]>(new uint8_t[bufferLen]);
uint32_t size = 0;
// The TLVReader's read head is not pointing to the first element in the container, instead of the container itself, use
// a TLVWriter to get a TLV with a normalized TLV buffer (Wrapped with an anonymous tag, no extra "end of container" tag
// at the end.)
TLV::TLVWriter writer;
writer.Init(buffer.get(), bufferLen);
err = writer.CopyElement(TLV::AnonymousTag(), readerForJavaTLV);
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Fail to copy element with error %s", ErrorStr(err));
aEventHeader.LogPath());
size = writer.GetLengthWritten();
chip::ByteArray jniByteArray(env, reinterpret_cast<jbyte *>(buffer.get()), static_cast<jint>(size));
// Convert TLV to JSON
std::string json;
err = ConvertReportTlvToJson(static_cast<uint32_t>(aEventHeader.mPath.mEventId), *apData, json);
VerifyOrReturn(err == CHIP_NO_ERROR,
ChipLogError(Controller, "Fail to convert report tlv to Json with error %s", ErrorStr(err));
aEventHeader.LogPath());
UtfString jsonString(env, json.c_str());
// Create EventState object
jclass eventStateCls;
err = JniReferences::GetInstance().GetLocalClassRef(env, "chip/devicecontroller/model/EventState", eventStateCls);
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Failed to find EventState class"); aEventHeader.LogPath());
VerifyOrReturn(eventStateCls != nullptr, ChipLogError(Controller, "Could not find EventState class"); aEventHeader.LogPath());
jmethodID eventStateCtor = env->GetMethodID(eventStateCls, "<init>", "(JIIJLjava/lang/Object;[BLjava/lang/String;)V");
VerifyOrReturn(eventStateCtor != nullptr, ChipLogError(Controller, "Could not find EventState constructor");
aEventHeader.LogPath());
jobject eventStateObj = env->NewObject(eventStateCls, eventStateCtor, eventNumber, priorityLevel, timestampType, timestampValue,
value, jniByteArray.jniValue(), jsonString.jniValue());
VerifyOrReturn(eventStateObj != nullptr, ChipLogError(Controller, "Could not create EventState object");
aEventHeader.LogPath());
// Add EventState to NodeState
jmethodID addEventMethod;
err = JniReferences::GetInstance().FindMethod(env, nodeState, "addEvent", "(IJJLchip/devicecontroller/model/EventState;)V",
&addEventMethod);
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Could not find addEvent method with error %s", ErrorStr(err));
aEventHeader.LogPath());
env->CallVoidMethod(nodeState, addEventMethod, static_cast<jint>(aEventHeader.mPath.mEndpointId),
static_cast<jlong>(aEventHeader.mPath.mClusterId), static_cast<jlong>(aEventHeader.mPath.mEventId),
eventStateObj);
VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe(); aEventHeader.LogPath());
}
CHIP_ERROR InvokeCallback::CreateInvokeElement(JNIEnv * env, const app::ConcreteCommandPath & aPath, TLV::TLVReader * apData,
jobject & outObj)
{
CHIP_ERROR err = CHIP_NO_ERROR;
jclass invokeElementCls = nullptr;
err = JniReferences::GetInstance().GetLocalClassRef(env, "chip/devicecontroller/model/InvokeElement", invokeElementCls);
ReturnErrorOnFailure(err);
jmethodID invokeElementCtor = env->GetStaticMethodID(invokeElementCls, "newInstance",
"(IJJ[BLjava/lang/String;)Lchip/devicecontroller/model/InvokeElement;");
VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN);
VerifyOrReturnError(invokeElementCtor != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
if (apData != nullptr)
{
TLV::TLVReader readerForJavaTLV;
TLV::TLVReader readerForJson;
readerForJavaTLV.Init(*apData);
// Create TLV byte array to pass to Java layer
size_t bufferLen = readerForJavaTLV.GetRemainingLength() + readerForJavaTLV.GetLengthRead();
std::unique_ptr<uint8_t[]> buffer = std::unique_ptr<uint8_t[]>(new uint8_t[bufferLen]);
uint32_t size = 0;
TLV::TLVWriter writer;
writer.Init(buffer.get(), bufferLen);
err = writer.CopyElement(TLV::AnonymousTag(), readerForJavaTLV);
ReturnErrorOnFailure(err);
size = writer.GetLengthWritten();
chip::ByteArray jniByteArray(env, reinterpret_cast<jbyte *>(buffer.get()), static_cast<jint>(size));
// Convert TLV to JSON
std::string json;
readerForJson.Init(buffer.get(), size);
err = readerForJson.Next();
ReturnErrorOnFailure(err);
err = TlvToJson(readerForJson, json);
ReturnErrorOnFailure(err);
UtfString jsonString(env, json.c_str());
outObj = env->CallStaticObjectMethod(invokeElementCls, invokeElementCtor, static_cast<jint>(aPath.mEndpointId),
static_cast<jlong>(aPath.mClusterId), static_cast<jlong>(aPath.mCommandId),
jniByteArray.jniValue(), jsonString.jniValue());
}
else
{
outObj = env->CallStaticObjectMethod(invokeElementCls, invokeElementCtor, static_cast<jint>(aPath.mEndpointId),
static_cast<jlong>(aPath.mClusterId), static_cast<jlong>(aPath.mCommandId), nullptr,
nullptr);
}
VerifyOrReturnError(outObj != nullptr, CHIP_JNI_ERROR_NULL_OBJECT);
return CHIP_NO_ERROR;
}
void ReportCallback::OnError(CHIP_ERROR aError)
{
ReportError(nullptr, nullptr, aError);
}
void ReportCallback::OnDone(app::ReadClient *)
{
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread"));
JniLocalReferenceScope scope(env);
VerifyOrReturn(mWrapperCallbackRef.HasValidObjectRef(),
ChipLogError(Controller, "mWrapperCallbackRef is not valid in %s", __func__));
JniGlobalReference globalRef(std::move(mWrapperCallbackRef));
jmethodID onDoneMethod;
VerifyOrReturn(mReportCallbackRef.HasValidObjectRef(),
ChipLogError(Controller, "mReportCallbackRef is not valid in %s", __func__));
jobject reportCallback = mReportCallbackRef.ObjectRef();
err = JniReferences::GetInstance().FindMethod(env, reportCallback, "onDone", "()V", &onDoneMethod);
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Could not find onDone method"));
if (mReadClient != nullptr)
{
Platform::Delete(mReadClient);
}
mReadClient = nullptr;
DeviceLayer::StackUnlock unlock;
env->CallVoidMethod(reportCallback, onDoneMethod);
VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe());
}
void ReportCallback::OnSubscriptionEstablished(SubscriptionId aSubscriptionId)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread"));
JniLocalReferenceScope scope(env);
DeviceLayer::StackUnlock unlock;
VerifyOrReturn(mSubscriptionEstablishedCallbackRef.HasValidObjectRef(),
ChipLogError(Controller, " mSubscriptionEstablishedCallbackRef is not valid in %s", __func__));
JniReferences::GetInstance().CallSubscriptionEstablished(mSubscriptionEstablishedCallbackRef.ObjectRef(), aSubscriptionId);
}
CHIP_ERROR ReportCallback::OnResubscriptionNeeded(app::ReadClient * apReadClient, CHIP_ERROR aTerminationCause)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
VerifyOrReturnError(env != nullptr, CHIP_JNI_ERROR_NULL_OBJECT);
ReturnErrorOnFailure(app::ReadClient::Callback::OnResubscriptionNeeded(apReadClient, aTerminationCause));
JniLocalReferenceScope scope(env);
jmethodID onResubscriptionAttemptMethod;
VerifyOrReturnLogError(mResubscriptionAttemptCallbackRef.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE);
jobject resubscriptionAttemptCallbackRef = mResubscriptionAttemptCallbackRef.ObjectRef();
ReturnLogErrorOnFailure(JniReferences::GetInstance().FindMethod(
env, resubscriptionAttemptCallbackRef, "onResubscriptionAttempt", "(JJ)V", &onResubscriptionAttemptMethod));
DeviceLayer::StackUnlock unlock;
env->CallVoidMethod(resubscriptionAttemptCallbackRef, onResubscriptionAttemptMethod,
static_cast<jlong>(aTerminationCause.AsInteger()),
static_cast<jlong>(apReadClient->ComputeTimeTillNextSubscription()));
VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN);
return CHIP_NO_ERROR;
}
void ReportCallback::ReportError(jobject attributePath, jobject eventPath, CHIP_ERROR err)
{
ReportError(attributePath, eventPath, ErrorStr(err), err.AsInteger());
}
void ReportCallback::ReportError(jobject attributePath, jobject eventPath, Protocols::InteractionModel::Status status)
{
ReportError(attributePath, eventPath, "IM Status",
static_cast<std::underlying_type_t<Protocols::InteractionModel::Status>>(status));
}
void ReportCallback::ReportError(jobject attributePath, jobject eventPath, const char * message, ChipError::StorageType errorCode)
{
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread"));
JniLocalReferenceScope scope(env);
VerifyOrReturn(mReportCallbackRef.HasValidObjectRef(),
ChipLogError(Controller, "mReportCallbackRef is not valid in %s", __func__));
jobject reportCallback = mReportCallbackRef.ObjectRef();
jthrowable exception;
err = AndroidControllerExceptions::GetInstance().CreateAndroidControllerException(env, message, errorCode, exception);
VerifyOrReturn(
err == CHIP_NO_ERROR,
ChipLogError(Controller, "Unable to create AndroidControllerException on ReportCallback::ReportError: %s", ErrorStr(err)));
jmethodID onErrorMethod;
err = JniReferences::GetInstance().FindMethod(
env, reportCallback, "onError",
"(Lchip/devicecontroller/model/ChipAttributePath;Lchip/devicecontroller/model/ChipEventPath;Ljava/lang/Exception;)V",
&onErrorMethod);
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Unable to find onError method: %s", ErrorStr(err)));
DeviceLayer::StackUnlock unlock;
env->CallVoidMethod(reportCallback, onErrorMethod, attributePath, eventPath, exception);
VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe());
}
WriteAttributesCallback::WriteAttributesCallback(jobject wrapperCallback, jobject javaCallback) : mChunkedWriteCallback(this)
{
VerifyOrReturn(mWrapperCallbackRef.Init(wrapperCallback) == CHIP_NO_ERROR,
ChipLogError(Controller, "Could not init mWrapperCallbackRef for WriteAttributesCallback"));
VerifyOrReturn(mJavaCallbackRef.Init(javaCallback) == CHIP_NO_ERROR,
ChipLogError(Controller, "Could not init mJavaCallbackRef in %s", __func__));
}
WriteAttributesCallback::~WriteAttributesCallback()
{
if (mWriteClient != nullptr)
{
Platform::Delete(mWriteClient);
}
}
void WriteAttributesCallback::OnResponse(const app::WriteClient * apWriteClient, const app::ConcreteDataAttributePath & aPath,
app::StatusIB aStatus)
{
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread"));
JniLocalReferenceScope scope(env);
jobject attributePathObj = nullptr;
err = CreateChipAttributePath(env, aPath, attributePathObj);
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Unable to create Java ChipAttributePath: %s", ErrorStr(err)));
if (aStatus.mStatus != Protocols::InteractionModel::Status::Success)
{
ReportError(attributePathObj, aStatus.mStatus);
return;
}
jmethodID onResponseMethod;
VerifyOrReturn(mJavaCallbackRef.HasValidObjectRef(), ChipLogError(Controller, "mJavaCallbackRef is not valid in %s", __func__));
jobject javaCallback = mJavaCallbackRef.ObjectRef();
err = JniReferences::GetInstance().FindMethod(env, javaCallback, "onResponse",
"(Lchip/devicecontroller/model/ChipAttributePath;)V", &onResponseMethod);
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Unable to find onError method: %s", ErrorStr(err)));
DeviceLayer::StackUnlock unlock;
env->CallVoidMethod(javaCallback, onResponseMethod, attributePathObj);
VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe());
}
void WriteAttributesCallback::OnError(const app::WriteClient * apWriteClient, CHIP_ERROR aError)
{
ReportError(nullptr, aError);
}
void WriteAttributesCallback::OnDone(app::WriteClient *)
{
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread"));
JniLocalReferenceScope scope(env);
VerifyOrReturn(mWrapperCallbackRef.HasValidObjectRef(),
ChipLogError(Controller, "mWrapperCallbackRef is not valid in %s", __func__));
JniGlobalReference globalRef(std::move(mWrapperCallbackRef));
jmethodID onDoneMethod;
VerifyOrReturn(mJavaCallbackRef.HasValidObjectRef(), ChipLogError(Controller, "mJavaCallbackRef is not valid in %s", __func__));
jobject javaCallback = mJavaCallbackRef.ObjectRef();
err = JniReferences::GetInstance().FindMethod(env, javaCallback, "onDone", "()V", &onDoneMethod);
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Could not find onDone method"));
DeviceLayer::StackUnlock unlock;
env->CallVoidMethod(javaCallback, onDoneMethod);
VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe());
}
void WriteAttributesCallback::ReportError(jobject attributePath, CHIP_ERROR err)
{
ReportError(attributePath, ErrorStr(err), err.AsInteger());
}
void WriteAttributesCallback::ReportError(jobject attributePath, Protocols::InteractionModel::Status status)
{
ReportError(attributePath, "IM Status", static_cast<std::underlying_type_t<Protocols::InteractionModel::Status>>(status));
}
void WriteAttributesCallback::ReportError(jobject attributePath, const char * message, ChipError::StorageType errorCode)
{
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread"));
JniLocalReferenceScope scope(env);
ChipLogError(Controller, "WriteAttributesCallback::ReportError is called with %u", errorCode);
jthrowable exception;
err = AndroidControllerExceptions::GetInstance().CreateAndroidControllerException(env, message, errorCode, exception);
VerifyOrReturn(err == CHIP_NO_ERROR,
ChipLogError(Controller,
"Unable to create AndroidControllerException on WriteAttributesCallback::ReportError: %s",
ErrorStr(err)));
jmethodID onErrorMethod;
VerifyOrReturn(mJavaCallbackRef.HasValidObjectRef(), ChipLogError(Controller, "mJavaCallbackRef is not valid in %s", __func__));
jobject javaCallback = mJavaCallbackRef.ObjectRef();
err = JniReferences::GetInstance().FindMethod(
env, javaCallback, "onError", "(Lchip/devicecontroller/model/ChipAttributePath;Ljava/lang/Exception;)V", &onErrorMethod);
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Unable to find onError method: %s", ErrorStr(err)));
DeviceLayer::StackUnlock unlock;
env->CallVoidMethod(javaCallback, onErrorMethod, attributePath, exception);
VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe());
}
InvokeCallback::InvokeCallback(jobject wrapperCallback, jobject javaCallback)
{
VerifyOrReturn(mWrapperCallbackRef.Init(wrapperCallback) == CHIP_NO_ERROR,
ChipLogError(Controller, "Could not init mWrapperCallbackRef for InvokeCallback"));
VerifyOrReturn(mJavaCallbackRef.Init(javaCallback) == CHIP_NO_ERROR,
ChipLogError(Controller, "Could not init mJavaCallbackRef in %s", __func__));
}
InvokeCallback::~InvokeCallback()
{
if (mCommandSender != nullptr)
{
Platform::Delete(mCommandSender);
}
}
void InvokeCallback::OnResponse(app::CommandSender * apCommandSender, const app::ConcreteCommandPath & aPath,
const app::StatusIB & aStatusIB, TLV::TLVReader * apData)
{
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread"));
jobject invokeElementObj = nullptr;
jmethodID onResponseMethod;
JniLocalReferenceScope scope(env);
err = CreateInvokeElement(env, aPath, apData, invokeElementObj);
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Unable to create Java InvokeElement: %s", ErrorStr(err)));
VerifyOrReturn(mJavaCallbackRef.HasValidObjectRef(), ChipLogError(Controller, "mJavaCallbackRef is not valid in %s", __func__));
jobject javaCallback = mJavaCallbackRef.ObjectRef();
err = JniReferences::GetInstance().FindMethod(env, javaCallback, "onResponse",
"(Lchip/devicecontroller/model/InvokeElement;J)V", &onResponseMethod);
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Unable to find onResponse method: %s", ErrorStr(err)));
DeviceLayer::StackUnlock unlock;
if (aStatusIB.mClusterStatus.HasValue())
{
env->CallVoidMethod(javaCallback, onResponseMethod, invokeElementObj, static_cast<jlong>(aStatusIB.mClusterStatus.Value()));
}
else
{
env->CallVoidMethod(javaCallback, onResponseMethod, invokeElementObj,
static_cast<jlong>(Protocols::InteractionModel::Status::Success));
}
VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe());
}
void InvokeCallback::OnError(const app::CommandSender * apCommandSender, CHIP_ERROR aError)
{
ReportError(aError);
}
void InvokeCallback::OnDone(app::CommandSender * apCommandSender)
{
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread"));
JniLocalReferenceScope scope(env);
VerifyOrReturn(mWrapperCallbackRef.HasValidObjectRef(),
ChipLogError(Controller, "mWrapperCallbackRef is not valid in %s", __func__));
JniGlobalReference globalRef(std::move(mWrapperCallbackRef));
jmethodID onDoneMethod;
VerifyOrReturn(mJavaCallbackRef.HasValidObjectRef(), ChipLogError(Controller, "mJavaCallbackRef is not valid in %s", __func__));
jobject javaCallback = mJavaCallbackRef.ObjectRef();
err = JniReferences::GetInstance().FindMethod(env, javaCallback, "onDone", "()V", &onDoneMethod);
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Could not find onDone method"));
DeviceLayer::StackUnlock unlock;
env->CallVoidMethod(javaCallback, onDoneMethod);
VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe());
}
void InvokeCallback::ReportError(CHIP_ERROR err)
{
ReportError(ErrorStr(err), err.AsInteger());
}
void InvokeCallback::ReportError(Protocols::InteractionModel::Status status)
{
ReportError("IM Status", static_cast<std::underlying_type_t<Protocols::InteractionModel::Status>>(status));
}
void InvokeCallback::ReportError(const char * message, ChipError::StorageType errorCode)
{
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread"));
JniLocalReferenceScope scope(env);
ChipLogError(Controller, "InvokeCallback::ReportError is called with %u", errorCode);
jthrowable exception;
err = AndroidControllerExceptions::GetInstance().CreateAndroidControllerException(env, message, errorCode, exception);
VerifyOrReturn(
err == CHIP_NO_ERROR,
ChipLogError(Controller, "Unable to create AndroidControllerException: %s on InvokeCallback::ReportError", ErrorStr(err)));
jmethodID onErrorMethod;
VerifyOrReturn(mJavaCallbackRef.HasValidObjectRef(), ChipLogError(Controller, "mJavaCallbackRef is not valid in %s", __func__));
jobject javaCallback = mJavaCallbackRef.ObjectRef();
err = JniReferences::GetInstance().FindMethod(env, javaCallback, "onError", "(Ljava/lang/Exception;)V", &onErrorMethod);
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Unable to find onError method: %s", ErrorStr(err)));
DeviceLayer::StackUnlock unlock;
env->CallVoidMethod(javaCallback, onErrorMethod, exception);
VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe());
}
} // namespace Controller
} // namespace chip