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;
74 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
75 static PresenceResource presenceResource;
76 uint8_t PresenceTimeOutSize = 0;
77 uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
81 OCDeviceEntityHandler defaultDeviceHandler;
82 OCStackResult getQueryFromUri(const char * uri, unsigned char** resourceType, char ** newURI);
84 //-----------------------------------------------------------------------------
86 //-----------------------------------------------------------------------------
87 #define TAG PCF("OCStack")
88 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
89 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
90 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
91 TAG, PCF(#arg " is NULL")); return (retVal); } }
92 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
95 //TODO: we should allow the server to define this
96 #define MAX_OBSERVE_AGE (0x2FFFFUL)
98 //=============================================================================
100 //=============================================================================
101 static uint32_t GetTime(float afterSeconds)
105 return now + (uint32_t)(afterSeconds * COAP_TICKS_PER_SECOND);
108 static OCStackResult FormOCResponse(OCResponse * * responseLoc,
111 unsigned char * fullUri,
112 unsigned char * rcvdUri,
113 CAToken_t * rcvdToken,
114 OCClientResponse * clientResponse,
115 unsigned char * bufRes)
117 OCResponse * response = (OCResponse *) OCMalloc(sizeof(OCResponse));
120 return OC_STACK_NO_MEMORY;
122 response->cbNode = cbNode;
123 response->maxAge = maxAge;
124 response->fullUri = fullUri;
125 response->rcvdUri = rcvdUri;
126 response->rcvdToken = rcvdToken;
127 response->clientResponse = clientResponse;
128 response->bufRes = bufRes;
130 *responseLoc = response;
134 //-----------------------------------------------------------------------------
135 // Internal API function
136 //-----------------------------------------------------------------------------
138 // This internal function is called to update the stack with the status of
139 // observers and communication failures
140 OCStackResult OCStackFeedBack(CAToken_t * token, uint8_t status)
142 OCStackResult result = OC_STACK_ERROR;
143 ResourceObserver * observer = NULL;
144 OCEntityHandlerRequest ehRequest = {0};
148 case OC_OBSERVER_NOT_INTERESTED:
149 OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
150 observer = GetObserverUsingToken (token);
153 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
154 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
155 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
156 if(result != OC_STACK_OK)
160 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
162 //observer is not observing anymore
163 result = DeleteObserverUsingToken (token);
164 if(result == OC_STACK_OK)
166 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
170 result = OC_STACK_OK;
171 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
174 case OC_OBSERVER_STILL_INTERESTED:
175 //observer is still interested
176 OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
177 notifications, reset the failedCount"));
178 observer = GetObserverUsingToken (token);
181 observer->forceHighQos = 0;
182 observer->failedCommCount = 0;
183 result = OC_STACK_OK;
187 result = OC_STACK_OBSERVER_NOT_FOUND;
190 case OC_OBSERVER_FAILED_COMM:
191 //observer is not reachable
192 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
193 observer = GetObserverUsingToken (token);
196 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
198 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
199 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
200 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
201 if(result != OC_STACK_OK)
203 return OC_STACK_ERROR;
205 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
206 //observer is unreachable
207 result = DeleteObserverUsingToken (token);
208 if(result == OC_STACK_OK)
210 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
214 result = OC_STACK_OK;
215 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
220 observer->failedCommCount++;
221 result = OC_STACK_CONTINUE;
223 observer->forceHighQos = 1;
224 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
228 OC_LOG(ERROR, TAG, PCF("Unknown status"));
229 result = OC_STACK_ERROR;
235 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
237 OCStackResult ret = OC_STACK_ERROR;
245 ret = OC_STACK_RESOURCE_CREATED;
248 ret = OC_STACK_RESOURCE_DELETED;
251 ret = OC_STACK_INVALID_QUERY;
254 ret = OC_STACK_INVALID_OPTION;
257 ret = OC_STACK_NO_RESOURCE;
265 OCStackResult OCToCAConnectivityType(OCConnectivityType ocConType, CAConnectivityType_t* caConType)
267 OCStackResult ret = OC_STACK_OK;
272 *caConType = CA_ETHERNET;
275 *caConType = CA_WIFI;
284 // Currently OC_ALL represents WIFI and ETHERNET
285 // Add other connectivity types as they are enabled in future
286 *caConType = (CAConnectivityType_t) (CA_WIFI|CA_ETHERNET);
289 ret = OC_STACK_INVALID_PARAM;
295 OCStackResult CAToOCConnectivityType(CAConnectivityType_t caConType, OCConnectivityType *ocConType)
297 OCStackResult ret = OC_STACK_OK;
302 *ocConType = OC_ETHERNET;
305 *ocConType = OC_WIFI;
314 ret = OC_STACK_INVALID_PARAM;
320 // update response.addr appropriately from endPoint.addressInfo
321 OCStackResult UpdateResponseAddr(OCClientResponse *response, const CARemoteEndpoint_t* endPoint)
323 OCStackResult ret = OC_STACK_ERROR;
324 static OCDevAddr address = {0};
326 char * savePtr = NULL;
327 char * cpAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
330 ret = OC_STACK_NO_MEMORY;
333 memcpy(cpAddress, endPoint->addressInfo.IP.ipAddress,
334 strlen(endPoint->addressInfo.IP.ipAddress) + 1);
336 // Grabs the first three numbers from the IPv4 address and replaces dots
337 for(int i=0; i<4; i++)
339 tok = strtok_r(i==0 ? cpAddress : NULL, ".", &savePtr);
343 ret = OC_STACK_ERROR;
346 address.addr[i] = atoi(tok);
349 memcpy(&address.addr[4], &endPoint->addressInfo.IP.port, sizeof(uint32_t));
353 response->addr = &address;
354 ret = CAToOCConnectivityType(endPoint->connectivityType, &(response->connType));
358 OC_LOG(ERROR, TAG, PCF("OCClientResponse is NULL!"));
365 void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge, char** resType)
369 // The format of the payload is {"oc":[%u:%u:%s]}
370 // %u : sequence number,
372 // %s : Resource Type (Optional)
373 tok = strtok_r(payload, "[:]}", &savePtr);
374 payload[strlen(payload)] = ':';
375 tok = strtok_r(NULL, "[:]}", &savePtr);
376 payload[strlen((char *)payload)] = ':';
377 *seqNum = (uint32_t) atoi(tok);
378 tok = strtok_r(NULL, "[:]}", &savePtr);
379 *maxAge = (uint32_t) atoi(tok);
380 tok = strtok_r(NULL, "[:]}",&savePtr);
384 *resType = (char *)OCMalloc(strlen(tok));
389 payload[strlen((char *)payload)] = ':';
390 strcpy(*resType, tok);
391 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s", *resType);
393 payload[strlen((char *)payload)] = ']';
396 OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
397 const CAResponseInfo_t* responseInfo)
399 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
400 ClientCB * cbNode = NULL;
401 char *resourceTypeName = NULL;
402 OCClientResponse response;
403 OCStackResult result = OC_STACK_ERROR;
404 uint32_t lowerBound = 0;
405 uint32_t higherBound = 0;
408 char *fullUri = NULL;
409 char *ipAddress = NULL;
410 int presenceSubscribe = 0;
411 int multicastPresenceSubscribe = 0;
413 if (responseInfo->result != CA_SUCCESS)
415 OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
416 return OC_STACK_ERROR;
419 fullUri = (char *) OCMalloc(MAX_URI_LENGTH );
423 OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for fullUri"));
424 result = OC_STACK_NO_MEMORY;
428 ipAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
430 if(NULL == ipAddress)
432 OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for ipAddress"));
433 result = OC_STACK_NO_MEMORY;
437 strncpy(ipAddress, endPoint->addressInfo.IP.ipAddress,
438 strlen(endPoint->addressInfo.IP.ipAddress));
439 ipAddress[strlen(endPoint->addressInfo.IP.ipAddress)] = '\0';
441 snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", ipAddress, endPoint->addressInfo.IP.port,
444 cbNode = GetClientCB(NULL, NULL, (unsigned char *) fullUri);
448 presenceSubscribe = 1;
452 snprintf(fullUri, MAX_URI_LENGTH, "%s%s", OC_MULTICAST_IP, endPoint->resourceUri);
453 cbNode = GetClientCB(NULL, NULL, (unsigned char *) fullUri);
456 multicastPresenceSubscribe = 1;
460 if(!presenceSubscribe && !multicastPresenceSubscribe)
462 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
463 ------------ ignoring"));
467 // No payload to the application in case of presence
468 response.resJSONPayload = NULL;
469 response.result = OC_STACK_OK;
471 result = UpdateResponseAddr(&response, endPoint);
472 if(result != OC_STACK_OK)
477 if(responseInfo->info.payload)
479 parsePresencePayload(responseInfo->info.payload,
480 &(response.sequenceNumber),
487 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
488 response.result = OC_STACK_PRESENCE_STOPPED;
491 OCFree(cbNode->presence->timeOut);
492 OCFree(cbNode->presence);
493 cbNode->presence = NULL;
496 else if(presenceSubscribe)
498 if(!cbNode->presence)
500 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
501 VERIFY_NON_NULL_V(cbNode->presence);
502 cbNode->presence->timeOut = NULL;
503 cbNode->presence->timeOut = (uint32_t *)
504 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
505 if(!(cbNode->presence->timeOut)){
506 OCFree(cbNode->presence);
507 result = OC_STACK_NO_MEMORY;
511 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %u", GetTime(0));
512 cbNode->presence->TTL = maxAge;
513 for(int index = 0; index < PresenceTimeOutSize; index++)
515 lowerBound = GetTime(((float)(PresenceTimeOut[index])
516 /(float)100)*(float)cbNode->presence->TTL);
517 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
518 /(float)100)*(float)cbNode->presence->TTL);
519 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
520 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
521 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
522 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
523 cbNode->presence->timeOut[index]);
525 cbNode->presence->TTLlevel = 0;
526 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
527 if(cbNode->sequenceNumber == response.sequenceNumber)
529 OC_LOG(INFO, TAG, PCF("===============No presence change"));
532 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
533 cbNode->sequenceNumber = response.sequenceNumber;
535 // Ensure that a filter is actually applied.
536 if(resourceTypeName && cbNode->filterResourceType)
538 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
546 // This is the multicast case
548 OCMulticastNode* mcNode = NULL;
549 mcNode = GetMCPresenceNode((const unsigned char *)fullUri);
553 if(mcNode->nonce == response.sequenceNumber)
555 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
558 mcNode->nonce = response.sequenceNumber;
562 uint32_t uriLen = strlen((char*)fullUri);
563 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
566 memcpy(uri, fullUri, (uriLen + 1));
571 PCF("===============No Memory for URI to store in the presence node"));
572 result = OC_STACK_NO_MEMORY;
575 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri, response.sequenceNumber);
576 if(result == OC_STACK_NO_MEMORY)
579 PCF("===============No Memory for Multicast Presence Node"));
580 result = OC_STACK_NO_MEMORY;
585 // Ensure that a filter is actually applied.
586 if(resourceTypeName && cbNode->filterResourceType)
588 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
595 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
597 if (cbResult == OC_STACK_DELETE_TRANSACTION)
599 FindAndDeleteClientCB(cbNode);
605 OCFree(resourceTypeName);
610 //This function will be called back by CA layer when a response is received
611 void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
613 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
615 OCStackApplicationResult appResult = OC_STACK_DELETE_TRANSACTION;
619 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
623 if(NULL == responseInfo)
625 OC_LOG(ERROR, TAG, PCF("responseInfo is NULL"));
629 if(strcmp(endPoint->resourceUri, OC_PRESENCE_URI) == 0)
631 HandlePresenceResponse(endPoint, responseInfo);
635 ClientCB *cbNode = GetClientCB((CAToken_t *)&(responseInfo->info.token), NULL, NULL);
639 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
640 OCClientResponse response;
642 OCStackResult result = UpdateResponseAddr(&response, endPoint);
643 if(result != OC_STACK_OK)
645 OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint"));
649 response.result = CAToOCStackResult(responseInfo->result);
650 response.resJSONPayload = (unsigned char*)responseInfo->info.payload;
651 response.numRcvdVendorSpecificHeaderOptions = 0;
652 if(responseInfo->info.numOptions > 0)
655 //First option always with option ID is OC_COAP_OPTION_OBSERVE if it is available.
656 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
658 memcpy (&(response.sequenceNumber),
659 &(responseInfo->info.options[0].optionData), sizeof(uint32_t));
660 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
665 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
668 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
670 OC_LOG(ERROR, TAG, PCF("#header options are more than MAX_HEADER_OPTIONS"));
674 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
676 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
677 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
680 appResult = cbNode->callBack(cbNode->context,
681 cbNode->handle, &response);
682 if (appResult == OC_STACK_DELETE_TRANSACTION)
684 FindAndDeleteClientCB(cbNode);
687 OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload);
688 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
691 //This function will be called back by CA layer when a request is received
692 void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
694 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
697 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
703 OC_LOG(ERROR, TAG, PCF("requestInfo is NULL"));
707 OCStackResult requestResult = OC_STACK_ERROR;
709 if(myStackMode == OC_CLIENT)
711 //TODO: should the client be responding to requests?
715 OCServerProtocolRequest serverRequest;
717 memset (&serverRequest, 0, sizeof(OCServerProtocolRequest));
718 OC_LOG_V(INFO, TAG, PCF("***** Endpoint URI ***** : %s\n"), (char*)endPoint->resourceUri);
720 char * newUri = (char *)endPoint->resourceUri;
721 unsigned char * query = NULL;
722 getQueryFromUri(endPoint->resourceUri, &query, &newUri);
723 OC_LOG_V(INFO, TAG, PCF("**********URI without query ****: %s\n"), newUri);
724 OC_LOG_V(INFO, TAG, PCF("**********Query ****: %s\n"), query);
726 memcpy (&(serverRequest.resourceUrl), newUri, strlen(newUri));
730 memcpy (&(serverRequest.query), query, strlen((char*)query));
732 //copy request payload
733 if (requestInfo->info.payload)
735 serverRequest.reqTotalSize = strlen(requestInfo->info.payload) + 1;
736 memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
737 strlen(requestInfo->info.payload));
738 serverRequest.reqTotalSize = strlen((const char *)requestInfo->info.payload) + 1;
742 serverRequest.reqTotalSize = 1;
745 switch (requestInfo->method)
749 serverRequest.method = OC_REST_GET;
754 serverRequest.method = OC_REST_PUT;
759 serverRequest.method = OC_REST_POST;
764 serverRequest.method = OC_REST_DELETE;
769 OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
774 OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d", CA_MAX_TOKEN_LEN);
775 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token, CA_MAX_TOKEN_LEN);
777 serverRequest.requestToken = (CAToken_t)OCMalloc(CA_MAX_TOKEN_LEN+1);
779 if (!serverRequest.requestToken)
781 OC_LOG(FATAL, TAG, "Server Request Token is NULL");
784 memset(serverRequest.requestToken, 0, CA_MAX_TOKEN_LEN + 1);
785 memcpy(serverRequest.requestToken, requestInfo->info.token, CA_MAX_TOKEN_LEN);
787 if (requestInfo->info.type == CA_MSG_CONFIRM)
789 serverRequest.qos = OC_HIGH_QOS;
791 else if (requestInfo->info.type == CA_MSG_NONCONFIRM)
793 serverRequest.qos = OC_LOW_QOS;
795 else if (requestInfo->info.type == CA_MSG_ACKNOWLEDGE)
797 // TODO-CA: Need to handle this
799 else if (requestInfo->info.type == CA_MSG_RESET)
801 // TODO-CA: Need to handle this
803 // CA does not need the following 3 fields
804 serverRequest.coapID = 0;
805 serverRequest.delayedResNeeded = 0;
806 serverRequest.secured = endPoint->isSecured;
809 serverRequest.addressInfo = endPoint->addressInfo;
810 serverRequest.connectivityType = endPoint->connectivityType;
812 // copy vendor specific header options
813 // TODO-CA: CA is including non-vendor header options as well, like observe.
814 // Need to filter those out
815 uint8_t tempNum = (requestInfo->info.numOptions);
816 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
817 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
820 PCF("The request info numOptions is greater than MAX_HEADER_OPTIONS"));
821 OCFree(serverRequest.requestToken);
824 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
825 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
827 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
828 sizeof(CAHeaderOption_t)*tempNum);
831 requestResult = HandleStackRequests (&serverRequest);
832 if(requestResult != OC_STACK_OK)
834 OC_LOG(ERROR, TAG, PCF("HandleStackRequests failed"));
836 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
839 //This function will be called back by occoap layer when a request is received
840 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
842 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
843 OCStackResult result = OC_STACK_ERROR;
844 ResourceHandling resHandling;
845 OCResource *resource;
848 OC_LOG(ERROR, TAG, PCF("protocolRequest is NULL"));
849 return OC_STACK_INVALID_PARAM;
852 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
855 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
856 result = AddServerRequest(&request, protocolRequest->coapID,
857 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
858 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
859 protocolRequest->observationOption, protocolRequest->qos,
860 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
861 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
862 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
863 protocolRequest->reqTotalSize,
864 &protocolRequest->addressInfo, protocolRequest->connectivityType);
865 if (OC_STACK_OK != result)
867 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
870 VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
872 if(!protocolRequest->reqMorePacket)
874 request->requestComplete = 1;
879 OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
882 if(request->requestComplete)
884 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
885 result = DetermineResourceHandling (request, &resHandling, &resource);
886 if (result == OC_STACK_OK)
888 result = ProcessRequest(resHandling, resource, request);
892 result = OC_STACK_ERROR;
897 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
898 result = OC_STACK_CONTINUE;
903 //This function will be called back by occoap layer when a response is received
904 OCStackResult HandleStackResponses(OCResponse * response)
906 OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)"));
907 OCStackResult result = OC_STACK_OK;
908 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
909 uint8_t isObserveNotification = 0;
910 ClientCB * cbNode = NULL;
913 OC_LOG(ERROR, TAG, PCF("response is NULL"));
914 return OC_STACK_INVALID_PARAM;
917 uint8_t isPresenceNotification = 0;
918 uint8_t isMulticastPresence = 0;
919 char * resourceTypeName = NULL;
920 uint32_t lowerBound = 0;
921 uint32_t higherBound = 0;
923 unsigned char * bufRes = response->bufRes;
924 #endif // WITH_PRESENCE
926 cbNode = response->cbNode;
929 cbNode = GetClientCB(response->rcvdToken, NULL, NULL);
932 if(response->clientResponse->sequenceNumber >= OC_OFFSET_SEQUENCE_NUMBER)
934 isObserveNotification = 1;
935 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
938 OC_LOG_V(DEBUG, TAG, "The sequenceNumber/NONCE of this response %u",
939 response->clientResponse->sequenceNumber);
940 OC_LOG_V(DEBUG, TAG, "The maxAge/TTL of this response %u", response->maxAge);
941 OC_LOG_V(DEBUG, TAG, "The response received is %s", bufRes);
944 if(!strcmp((char *)response->rcvdUri, (char *)OC_PRESENCE_URI)){
945 isPresenceNotification = 1;
948 result = OC_STACK_INVALID_PARAM;
952 tok = strtok_r((char *)bufRes, "[:]}", &savePtr);
953 bufRes[strlen((char *)bufRes)] = ':';
954 tok = strtok_r(NULL, "[:]}", &savePtr);
955 bufRes[strlen((char *)bufRes)] = ':';
956 response->clientResponse->sequenceNumber = (uint32_t )atoi(tok);
957 OC_LOG_V(DEBUG, TAG, "The received NONCE is %u", response->clientResponse->sequenceNumber);
958 tok = strtok_r(NULL, "[:]}", &savePtr);
959 response->maxAge = (uint32_t )atoi(tok);
960 OC_LOG_V(DEBUG, TAG, "The received TTL is %u", response->maxAge);
961 tok = strtok_r(NULL, "[:]}", &savePtr);
964 resourceTypeName = (char *)OCMalloc(strlen(tok));
965 if(!resourceTypeName)
969 bufRes[strlen((char *)bufRes)] = ':';
970 strcpy(resourceTypeName, tok);
971 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
974 bufRes[strlen((char *)bufRes)] = ']';
977 // Check if the application subcribed for presence
980 cbNode = GetClientCB(NULL, NULL, response->fullUri);
983 // Check if application subscribed for multicast presence
986 snprintf((char *)response->fullUri, MAX_URI_LENGTH, "%s%s",
987 OC_MULTICAST_IP, response->rcvdUri);
988 cbNode = GetClientCB(NULL, NULL, response->fullUri);
991 isMulticastPresence = 1;
992 isPresenceNotification = 0;
996 if(cbNode && isPresenceNotification)
998 OC_LOG(INFO, TAG, PCF("Received a presence notification"));
999 if(!cbNode->presence)
1001 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
1002 VERIFY_NON_NULL_V(cbNode->presence);
1003 cbNode->presence->timeOut = NULL;
1004 cbNode->presence->timeOut = (uint32_t *)
1005 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1006 if(!(cbNode->presence->timeOut)){
1007 OCFree(cbNode->presence);
1008 result = OC_STACK_NO_MEMORY;
1011 if(response->maxAge == 0)
1013 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
1014 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
1015 if(cbNode->presence)
1017 OCFree(cbNode->presence->timeOut);
1018 OCFree(cbNode->presence);
1019 cbNode->presence = NULL;
1024 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %d", GetTime(0));
1025 cbNode->presence->TTL = response->maxAge;
1026 for(int index = 0; index < PresenceTimeOutSize; index++)
1028 lowerBound = GetTime(((float)(PresenceTimeOut[index])
1029 /(float)100)*(float)cbNode->presence->TTL);
1030 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
1031 /(float)100)*(float)cbNode->presence->TTL);
1032 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
1033 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
1034 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
1035 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
1036 cbNode->presence->timeOut[index]);
1038 cbNode->presence->TTLlevel = 0;
1039 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
1040 if(cbNode->sequenceNumber == response->clientResponse->sequenceNumber)
1042 OC_LOG(INFO, TAG, PCF("===============No presence change"));
1045 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
1046 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;;
1049 // Ensure that a filter is actually applied.
1050 if(resourceTypeName && cbNode->filterResourceType)
1052 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1058 else if(cbNode && isMulticastPresence)
1060 // Check if the same nonce for a given host
1061 OCMulticastNode* mcNode = NULL;
1062 mcNode = GetMCPresenceNode(response->fullUri);
1064 if(response->maxAge == 0)
1066 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
1067 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
1068 if(cbNode->presence)
1070 OCFree(cbNode->presence->timeOut);
1071 OCFree(cbNode->presence);
1072 cbNode->presence = NULL;
1075 else if(mcNode != NULL)
1077 if(mcNode->nonce == response->clientResponse->sequenceNumber)
1079 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
1080 result = OC_STACK_NO_MEMORY;
1083 mcNode->nonce = response->clientResponse->sequenceNumber;
1087 uint32_t uriLen = strlen((char*)response->fullUri);
1088 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
1091 memcpy(uri, response->fullUri, (uriLen + 1));
1096 PCF("===============No Memory for URI to store in the presence node"));
1097 result = OC_STACK_NO_MEMORY;
1100 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri,
1101 response->clientResponse->sequenceNumber);
1102 if(result == OC_STACK_NO_MEMORY)
1105 PCF("===============No Memory for Multicast Presence Node"));
1106 result = OC_STACK_NO_MEMORY;
1111 // Ensure that a filter is actually applied.
1112 if(resourceTypeName && cbNode->filterResourceType)
1114 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1121 else if(!cbNode && isPresenceNotification)
1123 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
1124 ------------ ignoring"));
1126 #endif // WITH_PRESENCE
1130 if(isObserveNotification)
1132 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
1133 //TODO: check the standard for methods to detect wrap around condition
1134 if(cbNode->method == OC_REST_OBSERVE &&
1135 (response->clientResponse->sequenceNumber <= cbNode->sequenceNumber ||
1136 (response->clientResponse->sequenceNumber > cbNode->sequenceNumber &&
1137 response->clientResponse->sequenceNumber ==
1138 MAX_SEQUENCE_NUMBER)))
1140 OC_LOG_V(DEBUG, TAG, "Observe notification came out of order. \
1141 Ignoring Incoming:%d Against Current:%d.",
1142 response->clientResponse->sequenceNumber, cbNode->sequenceNumber);
1145 if(response->clientResponse->sequenceNumber > cbNode->sequenceNumber){
1146 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;
1150 response->clientResponse->resJSONPayload = bufRes;
1152 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response->clientResponse);
1154 if (cbResult == OC_STACK_DELETE_TRANSACTION ||
1155 response->clientResponse->result == OC_STACK_COMM_ERROR ||
1156 (response->clientResponse->result == OC_STACK_RESOURCE_DELETED &&
1157 !isPresenceNotification && !isMulticastPresence))
1159 FindAndDeleteClientCB(cbNode);
1164 result = OC_STACK_ERROR;
1168 #ifdef WITH_PRESENCE
1169 OCFree(resourceTypeName);
1174 int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
1177 unsigned char *itr, *coap;
1178 uint8_t dotCount = 0;
1182 /* search for scheme */
1184 if (!isdigit((unsigned char) *ipAddrStr))
1186 coap = (unsigned char *) OC_COAP_SCHEME;
1187 while (*coap && tolower(*itr) == *coap)
1195 while (*ipAddrStr) {
1196 if (isdigit((unsigned char) *ipAddrStr))
1198 ipAddr[index] *= 10;
1199 ipAddr[index] += *ipAddrStr - '0';
1201 else if ((unsigned char) *ipAddrStr == '.')
1213 if(*ipAddrStr == ':')
1217 if (isdigit((unsigned char) *ipAddrStr))
1220 *port += *ipAddrStr - '0';
1231 if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
1242 //-----------------------------------------------------------------------------
1243 // Private internal function prototypes
1244 //-----------------------------------------------------------------------------
1246 static OCDoHandle GenerateInvocationHandle();
1247 static OCStackResult initResources();
1248 static void insertResource(OCResource *resource);
1249 static OCResource *findResource(OCResource *resource);
1250 static void insertResourceType(OCResource *resource,
1251 OCResourceType *resourceType);
1252 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
1254 static void insertResourceInterface(OCResource *resource,
1255 OCResourceInterface *resourceInterface);
1256 static OCResourceInterface *findResourceInterfaceAtIndex(
1257 OCResourceHandle handle, uint8_t index);
1258 static void deleteResourceType(OCResourceType *resourceType);
1259 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
1260 static void deleteResourceElements(OCResource *resource);
1261 static int deleteResource(OCResource *resource);
1262 static void deleteAllResources();
1263 static void incrementSequenceNumber(OCResource * resPtr);
1264 static OCStackResult verifyUriQueryLength(const char * inputUri,
1266 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
1267 OCStackResult getResourceType(const char * query, unsigned char** resourceType);
1269 //-----------------------------------------------------------------------------
1271 //-----------------------------------------------------------------------------
1274 * Initialize the OC Stack. Must be called prior to starting the stack.
1277 * IP Address of host device
1279 * Port of host device
1281 * Host device is client, server, or client-server
1284 * OC_STACK_OK - no errors
1285 * OC_STACK_ERROR - stack init error
1287 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1289 OCStackResult result = OC_STACK_ERROR;
1290 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
1293 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)))
1295 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1296 return OC_STACK_ERROR;
1301 OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
1306 //It is ok to select network to CA_WIFI for now
1308 CAResult_t caResult = CASelectNetwork(CA_ETHERNET);
1310 CAResult_t caResult = CASelectNetwork(CA_WIFI|CA_ETHERNET);
1312 if(caResult == CA_STATUS_OK)
1314 OC_LOG(INFO, TAG, PCF("CASelectNetwork to WIFI"));
1315 CARegisterHandler(HandleCARequests, HandleCAResponses);
1317 OC_LOG(INFO, TAG, PCF("CARegisterHandler..."));
1318 stackState = OC_STACK_INITIALIZED;
1319 result = OC_STACK_OK;
1323 caResult = CAStartDiscoveryServer();
1324 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
1327 caResult = CAStartListeningServer();
1328 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
1330 case OC_CLIENT_SERVER:
1331 caResult = CAStartListeningServer();
1332 if(caResult == CA_STATUS_OK)
1334 caResult = CAStartDiscoveryServer();
1336 OC_LOG(INFO, TAG, PCF("Client-server mode"));
1339 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1340 return OC_STACK_ERROR;
1345 if (caResult == CA_STATUS_OK)
1347 result = OC_STACK_OK;
1351 result = OC_STACK_ERROR;
1356 defaultDeviceHandler = NULL;
1358 #if defined(__WITH_DTLS__)
1359 caResult = CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials);
1360 result = (caResult == CA_STATUS_OK) ? OC_STACK_OK : OC_STACK_ERROR;
1361 #endif // (__WITH_DTLS__)
1363 #ifdef WITH_PRESENCE
1364 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
1365 #endif // WITH_PRESENCE
1367 if (result == OC_STACK_OK)
1369 stackState = OC_STACK_INITIALIZED;
1371 // Initialize resource
1372 if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
1374 result = initResources();
1376 if(result != OC_STACK_OK)
1378 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1384 * Stop the OC stack. Use for a controlled shutdown.
1386 * OC_STACK_OK - no errors
1387 * OC_STACK_ERROR - stack not initialized
1389 OCStackResult OCStop()
1391 OCStackResult result = OC_STACK_ERROR;
1393 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1395 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1397 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1400 else if (stackState != OC_STACK_INITIALIZED)
1402 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1403 return OC_STACK_ERROR;
1406 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1408 #ifdef WITH_PRESENCE
1409 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1410 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1411 presenceResource.presenceTTL = 0;
1412 #endif // WITH_PRESENCE
1414 // Free memory dynamically allocated for resources
1415 deleteAllResources();
1418 //CATerminate does not return any error code. It is OK to assign result to OC_STACK_OK.
1419 result = OC_STACK_OK;
1421 if (result == OC_STACK_OK)
1423 // Remove all observers
1424 DeleteObserverList();
1425 // Remove all the client callbacks
1426 DeleteClientCBList();
1427 stackState = OC_STACK_UNINITIALIZED;
1428 result = OC_STACK_OK;
1430 stackState = OC_STACK_INITIALIZED;
1431 result = OC_STACK_ERROR;
1434 // Deinit security blob
1435 DeinitOCSecurityInfo();
1437 if (result != OC_STACK_OK) {
1438 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
1445 * Map OCQualityOfService to CAMessageType
1447 * @param OCQualityOfService - Input qos.
1449 * Returns CA message type for a given qos.
1451 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
1456 return CA_MSG_CONFIRM;
1461 return CA_MSG_NONCONFIRM;
1466 * Verify the lengths of the URI and the query separately
1468 * @param inputUri - Input URI and query.
1469 * @param uriLen - The length of the initial URI with query.
1471 * Note: The '?' that appears after the URI is not considered as
1472 * a part of the query.
1474 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1478 query = strchr (inputUri, '?');
1482 if((query - inputUri) > MAX_URI_LENGTH)
1484 return OC_STACK_INVALID_URI;
1487 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1489 return OC_STACK_INVALID_QUERY;
1492 else if(uriLen > MAX_URI_LENGTH)
1494 return OC_STACK_INVALID_URI;
1500 * Discover or Perform requests on a specified resource
1501 * (specified by that Resource's respective URI).
1503 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of
1505 * @param method - @ref OCMethod to perform on the resource
1506 * @param requiredUri - URI of the resource to interact with
1507 * @param referenceUri - URI of the reference resource
1508 * @param request - JSON encoded request
1509 * @param qos - quality of service
1510 * @param cbData - struct that contains asynchronous callback function that is invoked
1511 * by the stack when discovery or resource interaction is complete
1512 * @param options - The address of an array containing the vendor specific header
1513 * header options to be sent with the request
1514 * @param numOptions - Number of vendor specific header options to be included
1517 * OC_STACK_OK - no errors
1518 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
1519 * OC_STACK_INVALID_METHOD - invalid resource method
1520 * OC_STACK_INVALID_URI - invalid required or reference URI
1522 * Note: IN case of CA, when using multicast, the required URI should not contain IP address.
1523 * Instead, it just contains the URI to the resource such as "/oc/core".
1525 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1526 const char *referenceUri, const char *request, OCConnectivityType conType,
1527 OCQualityOfService qos, OCCallbackData *cbData,
1528 OCHeaderOption * options, uint8_t numOptions)
1530 OCStackResult result = OC_STACK_ERROR;
1531 ClientCB *clientCB = NULL;
1532 unsigned char * requestUri = NULL;
1533 unsigned char * resourceType = NULL;
1534 unsigned char * query = NULL;
1535 char * newUri = (char *)requiredUri;
1536 (void) referenceUri;
1537 CARemoteEndpoint_t* endpoint = NULL;
1538 CAResult_t caResult;
1539 CAToken_t token = NULL;
1540 CAInfo_t requestData;
1541 CARequestInfo_t requestInfo;
1542 CAGroupEndpoint_t grpEnd;
1544 // To track if memory is allocated for additional header options
1545 uint8_t hdrOptionMemAlloc = 0;
1547 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1549 // Validate input parameters
1550 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1551 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1553 //TODO ("Need to form the final query by concatenating require and reference URI's");
1554 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
1556 uint16_t uriLen = strlen(requiredUri);
1558 // ToDo: We should also check if the requiredUri has a mutlicast address,
1559 // then qos has to be OC_Low_QOS
1565 case OC_REST_DELETE:
1566 case OC_REST_OBSERVE:
1567 case OC_REST_OBSERVE_ALL:
1568 case OC_REST_CANCEL_OBSERVE:
1570 #ifdef WITH_PRESENCE
1571 case OC_REST_PRESENCE:
1575 result = OC_STACK_INVALID_METHOD;
1579 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
1584 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
1586 result = OC_STACK_INVALID_PARAM;
1590 #ifdef WITH_PRESENCE
1591 if(method == OC_REST_PRESENCE)
1593 result = getQueryFromUri(requiredUri, &query, &newUri);
1596 result = getResourceType((char *) query, &resourceType);
1599 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1603 OC_LOG(DEBUG, TAG, PCF("Resource type is NULL."));
1608 OC_LOG(DEBUG, TAG, PCF("Query string is NULL."));
1610 if(result != OC_STACK_OK)
1615 #endif // WITH_PRESENCE
1617 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
1620 memcpy(requestUri, newUri, (uriLen + 1));
1624 result = OC_STACK_NO_MEMORY;
1628 *handle = GenerateInvocationHandle();
1631 result = OC_STACK_NO_MEMORY;
1635 memset(&requestData, 0, sizeof(CAInfo_t));
1636 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1637 memset(&grpEnd, 0, sizeof(CAGroupEndpoint_t));
1641 case OC_REST_OBSERVE:
1642 case OC_REST_OBSERVE_ALL:
1643 case OC_REST_CANCEL_OBSERVE:
1645 requestInfo.method = CA_GET;
1650 requestInfo.method = CA_PUT;
1655 requestInfo.method = CA_POST;
1658 case OC_REST_DELETE:
1660 requestInfo.method = CA_DELETE;
1663 #ifdef WITH_PRESENCE
1664 case OC_REST_PRESENCE:
1666 // Replacing method type with GET because "presence"
1667 // is a stack layer only implementation.
1668 requestInfo.method = CA_GET;
1673 result = OC_STACK_INVALID_METHOD;
1677 //High QoS is not supported
1678 if(qos == OC_HIGH_QOS)
1680 result = OC_STACK_INVALID_PARAM;
1685 caResult = CAGenerateToken(&token);
1686 if (caResult != CA_STATUS_OK)
1688 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1689 CADestroyToken(token);
1693 requestData.type = qualityOfServiceToMessageType(qos);
1694 requestData.token = token;
1695 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1697 result = CreateObserveHeaderOption (&(requestData.options), options,
1698 numOptions, OC_OBSERVE_REGISTER);
1699 if (result != OC_STACK_OK)
1703 hdrOptionMemAlloc = 1;
1704 requestData.numOptions = numOptions + 1;
1708 requestData.options = (CAHeaderOption_t*)options;
1709 requestData.numOptions = numOptions;
1711 requestData.payload = (char *)request;
1713 requestInfo.info = requestData;
1715 CAConnectivityType_t caConType;
1717 result = OCToCAConnectivityType((OCConnectivityType) conType, &caConType);
1718 if (result != OC_STACK_OK)
1720 OC_LOG(ERROR, TAG, PCF("Invalid Connectivity Type"));
1725 if(conType == OC_ALL)
1727 grpEnd.connectivityType = caConType;
1729 grpEnd.resourceUri = (CAURI_t) OCMalloc(uriLen + 1);
1730 if(!grpEnd.resourceUri)
1732 result = OC_STACK_NO_MEMORY;
1735 strncpy(grpEnd.resourceUri, requiredUri, (uriLen + 1));
1737 caResult = CASendRequestToAll(&grpEnd, &requestInfo);
1741 caResult = CACreateRemoteEndpoint(newUri, caConType, &endpoint);
1743 if (caResult != CA_STATUS_OK)
1745 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1749 caResult = CASendRequest(endpoint, &requestInfo);
1752 if (caResult != CA_STATUS_OK)
1754 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1758 if((result = AddClientCB(&clientCB, cbData, &token, handle, method,
1759 requestUri, resourceType)) != OC_STACK_OK)
1761 result = OC_STACK_NO_MEMORY;
1766 if(newUri != requiredUri)
1770 if (result != OC_STACK_OK)
1772 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1773 FindAndDeleteClientCB(clientCB);
1775 CADestroyRemoteEndpoint(endpoint);
1776 OCFree(grpEnd.resourceUri);
1777 if (hdrOptionMemAlloc)
1779 OCFree(requestData.options);
1785 * Cancel a request associated with a specific @ref OCDoResource invocation.
1787 * @param handle - Used to identify a specific OCDoResource invocation.
1788 * @param qos - used to specify Quality of Service (read below for more info)
1789 * @param options- used to specify vendor specific header options when sending
1790 * explicit observe cancellation
1791 * @param numOptions- Number of header options to be included
1794 * OC_STACK_OK - No errors; Success
1795 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1797 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1801 * This ftn is implemented one of two ways in the case of observation:
1803 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1804 * Remove the callback associated on client side.
1805 * When the next notification comes in from server,
1806 * reply with RESET message to server.
1807 * Keep in mind that the server will react to RESET only
1808 * if the last notification was sent ans CON
1810 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1811 * and it is associated with an observe request
1812 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1813 * Send CON Observe request to server with
1814 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1815 * Remove the callback associated on client side.
1817 OCStackResult ret = OC_STACK_OK;
1818 CARemoteEndpoint_t* endpoint = NULL;
1819 CAResult_t caResult;
1820 CAInfo_t requestData;
1821 CARequestInfo_t requestInfo;
1822 // Track if memory is allocated for additional header options
1823 uint8_t hdrOptionMemAlloc = 0;
1826 return OC_STACK_INVALID_PARAM;
1829 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1831 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1834 switch (clientCB->method)
1836 case OC_REST_OBSERVE:
1837 case OC_REST_OBSERVE_ALL:
1838 //TODO-CA : Why CA_WIFI alone?
1839 caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri, CA_WIFI,
1841 if (caResult != CA_STATUS_OK)
1843 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1844 return OC_STACK_ERROR;
1847 memset(&requestData, 0, sizeof(CAInfo_t));
1848 requestData.type = qualityOfServiceToMessageType(qos);
1849 requestData.token = clientCB->token;
1850 if (CreateObserveHeaderOption (&(requestData.options),
1851 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
1853 return OC_STACK_ERROR;
1855 hdrOptionMemAlloc = 1;
1856 requestData.numOptions = numOptions + 1;
1857 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1858 requestInfo.method = CA_GET;
1859 requestInfo.info = requestData;
1861 caResult = CASendRequest(endpoint, &requestInfo);
1862 if (caResult != CA_STATUS_OK)
1864 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1866 if(caResult == CA_STATUS_OK)
1870 #ifdef WITH_PRESENCE
1871 case OC_REST_PRESENCE:
1872 FindAndDeleteClientCB(clientCB);
1876 return OC_STACK_INVALID_METHOD;
1879 CADestroyRemoteEndpoint(endpoint);
1880 if (hdrOptionMemAlloc)
1882 OCFree(requestData.options);
1888 #ifdef WITH_PRESENCE
1889 OCStackResult OCProcessPresence()
1891 OCStackResult result = OC_STACK_OK;
1892 uint8_t ipAddr[4] = { 0 };
1895 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1896 ClientCB* cbNode = NULL;
1898 OCClientResponse clientResponse;
1899 OCResponse * response = NULL;
1900 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1902 LL_FOREACH(cbList, cbNode) {
1903 if(OC_REST_PRESENCE == cbNode->method)
1905 if(cbNode->presence)
1907 uint32_t now = GetTime(0);
1908 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d",
1909 cbNode->presence->TTLlevel);
1910 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1913 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1918 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1919 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1920 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1923 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1925 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1926 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1928 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1931 clientResponse.sequenceNumber = 0;
1932 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
1933 clientResponse.addr = (OCDevAddr *) &dst;
1934 clientResponse.resJSONPayload = NULL;
1936 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1937 &cbNode->token, &clientResponse, NULL);
1938 if(result != OC_STACK_OK)
1943 // Increment the TTLLevel (going to a next state), so we don't keep
1944 // sending presence notification to client.
1945 cbNode->presence->TTLlevel++;
1946 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1947 cbNode->presence->TTLlevel);
1951 result = OC_STACK_INVALID_IP;
1955 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
1956 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1958 FindAndDeleteClientCB(cbNode);
1962 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1964 CAResult_t caResult;
1965 CARemoteEndpoint_t* endpoint = NULL;
1966 CAInfo_t requestData;
1967 CARequestInfo_t requestInfo;
1969 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
1971 //TODO-CA : Why CA_WIFI alone?
1972 caResult = CACreateRemoteEndpoint((char *)cbNode->requestUri, CA_WIFI,
1975 if (caResult != CA_STATUS_OK)
1977 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1981 memset(&requestData, 0, sizeof(CAInfo_t));
1982 requestData.type = CA_MSG_NONCONFIRM;
1983 requestData.token = cbNode->token;
1985 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1986 requestInfo.method = CA_GET;
1987 requestInfo.info = requestData;
1989 caResult = CASendRequest(endpoint, &requestInfo);
1991 if (caResult != CA_STATUS_OK)
1993 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1997 cbNode->presence->TTLlevel++;
1998 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1999 cbNode->presence->TTLlevel);
2005 if (result != OC_STACK_OK)
2007 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
2011 #endif // WITH_PRESENCE
2014 * Called in main loop of OC client or server. Allows low-level processing of
2018 * OC_STACK_OK - no errors
2019 * OC_STACK_ERROR - stack process error
2021 OCStackResult OCProcess()
2023 #ifdef WITH_PRESENCE
2024 OCProcessPresence();
2026 CAHandleRequestResponse();
2031 #ifdef WITH_PRESENCE
2033 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
2034 * presence notifications to clients via multicast. Once this API has been called with a success,
2035 * clients may query for this server's presence and this server's stack will respond via multicast.
2037 * Server can call this function when it comes online for the first time, or when it comes back
2038 * online from offline mode, or when it re enters network.
2040 * @param ttl - Time To Live in seconds
2041 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
2044 * OC_STACK_OK - No errors; Success
2046 OCStackResult OCStartPresence(const uint32_t ttl)
2048 OCChangeResourceProperty(
2049 &(((OCResource *)presenceResource.handle)->resourceProperties),
2054 presenceResource.presenceTTL = ttl;
2057 if(OC_PRESENCE_UNINITIALIZED == presenceState)
2059 OCDevAddr multiCastAddr;
2060 presenceState = OC_PRESENCE_INITIALIZED;
2062 OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
2064 CAAddress_t addressInfo;
2065 strncpy(addressInfo.IP.ipAddress, "224.0.1.187", CA_IPADDR_SIZE);
2066 addressInfo.IP.port = 5683;
2068 //TODO make sure there is no memory leak here since another copy
2069 //of token is being created inside AddObserver
2070 CAToken_t caToken = NULL;
2071 CAResult_t caResult = CAGenerateToken(&caToken);
2072 if (caResult != CA_STATUS_OK)
2074 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2075 CADestroyToken(caToken);
2076 return OC_STACK_ERROR;
2079 AddObserver(OC_PRESENCE_URI, NULL, 0, &caToken,
2080 &multiCastAddr, (OCResource *)presenceResource.handle, OC_LOW_QOS,
2081 &addressInfo, CA_WIFI);
2084 // Each time OCStartPresence is called
2085 // a different random 32-bit integer number is used
2086 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2088 return SendPresenceNotification(NULL);
2092 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
2093 * presence notifications to clients via multicast. Once this API has been called with a success,
2094 * this server's stack will not respond to clients querying for this server's presence.
2096 * Server can call this function when it is terminating, going offline, or when going
2097 * away from network.
2100 * OC_STACK_OK - No errors; Success
2102 OCStackResult OCStopPresence()
2104 OCStackResult result = OC_STACK_ERROR;
2105 //make resource inactive
2106 result = OCChangeResourceProperty(
2107 &(((OCResource *) presenceResource.handle)->resourceProperties),
2109 result = SendPresenceNotification(NULL);
2116 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
2118 defaultDeviceHandler = entityHandler;
2123 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2125 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
2127 if(myStackMode == OC_CLIENT)
2129 return OC_STACK_ERROR;
2132 return SaveDeviceInfo(deviceInfo);
2138 * @param handle - pointer to handle to newly created resource. Set by ocstack.
2139 * Used to refer to resource
2140 * @param resourceTypeName - name of resource type. Example: "core.led"
2141 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
2142 * @param uri - URI of the resource. Example: "/a/led"
2143 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2144 * NULL for default entity handler
2145 * @param resourceProperties - properties supported by resource.
2146 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
2149 * OC_STACK_OK - no errors
2150 * OC_STACK_ERROR - stack process error
2152 OCStackResult OCCreateResource(OCResourceHandle *handle,
2153 const char *resourceTypeName,
2154 const char *resourceInterfaceName,
2155 const char *uri, OCEntityHandler entityHandler,
2156 uint8_t resourceProperties) {
2158 OCResource *pointer = NULL;
2161 OCStackResult result = OC_STACK_ERROR;
2163 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
2165 if(myStackMode == OC_CLIENT)
2169 // Validate parameters
2170 if(!uri || (strlen(uri) == 0))
2172 OC_LOG(ERROR, TAG, PCF("URI is invalid"));
2173 return OC_STACK_INVALID_URI;
2175 // Is it presented during resource discovery?
2176 if (!handle || !resourceTypeName) {
2177 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
2178 return OC_STACK_INVALID_PARAM;
2181 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
2182 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2185 // Make sure resourceProperties bitmask has allowed properties specified
2186 if (resourceProperties
2187 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
2188 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2189 return OC_STACK_INVALID_PARAM;
2192 // If the headResource is NULL, then no resources have been created...
2193 pointer = headResource;
2195 // At least one resources is in the resource list, so we need to search for
2196 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2198 if (strcmp(uri, pointer->uri) == 0) {
2199 OC_LOG(ERROR, TAG, PCF("URI already in use"));
2200 return OC_STACK_INVALID_PARAM;
2202 pointer = pointer->next;
2205 // Create the pointer and insert it into the resource list
2206 pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
2210 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2212 insertResource(pointer);
2215 size = strlen(uri) + 1;
2216 str = (char *) OCMalloc(size);
2220 strncpy(str, uri, size);
2223 // Set properties. Set OC_ACTIVE
2224 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2227 // Add the resourcetype to the resource
2228 result = BindResourceTypeToResource(pointer, resourceTypeName);
2229 if (result != OC_STACK_OK) {
2230 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
2234 // Add the resourceinterface to the resource
2235 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2236 if (result != OC_STACK_OK) {
2237 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
2241 // If an entity handler has been passed, attach it to the newly created
2242 // resource. Otherwise, set the default entity handler.
2245 pointer->entityHandler = entityHandler;
2249 pointer->entityHandler = defaultResourceEHandler;
2253 result = OC_STACK_OK;
2255 #ifdef WITH_PRESENCE
2256 if(presenceResource.handle)
2258 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2259 SendPresenceNotification(pointer->rsrcType);
2263 if (result != OC_STACK_OK)
2265 // Deep delete of resource and other dynamic elements that it contains
2266 deleteResource(pointer);
2275 * Create a resource. with host ip address for remote resource
2277 * @param handle - pointer to handle to newly created resource. Set by ocstack.
2278 * Used to refer to resource
2279 * @param resourceTypeName - name of resource type. Example: "core.led"
2280 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
2281 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
2282 * @param uri - URI of the resource. Example: "/a/led"
2283 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2284 * NULL for default entity handler
2285 * @param resourceProperties - properties supported by resource.
2286 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
2289 * OC_STACK_OK - no errors
2290 * OC_STACK_ERROR - stack process error
2293 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
2294 const char *resourceTypeName,
2295 const char *resourceInterfaceName,
2298 OCEntityHandler entityHandler,
2299 uint8_t resourceProperties)
2303 OCStackResult result = OC_STACK_ERROR;
2305 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
2306 uri, entityHandler, resourceProperties);
2308 if (result != OC_STACK_ERROR)
2311 size = strlen(host) + 1;
2312 str = (char *) OCMalloc(size);
2315 return OC_STACK_ERROR;
2317 strncpy(str, host, size);
2318 ((OCResource *) *handle)->host = str;
2325 * Add a resource to a collection resource.
2327 * @param collectionHandle - handle to the collection resource
2328 * @param resourceHandle - handle to resource to be added to the collection resource
2331 * OC_STACK_OK - no errors
2332 * OC_STACK_ERROR - stack process error
2333 * OC_STACK_INVALID_PARAM - invalid collectionhandle
2335 OCStackResult OCBindResource(
2336 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2337 OCResource *resource;
2340 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2342 // Validate parameters
2343 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2344 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2345 // Container cannot contain itself
2346 if (collectionHandle == resourceHandle) {
2347 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2348 return OC_STACK_INVALID_PARAM;
2351 // Use the handle to find the resource in the resource linked list
2352 resource = findResource((OCResource *) collectionHandle);
2354 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2355 return OC_STACK_INVALID_PARAM;
2358 // Look for an open slot to add add the child resource.
2359 // If found, add it and return success
2360 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2361 if (!resource->rsrcResources[i]) {
2362 resource->rsrcResources[i] = (OCResource *) resourceHandle;
2363 OC_LOG(INFO, TAG, PCF("resource bound"));
2368 #ifdef WITH_PRESENCE
2369 if(presenceResource.handle)
2371 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2372 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2376 // Unable to add resourceHandle, so return error
2377 return OC_STACK_ERROR;
2381 * Remove a resource from a collection resource.
2383 * @param collectionHandle - handle to the collection resource
2384 * @param resourceHandle - handle to resource to be added to the collection resource
2387 * OC_STACK_OK - no errors
2388 * OC_STACK_ERROR - stack process error
2389 * OC_STACK_INVALID_PARAM - invalid collectionHandle
2391 OCStackResult OCUnBindResource(
2392 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2393 OCResource *resource;
2396 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2398 // Validate parameters
2399 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2400 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2401 // Container cannot contain itself
2402 if (collectionHandle == resourceHandle) {
2403 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2404 return OC_STACK_INVALID_PARAM;
2407 // Use the handle to find the resource in the resource linked list
2408 resource = findResource((OCResource *) collectionHandle);
2410 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2411 return OC_STACK_INVALID_PARAM;
2414 // Look for an open slot to add add the child resource.
2415 // If found, add it and return success
2416 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2417 if (resourceHandle == resource->rsrcResources[i]) {
2418 resource->rsrcResources[i] = (OCResource *) NULL;
2419 OC_LOG(INFO, TAG, PCF("resource unbound"));
2424 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2426 #ifdef WITH_PRESENCE
2427 if(presenceResource.handle)
2429 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2430 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2434 // Unable to add resourceHandle, so return error
2435 return OC_STACK_ERROR;
2438 OCStackResult BindResourceTypeToResource(OCResource* resource,
2439 const char *resourceTypeName)
2441 OCResourceType *pointer = NULL;
2444 OCStackResult result = OC_STACK_ERROR;
2446 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
2448 // Validate parameters
2449 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2450 // TODO: Does resource attribute resentation really have to be maintained in stack?
2451 // Is it presented during resource discovery?
2453 //TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
2455 // Create the resourcetype and insert it into the resource list
2456 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
2461 // Set the resourceTypeName
2462 size = strlen(resourceTypeName) + 1;
2463 str = (char *) OCMalloc(size);
2467 strncpy(str, resourceTypeName, size);
2468 pointer->resourcetypename = str;
2470 insertResourceType(resource, pointer);
2471 result = OC_STACK_OK;
2473 exit: if (result != OC_STACK_OK) {
2481 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2482 const char *resourceInterfaceName)
2484 OCResourceInterface *pointer = NULL;
2487 OCStackResult result = OC_STACK_ERROR;
2489 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
2491 // Validate parameters
2492 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2494 //TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
2496 // Create the resourceinterface and insert it into the resource list
2497 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
2502 // Set the resourceinterface name
2503 size = strlen(resourceInterfaceName) + 1;
2504 str = (char *) OCMalloc(size);
2508 strncpy(str, resourceInterfaceName, size);
2509 pointer->name = str;
2511 // Bind the resourceinterface to the resource
2512 insertResourceInterface(resource, pointer);
2514 result = OC_STACK_OK;
2516 exit: if (result != OC_STACK_OK) {
2525 * Bind a resourcetype to a resource.
2527 * @param handle - handle to the resource
2528 * @param resourceTypeName - name of resource type. Example: "core.led"
2531 * OC_STACK_OK - no errors
2532 * OC_STACK_ERROR - stack process error
2534 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2535 const char *resourceTypeName) {
2537 OCStackResult result = OC_STACK_ERROR;
2538 OCResource *resource;
2540 // Make sure resource exists
2541 resource = findResource((OCResource *) handle);
2543 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2544 return OC_STACK_ERROR;
2547 // call internal function
2548 result = BindResourceTypeToResource(resource, resourceTypeName);
2550 #ifdef WITH_PRESENCE
2551 if(presenceResource.handle)
2553 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2554 SendPresenceNotification(resource->rsrcType);
2562 * Bind a resourceinterface to a resource.
2564 * @param handle - handle to the resource
2565 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
2568 * OC_STACK_OK - no errors
2569 * OC_STACK_ERROR - stack process error
2572 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2573 const char *resourceInterfaceName) {
2575 OCStackResult result = OC_STACK_ERROR;
2576 OCResource *resource;
2578 // Make sure resource exists
2579 resource = findResource((OCResource *) handle);
2581 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2582 return OC_STACK_ERROR;
2585 // call internal function
2586 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2588 #ifdef WITH_PRESENCE
2589 if(presenceResource.handle)
2591 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2592 SendPresenceNotification(resource->rsrcType);
2600 * Get the number of resources that have been created in the stack.
2602 * @param numResources - pointer to count variable
2605 * OC_STACK_OK - no errors
2606 * OC_STACK_ERROR - stack process error
2609 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
2610 OCResource *pointer = headResource;
2612 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2613 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2616 *numResources = *numResources + 1;
2617 pointer = pointer->next;
2623 * Get a resource handle by index.
2625 * @param index - index of resource, 0 to Count - 1
2628 * Resource handle - if found
2629 * NULL - if not found
2631 OCResourceHandle OCGetResourceHandle(uint8_t index) {
2632 OCResource *pointer = headResource;
2635 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2637 // Iterate through the list
2638 while ((i < index) && pointer) {
2640 pointer = pointer->next;
2642 return (OCResourceHandle) pointer;
2646 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
2649 * @param handle - handle of resource to be deleted
2652 * OC_STACK_OK - no errors
2653 * OC_STACK_ERROR - stack process error
2654 * OC_STACK_NO_RESOURCE - resource not found
2655 * OC_STACK_INVALID_PARAM - invalid param
2657 OCStackResult OCDeleteResource(OCResourceHandle handle) {
2658 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2661 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2662 return OC_STACK_INVALID_PARAM;
2665 OCResource *resource = findResource((OCResource *) handle);
2666 if (resource == NULL) {
2667 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2668 return OC_STACK_NO_RESOURCE;
2671 if (deleteResource((OCResource *) handle) == 0) {
2672 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2673 return OC_STACK_ERROR;
2680 * Get the URI of the resource specified by handle.
2682 * @param handle - handle of resource
2684 * URI string - if resource found
2685 * NULL - resource not found
2687 const char *OCGetResourceUri(OCResourceHandle handle) {
2688 OCResource *resource;
2689 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2691 resource = findResource((OCResource *) handle);
2693 return resource->uri;
2695 return (const char *) NULL;
2699 * Get the properties of the resource specified by handle.
2700 * NOTE: that after a resource is created, the OC_ACTIVE property is set
2701 * for the resource by the stack.
2703 * @param handle - handle of resource
2705 * property bitmap - if resource found
2706 * NULL - resource not found
2708 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
2709 OCResource *resource;
2710 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2712 resource = findResource((OCResource *) handle);
2714 return resource->resourceProperties;
2720 * Get the number of resource types of the resource.
2722 * @param handle - handle of resource
2723 * @param numResourceTypes - pointer to count variable
2726 * OC_STACK_OK - no errors
2727 * OC_STACK_ERROR - stack process error
2729 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2730 uint8_t *numResourceTypes) {
2731 OCResource *resource;
2732 OCResourceType *pointer;
2734 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2735 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2736 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2738 *numResourceTypes = 0;
2740 resource = findResource((OCResource *) handle);
2742 pointer = resource->rsrcType;
2744 *numResourceTypes = *numResourceTypes + 1;
2745 pointer = pointer->next;
2752 * Get name of resource type of the resource.
2754 * @param handle - handle of resource
2755 * @param index - index of resource, 0 to Count - 1
2758 * resource type name - if resource found
2759 * NULL - resource not found
2761 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
2762 OCResourceType *resourceType;
2764 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2766 resourceType = findResourceTypeAtIndex(handle, index);
2768 return resourceType->resourcetypename;
2770 return (const char *) NULL;
2776 * Get the number of resource interfaces of the resource.
2778 * @param handle - handle of resource
2779 * @param numResources - pointer to count variable
2782 * OC_STACK_OK - no errors
2783 * OC_STACK_ERROR - stack process error
2785 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2786 uint8_t *numResourceInterfaces) {
2787 OCResourceInterface *pointer;
2788 OCResource *resource;
2790 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2792 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2793 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2795 *numResourceInterfaces = 0;
2796 resource = findResource((OCResource *) handle);
2798 pointer = resource->rsrcInterface;
2800 *numResourceInterfaces = *numResourceInterfaces + 1;
2801 pointer = pointer->next;
2808 * Get name of resource interface of the resource.
2810 * @param handle - handle of resource
2811 * @param index - index of resource, 0 to Count - 1
2814 * resource interface name - if resource found
2815 * NULL - resource not found
2817 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
2818 OCResourceInterface *resourceInterface;
2820 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2822 resourceInterface = findResourceInterfaceAtIndex(handle, index);
2823 if (resourceInterface) {
2824 return resourceInterface->name;
2826 return (const char *) NULL;
2830 * Get resource handle from the collection resource by index.
2832 * @param collectionHandle - handle of collection resource
2833 * @param index - index of contained resource, 0 to Count - 1
2836 * handle to resource - if resource found
2837 * NULL - resource not found
2839 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2841 OCResource *resource;
2843 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2845 if (index >= MAX_CONTAINED_RESOURCES) {
2849 resource = findResource((OCResource *) collectionHandle);
2854 return resource->rsrcResources[index];
2858 * Bind an entity handler to the resource.
2860 * @param handle - handle to the resource that the contained resource is to be bound
2861 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2863 * OC_STACK_OK - no errors
2864 * OC_STACK_ERROR - stack process error
2866 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2867 OCEntityHandler entityHandler) {
2868 OCResource *resource;
2870 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2872 // Validate parameters
2873 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2874 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2876 // Use the handle to find the resource in the resource linked list
2877 resource = findResource((OCResource *)handle);
2879 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2880 return OC_STACK_ERROR;
2884 resource->entityHandler = entityHandler;
2886 #ifdef WITH_PRESENCE
2887 if(presenceResource.handle)
2889 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2890 SendPresenceNotification(resource->rsrcType);
2898 * Get the entity handler for a resource.
2900 * @param handle - handle of resource
2903 * entity handler - if resource found
2904 * NULL - resource not found
2906 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
2907 OCResource *resource;
2909 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2911 // Use the handle to find the resource in the resource linked list
2912 resource = findResource((OCResource *)handle);
2914 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2919 return resource->entityHandler;
2922 void incrementSequenceNumber(OCResource * resPtr)
2924 // Increment the sequence number
2925 resPtr->sequenceNum += 1;
2926 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2928 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2934 * Notify Presence subscribers that a resource has been modified
2936 * @param resourceType - Handle to the resourceType linked list of resource
2937 * that was modified.
2938 * @param qos - Quality Of Service
2941 #ifdef WITH_PRESENCE
2942 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
2944 OCResource *resPtr = NULL;
2945 OCStackResult result;
2946 OCMethod method = OC_REST_PRESENCE;
2947 uint32_t maxAge = 0;
2948 resPtr = findResource((OCResource *) presenceResource.handle);
2951 return OC_STACK_NO_RESOURCE;
2953 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
2955 maxAge = presenceResource.presenceTTL;
2962 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
2966 #endif // WITH_PRESENCE
2968 * Notify observers that an observed value has changed.
2970 * @param handle - handle of resource
2973 * OC_STACK_OK - no errors
2974 * OC_STACK_NO_RESOURCE - invalid resource handle
2975 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
2977 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
2979 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2981 OCResource *resPtr = NULL;
2982 OCStackResult result;
2983 OCMethod method = OC_REST_NOMETHOD;
2984 uint32_t maxAge = 0;
2986 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2987 #ifdef WITH_PRESENCE
2988 if(handle == presenceResource.handle)
2992 #endif // WITH_PRESENCE
2993 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2995 // Verify that the resource exists
2996 resPtr = findResource ((OCResource *) handle);
2999 return OC_STACK_NO_RESOURCE;
3003 //only increment in the case of regular observing (not presence)
3004 incrementSequenceNumber(resPtr);
3005 method = OC_REST_OBSERVE;
3006 maxAge = MAX_OBSERVE_AGE;
3007 #ifdef WITH_PRESENCE
3008 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
3010 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3017 OCNotifyListOfObservers (OCResourceHandle handle,
3018 OCObservationId *obsIdList,
3019 uint8_t numberOfIds,
3020 unsigned char *notificationJSONPayload,
3021 OCQualityOfService qos)
3023 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
3025 OCResource *resPtr = NULL;
3026 //TODO: we should allow the server to define this
3027 uint32_t maxAge = MAX_OBSERVE_AGE;
3029 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3030 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3031 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
3033 // Verify that the resource exists
3034 resPtr = findResource ((OCResource *) handle);
3035 if (NULL == resPtr || myStackMode == OC_CLIENT)
3037 return OC_STACK_NO_RESOURCE;
3041 incrementSequenceNumber(resPtr);
3043 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3044 notificationJSONPayload, maxAge, qos));
3048 * Send a response to a request.
3049 * The response can be a regular, slow, or block (i.e. a response that
3050 * is too large to be sent in a single PDU and must span multiple transmissions)
3052 * @param response - pointer to structure that contains response parameters
3055 * OC_STACK_OK - No errors; Success
3056 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
3057 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
3058 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
3059 * persistent response buffer is necessary
3061 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3063 OCStackResult result = OC_STACK_ERROR;
3064 OCServerRequest *serverRequest = NULL;
3066 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
3068 // Validate input parameters
3069 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3070 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3072 // TODO: Placeholder for creating a response entry when implementing
3073 // block transfer feature
3075 // If a response payload is present, check if block transfer is required
3076 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
3077 (const char *)ehResponse->payload, ehResponse->payloadSize))
3079 OC_LOG(INFO, TAG, PCF("Block transfer required"));
3081 // Persistent response buffer is needed for block transfer
3082 if (!ehResponse->persistentBufferFlag)
3084 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
3085 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
3087 // TODO: Placeholder for block transfer handling
3088 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
3089 // when implementing the block transfer feature
3094 // Get pointer to request info
3095 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3098 result = serverRequest->ehResponseHandler(ehResponse);
3105 * Cancel a response. Applies to a block response
3107 * @param responseHandle - response handle set by stack in OCServerResponse after
3108 * OCDoResponse is called
3111 * OC_STACK_OK - No errors; Success
3112 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
3114 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
3116 OCStackResult result = OC_STACK_NOTIMPL;
3118 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
3120 // TODO: validate response handle
3125 //-----------------------------------------------------------------------------
3126 // Private internal function definitions
3127 //-----------------------------------------------------------------------------
3129 * Generate handle of OCDoResource invocation for callback management.
3131 static OCDoHandle GenerateInvocationHandle()
3133 OCDoHandle handle = NULL;
3134 // Generate token here, it will be deleted when the transaction is deleted
3135 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3138 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3143 #ifdef WITH_PRESENCE
3144 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3145 OCResourceProperty resourceProperties, uint8_t enable)
3147 if (resourceProperties
3148 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
3149 OC_LOG(ERROR, TAG, PCF("Invalid property"));
3150 return OC_STACK_INVALID_PARAM;
3154 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3158 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3165 * Initialize resource data structures, variables, etc.
3167 OCStackResult initResources() {
3168 OCStackResult result = OC_STACK_OK;
3169 // Init application resource vars
3170 headResource = NULL;
3171 // Init Virtual Resources
3172 #ifdef WITH_PRESENCE
3173 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
3174 //presenceResource.token = OCGenerateCoAPToken();
3175 result = OCCreateResource(&presenceResource.handle,
3176 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3181 //make resource inactive
3182 result = OCChangeResourceProperty(
3183 &(((OCResource *) presenceResource.handle)->resourceProperties),
3190 * Add a resource to the end of the linked list of resources.
3192 * @param resource - resource to be added
3194 void insertResource(OCResource *resource) {
3195 OCResource *pointer;
3197 if (!headResource) {
3198 headResource = resource;
3200 pointer = headResource;
3202 while (pointer->next) {
3203 pointer = pointer->next;
3205 pointer->next = resource;
3207 resource->next = NULL;
3211 * Find a resource in the linked list of resources.
3213 * @param resource - resource to be found
3215 * NULL - resource not found
3216 * pointer to resource - pointer to resource that was found in the linked list
3218 OCResource *findResource(OCResource *resource) {
3219 OCResource *pointer = headResource;
3222 if (pointer == resource) {
3225 pointer = pointer->next;
3230 void deleteAllResources()
3232 OCResource *pointer = headResource;
3237 temp = pointer->next;
3238 #ifdef WITH_PRESENCE
3239 if(pointer != (OCResource *) presenceResource.handle)
3241 #endif // WITH_PRESENCE
3242 deleteResource(pointer);
3243 #ifdef WITH_PRESENCE
3245 #endif // WITH_PRESENCE
3249 #ifdef WITH_PRESENCE
3250 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3251 // presence notification attributed to their deletion to be processed.
3252 deleteResource((OCResource *) presenceResource.handle);
3253 #endif // WITH_PRESENCE
3257 * Delete the resource from the linked list.
3259 * @param resource - resource to be deleted
3264 int deleteResource(OCResource *resource) {
3265 OCResource *prev = NULL;
3268 temp = headResource;
3270 if (temp == resource) {
3271 // Invalidate all Resource Properties.
3272 resource->resourceProperties = (OCResourceProperty) 0;
3273 #ifdef WITH_PRESENCE
3274 if(resource != (OCResource *) presenceResource.handle)
3276 #endif // WITH_PRESENCE
3277 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3278 #ifdef WITH_PRESENCE
3281 if(presenceResource.handle)
3283 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3284 if(resource != (OCResource *) presenceResource.handle)
3286 SendPresenceNotification(resource->rsrcType);
3290 SendPresenceNotification(NULL);
3295 if (temp == headResource) {
3296 headResource = temp->next;
3298 prev->next = temp->next;
3301 deleteResourceElements(temp);
3314 * Delete all of the dynamically allocated elements that were created for the resource.
3316 * @param resource - specified resource
3318 void deleteResourceElements(OCResource *resource) {
3324 OCFree(resource->uri);
3326 // Delete resourcetype linked list
3327 deleteResourceType(resource->rsrcType);
3329 // Delete resourceinterface linked list
3330 deleteResourceInterface(resource->rsrcInterface);
3334 * Delete all of the dynamically allocated elements that were created for the resource type.
3336 * @param resourceType - specified resource type
3338 void deleteResourceType(OCResourceType *resourceType) {
3339 OCResourceType *pointer = resourceType;
3340 OCResourceType *next;
3343 next = pointer->next;
3344 OCFree(pointer->resourcetypename);
3351 * Delete all of the dynamically allocated elements that were created for the resource interface.
3353 * @param resourceInterface - specified resource interface
3355 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
3356 OCResourceInterface *pointer = resourceInterface;
3357 OCResourceInterface *next;
3360 next = pointer->next;
3361 OCFree(pointer->name);
3368 * Insert a resource type into a resource's resource type linked list.
3370 * @param resource - resource where resource type is to be inserted
3371 * @param resourceType - resource type to be inserted
3373 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
3374 OCResourceType *pointer;
3376 if (resource && !resource->rsrcType) {
3377 resource->rsrcType = resourceType;
3381 pointer = resource->rsrcType;
3385 pointer = resourceType;
3387 while (pointer->next) {
3388 pointer = pointer->next;
3390 pointer->next = resourceType;
3392 resourceType->next = NULL;
3396 * Get a resource type at the specified index within a resource.
3398 * @param handle - handle of resource
3399 * @param index - index of resource type
3402 * resourcetype - if found
3405 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
3406 OCResource *resource;
3407 OCResourceType *pointer;
3410 // Find the specified resource
3411 resource = findResource((OCResource *) handle);
3416 // Make sure a resource has a resourcetype
3417 if (!resource->rsrcType) {
3421 // Iterate through the list
3422 pointer = resource->rsrcType;
3424 while ((i < index) && pointer) {
3426 pointer = pointer->next;
3432 * Finds a resource type in an OCResourceType link-list.
3434 * @param resourceTypeList - the link-list to be searched through
3435 * @param resourceTypeName - the key to search for
3438 * resourceType that matches the key (ie. resourceTypeName)
3439 * NULL - either an invalid parameter or this function was unable to find the key.
3441 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3443 if(resourceTypeList && resourceTypeName)
3445 OCResourceType * rtPointer = resourceTypeList;
3446 while(resourceTypeName && rtPointer)
3448 if(rtPointer->resourcetypename &&
3449 strcmp(resourceTypeName, (const char *)
3450 (rtPointer->resourcetypename)) == 0)
3454 rtPointer = rtPointer->next;
3461 * Insert a resource interface into a resource's resource interface linked list.
3463 * @param resource - resource where resource interface is to be inserted
3464 * @param resourceInterface - resource interface to be inserted
3466 void insertResourceInterface(OCResource *resource,
3467 OCResourceInterface *resourceInterface) {
3468 OCResourceInterface *pointer;
3470 if (!resource->rsrcInterface) {
3471 resource->rsrcInterface = resourceInterface;
3473 pointer = resource->rsrcInterface;
3474 while (pointer->next) {
3475 pointer = pointer->next;
3477 pointer->next = resourceInterface;
3479 resourceInterface->next = NULL;
3483 * Get a resource interface at the specified index within a resource.
3485 * @param handle - handle of resource
3486 * @param index - index of resource interface
3489 * resourceinterface - if found
3492 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3494 OCResource *resource;
3495 OCResourceInterface *pointer;
3498 // Find the specified resource
3499 resource = findResource((OCResource *) handle);
3504 // Make sure a resource has a resourceinterface
3505 if (!resource->rsrcInterface) {
3509 // Iterate through the list
3510 pointer = resource->rsrcInterface;
3512 while ((i < index) && pointer) {
3514 pointer = pointer->next;
3520 * Determine if a request/response must be sent in a block transfer because it is too large to be
3521 * sent in a single PDU. This function can be used for either a request or a response
3523 * @param request - NULL or pointer to request
3524 * @param response - NULL or pointer to response
3525 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
3526 * the length of the request/response
3529 * 0 - packet transfer NOT required (i.e. normal request/response)
3530 * 1 - packet transfer required (i.e. block transfer needed)
3532 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
3536 // Determine if we are checking a request or a response
3539 // If size is greater than 0, use it for the request size value, otherwise
3540 // assume request is null terminated and use strlen for size value
3541 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
3548 // If size is greater than 0, use it for the response size value, otherwise
3549 // assume response is null terminated and use strlen for size value
3550 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3559 * Retrieves a resource type based upon a query ontains only just one
3560 * resource attribute (and that has to be of type "rt").
3562 * @remark This API malloc's memory for the resource type. Do not malloc resourceType
3563 * before passing in.
3565 * @param query - The quert part of the URI
3566 * @param resourceType - The resource type to be populated; pass by reference.
3569 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
3570 * OC_STACK_OK - Success
3572 OCStackResult getResourceType(const char * query, unsigned char** resourceType)
3576 return OC_STACK_INVALID_PARAM;
3579 OCStackResult result = OC_STACK_ERROR;
3581 if(strncmp(query, "rt=", 3) == 0)
3583 *resourceType = (unsigned char *) OCMalloc(strlen(query)-3);
3586 result = OC_STACK_NO_MEMORY;
3589 strcpy((char *)*resourceType, ((const char *)&query[3]));
3590 result = OC_STACK_OK;
3596 OCStackResult getQueryFromUri(const char * uri, unsigned char** query, char ** newURI)
3600 return OC_STACK_INVALID_URI;
3602 if(!query || !newURI)
3604 return OC_STACK_INVALID_PARAM;
3606 char * leftToken = NULL;
3607 char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3612 strcpy(tempURI, uri);
3614 leftToken = strtok_r((char *)tempURI, "?", &strTokPtr);
3616 //TODO-CA: This could be simplified. Clean up required.
3617 while(leftToken != NULL)
3619 if(strncmp(leftToken, "rt=", 3) == 0 || strncmp(leftToken, "if=", 3) == 0)
3621 *query = (unsigned char *) OCMalloc(strlen(leftToken) + 1);
3627 strcpy((char *)*query, ((const char *)&leftToken[0]));
3630 leftToken = strtok_r(NULL, "?", &strTokPtr);
3638 return OC_STACK_NO_MEMORY;
3641 const ServerID OCGetServerInstanceID(void)
3643 static bool generated = false;
3644 static ServerID sid;
3651 sid = OCGetRandom();
3656 const char* OCGetServerInstanceIDString(void)
3658 // max printed length of a base 10
3659 // uint32 is 10 characters, so 11 includes null.
3660 // This will change as the representation gets switched
3662 static char buffer[11];
3663 int n = sprintf(buffer, "%u", OCGetServerInstanceID());