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();
1352 // Make call to OCCoAP layer
1353 if (OCStopCoAP() == OC_STACK_OK)
1355 // Remove all observers
1356 DeleteObserverList();
1357 // Remove all the client callbacks
1358 DeleteClientCBList();
1359 stackState = OC_STACK_UNINITIALIZED;
1360 result = OC_STACK_OK;
1362 stackState = OC_STACK_INITIALIZED;
1363 result = OC_STACK_ERROR;
1366 // Deinit security blob
1367 DeinitOCSecurityInfo();
1369 if (result != OC_STACK_OK) {
1370 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
1377 * Verify the lengths of the URI and the query separately
1379 * @param inputUri - Input URI and query.
1380 * @param uriLen - The length of the initial URI with query.
1382 * Note: The '?' that appears after the URI is not considered as
1383 * a part of the query.
1385 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1389 query = strchr (inputUri, '?');
1393 if((query - inputUri) > MAX_URI_LENGTH)
1395 return OC_STACK_INVALID_URI;
1398 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1400 return OC_STACK_INVALID_QUERY;
1403 else if(uriLen > MAX_URI_LENGTH)
1405 return OC_STACK_INVALID_URI;
1411 * Discover or Perform requests on a specified resource (specified by that Resource's respective URI).
1413 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of calling this API.
1414 * @param method - @ref OCMethod to perform on the resource
1415 * @param requiredUri - URI of the resource to interact with
1416 * @param referenceUri - URI of the reference resource
1417 * @param request - JSON encoded request
1418 * @param qos - quality of service
1419 * @param cbData - struct that contains asynchronous callback function that is invoked
1420 * by the stack when discovery or resource interaction is complete
1421 * @param options - The address of an array containing the vendor specific header
1422 * header options to be sent with the request
1423 * @param numOptions - Number of vendor specific header options to be included
1426 * OC_STACK_OK - no errors
1427 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
1428 * OC_STACK_INVALID_METHOD - invalid resource method
1429 * OC_STACK_INVALID_URI - invalid required or reference URI
1431 * Note: IN case of CA, when using multicast, the required URI should not contain IP address.
1432 * Instead, it just contains the URI to the resource such as "/oc/core".
1435 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1436 const char *referenceUri, const char *request, uint8_t conType,
1437 OCQualityOfService qos, OCCallbackData *cbData,
1438 OCHeaderOption * options, uint8_t numOptions)
1440 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1441 const char *referenceUri, const char *request,
1442 OCQualityOfService qos, OCCallbackData *cbData,
1443 OCHeaderOption * options, uint8_t numOptions)
1446 OCStackResult result = OC_STACK_ERROR;
1448 ClientCB *clientCB = NULL;
1449 unsigned char * requestUri = NULL;
1450 unsigned char * resourceType = NULL;
1451 unsigned char * query = NULL;
1452 char * newUri = (char *)requiredUri;
1453 (void) referenceUri;
1455 CARemoteEndpoint_t* endpoint = NULL;
1456 CAResult_t caResult;
1457 CAToken_t caToken = NULL;
1458 CAInfo_t requestData;
1459 CARequestInfo_t requestInfo;
1460 CAGroupEndpoint_t grpEnd;
1462 // To track if memory is allocated for additional header options
1463 uint8_t hdrOptionMemAlloc = 0;
1466 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1468 // Validate input parameters
1469 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1470 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1472 TODO ("Need to form the final query by concatenating require and reference URI's");
1473 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
1475 uint16_t uriLen = strlen(requiredUri);
1477 // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS
1483 case OC_REST_DELETE:
1484 case OC_REST_OBSERVE:
1485 case OC_REST_OBSERVE_ALL:
1486 case OC_REST_CANCEL_OBSERVE:
1488 #ifdef WITH_PRESENCE
1489 case OC_REST_PRESENCE:
1493 result = OC_STACK_INVALID_METHOD;
1497 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
1502 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
1504 result = OC_STACK_INVALID_PARAM;
1508 #ifdef WITH_PRESENCE
1509 if(method == OC_REST_PRESENCE)
1511 result = getQueryFromUri(requiredUri, &query, &newUri);
1514 result = getResourceType((char *) query, &resourceType);
1517 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1521 OC_LOG(DEBUG, TAG, PCF("Resource type is NULL."));
1526 OC_LOG(DEBUG, TAG, PCF("Query string is NULL."));
1528 if(result != OC_STACK_OK)
1533 #endif // WITH_PRESENCE
1535 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
1538 memcpy(requestUri, newUri, (uriLen + 1));
1542 result = OC_STACK_NO_MEMORY;
1546 *handle = GenerateInvocationHandle();
1549 result = OC_STACK_NO_MEMORY;
1554 memset(&requestData, 0, sizeof(CAInfo_t));
1555 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1556 memset(&grpEnd, 0, sizeof(CAGroupEndpoint_t));
1560 case OC_REST_OBSERVE:
1561 case OC_REST_OBSERVE_ALL:
1562 case OC_REST_CANCEL_OBSERVE:
1564 requestInfo.method = CA_GET;
1569 requestInfo.method = CA_PUT;
1574 requestInfo.method = CA_POST;
1577 case OC_REST_DELETE:
1579 requestInfo.method = CA_DELETE;
1582 #ifdef WITH_PRESENCE
1583 case OC_REST_PRESENCE:
1585 // Replacing method type with GET because "presence"
1586 // is a stack layer only implementation.
1587 requestInfo.method = CA_GET;
1592 result = OC_STACK_INVALID_METHOD;
1596 //High QoS is not supported
1597 if(qos == OC_HIGH_QOS)
1599 result = OC_STACK_INVALID_PARAM;
1604 caResult = CAGenerateToken(&caToken);
1606 //TODO-CA Remove this temporary fix (for some reason same token is being generated)
1609 caToken[0] += count;
1611 if (caResult != CA_STATUS_OK)
1613 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1618 // TODO-CA: Map QoS to the right CA msg type
1619 requestData.type = CA_MSG_NONCONFIRM;
1620 requestData.token = caToken;
1621 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1623 result = CreateObserveHeaderOption (&(requestData.options), options,
1624 numOptions, OC_OBSERVE_REGISTER);
1625 if (result != OC_STACK_OK)
1629 hdrOptionMemAlloc = 1;
1630 requestData.numOptions = numOptions + 1;
1634 requestData.options = (CAHeaderOption_t*)options;
1635 requestData.numOptions = numOptions;
1637 requestData.payload = (char *)request;
1639 requestInfo.info = requestData;
1641 CAConnectivityType_t caConType;
1643 result = OCToCAConnectivityType(conType, &caConType);
1644 if (result != OC_STACK_OK)
1646 OC_LOG(ERROR, TAG, PCF("Invalid Connectivity Type"));
1651 if(conType == OC_ALL)
1653 grpEnd.connectivityType = caConType;
1655 grpEnd.resourceUri = (CAURI_t) OICMalloc(uriLen + 1);
1656 strncpy(grpEnd.resourceUri, requiredUri, (uriLen + 1));
1658 caResult = CASendRequestToAll(&grpEnd, &requestInfo);
1662 caResult = CACreateRemoteEndpoint(newUri, caConType, &endpoint);
1664 if (caResult != CA_STATUS_OK)
1666 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1670 caResult = CASendRequest(endpoint, &requestInfo);
1673 if (caResult != CA_STATUS_OK)
1675 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1679 if((result = AddClientCB(&clientCB, cbData, &caToken, handle, method,
1680 requestUri, resourceType)) != OC_STACK_OK)
1682 result = OC_STACK_NO_MEMORY;
1688 // Generate token which will be used by OCStack to match responses received
1690 OCGenerateCoAPToken(&token);
1692 if((result = AddClientCB(&clientCB, cbData, &token, handle, method, requestUri, resourceType))
1695 result = OC_STACK_NO_MEMORY;
1699 // Make call to OCCoAP layer
1700 result = OCDoCoAPResource(method, qos, &token, newUri, request, options, numOptions);
1704 if(newUri != requiredUri)
1708 if (result != OC_STACK_OK)
1710 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1711 FindAndDeleteClientCB(clientCB);
1714 CADestroyRemoteEndpoint(endpoint);
1715 OCFree(grpEnd.resourceUri);
1716 if (hdrOptionMemAlloc)
1718 OCFree(requestData.options);
1725 * Cancel a request associated with a specific @ref OCDoResource invocation.
1727 * @param handle - Used to identify a specific OCDoResource invocation.
1728 * @param qos - used to specify Quality of Service (read below for more info)
1729 * @param options- used to specify vendor specific header options when sending
1730 * explicit observe cancellation
1731 * @param numOptions- Number of header options to be included
1734 * OC_STACK_OK - No errors; Success
1735 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1737 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1741 * This ftn is implemented one of two ways in the case of observation:
1743 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1744 * Remove the callback associated on client side.
1745 * When the next notification comes in from server,
1746 * reply with RESET message to server.
1747 * Keep in mind that the server will react to RESET only
1748 * if the last notification was sent ans CON
1750 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1751 * and it is associated with an observe request
1752 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1753 * Send CON Observe request to server with
1754 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1755 * Remove the callback associated on client side.
1757 OCStackResult ret = OC_STACK_OK;
1759 CARemoteEndpoint_t* endpoint = NULL;
1760 CAResult_t caResult;
1761 CAInfo_t requestData;
1762 CARequestInfo_t requestInfo;
1763 // Track if memory is allocated for additional header options
1764 uint8_t hdrOptionMemAlloc = 0;
1768 return OC_STACK_INVALID_PARAM;
1771 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1773 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1776 switch (clientCB->method)
1778 case OC_REST_OBSERVE:
1779 case OC_REST_OBSERVE_ALL:
1781 //TODO-CA : Why CA_WIFI alone?
1782 caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri, CA_WIFI,
1784 if (caResult != CA_STATUS_OK)
1786 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1787 return OC_STACK_ERROR;
1790 memset(&requestData, 0, sizeof(CAInfo_t));
1791 // TODO-CA: Map QoS to the right CA msg type
1792 requestData.type = CA_MSG_NONCONFIRM;
1793 requestData.token = clientCB->token;
1794 if (CreateObserveHeaderOption (&(requestData.options),
1795 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
1797 return OC_STACK_ERROR;
1799 hdrOptionMemAlloc = 1;
1800 requestData.numOptions = numOptions + 1;
1801 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1802 requestInfo.method = CA_GET;
1803 requestInfo.info = requestData;
1805 caResult = CASendRequest(endpoint, &requestInfo);
1806 if (caResult != CA_STATUS_OK)
1808 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1810 if(caResult == CA_STATUS_OK)
1815 if(qos == OC_HIGH_QOS)
1817 ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
1818 &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
1823 FindAndDeleteClientCB(clientCB);
1827 #ifdef WITH_PRESENCE
1828 case OC_REST_PRESENCE:
1829 FindAndDeleteClientCB(clientCB);
1833 return OC_STACK_INVALID_METHOD;
1837 CADestroyRemoteEndpoint(endpoint);
1838 if (hdrOptionMemAlloc)
1840 OCFree(requestData.options);
1847 #ifdef WITH_PRESENCE
1849 OCStackResult OCProcessPresence()
1851 OCStackResult result = OC_STACK_OK;
1852 uint8_t ipAddr[4] = { 0 };
1855 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1856 ClientCB* cbNode = NULL;
1858 OCClientResponse clientResponse;
1859 OCResponse * response = NULL;
1860 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1862 LL_FOREACH(cbList, cbNode) {
1863 if(OC_REST_PRESENCE == cbNode->method)
1865 if(cbNode->presence)
1867 uint32_t now = GetTime(0);
1868 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d",
1869 cbNode->presence->TTLlevel);
1870 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1873 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1878 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1879 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1880 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1883 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1885 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1886 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1888 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1890 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
1891 (OCDevAddr *) &dst, 0, NULL);
1892 if(result != OC_STACK_OK)
1896 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1897 &cbNode->token, &clientResponse, NULL);
1898 if(result != OC_STACK_OK)
1903 // Increment the TTLLevel (going to a next state), so we don't keep
1904 // sending presence notification to client.
1905 cbNode->presence->TTLlevel++;
1906 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1907 cbNode->presence->TTLlevel);
1911 result = OC_STACK_INVALID_IP;
1915 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
1916 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1918 FindAndDeleteClientCB(cbNode);
1922 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1924 CAResult_t caResult;
1925 CARemoteEndpoint_t* endpoint = NULL;
1926 CAInfo_t requestData;
1927 CARequestInfo_t requestInfo;
1929 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
1931 //TODO-CA : Why CA_WIFI alone?
1932 caResult = CACreateRemoteEndpoint((char *)cbNode->requestUri, CA_WIFI,
1935 if (caResult != CA_STATUS_OK)
1937 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1941 memset(&requestData, 0, sizeof(CAInfo_t));
1943 // TODO-CA: Map QoS to the right CA msg type
1944 requestData.type = CA_MSG_NONCONFIRM;
1945 requestData.token = cbNode->token;
1947 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1948 requestInfo.method = CA_GET;
1949 requestInfo.info = requestData;
1951 caResult = CASendRequest(endpoint, &requestInfo);
1953 if (caResult != CA_STATUS_OK)
1955 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1959 cbNode->presence->TTLlevel++;
1960 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1961 cbNode->presence->TTLlevel);
1967 if (result != OC_STACK_OK)
1969 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
1974 OCStackResult OCProcessPresence()
1976 OCStackResult result = OC_STACK_OK;
1977 uint8_t ipAddr[4] = { 0 };
1980 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1981 ClientCB* cbNode = NULL;
1983 OCClientResponse clientResponse;
1984 OCResponse * response = NULL;
1986 LL_FOREACH(cbList, cbNode) {
1987 if(OC_REST_PRESENCE == cbNode->method)
1989 if(cbNode->presence)
1991 uint32_t now = GetTime(0);
1992 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
1993 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1996 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
2001 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
2002 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
2003 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2006 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2008 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
2009 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
2011 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
2013 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
2014 (OCDevAddr *) &dst, 0, NULL);
2015 if(result != OC_STACK_OK)
2019 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
2020 &cbNode->token, &clientResponse, NULL);
2021 if(result != OC_STACK_OK)
2026 // Increment the TTLLevel (going to a next state), so we don't keep
2027 // sending presence notification to client.
2028 cbNode->presence->TTLlevel++;
2029 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
2030 cbNode->presence->TTLlevel);
2034 result = OC_STACK_INVALID_IP;
2037 HandleStackResponses(response);
2039 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2041 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
2044 OCGenerateCoAPToken(&token);
2045 result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
2046 &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
2048 if(result != OC_STACK_OK)
2052 cbNode->presence->TTLlevel++;
2053 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
2059 if (result != OC_STACK_OK)
2061 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
2066 #endif // WITH_PRESENCE
2069 * Called in main loop of OC client or server. Allows low-level processing of
2073 * OC_STACK_OK - no errors
2074 * OC_STACK_ERROR - stack process error
2076 OCStackResult OCProcess() {
2078 OC_LOG(INFO, TAG, PCF("Entering OCProcess"));
2079 #ifdef WITH_PRESENCE
2080 OCProcessPresence();
2083 CAHandleRequestResponse();
2091 #ifdef WITH_PRESENCE
2093 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
2094 * presence notifications to clients via multicast. Once this API has been called with a success,
2095 * clients may query for this server's presence and this server's stack will respond via multicast.
2097 * Server can call this function when it comes online for the first time, or when it comes back
2098 * online from offline mode, or when it re enters network.
2100 * @param ttl - Time To Live in seconds
2101 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
2104 * OC_STACK_OK - No errors; Success
2106 OCStackResult OCStartPresence(const uint32_t ttl)
2108 OCChangeResourceProperty(
2109 &(((OCResource *)presenceResource.handle)->resourceProperties),
2114 presenceResource.presenceTTL = ttl;
2117 if(OC_PRESENCE_UNINITIALIZED == presenceState)
2119 OCDevAddr multiCastAddr;
2122 presenceState = OC_PRESENCE_INITIALIZED;
2123 OCGenerateCoAPToken(&token);
2124 OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
2126 CAAddress_t addressInfo;
2127 strncpy(addressInfo.IP.ipAddress, "224.0.1.187", CA_IPADDR_SIZE);
2128 addressInfo.IP.port = 5298;
2130 CAToken_t caToken = NULL;
2131 CAGenerateToken(&caToken);
2133 AddCAObserver(OC_PRESENCE_URI, NULL, 0, &token,
2134 &multiCastAddr, (OCResource *)presenceResource.handle, OC_LOW_QOS,
2135 &addressInfo, CA_WIFI, caToken);
2137 //add the presence observer
2138 AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
2139 (OCResource *)presenceResource.handle, OC_LOW_QOS);
2143 // Each time OCStartPresence is called
2144 // a different random 32-bit integer number is used
2145 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2147 return SendPresenceNotification(NULL);
2151 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
2152 * presence notifications to clients via multicast. Once this API has been called with a success,
2153 * this server's stack will not respond to clients querying for this server's presence.
2155 * Server can call this function when it is terminating, going offline, or when going
2156 * away from network.
2159 * OC_STACK_OK - No errors; Success
2161 OCStackResult OCStopPresence()
2163 OCStackResult result = OC_STACK_ERROR;
2164 //make resource inactive
2165 result = OCChangeResourceProperty(
2166 &(((OCResource *) presenceResource.handle)->resourceProperties),
2168 result = SendPresenceNotification(NULL);
2175 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
2177 defaultDeviceHandler = entityHandler;
2182 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2184 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
2186 if(myStackMode == OC_CLIENT)
2188 return OC_STACK_ERROR;
2191 return SaveDeviceInfo(deviceInfo);
2197 * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource
2198 * @param resourceTypeName - name of resource type. Example: "core.led"
2199 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
2200 * @param uri - URI of the resource. Example: "/a/led"
2201 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2202 * NULL for default entity handler
2203 * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE
2206 * OC_STACK_OK - no errors
2207 * OC_STACK_ERROR - stack process error
2209 OCStackResult OCCreateResource(OCResourceHandle *handle,
2210 const char *resourceTypeName,
2211 const char *resourceInterfaceName,
2212 const char *uri, OCEntityHandler entityHandler,
2213 uint8_t resourceProperties) {
2215 OCResource *pointer = NULL;
2218 OCStackResult result = OC_STACK_ERROR;
2220 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
2222 if(myStackMode == OC_CLIENT)
2226 // Validate parameters
2227 if(!uri || (strlen(uri) == 0))
2229 OC_LOG(ERROR, TAG, PCF("URI is invalid"));
2230 return OC_STACK_INVALID_URI;
2232 // Is it presented during resource discovery?
2233 if (!handle || !resourceTypeName) {
2234 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
2235 return OC_STACK_INVALID_PARAM;
2238 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
2239 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2242 // Make sure resourceProperties bitmask has allowed properties specified
2243 if (resourceProperties
2244 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
2245 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2246 return OC_STACK_INVALID_PARAM;
2249 // If the headResource is NULL, then no resources have been created...
2250 pointer = headResource;
2252 // At least one resources is in the resource list, so we need to search for
2253 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2255 if (strcmp(uri, pointer->uri) == 0) {
2256 OC_LOG(ERROR, TAG, PCF("URI already in use"));
2257 return OC_STACK_INVALID_PARAM;
2259 pointer = pointer->next;
2262 // Create the pointer and insert it into the resource list
2263 pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
2267 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2269 insertResource(pointer);
2272 size = strlen(uri) + 1;
2273 str = (char *) OCMalloc(size);
2277 strncpy(str, uri, size);
2280 // Set properties. Set OC_ACTIVE
2281 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2284 // Add the resourcetype to the resource
2285 result = BindResourceTypeToResource(pointer, resourceTypeName);
2286 if (result != OC_STACK_OK) {
2287 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
2291 // Add the resourceinterface to the resource
2292 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2293 if (result != OC_STACK_OK) {
2294 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
2298 // If an entity handler has been passed, attach it to the newly created
2299 // resource. Otherwise, set the default entity handler.
2302 pointer->entityHandler = entityHandler;
2306 pointer->entityHandler = defaultResourceEHandler;
2310 result = OC_STACK_OK;
2312 #ifdef WITH_PRESENCE
2313 if(presenceResource.handle)
2315 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2316 SendPresenceNotification(pointer->rsrcType);
2320 if (result != OC_STACK_OK)
2322 // Deep delete of resource and other dynamic elements that it contains
2323 deleteResource(pointer);
2332 * Create a resource. with host ip address for remote resource
2334 * @param handle - pointer to handle to newly created resource. Set by ocstack.
2335 * Used to refer to resource
2336 * @param resourceTypeName - name of resource type. Example: "core.led"
2337 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
2338 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
2339 * @param uri - URI of the resource. Example: "/a/led"
2340 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2341 * NULL for default entity handler
2342 * @param resourceProperties - properties supported by resource.
2343 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
2346 * OC_STACK_OK - no errors
2347 * OC_STACK_ERROR - stack process error
2350 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
2351 const char *resourceTypeName,
2352 const char *resourceInterfaceName,
2355 OCEntityHandler entityHandler,
2356 uint8_t resourceProperties)
2360 OCStackResult result = OC_STACK_ERROR;
2362 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
2363 uri, entityHandler, resourceProperties);
2365 if (result != OC_STACK_ERROR)
2368 size = strlen(host) + 1;
2369 str = (char *) OCMalloc(size);
2372 return OC_STACK_ERROR;
2374 strncpy(str, host, size);
2375 ((OCResource *) *handle)->host = str;
2382 * Add a resource to a collection resource.
2384 * @param collectionHandle - handle to the collection resource
2385 * @param resourceHandle - handle to resource to be added to the collection resource
2388 * OC_STACK_OK - no errors
2389 * OC_STACK_ERROR - stack process error
2390 * OC_STACK_INVALID_PARAM - invalid collectionhandle
2392 OCStackResult OCBindResource(
2393 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2394 OCResource *resource;
2397 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2399 // Validate parameters
2400 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2401 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2402 // Container cannot contain itself
2403 if (collectionHandle == resourceHandle) {
2404 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2405 return OC_STACK_INVALID_PARAM;
2408 // Use the handle to find the resource in the resource linked list
2409 resource = findResource((OCResource *) collectionHandle);
2411 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2412 return OC_STACK_INVALID_PARAM;
2415 // Look for an open slot to add add the child resource.
2416 // If found, add it and return success
2417 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2418 if (!resource->rsrcResources[i]) {
2419 resource->rsrcResources[i] = (OCResource *) resourceHandle;
2420 OC_LOG(INFO, TAG, PCF("resource bound"));
2425 #ifdef WITH_PRESENCE
2426 if(presenceResource.handle)
2428 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2429 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2433 // Unable to add resourceHandle, so return error
2434 return OC_STACK_ERROR;
2438 * Remove a resource from a collection resource.
2440 * @param collectionHandle - handle to the collection resource
2441 * @param resourceHandle - handle to resource to be added to the collection resource
2444 * OC_STACK_OK - no errors
2445 * OC_STACK_ERROR - stack process error
2446 * OC_STACK_INVALID_PARAM - invalid collectionHandle
2448 OCStackResult OCUnBindResource(
2449 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2450 OCResource *resource;
2453 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2455 // Validate parameters
2456 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2457 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2458 // Container cannot contain itself
2459 if (collectionHandle == resourceHandle) {
2460 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2461 return OC_STACK_INVALID_PARAM;
2464 // Use the handle to find the resource in the resource linked list
2465 resource = findResource((OCResource *) collectionHandle);
2467 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2468 return OC_STACK_INVALID_PARAM;
2471 // Look for an open slot to add add the child resource.
2472 // If found, add it and return success
2473 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2474 if (resourceHandle == resource->rsrcResources[i]) {
2475 resource->rsrcResources[i] = (OCResource *) NULL;
2476 OC_LOG(INFO, TAG, PCF("resource unbound"));
2481 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2483 #ifdef WITH_PRESENCE
2484 if(presenceResource.handle)
2486 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2487 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2491 // Unable to add resourceHandle, so return error
2492 return OC_STACK_ERROR;
2495 OCStackResult BindResourceTypeToResource(OCResource* resource,
2496 const char *resourceTypeName)
2498 OCResourceType *pointer = NULL;
2501 OCStackResult result = OC_STACK_ERROR;
2503 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
2505 // Validate parameters
2506 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2507 // TODO: Does resource attribute resentation really have to be maintained in stack?
2508 // Is it presented during resource discovery?
2510 TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
2512 // Create the resourcetype and insert it into the resource list
2513 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
2518 // Set the resourceTypeName
2519 size = strlen(resourceTypeName) + 1;
2520 str = (char *) OCMalloc(size);
2524 strncpy(str, resourceTypeName, size);
2525 pointer->resourcetypename = str;
2527 insertResourceType(resource, pointer);
2528 result = OC_STACK_OK;
2530 exit: if (result != OC_STACK_OK) {
2538 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2539 const char *resourceInterfaceName)
2541 OCResourceInterface *pointer = NULL;
2544 OCStackResult result = OC_STACK_ERROR;
2546 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
2548 // Validate parameters
2549 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2551 TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
2553 // Create the resourceinterface and insert it into the resource list
2554 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
2559 // Set the resourceinterface name
2560 size = strlen(resourceInterfaceName) + 1;
2561 str = (char *) OCMalloc(size);
2565 strncpy(str, resourceInterfaceName, size);
2566 pointer->name = str;
2568 // Bind the resourceinterface to the resource
2569 insertResourceInterface(resource, pointer);
2571 result = OC_STACK_OK;
2573 exit: if (result != OC_STACK_OK) {
2582 * Bind a resourcetype to a resource.
2584 * @param handle - handle to the resource
2585 * @param resourceTypeName - name of resource type. Example: "core.led"
2588 * OC_STACK_OK - no errors
2589 * OC_STACK_ERROR - stack process error
2591 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2592 const char *resourceTypeName) {
2594 OCStackResult result = OC_STACK_ERROR;
2595 OCResource *resource;
2597 // Make sure resource exists
2598 resource = findResource((OCResource *) handle);
2600 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2601 return OC_STACK_ERROR;
2604 // call internal function
2605 result = BindResourceTypeToResource(resource, resourceTypeName);
2607 #ifdef WITH_PRESENCE
2608 if(presenceResource.handle)
2610 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2611 SendPresenceNotification(resource->rsrcType);
2619 * Bind a resourceinterface to a resource.
2621 * @param handle - handle to the resource
2622 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
2625 * OC_STACK_OK - no errors
2626 * OC_STACK_ERROR - stack process error
2629 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2630 const char *resourceInterfaceName) {
2632 OCStackResult result = OC_STACK_ERROR;
2633 OCResource *resource;
2635 // Make sure resource exists
2636 resource = findResource((OCResource *) handle);
2638 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2639 return OC_STACK_ERROR;
2642 // call internal function
2643 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2645 #ifdef WITH_PRESENCE
2646 if(presenceResource.handle)
2648 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2649 SendPresenceNotification(resource->rsrcType);
2657 * Get the number of resources that have been created in the stack.
2659 * @param numResources - pointer to count variable
2662 * OC_STACK_OK - no errors
2663 * OC_STACK_ERROR - stack process error
2666 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
2667 OCResource *pointer = headResource;
2669 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2670 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2673 *numResources = *numResources + 1;
2674 pointer = pointer->next;
2680 * Get a resource handle by index.
2682 * @param index - index of resource, 0 to Count - 1
2685 * Resource handle - if found
2686 * NULL - if not found
2688 OCResourceHandle OCGetResourceHandle(uint8_t index) {
2689 OCResource *pointer = headResource;
2692 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2694 // Iterate through the list
2695 while ((i < index) && pointer) {
2697 pointer = pointer->next;
2699 return (OCResourceHandle) pointer;
2703 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
2706 * @param handle - handle of resource to be deleted
2709 * OC_STACK_OK - no errors
2710 * OC_STACK_ERROR - stack process error
2711 * OC_STACK_NO_RESOURCE - resource not found
2712 * OC_STACK_INVALID_PARAM - invalid param
2714 OCStackResult OCDeleteResource(OCResourceHandle handle) {
2715 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2718 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2719 return OC_STACK_INVALID_PARAM;
2722 OCResource *resource = findResource((OCResource *) handle);
2723 if (resource == NULL) {
2724 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2725 return OC_STACK_NO_RESOURCE;
2728 if (deleteResource((OCResource *) handle) == 0) {
2729 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2730 return OC_STACK_ERROR;
2737 * Get the URI of the resource specified by handle.
2739 * @param handle - handle of resource
2741 * URI string - if resource found
2742 * NULL - resource not found
2744 const char *OCGetResourceUri(OCResourceHandle handle) {
2745 OCResource *resource;
2746 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2748 resource = findResource((OCResource *) handle);
2750 return resource->uri;
2752 return (const char *) NULL;
2756 * Get the properties of the resource specified by handle.
2757 * NOTE: that after a resource is created, the OC_ACTIVE property is set
2758 * for the resource by the stack.
2760 * @param handle - handle of resource
2762 * property bitmap - if resource found
2763 * NULL - resource not found
2765 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
2766 OCResource *resource;
2767 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2769 resource = findResource((OCResource *) handle);
2771 return resource->resourceProperties;
2777 * Get the number of resource types of the resource.
2779 * @param handle - handle of resource
2780 * @param numResourceTypes - pointer to count variable
2783 * OC_STACK_OK - no errors
2784 * OC_STACK_ERROR - stack process error
2786 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2787 uint8_t *numResourceTypes) {
2788 OCResource *resource;
2789 OCResourceType *pointer;
2791 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2792 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2793 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2795 *numResourceTypes = 0;
2797 resource = findResource((OCResource *) handle);
2799 pointer = resource->rsrcType;
2801 *numResourceTypes = *numResourceTypes + 1;
2802 pointer = pointer->next;
2809 * Get name of resource type of the resource.
2811 * @param handle - handle of resource
2812 * @param index - index of resource, 0 to Count - 1
2815 * resource type name - if resource found
2816 * NULL - resource not found
2818 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
2819 OCResourceType *resourceType;
2821 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2823 resourceType = findResourceTypeAtIndex(handle, index);
2825 return resourceType->resourcetypename;
2827 return (const char *) NULL;
2833 * Get the number of resource interfaces of the resource.
2835 * @param handle - handle of resource
2836 * @param numResources - pointer to count variable
2839 * OC_STACK_OK - no errors
2840 * OC_STACK_ERROR - stack process error
2842 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2843 uint8_t *numResourceInterfaces) {
2844 OCResourceInterface *pointer;
2845 OCResource *resource;
2847 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2849 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2850 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2852 *numResourceInterfaces = 0;
2853 resource = findResource((OCResource *) handle);
2855 pointer = resource->rsrcInterface;
2857 *numResourceInterfaces = *numResourceInterfaces + 1;
2858 pointer = pointer->next;
2865 * Get name of resource interface of the resource.
2867 * @param handle - handle of resource
2868 * @param index - index of resource, 0 to Count - 1
2871 * resource interface name - if resource found
2872 * NULL - resource not found
2874 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
2875 OCResourceInterface *resourceInterface;
2877 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2879 resourceInterface = findResourceInterfaceAtIndex(handle, index);
2880 if (resourceInterface) {
2881 return resourceInterface->name;
2883 return (const char *) NULL;
2887 * Get resource handle from the collection resource by index.
2889 * @param collectionHandle - handle of collection resource
2890 * @param index - index of contained resource, 0 to Count - 1
2893 * handle to resource - if resource found
2894 * NULL - resource not found
2896 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2898 OCResource *resource;
2900 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2902 if (index >= MAX_CONTAINED_RESOURCES) {
2906 resource = findResource((OCResource *) collectionHandle);
2911 return resource->rsrcResources[index];
2915 * Bind an entity handler to the resource.
2917 * @param handle - handle to the resource that the contained resource is to be bound
2918 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2920 * OC_STACK_OK - no errors
2921 * OC_STACK_ERROR - stack process error
2923 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2924 OCEntityHandler entityHandler) {
2925 OCResource *resource;
2927 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2929 // Validate parameters
2930 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2931 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2933 // Use the handle to find the resource in the resource linked list
2934 resource = findResource((OCResource *)handle);
2936 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2937 return OC_STACK_ERROR;
2941 resource->entityHandler = entityHandler;
2943 #ifdef WITH_PRESENCE
2944 if(presenceResource.handle)
2946 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2947 SendPresenceNotification(resource->rsrcType);
2955 * Get the entity handler for a resource.
2957 * @param handle - handle of resource
2960 * entity handler - if resource found
2961 * NULL - resource not found
2963 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
2964 OCResource *resource;
2966 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2968 // Use the handle to find the resource in the resource linked list
2969 resource = findResource((OCResource *)handle);
2971 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2976 return resource->entityHandler;
2979 void incrementSequenceNumber(OCResource * resPtr)
2981 // Increment the sequence number
2982 resPtr->sequenceNum += 1;
2983 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2985 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2991 * Notify Presence subscribers that a resource has been modified
2993 * @param resourceType - Handle to the resourceType linked list of resource
2994 * that was modified.
2995 * @param qos - Quality Of Service
2998 #ifdef WITH_PRESENCE
2999 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
3001 OCResource *resPtr = NULL;
3002 OCStackResult result;
3003 OCMethod method = OC_REST_PRESENCE;
3004 uint32_t maxAge = 0;
3005 resPtr = findResource((OCResource *) presenceResource.handle);
3008 return OC_STACK_NO_RESOURCE;
3010 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3012 maxAge = presenceResource.presenceTTL;
3019 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
3023 #endif // WITH_PRESENCE
3025 * Notify observers that an observed value has changed.
3027 * @param handle - handle of resource
3030 * OC_STACK_OK - no errors
3031 * OC_STACK_NO_RESOURCE - invalid resource handle
3032 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
3034 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
3036 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
3038 OCResource *resPtr = NULL;
3039 OCStackResult result;
3040 OCMethod method = OC_REST_NOMETHOD;
3041 uint32_t maxAge = 0;
3043 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
3044 #ifdef WITH_PRESENCE
3045 if(handle == presenceResource.handle)
3049 #endif // WITH_PRESENCE
3050 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3052 // Verify that the resource exists
3053 resPtr = findResource ((OCResource *) handle);
3056 return OC_STACK_NO_RESOURCE;
3060 //only increment in the case of regular observing (not presence)
3061 incrementSequenceNumber(resPtr);
3062 method = OC_REST_OBSERVE;
3063 maxAge = MAX_OBSERVE_AGE;
3064 #ifdef WITH_PRESENCE
3065 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
3067 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3074 OCNotifyListOfObservers (OCResourceHandle handle,
3075 OCObservationId *obsIdList,
3076 uint8_t numberOfIds,
3077 unsigned char *notificationJSONPayload,
3078 OCQualityOfService qos)
3080 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
3082 OCResource *resPtr = NULL;
3083 //TODO: we should allow the server to define this
3084 uint32_t maxAge = MAX_OBSERVE_AGE;
3086 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3087 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3088 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
3090 // Verify that the resource exists
3091 resPtr = findResource ((OCResource *) handle);
3092 if (NULL == resPtr || myStackMode == OC_CLIENT)
3094 return OC_STACK_NO_RESOURCE;
3098 incrementSequenceNumber(resPtr);
3100 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3101 notificationJSONPayload, maxAge, qos));
3105 * Send a response to a request.
3106 * The response can be a regular, slow, or block (i.e. a response that
3107 * is too large to be sent in a single PDU and must span multiple transmissions)
3109 * @param response - pointer to structure that contains response parameters
3112 * OC_STACK_OK - No errors; Success
3113 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
3114 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
3115 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
3116 * persistent response buffer is necessary
3118 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3120 OCStackResult result = OC_STACK_ERROR;
3121 OCServerRequest *serverRequest = NULL;
3123 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
3125 // Validate input parameters
3126 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3127 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3129 // TODO: Placeholder for creating a response entry when implementing
3130 // block transfer feature
3132 // If a response payload is present, check if block transfer is required
3133 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
3134 (const char *)ehResponse->payload, ehResponse->payloadSize))
3136 OC_LOG(INFO, TAG, PCF("Block transfer required"));
3138 // Persistent response buffer is needed for block transfer
3139 if (!ehResponse->persistentBufferFlag)
3141 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
3142 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
3144 // TODO: Placeholder for block transfer handling
3145 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
3146 // when implementing the block transfer feature
3151 // Get pointer to request info
3152 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3155 result = serverRequest->ehResponseHandler(ehResponse);
3162 * Cancel a response. Applies to a block response
3164 * @param responseHandle - response handle set by stack in OCServerResponse after
3165 * OCDoResponse is called
3168 * OC_STACK_OK - No errors; Success
3169 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
3171 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
3173 OCStackResult result = OC_STACK_NOTIMPL;
3175 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
3177 // TODO: validate response handle
3182 //-----------------------------------------------------------------------------
3183 // Private internal function definitions
3184 //-----------------------------------------------------------------------------
3186 * Generate handle of OCDoResource invocation for callback management.
3188 static OCDoHandle GenerateInvocationHandle()
3190 OCDoHandle handle = NULL;
3191 // Generate token here, it will be deleted when the transaction is deleted
3192 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
3195 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
3200 #ifdef WITH_PRESENCE
3201 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3202 OCResourceProperty resourceProperties, uint8_t enable)
3204 if (resourceProperties
3205 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
3206 OC_LOG(ERROR, TAG, PCF("Invalid property"));
3207 return OC_STACK_INVALID_PARAM;
3211 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3215 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3222 * Initialize resource data structures, variables, etc.
3224 OCStackResult initResources() {
3225 OCStackResult result = OC_STACK_OK;
3226 // Init application resource vars
3227 headResource = NULL;
3228 // Init Virtual Resources
3229 #ifdef WITH_PRESENCE
3230 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
3231 //presenceResource.token = OCGenerateCoAPToken();
3232 result = OCCreateResource(&presenceResource.handle,
3233 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3238 //make resource inactive
3239 result = OCChangeResourceProperty(
3240 &(((OCResource *) presenceResource.handle)->resourceProperties),
3247 * Add a resource to the end of the linked list of resources.
3249 * @param resource - resource to be added
3251 void insertResource(OCResource *resource) {
3252 OCResource *pointer;
3254 if (!headResource) {
3255 headResource = resource;
3257 pointer = headResource;
3259 while (pointer->next) {
3260 pointer = pointer->next;
3262 pointer->next = resource;
3264 resource->next = NULL;
3268 * Find a resource in the linked list of resources.
3270 * @param resource - resource to be found
3272 * NULL - resource not found
3273 * pointer to resource - pointer to resource that was found in the linked list
3275 OCResource *findResource(OCResource *resource) {
3276 OCResource *pointer = headResource;
3279 if (pointer == resource) {
3282 pointer = pointer->next;
3287 void deleteAllResources()
3289 OCResource *pointer = headResource;
3294 temp = pointer->next;
3295 #ifdef WITH_PRESENCE
3296 if(pointer != (OCResource *) presenceResource.handle)
3298 #endif // WITH_PRESENCE
3299 deleteResource(pointer);
3300 #ifdef WITH_PRESENCE
3302 #endif // WITH_PRESENCE
3306 #ifdef WITH_PRESENCE
3307 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3308 // presence notification attributed to their deletion to be processed.
3309 deleteResource((OCResource *) presenceResource.handle);
3310 #endif // WITH_PRESENCE
3314 * Delete the resource from the linked list.
3316 * @param resource - resource to be deleted
3321 int deleteResource(OCResource *resource) {
3322 OCResource *prev = NULL;
3325 temp = headResource;
3327 if (temp == resource) {
3328 // Invalidate all Resource Properties.
3329 resource->resourceProperties = (OCResourceProperty) 0;
3330 #ifdef WITH_PRESENCE
3331 if(resource != (OCResource *) presenceResource.handle)
3333 #endif // WITH_PRESENCE
3334 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3335 #ifdef WITH_PRESENCE
3338 if(presenceResource.handle)
3340 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3341 if(resource != (OCResource *) presenceResource.handle)
3343 SendPresenceNotification(resource->rsrcType);
3347 SendPresenceNotification(NULL);
3352 if (temp == headResource) {
3353 headResource = temp->next;
3355 prev->next = temp->next;
3358 deleteResourceElements(temp);
3371 * Delete all of the dynamically allocated elements that were created for the resource.
3373 * @param resource - specified resource
3375 void deleteResourceElements(OCResource *resource) {
3381 OCFree(resource->uri);
3383 // Delete resourcetype linked list
3384 deleteResourceType(resource->rsrcType);
3386 // Delete resourceinterface linked list
3387 deleteResourceInterface(resource->rsrcInterface);
3391 * Delete all of the dynamically allocated elements that were created for the resource type.
3393 * @param resourceType - specified resource type
3395 void deleteResourceType(OCResourceType *resourceType) {
3396 OCResourceType *pointer = resourceType;
3397 OCResourceType *next;
3400 next = pointer->next;
3401 OCFree(pointer->resourcetypename);
3408 * Delete all of the dynamically allocated elements that were created for the resource interface.
3410 * @param resourceInterface - specified resource interface
3412 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
3413 OCResourceInterface *pointer = resourceInterface;
3414 OCResourceInterface *next;
3417 next = pointer->next;
3418 OCFree(pointer->name);
3425 * Insert a resource type into a resource's resource type linked list.
3427 * @param resource - resource where resource type is to be inserted
3428 * @param resourceType - resource type to be inserted
3430 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
3431 OCResourceType *pointer;
3433 if (resource && !resource->rsrcType) {
3434 resource->rsrcType = resourceType;
3438 pointer = resource->rsrcType;
3442 pointer = resourceType;
3444 while (pointer->next) {
3445 pointer = pointer->next;
3447 pointer->next = resourceType;
3449 resourceType->next = NULL;
3453 * Get a resource type at the specified index within a resource.
3455 * @param handle - handle of resource
3456 * @param index - index of resource type
3459 * resourcetype - if found
3462 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
3463 OCResource *resource;
3464 OCResourceType *pointer;
3467 // Find the specified resource
3468 resource = findResource((OCResource *) handle);
3473 // Make sure a resource has a resourcetype
3474 if (!resource->rsrcType) {
3478 // Iterate through the list
3479 pointer = resource->rsrcType;
3481 while ((i < index) && pointer) {
3483 pointer = pointer->next;
3489 * Finds a resource type in an OCResourceType link-list.
3491 * @param resourceTypeList - the link-list to be searched through
3492 * @param resourceTypeName - the key to search for
3495 * resourceType that matches the key (ie. resourceTypeName)
3496 * NULL - either an invalid parameter or this function was unable to find the key.
3498 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3500 if(resourceTypeList && resourceTypeName)
3502 OCResourceType * rtPointer = resourceTypeList;
3503 while(resourceTypeName && rtPointer)
3505 if(rtPointer->resourcetypename &&
3506 strcmp(resourceTypeName, (const char *)
3507 (rtPointer->resourcetypename)) == 0)
3511 rtPointer = rtPointer->next;
3518 * Insert a resource interface into a resource's resource interface linked list.
3520 * @param resource - resource where resource interface is to be inserted
3521 * @param resourceInterface - resource interface to be inserted
3523 void insertResourceInterface(OCResource *resource,
3524 OCResourceInterface *resourceInterface) {
3525 OCResourceInterface *pointer;
3527 if (!resource->rsrcInterface) {
3528 resource->rsrcInterface = resourceInterface;
3530 pointer = resource->rsrcInterface;
3531 while (pointer->next) {
3532 pointer = pointer->next;
3534 pointer->next = resourceInterface;
3536 resourceInterface->next = NULL;
3540 * Get a resource interface at the specified index within a resource.
3542 * @param handle - handle of resource
3543 * @param index - index of resource interface
3546 * resourceinterface - if found
3549 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3551 OCResource *resource;
3552 OCResourceInterface *pointer;
3555 // Find the specified resource
3556 resource = findResource((OCResource *) handle);
3561 // Make sure a resource has a resourceinterface
3562 if (!resource->rsrcInterface) {
3566 // Iterate through the list
3567 pointer = resource->rsrcInterface;
3569 while ((i < index) && pointer) {
3571 pointer = pointer->next;
3577 * Determine if a request/response must be sent in a block transfer because it is too large to be
3578 * sent in a single PDU. This function can be used for either a request or a response
3580 * @param request - NULL or pointer to request
3581 * @param response - NULL or pointer to response
3582 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
3583 * the length of the request/response
3586 * 0 - packet transfer NOT required (i.e. normal request/response)
3587 * 1 - packet transfer required (i.e. block transfer needed)
3589 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
3593 // Determine if we are checking a request or a response
3596 // If size is greater than 0, use it for the request size value, otherwise
3597 // assume request is null terminated and use strlen for size value
3598 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
3605 // If size is greater than 0, use it for the response size value, otherwise
3606 // assume response is null terminated and use strlen for size value
3607 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3616 * Retrieves a resource type based upon a query ontains only just one
3617 * resource attribute (and that has to be of type "rt").
3619 * @remark This API malloc's memory for the resource type. Do not malloc resourceType
3620 * before passing in.
3622 * @param query - The quert part of the URI
3623 * @param resourceType - The resource type to be populated; pass by reference.
3626 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
3627 * OC_STACK_OK - Success
3629 OCStackResult getResourceType(const char * query, unsigned char** resourceType)
3633 return OC_STACK_INVALID_PARAM;
3636 OCStackResult result = OC_STACK_ERROR;
3638 if(strncmp(query, "rt=", 3) == 0)
3640 *resourceType = (unsigned char *) OCMalloc(strlen(query)-3);
3643 result = OC_STACK_NO_MEMORY;
3646 strcpy((char *)*resourceType, ((const char *)&query[3]));
3647 result = OC_STACK_OK;
3653 OCStackResult getQueryFromUri(const char * uri, unsigned char** query, char ** newURI)
3657 return OC_STACK_INVALID_URI;
3659 if(!query || !newURI)
3661 return OC_STACK_INVALID_PARAM;
3663 char * leftToken = NULL;
3664 char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3669 strcpy(tempURI, uri);
3671 leftToken = strtok_r((char *)tempURI, "?", &strTokPtr);
3673 //TODO-CA: This could be simplified. Clean up required.
3674 while(leftToken != NULL)
3676 if(strncmp(leftToken, "rt=", 3) == 0 || strncmp(leftToken, "if=", 3) == 0)
3678 *query = (unsigned char *) OCMalloc(strlen(leftToken));
3683 strcpy((char *)*query, ((const char *)&leftToken[0]));
3686 leftToken = strtok_r(NULL, "?", &strTokPtr);
3694 return OC_STACK_NO_MEMORY;
3697 const ServerID OCGetServerInstanceID(void)
3699 static bool generated = false;
3700 static ServerID sid;
3707 sid = OCGetRandom();
3712 const char* OCGetServerInstanceIDString(void)
3714 // max printed length of a base 10
3715 // uint32 is 10 characters, so 11 includes null.
3716 // This will change as the representation gets switched
3718 static char buffer[11];
3719 int n = sprintf(buffer, "%u", OCGetServerInstanceID());