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};
81 static OCMode myStackMode;
82 OCDeviceEntityHandler defaultDeviceHandler;
83 OCStackResult getQueryFromUri(const char * uri, 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 /// This method is used to create the IPv4 dev_addr structure.
110 /// TODO: Remove in future. Temporary helper function.
111 /// Builds a socket interface address using IP address and port number
112 static OCStackResult OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d,
113 uint16_t port, OCDevAddr *ipAddr)
116 OC_LOG(FATAL, TAG, PCF("Invalid argument"));
117 return OC_STACK_INVALID_PARAM;
124 ipAddr->addr[4] = (uint8_t)port;
125 ipAddr->addr[5] = (uint8_t)(port >> 8);
130 //-----------------------------------------------------------------------------
131 // Internal API function
132 //-----------------------------------------------------------------------------
134 // This internal function is called to update the stack with the status of
135 // observers and communication failures
136 OCStackResult OCStackFeedBack(CAToken_t * token, uint8_t status)
138 OCStackResult result = OC_STACK_ERROR;
139 ResourceObserver * observer = NULL;
140 OCEntityHandlerRequest ehRequest = {};
144 case OC_OBSERVER_NOT_INTERESTED:
145 OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
146 observer = GetObserverUsingToken (token);
149 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
150 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
151 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
152 if(result != OC_STACK_OK)
156 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
158 //observer is not observing anymore
159 result = DeleteObserverUsingToken (token);
160 if(result == OC_STACK_OK)
162 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
166 result = OC_STACK_OK;
167 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
170 case OC_OBSERVER_STILL_INTERESTED:
171 //observer is still interested
172 OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
173 notifications, reset the failedCount"));
174 observer = GetObserverUsingToken (token);
177 observer->forceHighQos = 0;
178 observer->failedCommCount = 0;
179 result = OC_STACK_OK;
183 result = OC_STACK_OBSERVER_NOT_FOUND;
186 case OC_OBSERVER_FAILED_COMM:
187 //observer is not reachable
188 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
189 observer = GetObserverUsingToken (token);
192 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
194 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
195 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
196 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
197 if(result != OC_STACK_OK)
199 return OC_STACK_ERROR;
201 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
202 //observer is unreachable
203 result = DeleteObserverUsingToken (token);
204 if(result == OC_STACK_OK)
206 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
210 result = OC_STACK_OK;
211 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
216 observer->failedCommCount++;
217 result = OC_STACK_CONTINUE;
219 observer->forceHighQos = 1;
220 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
224 OC_LOG(ERROR, TAG, PCF("Unknown status"));
225 result = OC_STACK_ERROR;
231 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
233 OCStackResult ret = OC_STACK_ERROR;
241 ret = OC_STACK_RESOURCE_CREATED;
244 ret = OC_STACK_RESOURCE_DELETED;
247 ret = OC_STACK_INVALID_QUERY;
250 ret = OC_STACK_INVALID_OPTION;
253 ret = OC_STACK_NO_RESOURCE;
261 OCStackResult OCToCAConnectivityType(OCConnectivityType ocConType, CAConnectivityType_t* caConType)
263 OCStackResult ret = OC_STACK_OK;
268 *caConType = CA_ETHERNET;
271 *caConType = CA_WIFI;
280 // Currently OC_ALL represents WIFI and ETHERNET
281 // Add other connectivity types as they are enabled in future
282 *caConType = (CAConnectivityType_t) (CA_WIFI|CA_ETHERNET);
285 ret = OC_STACK_INVALID_PARAM;
291 OCStackResult CAToOCConnectivityType(CAConnectivityType_t caConType, OCConnectivityType *ocConType)
293 OCStackResult ret = OC_STACK_OK;
298 *ocConType = OC_ETHERNET;
301 *ocConType = OC_WIFI;
310 ret = OC_STACK_INVALID_PARAM;
316 // update response.addr appropriately from endPoint.addressInfo
317 OCStackResult UpdateResponseAddr(OCDevAddr *address, const CARemoteEndpoint_t* endPoint)
319 OCStackResult ret = OC_STACK_ERROR;
321 char * savePtr = NULL;
322 char * cpAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
325 ret = OC_STACK_NO_MEMORY;
328 memcpy(cpAddress, endPoint->addressInfo.IP.ipAddress,
329 strlen(endPoint->addressInfo.IP.ipAddress) + 1);
331 // Grabs the first three numbers from the IPv4 address and replaces dots
332 for(int i=0; i<4; i++)
334 tok = strtok_r(i==0 ? cpAddress : NULL, ".", &savePtr);
338 ret = OC_STACK_ERROR;
341 address->addr[i] = atoi(tok);
344 memcpy(&address->addr[4], &endPoint->addressInfo.IP.port, sizeof(uint16_t));
351 // Note: Caller should invoke OCFree after done with resType pointer
352 void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge, char** resType)
355 char * savePtr = NULL;
356 // The format of the payload is {"oc":[%u:%u:%s]}
357 // %u : sequence number,
359 // %s : Resource Type (Optional)
361 if (!payload || !seqNum || !maxAge || !resType)
365 tok = strtok_r(payload, "[:]}", &savePtr);
366 payload[strlen(payload)] = ':';
368 //Retrieve sequence number
369 tok = strtok_r(NULL, "[:]}", &savePtr);
374 payload[strlen((char *)payload)] = ':';
375 *seqNum = (uint32_t) atoi(tok);
378 tok = strtok_r(NULL, "[:]}", &savePtr);
383 *maxAge = (uint32_t) atoi(tok);
385 //Retrieve ResourceType
386 tok = strtok_r(NULL, "[:]}",&savePtr);
392 *resType = (char *)OCMalloc(strlen(tok) + 1);
397 payload[strlen((char *)payload)] = ':';
398 strcpy(*resType, tok);
399 OC_LOG_V(DEBUG, TAG, "resourceTypeName %s", *resType);
401 payload[strlen((char *)payload)] = ']';
404 OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
405 const CAResponseInfo_t* responseInfo)
407 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
408 ClientCB * cbNode = NULL;
409 char *resourceTypeName = NULL;
410 OCClientResponse response = {};
411 OCDevAddr address = {};
412 OCStackResult result = OC_STACK_ERROR;
413 uint32_t lowerBound = 0;
414 uint32_t higherBound = 0;
417 char *fullUri = NULL;
418 char *ipAddress = NULL;
419 int presenceSubscribe = 0;
420 int multicastPresenceSubscribe = 0;
421 size_t addressLen = 0;
423 if (responseInfo->result != CA_SUCCESS)
425 OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
426 return OC_STACK_ERROR;
429 fullUri = (char *) OCMalloc(MAX_URI_LENGTH);
433 OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for fullUri"));
434 result = OC_STACK_NO_MEMORY;
438 addressLen = strlen(endPoint->addressInfo.IP.ipAddress);
439 ipAddress = (char *) OCMalloc(addressLen + 1);
443 OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for ipAddress"));
444 result = OC_STACK_NO_MEMORY;
448 strncpy(ipAddress, endPoint->addressInfo.IP.ipAddress, addressLen);
449 ipAddress[addressLen] = '\0';
451 snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", ipAddress, endPoint->addressInfo.IP.port,
454 cbNode = GetClientCB(NULL, NULL, fullUri);
458 presenceSubscribe = 1;
462 snprintf(fullUri, MAX_URI_LENGTH, "%s%s", OC_MULTICAST_IP, endPoint->resourceUri);
463 cbNode = GetClientCB(NULL, NULL, fullUri);
466 multicastPresenceSubscribe = 1;
470 if(!presenceSubscribe && !multicastPresenceSubscribe)
472 OC_LOG(ERROR, TAG, PCF("Received a presence notification, but no callback, ignoring"));
476 // No payload to the application in case of presence
477 response.resJSONPayload = NULL;
478 response.result = OC_STACK_OK;
480 result = UpdateResponseAddr(&address, endPoint);
481 if(result != OC_STACK_OK)
486 response.addr = &address;
488 result = CAToOCConnectivityType(endPoint->connectivityType, &(response.connType));
489 if(result != OC_STACK_OK)
491 OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint"));
495 if(responseInfo->info.payload)
497 parsePresencePayload(responseInfo->info.payload,
498 &(response.sequenceNumber),
503 if(presenceSubscribe)
505 if(cbNode->sequenceNumber == response.sequenceNumber)
507 OC_LOG(INFO, TAG, PCF("===============No presence change"));
512 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
513 response.result = OC_STACK_PRESENCE_STOPPED;
516 OCFree(cbNode->presence->timeOut);
517 OCFree(cbNode->presence);
518 cbNode->presence = NULL;
523 if(!cbNode->presence)
525 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
526 if(!(cbNode->presence))
528 OC_LOG(ERROR, TAG, PCF("Could not allocate memory for cbNode->presence"));
529 result = OC_STACK_NO_MEMORY;
533 VERIFY_NON_NULL_V(cbNode->presence);
534 cbNode->presence->timeOut = NULL;
535 cbNode->presence->timeOut = (uint32_t *)
536 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
537 if(!(cbNode->presence->timeOut)){
539 PCF("Could not allocate memory for cbNode->presence->timeOut"));
540 OCFree(cbNode->presence);
541 result = OC_STACK_NO_MEMORY;
546 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %u", GetTime(0));
547 cbNode->presence->TTL = maxAge;
548 for(int index = 0; index < PresenceTimeOutSize; index++)
550 lowerBound = GetTime(PresenceTimeOut[index]/ 100.0f*cbNode->presence->TTL);
551 higherBound = GetTime(PresenceTimeOut[index + 1]/100.0f*cbNode->presence->TTL);
552 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
553 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
554 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
555 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
556 cbNode->presence->timeOut[index]);
558 cbNode->presence->TTLlevel = 0;
559 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
562 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
563 cbNode->sequenceNumber = response.sequenceNumber;
565 // Ensure that a filter is actually applied.
566 if(resourceTypeName && cbNode->filterResourceType)
568 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
577 // This is the multicast case
579 OCMulticastNode* mcNode = NULL;
580 mcNode = GetMCPresenceNode(fullUri);
584 if(mcNode->nonce == response.sequenceNumber)
586 OC_LOG(INFO, TAG, PCF("No presence change (Multicast)"));
589 mcNode->nonce = response.sequenceNumber;
593 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
594 response.result = OC_STACK_PRESENCE_STOPPED;
599 uint32_t uriLen = strlen(fullUri);
600 char* uri = (char *) OCMalloc(uriLen + 1);
603 memcpy(uri, fullUri, (uriLen + 1));
608 PCF("No Memory for URI to store in the presence node"));
609 result = OC_STACK_NO_MEMORY;
612 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
613 if(result != OC_STACK_OK)
616 PCF("Unable to add Multicast Presence Node"));
622 // Ensure that a filter is actually applied.
623 if(resourceTypeName && cbNode->filterResourceType)
625 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
632 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
634 if (cbResult == OC_STACK_DELETE_TRANSACTION)
636 FindAndDeleteClientCB(cbNode);
642 OCFree(resourceTypeName);
647 //This function will be called back by CA layer when a response is received
648 void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
650 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
654 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
658 if(NULL == responseInfo)
660 OC_LOG(ERROR, TAG, PCF("responseInfo is NULL"));
664 if(strcmp(endPoint->resourceUri, OC_PRESENCE_URI) == 0)
666 HandlePresenceResponse(endPoint, responseInfo);
670 ClientCB *cbNode = GetClientCB(&(responseInfo->info.token), NULL, NULL);
674 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
675 OCClientResponse response = {};
676 OCDevAddr address = {};
678 OCStackResult result = UpdateResponseAddr(&address, endPoint);
679 if(result != OC_STACK_OK)
685 result = CAToOCConnectivityType(endPoint->connectivityType, &(response.connType));
686 if(result != OC_STACK_OK)
688 OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint"));
691 response.addr = &address;
692 response.result = CAToOCStackResult(responseInfo->result);
693 response.resJSONPayload = responseInfo->info.payload;
694 response.numRcvdVendorSpecificHeaderOptions = 0;
695 if(responseInfo->info.options && responseInfo->info.numOptions > 0)
698 //First option always with option ID is OC_COAP_OPTION_OBSERVE if it is available.
699 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
701 memcpy (&(response.sequenceNumber),
702 &(responseInfo->info.options[0].optionData), sizeof(uint32_t));
703 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
708 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
711 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
713 OC_LOG(ERROR, TAG, PCF("#header options are more than MAX_HEADER_OPTIONS"));
717 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
719 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
720 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
723 if (cbNode->callBack(cbNode->context,cbNode->handle, &response)
724 == OC_STACK_DELETE_TRANSACTION)
726 FindAndDeleteClientCB(cbNode);
729 OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload);
730 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
733 //This function will be called back by CA layer when a request is received
734 void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
736 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
739 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
745 OC_LOG(ERROR, TAG, PCF("requestInfo is NULL"));
749 OCStackResult requestResult = OC_STACK_ERROR;
751 if(myStackMode == OC_CLIENT)
753 //TODO: should the client be responding to requests?
757 OCServerProtocolRequest serverRequest = {};
759 OC_LOG_V(INFO, TAG, PCF("***** Endpoint URI ***** : %s\n"), (char*)endPoint->resourceUri);
761 char * newUri = NULL;
763 getQueryFromUri(endPoint->resourceUri, &query, &newUri);
764 OC_LOG_V(INFO, TAG, PCF("**********URI without query ****: %s\n"), newUri);
765 OC_LOG_V(INFO, TAG, PCF("**********Query ****: %s\n"), query);
766 if(strlen(newUri) < MAX_URI_LENGTH)
769 memcpy (&(serverRequest.resourceUrl), newUri, strlen(newUri));
773 OC_LOG(ERROR, TAG, PCF("URI length exceeds MAX_URI_LENGTH."));
779 if(strlen((char*)query) < MAX_QUERY_LENGTH)
781 memcpy (&(serverRequest.query), query, strlen((char*)query));
785 OC_LOG(ERROR, TAG, PCF("Query length exceeds MAX_QUERY_LENGTH."));
789 //copy request payload
790 if (requestInfo->info.payload)
792 size_t payloadLen = strlen(requestInfo->info.payload);
793 serverRequest.reqTotalSize = payloadLen + 1;
794 memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
799 serverRequest.reqTotalSize = 1;
800 serverRequest.reqJSONPayload[0] = '\0';
803 switch (requestInfo->method)
807 serverRequest.method = OC_REST_GET;
812 serverRequest.method = OC_REST_PUT;
817 serverRequest.method = OC_REST_POST;
822 serverRequest.method = OC_REST_DELETE;
827 OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
832 OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d", CA_MAX_TOKEN_LEN);
833 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token, CA_MAX_TOKEN_LEN);
835 serverRequest.requestToken = (CAToken_t)OCMalloc(CA_MAX_TOKEN_LEN+1);
837 if (!serverRequest.requestToken)
839 OC_LOG(FATAL, TAG, "Server Request Token is NULL");
842 memcpy(serverRequest.requestToken, requestInfo->info.token, CA_MAX_TOKEN_LEN);
844 if (requestInfo->info.type == CA_MSG_CONFIRM)
846 serverRequest.qos = OC_HIGH_QOS;
848 else if (requestInfo->info.type == CA_MSG_NONCONFIRM)
850 serverRequest.qos = OC_LOW_QOS;
852 else if (requestInfo->info.type == CA_MSG_ACKNOWLEDGE)
854 // TODO-CA: Need to handle this
856 else if (requestInfo->info.type == CA_MSG_RESET)
858 // TODO-CA: Need to handle this
860 // CA does not need the following 3 fields
861 serverRequest.coapID = 0;
862 serverRequest.delayedResNeeded = 0;
863 serverRequest.secured = endPoint->isSecured;
866 serverRequest.addressInfo = endPoint->addressInfo;
867 serverRequest.connectivityType = endPoint->connectivityType;
869 // copy vendor specific header options
870 // TODO-CA: CA is including non-vendor header options as well, like observe.
871 // Need to filter those out
872 uint8_t tempNum = (requestInfo->info.numOptions);
873 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
874 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
877 PCF("The request info numOptions is greater than MAX_HEADER_OPTIONS"));
878 OCFree(serverRequest.requestToken);
881 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
882 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
884 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
885 sizeof(CAHeaderOption_t)*tempNum);
888 requestResult = HandleStackRequests (&serverRequest);
889 if(requestResult != OC_STACK_OK)
891 OC_LOG(ERROR, TAG, PCF("HandleStackRequests failed"));
893 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
896 //This function will be called back by occoap layer when a request is received
897 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
899 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
900 OCStackResult result = OC_STACK_ERROR;
901 ResourceHandling resHandling;
902 OCResource *resource;
905 OC_LOG(ERROR, TAG, PCF("protocolRequest is NULL"));
906 return OC_STACK_INVALID_PARAM;
909 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
912 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
913 result = AddServerRequest(&request, protocolRequest->coapID,
914 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
915 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
916 protocolRequest->observationOption, protocolRequest->qos,
917 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
918 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
919 protocolRequest->resourceUrl,protocolRequest->reqTotalSize,
920 &protocolRequest->addressInfo, protocolRequest->connectivityType);
921 if (OC_STACK_OK != result)
923 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
929 OC_LOG(ERROR, TAG, PCF("Out of Memory"));
930 return OC_STACK_NO_MEMORY;
933 if(!protocolRequest->reqMorePacket)
935 request->requestComplete = 1;
941 PCF("This is either a repeated Server Request or blocked Server Request"));
944 if(request->requestComplete)
946 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
947 result = DetermineResourceHandling (request, &resHandling, &resource);
948 if (result == OC_STACK_OK)
950 result = ProcessRequest(resHandling, resource, request);
954 result = OC_STACK_ERROR;
959 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
960 result = OC_STACK_CONTINUE;
965 int ParseIPv4Address(char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
969 uint8_t dotCount = 0;
973 /* search for scheme */
975 if (!isdigit((char) *ipAddrStr))
977 coap = OC_COAP_SCHEME;
978 while (*coap && tolower(*itr) == *coap)
987 if (isdigit(*ipAddrStr))
990 ipAddr[index] += *ipAddrStr - '0';
992 else if (*ipAddrStr == '.')
1004 if(*ipAddrStr == ':')
1008 if (isdigit(*ipAddrStr))
1011 *port += *ipAddrStr - '0';
1032 //-----------------------------------------------------------------------------
1033 // Private internal function prototypes
1034 //-----------------------------------------------------------------------------
1036 static OCDoHandle GenerateInvocationHandle();
1037 static OCStackResult initResources();
1038 static void insertResource(OCResource *resource);
1039 static OCResource *findResource(OCResource *resource);
1040 static void insertResourceType(OCResource *resource,
1041 OCResourceType *resourceType);
1042 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
1044 static void insertResourceInterface(OCResource *resource,
1045 OCResourceInterface *resourceInterface);
1046 static OCResourceInterface *findResourceInterfaceAtIndex(
1047 OCResourceHandle handle, uint8_t index);
1048 static void deleteResourceType(OCResourceType *resourceType);
1049 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
1050 static void deleteResourceElements(OCResource *resource);
1051 static OCStackResult deleteResource(OCResource *resource);
1052 static void deleteAllResources();
1053 static void incrementSequenceNumber(OCResource * resPtr);
1054 static OCStackResult verifyUriQueryLength(const char * inputUri,
1056 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
1057 OCStackResult getResourceType(const char * query, char** resourceType);
1058 static CAResult_t OCSelectNetwork();
1060 //-----------------------------------------------------------------------------
1062 //-----------------------------------------------------------------------------
1065 * Initialize the OC Stack. Must be called prior to starting the stack.
1068 * IP Address of host device
1070 * Port of host device
1072 * Host device is client, server, or client-server
1075 * OC_STACK_OK - no errors
1076 * OC_STACK_ERROR - stack init error
1078 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1082 OCStackResult result = OC_STACK_ERROR;
1083 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
1086 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)))
1088 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1089 return OC_STACK_ERROR;
1093 defaultDeviceHandler = NULL;
1096 result = CAResultToOCResult(CAInitialize());
1097 VERIFY_SUCCESS(result, OC_STACK_OK);
1099 result = CAResultToOCResult(OCSelectNetwork());
1100 VERIFY_SUCCESS(result, OC_STACK_OK);
1102 CARegisterHandler(HandleCARequests, HandleCAResponses);
1103 switch (myStackMode)
1106 result = CAResultToOCResult(CAStartDiscoveryServer());
1107 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
1110 result = CAResultToOCResult(CAStartListeningServer());
1111 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
1113 case OC_CLIENT_SERVER:
1114 result = CAResultToOCResult(CAStartListeningServer());
1115 if(result == OC_STACK_OK)
1117 result = CAResultToOCResult(CAStartDiscoveryServer());
1121 VERIFY_SUCCESS(result, OC_STACK_OK);
1123 #if defined(__WITH_DTLS__)
1124 result = (CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials) == CA_STATUS_OK) ?
1125 OC_STACK_OK : OC_STACK_ERROR;
1126 VERIFY_SUCCESS(result, OC_STACK_OK);
1127 #endif // (__WITH_DTLS__)
1129 #ifdef WITH_PRESENCE
1130 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
1131 #endif // WITH_PRESENCE
1133 //Update Stack state to initialized
1134 stackState = OC_STACK_INITIALIZED;
1136 // Initialize resource
1137 if(myStackMode != OC_CLIENT)
1139 result = initResources();
1143 if(result != OC_STACK_OK)
1145 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1146 deleteAllResources();
1148 stackState = OC_STACK_UNINITIALIZED;
1154 * Stop the OC stack. Use for a controlled shutdown.
1156 * OC_STACK_OK - no errors
1157 * OC_STACK_ERROR - stack not initialized
1159 OCStackResult OCStop()
1161 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1163 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1165 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1168 else if (stackState != OC_STACK_INITIALIZED)
1170 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1171 return OC_STACK_ERROR;
1174 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1176 #ifdef WITH_PRESENCE
1177 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1178 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1179 presenceResource.presenceTTL = 0;
1180 #endif // WITH_PRESENCE
1182 // Free memory dynamically allocated for resources
1183 deleteAllResources();
1186 // Remove all observers
1187 DeleteObserverList();
1188 // Remove all the client callbacks
1189 DeleteClientCBList();
1190 // Deinit security blob
1191 DeinitOCSecurityInfo();
1192 stackState = OC_STACK_UNINITIALIZED;
1197 * Map OCQualityOfService to CAMessageType
1199 * @param OCQualityOfService - Input qos.
1201 * Returns CA message type for a given qos.
1203 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
1208 return CA_MSG_CONFIRM;
1213 return CA_MSG_NONCONFIRM;
1218 * Verify the lengths of the URI and the query separately
1220 * @param inputUri - Input URI and query.
1221 * @param uriLen - The length of the initial URI with query.
1223 * Note: The '?' that appears after the URI is not considered as
1224 * a part of the query.
1226 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1230 query = strchr (inputUri, '?');
1234 if((query - inputUri) > MAX_URI_LENGTH)
1236 return OC_STACK_INVALID_URI;
1239 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1241 return OC_STACK_INVALID_QUERY;
1244 else if(uriLen > MAX_URI_LENGTH)
1246 return OC_STACK_INVALID_URI;
1252 * Discover or Perform requests on a specified resource
1253 * (specified by that Resource's respective URI).
1255 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of
1257 * @param method - @ref OCMethod to perform on the resource
1258 * @param requiredUri - URI of the resource to interact with
1259 * @param referenceUri - URI of the reference resource
1260 * @param request - JSON encoded request
1261 * @param qos - quality of service
1262 * @param cbData - struct that contains asynchronous callback function that is invoked
1263 * by the stack when discovery or resource interaction is complete
1264 * @param options - The address of an array containing the vendor specific header
1265 * header options to be sent with the request
1266 * @param numOptions - Number of vendor specific header options to be included
1269 * OC_STACK_OK - no errors
1270 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
1271 * OC_STACK_INVALID_METHOD - invalid resource method
1272 * OC_STACK_INVALID_URI - invalid required or reference URI
1274 * Note: when using multicast, the required URI should not contain IP address.
1275 * Instead, it just contains the URI to the resource such as "/oc/core".
1277 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1278 const char *referenceUri, const char *request, OCConnectivityType conType,
1279 OCQualityOfService qos, OCCallbackData *cbData,
1280 OCHeaderOption * options, uint8_t numOptions)
1282 OCStackResult result = OC_STACK_ERROR;
1283 ClientCB *clientCB = NULL;
1284 char * requestUri = NULL;
1285 char * resourceType = NULL;
1286 char * query = NULL;
1287 char * newUri = (char *)requiredUri;
1288 (void) referenceUri;
1289 CARemoteEndpoint_t* endpoint = NULL;
1290 CAResult_t caResult;
1291 CAToken_t token = NULL;
1292 OCDoHandle resHandle = NULL;
1293 CAInfo_t requestData ={};
1294 CARequestInfo_t requestInfo ={};
1295 CAGroupEndpoint_t grpEnd = {};
1297 // To track if memory is allocated for additional header options
1299 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1301 // Validate input parameters
1302 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1303 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1305 //TODO ("Need to form the final query by concatenating require and reference URI's");
1306 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
1308 uint16_t uriLen = strlen(requiredUri);
1310 // ToDo: We should also check if the requiredUri has a mutlicast address,
1311 // then qos has to be OC_Low_QOS
1317 case OC_REST_DELETE:
1318 case OC_REST_OBSERVE:
1319 case OC_REST_OBSERVE_ALL:
1320 case OC_REST_CANCEL_OBSERVE:
1322 #ifdef WITH_PRESENCE
1323 case OC_REST_PRESENCE:
1327 result = OC_STACK_INVALID_METHOD;
1331 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
1336 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
1338 result = OC_STACK_INVALID_PARAM;
1342 #ifdef WITH_PRESENCE
1343 if(method == OC_REST_PRESENCE)
1345 result = getQueryFromUri(requiredUri, &query, &newUri);
1348 result = getResourceType((char *) query, &resourceType);
1351 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1355 OC_LOG(DEBUG, TAG, PCF("Resource type is NULL."));
1360 OC_LOG(DEBUG, TAG, PCF("Query string is NULL."));
1362 if(result != OC_STACK_OK)
1367 #endif // WITH_PRESENCE
1369 requestUri = (char *) OCMalloc(uriLen + 1);
1372 memcpy(requestUri, newUri, (uriLen + 1));
1376 result = OC_STACK_NO_MEMORY;
1380 resHandle = GenerateInvocationHandle();
1383 result = OC_STACK_NO_MEMORY;
1390 case OC_REST_OBSERVE:
1391 case OC_REST_OBSERVE_ALL:
1392 case OC_REST_CANCEL_OBSERVE:
1394 requestInfo.method = CA_GET;
1399 requestInfo.method = CA_PUT;
1404 requestInfo.method = CA_POST;
1407 case OC_REST_DELETE:
1409 requestInfo.method = CA_DELETE;
1412 #ifdef WITH_PRESENCE
1413 case OC_REST_PRESENCE:
1415 // Replacing method type with GET because "presence"
1416 // is a stack layer only implementation.
1417 requestInfo.method = CA_GET;
1422 result = OC_STACK_INVALID_METHOD;
1426 //High QoS is not supported
1427 if(qos == OC_HIGH_QOS)
1429 result = OC_STACK_INVALID_PARAM;
1434 caResult = CAGenerateToken(&token);
1435 if (caResult != CA_STATUS_OK)
1437 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1438 CADestroyToken(token);
1439 result = CAResultToOCResult(caResult);
1443 requestData.type = qualityOfServiceToMessageType(qos);
1444 requestData.token = token;
1445 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1447 result = CreateObserveHeaderOption (&(requestData.options), options,
1448 numOptions, OC_OBSERVE_REGISTER);
1449 if (result != OC_STACK_OK)
1453 requestData.numOptions = numOptions + 1;
1457 requestData.options = (CAHeaderOption_t*)options;
1458 requestData.numOptions = numOptions;
1460 requestData.payload = (char *)request;
1462 requestInfo.info = requestData;
1464 CAConnectivityType_t caConType;
1466 result = OCToCAConnectivityType((OCConnectivityType) conType, &caConType);
1467 if (result != OC_STACK_OK)
1469 OC_LOG(ERROR, TAG, PCF("Invalid Connectivity Type"));
1474 if(conType == OC_ALL)
1476 grpEnd.connectivityType = caConType;
1478 grpEnd.resourceUri = (CAURI_t) OCMalloc(uriLen + 1);
1479 if(!grpEnd.resourceUri)
1481 result = OC_STACK_NO_MEMORY;
1484 strncpy(grpEnd.resourceUri, requiredUri, (uriLen + 1));
1486 caResult = CASendRequestToAll(&grpEnd, &requestInfo);
1490 caResult = CACreateRemoteEndpoint(newUri, caConType, &endpoint);
1492 if (caResult != CA_STATUS_OK)
1494 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1495 result = CAResultToOCResult(caResult);
1499 caResult = CASendRequest(endpoint, &requestInfo);
1502 if (caResult != CA_STATUS_OK)
1504 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1505 result = CAResultToOCResult(caResult);
1509 if((result = AddClientCB(&clientCB, cbData, &token, &resHandle, method,
1510 requestUri, resourceType)) != OC_STACK_OK)
1512 result = OC_STACK_NO_MEMORY;
1518 *handle = resHandle;
1522 if(newUri != requiredUri)
1526 if (result != OC_STACK_OK)
1528 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1529 FindAndDeleteClientCB(clientCB);
1532 OCFree(resourceType);
1534 CADestroyRemoteEndpoint(endpoint);
1535 OCFree(grpEnd.resourceUri);
1536 if (requestData.options && requestData.numOptions > 0)
1538 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1540 OCFree(requestData.options);
1547 * Cancel a request associated with a specific @ref OCDoResource invocation.
1549 * @param handle - Used to identify a specific OCDoResource invocation.
1550 * @param qos - used to specify Quality of Service (read below for more info)
1551 * @param options- used to specify vendor specific header options when sending
1552 * explicit observe cancellation
1553 * @param numOptions- Number of header options to be included
1556 * OC_STACK_OK - No errors; Success
1557 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1559 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1563 * This ftn is implemented one of two ways in the case of observation:
1565 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1566 * Remove the callback associated on client side.
1567 * When the next notification comes in from server,
1568 * reply with RESET message to server.
1569 * Keep in mind that the server will react to RESET only
1570 * if the last notification was sent ans CON
1572 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1573 * and it is associated with an observe request
1574 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1575 * Send CON Observe request to server with
1576 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1577 * Remove the callback associated on client side.
1579 OCStackResult ret = OC_STACK_OK;
1580 CARemoteEndpoint_t* endpoint = NULL;
1581 CAResult_t caResult= CA_STATUS_OK;
1582 CAInfo_t requestData = {};
1583 CARequestInfo_t requestInfo = {};
1587 return OC_STACK_INVALID_PARAM;
1590 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1592 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1596 switch (clientCB->method)
1598 case OC_REST_OBSERVE:
1599 case OC_REST_OBSERVE_ALL:
1600 //TODO-CA : Why CA_WIFI alone?
1601 caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri, CA_WIFI,
1603 if (caResult != CA_STATUS_OK)
1605 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1606 return OC_STACK_ERROR;
1609 memset(&requestData, 0, sizeof(CAInfo_t));
1610 requestData.type = qualityOfServiceToMessageType(qos);
1611 requestData.token = clientCB->token;
1612 if (CreateObserveHeaderOption (&(requestData.options),
1613 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
1615 return OC_STACK_ERROR;
1617 requestData.numOptions = numOptions + 1;
1618 requestInfo.method = CA_GET;
1619 requestInfo.info = requestData;
1621 caResult = CASendRequest(endpoint, &requestInfo);
1622 if (caResult != CA_STATUS_OK)
1624 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1626 if(caResult == CA_STATUS_OK)
1630 #ifdef WITH_PRESENCE
1631 case OC_REST_PRESENCE:
1632 FindAndDeleteClientCB(clientCB);
1636 return OC_STACK_INVALID_METHOD;
1639 CADestroyRemoteEndpoint(endpoint);
1640 if (requestData.numOptions > 0)
1642 OCFree(requestData.options);
1648 #ifdef WITH_PRESENCE
1649 OCStackResult OCProcessPresence()
1651 OCStackResult result = OC_STACK_OK;
1652 uint8_t ipAddr[4] = { 0 };
1655 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1656 ClientCB* cbNode = NULL;
1658 OCClientResponse clientResponse ={};
1659 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1661 LL_FOREACH(cbList, cbNode)
1663 if(OC_REST_PRESENCE == cbNode->method)
1665 if(cbNode->presence)
1667 uint32_t now = GetTime(0);
1668 OC_LOG_V(DEBUG, TAG, "this TTL level %d",
1669 cbNode->presence->TTLlevel);
1670 OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
1673 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1678 if(cbNode->presence->TTLlevel < PresenceTimeOutSize)
1680 OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
1681 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1684 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1686 OC_LOG(DEBUG, TAG, PCF("No more timeout ticks"));
1687 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1689 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1692 clientResponse.sequenceNumber = 0;
1693 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
1694 clientResponse.addr = (OCDevAddr *) &dst;
1695 clientResponse.resJSONPayload = NULL;
1697 // Increment the TTLLevel (going to a next state), so we don't keep
1698 // sending presence notification to client.
1699 cbNode->presence->TTLlevel++;
1700 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
1701 cbNode->presence->TTLlevel);
1705 result = OC_STACK_INVALID_IP;
1709 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
1710 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1712 FindAndDeleteClientCB(cbNode);
1716 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1718 CAResult_t caResult = CA_STATUS_OK;
1719 CARemoteEndpoint_t* endpoint = NULL;
1720 CAInfo_t requestData ={};
1721 CARequestInfo_t requestInfo = {};
1723 OC_LOG(DEBUG, TAG, PCF("time to test server presence"));
1725 //TODO-CA : Why CA_WIFI alone?
1726 caResult = CACreateRemoteEndpoint((char *)cbNode->requestUri, CA_WIFI,
1729 if (caResult != CA_STATUS_OK)
1731 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1735 requestData.type = CA_MSG_NONCONFIRM;
1736 requestData.token = cbNode->token;
1738 requestInfo.method = CA_GET;
1739 requestInfo.info = requestData;
1741 caResult = CASendRequest(endpoint, &requestInfo);
1743 if (caResult != CA_STATUS_OK)
1745 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1749 cbNode->presence->TTLlevel++;
1750 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
1751 cbNode->presence->TTLlevel);
1757 if (result != OC_STACK_OK)
1759 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
1763 #endif // WITH_PRESENCE
1766 * Called in main loop of OC client or server. Allows low-level processing of
1770 * OC_STACK_OK - no errors
1771 * OC_STACK_ERROR - stack process error
1773 OCStackResult OCProcess()
1775 #ifdef WITH_PRESENCE
1776 OCProcessPresence();
1778 CAHandleRequestResponse();
1783 #ifdef WITH_PRESENCE
1785 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
1786 * presence notifications to clients via multicast. Once this API has been called with a success,
1787 * clients may query for this server's presence and this server's stack will respond via multicast.
1789 * Server can call this function when it comes online for the first time, or when it comes back
1790 * online from offline mode, or when it re enters network.
1792 * @param ttl - Time To Live in seconds
1793 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
1796 * OC_STACK_OK - No errors; Success
1798 OCStackResult OCStartPresence(const uint32_t ttl)
1800 OCChangeResourceProperty(
1801 &(((OCResource *)presenceResource.handle)->resourceProperties),
1806 presenceResource.presenceTTL = ttl;
1809 if(OC_PRESENCE_UNINITIALIZED == presenceState)
1811 presenceState = OC_PRESENCE_INITIALIZED;
1813 CAAddress_t addressInfo;
1814 strncpy(addressInfo.IP.ipAddress, OC_MULTICAST_IP, CA_IPADDR_SIZE);
1815 addressInfo.IP.port = OC_MULTICAST_PORT;
1817 //TODO make sure there is no memory leak here since another copy
1818 //of token is being created inside AddObserver
1819 CAToken_t caToken = NULL;
1820 CAResult_t caResult = CAGenerateToken(&caToken);
1821 if (caResult != CA_STATUS_OK)
1823 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1824 CADestroyToken(caToken);
1825 return OC_STACK_ERROR;
1828 CAConnectivityType_t connType;
1829 OCToCAConnectivityType(OC_ALL, &connType );
1830 AddObserver(OC_PRESENCE_URI, NULL, 0, &caToken,
1831 (OCResource *)presenceResource.handle, OC_LOW_QOS,
1832 &addressInfo, connType);
1835 // Each time OCStartPresence is called
1836 // a different random 32-bit integer number is used
1837 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1839 return SendPresenceNotification(NULL);
1843 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
1844 * presence notifications to clients via multicast. Once this API has been called with a success,
1845 * this server's stack will not respond to clients querying for this server's presence.
1847 * Server can call this function when it is terminating, going offline, or when going
1848 * away from network.
1851 * OC_STACK_OK - No errors; Success
1853 OCStackResult OCStopPresence()
1855 OCStackResult result = OC_STACK_ERROR;
1857 if(presenceResource.handle)
1859 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1862 // make resource inactive
1863 result = OCChangeResourceProperty(
1864 &(((OCResource *) presenceResource.handle)->resourceProperties),
1867 if(result != OC_STACK_OK)
1870 PCF("Changing the presence resource properties to ACTIVE not successful"));
1874 return SendStopNotification();
1879 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
1881 defaultDeviceHandler = entityHandler;
1886 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
1888 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
1890 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
1892 return SaveDeviceInfo(deviceInfo);
1896 return OC_STACK_ERROR;
1903 * @param handle - pointer to handle to newly created resource. Set by ocstack.
1904 * Used to refer to resource
1905 * @param resourceTypeName - name of resource type. Example: "core.led"
1906 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1907 * @param uri - URI of the resource. Example: "/a/led"
1908 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1909 * NULL for default entity handler
1910 * @param resourceProperties - properties supported by resource.
1911 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
1914 * OC_STACK_OK - no errors
1915 * OC_STACK_ERROR - stack process error
1917 OCStackResult OCCreateResource(OCResourceHandle *handle,
1918 const char *resourceTypeName,
1919 const char *resourceInterfaceName,
1920 const char *uri, OCEntityHandler entityHandler,
1921 uint8_t resourceProperties)
1924 OCResource *pointer = NULL;
1927 OCStackResult result = OC_STACK_ERROR;
1929 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
1931 if(myStackMode == OC_CLIENT)
1933 return OC_STACK_INVALID_PARAM;
1935 // Validate parameters
1936 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
1938 OC_LOG(ERROR, TAG, PCF("URI is invalid"));
1939 return OC_STACK_INVALID_URI;
1941 // Is it presented during resource discovery?
1942 if (!handle || !resourceTypeName)
1944 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
1945 return OC_STACK_INVALID_PARAM;
1948 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
1950 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
1953 // Make sure resourceProperties bitmask has allowed properties specified
1954 if (resourceProperties
1955 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
1956 OC_LOG(ERROR, TAG, PCF("Invalid property"));
1957 return OC_STACK_INVALID_PARAM;
1960 // If the headResource is NULL, then no resources have been created...
1961 pointer = headResource;
1964 // At least one resources is in the resource list, so we need to search for
1965 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
1968 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
1970 OC_LOG(ERROR, TAG, PCF("URI already in use"));
1971 return OC_STACK_INVALID_PARAM;
1973 pointer = pointer->next;
1976 // Create the pointer and insert it into the resource list
1977 pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
1980 result = OC_STACK_NO_MEMORY;
1983 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
1985 insertResource(pointer);
1988 size = strlen(uri) + 1;
1989 str = (char *) OCMalloc(size);
1992 result = OC_STACK_NO_MEMORY;
1995 strncpy(str, uri, size);
1998 // Set properties. Set OC_ACTIVE
1999 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2002 // Add the resourcetype to the resource
2003 result = BindResourceTypeToResource(pointer, resourceTypeName);
2004 if (result != OC_STACK_OK)
2006 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
2010 // Add the resourceinterface to the resource
2011 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2012 if (result != OC_STACK_OK)
2014 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
2018 // If an entity handler has been passed, attach it to the newly created
2019 // resource. Otherwise, set the default entity handler.
2022 pointer->entityHandler = entityHandler;
2026 pointer->entityHandler = defaultResourceEHandler;
2030 result = OC_STACK_OK;
2032 #ifdef WITH_PRESENCE
2033 if(presenceResource.handle)
2035 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2036 SendPresenceNotification(pointer->rsrcType);
2040 if (result != OC_STACK_OK)
2042 // Deep delete of resource and other dynamic elements that it contains
2043 deleteResource(pointer);
2052 * Create a resource. with host ip address for remote resource
2054 * @param handle - pointer to handle to newly created resource. Set by ocstack.
2055 * Used to refer to resource
2056 * @param resourceTypeName - name of resource type. Example: "core.led"
2057 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
2058 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
2059 * @param uri - URI of the resource. Example: "/a/led"
2060 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2061 * NULL for default entity handler
2062 * @param resourceProperties - properties supported by resource.
2063 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
2066 * OC_STACK_OK - no errors
2067 * OC_STACK_ERROR - stack process error
2070 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
2071 const char *resourceTypeName,
2072 const char *resourceInterfaceName,
2075 OCEntityHandler entityHandler,
2076 uint8_t resourceProperties)
2083 return OC_STACK_INVALID_PARAM;
2086 OCStackResult result = OC_STACK_ERROR;
2088 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
2089 uri, entityHandler, resourceProperties);
2091 if (result != OC_STACK_ERROR)
2094 size = strlen(host) + 1;
2095 str = (char *) OCMalloc(size);
2098 return OC_STACK_NO_MEMORY;
2100 strncpy(str, host, size);
2101 ((OCResource *) *handle)->host = str;
2108 * Add a resource to a collection resource.
2110 * @param collectionHandle - handle to the collection resource
2111 * @param resourceHandle - handle to resource to be added to the collection resource
2114 * OC_STACK_OK - no errors
2115 * OC_STACK_ERROR - stack process error
2116 * OC_STACK_INVALID_PARAM - invalid collectionhandle
2118 OCStackResult OCBindResource(
2119 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2121 OCResource *resource = NULL;
2124 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2126 // Validate parameters
2127 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2128 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2129 // Container cannot contain itself
2130 if (collectionHandle == resourceHandle)
2132 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2133 return OC_STACK_INVALID_PARAM;
2136 // Use the handle to find the resource in the resource linked list
2137 resource = findResource((OCResource *) collectionHandle);
2140 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2141 return OC_STACK_INVALID_PARAM;
2144 // Look for an open slot to add add the child resource.
2145 // If found, add it and return success
2146 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2148 if (!resource->rsrcResources[i])
2150 resource->rsrcResources[i] = (OCResource *) resourceHandle;
2151 OC_LOG(INFO, TAG, PCF("resource bound"));
2153 #ifdef WITH_PRESENCE
2154 if(presenceResource.handle)
2156 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2157 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2165 // Unable to add resourceHandle, so return error
2166 return OC_STACK_ERROR;
2170 * Remove a resource from a collection resource.
2172 * @param collectionHandle - handle to the collection resource
2173 * @param resourceHandle - handle to resource to be added to the collection resource
2176 * OC_STACK_OK - no errors
2177 * OC_STACK_ERROR - stack process error
2178 * OC_STACK_INVALID_PARAM - invalid collectionHandle
2180 OCStackResult OCUnBindResource(
2181 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2183 OCResource *resource = NULL;
2186 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2188 // Validate parameters
2189 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2190 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2191 // Container cannot contain itself
2192 if (collectionHandle == resourceHandle)
2194 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2195 return OC_STACK_INVALID_PARAM;
2198 // Use the handle to find the resource in the resource linked list
2199 resource = findResource((OCResource *) collectionHandle);
2202 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2203 return OC_STACK_INVALID_PARAM;
2206 // Look for an open slot to add add the child resource.
2207 // If found, add it and return success
2208 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2210 if (resourceHandle == resource->rsrcResources[i])
2212 resource->rsrcResources[i] = (OCResource *) NULL;
2213 OC_LOG(INFO, TAG, PCF("resource unbound"));
2215 // Send notification when resource is unbounded successfully.
2216 #ifdef WITH_PRESENCE
2217 if(presenceResource.handle)
2219 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2220 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2227 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2229 // Unable to add resourceHandle, so return error
2230 return OC_STACK_ERROR;
2233 OCStackResult BindResourceTypeToResource(OCResource* resource,
2234 const char *resourceTypeName)
2236 OCResourceType *pointer = NULL;
2239 OCStackResult result = OC_STACK_ERROR;
2241 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
2243 // Validate parameters
2244 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2245 // TODO: Does resource attribute resentation really have to be maintained in stack?
2246 // Is it presented during resource discovery?
2248 //TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
2250 // Create the resourcetype and insert it into the resource list
2251 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
2254 result = OC_STACK_NO_MEMORY;
2258 // Set the resourceTypeName
2259 size = strlen(resourceTypeName) + 1;
2260 str = (char *) OCMalloc(size);
2263 result = OC_STACK_NO_MEMORY;
2266 strncpy(str, resourceTypeName, size);
2267 pointer->resourcetypename = str;
2269 insertResourceType(resource, pointer);
2270 result = OC_STACK_OK;
2273 if (result != OC_STACK_OK)
2282 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2283 const char *resourceInterfaceName)
2285 OCResourceInterface *pointer = NULL;
2288 OCStackResult result = OC_STACK_ERROR;
2290 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
2292 // Validate parameters
2293 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2295 //TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
2297 // Create the resourceinterface and insert it into the resource list
2298 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
2301 result = OC_STACK_NO_MEMORY;
2305 // Set the resourceinterface name
2306 size = strlen(resourceInterfaceName) + 1;
2307 str = (char *) OCMalloc(size);
2310 result = OC_STACK_NO_MEMORY;
2313 strncpy(str, resourceInterfaceName, size);
2314 pointer->name = str;
2316 // Bind the resourceinterface to the resource
2317 insertResourceInterface(resource, pointer);
2319 result = OC_STACK_OK;
2322 if (result != OC_STACK_OK)
2332 * Bind a resourcetype to a resource.
2334 * @param handle - handle to the resource
2335 * @param resourceTypeName - name of resource type. Example: "core.led"
2338 * OC_STACK_OK - no errors
2339 * OC_STACK_ERROR - stack process error
2341 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2342 const char *resourceTypeName)
2345 OCStackResult result = OC_STACK_ERROR;
2346 OCResource *resource = NULL;
2348 // Make sure resource exists
2349 resource = findResource((OCResource *) handle);
2352 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2353 return OC_STACK_ERROR;
2356 // call internal function
2357 result = BindResourceTypeToResource(resource, resourceTypeName);
2359 #ifdef WITH_PRESENCE
2360 if(presenceResource.handle)
2362 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2363 SendPresenceNotification(resource->rsrcType);
2371 * Bind a resourceinterface to a resource.
2373 * @param handle - handle to the resource
2374 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
2377 * OC_STACK_OK - no errors
2378 * OC_STACK_ERROR - stack process error
2381 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2382 const char *resourceInterfaceName)
2385 OCStackResult result = OC_STACK_ERROR;
2386 OCResource *resource = NULL;
2388 // Make sure resource exists
2389 resource = findResource((OCResource *) handle);
2392 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2393 return OC_STACK_ERROR;
2396 // call internal function
2397 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2399 #ifdef WITH_PRESENCE
2400 if(presenceResource.handle)
2402 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2403 SendPresenceNotification(resource->rsrcType);
2411 * Get the number of resources that have been created in the stack.
2413 * @param numResources - pointer to count variable
2416 * OC_STACK_OK - no errors
2417 * OC_STACK_ERROR - stack process error
2420 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
2422 OCResource *pointer = headResource;
2424 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2425 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2429 *numResources = *numResources + 1;
2430 pointer = pointer->next;
2436 * Get a resource handle by index.
2438 * @param index - index of resource, 0 to Count - 1
2441 * Resource handle - if found
2442 * NULL - if not found
2444 OCResourceHandle OCGetResourceHandle(uint8_t index)
2446 OCResource *pointer = headResource;
2448 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2450 // Iterate through the list
2451 for( uint8_t i = 0; i < index && pointer; ++i)
2453 pointer = pointer->next;
2455 return (OCResourceHandle) pointer;
2459 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
2462 * @param handle - handle of resource to be deleted
2465 * OC_STACK_OK - no errors
2466 * OC_STACK_ERROR - stack process error
2467 * OC_STACK_NO_RESOURCE - resource not found
2468 * OC_STACK_INVALID_PARAM - invalid param
2470 OCStackResult OCDeleteResource(OCResourceHandle handle)
2472 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2476 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2477 return OC_STACK_INVALID_PARAM;
2480 OCResource *resource = findResource((OCResource *) handle);
2481 if (resource == NULL)
2483 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2484 return OC_STACK_NO_RESOURCE;
2487 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
2489 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2490 return OC_STACK_ERROR;
2497 * Get the URI of the resource specified by handle.
2499 * @param handle - handle of resource
2501 * URI string - if resource found
2502 * NULL - resource not found
2504 const char *OCGetResourceUri(OCResourceHandle handle)
2506 OCResource *resource = NULL;
2507 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2509 resource = findResource((OCResource *) handle);
2512 return resource->uri;
2514 return (const char *) NULL;
2518 * Get the properties of the resource specified by handle.
2519 * NOTE: that after a resource is created, the OC_ACTIVE property is set
2520 * for the resource by the stack.
2522 * @param handle - handle of resource
2524 * OCResourceProperty Bitmask
2525 * -1 if resource is not found
2527 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
2529 OCResource *resource = NULL;
2530 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2532 resource = findResource((OCResource *) handle);
2535 return resource->resourceProperties;
2537 return (OCResourceProperty)-1;
2541 * Get the number of resource types of the resource.
2543 * @param handle - handle of resource
2544 * @param numResourceTypes - pointer to count variable
2547 * OC_STACK_OK - no errors
2548 * OC_STACK_ERROR - stack process error
2550 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2551 uint8_t *numResourceTypes)
2553 OCResource *resource = NULL;
2554 OCResourceType *pointer = NULL;
2556 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2557 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2558 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2560 *numResourceTypes = 0;
2562 resource = findResource((OCResource *) handle);
2565 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)
2587 OCResourceType *resourceType = NULL;
2589 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2591 resourceType = findResourceTypeAtIndex(handle, index);
2594 return resourceType->resourcetypename;
2596 return (const char *) NULL;
2602 * Get the number of resource interfaces of the resource.
2604 * @param handle - handle of resource
2605 * @param numResources - pointer to count variable
2608 * OC_STACK_OK - no errors
2609 * OC_STACK_ERROR - stack process error
2611 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2612 uint8_t *numResourceInterfaces)
2614 OCResourceInterface *pointer = NULL;
2615 OCResource *resource = NULL;
2617 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2619 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2620 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2622 *numResourceInterfaces = 0;
2623 resource = findResource((OCResource *) handle);
2626 pointer = resource->rsrcInterface;
2629 *numResourceInterfaces = *numResourceInterfaces + 1;
2630 pointer = pointer->next;
2637 * Get name of resource interface of the resource.
2639 * @param handle - handle of resource
2640 * @param index - index of resource, 0 to Count - 1
2643 * resource interface name - if resource found
2644 * NULL - resource not found
2646 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
2648 OCResourceInterface *resourceInterface = NULL;
2650 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2652 resourceInterface = findResourceInterfaceAtIndex(handle, index);
2653 if (resourceInterface)
2655 return resourceInterface->name;
2657 return (const char *) NULL;
2661 * Get resource handle from the collection resource by index.
2663 * @param collectionHandle - handle of collection resource
2664 * @param index - index of contained resource, 0 to Count - 1
2667 * handle to resource - if resource found
2668 * NULL - resource not found
2670 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2673 OCResource *resource = NULL;
2675 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2677 if (index >= MAX_CONTAINED_RESOURCES)
2682 resource = findResource((OCResource *) collectionHandle);
2688 return resource->rsrcResources[index];
2692 * Bind an entity handler to the resource.
2694 * @param handle - handle to the resource that the contained resource is to be bound
2695 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2697 * OC_STACK_OK - no errors
2698 * OC_STACK_ERROR - stack process error
2700 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2701 OCEntityHandler entityHandler)
2703 OCResource *resource = NULL;
2705 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2707 // Validate parameters
2708 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2710 // Use the handle to find the resource in the resource linked list
2711 resource = findResource((OCResource *)handle);
2714 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2715 return OC_STACK_ERROR;
2719 resource->entityHandler = entityHandler;
2721 #ifdef WITH_PRESENCE
2722 if(presenceResource.handle)
2724 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2725 SendPresenceNotification(resource->rsrcType);
2733 * Get the entity handler for a resource.
2735 * @param handle - handle of resource
2738 * entity handler - if resource found
2739 * NULL - resource not found
2741 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
2743 OCResource *resource = NULL;
2745 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2747 // Use the handle to find the resource in the resource linked list
2748 resource = findResource((OCResource *)handle);
2751 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2756 return resource->entityHandler;
2759 void incrementSequenceNumber(OCResource * resPtr)
2761 // Increment the sequence number
2762 resPtr->sequenceNum += 1;
2763 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2765 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2771 * Notify Presence subscribers that a resource has been modified
2773 * @param resourceType - Handle to the resourceType linked list of resource
2774 * that was modified.
2775 * @param qos - Quality Of Service
2778 * OC_STACK_OK - no errors
2779 * OC_STACK_ERROR - stack process error
2781 #ifdef WITH_PRESENCE
2784 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
2786 OCResource *resPtr = NULL;
2787 OCStackResult result = OC_STACK_ERROR;
2788 OCMethod method = OC_REST_PRESENCE;
2789 uint32_t maxAge = 0;
2790 resPtr = findResource((OCResource *) presenceResource.handle);
2793 return OC_STACK_NO_RESOURCE;
2796 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
2798 maxAge = presenceResource.presenceTTL;
2800 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
2807 * Send Stop Notification to Presence subscribers
2810 * OC_STACK_OK - no errors
2811 * OC_STACK_ERROR - stack process error
2815 OCStackResult SendStopNotification()
2817 OCResource *resPtr = NULL;
2818 OCStackResult result = OC_STACK_ERROR;
2819 OCMethod method = OC_REST_PRESENCE;
2820 resPtr = findResource((OCResource *) presenceResource.handle);
2823 return OC_STACK_NO_RESOURCE;
2826 // maxAge is 0. ResourceType is NULL.
2827 result = SendAllObserverNotification(method, resPtr, 0, NULL, OC_LOW_QOS);
2832 #endif // WITH_PRESENCE
2834 * Notify observers that an observed value has changed.
2836 * @param handle - handle of resource
2839 * OC_STACK_OK - no errors
2840 * OC_STACK_NO_RESOURCE - invalid resource handle
2841 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
2843 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
2846 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2848 OCResource *resPtr = NULL;
2849 OCStackResult result = OC_STACK_ERROR;
2850 OCMethod method = OC_REST_NOMETHOD;
2851 uint32_t maxAge = 0;
2853 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2854 #ifdef WITH_PRESENCE
2855 if(handle == presenceResource.handle)
2859 #endif // WITH_PRESENCE
2860 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2862 // Verify that the resource exists
2863 resPtr = findResource ((OCResource *) handle);
2866 return OC_STACK_NO_RESOURCE;
2870 //only increment in the case of regular observing (not presence)
2871 incrementSequenceNumber(resPtr);
2872 method = OC_REST_OBSERVE;
2873 maxAge = MAX_OBSERVE_AGE;
2874 #ifdef WITH_PRESENCE
2875 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
2877 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
2884 OCNotifyListOfObservers (OCResourceHandle handle,
2885 OCObservationId *obsIdList,
2886 uint8_t numberOfIds,
2887 const char *notificationJSONPayload,
2888 OCQualityOfService qos)
2890 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
2892 OCResource *resPtr = NULL;
2893 //TODO: we should allow the server to define this
2894 uint32_t maxAge = MAX_OBSERVE_AGE;
2896 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2897 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
2898 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
2900 // Verify that the resource exists
2901 resPtr = findResource ((OCResource *) handle);
2902 if (NULL == resPtr || myStackMode == OC_CLIENT)
2904 return OC_STACK_NO_RESOURCE;
2908 incrementSequenceNumber(resPtr);
2910 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
2911 notificationJSONPayload, maxAge, qos));
2915 * Send a response to a request.
2916 * The response can be a regular, slow, or block (i.e. a response that
2917 * is too large to be sent in a single PDU and must span multiple transmissions)
2919 * @param response - pointer to structure that contains response parameters
2922 * OC_STACK_OK - No errors; Success
2923 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
2924 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
2925 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
2926 * persistent response buffer is necessary
2928 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
2930 OCStackResult result = OC_STACK_ERROR;
2931 OCServerRequest *serverRequest = NULL;
2933 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
2935 // Validate input parameters
2936 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
2937 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
2939 // TODO: Placeholder for creating a response entry when implementing
2940 // block transfer feature
2942 // If a response payload is present, check if block transfer is required
2943 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
2944 (const char *)ehResponse->payload, ehResponse->payloadSize))
2946 OC_LOG(INFO, TAG, PCF("Block transfer required"));
2948 // Persistent response buffer is needed for block transfer
2949 if (!ehResponse->persistentBufferFlag)
2951 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
2952 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
2954 // TODO: Placeholder for block transfer handling
2955 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
2956 // when implementing the block transfer feature
2961 // Get pointer to request info
2962 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
2965 result = serverRequest->ehResponseHandler(ehResponse);
2972 * Cancel a response. Applies to a block response
2974 * @param responseHandle - response handle set by stack in OCServerResponse after
2975 * OCDoResponse is called
2978 * OC_STACK_OK - No errors; Success
2979 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
2981 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
2983 OCStackResult result = OC_STACK_NOTIMPL;
2985 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
2987 // TODO: validate response handle
2992 //-----------------------------------------------------------------------------
2993 // Private internal function definitions
2994 //-----------------------------------------------------------------------------
2996 * Generate handle of OCDoResource invocation for callback management.
2998 static OCDoHandle GenerateInvocationHandle()
3000 OCDoHandle handle = NULL;
3001 // Generate token here, it will be deleted when the transaction is deleted
3002 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3005 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3010 #ifdef WITH_PRESENCE
3011 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3012 OCResourceProperty resourceProperties, uint8_t enable)
3014 if (resourceProperties
3015 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
3017 OC_LOG(ERROR, TAG, PCF("Invalid property"));
3018 return OC_STACK_INVALID_PARAM;
3022 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3026 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3033 * Initialize resource data structures, variables, etc.
3035 OCStackResult initResources()
3037 OCStackResult result = OC_STACK_OK;
3038 // Init application resource vars
3039 headResource = NULL;
3040 tailResource = NULL;
3041 // Init Virtual Resources
3042 #ifdef WITH_PRESENCE
3043 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
3044 //presenceResource.token = OCGenerateCoAPToken();
3045 result = OCCreateResource(&presenceResource.handle,
3046 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3051 //make resource inactive
3052 result = OCChangeResourceProperty(
3053 &(((OCResource *) presenceResource.handle)->resourceProperties),
3060 * Add a resource to the end of the linked list of resources.
3062 * @param resource - resource to be added
3064 void insertResource(OCResource *resource)
3066 if (!headResource) {
3067 headResource = resource;
3068 tailResource = resource;
3072 tailResource->next = resource;
3073 tailResource = resource;
3075 resource->next = NULL;
3079 * Find a resource in the linked list of resources.
3081 * @param resource - resource to be found
3083 * NULL - resource not found
3084 * pointer to resource - pointer to resource that was found in the linked list
3086 OCResource *findResource(OCResource *resource)
3088 OCResource *pointer = headResource;
3092 if (pointer == resource)
3096 pointer = pointer->next;
3101 void deleteAllResources()
3103 OCResource *pointer = headResource;
3104 OCResource *temp = NULL;
3108 temp = pointer->next;
3109 #ifdef WITH_PRESENCE
3110 if(pointer != (OCResource *) presenceResource.handle)
3112 #endif // WITH_PRESENCE
3113 deleteResource(pointer);
3114 #ifdef WITH_PRESENCE
3116 #endif // WITH_PRESENCE
3120 #ifdef WITH_PRESENCE
3121 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3122 // presence notification attributed to their deletion to be processed.
3123 deleteResource((OCResource *) presenceResource.handle);
3124 #endif // WITH_PRESENCE
3128 * Delete the resource from the linked list.
3130 * @param resource - resource to be deleted
3132 * OC_STACK_ERROR - error
3133 * OC_STACK_OK - success
3135 OCStackResult deleteResource(OCResource *resource)
3137 OCResource *prev = NULL;
3138 OCResource *temp = NULL;
3140 temp = headResource;
3143 if (temp == resource)
3145 // Invalidate all Resource Properties.
3146 resource->resourceProperties = (OCResourceProperty) 0;
3147 #ifdef WITH_PRESENCE
3148 if(resource != (OCResource *) presenceResource.handle)
3150 #endif // WITH_PRESENCE
3151 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3152 #ifdef WITH_PRESENCE
3155 if(presenceResource.handle)
3157 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3158 if(resource != (OCResource *) presenceResource.handle)
3160 SendPresenceNotification(resource->rsrcType);
3164 SendPresenceNotification(NULL);
3168 // Only resource in list.
3169 if (temp == headResource && temp == tailResource)
3171 headResource = NULL;
3172 tailResource = NULL;
3175 else if (temp == headResource)
3177 headResource = temp->next;
3180 else if (temp == tailResource)
3182 tailResource = prev;
3183 tailResource->next = NULL;
3187 prev->next = temp->next;
3190 deleteResourceElements(temp);
3201 return OC_STACK_ERROR;
3205 * Delete all of the dynamically allocated elements that were created for the resource.
3207 * @param resource - specified resource
3209 void deleteResourceElements(OCResource *resource)
3217 OCFree(resource->uri);
3219 // Delete resourcetype linked list
3220 deleteResourceType(resource->rsrcType);
3222 // Delete resourceinterface linked list
3223 deleteResourceInterface(resource->rsrcInterface);
3227 * Delete all of the dynamically allocated elements that were created for the resource type.
3229 * @param resourceType - specified resource type
3231 void deleteResourceType(OCResourceType *resourceType)
3233 OCResourceType *pointer = resourceType;
3234 OCResourceType *next = NULL;
3238 next = pointer->next;
3239 OCFree(pointer->resourcetypename);
3246 * Delete all of the dynamically allocated elements that were created for the resource interface.
3248 * @param resourceInterface - specified resource interface
3250 void deleteResourceInterface(OCResourceInterface *resourceInterface)
3252 OCResourceInterface *pointer = resourceInterface;
3253 OCResourceInterface *next = NULL;
3257 next = pointer->next;
3258 OCFree(pointer->name);
3265 * Insert a resource type into a resource's resource type linked list.
3267 * @param resource - resource where resource type is to be inserted
3268 * @param resourceType - resource type to be inserted
3270 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
3272 OCResourceType *pointer = NULL;
3274 if (resource && !resource->rsrcType)
3276 resource->rsrcType = resourceType;
3282 pointer = resource->rsrcType;
3286 pointer = resourceType;
3288 while (pointer->next)
3290 pointer = pointer->next;
3292 pointer->next = resourceType;
3294 resourceType->next = NULL;
3298 * Get a resource type at the specified index within a resource.
3300 * @param handle - handle of resource
3301 * @param index - index of resource type
3304 * resourcetype - if found
3307 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
3309 OCResource *resource = NULL;
3310 OCResourceType *pointer = NULL;
3312 // Find the specified resource
3313 resource = findResource((OCResource *) handle);
3319 // Make sure a resource has a resourcetype
3320 if (!resource->rsrcType)
3325 // Iterate through the list
3326 pointer = resource->rsrcType;
3327 for(uint8_t i = 0; i< index && pointer; ++i)
3329 pointer = pointer->next;
3335 * Finds a resource type in an OCResourceType link-list.
3337 * @param resourceTypeList - the link-list to be searched through
3338 * @param resourceTypeName - the key to search for
3341 * resourceType that matches the key (ie. resourceTypeName)
3342 * NULL - either an invalid parameter or this function was unable to find the key.
3344 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3346 if(resourceTypeList && resourceTypeName)
3348 OCResourceType * rtPointer = resourceTypeList;
3349 while(resourceTypeName && rtPointer)
3351 if(rtPointer->resourcetypename &&
3352 strcmp(resourceTypeName, (const char *)
3353 (rtPointer->resourcetypename)) == 0)
3357 rtPointer = rtPointer->next;
3364 * Insert a resource interface into a resource's resource interface linked list.
3366 * @param resource - resource where resource interface is to be inserted
3367 * @param resourceInterface - resource interface to be inserted
3369 void insertResourceInterface(OCResource *resource,
3370 OCResourceInterface *resourceInterface)
3372 OCResourceInterface *pointer = NULL;
3373 if (!resource->rsrcInterface)
3375 resource->rsrcInterface = resourceInterface;
3379 pointer = resource->rsrcInterface;
3380 while (pointer->next)
3382 pointer = pointer->next;
3384 pointer->next = resourceInterface;
3386 resourceInterface->next = NULL;
3390 * Get a resource interface at the specified index within a resource.
3392 * @param handle - handle of resource
3393 * @param index - index of resource interface
3396 * resourceinterface - if found
3399 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3402 OCResource *resource = NULL;
3403 OCResourceInterface *pointer = NULL;
3405 // Find the specified resource
3406 resource = findResource((OCResource *) handle);
3412 // Make sure a resource has a resourceinterface
3413 if (!resource->rsrcInterface)
3418 // Iterate through the list
3419 pointer = resource->rsrcInterface;
3421 for (uint8_t i = 0; i < index && pointer; ++i)
3423 pointer = pointer->next;
3429 * Determine if a request/response must be sent in a block transfer because it is too large to be
3430 * sent in a single PDU. This function can be used for either a request or a response
3432 * @param request - NULL or pointer to request
3433 * @param response - NULL or pointer to response
3434 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
3435 * the length of the request/response
3438 * 0 - packet transfer NOT required (i.e. normal request/response)
3439 * 1 - packet transfer required (i.e. block transfer needed)
3441 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
3445 // Determine if we are checking a request or a response
3448 // If size is greater than 0, use it for the request size value, otherwise
3449 // assume request is null terminated and use strlen for size value
3450 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
3457 // If size is greater than 0, use it for the response size value, otherwise
3458 // assume response is null terminated and use strlen for size value
3459 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3468 * Retrieves a resource type based upon a query contains only just one
3469 * resource attribute (and that has to be of type "rt").
3471 * @remark This API malloc's memory for the resource type. Do not malloc resourceType
3472 * before passing in.
3474 * @param query - The query part of the URI
3475 * @param resourceType - The resource type to be populated; pass by reference.
3478 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
3479 * OC_STACK_OK - Success
3481 OCStackResult getResourceType(const char * query, char** resourceType)
3485 return OC_STACK_INVALID_PARAM;
3488 OCStackResult result = OC_STACK_ERROR;
3490 if(strncmp(query, "rt=", 3) == 0)
3492 *resourceType = (char *) OCMalloc(strlen(query)-3 + 1);
3495 result = OC_STACK_NO_MEMORY;
3497 strcpy((char *)*resourceType, ((const char *)&query[3]));
3498 result = OC_STACK_OK;
3504 OCStackResult getQueryFromUri(const char * uri, char** query, char ** newURI)
3508 return OC_STACK_INVALID_URI;
3510 if(!query || !newURI)
3512 return OC_STACK_INVALID_PARAM;
3514 char* strTokPtr = NULL;
3515 char * leftToken = NULL;
3516 char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3521 strcpy(tempURI, uri);
3523 leftToken = strtok_r(tempURI, "?", &strTokPtr);
3525 //TODO-CA: This could be simplified. Clean up required.
3526 while(leftToken != NULL)
3528 if(strncmp(leftToken, "rt=", 3) == 0 || strncmp(leftToken, "if=", 3) == 0)
3530 *query = (char *) OCMalloc(strlen(leftToken) + 1);
3536 strcpy(*query, leftToken);
3539 leftToken = strtok_r(NULL, "?", &strTokPtr);
3547 return OC_STACK_NO_MEMORY;
3550 const ServerID OCGetServerInstanceID(void)
3552 static bool generated = false;
3553 static ServerID sid;
3559 sid = OCGetRandom();
3564 const char* OCGetServerInstanceIDString(void)
3566 // max printed length of a base 10
3567 // uint32 is 10 characters, so 11 includes null.
3568 // This will change as the representation gets switched
3570 static char buffer[11];
3572 if (snprintf(buffer, sizeof(buffer),"%u", OCGetServerInstanceID()) < 0)
3580 /// Retrieve the IPv4 address embedded inside OCDev address data structure
3581 int32_t OCDevAddrToIPv4Addr(OCDevAddr *ipAddr, uint8_t *a, uint8_t *b,
3582 uint8_t *c, uint8_t *d )
3584 if ( !ipAddr || !a || !b || !c || !d )
3586 OC_LOG(FATAL, TAG, PCF("Invalid argument"));
3587 return OC_STACK_INVALID_PARAM;
3590 *a = ipAddr->addr[0];
3591 *b = ipAddr->addr[1];
3592 *c = ipAddr->addr[2];
3593 *d = ipAddr->addr[3];
3599 /// Retrieve the IPv4 address embedded inside OCDev address data structure
3600 int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port)
3602 if ( !ipAddr || !port )
3604 OC_LOG(FATAL, TAG, PCF("Invalid argument"));
3605 return OC_STACK_INVALID_PARAM;
3608 *port = (ipAddr->addr[5]<< 8) | ipAddr->addr[4];
3614 * Attempts to initialize every network interface that the CA Layer might have compiled in.
3616 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
3617 * return something other than @ref CA_STATUS_OK, then this function fails.
3620 * CA_STATUS_OK - Success
3621 * CA_NOT_SUPPORTED or CA_STATUS_FAILED - None of the transports successfully initialized.
3623 CAResult_t OCSelectNetwork()
3625 CAResult_t retResult = CA_STATUS_FAILED;
3626 CAResult_t caResult = CA_STATUS_OK;
3628 CAConnectivityType_t connTypes[] = {
3633 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
3635 for(int i = 0; i<numConnTypes; i++)
3637 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
3638 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
3640 caResult = CASelectNetwork(connTypes[i]);
3641 if(caResult == CA_STATUS_OK)
3643 retResult = CA_STATUS_OK;
3648 if(retResult != CA_STATUS_OK)
3650 return caResult; // Returns error of appropriate transport that failed fatally.
3657 * Takes a @ref CAResult_t and converts it to a similar or equivalent @ref OCStackResult value.
3659 * @return @ref OCStackResult - The equivalent or similar result code to the in-param caResult.
3661 OCStackResult CAResultToOCResult(CAResult_t caResult)
3667 case CA_STATUS_INVALID_PARAM:
3668 return OC_STACK_INVALID_PARAM;
3669 case CA_ADAPTER_NOT_ENABLED:
3670 return OC_STACK_ADAPTER_NOT_ENABLED;
3671 case CA_SERVER_STARTED_ALREADY:
3673 case CA_SERVER_NOT_STARTED:
3674 return OC_STACK_ERROR;
3675 case CA_DESTINATION_NOT_REACHABLE:
3676 return OC_STACK_COMM_ERROR;
3677 case CA_SOCKET_OPERATION_FAILED:
3678 return OC_STACK_COMM_ERROR;
3679 case CA_SEND_FAILED:
3680 return OC_STACK_COMM_ERROR;
3681 case CA_RECEVIE_FAILED:
3682 return OC_STACK_COMM_ERROR;
3683 case CA_MEMORY_ALLOC_FAILED:
3684 return OC_STACK_NO_MEMORY;
3685 case CA_REQUEST_TIMEOUT:
3686 return OC_STACK_TIMEOUT;
3687 case CA_DESTINATION_DISCONNECTED:
3688 return OC_STACK_COMM_ERROR;
3689 case CA_STATUS_FAILED:
3690 return OC_STACK_ERROR;
3691 case CA_NOT_SUPPORTED:
3692 return OC_STACK_NOTIMPL;
3694 return OC_STACK_ERROR;