1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 //-----------------------------------------------------------------------------
24 //-----------------------------------------------------------------------------
25 #define _POSIX_C_SOURCE 200112L
30 #include "ocstackinternal.h"
31 #include "ocresourcehandler.h"
32 #include "occlientcb.h"
33 #include "ocobserve.h"
36 #include "ocserverrequest.h"
37 #include "ocsecurityinternal.h"
40 #include "cainterface.h"
47 #include "coap_time.h"
52 #include <arpa/inet.h>
55 //-----------------------------------------------------------------------------
57 //-----------------------------------------------------------------------------
59 OC_STACK_UNINITIALIZED = 0, OC_STACK_INITIALIZED, OC_STACK_UNINIT_IN_PROGRESS
63 OC_PRESENCE_UNINITIALIZED = 0, OC_PRESENCE_INITIALIZED
67 //-----------------------------------------------------------------------------
69 //-----------------------------------------------------------------------------
70 static OCStackState stackState = OC_STACK_UNINITIALIZED;
72 OCResource *headResource = NULL;
73 static OCResource *tailResource = NULL;
75 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
76 static PresenceResource presenceResource;
77 static uint8_t PresenceTimeOutSize = 0;
78 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
82 OCDeviceEntityHandler defaultDeviceHandler;
83 OCStackResult getQueryFromUri(const char * uri, unsigned char** resourceType, char ** newURI);
85 //-----------------------------------------------------------------------------
87 //-----------------------------------------------------------------------------
88 #define TAG PCF("OCStack")
89 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
90 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
91 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
92 TAG, PCF(#arg " is NULL")); return (retVal); } }
93 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
96 //TODO: we should allow the server to define this
97 #define MAX_OBSERVE_AGE (0x2FFFFUL)
99 //=============================================================================
101 //=============================================================================
102 static uint32_t GetTime(float afterSeconds)
106 return now + (uint32_t)(afterSeconds * COAP_TICKS_PER_SECOND);
109 static OCStackResult FormOCResponse(OCResponse * * responseLoc,
112 unsigned char * fullUri,
113 unsigned char * rcvdUri,
114 CAToken_t * rcvdToken,
115 OCClientResponse * clientResponse,
116 unsigned char * bufRes)
118 OCResponse * response = (OCResponse *) OCMalloc(sizeof(OCResponse));
121 return OC_STACK_NO_MEMORY;
123 response->cbNode = cbNode;
124 response->maxAge = maxAge;
125 response->fullUri = fullUri;
126 response->rcvdUri = rcvdUri;
127 response->rcvdToken = rcvdToken;
128 response->clientResponse = clientResponse;
129 response->bufRes = bufRes;
131 *responseLoc = response;
135 /// This method is used to create the IPv4 dev_addr structure.
136 /// TODO: Remove in future. Temporary helper function.
137 /// Builds a socket interface address using IP address and port number
138 static int32_t OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d,
139 uint16_t port, OCDevAddr *ipAddr)
142 OC_LOG(FATAL, TAG, "Invalid argument");
150 *((uint16_t*)&(ipAddr->addr[4])) = port;
155 //-----------------------------------------------------------------------------
156 // Internal API function
157 //-----------------------------------------------------------------------------
159 // This internal function is called to update the stack with the status of
160 // observers and communication failures
161 OCStackResult OCStackFeedBack(CAToken_t * token, uint8_t status)
163 OCStackResult result = OC_STACK_ERROR;
164 ResourceObserver * observer = NULL;
165 OCEntityHandlerRequest ehRequest = {0};
169 case OC_OBSERVER_NOT_INTERESTED:
170 OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
171 observer = GetObserverUsingToken (token);
174 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
175 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
176 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
177 if(result != OC_STACK_OK)
181 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
183 //observer is not observing anymore
184 result = DeleteObserverUsingToken (token);
185 if(result == OC_STACK_OK)
187 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
191 result = OC_STACK_OK;
192 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
195 case OC_OBSERVER_STILL_INTERESTED:
196 //observer is still interested
197 OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
198 notifications, reset the failedCount"));
199 observer = GetObserverUsingToken (token);
202 observer->forceHighQos = 0;
203 observer->failedCommCount = 0;
204 result = OC_STACK_OK;
208 result = OC_STACK_OBSERVER_NOT_FOUND;
211 case OC_OBSERVER_FAILED_COMM:
212 //observer is not reachable
213 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
214 observer = GetObserverUsingToken (token);
217 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
219 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
220 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
221 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
222 if(result != OC_STACK_OK)
224 return OC_STACK_ERROR;
226 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
227 //observer is unreachable
228 result = DeleteObserverUsingToken (token);
229 if(result == OC_STACK_OK)
231 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
235 result = OC_STACK_OK;
236 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
241 observer->failedCommCount++;
242 result = OC_STACK_CONTINUE;
244 observer->forceHighQos = 1;
245 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
249 OC_LOG(ERROR, TAG, PCF("Unknown status"));
250 result = OC_STACK_ERROR;
256 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
258 OCStackResult ret = OC_STACK_ERROR;
266 ret = OC_STACK_RESOURCE_CREATED;
269 ret = OC_STACK_RESOURCE_DELETED;
272 ret = OC_STACK_INVALID_QUERY;
275 ret = OC_STACK_INVALID_OPTION;
278 ret = OC_STACK_NO_RESOURCE;
286 OCStackResult OCToCAConnectivityType(OCConnectivityType ocConType, CAConnectivityType_t* caConType)
288 OCStackResult ret = OC_STACK_OK;
293 *caConType = CA_ETHERNET;
296 *caConType = CA_WIFI;
305 // Currently OC_ALL represents WIFI and ETHERNET
306 // Add other connectivity types as they are enabled in future
307 *caConType = (CAConnectivityType_t) (CA_WIFI|CA_ETHERNET);
310 ret = OC_STACK_INVALID_PARAM;
316 OCStackResult CAToOCConnectivityType(CAConnectivityType_t caConType, OCConnectivityType *ocConType)
318 OCStackResult ret = OC_STACK_OK;
323 *ocConType = OC_ETHERNET;
326 *ocConType = OC_WIFI;
335 ret = OC_STACK_INVALID_PARAM;
341 // update response.addr appropriately from endPoint.addressInfo
342 OCStackResult UpdateResponseAddr(OCClientResponse *response, const CARemoteEndpoint_t* endPoint)
344 OCStackResult ret = OC_STACK_ERROR;
345 static OCDevAddr address = {0};
347 char * savePtr = NULL;
348 char * cpAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
351 ret = OC_STACK_NO_MEMORY;
354 memcpy(cpAddress, endPoint->addressInfo.IP.ipAddress,
355 strlen(endPoint->addressInfo.IP.ipAddress) + 1);
357 // Grabs the first three numbers from the IPv4 address and replaces dots
358 for(int i=0; i<4; i++)
360 tok = strtok_r(i==0 ? cpAddress : NULL, ".", &savePtr);
364 ret = OC_STACK_ERROR;
367 address.addr[i] = atoi(tok);
370 memcpy(&address.addr[4], &endPoint->addressInfo.IP.port, sizeof(uint32_t));
374 response->addr = &address;
375 ret = CAToOCConnectivityType(endPoint->connectivityType, &(response->connType));
379 OC_LOG(ERROR, TAG, PCF("OCClientResponse is NULL!"));
386 void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge, char** resType)
390 // The format of the payload is {"oc":[%u:%u:%s]}
391 // %u : sequence number,
393 // %s : Resource Type (Optional)
394 tok = strtok_r(payload, "[:]}", &savePtr);
395 payload[strlen(payload)] = ':';
396 tok = strtok_r(NULL, "[:]}", &savePtr);
397 payload[strlen((char *)payload)] = ':';
398 *seqNum = (uint32_t) atoi(tok);
400 tok = strtok_r(NULL, "[:]}", &savePtr);
401 *maxAge = (uint32_t) atoi(tok);
402 tok = strtok_r(NULL, "[:]}",&savePtr);
406 *resType = (char *)OCMalloc(strlen(tok));
411 payload[strlen((char *)payload)] = ':';
412 strcpy(*resType, tok);
413 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s", *resType);
415 payload[strlen((char *)payload)] = ']';
418 OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
419 const CAResponseInfo_t* responseInfo)
421 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
422 ClientCB * cbNode = NULL;
423 char *resourceTypeName = NULL;
424 OCClientResponse response;
425 OCStackResult result = OC_STACK_ERROR;
426 uint32_t lowerBound = 0;
427 uint32_t higherBound = 0;
430 char *fullUri = NULL;
431 char *ipAddress = NULL;
432 int presenceSubscribe = 0;
433 int multicastPresenceSubscribe = 0;
435 if (responseInfo->result != CA_SUCCESS)
437 OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
438 return OC_STACK_ERROR;
441 fullUri = (char *) OCMalloc(MAX_URI_LENGTH );
445 OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for fullUri"));
446 result = OC_STACK_NO_MEMORY;
450 ipAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
452 if(NULL == ipAddress)
454 OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for ipAddress"));
455 result = OC_STACK_NO_MEMORY;
459 strncpy(ipAddress, endPoint->addressInfo.IP.ipAddress,
460 strlen(endPoint->addressInfo.IP.ipAddress));
461 ipAddress[strlen(endPoint->addressInfo.IP.ipAddress)] = '\0';
463 snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", ipAddress, endPoint->addressInfo.IP.port,
466 cbNode = GetClientCB(NULL, NULL, (unsigned char *) fullUri);
470 presenceSubscribe = 1;
474 snprintf(fullUri, MAX_URI_LENGTH, "%s%s", OC_MULTICAST_IP, endPoint->resourceUri);
475 cbNode = GetClientCB(NULL, NULL, (unsigned char *) fullUri);
478 multicastPresenceSubscribe = 1;
482 if(!presenceSubscribe && !multicastPresenceSubscribe)
484 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
485 ------------ ignoring"));
489 // No payload to the application in case of presence
490 response.resJSONPayload = NULL;
491 response.result = OC_STACK_OK;
493 result = UpdateResponseAddr(&response, endPoint);
494 if(result != OC_STACK_OK)
499 if(responseInfo->info.payload)
501 parsePresencePayload(responseInfo->info.payload,
502 &(response.sequenceNumber),
507 if(presenceSubscribe)
509 if(cbNode->sequenceNumber == response.sequenceNumber)
511 OC_LOG(INFO, TAG, PCF("===============No presence change"));
517 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
518 response.result = OC_STACK_PRESENCE_STOPPED;
521 OCFree(cbNode->presence->timeOut);
522 OCFree(cbNode->presence);
523 cbNode->presence = NULL;
528 if(!cbNode->presence)
530 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
532 if(!(cbNode->presence))
534 OC_LOG(ERROR, TAG, PCF("Could not allocate memory for cbNode->presence"));
535 result = OC_STACK_NO_MEMORY;
539 VERIFY_NON_NULL_V(cbNode->presence);
540 cbNode->presence->timeOut = NULL;
541 cbNode->presence->timeOut = (uint32_t *)
542 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
543 if(!(cbNode->presence->timeOut)){
545 PCF("Could not allocate memory for cbNode->presence->timeOut"));
546 OCFree(cbNode->presence);
547 result = OC_STACK_NO_MEMORY;
552 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %u", GetTime(0));
553 cbNode->presence->TTL = maxAge;
554 for(int index = 0; index < PresenceTimeOutSize; index++)
556 lowerBound = GetTime(PresenceTimeOut[index]/ 100.0f*cbNode->presence->TTL);
557 higherBound = GetTime(PresenceTimeOut[index + 1]/100.0f*cbNode->presence->TTL);
558 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
559 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
560 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
561 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
562 cbNode->presence->timeOut[index]);
564 cbNode->presence->TTLlevel = 0;
565 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
568 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
569 cbNode->sequenceNumber = response.sequenceNumber;
571 // Ensure that a filter is actually applied.
572 if(resourceTypeName && cbNode->filterResourceType)
574 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
583 // This is the multicast case
585 OCMulticastNode* mcNode = NULL;
586 mcNode = GetMCPresenceNode((const unsigned char *)fullUri);
590 if(mcNode->nonce == response.sequenceNumber)
592 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
595 mcNode->nonce = response.sequenceNumber;
599 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
600 response.result = OC_STACK_PRESENCE_STOPPED;
605 uint32_t uriLen = strlen((char*)fullUri);
606 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
609 memcpy(uri, fullUri, (uriLen + 1));
614 PCF("===============No Memory for URI to store in the presence node"));
615 result = OC_STACK_NO_MEMORY;
618 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri, response.sequenceNumber);
619 if(result == OC_STACK_NO_MEMORY)
622 PCF("===============No Memory for Multicast Presence Node"));
623 result = OC_STACK_NO_MEMORY;
629 // Ensure that a filter is actually applied.
630 if(resourceTypeName && cbNode->filterResourceType)
632 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
639 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
641 if (cbResult == OC_STACK_DELETE_TRANSACTION)
643 FindAndDeleteClientCB(cbNode);
649 OCFree(resourceTypeName);
654 //This function will be called back by CA layer when a response is received
655 void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
657 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
659 OCStackApplicationResult appResult = OC_STACK_DELETE_TRANSACTION;
663 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
667 if(NULL == responseInfo)
669 OC_LOG(ERROR, TAG, PCF("responseInfo is NULL"));
673 if(strcmp(endPoint->resourceUri, OC_PRESENCE_URI) == 0)
675 HandlePresenceResponse(endPoint, responseInfo);
679 ClientCB *cbNode = GetClientCB((CAToken_t *)&(responseInfo->info.token), NULL, NULL);
683 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
684 OCClientResponse response;
686 OCStackResult result = UpdateResponseAddr(&response, endPoint);
687 if(result != OC_STACK_OK)
689 OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint"));
693 response.result = CAToOCStackResult(responseInfo->result);
694 response.resJSONPayload = (unsigned char*)responseInfo->info.payload;
695 response.numRcvdVendorSpecificHeaderOptions = 0;
696 if(responseInfo->info.numOptions > 0)
699 //First option always with option ID is OC_COAP_OPTION_OBSERVE if it is available.
700 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
702 memcpy (&(response.sequenceNumber),
703 &(responseInfo->info.options[0].optionData), sizeof(uint32_t));
704 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
709 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
712 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
714 OC_LOG(ERROR, TAG, PCF("#header options are more than MAX_HEADER_OPTIONS"));
718 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
720 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
721 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
724 appResult = cbNode->callBack(cbNode->context,
725 cbNode->handle, &response);
726 if (appResult == OC_STACK_DELETE_TRANSACTION)
728 FindAndDeleteClientCB(cbNode);
731 OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload);
732 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
735 //This function will be called back by CA layer when a request is received
736 void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
738 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
741 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
747 OC_LOG(ERROR, TAG, PCF("requestInfo is NULL"));
751 OCStackResult requestResult = OC_STACK_ERROR;
753 if(myStackMode == OC_CLIENT)
755 //TODO: should the client be responding to requests?
759 OCServerProtocolRequest serverRequest = {};
761 OC_LOG_V(INFO, TAG, PCF("***** Endpoint URI ***** : %s\n"), (char*)endPoint->resourceUri);
763 char * newUri = (char *)endPoint->resourceUri;
764 unsigned char * query = NULL;
765 getQueryFromUri(endPoint->resourceUri, &query, &newUri);
766 OC_LOG_V(INFO, TAG, PCF("**********URI without query ****: %s\n"), newUri);
767 OC_LOG_V(INFO, TAG, PCF("**********Query ****: %s\n"), query);
768 if(strlen(newUri) < MAX_URI_LENGTH)
771 memcpy (&(serverRequest.resourceUrl), newUri, strlen(newUri));
775 OC_LOG(ERROR, TAG, PCF("URI length exceeds MAX_URI_LENGTH."));
781 if(strlen((char*)query) < MAX_QUERY_LENGTH)
783 memcpy (&(serverRequest.query), query, strlen((char*)query));
787 OC_LOG(ERROR, TAG, PCF("Query length exceeds MAX_QUERY_LENGTH."));
791 //copy request payload
792 if (requestInfo->info.payload)
794 serverRequest.reqTotalSize = strlen(requestInfo->info.payload) + 1;
795 memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
796 strlen(requestInfo->info.payload));
797 serverRequest.reqTotalSize = strlen((const char *)requestInfo->info.payload) + 1;
801 serverRequest.reqTotalSize = 1;
804 switch (requestInfo->method)
808 serverRequest.method = OC_REST_GET;
813 serverRequest.method = OC_REST_PUT;
818 serverRequest.method = OC_REST_POST;
823 serverRequest.method = OC_REST_DELETE;
828 OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
833 OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d", CA_MAX_TOKEN_LEN);
834 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token, CA_MAX_TOKEN_LEN);
836 serverRequest.requestToken = (CAToken_t)OCCalloc(1, CA_MAX_TOKEN_LEN+1);
838 if (!serverRequest.requestToken)
840 OC_LOG(FATAL, TAG, "Server Request Token is NULL");
843 memcpy(serverRequest.requestToken, requestInfo->info.token, CA_MAX_TOKEN_LEN);
845 if (requestInfo->info.type == CA_MSG_CONFIRM)
847 serverRequest.qos = OC_HIGH_QOS;
849 else if (requestInfo->info.type == CA_MSG_NONCONFIRM)
851 serverRequest.qos = OC_LOW_QOS;
853 else if (requestInfo->info.type == CA_MSG_ACKNOWLEDGE)
855 // TODO-CA: Need to handle this
857 else if (requestInfo->info.type == CA_MSG_RESET)
859 // TODO-CA: Need to handle this
861 // CA does not need the following 3 fields
862 serverRequest.coapID = 0;
863 serverRequest.delayedResNeeded = 0;
864 serverRequest.secured = endPoint->isSecured;
867 serverRequest.addressInfo = endPoint->addressInfo;
868 serverRequest.connectivityType = endPoint->connectivityType;
870 // copy vendor specific header options
871 // TODO-CA: CA is including non-vendor header options as well, like observe.
872 // Need to filter those out
873 uint8_t tempNum = (requestInfo->info.numOptions);
874 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
875 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
878 PCF("The request info numOptions is greater than MAX_HEADER_OPTIONS"));
879 OCFree(serverRequest.requestToken);
882 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
883 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
885 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
886 sizeof(CAHeaderOption_t)*tempNum);
889 requestResult = HandleStackRequests (&serverRequest);
890 if(requestResult != OC_STACK_OK)
892 OC_LOG(ERROR, TAG, PCF("HandleStackRequests failed"));
894 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
897 //This function will be called back by occoap layer when a request is received
898 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
900 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
901 OCStackResult result = OC_STACK_ERROR;
902 ResourceHandling resHandling;
903 OCResource *resource;
906 OC_LOG(ERROR, TAG, PCF("protocolRequest is NULL"));
907 return OC_STACK_INVALID_PARAM;
910 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
913 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
914 result = AddServerRequest(&request, protocolRequest->coapID,
915 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
916 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
917 protocolRequest->observationOption, protocolRequest->qos,
918 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
919 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
920 protocolRequest->resourceUrl,protocolRequest->reqTotalSize,
921 &protocolRequest->addressInfo, protocolRequest->connectivityType);
922 if (OC_STACK_OK != result)
924 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
927 VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
929 if(!protocolRequest->reqMorePacket)
931 request->requestComplete = 1;
936 OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
939 if(request->requestComplete)
941 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
942 result = DetermineResourceHandling (request, &resHandling, &resource);
943 if (result == OC_STACK_OK)
945 result = ProcessRequest(resHandling, resource, request);
949 result = OC_STACK_ERROR;
954 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
955 result = OC_STACK_CONTINUE;
960 int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
963 unsigned char *itr, *coap;
964 uint8_t dotCount = 0;
968 /* search for scheme */
970 if (!isdigit((unsigned char) *ipAddrStr))
972 coap = (unsigned char *) OC_COAP_SCHEME;
973 while (*coap && tolower(*itr) == *coap)
982 if (isdigit((unsigned char) *ipAddrStr))
985 ipAddr[index] += *ipAddrStr - '0';
987 else if ((unsigned char) *ipAddrStr == '.')
999 if(*ipAddrStr == ':')
1003 if (isdigit((unsigned char) *ipAddrStr))
1006 *port += *ipAddrStr - '0';
1017 if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
1028 //-----------------------------------------------------------------------------
1029 // Private internal function prototypes
1030 //-----------------------------------------------------------------------------
1032 static OCDoHandle GenerateInvocationHandle();
1033 static OCStackResult initResources();
1034 static void insertResource(OCResource *resource);
1035 static OCResource *findResource(OCResource *resource);
1036 static void insertResourceType(OCResource *resource,
1037 OCResourceType *resourceType);
1038 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
1040 static void insertResourceInterface(OCResource *resource,
1041 OCResourceInterface *resourceInterface);
1042 static OCResourceInterface *findResourceInterfaceAtIndex(
1043 OCResourceHandle handle, uint8_t index);
1044 static void deleteResourceType(OCResourceType *resourceType);
1045 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
1046 static void deleteResourceElements(OCResource *resource);
1047 static int deleteResource(OCResource *resource);
1048 static void deleteAllResources();
1049 static void incrementSequenceNumber(OCResource * resPtr);
1050 static OCStackResult verifyUriQueryLength(const char * inputUri,
1052 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
1053 OCStackResult getResourceType(const char * query, unsigned char** resourceType);
1054 static CAResult_t OCSelectNetwork();
1056 //-----------------------------------------------------------------------------
1058 //-----------------------------------------------------------------------------
1061 * Initialize the OC Stack. Must be called prior to starting the stack.
1064 * IP Address of host device
1066 * Port of host device
1068 * Host device is client, server, or client-server
1071 * OC_STACK_OK - no errors
1072 * OC_STACK_ERROR - stack init error
1074 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1076 OCStackResult result = OC_STACK_ERROR;
1077 CAResult_t caResult = CA_STATUS_OK;
1078 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
1081 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)))
1083 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1084 return OC_STACK_ERROR;
1089 OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
1093 caResult = CAInitialize();
1094 if(caResult == CA_STATUS_OK)
1096 caResult = OCSelectNetwork();
1100 OC_LOG(ERROR, TAG, PCF("Failed to initialize the CA Layer."));
1101 return CAResultToOCResult(caResult);
1104 if(caResult == CA_STATUS_OK)
1106 CARegisterHandler(HandleCARequests, HandleCAResponses);
1108 OC_LOG(INFO, TAG, PCF("CARegisterHandler..."));
1109 stackState = OC_STACK_INITIALIZED;
1110 result = OC_STACK_OK;
1114 caResult = CAStartDiscoveryServer();
1115 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
1118 caResult = CAStartListeningServer();
1119 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
1121 case OC_CLIENT_SERVER:
1122 caResult = CAStartListeningServer();
1123 if(caResult == CA_STATUS_OK)
1125 caResult = CAStartDiscoveryServer();
1127 OC_LOG(INFO, TAG, PCF("Client-server mode"));
1130 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1131 return OC_STACK_ERROR;
1137 result = CAResultToOCResult(caResult);
1141 OC_LOG(ERROR, TAG, PCF("Failed to initialize any transports."));
1142 return CAResultToOCResult(caResult);
1146 defaultDeviceHandler = NULL;
1148 #if defined(__WITH_DTLS__)
1149 caResult = CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials);
1150 result = (caResult == CA_STATUS_OK) ? OC_STACK_OK : OC_STACK_ERROR;
1151 #endif // (__WITH_DTLS__)
1153 #ifdef WITH_PRESENCE
1154 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
1155 #endif // WITH_PRESENCE
1157 if (result == OC_STACK_OK)
1159 stackState = OC_STACK_INITIALIZED;
1161 // Initialize resource
1162 if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
1164 result = initResources();
1166 if(result != OC_STACK_OK)
1168 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1174 * Stop the OC stack. Use for a controlled shutdown.
1176 * OC_STACK_OK - no errors
1177 * OC_STACK_ERROR - stack not initialized
1179 OCStackResult OCStop()
1181 OCStackResult result = OC_STACK_ERROR;
1183 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1185 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1187 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1190 else if (stackState != OC_STACK_INITIALIZED)
1192 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1193 return OC_STACK_ERROR;
1196 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1198 #ifdef WITH_PRESENCE
1199 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1200 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1201 presenceResource.presenceTTL = 0;
1202 #endif // WITH_PRESENCE
1204 // Free memory dynamically allocated for resources
1205 deleteAllResources();
1208 //CATerminate does not return any error code. It is OK to assign result to OC_STACK_OK.
1209 result = OC_STACK_OK;
1211 if (result == OC_STACK_OK)
1213 // Remove all observers
1214 DeleteObserverList();
1215 // Remove all the client callbacks
1216 DeleteClientCBList();
1217 stackState = OC_STACK_UNINITIALIZED;
1218 result = OC_STACK_OK;
1220 stackState = OC_STACK_INITIALIZED;
1221 result = OC_STACK_ERROR;
1224 // Deinit security blob
1225 DeinitOCSecurityInfo();
1227 if (result != OC_STACK_OK) {
1228 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
1235 * Map OCQualityOfService to CAMessageType
1237 * @param OCQualityOfService - Input qos.
1239 * Returns CA message type for a given qos.
1241 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
1246 return CA_MSG_CONFIRM;
1251 return CA_MSG_NONCONFIRM;
1256 * Verify the lengths of the URI and the query separately
1258 * @param inputUri - Input URI and query.
1259 * @param uriLen - The length of the initial URI with query.
1261 * Note: The '?' that appears after the URI is not considered as
1262 * a part of the query.
1264 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1268 query = strchr (inputUri, '?');
1272 if((query - inputUri) > MAX_URI_LENGTH)
1274 return OC_STACK_INVALID_URI;
1277 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1279 return OC_STACK_INVALID_QUERY;
1282 else if(uriLen > MAX_URI_LENGTH)
1284 return OC_STACK_INVALID_URI;
1290 * Discover or Perform requests on a specified resource
1291 * (specified by that Resource's respective URI).
1293 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of
1295 * @param method - @ref OCMethod to perform on the resource
1296 * @param requiredUri - URI of the resource to interact with
1297 * @param referenceUri - URI of the reference resource
1298 * @param request - JSON encoded request
1299 * @param qos - quality of service
1300 * @param cbData - struct that contains asynchronous callback function that is invoked
1301 * by the stack when discovery or resource interaction is complete
1302 * @param options - The address of an array containing the vendor specific header
1303 * header options to be sent with the request
1304 * @param numOptions - Number of vendor specific header options to be included
1307 * OC_STACK_OK - no errors
1308 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
1309 * OC_STACK_INVALID_METHOD - invalid resource method
1310 * OC_STACK_INVALID_URI - invalid required or reference URI
1312 * Note: IN case of CA, when using multicast, the required URI should not contain IP address.
1313 * Instead, it just contains the URI to the resource such as "/oc/core".
1315 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1316 const char *referenceUri, const char *request, OCConnectivityType conType,
1317 OCQualityOfService qos, OCCallbackData *cbData,
1318 OCHeaderOption * options, uint8_t numOptions)
1320 OCStackResult result = OC_STACK_ERROR;
1321 ClientCB *clientCB = NULL;
1322 unsigned char * requestUri = NULL;
1323 unsigned char * resourceType = NULL;
1324 unsigned char * query = NULL;
1325 char * newUri = (char *)requiredUri;
1326 (void) referenceUri;
1327 CARemoteEndpoint_t* endpoint = NULL;
1328 CAResult_t caResult;
1329 CAToken_t token = NULL;
1330 CAInfo_t requestData;
1331 CARequestInfo_t requestInfo;
1332 CAGroupEndpoint_t grpEnd = {0};
1333 OCDoHandle resHandle = NULL;
1335 // To track if memory is allocated for additional header options
1336 uint8_t hdrOptionMemAlloc = 0;
1338 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1340 // Validate input parameters
1341 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1342 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1344 //TODO ("Need to form the final query by concatenating require and reference URI's");
1345 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
1347 uint16_t uriLen = strlen(requiredUri);
1349 // ToDo: We should also check if the requiredUri has a mutlicast address,
1350 // then qos has to be OC_Low_QOS
1356 case OC_REST_DELETE:
1357 case OC_REST_OBSERVE:
1358 case OC_REST_OBSERVE_ALL:
1359 case OC_REST_CANCEL_OBSERVE:
1361 #ifdef WITH_PRESENCE
1362 case OC_REST_PRESENCE:
1366 result = OC_STACK_INVALID_METHOD;
1370 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
1375 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
1377 result = OC_STACK_INVALID_PARAM;
1381 #ifdef WITH_PRESENCE
1382 if(method == OC_REST_PRESENCE)
1384 result = getQueryFromUri(requiredUri, &query, &newUri);
1387 result = getResourceType((char *) query, &resourceType);
1390 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1394 OC_LOG(DEBUG, TAG, PCF("Resource type is NULL."));
1399 OC_LOG(DEBUG, TAG, PCF("Query string is NULL."));
1401 if(result != OC_STACK_OK)
1406 #endif // WITH_PRESENCE
1408 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
1411 memcpy(requestUri, newUri, (uriLen + 1));
1415 result = OC_STACK_NO_MEMORY;
1419 resHandle = GenerateInvocationHandle();
1422 result = OC_STACK_NO_MEMORY;
1426 memset(&requestData, 0, sizeof(CAInfo_t));
1427 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1431 case OC_REST_OBSERVE:
1432 case OC_REST_OBSERVE_ALL:
1433 case OC_REST_CANCEL_OBSERVE:
1435 requestInfo.method = CA_GET;
1440 requestInfo.method = CA_PUT;
1445 requestInfo.method = CA_POST;
1448 case OC_REST_DELETE:
1450 requestInfo.method = CA_DELETE;
1453 #ifdef WITH_PRESENCE
1454 case OC_REST_PRESENCE:
1456 // Replacing method type with GET because "presence"
1457 // is a stack layer only implementation.
1458 requestInfo.method = CA_GET;
1463 result = OC_STACK_INVALID_METHOD;
1467 //High QoS is not supported
1468 if(qos == OC_HIGH_QOS)
1470 result = OC_STACK_INVALID_PARAM;
1475 caResult = CAGenerateToken(&token);
1476 if (caResult != CA_STATUS_OK)
1478 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1479 CADestroyToken(token);
1483 requestData.type = qualityOfServiceToMessageType(qos);
1484 requestData.token = token;
1485 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1487 result = CreateObserveHeaderOption (&(requestData.options), options,
1488 numOptions, OC_OBSERVE_REGISTER);
1489 if (result != OC_STACK_OK)
1493 hdrOptionMemAlloc = 1;
1494 requestData.numOptions = numOptions + 1;
1498 requestData.options = (CAHeaderOption_t*)options;
1499 requestData.numOptions = numOptions;
1501 requestData.payload = (char *)request;
1503 requestInfo.info = requestData;
1505 CAConnectivityType_t caConType;
1507 result = OCToCAConnectivityType((OCConnectivityType) conType, &caConType);
1508 if (result != OC_STACK_OK)
1510 OC_LOG(ERROR, TAG, PCF("Invalid Connectivity Type"));
1515 if(conType == OC_ALL)
1517 grpEnd.connectivityType = caConType;
1519 grpEnd.resourceUri = (CAURI_t) OCMalloc(uriLen + 1);
1520 if(!grpEnd.resourceUri)
1522 result = OC_STACK_NO_MEMORY;
1525 strncpy(grpEnd.resourceUri, requiredUri, (uriLen + 1));
1527 caResult = CASendRequestToAll(&grpEnd, &requestInfo);
1531 caResult = CACreateRemoteEndpoint(newUri, caConType, &endpoint);
1533 if (caResult != CA_STATUS_OK)
1535 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1539 caResult = CASendRequest(endpoint, &requestInfo);
1542 if (caResult != CA_STATUS_OK)
1544 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1548 if((result = AddClientCB(&clientCB, cbData, &token, &resHandle, method,
1549 requestUri, resourceType)) != OC_STACK_OK)
1551 result = OC_STACK_NO_MEMORY;
1557 *handle = resHandle;
1561 if(newUri != requiredUri)
1565 if (result != OC_STACK_OK)
1567 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1568 FindAndDeleteClientCB(clientCB);
1571 CADestroyRemoteEndpoint(endpoint);
1572 OCFree(grpEnd.resourceUri);
1574 if (hdrOptionMemAlloc)
1576 OCFree(requestData.options);
1582 * Cancel a request associated with a specific @ref OCDoResource invocation.
1584 * @param handle - Used to identify a specific OCDoResource invocation.
1585 * @param qos - used to specify Quality of Service (read below for more info)
1586 * @param options- used to specify vendor specific header options when sending
1587 * explicit observe cancellation
1588 * @param numOptions- Number of header options to be included
1591 * OC_STACK_OK - No errors; Success
1592 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1594 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1598 * This ftn is implemented one of two ways in the case of observation:
1600 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1601 * Remove the callback associated on client side.
1602 * When the next notification comes in from server,
1603 * reply with RESET message to server.
1604 * Keep in mind that the server will react to RESET only
1605 * if the last notification was sent ans CON
1607 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1608 * and it is associated with an observe request
1609 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1610 * Send CON Observe request to server with
1611 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1612 * Remove the callback associated on client side.
1614 OCStackResult ret = OC_STACK_OK;
1615 CARemoteEndpoint_t* endpoint = NULL;
1616 CAResult_t caResult;
1617 CAInfo_t requestData;
1618 CARequestInfo_t requestInfo;
1619 // Track if memory is allocated for additional header options
1620 uint8_t hdrOptionMemAlloc = 0;
1623 return OC_STACK_INVALID_PARAM;
1626 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1628 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1631 switch (clientCB->method)
1633 case OC_REST_OBSERVE:
1634 case OC_REST_OBSERVE_ALL:
1635 //TODO-CA : Why CA_WIFI alone?
1636 caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri, CA_WIFI,
1638 if (caResult != CA_STATUS_OK)
1640 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1641 return OC_STACK_ERROR;
1644 memset(&requestData, 0, sizeof(CAInfo_t));
1645 requestData.type = qualityOfServiceToMessageType(qos);
1646 requestData.token = clientCB->token;
1647 if (CreateObserveHeaderOption (&(requestData.options),
1648 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
1650 return OC_STACK_ERROR;
1652 hdrOptionMemAlloc = 1;
1653 requestData.numOptions = numOptions + 1;
1654 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1655 requestInfo.method = CA_GET;
1656 requestInfo.info = requestData;
1658 caResult = CASendRequest(endpoint, &requestInfo);
1659 if (caResult != CA_STATUS_OK)
1661 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1663 if(caResult == CA_STATUS_OK)
1667 #ifdef WITH_PRESENCE
1668 case OC_REST_PRESENCE:
1669 FindAndDeleteClientCB(clientCB);
1673 return OC_STACK_INVALID_METHOD;
1676 CADestroyRemoteEndpoint(endpoint);
1677 if (hdrOptionMemAlloc)
1679 OCFree(requestData.options);
1685 #ifdef WITH_PRESENCE
1686 OCStackResult OCProcessPresence()
1688 OCStackResult result = OC_STACK_OK;
1689 uint8_t ipAddr[4] = { 0 };
1692 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1693 ClientCB* cbNode = NULL;
1695 OCClientResponse clientResponse;
1696 OCResponse * response = NULL;
1697 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1699 LL_FOREACH(cbList, cbNode) {
1700 if(OC_REST_PRESENCE == cbNode->method)
1702 if(cbNode->presence)
1704 uint32_t now = GetTime(0);
1705 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d",
1706 cbNode->presence->TTLlevel);
1707 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1710 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1715 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1716 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1717 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1720 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1722 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1723 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1725 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1728 clientResponse.sequenceNumber = 0;
1729 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
1730 clientResponse.addr = (OCDevAddr *) &dst;
1731 clientResponse.resJSONPayload = NULL;
1733 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1734 &cbNode->token, &clientResponse, NULL);
1735 if(result != OC_STACK_OK)
1740 // Increment the TTLLevel (going to a next state), so we don't keep
1741 // sending presence notification to client.
1742 cbNode->presence->TTLlevel++;
1743 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1744 cbNode->presence->TTLlevel);
1748 result = OC_STACK_INVALID_IP;
1752 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
1753 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1755 FindAndDeleteClientCB(cbNode);
1759 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1761 CAResult_t caResult;
1762 CARemoteEndpoint_t* endpoint = NULL;
1763 CAInfo_t requestData;
1764 CARequestInfo_t requestInfo;
1766 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
1768 //TODO-CA : Why CA_WIFI alone?
1769 caResult = CACreateRemoteEndpoint((char *)cbNode->requestUri, CA_WIFI,
1772 if (caResult != CA_STATUS_OK)
1774 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1778 memset(&requestData, 0, sizeof(CAInfo_t));
1779 requestData.type = CA_MSG_NONCONFIRM;
1780 requestData.token = cbNode->token;
1782 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1783 requestInfo.method = CA_GET;
1784 requestInfo.info = requestData;
1786 caResult = CASendRequest(endpoint, &requestInfo);
1788 if (caResult != CA_STATUS_OK)
1790 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1794 cbNode->presence->TTLlevel++;
1795 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1796 cbNode->presence->TTLlevel);
1802 if (result != OC_STACK_OK)
1804 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
1808 #endif // WITH_PRESENCE
1811 * Called in main loop of OC client or server. Allows low-level processing of
1815 * OC_STACK_OK - no errors
1816 * OC_STACK_ERROR - stack process error
1818 OCStackResult OCProcess()
1820 #ifdef WITH_PRESENCE
1821 OCProcessPresence();
1823 CAHandleRequestResponse();
1828 #ifdef WITH_PRESENCE
1830 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
1831 * presence notifications to clients via multicast. Once this API has been called with a success,
1832 * clients may query for this server's presence and this server's stack will respond via multicast.
1834 * Server can call this function when it comes online for the first time, or when it comes back
1835 * online from offline mode, or when it re enters network.
1837 * @param ttl - Time To Live in seconds
1838 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
1841 * OC_STACK_OK - No errors; Success
1843 OCStackResult OCStartPresence(const uint32_t ttl)
1845 OCChangeResourceProperty(
1846 &(((OCResource *)presenceResource.handle)->resourceProperties),
1851 presenceResource.presenceTTL = ttl;
1854 if(OC_PRESENCE_UNINITIALIZED == presenceState)
1856 presenceState = OC_PRESENCE_INITIALIZED;
1858 CAAddress_t addressInfo;
1859 strncpy(addressInfo.IP.ipAddress, "224.0.1.187", CA_IPADDR_SIZE);
1860 addressInfo.IP.port = 5683;
1862 //TODO make sure there is no memory leak here since another copy
1863 //of token is being created inside AddObserver
1864 CAToken_t caToken = NULL;
1865 CAResult_t caResult = CAGenerateToken(&caToken);
1866 if (caResult != CA_STATUS_OK)
1868 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1869 CADestroyToken(caToken);
1870 return OC_STACK_ERROR;
1873 CAConnectivityType_t connType;
1874 OCToCAConnectivityType(OC_ALL, &connType );
1875 AddObserver(OC_PRESENCE_URI, NULL, 0, &caToken,
1876 (OCResource *)presenceResource.handle, OC_LOW_QOS,
1877 &addressInfo, connType);
1880 // Each time OCStartPresence is called
1881 // a different random 32-bit integer number is used
1882 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1884 return SendPresenceNotification(NULL);
1888 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
1889 * presence notifications to clients via multicast. Once this API has been called with a success,
1890 * this server's stack will not respond to clients querying for this server's presence.
1892 * Server can call this function when it is terminating, going offline, or when going
1893 * away from network.
1896 * OC_STACK_OK - No errors; Success
1898 OCStackResult OCStopPresence()
1900 OCStackResult result = OC_STACK_ERROR;
1902 if(presenceResource.handle)
1904 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1907 // make resource inactive
1908 result = OCChangeResourceProperty(
1909 &(((OCResource *) presenceResource.handle)->resourceProperties),
1912 if(result != OC_STACK_OK)
1915 PCF("Changing the presence resource properties to ACTIVE not successful"));
1919 return SendStopNotification();
1924 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
1926 defaultDeviceHandler = entityHandler;
1931 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
1933 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
1935 if(myStackMode == OC_CLIENT)
1937 return OC_STACK_ERROR;
1940 return SaveDeviceInfo(deviceInfo);
1946 * @param handle - pointer to handle to newly created resource. Set by ocstack.
1947 * Used to refer to resource
1948 * @param resourceTypeName - name of resource type. Example: "core.led"
1949 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1950 * @param uri - URI of the resource. Example: "/a/led"
1951 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1952 * NULL for default entity handler
1953 * @param resourceProperties - properties supported by resource.
1954 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
1957 * OC_STACK_OK - no errors
1958 * OC_STACK_ERROR - stack process error
1960 OCStackResult OCCreateResource(OCResourceHandle *handle,
1961 const char *resourceTypeName,
1962 const char *resourceInterfaceName,
1963 const char *uri, OCEntityHandler entityHandler,
1964 uint8_t resourceProperties)
1967 OCResource *pointer = NULL;
1970 OCStackResult result = OC_STACK_ERROR;
1972 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
1974 if(myStackMode == OC_CLIENT)
1978 // Validate parameters
1979 if(!uri || (strlen(uri) == 0))
1981 OC_LOG(ERROR, TAG, PCF("URI is invalid"));
1982 return OC_STACK_INVALID_URI;
1984 // Is it presented during resource discovery?
1985 if (!handle || !resourceTypeName)
1987 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
1988 return OC_STACK_INVALID_PARAM;
1991 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
1992 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
1995 // Make sure resourceProperties bitmask has allowed properties specified
1996 if (resourceProperties
1997 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
1998 OC_LOG(ERROR, TAG, PCF("Invalid property"));
1999 return OC_STACK_INVALID_PARAM;
2002 // If the headResource is NULL, then no resources have been created...
2003 pointer = headResource;
2006 // At least one resources is in the resource list, so we need to search for
2007 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2010 if (strcmp(uri, pointer->uri) == 0)
2012 OC_LOG(ERROR, TAG, PCF("URI already in use"));
2013 return OC_STACK_INVALID_PARAM;
2015 pointer = pointer->next;
2018 // Create the pointer and insert it into the resource list
2019 pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
2024 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2026 insertResource(pointer);
2029 size = strlen(uri) + 1;
2030 str = (char *) OCMalloc(size);
2035 strncpy(str, uri, size);
2038 // Set properties. Set OC_ACTIVE
2039 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2042 // Add the resourcetype to the resource
2043 result = BindResourceTypeToResource(pointer, resourceTypeName);
2044 if (result != OC_STACK_OK)
2046 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
2050 // Add the resourceinterface to the resource
2051 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2052 if (result != OC_STACK_OK)
2054 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
2058 // If an entity handler has been passed, attach it to the newly created
2059 // resource. Otherwise, set the default entity handler.
2062 pointer->entityHandler = entityHandler;
2066 pointer->entityHandler = defaultResourceEHandler;
2070 result = OC_STACK_OK;
2072 #ifdef WITH_PRESENCE
2073 if(presenceResource.handle)
2075 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2076 SendPresenceNotification(pointer->rsrcType);
2080 if (result != OC_STACK_OK)
2082 // Deep delete of resource and other dynamic elements that it contains
2083 deleteResource(pointer);
2092 * Create a resource. with host ip address for remote resource
2094 * @param handle - pointer to handle to newly created resource. Set by ocstack.
2095 * Used to refer to resource
2096 * @param resourceTypeName - name of resource type. Example: "core.led"
2097 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
2098 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
2099 * @param uri - URI of the resource. Example: "/a/led"
2100 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2101 * NULL for default entity handler
2102 * @param resourceProperties - properties supported by resource.
2103 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
2106 * OC_STACK_OK - no errors
2107 * OC_STACK_ERROR - stack process error
2110 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
2111 const char *resourceTypeName,
2112 const char *resourceInterfaceName,
2115 OCEntityHandler entityHandler,
2116 uint8_t resourceProperties)
2120 OCStackResult result = OC_STACK_ERROR;
2122 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
2123 uri, entityHandler, resourceProperties);
2125 if (result != OC_STACK_ERROR)
2128 size = strlen(host) + 1;
2129 str = (char *) OCMalloc(size);
2132 return OC_STACK_ERROR;
2134 strncpy(str, host, size);
2135 ((OCResource *) *handle)->host = str;
2142 * Add a resource to a collection resource.
2144 * @param collectionHandle - handle to the collection resource
2145 * @param resourceHandle - handle to resource to be added to the collection resource
2148 * OC_STACK_OK - no errors
2149 * OC_STACK_ERROR - stack process error
2150 * OC_STACK_INVALID_PARAM - invalid collectionhandle
2152 OCStackResult OCBindResource(
2153 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2155 OCResource *resource;
2158 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2160 // Validate parameters
2161 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2162 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2163 // Container cannot contain itself
2164 if (collectionHandle == resourceHandle)
2166 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2167 return OC_STACK_INVALID_PARAM;
2170 // Use the handle to find the resource in the resource linked list
2171 resource = findResource((OCResource *) collectionHandle);
2174 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2175 return OC_STACK_INVALID_PARAM;
2178 // Look for an open slot to add add the child resource.
2179 // If found, add it and return success
2180 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2182 if (!resource->rsrcResources[i])
2184 resource->rsrcResources[i] = (OCResource *) resourceHandle;
2185 OC_LOG(INFO, TAG, PCF("resource bound"));
2190 #ifdef WITH_PRESENCE
2191 if(presenceResource.handle)
2193 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2194 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2198 // Unable to add resourceHandle, so return error
2199 return OC_STACK_ERROR;
2203 * Remove a resource from a collection resource.
2205 * @param collectionHandle - handle to the collection resource
2206 * @param resourceHandle - handle to resource to be added to the collection resource
2209 * OC_STACK_OK - no errors
2210 * OC_STACK_ERROR - stack process error
2211 * OC_STACK_INVALID_PARAM - invalid collectionHandle
2213 OCStackResult OCUnBindResource(
2214 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2215 OCResource *resource;
2218 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2220 // Validate parameters
2221 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2222 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2223 // Container cannot contain itself
2224 if (collectionHandle == resourceHandle) {
2225 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2226 return OC_STACK_INVALID_PARAM;
2229 // Use the handle to find the resource in the resource linked list
2230 resource = findResource((OCResource *) collectionHandle);
2232 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2233 return OC_STACK_INVALID_PARAM;
2236 // Look for an open slot to add add the child resource.
2237 // If found, add it and return success
2238 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2239 if (resourceHandle == resource->rsrcResources[i]) {
2240 resource->rsrcResources[i] = (OCResource *) NULL;
2241 OC_LOG(INFO, TAG, PCF("resource unbound"));
2243 // Send notification when resource is unbounded successfully.
2244 #ifdef WITH_PRESENCE
2245 if(presenceResource.handle)
2247 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2248 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2256 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2258 // Unable to add resourceHandle, so return error
2259 return OC_STACK_ERROR;
2262 OCStackResult BindResourceTypeToResource(OCResource* resource,
2263 const char *resourceTypeName)
2265 OCResourceType *pointer = NULL;
2268 OCStackResult result = OC_STACK_ERROR;
2270 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
2272 // Validate parameters
2273 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2274 // TODO: Does resource attribute resentation really have to be maintained in stack?
2275 // Is it presented during resource discovery?
2277 //TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
2279 // Create the resourcetype and insert it into the resource list
2280 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
2285 // Set the resourceTypeName
2286 size = strlen(resourceTypeName) + 1;
2287 str = (char *) OCMalloc(size);
2291 strncpy(str, resourceTypeName, size);
2292 pointer->resourcetypename = str;
2294 insertResourceType(resource, pointer);
2295 result = OC_STACK_OK;
2297 exit: if (result != OC_STACK_OK) {
2305 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2306 const char *resourceInterfaceName)
2308 OCResourceInterface *pointer = NULL;
2311 OCStackResult result = OC_STACK_ERROR;
2313 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
2315 // Validate parameters
2316 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2318 //TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
2320 // Create the resourceinterface and insert it into the resource list
2321 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
2326 // Set the resourceinterface name
2327 size = strlen(resourceInterfaceName) + 1;
2328 str = (char *) OCMalloc(size);
2332 strncpy(str, resourceInterfaceName, size);
2333 pointer->name = str;
2335 // Bind the resourceinterface to the resource
2336 insertResourceInterface(resource, pointer);
2338 result = OC_STACK_OK;
2340 exit: if (result != OC_STACK_OK) {
2349 * Bind a resourcetype to a resource.
2351 * @param handle - handle to the resource
2352 * @param resourceTypeName - name of resource type. Example: "core.led"
2355 * OC_STACK_OK - no errors
2356 * OC_STACK_ERROR - stack process error
2358 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2359 const char *resourceTypeName) {
2361 OCStackResult result = OC_STACK_ERROR;
2362 OCResource *resource;
2364 // Make sure resource exists
2365 resource = findResource((OCResource *) handle);
2367 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2368 return OC_STACK_ERROR;
2371 // call internal function
2372 result = BindResourceTypeToResource(resource, resourceTypeName);
2374 #ifdef WITH_PRESENCE
2375 if(presenceResource.handle)
2377 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2378 SendPresenceNotification(resource->rsrcType);
2386 * Bind a resourceinterface to a resource.
2388 * @param handle - handle to the resource
2389 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
2392 * OC_STACK_OK - no errors
2393 * OC_STACK_ERROR - stack process error
2396 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2397 const char *resourceInterfaceName) {
2399 OCStackResult result = OC_STACK_ERROR;
2400 OCResource *resource;
2402 // Make sure resource exists
2403 resource = findResource((OCResource *) handle);
2405 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2406 return OC_STACK_ERROR;
2409 // call internal function
2410 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2412 #ifdef WITH_PRESENCE
2413 if(presenceResource.handle)
2415 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2416 SendPresenceNotification(resource->rsrcType);
2424 * Get the number of resources that have been created in the stack.
2426 * @param numResources - pointer to count variable
2429 * OC_STACK_OK - no errors
2430 * OC_STACK_ERROR - stack process error
2433 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
2434 OCResource *pointer = headResource;
2436 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2437 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2440 *numResources = *numResources + 1;
2441 pointer = pointer->next;
2447 * Get a resource handle by index.
2449 * @param index - index of resource, 0 to Count - 1
2452 * Resource handle - if found
2453 * NULL - if not found
2455 OCResourceHandle OCGetResourceHandle(uint8_t index) {
2456 OCResource *pointer = headResource;
2459 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2461 // Iterate through the list
2462 while ((i < index) && pointer) {
2464 pointer = pointer->next;
2466 return (OCResourceHandle) pointer;
2470 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
2473 * @param handle - handle of resource to be deleted
2476 * OC_STACK_OK - no errors
2477 * OC_STACK_ERROR - stack process error
2478 * OC_STACK_NO_RESOURCE - resource not found
2479 * OC_STACK_INVALID_PARAM - invalid param
2481 OCStackResult OCDeleteResource(OCResourceHandle handle) {
2482 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2485 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2486 return OC_STACK_INVALID_PARAM;
2489 OCResource *resource = findResource((OCResource *) handle);
2490 if (resource == NULL) {
2491 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2492 return OC_STACK_NO_RESOURCE;
2495 if (deleteResource((OCResource *) handle) == 0) {
2496 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2497 return OC_STACK_ERROR;
2504 * Get the URI of the resource specified by handle.
2506 * @param handle - handle of resource
2508 * URI string - if resource found
2509 * NULL - resource not found
2511 const char *OCGetResourceUri(OCResourceHandle handle) {
2512 OCResource *resource;
2513 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2515 resource = findResource((OCResource *) handle);
2517 return resource->uri;
2519 return (const char *) NULL;
2523 * Get the properties of the resource specified by handle.
2524 * NOTE: that after a resource is created, the OC_ACTIVE property is set
2525 * for the resource by the stack.
2527 * @param handle - handle of resource
2529 * property bitmap - if resource found
2530 * NULL - resource not found
2532 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
2533 OCResource *resource;
2534 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2536 resource = findResource((OCResource *) handle);
2538 return resource->resourceProperties;
2544 * Get the number of resource types of the resource.
2546 * @param handle - handle of resource
2547 * @param numResourceTypes - pointer to count variable
2550 * OC_STACK_OK - no errors
2551 * OC_STACK_ERROR - stack process error
2553 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2554 uint8_t *numResourceTypes) {
2555 OCResource *resource;
2556 OCResourceType *pointer;
2558 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2559 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2560 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2562 *numResourceTypes = 0;
2564 resource = findResource((OCResource *) handle);
2566 pointer = resource->rsrcType;
2568 *numResourceTypes = *numResourceTypes + 1;
2569 pointer = pointer->next;
2576 * Get name of resource type of the resource.
2578 * @param handle - handle of resource
2579 * @param index - index of resource, 0 to Count - 1
2582 * resource type name - if resource found
2583 * NULL - resource not found
2585 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
2586 OCResourceType *resourceType;
2588 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2590 resourceType = findResourceTypeAtIndex(handle, index);
2592 return resourceType->resourcetypename;
2594 return (const char *) NULL;
2600 * Get the number of resource interfaces of the resource.
2602 * @param handle - handle of resource
2603 * @param numResources - pointer to count variable
2606 * OC_STACK_OK - no errors
2607 * OC_STACK_ERROR - stack process error
2609 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2610 uint8_t *numResourceInterfaces) {
2611 OCResourceInterface *pointer;
2612 OCResource *resource;
2614 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2616 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2617 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2619 *numResourceInterfaces = 0;
2620 resource = findResource((OCResource *) handle);
2622 pointer = resource->rsrcInterface;
2624 *numResourceInterfaces = *numResourceInterfaces + 1;
2625 pointer = pointer->next;
2632 * Get name of resource interface of the resource.
2634 * @param handle - handle of resource
2635 * @param index - index of resource, 0 to Count - 1
2638 * resource interface name - if resource found
2639 * NULL - resource not found
2641 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
2642 OCResourceInterface *resourceInterface;
2644 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2646 resourceInterface = findResourceInterfaceAtIndex(handle, index);
2647 if (resourceInterface) {
2648 return resourceInterface->name;
2650 return (const char *) NULL;
2654 * Get resource handle from the collection resource by index.
2656 * @param collectionHandle - handle of collection resource
2657 * @param index - index of contained resource, 0 to Count - 1
2660 * handle to resource - if resource found
2661 * NULL - resource not found
2663 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2665 OCResource *resource;
2667 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2669 if (index >= MAX_CONTAINED_RESOURCES) {
2673 resource = findResource((OCResource *) collectionHandle);
2678 return resource->rsrcResources[index];
2682 * Bind an entity handler to the resource.
2684 * @param handle - handle to the resource that the contained resource is to be bound
2685 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2687 * OC_STACK_OK - no errors
2688 * OC_STACK_ERROR - stack process error
2690 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2691 OCEntityHandler entityHandler) {
2692 OCResource *resource;
2694 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2696 // Validate parameters
2697 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2698 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2700 // Use the handle to find the resource in the resource linked list
2701 resource = findResource((OCResource *)handle);
2703 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2704 return OC_STACK_ERROR;
2708 resource->entityHandler = entityHandler;
2710 #ifdef WITH_PRESENCE
2711 if(presenceResource.handle)
2713 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2714 SendPresenceNotification(resource->rsrcType);
2722 * Get the entity handler for a resource.
2724 * @param handle - handle of resource
2727 * entity handler - if resource found
2728 * NULL - resource not found
2730 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
2731 OCResource *resource;
2733 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2735 // Use the handle to find the resource in the resource linked list
2736 resource = findResource((OCResource *)handle);
2738 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2743 return resource->entityHandler;
2746 void incrementSequenceNumber(OCResource * resPtr)
2748 // Increment the sequence number
2749 resPtr->sequenceNum += 1;
2750 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2752 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2758 * Notify Presence subscribers that a resource has been modified
2760 * @param resourceType - Handle to the resourceType linked list of resource
2761 * that was modified.
2762 * @param qos - Quality Of Service
2765 * OC_STACK_OK - no errors
2766 * OC_STACK_ERROR - stack process error
2768 #ifdef WITH_PRESENCE
2771 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
2773 OCResource *resPtr = NULL;
2774 OCStackResult result = OC_STACK_ERROR;
2775 OCMethod method = OC_REST_PRESENCE;
2776 uint32_t maxAge = 0;
2777 resPtr = findResource((OCResource *) presenceResource.handle);
2780 return OC_STACK_NO_RESOURCE;
2783 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
2785 maxAge = presenceResource.presenceTTL;
2787 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
2794 * Send Stop Notification to Presence subscribers
2797 * OC_STACK_OK - no errors
2798 * OC_STACK_ERROR - stack process error
2802 OCStackResult SendStopNotification()
2804 OCResource *resPtr = NULL;
2805 OCStackResult result = OC_STACK_ERROR;
2806 OCMethod method = OC_REST_PRESENCE;
2807 resPtr = findResource((OCResource *) presenceResource.handle);
2810 return OC_STACK_NO_RESOURCE;
2813 // maxAge is 0. ResourceType is NULL.
2814 result = SendAllObserverNotification(method, resPtr, 0, NULL, OC_LOW_QOS);
2819 #endif // WITH_PRESENCE
2821 * Notify observers that an observed value has changed.
2823 * @param handle - handle of resource
2826 * OC_STACK_OK - no errors
2827 * OC_STACK_NO_RESOURCE - invalid resource handle
2828 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
2830 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
2832 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2834 OCResource *resPtr = NULL;
2835 OCStackResult result;
2836 OCMethod method = OC_REST_NOMETHOD;
2837 uint32_t maxAge = 0;
2839 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2840 #ifdef WITH_PRESENCE
2841 if(handle == presenceResource.handle)
2845 #endif // WITH_PRESENCE
2846 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2848 // Verify that the resource exists
2849 resPtr = findResource ((OCResource *) handle);
2852 return OC_STACK_NO_RESOURCE;
2856 //only increment in the case of regular observing (not presence)
2857 incrementSequenceNumber(resPtr);
2858 method = OC_REST_OBSERVE;
2859 maxAge = MAX_OBSERVE_AGE;
2860 #ifdef WITH_PRESENCE
2861 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
2863 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
2870 OCNotifyListOfObservers (OCResourceHandle handle,
2871 OCObservationId *obsIdList,
2872 uint8_t numberOfIds,
2873 unsigned char *notificationJSONPayload,
2874 OCQualityOfService qos)
2876 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
2878 OCResource *resPtr = NULL;
2879 //TODO: we should allow the server to define this
2880 uint32_t maxAge = MAX_OBSERVE_AGE;
2882 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2883 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
2884 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
2886 // Verify that the resource exists
2887 resPtr = findResource ((OCResource *) handle);
2888 if (NULL == resPtr || myStackMode == OC_CLIENT)
2890 return OC_STACK_NO_RESOURCE;
2894 incrementSequenceNumber(resPtr);
2896 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
2897 notificationJSONPayload, maxAge, qos));
2901 * Send a response to a request.
2902 * The response can be a regular, slow, or block (i.e. a response that
2903 * is too large to be sent in a single PDU and must span multiple transmissions)
2905 * @param response - pointer to structure that contains response parameters
2908 * OC_STACK_OK - No errors; Success
2909 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
2910 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
2911 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
2912 * persistent response buffer is necessary
2914 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
2916 OCStackResult result = OC_STACK_ERROR;
2917 OCServerRequest *serverRequest = NULL;
2919 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
2921 // Validate input parameters
2922 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
2923 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
2925 // TODO: Placeholder for creating a response entry when implementing
2926 // block transfer feature
2928 // If a response payload is present, check if block transfer is required
2929 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
2930 (const char *)ehResponse->payload, ehResponse->payloadSize))
2932 OC_LOG(INFO, TAG, PCF("Block transfer required"));
2934 // Persistent response buffer is needed for block transfer
2935 if (!ehResponse->persistentBufferFlag)
2937 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
2938 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
2940 // TODO: Placeholder for block transfer handling
2941 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
2942 // when implementing the block transfer feature
2947 // Get pointer to request info
2948 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
2951 result = serverRequest->ehResponseHandler(ehResponse);
2958 * Cancel a response. Applies to a block response
2960 * @param responseHandle - response handle set by stack in OCServerResponse after
2961 * OCDoResponse is called
2964 * OC_STACK_OK - No errors; Success
2965 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
2967 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
2969 OCStackResult result = OC_STACK_NOTIMPL;
2971 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
2973 // TODO: validate response handle
2978 //-----------------------------------------------------------------------------
2979 // Private internal function definitions
2980 //-----------------------------------------------------------------------------
2982 * Generate handle of OCDoResource invocation for callback management.
2984 static OCDoHandle GenerateInvocationHandle()
2986 OCDoHandle handle = NULL;
2987 // Generate token here, it will be deleted when the transaction is deleted
2988 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
2991 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
2996 #ifdef WITH_PRESENCE
2997 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
2998 OCResourceProperty resourceProperties, uint8_t enable)
3000 if (resourceProperties
3001 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
3002 OC_LOG(ERROR, TAG, PCF("Invalid property"));
3003 return OC_STACK_INVALID_PARAM;
3007 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3011 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3018 * Initialize resource data structures, variables, etc.
3020 OCStackResult initResources() {
3021 OCStackResult result = OC_STACK_OK;
3022 // Init application resource vars
3023 headResource = NULL;
3024 tailResource = NULL;
3025 // Init Virtual Resources
3026 #ifdef WITH_PRESENCE
3027 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
3028 //presenceResource.token = OCGenerateCoAPToken();
3029 result = OCCreateResource(&presenceResource.handle,
3030 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3035 //make resource inactive
3036 result = OCChangeResourceProperty(
3037 &(((OCResource *) presenceResource.handle)->resourceProperties),
3044 * Add a resource to the end of the linked list of resources.
3046 * @param resource - resource to be added
3048 void insertResource(OCResource *resource)
3052 // First resource. Head and tail are the same.
3053 headResource = resource;
3054 tailResource = resource;
3058 tailResource->next = resource;
3059 tailResource = resource;
3061 resource->next = NULL;
3065 * Find a resource in the linked list of resources.
3067 * @param resource - resource to be found
3069 * NULL - resource not found
3070 * pointer to resource - pointer to resource that was found in the linked list
3072 OCResource *findResource(OCResource *resource)
3074 OCResource *pointer = headResource;
3078 if (pointer == resource)
3082 pointer = pointer->next;
3087 void deleteAllResources()
3089 OCResource *pointer = headResource;
3094 temp = pointer->next;
3095 #ifdef WITH_PRESENCE
3096 if(pointer != (OCResource *) presenceResource.handle)
3098 #endif // WITH_PRESENCE
3099 deleteResource(pointer);
3100 #ifdef WITH_PRESENCE
3102 #endif // WITH_PRESENCE
3106 #ifdef WITH_PRESENCE
3107 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3108 // presence notification attributed to their deletion to be processed.
3109 deleteResource((OCResource *) presenceResource.handle);
3110 #endif // WITH_PRESENCE
3114 * Delete the resource from the linked list.
3116 * @param resource - resource to be deleted
3121 int deleteResource(OCResource *resource)
3123 OCResource *prev = NULL;
3126 temp = headResource;
3129 if (temp == resource)
3131 // Invalidate all Resource Properties.
3132 resource->resourceProperties = (OCResourceProperty) 0;
3133 #ifdef WITH_PRESENCE
3134 if(resource != (OCResource *) presenceResource.handle)
3136 #endif // WITH_PRESENCE
3137 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3138 #ifdef WITH_PRESENCE
3141 if(presenceResource.handle)
3143 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3144 if(resource != (OCResource *) presenceResource.handle)
3146 SendPresenceNotification(resource->rsrcType);
3150 SendPresenceNotification(NULL);
3155 // Only resource in list.
3156 if (temp == headResource && temp == tailResource)
3158 headResource = NULL;
3159 tailResource = NULL;
3162 else if (temp == headResource)
3164 headResource = temp->next;
3167 else if (temp == tailResource)
3169 tailResource = prev;
3170 tailResource->next = NULL;
3174 prev->next = temp->next;
3177 deleteResourceElements(temp);
3192 * Delete all of the dynamically allocated elements that were created for the resource.
3194 * @param resource - specified resource
3196 void deleteResourceElements(OCResource *resource)
3203 OCFree(resource->uri);
3205 // Delete resourcetype linked list
3206 deleteResourceType(resource->rsrcType);
3208 // Delete resourceinterface linked list
3209 deleteResourceInterface(resource->rsrcInterface);
3213 * Delete all of the dynamically allocated elements that were created for the resource type.
3215 * @param resourceType - specified resource type
3217 void deleteResourceType(OCResourceType *resourceType)
3219 OCResourceType *pointer = resourceType;
3220 OCResourceType *next;
3224 next = pointer->next;
3225 OCFree(pointer->resourcetypename);
3232 * Delete all of the dynamically allocated elements that were created for the resource interface.
3234 * @param resourceInterface - specified resource interface
3236 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
3237 OCResourceInterface *pointer = resourceInterface;
3238 OCResourceInterface *next;
3242 next = pointer->next;
3243 OCFree(pointer->name);
3250 * Insert a resource type into a resource's resource type linked list.
3252 * @param resource - resource where resource type is to be inserted
3253 * @param resourceType - resource type to be inserted
3255 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
3256 OCResourceType *pointer;
3258 if (resource && !resource->rsrcType)
3260 resource->rsrcType = resourceType;
3266 pointer = resource->rsrcType;
3270 pointer = resourceType;
3272 while (pointer->next) {
3273 pointer = pointer->next;
3275 pointer->next = resourceType;
3277 resourceType->next = NULL;
3281 * Get a resource type at the specified index within a resource.
3283 * @param handle - handle of resource
3284 * @param index - index of resource type
3287 * resourcetype - if found
3290 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
3291 OCResource *resource;
3292 OCResourceType *pointer;
3295 // Find the specified resource
3296 resource = findResource((OCResource *) handle);
3302 // Make sure a resource has a resourcetype
3303 if (!resource->rsrcType)
3308 // Iterate through the list
3309 pointer = resource->rsrcType;
3311 while ((i < index) && pointer)
3314 pointer = pointer->next;
3320 * Finds a resource type in an OCResourceType link-list.
3322 * @param resourceTypeList - the link-list to be searched through
3323 * @param resourceTypeName - the key to search for
3326 * resourceType that matches the key (ie. resourceTypeName)
3327 * NULL - either an invalid parameter or this function was unable to find the key.
3329 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3331 if(resourceTypeList && resourceTypeName)
3333 OCResourceType * rtPointer = resourceTypeList;
3334 while(resourceTypeName && rtPointer)
3336 if(rtPointer->resourcetypename &&
3337 strcmp(resourceTypeName, (const char *)
3338 (rtPointer->resourcetypename)) == 0)
3342 rtPointer = rtPointer->next;
3349 * Insert a resource interface into a resource's resource interface linked list.
3351 * @param resource - resource where resource interface is to be inserted
3352 * @param resourceInterface - resource interface to be inserted
3354 void insertResourceInterface(OCResource *resource,
3355 OCResourceInterface *resourceInterface)
3357 OCResourceInterface *pointer;
3359 if (!resource->rsrcInterface)
3361 resource->rsrcInterface = resourceInterface;
3365 pointer = resource->rsrcInterface;
3366 while (pointer->next)
3368 pointer = pointer->next;
3370 pointer->next = resourceInterface;
3372 resourceInterface->next = NULL;
3376 * Get a resource interface at the specified index within a resource.
3378 * @param handle - handle of resource
3379 * @param index - index of resource interface
3382 * resourceinterface - if found
3385 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3387 OCResource *resource;
3388 OCResourceInterface *pointer;
3391 // Find the specified resource
3392 resource = findResource((OCResource *) handle);
3397 // Make sure a resource has a resourceinterface
3398 if (!resource->rsrcInterface) {
3402 // Iterate through the list
3403 pointer = resource->rsrcInterface;
3405 while ((i < index) && pointer) {
3407 pointer = pointer->next;
3413 * Determine if a request/response must be sent in a block transfer because it is too large to be
3414 * sent in a single PDU. This function can be used for either a request or a response
3416 * @param request - NULL or pointer to request
3417 * @param response - NULL or pointer to response
3418 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
3419 * the length of the request/response
3422 * 0 - packet transfer NOT required (i.e. normal request/response)
3423 * 1 - packet transfer required (i.e. block transfer needed)
3425 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
3429 // Determine if we are checking a request or a response
3432 // If size is greater than 0, use it for the request size value, otherwise
3433 // assume request is null terminated and use strlen for size value
3434 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
3441 // If size is greater than 0, use it for the response size value, otherwise
3442 // assume response is null terminated and use strlen for size value
3443 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3452 * Retrieves a resource type based upon a query ontains only just one
3453 * resource attribute (and that has to be of type "rt").
3455 * @remark This API malloc's memory for the resource type. Do not malloc resourceType
3456 * before passing in.
3458 * @param query - The quert part of the URI
3459 * @param resourceType - The resource type to be populated; pass by reference.
3462 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
3463 * OC_STACK_OK - Success
3465 OCStackResult getResourceType(const char * query, unsigned char** resourceType)
3469 return OC_STACK_INVALID_PARAM;
3472 OCStackResult result = OC_STACK_ERROR;
3474 if(strncmp(query, "rt=", 3) == 0)
3476 *resourceType = (unsigned char *) OCMalloc(strlen(query)-3);
3479 result = OC_STACK_NO_MEMORY;
3482 strcpy((char *)*resourceType, ((const char *)&query[3]));
3483 result = OC_STACK_OK;
3489 OCStackResult getQueryFromUri(const char * uri, unsigned char** query, char ** newURI)
3493 return OC_STACK_INVALID_URI;
3495 if(!query || !newURI)
3497 return OC_STACK_INVALID_PARAM;
3499 char * leftToken = NULL;
3500 char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3505 strcpy(tempURI, uri);
3507 leftToken = strtok_r((char *)tempURI, "?", &strTokPtr);
3509 //TODO-CA: This could be simplified. Clean up required.
3510 while(leftToken != NULL)
3512 if(strncmp(leftToken, "rt=", 3) == 0 || strncmp(leftToken, "if=", 3) == 0)
3514 *query = (unsigned char *) OCMalloc(strlen(leftToken) + 1);
3520 strcpy((char *)*query, ((const char *)&leftToken[0]));
3523 leftToken = strtok_r(NULL, "?", &strTokPtr);
3531 return OC_STACK_NO_MEMORY;
3534 const ServerID OCGetServerInstanceID(void)
3536 static bool generated = false;
3537 static ServerID sid;
3544 sid = OCGetRandom();
3549 const char* OCGetServerInstanceIDString(void)
3551 // max printed length of a base 10
3552 // uint32 is 10 characters, so 11 includes null.
3553 // This will change as the representation gets switched
3555 static char buffer[11];
3556 int n = sprintf(buffer, "%u", OCGetServerInstanceID());
3565 /// Retrieve the IPv4 address embedded inside OCDev address data structure
3566 int32_t OCDevAddrToIPv4Addr(OCDevAddr *ipAddr, uint8_t *a, uint8_t *b,
3567 uint8_t *c, uint8_t *d )
3569 if ( !ipAddr || !a || !b || !c || !d ) {
3570 OC_LOG(FATAL, TAG, "Invalid argument");
3571 return OC_STACK_INVALID_PARAM;
3574 *a = ipAddr->addr[0];
3575 *b = ipAddr->addr[1];
3576 *c = ipAddr->addr[2];
3577 *d = ipAddr->addr[3];
3583 /// Retrieve the IPv4 address embedded inside OCDev address data structure
3584 int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port)
3586 if ( !ipAddr || !port ) {
3587 OC_LOG(FATAL, TAG, "Invalid argument");
3588 return OC_STACK_INVALID_PARAM;
3591 *port = *((uint16_t*)&ipAddr->addr[4]);
3597 * Attempts to initialize every network interface that the CA Layer might have compiled in.
3599 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
3600 * return something other than @ref CA_STATUS_OK, then this function fails.
3603 * CA_STATUS_OK - Success
3604 * CA_NOT_SUPPORTED or CA_STATUS_FAILED - None of the transports successfully initialized.
3606 CAResult_t OCSelectNetwork()
3608 CAResult_t retResult = CA_STATUS_FAILED;
3609 CAResult_t caResult = CA_STATUS_OK;
3611 CAConnectivityType_t connTypes[] = {
3616 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
3618 for(int i = 0; i<numConnTypes; i++)
3620 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
3621 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
3623 caResult = CASelectNetwork(connTypes[i]);
3624 if(caResult == CA_STATUS_OK)
3626 retResult = CA_STATUS_OK;
3631 if(retResult != CA_STATUS_OK)
3633 return caResult; // Returns error of appropriate transport that failed fatally.
3640 * Takes a @ref CAResult_t and converts it to a similar or equivalent @ref OCStackResult value.
3642 * @return @ref OCStackResult - The equivalent or similar result code to the in-param caResult.
3644 OCStackResult CAResultToOCResult(CAResult_t caResult)
3650 case CA_STATUS_INVALID_PARAM:
3651 return OC_STACK_INVALID_PARAM;
3652 case CA_ADAPTER_NOT_ENABLED:
3653 return OC_STACK_ADAPTER_NOT_ENABLED;
3654 case CA_SERVER_STARTED_ALREADY:
3656 case CA_SERVER_NOT_STARTED:
3657 return OC_STACK_ERROR;
3658 case CA_DESTINATION_NOT_REACHABLE:
3659 return OC_STACK_COMM_ERROR;
3660 case CA_SOCKET_OPERATION_FAILED:
3661 return OC_STACK_COMM_ERROR;
3662 case CA_SEND_FAILED:
3663 return OC_STACK_COMM_ERROR;
3664 case CA_RECEVIE_FAILED:
3665 return OC_STACK_COMM_ERROR;
3666 case CA_MEMORY_ALLOC_FAILED:
3667 return OC_STACK_NO_MEMORY;
3668 case CA_REQUEST_TIMEOUT:
3669 return OC_STACK_TIMEOUT;
3670 case CA_DESTINATION_DISCONNECTED:
3671 return OC_STACK_COMM_ERROR;
3672 case CA_STATUS_FAILED:
3673 return OC_STACK_ERROR;
3674 case CA_NOT_SUPPORTED:
3675 return OC_STACK_NOTIMPL;
3677 return OC_STACK_ERROR;