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
29 #include "ocstackinternal.h"
30 #include "ocresourcehandler.h"
31 #include "occlientcb.h"
32 #include "ocobserve.h"
37 #include "ocserverrequest.h"
41 #include "cainterface.h"
44 //-----------------------------------------------------------------------------
46 //-----------------------------------------------------------------------------
48 OC_STACK_UNINITIALIZED = 0, OC_STACK_INITIALIZED, OC_STACK_UNINIT_IN_PROGRESS
53 OC_PRESENCE_UNINITIALIZED = 0, OC_PRESENCE_INITIALIZED
57 //-----------------------------------------------------------------------------
59 //-----------------------------------------------------------------------------
60 static OCStackState stackState = OC_STACK_UNINITIALIZED;
62 OCResource *headResource = NULL;
64 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
65 static PresenceResource presenceResource;
66 uint8_t PresenceTimeOutSize = 0;
67 uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
71 OCDeviceEntityHandler defaultDeviceHandler;
72 OCStackResult getQueryFromUri(const char * uri, unsigned char** resourceType, char ** newURI);
74 //-----------------------------------------------------------------------------
76 //-----------------------------------------------------------------------------
77 #define TAG PCF("OCStack")
78 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
79 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
80 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
81 TAG, PCF(#arg " is NULL")); return (retVal); } }
82 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
85 //TODO: we should allow the server to define this
86 #define MAX_OBSERVE_AGE (0x2FFFFUL)
88 //-----------------------------------------------------------------------------
90 //-----------------------------------------------------------------------------
91 extern void DeinitOCSecurityInfo();
93 //-----------------------------------------------------------------------------
94 // Internal API function
95 //-----------------------------------------------------------------------------
97 // This internal function is called to update the stack with the status of
98 // observers and communication failures
99 OCStackResult OCStackFeedBack(OCCoAPToken * token, uint8_t status)
101 OCStackResult result = OC_STACK_ERROR;
102 ResourceObserver * observer = NULL;
103 OCEntityHandlerRequest ehRequest = {0};
107 case OC_OBSERVER_NOT_INTERESTED:
108 OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
110 observer = GetObserverUsingToken (token->token);
112 observer = GetObserverUsingToken (token);
116 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
117 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
118 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
119 if(result != OC_STACK_OK)
123 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
125 //observer is not observing anymore
127 result = DeleteObserverUsingToken (token->token);
129 result = DeleteObserverUsingToken (token);
131 if(result == OC_STACK_OK)
133 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
137 result = OC_STACK_OK;
138 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
141 case OC_OBSERVER_STILL_INTERESTED:
142 //observer is still interested
143 OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
144 notifications, reset the failedCount"));
146 observer = GetObserverUsingToken (token->token);
148 observer = GetObserverUsingToken (token);
152 observer->forceHighQos = 0;
153 observer->failedCommCount = 0;
154 result = OC_STACK_OK;
158 result = OC_STACK_OBSERVER_NOT_FOUND;
161 case OC_OBSERVER_FAILED_COMM:
162 //observer is not reachable
163 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
165 observer = GetObserverUsingToken (token->token);
167 observer = GetObserverUsingToken (token);
171 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
173 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
174 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
175 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
176 if(result != OC_STACK_OK)
178 return OC_STACK_ERROR;
180 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
181 //observer is unreachable
182 result = DeleteObserverUsingToken (token);
183 if(result == OC_STACK_OK)
185 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
189 result = OC_STACK_OK;
190 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
195 observer->failedCommCount++;
196 result = OC_STACK_CONTINUE;
198 observer->forceHighQos = 1;
199 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
203 OC_LOG(ERROR, TAG, PCF("Unknown status"));
204 result = OC_STACK_ERROR;
211 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
213 OCStackResult ret = OC_STACK_ERROR;
221 ret = OC_STACK_RESOURCE_CREATED;
224 ret = OC_STACK_RESOURCE_DELETED;
227 ret = OC_STACK_INVALID_QUERY;
230 ret = OC_STACK_INVALID_OPTION;
233 ret = OC_STACK_NO_RESOURCE;
241 OCStackResult OCToCAConnectivityType(OCConnectivityType ocConType, CAConnectivityType_t* caConType)
243 OCStackResult ret = OC_STACK_OK;
248 *caConType = CA_ETHERNET;
251 *caConType = CA_WIFI;
260 //TODO-CA Add other connectivity types as they are enabled
261 *caConType = (CA_WIFI|CA_ETHERNET);
264 ret = OC_STACK_INVALID_PARAM;
270 OCStackResult CAToOCConnectivityType(CAConnectivityType_t caConType, OCConnectivityType *ocConType)
272 OCStackResult ret = OC_STACK_OK;
277 *ocConType = OC_ETHERNET;
280 *ocConType = OC_WIFI;
289 ret = OC_STACK_INVALID_PARAM;
295 // update response.addr appropriately from endPoint.addressInfo
296 OCStackResult UpdateResponseAddr(OCClientResponse *response, const CARemoteEndpoint_t* endPoint)
298 struct sockaddr_in sa;
299 OCStackResult ret = OC_STACK_INVALID_PARAM;
300 //TODO-CA Check validity of the endPoint pointer
301 inet_pton(AF_INET, endPoint->addressInfo.IP.ipAddress, &(sa.sin_addr));
302 sa.sin_port = htons(endPoint->addressInfo.IP.port);
303 static OCDevAddr address;
304 memcpy((void*)&address.addr, &(sa), sizeof(sa));
307 response->addr = &address;
308 ret = CAToOCConnectivityType(endPoint->connectivityType, &(response->connType));
313 void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge, char** resType)
317 // The format of the payload is {"oc":[%u:%u:%s]}
318 // %u : sequence number,
320 // %s : Resource Type (Optional)
321 tok = strtok(payload, "[:]}");
322 payload[strlen(payload)] = ':';
323 tok = strtok(NULL, "[:]}");
324 payload[strlen((char *)payload)] = ':';
325 *seqNum = (uint32_t) atoi(tok);
326 tok = strtok(NULL, "[:]}");
327 *maxAge = (uint32_t) atoi(tok);
328 tok = strtok(NULL, "[:]}");
332 *resType = (char *)OCMalloc(strlen(tok));
337 payload[strlen((char *)payload)] = ':';
338 strcpy(*resType, tok);
339 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s", *resType);
341 payload[strlen((char *)payload)] = ']';
344 OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
345 const CAResponseInfo_t* responseInfo)
347 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
348 ClientCB * cbNode = NULL;
349 char *resourceTypeName = NULL;
350 OCClientResponse response;
351 OCStackResult result = OC_STACK_ERROR;
352 uint32_t lowerBound = 0;
353 uint32_t higherBound = 0;
356 char *fullUri = NULL;
357 char *ipAddress = NULL;
358 int presenceSubscribe = 0;
359 int multicastPresenceSubscribe = 0;
361 fullUri = (char *) OCMalloc(MAX_URI_LENGTH );
365 OC_LOG(INFO, TAG, PCF("Memory could not be abllocated for fullUri"));
366 result = OC_STACK_NO_MEMORY;
370 ipAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
372 if(NULL == ipAddress)
374 OC_LOG(INFO, TAG, PCF("Memory could not be abllocated for ipAddress"));
375 result = OC_STACK_NO_MEMORY;
379 strncpy(ipAddress, endPoint->addressInfo.IP.ipAddress,
380 strlen(endPoint->addressInfo.IP.ipAddress));
381 ipAddress[strlen(endPoint->addressInfo.IP.ipAddress)] = '\0';
383 snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", ipAddress, endPoint->addressInfo.IP.port,
386 cbNode = GetClientCB(NULL, NULL, fullUri);
390 presenceSubscribe = 1;
394 snprintf(fullUri, MAX_URI_LENGTH, "%s%s", OC_MULTICAST_IP, endPoint->resourceUri);
395 cbNode = GetClientCB(NULL, NULL, fullUri);
398 multicastPresenceSubscribe = 1;
402 if(!presenceSubscribe && !multicastPresenceSubscribe)
404 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
405 ------------ ignoring"));
409 // No payload to the application in case of presence
410 response.resJSONPayload = NULL;
411 response.result = OC_STACK_OK;
413 UpdateResponseAddr(&response, endPoint);
415 if(responseInfo->info.payload)
417 parsePresencePayload(responseInfo->info.payload,
418 &(response.sequenceNumber),
425 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
426 response.result = OC_STACK_PRESENCE_STOPPED;
429 OCFree(cbNode->presence->timeOut);
430 OCFree(cbNode->presence);
431 cbNode->presence = NULL;
434 else if(presenceSubscribe)
436 if(!cbNode->presence)
438 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
439 VERIFY_NON_NULL_V(cbNode->presence);
440 cbNode->presence->timeOut = NULL;
441 cbNode->presence->timeOut = (uint32_t *)
442 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
443 if(!(cbNode->presence->timeOut)){
444 OCFree(cbNode->presence);
445 result = OC_STACK_NO_MEMORY;
449 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %u", GetTime(0));
450 cbNode->presence->TTL = maxAge;
451 for(int index = 0; index < PresenceTimeOutSize; index++)
453 lowerBound = GetTime(((float)(PresenceTimeOut[index])
454 /(float)100)*(float)cbNode->presence->TTL);
455 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
456 /(float)100)*(float)cbNode->presence->TTL);
457 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
458 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
459 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
460 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
461 cbNode->presence->timeOut[index]);
463 cbNode->presence->TTLlevel = 0;
464 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
465 if(cbNode->sequenceNumber == response.sequenceNumber)
467 OC_LOG(INFO, TAG, PCF("===============No presence change"));
470 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
471 cbNode->sequenceNumber = response.sequenceNumber;
473 // Ensure that a filter is actually applied.
474 if(resourceTypeName && cbNode->filterResourceType)
476 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
484 // This is the multicast case
486 OCMulticastNode* mcNode = NULL;
487 mcNode = GetMCPresenceNode(fullUri);
491 if(mcNode->nonce == response.sequenceNumber)
493 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
496 mcNode->nonce = response.sequenceNumber;
500 uint32_t uriLen = strlen((char*)fullUri);
501 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
504 memcpy(uri, fullUri, (uriLen + 1));
509 PCF("===============No Memory for URI to store in the presence node"));
510 result = OC_STACK_NO_MEMORY;
513 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri, response.sequenceNumber);
514 if(result == OC_STACK_NO_MEMORY)
517 PCF("===============No Memory for Multicast Presence Node"));
518 result = OC_STACK_NO_MEMORY;
523 // Ensure that a filter is actually applied.
524 if(resourceTypeName && cbNode->filterResourceType)
526 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
533 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
535 if (cbResult == OC_STACK_DELETE_TRANSACTION)
537 FindAndDeleteClientCB(cbNode);
543 OCFree(resourceTypeName);
547 //This function will be called back by CA layer when a response is received
548 void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
550 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
552 OCStackApplicationResult result = OC_STACK_DELETE_TRANSACTION;
556 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
560 if(NULL == responseInfo)
562 OC_LOG(ERROR, TAG, PCF("responseInfo is NULL"));
566 if(strcmp(endPoint->resourceUri, OC_PRESENCE_URI) == 0)
568 HandlePresenceResponse(endPoint, responseInfo);
572 ClientCB *cbNode = GetClientCB((CAToken_t *)&responseInfo->info.token, NULL, NULL);
576 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
577 OCClientResponse response;
579 OCStackResult result = UpdateResponseAddr(&response, endPoint);
580 if(result != OC_STACK_OK)
582 OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint"));
586 response.result = CAToOCStackResult(responseInfo->result);
587 response.resJSONPayload = (unsigned char*)responseInfo->info.payload;
588 response.numRcvdVendorSpecificHeaderOptions = 0;
589 if(responseInfo->info.numOptions > 0)
592 //First option alwas with option ID COAP_OPTION_OBSERVE if it is availbale
593 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
595 memcpy (&(response.sequenceNumber),
596 &(responseInfo->info.options[0].optionData), 4);
597 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
602 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
605 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
607 OC_LOG(ERROR, TAG, PCF("#header options are more than MAX_HEADER_OPTIONS"));
611 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
613 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
614 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
617 result = cbNode->callBack(cbNode->context,
618 cbNode->handle, &response);
619 if (result == OC_STACK_DELETE_TRANSACTION)
621 FindAndDeleteClientCB(cbNode);
624 OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload);
625 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
628 //This function will be called back by CA layer when a request is received
629 void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
631 CAInfo_t responseData;
632 CAResponseInfo_t responseInfo;
633 OCStackResult requestResult = OC_STACK_ERROR;
635 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
638 if(myStackMode == OC_CLIENT)
640 //TODO: should the client be responding to requests?
644 OCServerProtocolRequest serverRequest;
646 memset (&serverRequest, 0, sizeof(OCServerProtocolRequest));
647 OC_LOG_V(INFO, TAG, PCF("***** Endpoint URI ***** : %s\n"), (char*)endPoint->resourceUri);
649 char * newUri = (char *)endPoint->resourceUri;
650 unsigned char * query = NULL;
651 unsigned char * resourceType = NULL;
652 getQueryFromUri(endPoint->resourceUri, &query, &newUri);
653 OC_LOG_V(INFO, TAG, PCF("**********URI without query ****: %s\n"), newUri);
654 OC_LOG_V(INFO, TAG, PCF("**********Query ****: %s\n"), query);
656 memcpy (&(serverRequest.resourceUrl), newUri, strlen(newUri));
660 memcpy (&(serverRequest.query), query, strlen(query));
662 //copy request payload
663 if (requestInfo->info.payload)
665 serverRequest.reqTotalSize = strlen(requestInfo->info.payload) + 1;
666 memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
667 strlen(requestInfo->info.payload));
668 serverRequest.reqTotalSize = strlen((const char *)requestInfo->info.payload) + 1;
672 serverRequest.reqTotalSize = 1;
675 switch (requestInfo->method)
679 serverRequest.method = OC_REST_GET;
684 serverRequest.method = OC_REST_PUT;
689 serverRequest.method = OC_REST_POST;
694 serverRequest.method = OC_REST_DELETE;
699 OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
705 OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d", strlen(requestInfo->info.token));
706 OC_LOG_BUFFER(INFO, TAG, requestInfo->info.token, strlen(requestInfo->info.token));
707 // TODO-CA: For CA integration currently copying CAToken to OCCoapToken:
708 // Need to remove OCCoapToken
709 memcpy (&(serverRequest.requestToken.token), requestInfo->info.token,
711 serverRequest.requestToken.tokenLength = MAX_TOKEN_LENGTH;
713 if (requestInfo->info.type == CA_MSG_CONFIRM)
715 serverRequest.qos = OC_HIGH_QOS;
717 else if (requestInfo->info.type == CA_MSG_NONCONFIRM)
719 serverRequest.qos = OC_LOW_QOS;
721 else if (requestInfo->info.type == CA_MSG_ACKNOWLEDGE)
723 // TODO-CA: Need to handle this
725 else if (requestInfo->info.type == CA_MSG_RESET)
727 // TODO-CA: Need to handle this
729 // CA does not need the following 3 fields
730 serverRequest.coapID = 0;
731 serverRequest.delayedResNeeded = 0;
732 serverRequest.secured = endPoint->isSecured;
735 serverRequest.addressInfo = endPoint->addressInfo;
736 serverRequest.connectivityType = endPoint->connectivityType;
737 if (requestInfo->info.token)
739 strncpy(serverRequest.token, requestInfo->info.token, sizeof(serverRequest.token) - 1);
742 // copy vendor specific header options
743 // TODO-CA: CA is including non-vendor header options as well, like observe.
744 // Need to filter those out
745 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &(requestInfo->info.numOptions));
746 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
748 // TODO-CA: Need to send an error indicating the num of options is incorrect
751 serverRequest.numRcvdVendorSpecificHeaderOptions = requestInfo->info.numOptions;
752 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
754 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
755 sizeof(CAHeaderOption_t)*requestInfo->info.numOptions);
758 requestResult = HandleStackRequests (&serverRequest);
761 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
766 //This function will be called back by occoap layer when a request is received
767 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
769 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
770 OCStackResult result = OC_STACK_ERROR;
771 ResourceHandling resHandling;
772 OCResource *resource;
774 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
777 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
779 result = AddServerCARequest(&request, protocolRequest->coapID,
780 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
781 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
782 protocolRequest->observationOption, protocolRequest->qos,
783 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
784 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
785 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
786 protocolRequest->reqTotalSize,
787 &protocolRequest->addressInfo, protocolRequest->connectivityType, protocolRequest->token);
789 result = AddServerRequest(&request, protocolRequest->coapID,
790 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
791 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
792 protocolRequest->observationOption, protocolRequest->qos,
793 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
794 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
795 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
796 protocolRequest->reqTotalSize);
798 if (OC_STACK_OK != result)
800 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
803 VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
805 if(!protocolRequest->reqMorePacket)
807 request->requestComplete = 1;
812 OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
815 if(request->requestComplete)
817 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
818 result = DetermineResourceHandling (request, &resHandling, &resource);
819 if (result == OC_STACK_OK)
821 result = ProcessRequest(resHandling, resource, request);
825 result = OC_STACK_ERROR;
830 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
831 result = OC_STACK_CONTINUE;
836 //This function will be called back by occoap layer when a response is received
837 OCStackResult HandleStackResponses(OCResponse * response)
839 OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)"));
840 OCStackResult result = OC_STACK_OK;
841 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
842 uint8_t isObserveNotification = 0;
843 ClientCB * cbNode = NULL;
845 uint8_t isPresenceNotification = 0;
846 uint8_t isMulticastPresence = 0;
847 char * resourceTypeName = NULL;
848 uint32_t lowerBound = 0;
849 uint32_t higherBound = 0;
851 unsigned char * bufRes = response->bufRes;
852 #endif // WITH_PRESENCE
854 cbNode = response->cbNode;
857 cbNode = GetClientCB(response->rcvdToken, NULL, NULL);
860 if(response->clientResponse->sequenceNumber >= OC_OFFSET_SEQUENCE_NUMBER)
862 isObserveNotification = 1;
863 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
866 OC_LOG_V(DEBUG, TAG, "The sequenceNumber/NONCE of this response %u",
867 response->clientResponse->sequenceNumber);
868 OC_LOG_V(DEBUG, TAG, "The maxAge/TTL of this response %u", response->maxAge);
869 OC_LOG_V(DEBUG, TAG, "The response received is %s", bufRes);
872 if(!strcmp((char *)response->rcvdUri, (char *)OC_PRESENCE_URI)){
873 isPresenceNotification = 1;
876 result = OC_STACK_INVALID_PARAM;
879 tok = strtok((char *)bufRes, "[:]}");
880 bufRes[strlen((char *)bufRes)] = ':';
881 tok = strtok(NULL, "[:]}");
882 bufRes[strlen((char *)bufRes)] = ':';
883 response->clientResponse->sequenceNumber = (uint32_t )atoi(tok);
884 OC_LOG_V(DEBUG, TAG, "The received NONCE is %u", response->clientResponse->sequenceNumber);
885 tok = strtok(NULL, "[:]}");
886 response->maxAge = (uint32_t )atoi(tok);
887 OC_LOG_V(DEBUG, TAG, "The received TTL is %u", response->maxAge);
888 tok = strtok(NULL, "[:]}");
891 resourceTypeName = (char *)OCMalloc(strlen(tok));
892 if(!resourceTypeName)
896 bufRes[strlen((char *)bufRes)] = ':';
897 strcpy(resourceTypeName, tok);
898 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
901 bufRes[strlen((char *)bufRes)] = ']';
904 // Check if the application subcribed for presence
907 cbNode = GetClientCB(NULL, NULL, response->fullUri);
910 // Check if application subscribed for multicast presence
913 snprintf((char *)response->fullUri, MAX_URI_LENGTH, "%s%s",
914 OC_MULTICAST_IP, response->rcvdUri);
915 cbNode = GetClientCB(NULL, NULL, response->fullUri);
918 isMulticastPresence = 1;
919 isPresenceNotification = 0;
923 if(cbNode && isPresenceNotification)
925 OC_LOG(INFO, TAG, PCF("Received a presence notification"));
926 if(!cbNode->presence)
928 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
929 VERIFY_NON_NULL_V(cbNode->presence);
930 cbNode->presence->timeOut = NULL;
931 cbNode->presence->timeOut = (uint32_t *)
932 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
933 if(!(cbNode->presence->timeOut)){
934 OCFree(cbNode->presence);
935 result = OC_STACK_NO_MEMORY;
938 if(response->maxAge == 0)
940 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
941 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
944 OCFree(cbNode->presence->timeOut);
945 OCFree(cbNode->presence);
946 cbNode->presence = NULL;
951 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %d", GetTime(0));
952 cbNode->presence->TTL = response->maxAge;
953 for(int index = 0; index < PresenceTimeOutSize; index++)
955 lowerBound = GetTime(((float)(PresenceTimeOut[index])
956 /(float)100)*(float)cbNode->presence->TTL);
957 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
958 /(float)100)*(float)cbNode->presence->TTL);
959 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
960 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
961 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
962 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
963 cbNode->presence->timeOut[index]);
965 cbNode->presence->TTLlevel = 0;
966 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
967 if(cbNode->sequenceNumber == response->clientResponse->sequenceNumber)
969 OC_LOG(INFO, TAG, PCF("===============No presence change"));
972 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
973 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;;
976 // Ensure that a filter is actually applied.
977 if(resourceTypeName && cbNode->filterResourceType)
979 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
985 else if(cbNode && isMulticastPresence)
987 // Check if the same nonce for a given host
988 OCMulticastNode* mcNode = NULL;
989 mcNode = GetMCPresenceNode(response->fullUri);
991 if(response->maxAge == 0)
993 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
994 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
997 OCFree(cbNode->presence->timeOut);
998 OCFree(cbNode->presence);
999 cbNode->presence = NULL;
1002 else if(mcNode != NULL)
1004 if(mcNode->nonce == response->clientResponse->sequenceNumber)
1006 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
1007 result = OC_STACK_NO_MEMORY;
1010 mcNode->nonce = response->clientResponse->sequenceNumber;
1014 uint32_t uriLen = strlen((char*)response->fullUri);
1015 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
1018 memcpy(uri, response->fullUri, (uriLen + 1));
1023 PCF("===============No Memory for URI to store in the presence node"));
1024 result = OC_STACK_NO_MEMORY;
1027 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri,
1028 response->clientResponse->sequenceNumber);
1029 if(result == OC_STACK_NO_MEMORY)
1032 PCF("===============No Memory for Multicast Presence Node"));
1033 result = OC_STACK_NO_MEMORY;
1038 // Ensure that a filter is actually applied.
1039 if(resourceTypeName && cbNode->filterResourceType)
1041 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1048 else if(!cbNode && isPresenceNotification)
1050 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
1051 ------------ ignoring"));
1053 #endif // WITH_PRESENCE
1057 if(isObserveNotification)
1059 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
1060 //TODO: check the standard for methods to detect wrap around condition
1061 if(cbNode->method == OC_REST_OBSERVE &&
1062 (response->clientResponse->sequenceNumber <= cbNode->sequenceNumber ||
1063 (response->clientResponse->sequenceNumber > cbNode->sequenceNumber &&
1064 response->clientResponse->sequenceNumber ==
1065 MAX_SEQUENCE_NUMBER)))
1067 OC_LOG_V(DEBUG, TAG, "Observe notification came out of order. \
1068 Ignoring Incoming:%d Against Current:%d.",
1069 response->clientResponse->sequenceNumber, cbNode->sequenceNumber);
1072 if(response->clientResponse->sequenceNumber > cbNode->sequenceNumber){
1073 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;
1077 response->clientResponse->resJSONPayload = bufRes;
1079 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response->clientResponse);
1081 if (cbResult == OC_STACK_DELETE_TRANSACTION ||
1082 response->clientResponse->result == OC_STACK_COMM_ERROR ||
1083 (response->clientResponse->result == OC_STACK_RESOURCE_DELETED &&
1084 !isPresenceNotification && !isMulticastPresence))
1086 FindAndDeleteClientCB(cbNode);
1091 result = OC_STACK_ERROR;
1095 #ifdef WITH_PRESENCE
1096 OCFree(resourceTypeName);
1101 int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
1104 unsigned char *itr, *coap;
1105 uint8_t dotCount = 0;
1109 /* search for scheme */
1111 if (!isdigit((unsigned char) *ipAddrStr))
1113 coap = (unsigned char *) OC_COAP_SCHEME;
1114 while (*coap && tolower(*itr) == *coap)
1122 while (*ipAddrStr) {
1123 if (isdigit((unsigned char) *ipAddrStr))
1125 ipAddr[index] *= 10;
1126 ipAddr[index] += *ipAddrStr - '0';
1128 else if ((unsigned char) *ipAddrStr == '.')
1140 if(*ipAddrStr == ':')
1144 if (isdigit((unsigned char) *ipAddrStr))
1147 *port += *ipAddrStr - '0';
1158 if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
1169 //-----------------------------------------------------------------------------
1170 // Private internal function prototypes
1171 //-----------------------------------------------------------------------------
1173 static OCDoHandle GenerateInvocationHandle();
1174 static OCStackResult initResources();
1175 static void insertResource(OCResource *resource);
1176 static OCResource *findResource(OCResource *resource);
1177 static void insertResourceType(OCResource *resource,
1178 OCResourceType *resourceType);
1179 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
1181 static void insertResourceInterface(OCResource *resource,
1182 OCResourceInterface *resourceInterface);
1183 static OCResourceInterface *findResourceInterfaceAtIndex(
1184 OCResourceHandle handle, uint8_t index);
1185 static void deleteResourceType(OCResourceType *resourceType);
1186 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
1187 static void deleteResourceElements(OCResource *resource);
1188 static int deleteResource(OCResource *resource);
1189 static void deleteAllResources();
1190 static void incrementSequenceNumber(OCResource * resPtr);
1191 static OCStackResult verifyUriQueryLength(const char * inputUri,
1193 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
1194 OCStackResult getResourceType(const char * query, unsigned char** resourceType);
1196 //-----------------------------------------------------------------------------
1198 //-----------------------------------------------------------------------------
1201 * Initialize the OC Stack. Must be called prior to starting the stack.
1204 * IP Address of host device
1206 * Port of host device
1208 * Host device is client, server, or client-server
1211 * OC_STACK_OK - no errors
1212 * OC_STACK_ERROR - stack init error
1214 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1216 OCStackResult result = OC_STACK_ERROR;
1217 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
1221 OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
1227 //It is ok to select network to CA_WIFI for now
1228 CAResult_t caResult = CASelectNetwork(CA_WIFI|CA_ETHERNET);
1229 if(caResult == CA_STATUS_OK)
1231 OC_LOG(INFO, TAG, PCF("CASelectNetwork to WIFI"));
1232 caResult = CARegisterHandler(HandleCARequests, HandleCAResponses);
1233 if(caResult == CA_STATUS_OK)
1235 OC_LOG(INFO, TAG, PCF("CARegisterHandler..."));
1236 stackState = OC_STACK_INITIALIZED;
1237 result = OC_STACK_OK;
1241 caResult = CAStartDiscoveryServer();
1242 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
1245 caResult = CAStartListeningServer();
1246 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
1248 case OC_CLIENT_SERVER:
1249 caResult = CAStartListeningServer();
1250 if(caResult == CA_STATUS_OK)
1252 caResult = CAStartDiscoveryServer();
1254 OC_LOG(INFO, TAG, PCF("Client-server mode"));
1257 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1258 return OC_STACK_ERROR;
1263 if (caResult == CA_STATUS_OK)
1265 result = OC_STACK_OK;
1269 result = OC_STACK_ERROR;
1276 OC_LOG(INFO, TAG, PCF("Client mode"));
1279 OC_LOG(INFO, TAG, PCF("Server mode"));
1281 case OC_CLIENT_SERVER:
1282 OC_LOG(INFO, TAG, PCF("Client-server mode"));
1285 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1286 return OC_STACK_ERROR;
1290 // Make call to OCCoAP layer
1291 result = OCInitCoAP(ipAddr, (uint16_t) port, myStackMode);
1295 defaultDeviceHandler = NULL;
1297 #ifdef WITH_PRESENCE
1298 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
1299 #endif // WITH_PRESENCE
1301 if (result == OC_STACK_OK)
1303 stackState = OC_STACK_INITIALIZED;
1305 // Initialize resource
1306 if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
1308 result = initResources();
1310 if(result != OC_STACK_OK)
1312 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1318 * Stop the OC stack. Use for a controlled shutdown.
1320 * OC_STACK_OK - no errors
1321 * OC_STACK_ERROR - stack not initialized
1323 OCStackResult OCStop()
1325 OCStackResult result = OC_STACK_ERROR;
1327 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1329 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1331 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1334 else if (stackState != OC_STACK_INITIALIZED)
1336 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1337 return OC_STACK_ERROR;
1340 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1342 #ifdef WITH_PRESENCE
1343 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1344 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1345 presenceResource.presenceTTL = 0;
1346 #endif // WITH_PRESENCE
1348 // Free memory dynamically allocated for resources
1349 deleteAllResources();
1353 //CATerminate does not return any error code. It is OK to assign result to OC_STACK_OK.
1354 result = OC_STACK_OK;
1356 result = OCStopCoAP();
1359 if (result == OC_STACK_OK)
1361 // Remove all observers
1362 DeleteObserverList();
1363 // Remove all the client callbacks
1364 DeleteClientCBList();
1365 stackState = OC_STACK_UNINITIALIZED;
1366 result = OC_STACK_OK;
1368 stackState = OC_STACK_INITIALIZED;
1369 result = OC_STACK_ERROR;
1372 // Deinit security blob
1373 DeinitOCSecurityInfo();
1375 if (result != OC_STACK_OK) {
1376 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
1383 * Verify the lengths of the URI and the query separately
1385 * @param inputUri - Input URI and query.
1386 * @param uriLen - The length of the initial URI with query.
1388 * Note: The '?' that appears after the URI is not considered as
1389 * a part of the query.
1391 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1395 query = strchr (inputUri, '?');
1399 if((query - inputUri) > MAX_URI_LENGTH)
1401 return OC_STACK_INVALID_URI;
1404 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1406 return OC_STACK_INVALID_QUERY;
1409 else if(uriLen > MAX_URI_LENGTH)
1411 return OC_STACK_INVALID_URI;
1417 * Discover or Perform requests on a specified resource (specified by that Resource's respective URI).
1419 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of calling this API.
1420 * @param method - @ref OCMethod to perform on the resource
1421 * @param requiredUri - URI of the resource to interact with
1422 * @param referenceUri - URI of the reference resource
1423 * @param request - JSON encoded request
1424 * @param qos - quality of service
1425 * @param cbData - struct that contains asynchronous callback function that is invoked
1426 * by the stack when discovery or resource interaction is complete
1427 * @param options - The address of an array containing the vendor specific header
1428 * header options to be sent with the request
1429 * @param numOptions - Number of vendor specific header options to be included
1432 * OC_STACK_OK - no errors
1433 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
1434 * OC_STACK_INVALID_METHOD - invalid resource method
1435 * OC_STACK_INVALID_URI - invalid required or reference URI
1437 * Note: IN case of CA, when using multicast, the required URI should not contain IP address.
1438 * Instead, it just contains the URI to the resource such as "/oc/core".
1441 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1442 const char *referenceUri, const char *request, uint8_t conType,
1443 OCQualityOfService qos, OCCallbackData *cbData,
1444 OCHeaderOption * options, uint8_t numOptions)
1446 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1447 const char *referenceUri, const char *request,
1448 OCQualityOfService qos, OCCallbackData *cbData,
1449 OCHeaderOption * options, uint8_t numOptions)
1452 OCStackResult result = OC_STACK_ERROR;
1454 ClientCB *clientCB = NULL;
1455 unsigned char * requestUri = NULL;
1456 unsigned char * resourceType = NULL;
1457 unsigned char * query = NULL;
1458 char * newUri = (char *)requiredUri;
1459 (void) referenceUri;
1461 CARemoteEndpoint_t* endpoint = NULL;
1462 CAResult_t caResult;
1463 CAToken_t caToken = NULL;
1464 CAInfo_t requestData;
1465 CARequestInfo_t requestInfo;
1466 CAGroupEndpoint_t grpEnd;
1468 // To track if memory is allocated for additional header options
1469 uint8_t hdrOptionMemAlloc = 0;
1472 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1474 // Validate input parameters
1475 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1476 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1478 TODO ("Need to form the final query by concatenating require and reference URI's");
1479 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
1481 uint16_t uriLen = strlen(requiredUri);
1483 // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS
1489 case OC_REST_DELETE:
1490 case OC_REST_OBSERVE:
1491 case OC_REST_OBSERVE_ALL:
1492 case OC_REST_CANCEL_OBSERVE:
1494 #ifdef WITH_PRESENCE
1495 case OC_REST_PRESENCE:
1499 result = OC_STACK_INVALID_METHOD;
1503 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
1508 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
1510 result = OC_STACK_INVALID_PARAM;
1514 #ifdef WITH_PRESENCE
1515 if(method == OC_REST_PRESENCE)
1517 result = getQueryFromUri(requiredUri, &query, &newUri);
1520 result = getResourceType((char *) query, &resourceType);
1523 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1527 OC_LOG(DEBUG, TAG, PCF("Resource type is NULL."));
1532 OC_LOG(DEBUG, TAG, PCF("Query string is NULL."));
1534 if(result != OC_STACK_OK)
1539 #endif // WITH_PRESENCE
1541 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
1544 memcpy(requestUri, newUri, (uriLen + 1));
1548 result = OC_STACK_NO_MEMORY;
1552 *handle = GenerateInvocationHandle();
1555 result = OC_STACK_NO_MEMORY;
1560 memset(&requestData, 0, sizeof(CAInfo_t));
1561 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1562 memset(&grpEnd, 0, sizeof(CAGroupEndpoint_t));
1566 case OC_REST_OBSERVE:
1567 case OC_REST_OBSERVE_ALL:
1568 case OC_REST_CANCEL_OBSERVE:
1570 requestInfo.method = CA_GET;
1575 requestInfo.method = CA_PUT;
1580 requestInfo.method = CA_POST;
1583 case OC_REST_DELETE:
1585 requestInfo.method = CA_DELETE;
1588 #ifdef WITH_PRESENCE
1589 case OC_REST_PRESENCE:
1591 // Replacing method type with GET because "presence"
1592 // is a stack layer only implementation.
1593 requestInfo.method = CA_GET;
1598 result = OC_STACK_INVALID_METHOD;
1602 //High QoS is not supported
1603 if(qos == OC_HIGH_QOS)
1605 result = OC_STACK_INVALID_PARAM;
1610 caResult = CAGenerateToken(&caToken);
1612 //TODO-CA Remove this temporary fix (for some reason same token is being generated)
1615 caToken[0] += count;
1617 if (caResult != CA_STATUS_OK)
1619 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1624 // TODO-CA: Map QoS to the right CA msg type
1625 requestData.type = CA_MSG_NONCONFIRM;
1626 requestData.token = caToken;
1627 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1629 result = CreateObserveHeaderOption (&(requestData.options), options,
1630 numOptions, OC_OBSERVE_REGISTER);
1631 if (result != OC_STACK_OK)
1635 hdrOptionMemAlloc = 1;
1636 requestData.numOptions = numOptions + 1;
1640 requestData.options = (CAHeaderOption_t*)options;
1641 requestData.numOptions = numOptions;
1643 requestData.payload = (char *)request;
1645 requestInfo.info = requestData;
1647 CAConnectivityType_t caConType;
1649 result = OCToCAConnectivityType(conType, &caConType);
1650 if (result != OC_STACK_OK)
1652 OC_LOG(ERROR, TAG, PCF("Invalid Connectivity Type"));
1657 if(conType == OC_ALL)
1659 grpEnd.connectivityType = caConType;
1661 grpEnd.resourceUri = (CAURI_t) OCMalloc(uriLen + 1);
1662 strncpy(grpEnd.resourceUri, requiredUri, (uriLen + 1));
1664 caResult = CASendRequestToAll(&grpEnd, &requestInfo);
1668 caResult = CACreateRemoteEndpoint(newUri, caConType, &endpoint);
1670 if (caResult != CA_STATUS_OK)
1672 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1676 caResult = CASendRequest(endpoint, &requestInfo);
1679 if (caResult != CA_STATUS_OK)
1681 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1685 if((result = AddClientCB(&clientCB, cbData, &caToken, handle, method,
1686 requestUri, resourceType)) != OC_STACK_OK)
1688 result = OC_STACK_NO_MEMORY;
1694 // Generate token which will be used by OCStack to match responses received
1696 OCGenerateCoAPToken(&token);
1698 if((result = AddClientCB(&clientCB, cbData, &token, handle, method, requestUri, resourceType))
1701 result = OC_STACK_NO_MEMORY;
1705 // Make call to OCCoAP layer
1706 result = OCDoCoAPResource(method, qos, &token, newUri, request, options, numOptions);
1710 if(newUri != requiredUri)
1714 if (result != OC_STACK_OK)
1716 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1717 FindAndDeleteClientCB(clientCB);
1720 CADestroyRemoteEndpoint(endpoint);
1721 OCFree(grpEnd.resourceUri);
1722 if (hdrOptionMemAlloc)
1724 OCFree(requestData.options);
1731 * Cancel a request associated with a specific @ref OCDoResource invocation.
1733 * @param handle - Used to identify a specific OCDoResource invocation.
1734 * @param qos - used to specify Quality of Service (read below for more info)
1735 * @param options- used to specify vendor specific header options when sending
1736 * explicit observe cancellation
1737 * @param numOptions- Number of header options to be included
1740 * OC_STACK_OK - No errors; Success
1741 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1743 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1747 * This ftn is implemented one of two ways in the case of observation:
1749 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1750 * Remove the callback associated on client side.
1751 * When the next notification comes in from server,
1752 * reply with RESET message to server.
1753 * Keep in mind that the server will react to RESET only
1754 * if the last notification was sent ans CON
1756 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1757 * and it is associated with an observe request
1758 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1759 * Send CON Observe request to server with
1760 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1761 * Remove the callback associated on client side.
1763 OCStackResult ret = OC_STACK_OK;
1765 CARemoteEndpoint_t* endpoint = NULL;
1766 CAResult_t caResult;
1767 CAInfo_t requestData;
1768 CARequestInfo_t requestInfo;
1769 // Track if memory is allocated for additional header options
1770 uint8_t hdrOptionMemAlloc = 0;
1774 return OC_STACK_INVALID_PARAM;
1777 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1779 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1782 switch (clientCB->method)
1784 case OC_REST_OBSERVE:
1785 case OC_REST_OBSERVE_ALL:
1787 //TODO-CA : Why CA_WIFI alone?
1788 caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri, CA_WIFI,
1790 if (caResult != CA_STATUS_OK)
1792 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1793 return OC_STACK_ERROR;
1796 memset(&requestData, 0, sizeof(CAInfo_t));
1797 // TODO-CA: Map QoS to the right CA msg type
1798 requestData.type = CA_MSG_NONCONFIRM;
1799 requestData.token = clientCB->token;
1800 if (CreateObserveHeaderOption (&(requestData.options),
1801 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
1803 return OC_STACK_ERROR;
1805 hdrOptionMemAlloc = 1;
1806 requestData.numOptions = numOptions + 1;
1807 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1808 requestInfo.method = CA_GET;
1809 requestInfo.info = requestData;
1811 caResult = CASendRequest(endpoint, &requestInfo);
1812 if (caResult != CA_STATUS_OK)
1814 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1816 if(caResult == CA_STATUS_OK)
1821 if(qos == OC_HIGH_QOS)
1823 ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
1824 &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
1829 FindAndDeleteClientCB(clientCB);
1833 #ifdef WITH_PRESENCE
1834 case OC_REST_PRESENCE:
1835 FindAndDeleteClientCB(clientCB);
1839 return OC_STACK_INVALID_METHOD;
1843 CADestroyRemoteEndpoint(endpoint);
1844 if (hdrOptionMemAlloc)
1846 OCFree(requestData.options);
1853 #ifdef WITH_PRESENCE
1855 OCStackResult OCProcessPresence()
1857 OCStackResult result = OC_STACK_OK;
1858 uint8_t ipAddr[4] = { 0 };
1861 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1862 ClientCB* cbNode = NULL;
1864 OCClientResponse clientResponse;
1865 OCResponse * response = NULL;
1866 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1868 LL_FOREACH(cbList, cbNode) {
1869 if(OC_REST_PRESENCE == cbNode->method)
1871 if(cbNode->presence)
1873 uint32_t now = GetTime(0);
1874 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d",
1875 cbNode->presence->TTLlevel);
1876 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1879 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1884 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1885 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1886 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1889 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1891 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1892 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1894 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1896 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
1897 (OCDevAddr *) &dst, 0, NULL);
1898 if(result != OC_STACK_OK)
1902 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1903 &cbNode->token, &clientResponse, NULL);
1904 if(result != OC_STACK_OK)
1909 // Increment the TTLLevel (going to a next state), so we don't keep
1910 // sending presence notification to client.
1911 cbNode->presence->TTLlevel++;
1912 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1913 cbNode->presence->TTLlevel);
1917 result = OC_STACK_INVALID_IP;
1921 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
1922 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1924 FindAndDeleteClientCB(cbNode);
1928 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1930 CAResult_t caResult;
1931 CARemoteEndpoint_t* endpoint = NULL;
1932 CAInfo_t requestData;
1933 CARequestInfo_t requestInfo;
1935 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
1937 //TODO-CA : Why CA_WIFI alone?
1938 caResult = CACreateRemoteEndpoint((char *)cbNode->requestUri, CA_WIFI,
1941 if (caResult != CA_STATUS_OK)
1943 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1947 memset(&requestData, 0, sizeof(CAInfo_t));
1949 // TODO-CA: Map QoS to the right CA msg type
1950 requestData.type = CA_MSG_NONCONFIRM;
1951 requestData.token = cbNode->token;
1953 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1954 requestInfo.method = CA_GET;
1955 requestInfo.info = requestData;
1957 caResult = CASendRequest(endpoint, &requestInfo);
1959 if (caResult != CA_STATUS_OK)
1961 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1965 cbNode->presence->TTLlevel++;
1966 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1967 cbNode->presence->TTLlevel);
1973 if (result != OC_STACK_OK)
1975 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
1980 OCStackResult OCProcessPresence()
1982 OCStackResult result = OC_STACK_OK;
1983 uint8_t ipAddr[4] = { 0 };
1986 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1987 ClientCB* cbNode = NULL;
1989 OCClientResponse clientResponse;
1990 OCResponse * response = NULL;
1992 LL_FOREACH(cbList, cbNode) {
1993 if(OC_REST_PRESENCE == cbNode->method)
1995 if(cbNode->presence)
1997 uint32_t now = GetTime(0);
1998 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
1999 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
2002 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
2007 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
2008 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
2009 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2012 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2014 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
2015 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
2017 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
2019 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
2020 (OCDevAddr *) &dst, 0, NULL);
2021 if(result != OC_STACK_OK)
2025 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
2026 &cbNode->token, &clientResponse, NULL);
2027 if(result != OC_STACK_OK)
2032 // Increment the TTLLevel (going to a next state), so we don't keep
2033 // sending presence notification to client.
2034 cbNode->presence->TTLlevel++;
2035 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
2036 cbNode->presence->TTLlevel);
2040 result = OC_STACK_INVALID_IP;
2043 HandleStackResponses(response);
2045 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2047 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
2050 OCGenerateCoAPToken(&token);
2051 result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
2052 &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
2054 if(result != OC_STACK_OK)
2058 cbNode->presence->TTLlevel++;
2059 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
2065 if (result != OC_STACK_OK)
2067 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
2072 #endif // WITH_PRESENCE
2075 * Called in main loop of OC client or server. Allows low-level processing of
2079 * OC_STACK_OK - no errors
2080 * OC_STACK_ERROR - stack process error
2082 OCStackResult OCProcess() {
2084 OC_LOG(INFO, TAG, PCF("Entering OCProcess"));
2085 #ifdef WITH_PRESENCE
2086 OCProcessPresence();
2089 CAHandleRequestResponse();
2097 #ifdef WITH_PRESENCE
2099 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
2100 * presence notifications to clients via multicast. Once this API has been called with a success,
2101 * clients may query for this server's presence and this server's stack will respond via multicast.
2103 * Server can call this function when it comes online for the first time, or when it comes back
2104 * online from offline mode, or when it re enters network.
2106 * @param ttl - Time To Live in seconds
2107 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
2110 * OC_STACK_OK - No errors; Success
2112 OCStackResult OCStartPresence(const uint32_t ttl)
2114 OCChangeResourceProperty(
2115 &(((OCResource *)presenceResource.handle)->resourceProperties),
2120 presenceResource.presenceTTL = ttl;
2123 if(OC_PRESENCE_UNINITIALIZED == presenceState)
2125 OCDevAddr multiCastAddr;
2128 presenceState = OC_PRESENCE_INITIALIZED;
2129 OCGenerateCoAPToken(&token);
2130 OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
2132 CAAddress_t addressInfo;
2133 strncpy(addressInfo.IP.ipAddress, "224.0.1.187", CA_IPADDR_SIZE);
2134 addressInfo.IP.port = 5298;
2136 CAToken_t caToken = NULL;
2137 CAGenerateToken(&caToken);
2139 AddCAObserver(OC_PRESENCE_URI, NULL, 0, &token,
2140 &multiCastAddr, (OCResource *)presenceResource.handle, OC_LOW_QOS,
2141 &addressInfo, CA_WIFI, caToken);
2143 //add the presence observer
2144 AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
2145 (OCResource *)presenceResource.handle, OC_LOW_QOS);
2149 // Each time OCStartPresence is called
2150 // a different random 32-bit integer number is used
2151 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2153 return SendPresenceNotification(NULL);
2157 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
2158 * presence notifications to clients via multicast. Once this API has been called with a success,
2159 * this server's stack will not respond to clients querying for this server's presence.
2161 * Server can call this function when it is terminating, going offline, or when going
2162 * away from network.
2165 * OC_STACK_OK - No errors; Success
2167 OCStackResult OCStopPresence()
2169 OCStackResult result = OC_STACK_ERROR;
2170 //make resource inactive
2171 result = OCChangeResourceProperty(
2172 &(((OCResource *) presenceResource.handle)->resourceProperties),
2174 result = SendPresenceNotification(NULL);
2181 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
2183 defaultDeviceHandler = entityHandler;
2188 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2190 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
2192 if(myStackMode == OC_CLIENT)
2194 return OC_STACK_ERROR;
2197 return SaveDeviceInfo(deviceInfo);
2203 * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource
2204 * @param resourceTypeName - name of resource type. Example: "core.led"
2205 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
2206 * @param uri - URI of the resource. Example: "/a/led"
2207 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2208 * NULL for default entity handler
2209 * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE
2212 * OC_STACK_OK - no errors
2213 * OC_STACK_ERROR - stack process error
2215 OCStackResult OCCreateResource(OCResourceHandle *handle,
2216 const char *resourceTypeName,
2217 const char *resourceInterfaceName,
2218 const char *uri, OCEntityHandler entityHandler,
2219 uint8_t resourceProperties) {
2221 OCResource *pointer = NULL;
2224 OCStackResult result = OC_STACK_ERROR;
2226 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
2228 if(myStackMode == OC_CLIENT)
2232 // Validate parameters
2233 if(!uri || (strlen(uri) == 0))
2235 OC_LOG(ERROR, TAG, PCF("URI is invalid"));
2236 return OC_STACK_INVALID_URI;
2238 // Is it presented during resource discovery?
2239 if (!handle || !resourceTypeName) {
2240 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
2241 return OC_STACK_INVALID_PARAM;
2244 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
2245 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2248 // Make sure resourceProperties bitmask has allowed properties specified
2249 if (resourceProperties
2250 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
2251 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2252 return OC_STACK_INVALID_PARAM;
2255 // If the headResource is NULL, then no resources have been created...
2256 pointer = headResource;
2258 // At least one resources is in the resource list, so we need to search for
2259 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2261 if (strcmp(uri, pointer->uri) == 0) {
2262 OC_LOG(ERROR, TAG, PCF("URI already in use"));
2263 return OC_STACK_INVALID_PARAM;
2265 pointer = pointer->next;
2268 // Create the pointer and insert it into the resource list
2269 pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
2273 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2275 insertResource(pointer);
2278 size = strlen(uri) + 1;
2279 str = (char *) OCMalloc(size);
2283 strncpy(str, uri, size);
2286 // Set properties. Set OC_ACTIVE
2287 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2290 // Add the resourcetype to the resource
2291 result = BindResourceTypeToResource(pointer, resourceTypeName);
2292 if (result != OC_STACK_OK) {
2293 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
2297 // Add the resourceinterface to the resource
2298 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2299 if (result != OC_STACK_OK) {
2300 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
2304 // If an entity handler has been passed, attach it to the newly created
2305 // resource. Otherwise, set the default entity handler.
2308 pointer->entityHandler = entityHandler;
2312 pointer->entityHandler = defaultResourceEHandler;
2316 result = OC_STACK_OK;
2318 #ifdef WITH_PRESENCE
2319 if(presenceResource.handle)
2321 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2322 SendPresenceNotification(pointer->rsrcType);
2326 if (result != OC_STACK_OK)
2328 // Deep delete of resource and other dynamic elements that it contains
2329 deleteResource(pointer);
2338 * Create a resource. with host ip address for remote resource
2340 * @param handle - pointer to handle to newly created resource. Set by ocstack.
2341 * Used to refer to resource
2342 * @param resourceTypeName - name of resource type. Example: "core.led"
2343 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
2344 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
2345 * @param uri - URI of the resource. Example: "/a/led"
2346 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2347 * NULL for default entity handler
2348 * @param resourceProperties - properties supported by resource.
2349 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
2352 * OC_STACK_OK - no errors
2353 * OC_STACK_ERROR - stack process error
2356 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
2357 const char *resourceTypeName,
2358 const char *resourceInterfaceName,
2361 OCEntityHandler entityHandler,
2362 uint8_t resourceProperties)
2366 OCStackResult result = OC_STACK_ERROR;
2368 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
2369 uri, entityHandler, resourceProperties);
2371 if (result != OC_STACK_ERROR)
2374 size = strlen(host) + 1;
2375 str = (char *) OCMalloc(size);
2378 return OC_STACK_ERROR;
2380 strncpy(str, host, size);
2381 ((OCResource *) *handle)->host = str;
2388 * Add a resource to a collection resource.
2390 * @param collectionHandle - handle to the collection resource
2391 * @param resourceHandle - handle to resource to be added to the collection resource
2394 * OC_STACK_OK - no errors
2395 * OC_STACK_ERROR - stack process error
2396 * OC_STACK_INVALID_PARAM - invalid collectionhandle
2398 OCStackResult OCBindResource(
2399 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2400 OCResource *resource;
2403 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2405 // Validate parameters
2406 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2407 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2408 // Container cannot contain itself
2409 if (collectionHandle == resourceHandle) {
2410 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2411 return OC_STACK_INVALID_PARAM;
2414 // Use the handle to find the resource in the resource linked list
2415 resource = findResource((OCResource *) collectionHandle);
2417 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2418 return OC_STACK_INVALID_PARAM;
2421 // Look for an open slot to add add the child resource.
2422 // If found, add it and return success
2423 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2424 if (!resource->rsrcResources[i]) {
2425 resource->rsrcResources[i] = (OCResource *) resourceHandle;
2426 OC_LOG(INFO, TAG, PCF("resource bound"));
2431 #ifdef WITH_PRESENCE
2432 if(presenceResource.handle)
2434 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2435 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2439 // Unable to add resourceHandle, so return error
2440 return OC_STACK_ERROR;
2444 * Remove a resource from a collection resource.
2446 * @param collectionHandle - handle to the collection resource
2447 * @param resourceHandle - handle to resource to be added to the collection resource
2450 * OC_STACK_OK - no errors
2451 * OC_STACK_ERROR - stack process error
2452 * OC_STACK_INVALID_PARAM - invalid collectionHandle
2454 OCStackResult OCUnBindResource(
2455 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2456 OCResource *resource;
2459 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2461 // Validate parameters
2462 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2463 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2464 // Container cannot contain itself
2465 if (collectionHandle == resourceHandle) {
2466 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2467 return OC_STACK_INVALID_PARAM;
2470 // Use the handle to find the resource in the resource linked list
2471 resource = findResource((OCResource *) collectionHandle);
2473 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2474 return OC_STACK_INVALID_PARAM;
2477 // Look for an open slot to add add the child resource.
2478 // If found, add it and return success
2479 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2480 if (resourceHandle == resource->rsrcResources[i]) {
2481 resource->rsrcResources[i] = (OCResource *) NULL;
2482 OC_LOG(INFO, TAG, PCF("resource unbound"));
2487 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2489 #ifdef WITH_PRESENCE
2490 if(presenceResource.handle)
2492 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2493 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2497 // Unable to add resourceHandle, so return error
2498 return OC_STACK_ERROR;
2501 OCStackResult BindResourceTypeToResource(OCResource* resource,
2502 const char *resourceTypeName)
2504 OCResourceType *pointer = NULL;
2507 OCStackResult result = OC_STACK_ERROR;
2509 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
2511 // Validate parameters
2512 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2513 // TODO: Does resource attribute resentation really have to be maintained in stack?
2514 // Is it presented during resource discovery?
2516 TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
2518 // Create the resourcetype and insert it into the resource list
2519 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
2524 // Set the resourceTypeName
2525 size = strlen(resourceTypeName) + 1;
2526 str = (char *) OCMalloc(size);
2530 strncpy(str, resourceTypeName, size);
2531 pointer->resourcetypename = str;
2533 insertResourceType(resource, pointer);
2534 result = OC_STACK_OK;
2536 exit: if (result != OC_STACK_OK) {
2544 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2545 const char *resourceInterfaceName)
2547 OCResourceInterface *pointer = NULL;
2550 OCStackResult result = OC_STACK_ERROR;
2552 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
2554 // Validate parameters
2555 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2557 TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
2559 // Create the resourceinterface and insert it into the resource list
2560 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
2565 // Set the resourceinterface name
2566 size = strlen(resourceInterfaceName) + 1;
2567 str = (char *) OCMalloc(size);
2571 strncpy(str, resourceInterfaceName, size);
2572 pointer->name = str;
2574 // Bind the resourceinterface to the resource
2575 insertResourceInterface(resource, pointer);
2577 result = OC_STACK_OK;
2579 exit: if (result != OC_STACK_OK) {
2588 * Bind a resourcetype to a resource.
2590 * @param handle - handle to the resource
2591 * @param resourceTypeName - name of resource type. Example: "core.led"
2594 * OC_STACK_OK - no errors
2595 * OC_STACK_ERROR - stack process error
2597 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2598 const char *resourceTypeName) {
2600 OCStackResult result = OC_STACK_ERROR;
2601 OCResource *resource;
2603 // Make sure resource exists
2604 resource = findResource((OCResource *) handle);
2606 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2607 return OC_STACK_ERROR;
2610 // call internal function
2611 result = BindResourceTypeToResource(resource, resourceTypeName);
2613 #ifdef WITH_PRESENCE
2614 if(presenceResource.handle)
2616 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2617 SendPresenceNotification(resource->rsrcType);
2625 * Bind a resourceinterface to a resource.
2627 * @param handle - handle to the resource
2628 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
2631 * OC_STACK_OK - no errors
2632 * OC_STACK_ERROR - stack process error
2635 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2636 const char *resourceInterfaceName) {
2638 OCStackResult result = OC_STACK_ERROR;
2639 OCResource *resource;
2641 // Make sure resource exists
2642 resource = findResource((OCResource *) handle);
2644 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2645 return OC_STACK_ERROR;
2648 // call internal function
2649 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2651 #ifdef WITH_PRESENCE
2652 if(presenceResource.handle)
2654 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2655 SendPresenceNotification(resource->rsrcType);
2663 * Get the number of resources that have been created in the stack.
2665 * @param numResources - pointer to count variable
2668 * OC_STACK_OK - no errors
2669 * OC_STACK_ERROR - stack process error
2672 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
2673 OCResource *pointer = headResource;
2675 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2676 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2679 *numResources = *numResources + 1;
2680 pointer = pointer->next;
2686 * Get a resource handle by index.
2688 * @param index - index of resource, 0 to Count - 1
2691 * Resource handle - if found
2692 * NULL - if not found
2694 OCResourceHandle OCGetResourceHandle(uint8_t index) {
2695 OCResource *pointer = headResource;
2698 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2700 // Iterate through the list
2701 while ((i < index) && pointer) {
2703 pointer = pointer->next;
2705 return (OCResourceHandle) pointer;
2709 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
2712 * @param handle - handle of resource to be deleted
2715 * OC_STACK_OK - no errors
2716 * OC_STACK_ERROR - stack process error
2717 * OC_STACK_NO_RESOURCE - resource not found
2718 * OC_STACK_INVALID_PARAM - invalid param
2720 OCStackResult OCDeleteResource(OCResourceHandle handle) {
2721 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2724 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2725 return OC_STACK_INVALID_PARAM;
2728 OCResource *resource = findResource((OCResource *) handle);
2729 if (resource == NULL) {
2730 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2731 return OC_STACK_NO_RESOURCE;
2734 if (deleteResource((OCResource *) handle) == 0) {
2735 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2736 return OC_STACK_ERROR;
2743 * Get the URI of the resource specified by handle.
2745 * @param handle - handle of resource
2747 * URI string - if resource found
2748 * NULL - resource not found
2750 const char *OCGetResourceUri(OCResourceHandle handle) {
2751 OCResource *resource;
2752 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2754 resource = findResource((OCResource *) handle);
2756 return resource->uri;
2758 return (const char *) NULL;
2762 * Get the properties of the resource specified by handle.
2763 * NOTE: that after a resource is created, the OC_ACTIVE property is set
2764 * for the resource by the stack.
2766 * @param handle - handle of resource
2768 * property bitmap - if resource found
2769 * NULL - resource not found
2771 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
2772 OCResource *resource;
2773 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2775 resource = findResource((OCResource *) handle);
2777 return resource->resourceProperties;
2783 * Get the number of resource types of the resource.
2785 * @param handle - handle of resource
2786 * @param numResourceTypes - pointer to count variable
2789 * OC_STACK_OK - no errors
2790 * OC_STACK_ERROR - stack process error
2792 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2793 uint8_t *numResourceTypes) {
2794 OCResource *resource;
2795 OCResourceType *pointer;
2797 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2798 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2799 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2801 *numResourceTypes = 0;
2803 resource = findResource((OCResource *) handle);
2805 pointer = resource->rsrcType;
2807 *numResourceTypes = *numResourceTypes + 1;
2808 pointer = pointer->next;
2815 * Get name of resource type of the resource.
2817 * @param handle - handle of resource
2818 * @param index - index of resource, 0 to Count - 1
2821 * resource type name - if resource found
2822 * NULL - resource not found
2824 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
2825 OCResourceType *resourceType;
2827 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2829 resourceType = findResourceTypeAtIndex(handle, index);
2831 return resourceType->resourcetypename;
2833 return (const char *) NULL;
2839 * Get the number of resource interfaces of the resource.
2841 * @param handle - handle of resource
2842 * @param numResources - pointer to count variable
2845 * OC_STACK_OK - no errors
2846 * OC_STACK_ERROR - stack process error
2848 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2849 uint8_t *numResourceInterfaces) {
2850 OCResourceInterface *pointer;
2851 OCResource *resource;
2853 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2855 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2856 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2858 *numResourceInterfaces = 0;
2859 resource = findResource((OCResource *) handle);
2861 pointer = resource->rsrcInterface;
2863 *numResourceInterfaces = *numResourceInterfaces + 1;
2864 pointer = pointer->next;
2871 * Get name of resource interface of the resource.
2873 * @param handle - handle of resource
2874 * @param index - index of resource, 0 to Count - 1
2877 * resource interface name - if resource found
2878 * NULL - resource not found
2880 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
2881 OCResourceInterface *resourceInterface;
2883 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2885 resourceInterface = findResourceInterfaceAtIndex(handle, index);
2886 if (resourceInterface) {
2887 return resourceInterface->name;
2889 return (const char *) NULL;
2893 * Get resource handle from the collection resource by index.
2895 * @param collectionHandle - handle of collection resource
2896 * @param index - index of contained resource, 0 to Count - 1
2899 * handle to resource - if resource found
2900 * NULL - resource not found
2902 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2904 OCResource *resource;
2906 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2908 if (index >= MAX_CONTAINED_RESOURCES) {
2912 resource = findResource((OCResource *) collectionHandle);
2917 return resource->rsrcResources[index];
2921 * Bind an entity handler to the resource.
2923 * @param handle - handle to the resource that the contained resource is to be bound
2924 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2926 * OC_STACK_OK - no errors
2927 * OC_STACK_ERROR - stack process error
2929 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2930 OCEntityHandler entityHandler) {
2931 OCResource *resource;
2933 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2935 // Validate parameters
2936 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2937 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2939 // Use the handle to find the resource in the resource linked list
2940 resource = findResource((OCResource *)handle);
2942 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2943 return OC_STACK_ERROR;
2947 resource->entityHandler = entityHandler;
2949 #ifdef WITH_PRESENCE
2950 if(presenceResource.handle)
2952 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2953 SendPresenceNotification(resource->rsrcType);
2961 * Get the entity handler for a resource.
2963 * @param handle - handle of resource
2966 * entity handler - if resource found
2967 * NULL - resource not found
2969 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
2970 OCResource *resource;
2972 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2974 // Use the handle to find the resource in the resource linked list
2975 resource = findResource((OCResource *)handle);
2977 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2982 return resource->entityHandler;
2985 void incrementSequenceNumber(OCResource * resPtr)
2987 // Increment the sequence number
2988 resPtr->sequenceNum += 1;
2989 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2991 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2997 * Notify Presence subscribers that a resource has been modified
2999 * @param resourceType - Handle to the resourceType linked list of resource
3000 * that was modified.
3001 * @param qos - Quality Of Service
3004 #ifdef WITH_PRESENCE
3005 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
3007 OCResource *resPtr = NULL;
3008 OCStackResult result;
3009 OCMethod method = OC_REST_PRESENCE;
3010 uint32_t maxAge = 0;
3011 resPtr = findResource((OCResource *) presenceResource.handle);
3014 return OC_STACK_NO_RESOURCE;
3016 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3018 maxAge = presenceResource.presenceTTL;
3025 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
3029 #endif // WITH_PRESENCE
3031 * Notify observers that an observed value has changed.
3033 * @param handle - handle of resource
3036 * OC_STACK_OK - no errors
3037 * OC_STACK_NO_RESOURCE - invalid resource handle
3038 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
3040 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
3042 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
3044 OCResource *resPtr = NULL;
3045 OCStackResult result;
3046 OCMethod method = OC_REST_NOMETHOD;
3047 uint32_t maxAge = 0;
3049 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
3050 #ifdef WITH_PRESENCE
3051 if(handle == presenceResource.handle)
3055 #endif // WITH_PRESENCE
3056 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3058 // Verify that the resource exists
3059 resPtr = findResource ((OCResource *) handle);
3062 return OC_STACK_NO_RESOURCE;
3066 //only increment in the case of regular observing (not presence)
3067 incrementSequenceNumber(resPtr);
3068 method = OC_REST_OBSERVE;
3069 maxAge = MAX_OBSERVE_AGE;
3070 #ifdef WITH_PRESENCE
3071 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
3073 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3080 OCNotifyListOfObservers (OCResourceHandle handle,
3081 OCObservationId *obsIdList,
3082 uint8_t numberOfIds,
3083 unsigned char *notificationJSONPayload,
3084 OCQualityOfService qos)
3086 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
3088 OCResource *resPtr = NULL;
3089 //TODO: we should allow the server to define this
3090 uint32_t maxAge = MAX_OBSERVE_AGE;
3092 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3093 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3094 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
3096 // Verify that the resource exists
3097 resPtr = findResource ((OCResource *) handle);
3098 if (NULL == resPtr || myStackMode == OC_CLIENT)
3100 return OC_STACK_NO_RESOURCE;
3104 incrementSequenceNumber(resPtr);
3106 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3107 notificationJSONPayload, maxAge, qos));
3111 * Send a response to a request.
3112 * The response can be a regular, slow, or block (i.e. a response that
3113 * is too large to be sent in a single PDU and must span multiple transmissions)
3115 * @param response - pointer to structure that contains response parameters
3118 * OC_STACK_OK - No errors; Success
3119 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
3120 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
3121 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
3122 * persistent response buffer is necessary
3124 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3126 OCStackResult result = OC_STACK_ERROR;
3127 OCServerRequest *serverRequest = NULL;
3129 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
3131 // Validate input parameters
3132 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3133 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3135 // TODO: Placeholder for creating a response entry when implementing
3136 // block transfer feature
3138 // If a response payload is present, check if block transfer is required
3139 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
3140 (const char *)ehResponse->payload, ehResponse->payloadSize))
3142 OC_LOG(INFO, TAG, PCF("Block transfer required"));
3144 // Persistent response buffer is needed for block transfer
3145 if (!ehResponse->persistentBufferFlag)
3147 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
3148 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
3150 // TODO: Placeholder for block transfer handling
3151 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
3152 // when implementing the block transfer feature
3157 // Get pointer to request info
3158 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3161 result = serverRequest->ehResponseHandler(ehResponse);
3168 * Cancel a response. Applies to a block response
3170 * @param responseHandle - response handle set by stack in OCServerResponse after
3171 * OCDoResponse is called
3174 * OC_STACK_OK - No errors; Success
3175 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
3177 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
3179 OCStackResult result = OC_STACK_NOTIMPL;
3181 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
3183 // TODO: validate response handle
3188 //-----------------------------------------------------------------------------
3189 // Private internal function definitions
3190 //-----------------------------------------------------------------------------
3192 * Generate handle of OCDoResource invocation for callback management.
3194 static OCDoHandle GenerateInvocationHandle()
3196 OCDoHandle handle = NULL;
3197 // Generate token here, it will be deleted when the transaction is deleted
3198 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
3201 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
3206 #ifdef WITH_PRESENCE
3207 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3208 OCResourceProperty resourceProperties, uint8_t enable)
3210 if (resourceProperties
3211 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
3212 OC_LOG(ERROR, TAG, PCF("Invalid property"));
3213 return OC_STACK_INVALID_PARAM;
3217 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3221 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3228 * Initialize resource data structures, variables, etc.
3230 OCStackResult initResources() {
3231 OCStackResult result = OC_STACK_OK;
3232 // Init application resource vars
3233 headResource = NULL;
3234 // Init Virtual Resources
3235 #ifdef WITH_PRESENCE
3236 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
3237 //presenceResource.token = OCGenerateCoAPToken();
3238 result = OCCreateResource(&presenceResource.handle,
3239 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3244 //make resource inactive
3245 result = OCChangeResourceProperty(
3246 &(((OCResource *) presenceResource.handle)->resourceProperties),
3253 * Add a resource to the end of the linked list of resources.
3255 * @param resource - resource to be added
3257 void insertResource(OCResource *resource) {
3258 OCResource *pointer;
3260 if (!headResource) {
3261 headResource = resource;
3263 pointer = headResource;
3265 while (pointer->next) {
3266 pointer = pointer->next;
3268 pointer->next = resource;
3270 resource->next = NULL;
3274 * Find a resource in the linked list of resources.
3276 * @param resource - resource to be found
3278 * NULL - resource not found
3279 * pointer to resource - pointer to resource that was found in the linked list
3281 OCResource *findResource(OCResource *resource) {
3282 OCResource *pointer = headResource;
3285 if (pointer == resource) {
3288 pointer = pointer->next;
3293 void deleteAllResources()
3295 OCResource *pointer = headResource;
3300 temp = pointer->next;
3301 #ifdef WITH_PRESENCE
3302 if(pointer != (OCResource *) presenceResource.handle)
3304 #endif // WITH_PRESENCE
3305 deleteResource(pointer);
3306 #ifdef WITH_PRESENCE
3308 #endif // WITH_PRESENCE
3312 #ifdef WITH_PRESENCE
3313 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3314 // presence notification attributed to their deletion to be processed.
3315 deleteResource((OCResource *) presenceResource.handle);
3316 #endif // WITH_PRESENCE
3320 * Delete the resource from the linked list.
3322 * @param resource - resource to be deleted
3327 int deleteResource(OCResource *resource) {
3328 OCResource *prev = NULL;
3331 temp = headResource;
3333 if (temp == resource) {
3334 // Invalidate all Resource Properties.
3335 resource->resourceProperties = (OCResourceProperty) 0;
3336 #ifdef WITH_PRESENCE
3337 if(resource != (OCResource *) presenceResource.handle)
3339 #endif // WITH_PRESENCE
3340 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3341 #ifdef WITH_PRESENCE
3344 if(presenceResource.handle)
3346 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3347 if(resource != (OCResource *) presenceResource.handle)
3349 SendPresenceNotification(resource->rsrcType);
3353 SendPresenceNotification(NULL);
3358 if (temp == headResource) {
3359 headResource = temp->next;
3361 prev->next = temp->next;
3364 deleteResourceElements(temp);
3377 * Delete all of the dynamically allocated elements that were created for the resource.
3379 * @param resource - specified resource
3381 void deleteResourceElements(OCResource *resource) {
3387 OCFree(resource->uri);
3389 // Delete resourcetype linked list
3390 deleteResourceType(resource->rsrcType);
3392 // Delete resourceinterface linked list
3393 deleteResourceInterface(resource->rsrcInterface);
3397 * Delete all of the dynamically allocated elements that were created for the resource type.
3399 * @param resourceType - specified resource type
3401 void deleteResourceType(OCResourceType *resourceType) {
3402 OCResourceType *pointer = resourceType;
3403 OCResourceType *next;
3406 next = pointer->next;
3407 OCFree(pointer->resourcetypename);
3414 * Delete all of the dynamically allocated elements that were created for the resource interface.
3416 * @param resourceInterface - specified resource interface
3418 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
3419 OCResourceInterface *pointer = resourceInterface;
3420 OCResourceInterface *next;
3423 next = pointer->next;
3424 OCFree(pointer->name);
3431 * Insert a resource type into a resource's resource type linked list.
3433 * @param resource - resource where resource type is to be inserted
3434 * @param resourceType - resource type to be inserted
3436 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
3437 OCResourceType *pointer;
3439 if (resource && !resource->rsrcType) {
3440 resource->rsrcType = resourceType;
3444 pointer = resource->rsrcType;
3448 pointer = resourceType;
3450 while (pointer->next) {
3451 pointer = pointer->next;
3453 pointer->next = resourceType;
3455 resourceType->next = NULL;
3459 * Get a resource type at the specified index within a resource.
3461 * @param handle - handle of resource
3462 * @param index - index of resource type
3465 * resourcetype - if found
3468 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
3469 OCResource *resource;
3470 OCResourceType *pointer;
3473 // Find the specified resource
3474 resource = findResource((OCResource *) handle);
3479 // Make sure a resource has a resourcetype
3480 if (!resource->rsrcType) {
3484 // Iterate through the list
3485 pointer = resource->rsrcType;
3487 while ((i < index) && pointer) {
3489 pointer = pointer->next;
3495 * Finds a resource type in an OCResourceType link-list.
3497 * @param resourceTypeList - the link-list to be searched through
3498 * @param resourceTypeName - the key to search for
3501 * resourceType that matches the key (ie. resourceTypeName)
3502 * NULL - either an invalid parameter or this function was unable to find the key.
3504 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3506 if(resourceTypeList && resourceTypeName)
3508 OCResourceType * rtPointer = resourceTypeList;
3509 while(resourceTypeName && rtPointer)
3511 if(rtPointer->resourcetypename &&
3512 strcmp(resourceTypeName, (const char *)
3513 (rtPointer->resourcetypename)) == 0)
3517 rtPointer = rtPointer->next;
3524 * Insert a resource interface into a resource's resource interface linked list.
3526 * @param resource - resource where resource interface is to be inserted
3527 * @param resourceInterface - resource interface to be inserted
3529 void insertResourceInterface(OCResource *resource,
3530 OCResourceInterface *resourceInterface) {
3531 OCResourceInterface *pointer;
3533 if (!resource->rsrcInterface) {
3534 resource->rsrcInterface = resourceInterface;
3536 pointer = resource->rsrcInterface;
3537 while (pointer->next) {
3538 pointer = pointer->next;
3540 pointer->next = resourceInterface;
3542 resourceInterface->next = NULL;
3546 * Get a resource interface at the specified index within a resource.
3548 * @param handle - handle of resource
3549 * @param index - index of resource interface
3552 * resourceinterface - if found
3555 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3557 OCResource *resource;
3558 OCResourceInterface *pointer;
3561 // Find the specified resource
3562 resource = findResource((OCResource *) handle);
3567 // Make sure a resource has a resourceinterface
3568 if (!resource->rsrcInterface) {
3572 // Iterate through the list
3573 pointer = resource->rsrcInterface;
3575 while ((i < index) && pointer) {
3577 pointer = pointer->next;
3583 * Determine if a request/response must be sent in a block transfer because it is too large to be
3584 * sent in a single PDU. This function can be used for either a request or a response
3586 * @param request - NULL or pointer to request
3587 * @param response - NULL or pointer to response
3588 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
3589 * the length of the request/response
3592 * 0 - packet transfer NOT required (i.e. normal request/response)
3593 * 1 - packet transfer required (i.e. block transfer needed)
3595 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
3599 // Determine if we are checking a request or a response
3602 // If size is greater than 0, use it for the request size value, otherwise
3603 // assume request is null terminated and use strlen for size value
3604 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
3611 // If size is greater than 0, use it for the response size value, otherwise
3612 // assume response is null terminated and use strlen for size value
3613 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3622 * Retrieves a resource type based upon a query ontains only just one
3623 * resource attribute (and that has to be of type "rt").
3625 * @remark This API malloc's memory for the resource type. Do not malloc resourceType
3626 * before passing in.
3628 * @param query - The quert part of the URI
3629 * @param resourceType - The resource type to be populated; pass by reference.
3632 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
3633 * OC_STACK_OK - Success
3635 OCStackResult getResourceType(const char * query, unsigned char** resourceType)
3639 return OC_STACK_INVALID_PARAM;
3642 OCStackResult result = OC_STACK_ERROR;
3644 if(strncmp(query, "rt=", 3) == 0)
3646 *resourceType = (unsigned char *) OCMalloc(strlen(query)-3);
3649 result = OC_STACK_NO_MEMORY;
3652 strcpy((char *)*resourceType, ((const char *)&query[3]));
3653 result = OC_STACK_OK;
3659 OCStackResult getQueryFromUri(const char * uri, unsigned char** query, char ** newURI)
3663 return OC_STACK_INVALID_URI;
3665 if(!query || !newURI)
3667 return OC_STACK_INVALID_PARAM;
3669 char * leftToken = NULL;
3670 char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3675 strcpy(tempURI, uri);
3677 leftToken = strtok_r((char *)tempURI, "?", &strTokPtr);
3679 //TODO-CA: This could be simplified. Clean up required.
3680 while(leftToken != NULL)
3682 if(strncmp(leftToken, "rt=", 3) == 0 || strncmp(leftToken, "if=", 3) == 0)
3684 *query = (unsigned char *) OCMalloc(strlen(leftToken));
3689 strcpy((char *)*query, ((const char *)&leftToken[0]));
3692 leftToken = strtok_r(NULL, "?", &strTokPtr);
3700 return OC_STACK_NO_MEMORY;
3703 const ServerID OCGetServerInstanceID(void)
3705 static bool generated = false;
3706 static ServerID sid;
3713 sid = OCGetRandom();
3718 const char* OCGetServerInstanceIDString(void)
3720 // max printed length of a base 10
3721 // uint32 is 10 characters, so 11 includes null.
3722 // This will change as the representation gets switched
3724 static char buffer[11];
3725 int n = sprintf(buffer, "%u", OCGetServerInstanceID());