2 #include <android/log.h>
8 #include "cainterface.h"
11 #include "org_iotivity_service_RMInterface.h"
13 #define LOG_TAG "JNI_INTERFACE_SAMPLE"
14 #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
15 #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
21 #define IDENTITY ("1111111111111111")
25 #define RS_CLIENT_PSK ("AAAAAAAAAAAAAAAA")
28 #define SECURE_DEFAULT_PORT 5684
29 #define RESOURCE_URI_LENGTH 14
30 #define OPTION_INFO_LENGTH 1024
31 #define NETWORK_INFO_LENGTH 1024
33 uint16_t g_localSecurePort = SECURE_DEFAULT_PORT;
35 void request_handler(const CARemoteEndpoint_t* object, const CARequestInfo_t* requestInfo);
36 void response_handler(const CARemoteEndpoint_t* object, const CAResponseInfo_t* responseInfo);
37 void get_resource_uri(const char *URI, char *resourceURI, uint32_t length);
38 uint32_t get_secure_information(CAPayload_t payLoad);
39 CAResult_t get_network_type(uint32_t selectedNetwork);
40 void callback(char *subject, char *receivedData);
41 CAResult_t get_remote_address(CATransportType_t transportType, CAAddress_t addressInfo);
43 CATransportType_t g_selectedNwType = CA_IPV4;
44 static CAToken_t g_lastRequestToken = NULL;
45 static uint8_t g_lastRequestTokenLength;
47 static const char SECURE_COAPS_PREFIX[] = "coaps://";
49 static const char SECURE_INFO_DATA[]
50 = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
51 "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
52 static const char NORMAL_INFO_DATA[]
53 = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
54 "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
57 static jobject g_responseListenerObject = NULL;
60 static CARemoteEndpoint_t *g_clientEndpoint = NULL;
61 static CAToken_t g_clientToken;
62 static uint8_t g_clientTokenLength = NULL;
64 static uint16_t g_clientMsgId;
65 static char *g_remoteAddress = NULL;
68 JNIEXPORT void JNICALL
69 Java_org_iotivity_service_RMInterface_setNativeResponseListener(JNIEnv *env, jobject obj,
72 LOGI("setNativeResponseListener");
73 g_responseListenerObject = (*env)->NewGlobalRef(env, obj);
77 static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
79 void clearDtlsCredentialInfo()
81 LOGI("clearDtlsCredentialInfo IN");
84 // Initialize sensitive data to zeroes before freeing.
85 if (NULL != pskCredsBlob->creds)
87 memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds)*(pskCredsBlob->num));
88 free(pskCredsBlob->creds);
91 memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
95 LOGI("clearDtlsCredentialInfo OUT");
98 // Internal API. Invoked by OC stack to retrieve credentials from this module
99 void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
101 LOGI("CAGetDtlsPskCredentials IN");
102 *credInfo = (CADtlsPskCredsBlob_t *) malloc(sizeof(CADtlsPskCredsBlob_t));
103 if (NULL == *credInfo)
105 LOGE("Failed to allocate credential blob.");
109 int16_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
110 (*credInfo)->creds = (OCDtlsPskCreds *) malloc(credLen);
111 if (NULL == (*credInfo)->creds)
113 LOGE("Failed to allocate crentials.");
119 memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
120 (*credInfo)->num = pskCredsBlob->num;
121 memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
123 LOGI("CAGetDtlsPskCredentials OUT");
126 CAResult_t SetCredentials()
128 LOGI("SetCredentials IN");
129 pskCredsBlob = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
130 if (NULL == pskCredsBlob)
132 LOGE("Memory allocation failed!");
133 return CA_MEMORY_ALLOC_FAILED;
135 memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
137 pskCredsBlob->num = 1;
139 pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) *(pskCredsBlob->num));
140 if (NULL == pskCredsBlob->creds)
142 LOGE("Memory allocation failed!");
143 return CA_MEMORY_ALLOC_FAILED;
145 memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
146 memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
148 LOGI("SetCredentials OUT");
153 JNIEXPORT jint JNI_OnLoad(JavaVM *jvm, void *reserved)
158 if (JNI_OK != (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6))
162 g_jvm = jvm; /* cache the JavaVM pointer */
164 CANativeJNISetJavaVM(g_jvm);
166 return JNI_VERSION_1_6;
169 void JNI_OnUnload(JavaVM *jvm, void *reserved)
171 LOGI("JNI_OnUnload");
174 if (JNI_OK != (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6))
182 JNIEXPORT void JNICALL
183 Java_org_iotivity_service_RMInterface_RMInitialize(JNIEnv *env, jobject obj, jobject context)
185 LOGI("RMInitialize");
187 //Currently set context for Android Platform
188 CANativeJNISetContext(env, context);
190 CAResult_t res = CAInitialize();
192 if (CA_STATUS_OK != res)
194 LOGE("Could not Initialize");
198 if (CA_STATUS_OK != SetCredentials())
200 LOGE("SetCredentials failed");
204 res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
205 if(CA_STATUS_OK != res)
207 LOGE("Set credential handler fail");
213 JNIEXPORT void JNICALL
214 Java_org_iotivity_service_RMInterface_RMTerminate(JNIEnv *env, jobject obj)
217 CADestroyToken(g_lastRequestToken);
221 JNIEXPORT void JNICALL
222 Java_org_iotivity_service_RMInterface_RMStartListeningServer(JNIEnv *env, jobject obj)
224 LOGI("RMStartListeningServer");
226 if (CA_STATUS_OK != CAStartListeningServer())
228 LOGE("Could not start Listening server");
232 JNIEXPORT void JNICALL
233 Java_org_iotivity_service_RMInterface_RMStartDiscoveryServer(JNIEnv *env, jobject obj)
235 LOGI("RMStartDiscoveryServer");
237 if (CA_STATUS_OK != CAStartDiscoveryServer())
239 LOGE("Could not start discovery server");
243 JNIEXPORT void JNICALL
244 Java_org_iotivity_service_RMInterface_RMRegisterHandler(JNIEnv *env, jobject obj)
246 LOGI("RMRegisterHandler");
248 CARegisterHandler(request_handler, response_handler);
251 JNIEXPORT void JNICALL
252 Java_org_iotivity_service_RMInterface_RMFindResource(JNIEnv *env, jobject obj, jstring uri)
255 CAToken_t token = NULL;
256 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
258 CAResult_t res = CAGenerateToken(&token, tokenLength);
259 if ((CA_STATUS_OK != res) || (!token))
261 LOGE("token generate error!!");
265 printf("Generated token %s\n", token);
267 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
268 LOGI("RMFindResource - %s", strUri);
270 res = CAFindResource((const CAURI_t) strUri, token, tokenLength);
272 //ReleseStringUTFCharss for strUri
273 (*env)->ReleaseStringUTFChars(env, uri, strUri);
275 if (CA_STATUS_OK != res)
277 LOGE("Could not find resource");
279 CADestroyToken(token);
283 LOGI("find resource to %s URI", strUri);
284 CADestroyToken(g_lastRequestToken);
285 g_lastRequestToken = token;
286 g_lastRequestTokenLength = tokenLength;
290 JNIEXPORT void JNICALL
291 Java_org_iotivity_service_RMInterface_RMSendRequest(JNIEnv *env, jobject obj, jstring uri,
292 jstring payload, jint selectedNetwork,
293 jint isSecured, jint msgType)
295 LOGI("selectedNetwork - %d", selectedNetwork);
296 CAResult_t res = get_network_type(selectedNetwork);
297 if (CA_STATUS_OK != res)
302 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
303 LOGI("RMSendRequest - %s", strUri);
305 //create remote endpoint
306 CARemoteEndpoint_t* endpoint = NULL;
307 res = CACreateRemoteEndpoint((const CAURI_t) strUri, g_selectedNwType, &endpoint);
309 //ReleaseStringUTFChars for strUri
310 (*env)->ReleaseStringUTFChars(env, uri, strUri);
312 if (CA_STATUS_OK != res)
314 LOGE("Could not create remote end point");
318 CAMessageType_t messageType = msgType;
321 CAToken_t token = NULL;
322 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
324 res = CAGenerateToken(&token, tokenLength);
325 if ((CA_STATUS_OK != res) || (!token))
327 LOGE("token generate error!!");
328 // destroy remote endpoint
329 CADestroyRemoteEndpoint(endpoint);
333 char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
335 get_resource_uri((const CAURI_t) strUri, resourceURI, RESOURCE_URI_LENGTH);
337 CAInfo_t requestData = { 0 };
338 requestData.token = token;
339 requestData.tokenLength = tokenLength;
343 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
344 requestData.payload = (CAPayload_t) malloc(length);
345 if (NULL == requestData.payload)
347 LOGE("Memory allocation failed!");
349 CADestroyToken(token);
350 // destroy remote endpoint
351 CADestroyRemoteEndpoint(endpoint);
354 snprintf(requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
358 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
359 requestData.payload = (CAPayload_t) malloc(length);
360 if (NULL == requestData.payload)
362 LOGE("Memory allocation failed!");
364 CADestroyToken(token);
365 // destroy remote endpoint
366 CADestroyRemoteEndpoint(endpoint);
369 snprintf(requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
372 requestData.type = messageType;
374 CARequestInfo_t requestInfo = { 0 };
375 requestInfo.method = CA_GET;
376 requestInfo.info = requestData;
379 if (CA_STATUS_OK != CASendRequest(endpoint, &requestInfo))
381 LOGE("Could not send request");
385 CADestroyToken(token);
387 // destroy remote endpoint
388 CADestroyRemoteEndpoint(endpoint);
390 free(requestData.payload);
393 JNIEXPORT void JNICALL
394 Java_org_iotivity_service_RMInterface_RMSendReqestToAll(JNIEnv *env, jobject obj, jstring uri,
395 jint selectedNetwork)
397 LOGI("selectedNetwork - %d", selectedNetwork);
398 CAResult_t res = get_network_type(selectedNetwork);
399 if (CA_STATUS_OK != res)
404 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
405 LOGI("RMSendReqestToAll - %s", strUri);
407 // create remote endpoint
408 CARemoteEndpoint_t *endpoint = NULL;
409 res = CACreateRemoteEndpoint((const CAURI_t) strUri, g_selectedNwType, &endpoint);
411 //ReleaseStringUTFChars for strUri
412 (*env)->ReleaseStringUTFChars(env, uri, strUri);
414 if (CA_STATUS_OK != res)
416 LOGE("create remote endpoint error, error code: %d", res);
420 CAGroupEndpoint_t *group = (CAGroupEndpoint_t *) malloc(sizeof(CAGroupEndpoint_t));
423 LOGE("Memory allocation failed!");
424 CADestroyRemoteEndpoint(endpoint);
427 group->transportType = endpoint->transportType;
428 group->resourceUri = endpoint->resourceUri;
431 CAToken_t token = NULL;
432 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
434 res = CAGenerateToken(&token, tokenLength);
435 if ((CA_STATUS_OK != res) || (!token))
437 LOGE("token generate error!!");
438 // destroy remote endpoint
439 CADestroyRemoteEndpoint(endpoint);
444 LOGI("generated token %s", token);
446 CAInfo_t requestData = { 0 };
447 requestData.token = token;
448 requestData.tokenLength = tokenLength;
449 requestData.payload = "Temp Json Payload";
450 requestData.type = CA_MSG_NONCONFIRM;
452 CARequestInfo_t requestInfo = { 0 };
453 requestInfo.method = CA_GET;
454 requestInfo.info = requestData;
456 // send request to all
457 res = CASendRequestToAll(group, &requestInfo);
458 if (CA_STATUS_OK != res)
460 LOGE("Could not send request to all");
462 CADestroyToken(token);
466 CADestroyToken(g_lastRequestToken);
467 g_lastRequestToken = token;
468 g_lastRequestTokenLength = tokenLength;
471 // destroy remote endpoint
472 CADestroyRemoteEndpoint(endpoint);
477 JNIEXPORT void JNICALL
478 Java_org_iotivity_service_RMInterface_RMSendResponse(JNIEnv *env, jobject obj,
479 jint selectedNetwork,
480 jint isSecured, jint msgType,
483 LOGI("RMSendResponse");
485 LOGI("selectedNetwork - %d", selectedNetwork);
487 CAResult_t res = get_network_type(selectedNetwork);
488 if (CA_STATUS_OK != res)
490 LOGE("Not supported network type");
494 if (NULL == g_clientEndpoint)
496 LOGE("No Request received");
500 CAMessageType_t messageType = msgType;
502 CAInfo_t responseData = { 0 };
503 responseData.type = messageType;
504 responseData.messageId = g_clientMsgId;
506 CAResponseInfo_t responseInfo = { 0 };
508 if (msgType != CA_MSG_RESET)
510 responseData.token = g_clientToken;
511 responseData.tokenLength = g_clientTokenLength;
512 responseInfo.result = responseValue;
516 uint32_t length = strlen(SECURE_INFO_DATA) + strlen(g_clientEndpoint->resourceUri) + 1;
517 responseData.payload = (CAPayload_t) malloc(length);
518 sprintf(responseData.payload, SECURE_INFO_DATA, g_clientEndpoint->resourceUri,
523 uint32_t length = strlen(NORMAL_INFO_DATA) + strlen(g_clientEndpoint->resourceUri) + 1;
524 responseData.payload = (CAPayload_t) malloc(length);
525 sprintf(responseData.payload, NORMAL_INFO_DATA, g_clientEndpoint->resourceUri);
531 responseInfo.result = CA_EMPTY;
534 responseInfo.info = responseData;
537 res = CASendResponse(g_clientEndpoint, &responseInfo);
538 if (CA_STATUS_OK != res)
540 LOGE("Could not send response");
544 CADestroyToken(g_clientToken);
545 g_clientToken = NULL;
546 g_clientTokenLength = 0;
548 // destroy remote endpoint
549 CADestroyRemoteEndpoint(g_clientEndpoint);
550 g_clientEndpoint = NULL;
553 JNIEXPORT void JNICALL
554 Java_org_iotivity_service_RMInterface_RMAdvertiseResource(JNIEnv *env, jobject obj, jstring uri)
556 LOGI("RMAdvertiseResource");
558 uint32_t optionNum = 2;
560 CAHeaderOption_t *headerOpt = (CAHeaderOption_t*) calloc(1,
561 sizeof(CAHeaderOption_t) * optionNum);
562 if (NULL == headerOpt)
564 LOGE("Memory allocation failed!");
568 char* tmpOptionData1 = "Hello";
569 headerOpt[0].optionID = 3000;
570 memcpy(headerOpt[0].optionData, tmpOptionData1, strlen(tmpOptionData1));
571 headerOpt[0].optionLength = (uint16_t) strlen(tmpOptionData1);
573 char* tmpOptionData2 = "World";
574 headerOpt[1].optionID = 3001;
575 memcpy(headerOpt[1].optionData, tmpOptionData2, strlen(tmpOptionData2));
576 headerOpt[1].optionLength = (uint16_t) strlen(tmpOptionData2);
579 CAToken_t token = NULL;
580 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
582 CAResult_t res = CAGenerateToken(&token, tokenLength);
583 if ((CA_STATUS_OK != res) || (!token))
585 LOGE("token generate error!");
590 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
592 res = CAAdvertiseResource((const CAURI_t) strUri, token, tokenLength,
593 headerOpt, (uint8_t) optionNum);
594 if (CA_STATUS_OK != res)
596 LOGE("Could not start advertise resource");
597 CADestroyToken(token);
601 CADestroyToken(g_lastRequestToken);
602 g_lastRequestToken = token;
603 g_lastRequestTokenLength = tokenLength;
608 //ReleaseStringUTFChars for strUri
609 (*env)->ReleaseStringUTFChars(env, uri, strUri);
612 JNIEXPORT void JNICALL
613 Java_org_iotivity_service_RMInterface_RMSendNotification(JNIEnv *env, jobject obj, jstring uri,
614 jstring payload, jint selectedNetwork,
615 jint isSecured, jint msgType,
618 LOGI("selectedNetwork - %d", selectedNetwork);
620 CAResult_t res = get_network_type(selectedNetwork);
621 if (CA_STATUS_OK != res)
623 LOGE("Not supported network type");
627 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
628 LOGI("RMSendNotification - %s", strUri);
630 //create remote endpoint
631 CARemoteEndpoint_t* endpoint = NULL;
632 if (CA_STATUS_OK != CACreateRemoteEndpoint((const CAURI_t) strUri,
633 g_selectedNwType, &endpoint))
635 LOGE("Could not create remote end point");
638 //ReleaseStringUTFChars for strUri
639 (*env)->ReleaseStringUTFChars(env, uri, strUri);
642 char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
643 get_resource_uri((const CAURI_t) strUri, resourceURI, RESOURCE_URI_LENGTH);
645 //ReleaseStringUTFChars for strUri
646 (*env)->ReleaseStringUTFChars(env, uri, strUri);
648 CAMessageType_t messageType = msgType;
651 CAToken_t token = NULL;
652 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
654 res = CAGenerateToken(&token, tokenLength);
655 if ((CA_STATUS_OK != res) || (!token))
657 LOGE("token generate error!");
658 CADestroyRemoteEndpoint(endpoint);
662 CAInfo_t responseData = { 0 };
663 responseData.token = token;
664 responseData.tokenLength = tokenLength;
668 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
669 responseData.payload = (CAPayload_t) malloc(length);
670 if (NULL == responseData.payload)
672 LOGE("Memory allocation failed!");
674 CADestroyToken(token);
675 // destroy remote endpoint
676 CADestroyRemoteEndpoint(endpoint);
679 snprintf(responseData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
683 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
684 responseData.payload = (CAPayload_t) malloc(length);
685 if (NULL == responseData.payload)
687 LOGE("Memory allocation failed!");
689 CADestroyToken(token);
690 // destroy remote endpoint
691 CADestroyRemoteEndpoint(endpoint);
694 snprintf(responseData.payload, length, NORMAL_INFO_DATA, resourceURI);
697 responseData.type = messageType;
699 CAResponseInfo_t responseInfo = { 0 };
700 responseInfo.result = responseValue;
701 responseInfo.info = responseData;
704 if (CA_STATUS_OK != CASendNotification(endpoint, &responseInfo))
706 LOGE("Could not send notification");
709 LOGI("Send Notification");
712 CADestroyToken(token);
714 // destroy remote endpoint
715 CADestroyRemoteEndpoint(endpoint);
717 free(responseData.payload);
720 JNIEXPORT void JNICALL
721 Java_org_iotivity_service_RMInterface_RMSelectNetwork(JNIEnv *env, jobject obj, jint networkType)
723 LOGI("RMSelectNetwork Type : %d", networkType);
725 if (CA_STATUS_OK != CASelectNetwork(networkType))
727 LOGE("Could not select network");
731 JNIEXPORT void JNICALL
732 Java_org_iotivity_service_RMInterface_RMUnSelectNetwork(JNIEnv *env, jobject obj, jint networkType)
734 LOGI("RMUnSelectNetwork Type : %d", networkType);
736 if (CA_STATUS_OK != CAUnSelectNetwork(networkType))
738 LOGE("Could not unselect network");
742 JNIEXPORT void JNICALL
743 Java_org_iotivity_service_RMInterface_RMGetNetworkInfomation(JNIEnv *env, jobject obj)
745 LOGI("RMGetNetworkInfomation");
747 CALocalConnectivity_t *tempInfo = NULL;
748 uint32_t tempSize = 0;
750 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
751 if (CA_STATUS_OK != res)
753 LOGE("Could not start get network information");
758 LOGI("################## Network Information #######################");
759 callback("######## Network Information", "#######");
760 LOGI("Network info total size is %d", tempSize);
763 for (index = 0; index < tempSize; index++)
765 res = get_remote_address(tempInfo[index].type, tempInfo[index].addressInfo);
766 if (CA_STATUS_OK != res)
771 if (NULL != g_responseListenerObject)
773 char networkInfo[NETWORK_INFO_LENGTH];
774 LOGI("Type: %d", tempInfo[index].type);
775 sprintf(networkInfo, "%d",tempInfo[index].type);
776 callback("Type :", networkInfo);
777 if (CA_IPV4 == tempInfo[index].type)
779 LOGI("Port: %d", tempInfo[index].addressInfo.IP.port);
780 sprintf(networkInfo, "%d",tempInfo[index].addressInfo.IP.port);
781 callback("Port: ", networkInfo);
783 LOGI("Secured: %d", tempInfo[index].isSecured);
784 LOGI("Address: %s", g_remoteAddress);
785 callback("Address: ", g_remoteAddress);
786 free(g_remoteAddress);
788 if (true == tempInfo[index].isSecured)
790 g_localSecurePort = tempInfo[index].addressInfo.IP.port;
797 LOGI("##############################################################");
800 JNIEXPORT void JNICALL
801 Java_org_iotivity_service_RMInterface_RMHandleRequestResponse(JNIEnv *env, jobject obj)
803 LOGI("RMHandleRequestResponse");
805 if (CA_STATUS_OK != CAHandleRequestResponse())
807 LOGE("Could not handle request and response");
811 void request_handler(const CARemoteEndpoint_t* object, const CARequestInfo_t* requestInfo)
816 LOGE("Remote endpoint is NULL!");
822 LOGE("Request info is NULL!");
826 if ((NULL != g_lastRequestToken) && (NULL != requestInfo->info.token) &&
827 (strncmp(g_lastRequestToken, requestInfo->info.token,
828 requestInfo->info.tokenLength) == 0))
830 LOGI("token is same. received request of it's own. skip.. ");
834 CAResult_t res = get_remote_address(object->transportType, object->addressInfo);
835 if (CA_STATUS_OK != res)
840 LOGI("##########received request from remote device #############");
841 if (object->resourceUri)
843 LOGI("Uri: %s", object->resourceUri);
845 LOGI("Remote Address: %s", g_remoteAddress);
846 LOGI("Data: %s", requestInfo->info.payload);
847 LOGI("Token: %s", requestInfo->info.token);
848 LOGI("Code: %d", requestInfo->method);
849 LOGI("MessageType: %d", requestInfo->info.type);
851 if (NULL != g_responseListenerObject)
853 callback("received request from remote device", "#######");
854 char *cloneUri = NULL;
857 if (NULL != object->resourceUri)
859 len = strlen(object->resourceUri);
860 cloneUri = (char *) malloc(sizeof(char) * (len + 1));
862 if (NULL == cloneUri)
864 LOGE("cloneUri Out of memory");
865 free(g_remoteAddress);
869 memcpy(cloneUri, object->resourceUri, len + 1);
870 callback("Uri: ", cloneUri);
873 len = strlen(g_remoteAddress);
874 char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
876 if (NULL == cloneRemoteAddress)
878 LOGE("cloneRemoteAddress Out of memory");
879 free(g_remoteAddress);
884 memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
886 callback("Remote Address: ", cloneRemoteAddress);
887 free(cloneRemoteAddress);
888 free(g_remoteAddress);
890 //clone g_clientEndpoint
891 g_clientEndpoint = (CARemoteEndpoint_t *) malloc(sizeof(CARemoteEndpoint_t));
892 if (NULL == g_clientEndpoint)
894 LOGE("g_clientEndpoint Out of memory");
898 memcpy(g_clientEndpoint, object, sizeof(CARemoteEndpoint_t));
900 if (NULL != cloneUri)
902 len = strlen(cloneUri);
903 g_clientEndpoint->resourceUri = (char *) malloc(sizeof(char) * (len + 1));
904 if (NULL == g_clientEndpoint)
906 LOGE("g_clientEndpoint->resourceUri Out of memory");
907 free(g_clientEndpoint);
911 memcpy(g_clientEndpoint->resourceUri, cloneUri, len + 1);
914 //clone g_clientToken
915 len = requestInfo->info.tokenLength;
917 g_clientToken = (char *) malloc(sizeof(char) * len);
918 if (NULL == g_clientToken)
920 LOGE("g_clientToken Out of memory");
921 free(g_clientEndpoint->resourceUri);
922 free(g_clientEndpoint);
926 if (NULL != requestInfo->info.token)
928 memcpy(g_clientToken, requestInfo->info.token, len);
929 g_clientTokenLength = len;
933 //clone g_clientMsgId
934 g_clientMsgId = requestInfo->info.messageId;
936 if (NULL != requestInfo->info.payload)
938 len = strlen(requestInfo->info.payload);
939 char *clonePayload = (char *) malloc(sizeof(char) * (len + 1));
941 if (NULL == clonePayload)
943 LOGE("clonePayload Out of memory");
944 free(g_clientEndpoint->resourceUri);
945 free(g_clientEndpoint);
949 memcpy(clonePayload, requestInfo->info.payload, len + 1);
951 callback("Data: ", clonePayload);
956 if (requestInfo->info.options)
958 uint32_t len = requestInfo->info.numOptions;
961 LOGI("Option count: %d", requestInfo->info.numOptions);
963 for (i = 0; i < len; i++)
965 LOGI("Option %d", i + 1);
966 LOGI("ID : %d", requestInfo->info.options[i].optionID);
967 LOGI("Data[%d]: %s", requestInfo->info.options[i].optionLength,
968 requestInfo->info.options[i].optionData);
970 if (NULL != g_responseListenerObject)
972 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
973 sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
974 requestInfo->info.options[i].optionID,
975 requestInfo->info.options[i].optionLength);
977 callback("Option info: ", optionInfo);
979 if (0 != requestInfo->info.options[i].optionData)
981 uint32_t optionDataLen = strlen(requestInfo->info.options[i].optionData);
982 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
984 if (NULL == cloneOptionData)
986 LOGE("cloneOptionData Out of memory");
987 free(g_clientEndpoint->resourceUri);
988 free(g_clientEndpoint);
992 memcpy(cloneOptionData, requestInfo->info.options[i].optionData,
995 callback("Option Data: ", cloneOptionData);
996 free(cloneOptionData);
1001 LOGI("############################################################");
1003 //Check if this has secure communication information
1004 if (requestInfo->info.payload && CA_IPV4 == object->transportType)
1006 uint32_t securePort = get_secure_information(requestInfo->info.payload);
1007 if (0 < securePort) //Set the remote endpoint secure details and send response
1009 LOGI("This is secure resource...");
1011 uint32_t length = 0;
1013 length = sizeof(SECURE_COAPS_PREFIX) - 1; //length of "coaps://"
1014 // length of "ipaddress:port"
1015 length += strlen(object->addressInfo.IP.ipAddress) + PORT_LENGTH;
1016 length += strlen(object->resourceUri) + 1;
1018 uri = calloc(1, sizeof(char) * length);
1021 LOGE("Failed to create new uri");
1025 sprintf(uri, "%s%s:%d/%s", SECURE_COAPS_PREFIX, object->addressInfo.IP.ipAddress,
1026 securePort, object->resourceUri);
1028 CARemoteEndpoint_t *endpoint = NULL;
1029 if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, object->transportType, &endpoint))
1031 LOGE("Failed to create duplicate of remote endpoint!");
1035 endpoint->isSecured = true;
1043 void response_handler(const CARemoteEndpoint_t* object, const CAResponseInfo_t* responseInfo)
1046 CAResult_t res = get_remote_address(object->transportType, object->addressInfo);
1047 if (CA_STATUS_OK != res)
1052 LOGI("##########Received response from remote device #############");
1053 LOGI("Uri: %s", object->resourceUri);
1054 LOGI("Remote Address: %s", g_remoteAddress);
1055 LOGI("response result: %d", responseInfo->result);
1056 LOGI("Data: %s", responseInfo->info.payload);
1057 LOGI("Token: %s", responseInfo->info.token);
1058 LOGI("MessageType: %d", responseInfo->info.type);
1060 if (NULL != g_responseListenerObject)
1064 if (NULL != object->resourceUri)
1066 len = strlen(object->resourceUri);
1067 char *cloneUri = (char *) malloc(sizeof(char) * (len + 1));
1069 if (NULL == cloneUri)
1071 LOGE("cloneUri Out of memory");
1072 free(g_remoteAddress);
1076 memcpy(cloneUri, object->resourceUri, len + 1);
1078 callback("Uri: ", cloneUri);
1082 len = strlen(g_remoteAddress);
1083 char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
1085 if (NULL == cloneRemoteAddress)
1087 LOGE("cloneRemoteAddress Out of memory");
1088 free(g_remoteAddress);
1092 memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
1094 callback("Remote Address: ", cloneRemoteAddress);
1095 free(cloneRemoteAddress);
1096 free(g_remoteAddress);
1098 if (NULL != responseInfo->info.payload)
1100 len = strlen(responseInfo->info.payload);
1101 char *clonePayload = (char *) malloc(sizeof(char) * (len + 1));
1103 if (NULL == clonePayload)
1105 LOGE("clonePayload Out of memory");
1109 memcpy(clonePayload, responseInfo->info.payload, len + 1);
1111 callback("Data: ", clonePayload);
1116 if (responseInfo->info.options)
1118 uint32_t len = responseInfo->info.numOptions;
1120 for (i = 0; i < len; i++)
1122 LOGI("Option %d", i + 1);
1123 LOGI("ID : %d", responseInfo->info.options[i].optionID);
1124 LOGI("Data[%d]: %s", responseInfo->info.options[i].optionLength,
1125 responseInfo->info.options[i].optionData);
1127 if (NULL != g_responseListenerObject)
1129 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1130 sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
1131 responseInfo->info.options[i].optionID,
1132 responseInfo->info.options[i].optionLength);
1134 callback("Option info: ", optionInfo);
1136 if (0 != responseInfo->info.options[i].optionData)
1138 uint32_t optionDataLen = strlen(responseInfo->info.options[i].optionData);
1139 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1141 if (NULL == cloneOptionData)
1143 LOGE("cloneOptionData Out of memory");
1146 memcpy(cloneOptionData, responseInfo->info.options[i].optionData,
1148 callback("Option Data: ", cloneOptionData);
1149 free(cloneOptionData);
1154 LOGI("############################################################");
1156 //Check if this has secure communication information
1157 if (responseInfo->info.payload && CA_IPV4 == object->transportType)
1159 uint32_t securePort = get_secure_information(responseInfo->info.payload);
1160 if (0 < securePort) //Set the remote endpoint secure details and send response
1162 LOGI("This is secure resource...");
1167 void get_resource_uri(const char *URI, char *resourceURI, uint32_t length)
1169 const char *startPos = URI;
1170 const char *temp = NULL;
1171 if (NULL != (temp = strstr(URI, "://")))
1173 startPos = strchr(temp + 3, '/');
1176 LOGE("Resource URI is missing");
1181 const char *endPos = strchr(startPos, '?');
1184 endPos = URI + strlen(URI);
1188 if (endPos - startPos <= length)
1190 memcpy(resourceURI, startPos + 1, endPos - startPos);
1193 LOGI("URI: %s, ResourceURI: %s", URI, resourceURI);
1196 uint32_t get_secure_information(CAPayload_t payLoad)
1198 LOGI("entering get_secure_information");
1202 LOGE("Payload is NULL");
1206 const char *subString = NULL;
1207 if (NULL == (subString = strstr(payLoad, "\"sec\":1")))
1209 LOGE("This is not secure resource");
1213 if (NULL == (subString = strstr(payLoad, "\"port\":")))
1215 LOGE("This secure resource does not have port information");
1219 const char *startPos = strstr(subString, ":");
1222 LOGE("Parsing failed !");
1226 const char *endPos = strstr(startPos, "}");
1229 LOGE("Parsing failed !");
1233 char portStr[6] = { 0 };
1234 memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1236 LOGI("secured port is: %s", portStr);
1237 return atoi(portStr);
1240 CAResult_t get_network_type(uint32_t selectedNetwork)
1243 uint32_t number = selectedNetwork;
1245 if (!(number & 0xf))
1247 return CA_NOT_SUPPORTED;
1249 if (number & CA_IPV4)
1251 g_selectedNwType = CA_IPV4;
1252 return CA_STATUS_OK;
1254 if (number & CA_EDR)
1256 g_selectedNwType = CA_EDR;
1257 return CA_STATUS_OK;
1261 g_selectedNwType = CA_LE;
1262 return CA_STATUS_OK;
1265 return CA_NOT_SUPPORTED;
1268 void callback(char *subject, char *receivedData)
1271 uint32_t status = (*g_jvm)->GetEnv(g_jvm, (void **) &env, JNI_VERSION_1_6);
1272 uint32_t res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
1274 jclass cls = (*env)->GetObjectClass(env, g_responseListenerObject);
1275 jmethodID mid = (*env)->GetMethodID(env, cls, "OnResponseReceived",
1276 "(Ljava/lang/String;Ljava/lang/String;)V");
1278 jstring jsubject = (*env)->NewStringUTF(env, (char*) subject);
1279 jstring jreceivedData = (*env)->NewStringUTF(env, (char*) receivedData);
1280 (*env)->CallVoidMethod(env, g_responseListenerObject, mid, jsubject, jreceivedData);
1284 CAResult_t get_remote_address(CATransportType_t transportType, CAAddress_t addressInfo)
1288 if (CA_IPV4 == transportType)
1290 len = strlen(addressInfo.IP.ipAddress);
1291 g_remoteAddress = (char *) malloc(sizeof(char) * (len + 1));
1293 if (NULL == g_remoteAddress)
1295 LOGE("g_remoteAddress Out of memory");
1296 return CA_MEMORY_ALLOC_FAILED;
1299 memcpy(g_remoteAddress, addressInfo.IP.ipAddress, len + 1);
1302 else if (CA_EDR == transportType)
1304 len = strlen(addressInfo.BT.btMacAddress);
1305 g_remoteAddress = (char *) malloc(sizeof(char) * (len + 1));
1307 if (NULL == g_remoteAddress)
1309 LOGE("g_remoteAddress Out of memory");
1310 return CA_MEMORY_ALLOC_FAILED;
1313 memcpy(g_remoteAddress, addressInfo.BT.btMacAddress, len + 1);
1316 else if (CA_LE == transportType)
1318 len = strlen(addressInfo.LE.leMacAddress);
1319 g_remoteAddress = (char *) malloc(sizeof(char) * (len + 1));
1321 if (NULL == g_remoteAddress)
1323 LOGE("g_remoteAddress Out of memory");
1324 return CA_MEMORY_ALLOC_FAILED;
1327 memcpy(g_remoteAddress, addressInfo.LE.leMacAddress, len + 1);
1330 return CA_STATUS_OK;