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"
38 #include "ocsecurityinternal.h"
42 #include "cainterface.h"
43 #include <arpa/inet.h>
47 //-----------------------------------------------------------------------------
49 //-----------------------------------------------------------------------------
51 OC_STACK_UNINITIALIZED = 0, OC_STACK_INITIALIZED, OC_STACK_UNINIT_IN_PROGRESS
55 OC_PRESENCE_UNINITIALIZED = 0, OC_PRESENCE_INITIALIZED
59 //-----------------------------------------------------------------------------
61 //-----------------------------------------------------------------------------
62 static OCStackState stackState = OC_STACK_UNINITIALIZED;
64 OCResource *headResource = NULL;
66 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
67 static PresenceResource presenceResource;
68 uint8_t PresenceTimeOutSize = 0;
69 uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
73 OCDeviceEntityHandler defaultDeviceHandler;
74 OCStackResult getQueryFromUri(const char * uri, unsigned char** resourceType, char ** newURI);
76 //-----------------------------------------------------------------------------
78 //-----------------------------------------------------------------------------
79 #define TAG PCF("OCStack")
80 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
81 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
82 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
83 TAG, PCF(#arg " is NULL")); return (retVal); } }
84 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
87 //TODO: we should allow the server to define this
88 #define MAX_OBSERVE_AGE (0x2FFFFUL)
90 //-----------------------------------------------------------------------------
91 // Internal API function
92 //-----------------------------------------------------------------------------
94 // This internal function is called to update the stack with the status of
95 // observers and communication failures
97 OCStackResult OCStackFeedBack(CAToken_t * token, uint8_t status)
99 OCStackResult OCStackFeedBack(OCCoAPToken * token, uint8_t status)
102 OCStackResult result = OC_STACK_ERROR;
103 ResourceObserver * observer = NULL;
104 OCEntityHandlerRequest ehRequest = {0};
108 case OC_OBSERVER_NOT_INTERESTED:
109 OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
110 observer = GetObserverUsingToken (token);
113 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
114 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
115 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
116 if(result != OC_STACK_OK)
120 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
122 //observer is not observing anymore
123 result = DeleteObserverUsingToken (token);
124 if(result == OC_STACK_OK)
126 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
130 result = OC_STACK_OK;
131 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
134 case OC_OBSERVER_STILL_INTERESTED:
135 //observer is still interested
136 OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
137 notifications, reset the failedCount"));
138 observer = GetObserverUsingToken (token);
141 observer->forceHighQos = 0;
142 observer->failedCommCount = 0;
143 result = OC_STACK_OK;
147 result = OC_STACK_OBSERVER_NOT_FOUND;
150 case OC_OBSERVER_FAILED_COMM:
151 //observer is not reachable
152 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
153 observer = GetObserverUsingToken (token);
156 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
158 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
159 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
160 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
161 if(result != OC_STACK_OK)
163 return OC_STACK_ERROR;
165 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
166 //observer is unreachable
167 result = DeleteObserverUsingToken (token);
168 if(result == OC_STACK_OK)
170 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
174 result = OC_STACK_OK;
175 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
180 observer->failedCommCount++;
181 result = OC_STACK_CONTINUE;
183 observer->forceHighQos = 1;
184 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
188 OC_LOG(ERROR, TAG, PCF("Unknown status"));
189 result = OC_STACK_ERROR;
196 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
198 OCStackResult ret = OC_STACK_ERROR;
206 ret = OC_STACK_RESOURCE_CREATED;
209 ret = OC_STACK_RESOURCE_DELETED;
212 ret = OC_STACK_INVALID_QUERY;
215 ret = OC_STACK_INVALID_OPTION;
218 ret = OC_STACK_NO_RESOURCE;
226 OCStackResult OCToCAConnectivityType(OCConnectivityType ocConType, CAConnectivityType_t* caConType)
228 OCStackResult ret = OC_STACK_OK;
233 *caConType = CA_ETHERNET;
236 *caConType = CA_WIFI;
245 // Currently OC_ALL represents WIFI and ETHERNET
246 // Add other connectivity types as they are enabled in future
247 *caConType = (CA_WIFI|CA_ETHERNET);
250 ret = OC_STACK_INVALID_PARAM;
256 OCStackResult CAToOCConnectivityType(CAConnectivityType_t caConType, OCConnectivityType *ocConType)
258 OCStackResult ret = OC_STACK_OK;
263 *ocConType = OC_ETHERNET;
266 *ocConType = OC_WIFI;
275 ret = OC_STACK_INVALID_PARAM;
281 // update response.addr appropriately from endPoint.addressInfo
282 OCStackResult UpdateResponseAddr(OCClientResponse *response, const CARemoteEndpoint_t* endPoint)
284 struct sockaddr_in sa;
285 OCStackResult ret = OC_STACK_INVALID_PARAM;
289 OC_LOG(ERROR, TAG, PCF("CA Remote end-point is NULL!"));
292 inet_pton(AF_INET, endPoint->addressInfo.IP.ipAddress, &(sa.sin_addr));
293 sa.sin_port = htons(endPoint->addressInfo.IP.port);
294 static OCDevAddr address;
295 memcpy((void*)&address.addr, &(sa), sizeof(sa));
298 response->addr = &address;
299 ret = CAToOCConnectivityType(endPoint->connectivityType, &(response->connType));
303 OC_LOG(ERROR, TAG, PCF("OCClientResponse is NULL!"));
308 void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge, char** resType)
312 // The format of the payload is {"oc":[%u:%u:%s]}
313 // %u : sequence number,
315 // %s : Resource Type (Optional)
316 tok = strtok(payload, "[:]}");
317 payload[strlen(payload)] = ':';
318 tok = strtok(NULL, "[:]}");
319 payload[strlen((char *)payload)] = ':';
320 *seqNum = (uint32_t) atoi(tok);
321 tok = strtok(NULL, "[:]}");
322 *maxAge = (uint32_t) atoi(tok);
323 tok = strtok(NULL, "[:]}");
327 *resType = (char *)OCMalloc(strlen(tok));
332 payload[strlen((char *)payload)] = ':';
333 strcpy(*resType, tok);
334 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s", *resType);
336 payload[strlen((char *)payload)] = ']';
339 OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
340 const CAResponseInfo_t* responseInfo)
342 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
343 ClientCB * cbNode = NULL;
344 char *resourceTypeName = NULL;
345 OCClientResponse response;
346 OCStackResult result = OC_STACK_ERROR;
347 uint32_t lowerBound = 0;
348 uint32_t higherBound = 0;
351 char *fullUri = NULL;
352 char *ipAddress = NULL;
353 int presenceSubscribe = 0;
354 int multicastPresenceSubscribe = 0;
356 if (responseInfo->result != CA_SUCCESS)
358 OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
359 return OC_STACK_ERROR;
362 fullUri = (char *) OCMalloc(MAX_URI_LENGTH );
366 OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for fullUri"));
367 result = OC_STACK_NO_MEMORY;
371 ipAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
373 if(NULL == ipAddress)
375 OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for ipAddress"));
376 result = OC_STACK_NO_MEMORY;
380 strncpy(ipAddress, endPoint->addressInfo.IP.ipAddress,
381 strlen(endPoint->addressInfo.IP.ipAddress));
382 ipAddress[strlen(endPoint->addressInfo.IP.ipAddress)] = '\0';
384 snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", ipAddress, endPoint->addressInfo.IP.port,
387 cbNode = GetClientCB(NULL, NULL, (unsigned char *)fullUri);
391 presenceSubscribe = 1;
395 snprintf(fullUri, MAX_URI_LENGTH, "%s%s", OC_MULTICAST_IP, endPoint->resourceUri);
396 cbNode = GetClientCB(NULL, NULL, (unsigned char *)fullUri);
399 multicastPresenceSubscribe = 1;
403 if(!presenceSubscribe && !multicastPresenceSubscribe)
405 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
406 ------------ ignoring"));
410 // No payload to the application in case of presence
411 response.resJSONPayload = NULL;
412 response.result = OC_STACK_OK;
414 UpdateResponseAddr(&response, endPoint);
416 if(responseInfo->info.payload)
418 parsePresencePayload(responseInfo->info.payload,
419 &(response.sequenceNumber),
426 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
427 response.result = OC_STACK_PRESENCE_STOPPED;
430 OCFree(cbNode->presence->timeOut);
431 OCFree(cbNode->presence);
432 cbNode->presence = NULL;
435 else if(presenceSubscribe)
437 if(!cbNode->presence)
439 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
440 VERIFY_NON_NULL_V(cbNode->presence);
441 cbNode->presence->timeOut = NULL;
442 cbNode->presence->timeOut = (uint32_t *)
443 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
444 if(!(cbNode->presence->timeOut)){
445 OCFree(cbNode->presence);
446 result = OC_STACK_NO_MEMORY;
450 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %u", GetTime(0));
451 cbNode->presence->TTL = maxAge;
452 for(int index = 0; index < PresenceTimeOutSize; index++)
454 lowerBound = GetTime(((float)(PresenceTimeOut[index])
455 /(float)100)*(float)cbNode->presence->TTL);
456 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
457 /(float)100)*(float)cbNode->presence->TTL);
458 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
459 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
460 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
461 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
462 cbNode->presence->timeOut[index]);
464 cbNode->presence->TTLlevel = 0;
465 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
466 if(cbNode->sequenceNumber == response.sequenceNumber)
468 OC_LOG(INFO, TAG, PCF("===============No presence change"));
471 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
472 cbNode->sequenceNumber = response.sequenceNumber;
474 // Ensure that a filter is actually applied.
475 if(resourceTypeName && cbNode->filterResourceType)
477 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
485 // This is the multicast case
487 OCMulticastNode* mcNode = NULL;
488 mcNode = GetMCPresenceNode((const unsigned char *)fullUri);
492 if(mcNode->nonce == response.sequenceNumber)
494 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
497 mcNode->nonce = response.sequenceNumber;
501 uint32_t uriLen = strlen((char*)fullUri);
502 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
505 memcpy(uri, fullUri, (uriLen + 1));
510 PCF("===============No Memory for URI to store in the presence node"));
511 result = OC_STACK_NO_MEMORY;
514 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri, response.sequenceNumber);
515 if(result == OC_STACK_NO_MEMORY)
518 PCF("===============No Memory for Multicast Presence Node"));
519 result = OC_STACK_NO_MEMORY;
524 // Ensure that a filter is actually applied.
525 if(resourceTypeName && cbNode->filterResourceType)
527 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
534 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
536 if (cbResult == OC_STACK_DELETE_TRANSACTION)
538 FindAndDeleteClientCB(cbNode);
544 OCFree(resourceTypeName);
549 //This function will be called back by CA layer when a response is received
550 void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
552 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
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(&(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 always with option ID is COAP_OPTION_OBSERVE if it is available.
593 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
595 memcpy (&(response.sequenceNumber),
596 &(responseInfo->info.options[0].optionData), sizeof(uint32_t));
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 if (cbNode->callBack(cbNode->context,
618 cbNode->handle, &response) == OC_STACK_DELETE_TRANSACTION)
620 FindAndDeleteClientCB(cbNode);
623 OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload);
624 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
627 //This function will be called back by CA layer when a request is received
628 void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
630 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
633 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
639 OC_LOG(ERROR, TAG, PCF("requestInfo is NULL"));
643 if(myStackMode == OC_CLIENT)
645 //TODO: should the client be responding to requests?
649 OCServerProtocolRequest serverRequest;
651 memset (&serverRequest, 0, sizeof(OCServerProtocolRequest));
652 OC_LOG_V(INFO, TAG, PCF("***** Endpoint URI ***** : %s\n"), (char*)endPoint->resourceUri);
654 char * newUri = (char *)endPoint->resourceUri;
655 unsigned char * query = NULL;
656 getQueryFromUri(endPoint->resourceUri, &query, &newUri);
657 OC_LOG_V(INFO, TAG, PCF("**********URI without query ****: %s\n"), newUri);
658 OC_LOG_V(INFO, TAG, PCF("**********Query ****: %s\n"), query);
660 memcpy (&(serverRequest.resourceUrl), newUri, strlen(newUri));
664 memcpy (&(serverRequest.query), query, strlen((char*)query));
666 //copy request payload
667 if (requestInfo->info.payload)
669 serverRequest.reqTotalSize = strlen(requestInfo->info.payload) + 1;
670 memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
671 strlen(requestInfo->info.payload));
672 serverRequest.reqTotalSize = strlen((const char *)requestInfo->info.payload) + 1;
676 serverRequest.reqTotalSize = 1;
679 switch (requestInfo->method)
683 serverRequest.method = OC_REST_GET;
688 serverRequest.method = OC_REST_PUT;
693 serverRequest.method = OC_REST_POST;
698 serverRequest.method = OC_REST_DELETE;
703 OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
708 OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d", CA_MAX_TOKEN_LEN);
709 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token, CA_MAX_TOKEN_LEN);
711 serverRequest.requestToken = (CAToken_t)OCMalloc(CA_MAX_TOKEN_LEN+1);
713 if (!serverRequest.requestToken)
715 OC_LOG(FATAL, TAG, "Server Request Token is NULL");
718 memset(serverRequest.requestToken, 0, CA_MAX_TOKEN_LEN + 1);
719 memcpy(serverRequest.requestToken, requestInfo->info.token, CA_MAX_TOKEN_LEN);
721 if (requestInfo->info.type == CA_MSG_CONFIRM)
723 serverRequest.qos = OC_HIGH_QOS;
725 else if (requestInfo->info.type == CA_MSG_NONCONFIRM)
727 serverRequest.qos = OC_LOW_QOS;
729 else if (requestInfo->info.type == CA_MSG_ACKNOWLEDGE)
731 // TODO-CA: Need to handle this
733 else if (requestInfo->info.type == CA_MSG_RESET)
735 // TODO-CA: Need to handle this
737 // CA does not need the following 3 fields
738 serverRequest.coapID = 0;
739 serverRequest.delayedResNeeded = 0;
740 serverRequest.secured = endPoint->isSecured;
743 serverRequest.addressInfo = endPoint->addressInfo;
744 serverRequest.connectivityType = endPoint->connectivityType;
746 // copy vendor specific header options
747 // TODO-CA: CA is including non-vendor header options as well, like observe.
748 // Need to filter those out
749 GetObserveHeaderOption(&serverRequest.observationOption,
750 requestInfo->info.options, (uint8_t *)&(requestInfo->info.numOptions));
751 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
754 PCF("The request info numOptions is greater than MAX_HEADER_OPTIONS"));
757 serverRequest.numRcvdVendorSpecificHeaderOptions = requestInfo->info.numOptions;
758 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
760 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
761 sizeof(CAHeaderOption_t)*requestInfo->info.numOptions);
765 if(HandleStackRequests (&serverRequest) != OC_STACK_OK)
767 OC_LOG(ERROR, TAG, PCF("HandleStackRequests failed"));
769 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
774 //This function will be called back by occoap layer when a request is received
775 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
777 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
778 OCStackResult result = OC_STACK_ERROR;
779 ResourceHandling resHandling;
780 OCResource *resource;
783 OC_LOG(ERROR, TAG, PCF("protocolRequest is NULL"));
784 return OC_STACK_INVALID_PARAM;
787 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
790 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
792 result = AddServerRequest(&request, protocolRequest->coapID,
793 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
794 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
795 protocolRequest->observationOption, protocolRequest->qos,
796 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
797 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
798 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
799 protocolRequest->reqTotalSize,
800 &protocolRequest->addressInfo, protocolRequest->connectivityType);
802 result = AddServerRequest(&request, protocolRequest->coapID,
803 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
804 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
805 protocolRequest->observationOption, protocolRequest->qos,
806 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
807 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
808 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
809 protocolRequest->reqTotalSize);
811 if (OC_STACK_OK != result)
813 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
816 VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
818 if(!protocolRequest->reqMorePacket)
820 request->requestComplete = 1;
825 OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
828 if(request->requestComplete)
830 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
831 result = DetermineResourceHandling (request, &resHandling, &resource);
832 if (result == OC_STACK_OK)
834 result = ProcessRequest(resHandling, resource, request);
838 result = OC_STACK_ERROR;
843 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
844 result = OC_STACK_CONTINUE;
849 //This function will be called back by occoap layer when a response is received
850 OCStackResult HandleStackResponses(OCResponse * response)
852 OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)"));
853 OCStackResult result = OC_STACK_OK;
854 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
855 uint8_t isObserveNotification = 0;
856 ClientCB * cbNode = NULL;
859 OC_LOG(ERROR, TAG, PCF("response is NULL"));
860 return OC_STACK_INVALID_PARAM;
863 uint8_t isPresenceNotification = 0;
864 uint8_t isMulticastPresence = 0;
865 char * resourceTypeName = NULL;
866 uint32_t lowerBound = 0;
867 uint32_t higherBound = 0;
869 unsigned char * bufRes = response->bufRes;
870 #endif // WITH_PRESENCE
872 cbNode = response->cbNode;
875 cbNode = GetClientCB(response->rcvdToken, NULL, NULL);
878 if(response->clientResponse->sequenceNumber >= OC_OFFSET_SEQUENCE_NUMBER)
880 isObserveNotification = 1;
881 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
884 OC_LOG_V(DEBUG, TAG, "The sequenceNumber/NONCE of this response %u",
885 response->clientResponse->sequenceNumber);
886 OC_LOG_V(DEBUG, TAG, "The maxAge/TTL of this response %u", response->maxAge);
887 OC_LOG_V(DEBUG, TAG, "The response received is %s", bufRes);
890 if(!strcmp((char *)response->rcvdUri, (char *)OC_PRESENCE_URI)){
891 isPresenceNotification = 1;
894 result = OC_STACK_INVALID_PARAM;
897 tok = strtok((char *)bufRes, "[:]}");
898 bufRes[strlen((char *)bufRes)] = ':';
899 tok = strtok(NULL, "[:]}");
900 bufRes[strlen((char *)bufRes)] = ':';
901 response->clientResponse->sequenceNumber = (uint32_t )atoi(tok);
902 OC_LOG_V(DEBUG, TAG, "The received NONCE is %u", response->clientResponse->sequenceNumber);
903 tok = strtok(NULL, "[:]}");
904 response->maxAge = (uint32_t )atoi(tok);
905 OC_LOG_V(DEBUG, TAG, "The received TTL is %u", response->maxAge);
906 tok = strtok(NULL, "[:]}");
909 resourceTypeName = (char *)OCMalloc(strlen(tok));
910 if(!resourceTypeName)
914 bufRes[strlen((char *)bufRes)] = ':';
915 strcpy(resourceTypeName, tok);
916 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
919 bufRes[strlen((char *)bufRes)] = ']';
922 // Check if the application subcribed for presence
925 cbNode = GetClientCB(NULL, NULL, response->fullUri);
928 // Check if application subscribed for multicast presence
931 snprintf((char *)response->fullUri, MAX_URI_LENGTH, "%s%s",
932 OC_MULTICAST_IP, response->rcvdUri);
933 cbNode = GetClientCB(NULL, NULL, response->fullUri);
936 isMulticastPresence = 1;
937 isPresenceNotification = 0;
941 if(cbNode && isPresenceNotification)
943 OC_LOG(INFO, TAG, PCF("Received a presence notification"));
944 if(!cbNode->presence)
946 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
947 VERIFY_NON_NULL_V(cbNode->presence);
948 cbNode->presence->timeOut = NULL;
949 cbNode->presence->timeOut = (uint32_t *)
950 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
951 if(!(cbNode->presence->timeOut)){
952 OCFree(cbNode->presence);
953 result = OC_STACK_NO_MEMORY;
956 if(response->maxAge == 0)
958 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
959 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
962 OCFree(cbNode->presence->timeOut);
963 OCFree(cbNode->presence);
964 cbNode->presence = NULL;
969 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %d", GetTime(0));
970 cbNode->presence->TTL = response->maxAge;
971 for(int index = 0; index < PresenceTimeOutSize; index++)
973 lowerBound = GetTime(((float)(PresenceTimeOut[index])
974 /(float)100)*(float)cbNode->presence->TTL);
975 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
976 /(float)100)*(float)cbNode->presence->TTL);
977 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
978 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
979 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
980 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
981 cbNode->presence->timeOut[index]);
983 cbNode->presence->TTLlevel = 0;
984 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
985 if(cbNode->sequenceNumber == response->clientResponse->sequenceNumber)
987 OC_LOG(INFO, TAG, PCF("===============No presence change"));
990 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
991 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;;
994 // Ensure that a filter is actually applied.
995 if(resourceTypeName && cbNode->filterResourceType)
997 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1003 else if(cbNode && isMulticastPresence)
1005 // Check if the same nonce for a given host
1006 OCMulticastNode* mcNode = NULL;
1007 mcNode = GetMCPresenceNode(response->fullUri);
1009 if(response->maxAge == 0)
1011 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
1012 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
1013 if(cbNode->presence)
1015 OCFree(cbNode->presence->timeOut);
1016 OCFree(cbNode->presence);
1017 cbNode->presence = NULL;
1020 else if(mcNode != NULL)
1022 if(mcNode->nonce == response->clientResponse->sequenceNumber)
1024 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
1025 result = OC_STACK_NO_MEMORY;
1028 mcNode->nonce = response->clientResponse->sequenceNumber;
1032 uint32_t uriLen = strlen((char*)response->fullUri);
1033 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
1036 memcpy(uri, response->fullUri, (uriLen + 1));
1041 PCF("===============No Memory for URI to store in the presence node"));
1042 result = OC_STACK_NO_MEMORY;
1045 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri,
1046 response->clientResponse->sequenceNumber);
1047 if(result == OC_STACK_NO_MEMORY)
1050 PCF("===============No Memory for Multicast Presence Node"));
1051 result = OC_STACK_NO_MEMORY;
1056 // Ensure that a filter is actually applied.
1057 if(resourceTypeName && cbNode->filterResourceType)
1059 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1066 else if(!cbNode && isPresenceNotification)
1068 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
1069 ------------ ignoring"));
1071 #endif // WITH_PRESENCE
1075 if(isObserveNotification)
1077 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
1078 //TODO: check the standard for methods to detect wrap around condition
1079 if(cbNode->method == OC_REST_OBSERVE &&
1080 (response->clientResponse->sequenceNumber <= cbNode->sequenceNumber ||
1081 (response->clientResponse->sequenceNumber > cbNode->sequenceNumber &&
1082 response->clientResponse->sequenceNumber ==
1083 MAX_SEQUENCE_NUMBER)))
1085 OC_LOG_V(DEBUG, TAG, "Observe notification came out of order. \
1086 Ignoring Incoming:%d Against Current:%d.",
1087 response->clientResponse->sequenceNumber, cbNode->sequenceNumber);
1090 if(response->clientResponse->sequenceNumber > cbNode->sequenceNumber){
1091 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;
1095 response->clientResponse->resJSONPayload = bufRes;
1097 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response->clientResponse);
1099 if (cbResult == OC_STACK_DELETE_TRANSACTION ||
1100 response->clientResponse->result == OC_STACK_COMM_ERROR ||
1101 (response->clientResponse->result == OC_STACK_RESOURCE_DELETED &&
1102 !isPresenceNotification && !isMulticastPresence))
1104 FindAndDeleteClientCB(cbNode);
1109 result = OC_STACK_ERROR;
1113 #ifdef WITH_PRESENCE
1114 OCFree(resourceTypeName);
1119 int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
1122 unsigned char *itr, *coap;
1123 uint8_t dotCount = 0;
1127 /* search for scheme */
1129 if (!isdigit((unsigned char) *ipAddrStr))
1131 coap = (unsigned char *) OC_COAP_SCHEME;
1132 while (*coap && tolower(*itr) == *coap)
1140 while (*ipAddrStr) {
1141 if (isdigit((unsigned char) *ipAddrStr))
1143 ipAddr[index] *= 10;
1144 ipAddr[index] += *ipAddrStr - '0';
1146 else if ((unsigned char) *ipAddrStr == '.')
1158 if(*ipAddrStr == ':')
1162 if (isdigit((unsigned char) *ipAddrStr))
1165 *port += *ipAddrStr - '0';
1176 if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
1187 //-----------------------------------------------------------------------------
1188 // Private internal function prototypes
1189 //-----------------------------------------------------------------------------
1191 static OCDoHandle GenerateInvocationHandle();
1192 static OCStackResult initResources();
1193 static void insertResource(OCResource *resource);
1194 static OCResource *findResource(OCResource *resource);
1195 static void insertResourceType(OCResource *resource,
1196 OCResourceType *resourceType);
1197 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
1199 static void insertResourceInterface(OCResource *resource,
1200 OCResourceInterface *resourceInterface);
1201 static OCResourceInterface *findResourceInterfaceAtIndex(
1202 OCResourceHandle handle, uint8_t index);
1203 static void deleteResourceType(OCResourceType *resourceType);
1204 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
1205 static void deleteResourceElements(OCResource *resource);
1206 static int deleteResource(OCResource *resource);
1207 static void deleteAllResources();
1208 static void incrementSequenceNumber(OCResource * resPtr);
1209 static OCStackResult verifyUriQueryLength(const char * inputUri,
1211 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
1212 OCStackResult getResourceType(const char * query, unsigned char** resourceType);
1214 //-----------------------------------------------------------------------------
1216 //-----------------------------------------------------------------------------
1219 * Initialize the OC Stack. Must be called prior to starting the stack.
1222 * IP Address of host device
1224 * Port of host device
1226 * Host device is client, server, or client-server
1229 * OC_STACK_OK - no errors
1230 * OC_STACK_ERROR - stack init error
1232 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1234 OCStackResult result = OC_STACK_ERROR;
1235 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
1239 OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
1245 //It is ok to select network to CA_WIFI for now
1246 CAResult_t caResult = CASelectNetwork(CA_WIFI|CA_ETHERNET);
1247 if(caResult == CA_STATUS_OK)
1249 OC_LOG(INFO, TAG, PCF("CASelectNetwork to WIFI"));
1250 CARegisterHandler(HandleCARequests, HandleCAResponses);
1252 OC_LOG(INFO, TAG, PCF("CARegisterHandler..."));
1253 stackState = OC_STACK_INITIALIZED;
1254 result = OC_STACK_OK;
1258 caResult = CAStartDiscoveryServer();
1259 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
1262 caResult = CAStartListeningServer();
1263 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
1265 case OC_CLIENT_SERVER:
1266 caResult = CAStartListeningServer();
1267 if(caResult == CA_STATUS_OK)
1269 caResult = CAStartDiscoveryServer();
1271 OC_LOG(INFO, TAG, PCF("Client-server mode"));
1274 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1275 return OC_STACK_ERROR;
1280 if (caResult == CA_STATUS_OK)
1282 result = OC_STACK_OK;
1286 result = OC_STACK_ERROR;
1293 OC_LOG(INFO, TAG, PCF("Client mode"));
1296 OC_LOG(INFO, TAG, PCF("Server mode"));
1298 case OC_CLIENT_SERVER:
1299 OC_LOG(INFO, TAG, PCF("Client-server mode"));
1302 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1303 return OC_STACK_ERROR;
1307 // Make call to OCCoAP layer
1308 result = OCInitCoAP(ipAddr, (uint16_t) port, myStackMode);
1312 defaultDeviceHandler = NULL;
1314 #if defined(CA_INT) && defined(__WITH_DTLS__)
1315 caResult = CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials);
1316 result = (caResult == CA_STATUS_OK) ? OC_STACK_OK : OC_STACK_ERROR;
1317 #endif //(CA_INT) && (__WITH_DTLS__)
1318 #ifdef WITH_PRESENCE
1319 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
1320 #endif // WITH_PRESENCE
1322 if (result == OC_STACK_OK)
1324 stackState = OC_STACK_INITIALIZED;
1326 // Initialize resource
1327 if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
1329 result = initResources();
1331 if(result != OC_STACK_OK)
1333 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1339 * Stop the OC stack. Use for a controlled shutdown.
1341 * OC_STACK_OK - no errors
1342 * OC_STACK_ERROR - stack not initialized
1344 OCStackResult OCStop()
1346 OCStackResult result = OC_STACK_ERROR;
1348 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1350 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1352 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1355 else if (stackState != OC_STACK_INITIALIZED)
1357 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1358 return OC_STACK_ERROR;
1361 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1363 #ifdef WITH_PRESENCE
1364 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1365 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1366 presenceResource.presenceTTL = 0;
1367 #endif // WITH_PRESENCE
1369 // Free memory dynamically allocated for resources
1370 deleteAllResources();
1374 //CATerminate does not return any error code. It is OK to assign result to OC_STACK_OK.
1375 result = OC_STACK_OK;
1377 result = OCStopCoAP();
1380 if (result == OC_STACK_OK)
1382 // Remove all observers
1383 DeleteObserverList();
1384 // Remove all the client callbacks
1385 DeleteClientCBList();
1386 stackState = OC_STACK_UNINITIALIZED;
1387 result = OC_STACK_OK;
1389 stackState = OC_STACK_INITIALIZED;
1390 result = OC_STACK_ERROR;
1393 // Deinit security blob
1394 DeinitOCSecurityInfo();
1396 if (result != OC_STACK_OK) {
1397 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
1404 * Map OCQualityOfService to CAMessageType
1406 * @param OCQualityOfService - Input qos.
1408 * Returns CA message type for a given qos.
1410 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
1415 return CA_MSG_CONFIRM;
1420 return CA_MSG_NONCONFIRM;
1425 * Verify the lengths of the URI and the query separately
1427 * @param inputUri - Input URI and query.
1428 * @param uriLen - The length of the initial URI with query.
1430 * Note: The '?' that appears after the URI is not considered as
1431 * a part of the query.
1433 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1437 query = strchr (inputUri, '?');
1441 if((query - inputUri) > MAX_URI_LENGTH)
1443 return OC_STACK_INVALID_URI;
1446 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1448 return OC_STACK_INVALID_QUERY;
1451 else if(uriLen > MAX_URI_LENGTH)
1453 return OC_STACK_INVALID_URI;
1459 * Discover or Perform requests on a specified resource (specified by that Resource's respective URI).
1461 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of calling this API.
1462 * @param method - @ref OCMethod to perform on the resource
1463 * @param requiredUri - URI of the resource to interact with
1464 * @param referenceUri - URI of the reference resource
1465 * @param request - JSON encoded request
1466 * @param qos - quality of service
1467 * @param cbData - struct that contains asynchronous callback function that is invoked
1468 * by the stack when discovery or resource interaction is complete
1469 * @param options - The address of an array containing the vendor specific header
1470 * header options to be sent with the request
1471 * @param numOptions - Number of vendor specific header options to be included
1474 * OC_STACK_OK - no errors
1475 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
1476 * OC_STACK_INVALID_METHOD - invalid resource method
1477 * OC_STACK_INVALID_URI - invalid required or reference URI
1479 * Note: IN case of CA, when using multicast, the required URI should not contain IP address.
1480 * Instead, it just contains the URI to the resource such as "/oc/core".
1483 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1484 const char *referenceUri, const char *request, OCConnectivityType conType,
1485 OCQualityOfService qos, OCCallbackData *cbData,
1486 OCHeaderOption * options, uint8_t numOptions)
1488 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1489 const char *referenceUri, const char *request,
1490 OCQualityOfService qos, OCCallbackData *cbData,
1491 OCHeaderOption * options, uint8_t numOptions)
1494 OCStackResult result = OC_STACK_ERROR;
1495 ClientCB *clientCB = NULL;
1496 unsigned char * requestUri = NULL;
1497 unsigned char * resourceType = NULL;
1498 unsigned char * query = NULL;
1499 char * newUri = (char *)requiredUri;
1500 (void) referenceUri;
1502 CARemoteEndpoint_t* endpoint = NULL;
1503 CAResult_t caResult;
1504 CAToken_t token = NULL;
1505 CAInfo_t requestData;
1506 CARequestInfo_t requestInfo;
1507 CAGroupEndpoint_t grpEnd;
1509 // To track if memory is allocated for additional header options
1510 uint8_t hdrOptionMemAlloc = 0;
1515 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1517 // Validate input parameters
1518 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1519 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1521 TODO ("Need to form the final query by concatenating require and reference URI's");
1522 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
1524 uint16_t uriLen = strlen(requiredUri);
1526 // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS
1532 case OC_REST_DELETE:
1533 case OC_REST_OBSERVE:
1534 case OC_REST_OBSERVE_ALL:
1535 case OC_REST_CANCEL_OBSERVE:
1537 #ifdef WITH_PRESENCE
1538 case OC_REST_PRESENCE:
1542 result = OC_STACK_INVALID_METHOD;
1546 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
1551 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
1553 result = OC_STACK_INVALID_PARAM;
1557 #ifdef WITH_PRESENCE
1558 if(method == OC_REST_PRESENCE)
1560 result = getQueryFromUri(requiredUri, &query, &newUri);
1563 result = getResourceType((char *) query, &resourceType);
1566 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1570 OC_LOG(DEBUG, TAG, PCF("Resource type is NULL."));
1575 OC_LOG(DEBUG, TAG, PCF("Query string is NULL."));
1577 if(result != OC_STACK_OK)
1582 #endif // WITH_PRESENCE
1584 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
1587 memcpy(requestUri, newUri, (uriLen + 1));
1591 result = OC_STACK_NO_MEMORY;
1595 *handle = GenerateInvocationHandle();
1598 result = OC_STACK_NO_MEMORY;
1603 memset(&requestData, 0, sizeof(CAInfo_t));
1604 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1605 memset(&grpEnd, 0, sizeof(CAGroupEndpoint_t));
1609 case OC_REST_OBSERVE:
1610 case OC_REST_OBSERVE_ALL:
1611 case OC_REST_CANCEL_OBSERVE:
1613 requestInfo.method = CA_GET;
1618 requestInfo.method = CA_PUT;
1623 requestInfo.method = CA_POST;
1626 case OC_REST_DELETE:
1628 requestInfo.method = CA_DELETE;
1631 #ifdef WITH_PRESENCE
1632 case OC_REST_PRESENCE:
1634 // Replacing method type with GET because "presence"
1635 // is a stack layer only implementation.
1636 requestInfo.method = CA_GET;
1641 result = OC_STACK_INVALID_METHOD;
1645 //High QoS is not supported
1646 if(qos == OC_HIGH_QOS)
1648 result = OC_STACK_INVALID_PARAM;
1654 caResult = CAGenerateToken(&token);
1655 if (caResult != CA_STATUS_OK)
1657 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1658 CADestroyToken(token);
1662 requestData.type = qualityOfServiceToMessageType(qos);
1663 requestData.token = token;
1664 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1666 result = CreateObserveHeaderOption (&(requestData.options), options,
1667 numOptions, OC_OBSERVE_REGISTER);
1668 if (result != OC_STACK_OK)
1672 hdrOptionMemAlloc = 1;
1673 requestData.numOptions = numOptions + 1;
1677 requestData.options = (CAHeaderOption_t*)options;
1678 requestData.numOptions = numOptions;
1680 requestData.payload = (char *)request;
1682 requestInfo.info = requestData;
1684 CAConnectivityType_t caConType;
1686 result = OCToCAConnectivityType(conType, &caConType);
1687 if (result != OC_STACK_OK)
1689 OC_LOG(ERROR, TAG, PCF("Invalid Connectivity Type"));
1694 if(conType == OC_ALL)
1696 grpEnd.connectivityType = caConType;
1698 grpEnd.resourceUri = (CAURI_t) OCMalloc(uriLen + 1);
1699 strncpy(grpEnd.resourceUri, requiredUri, (uriLen + 1));
1701 caResult = CASendRequestToAll(&grpEnd, &requestInfo);
1705 caResult = CACreateRemoteEndpoint(newUri, caConType, &endpoint);
1707 if (caResult != CA_STATUS_OK)
1709 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1713 caResult = CASendRequest(endpoint, &requestInfo);
1716 if (caResult != CA_STATUS_OK)
1718 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1722 if((result = AddClientCB(&clientCB, cbData, &token, handle, method,
1723 requestUri, resourceType)) != OC_STACK_OK)
1725 result = OC_STACK_NO_MEMORY;
1731 // Generate token which will be used by OCStack to match responses received
1733 OCGenerateCoAPToken(&token);
1735 if((result = AddClientCB(&clientCB, cbData, &token, handle, method, requestUri, resourceType))
1738 result = OC_STACK_NO_MEMORY;
1742 // Make call to OCCoAP layer
1743 result = OCDoCoAPResource(method, qos, &token, newUri, request, options, numOptions);
1747 if(newUri != requiredUri)
1751 if (result != OC_STACK_OK)
1753 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1754 FindAndDeleteClientCB(clientCB);
1757 CADestroyRemoteEndpoint(endpoint);
1758 OCFree(grpEnd.resourceUri);
1759 if (hdrOptionMemAlloc)
1761 OCFree(requestData.options);
1768 * Cancel a request associated with a specific @ref OCDoResource invocation.
1770 * @param handle - Used to identify a specific OCDoResource invocation.
1771 * @param qos - used to specify Quality of Service (read below for more info)
1772 * @param options- used to specify vendor specific header options when sending
1773 * explicit observe cancellation
1774 * @param numOptions- Number of header options to be included
1777 * OC_STACK_OK - No errors; Success
1778 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1780 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1784 * This ftn is implemented one of two ways in the case of observation:
1786 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1787 * Remove the callback associated on client side.
1788 * When the next notification comes in from server,
1789 * reply with RESET message to server.
1790 * Keep in mind that the server will react to RESET only
1791 * if the last notification was sent ans CON
1793 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1794 * and it is associated with an observe request
1795 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1796 * Send CON Observe request to server with
1797 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1798 * Remove the callback associated on client side.
1800 OCStackResult ret = OC_STACK_OK;
1802 CARemoteEndpoint_t* endpoint = NULL;
1803 CAResult_t caResult;
1804 CAInfo_t requestData;
1805 CARequestInfo_t requestInfo;
1806 // Track if memory is allocated for additional header options
1807 uint8_t hdrOptionMemAlloc = 0;
1811 return OC_STACK_INVALID_PARAM;
1814 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1816 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1819 switch (clientCB->method)
1821 case OC_REST_OBSERVE:
1822 case OC_REST_OBSERVE_ALL:
1824 //TODO-CA : Why CA_WIFI alone?
1825 caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri, CA_WIFI,
1827 if (caResult != CA_STATUS_OK)
1829 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1830 return OC_STACK_ERROR;
1833 memset(&requestData, 0, sizeof(CAInfo_t));
1834 requestData.type = qualityOfServiceToMessageType(qos);
1835 requestData.token = clientCB->token;
1836 if (CreateObserveHeaderOption (&(requestData.options),
1837 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
1839 return OC_STACK_ERROR;
1841 hdrOptionMemAlloc = 1;
1842 requestData.numOptions = numOptions + 1;
1843 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1844 requestInfo.method = CA_GET;
1845 requestInfo.info = requestData;
1847 caResult = CASendRequest(endpoint, &requestInfo);
1848 if (caResult != CA_STATUS_OK)
1850 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1852 if(caResult == CA_STATUS_OK)
1857 if(qos == OC_HIGH_QOS)
1859 ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
1860 &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
1865 FindAndDeleteClientCB(clientCB);
1869 #ifdef WITH_PRESENCE
1870 case OC_REST_PRESENCE:
1871 FindAndDeleteClientCB(clientCB);
1875 return OC_STACK_INVALID_METHOD;
1879 CADestroyRemoteEndpoint(endpoint);
1880 if (hdrOptionMemAlloc)
1882 OCFree(requestData.options);
1889 #ifdef WITH_PRESENCE
1891 OCStackResult OCProcessPresence()
1893 OCStackResult result = OC_STACK_OK;
1894 uint8_t ipAddr[4] = { 0 };
1897 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1898 ClientCB* cbNode = NULL;
1900 OCClientResponse clientResponse;
1901 OCResponse * response = NULL;
1902 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1904 LL_FOREACH(cbList, cbNode) {
1905 if(OC_REST_PRESENCE == cbNode->method)
1907 if(cbNode->presence)
1909 uint32_t now = GetTime(0);
1910 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d",
1911 cbNode->presence->TTLlevel);
1912 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1915 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1920 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1921 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1922 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1925 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1927 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1928 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1930 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1932 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
1933 (OCDevAddr *) &dst, 0, NULL);
1934 if(result != OC_STACK_OK)
1938 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1939 &cbNode->token, &clientResponse, NULL);
1940 if(result != OC_STACK_OK)
1945 // Increment the TTLLevel (going to a next state), so we don't keep
1946 // sending presence notification to client.
1947 cbNode->presence->TTLlevel++;
1948 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1949 cbNode->presence->TTLlevel);
1953 result = OC_STACK_INVALID_IP;
1957 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
1958 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1960 FindAndDeleteClientCB(cbNode);
1964 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1966 CAResult_t caResult;
1967 CARemoteEndpoint_t* endpoint = NULL;
1968 CAInfo_t requestData;
1969 CARequestInfo_t requestInfo;
1971 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
1973 //TODO-CA : Why CA_WIFI alone?
1974 caResult = CACreateRemoteEndpoint((char *)cbNode->requestUri, CA_WIFI,
1977 if (caResult != CA_STATUS_OK)
1979 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1983 memset(&requestData, 0, sizeof(CAInfo_t));
1984 requestData.type = CA_MSG_NONCONFIRM;
1985 requestData.token = cbNode->token;
1987 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1988 requestInfo.method = CA_GET;
1989 requestInfo.info = requestData;
1991 caResult = CASendRequest(endpoint, &requestInfo);
1993 if (caResult != CA_STATUS_OK)
1995 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1999 cbNode->presence->TTLlevel++;
2000 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
2001 cbNode->presence->TTLlevel);
2007 if (result != OC_STACK_OK)
2009 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
2014 OCStackResult OCProcessPresence()
2016 OCStackResult result = OC_STACK_OK;
2017 uint8_t ipAddr[4] = { 0 };
2020 ClientCB* cbNode = NULL;
2022 OCClientResponse clientResponse;
2023 OCResponse * response = NULL;
2025 LL_FOREACH(cbList, cbNode) {
2026 if(OC_REST_PRESENCE == cbNode->method)
2028 if(cbNode->presence)
2030 uint32_t now = GetTime(0);
2031 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
2032 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
2035 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
2040 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
2041 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
2042 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2045 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2047 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
2048 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
2050 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
2052 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
2053 (OCDevAddr *) &dst, 0, NULL);
2054 if(result != OC_STACK_OK)
2058 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
2059 &cbNode->token, &clientResponse, NULL);
2060 if(result != OC_STACK_OK)
2065 // Increment the TTLLevel (going to a next state), so we don't keep
2066 // sending presence notification to client.
2067 cbNode->presence->TTLlevel++;
2068 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
2069 cbNode->presence->TTLlevel);
2073 result = OC_STACK_INVALID_IP;
2076 HandleStackResponses(response);
2078 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2080 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
2083 CAToken_t token = NULL;
2084 CAResult_t caResult = CAGenerateToken(&token);
2085 if (caResult != CA_STATUS_OK)
2087 CADestroyToken(token);
2092 OCGenerateCoAPToken(&token);
2094 result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
2095 &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
2097 if(result != OC_STACK_OK)
2102 cbNode->presence->TTLlevel++;
2103 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
2109 if (result != OC_STACK_OK)
2111 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
2116 #endif // WITH_PRESENCE
2119 * Called in main loop of OC client or server. Allows low-level processing of
2123 * OC_STACK_OK - no errors
2124 * OC_STACK_ERROR - stack process error
2126 OCStackResult OCProcess()
2128 #ifdef WITH_PRESENCE
2129 OCProcessPresence();
2132 CAHandleRequestResponse();
2140 #ifdef WITH_PRESENCE
2142 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
2143 * presence notifications to clients via multicast. Once this API has been called with a success,
2144 * clients may query for this server's presence and this server's stack will respond via multicast.
2146 * Server can call this function when it comes online for the first time, or when it comes back
2147 * online from offline mode, or when it re enters network.
2149 * @param ttl - Time To Live in seconds
2150 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
2153 * OC_STACK_OK - No errors; Success
2155 OCStackResult OCStartPresence(const uint32_t ttl)
2157 OCChangeResourceProperty(
2158 &(((OCResource *)presenceResource.handle)->resourceProperties),
2163 presenceResource.presenceTTL = ttl;
2166 if(OC_PRESENCE_UNINITIALIZED == presenceState)
2168 OCDevAddr multiCastAddr;
2169 presenceState = OC_PRESENCE_INITIALIZED;
2171 OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
2174 CAAddress_t addressInfo;
2175 strncpy(addressInfo.IP.ipAddress, "224.0.1.187", CA_IPADDR_SIZE);
2176 addressInfo.IP.port = 5683;
2178 //TODO make sure there is no memory leak here since another copy
2179 //of token is being created inside AddObserver
2180 CAToken_t caToken = NULL;
2181 CAResult_t caResult = CAGenerateToken(&caToken);
2182 if (caResult != CA_STATUS_OK)
2184 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2185 CADestroyToken(caToken);
2186 return OC_STACK_ERROR;
2189 AddObserver(OC_PRESENCE_URI, NULL, 0, &caToken,
2190 &multiCastAddr, (OCResource *)presenceResource.handle, OC_LOW_QOS,
2191 &addressInfo, CA_WIFI);
2194 OCGenerateCoAPToken(&token);
2195 //add the presence observer
2196 AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
2197 (OCResource *)presenceResource.handle, OC_LOW_QOS);
2201 // Each time OCStartPresence is called
2202 // a different random 32-bit integer number is used
2203 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2205 return SendPresenceNotification(NULL);
2209 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
2210 * presence notifications to clients via multicast. Once this API has been called with a success,
2211 * this server's stack will not respond to clients querying for this server's presence.
2213 * Server can call this function when it is terminating, going offline, or when going
2214 * away from network.
2217 * OC_STACK_OK - No errors; Success
2219 OCStackResult OCStopPresence()
2221 OCStackResult result = OC_STACK_ERROR;
2222 //make resource inactive
2223 result = OCChangeResourceProperty(
2224 &(((OCResource *) presenceResource.handle)->resourceProperties),
2226 result = SendPresenceNotification(NULL);
2233 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
2235 defaultDeviceHandler = entityHandler;
2240 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2242 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
2244 if(myStackMode == OC_CLIENT)
2246 return OC_STACK_ERROR;
2249 return SaveDeviceInfo(deviceInfo);
2255 * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource
2256 * @param resourceTypeName - name of resource type. Example: "core.led"
2257 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
2258 * @param uri - URI of the resource. Example: "/a/led"
2259 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2260 * NULL for default entity handler
2261 * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE
2264 * OC_STACK_OK - no errors
2265 * OC_STACK_ERROR - stack process error
2267 OCStackResult OCCreateResource(OCResourceHandle *handle,
2268 const char *resourceTypeName,
2269 const char *resourceInterfaceName,
2270 const char *uri, OCEntityHandler entityHandler,
2271 uint8_t resourceProperties) {
2273 OCResource *pointer = NULL;
2276 OCStackResult result = OC_STACK_ERROR;
2278 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
2280 if(myStackMode == OC_CLIENT)
2284 // Validate parameters
2285 if(!uri || (strlen(uri) == 0))
2287 OC_LOG(ERROR, TAG, PCF("URI is invalid"));
2288 return OC_STACK_INVALID_URI;
2290 // Is it presented during resource discovery?
2291 if (!handle || !resourceTypeName) {
2292 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
2293 return OC_STACK_INVALID_PARAM;
2296 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
2297 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2300 // Make sure resourceProperties bitmask has allowed properties specified
2301 if (resourceProperties
2302 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
2303 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2304 return OC_STACK_INVALID_PARAM;
2307 // If the headResource is NULL, then no resources have been created...
2308 pointer = headResource;
2310 // At least one resources is in the resource list, so we need to search for
2311 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2313 if (strcmp(uri, pointer->uri) == 0) {
2314 OC_LOG(ERROR, TAG, PCF("URI already in use"));
2315 return OC_STACK_INVALID_PARAM;
2317 pointer = pointer->next;
2320 // Create the pointer and insert it into the resource list
2321 pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
2325 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2327 insertResource(pointer);
2330 size = strlen(uri) + 1;
2331 str = (char *) OCMalloc(size);
2335 strncpy(str, uri, size);
2338 // Set properties. Set OC_ACTIVE
2339 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2342 // Add the resourcetype to the resource
2343 result = BindResourceTypeToResource(pointer, resourceTypeName);
2344 if (result != OC_STACK_OK) {
2345 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
2349 // Add the resourceinterface to the resource
2350 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2351 if (result != OC_STACK_OK) {
2352 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
2356 // If an entity handler has been passed, attach it to the newly created
2357 // resource. Otherwise, set the default entity handler.
2360 pointer->entityHandler = entityHandler;
2364 pointer->entityHandler = defaultResourceEHandler;
2368 result = OC_STACK_OK;
2370 #ifdef WITH_PRESENCE
2371 if(presenceResource.handle)
2373 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2374 SendPresenceNotification(pointer->rsrcType);
2378 if (result != OC_STACK_OK)
2380 // Deep delete of resource and other dynamic elements that it contains
2381 deleteResource(pointer);
2390 * Create a resource. with host ip address for remote resource
2392 * @param handle - pointer to handle to newly created resource. Set by ocstack.
2393 * Used to refer to resource
2394 * @param resourceTypeName - name of resource type. Example: "core.led"
2395 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
2396 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
2397 * @param uri - URI of the resource. Example: "/a/led"
2398 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2399 * NULL for default entity handler
2400 * @param resourceProperties - properties supported by resource.
2401 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
2404 * OC_STACK_OK - no errors
2405 * OC_STACK_ERROR - stack process error
2408 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
2409 const char *resourceTypeName,
2410 const char *resourceInterfaceName,
2413 OCEntityHandler entityHandler,
2414 uint8_t resourceProperties)
2418 OCStackResult result = OC_STACK_ERROR;
2420 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
2421 uri, entityHandler, resourceProperties);
2423 if (result != OC_STACK_ERROR)
2426 size = strlen(host) + 1;
2427 str = (char *) OCMalloc(size);
2430 return OC_STACK_ERROR;
2432 strncpy(str, host, size);
2433 ((OCResource *) *handle)->host = str;
2440 * Add a resource to a collection resource.
2442 * @param collectionHandle - handle to the collection resource
2443 * @param resourceHandle - handle to resource to be added to the collection resource
2446 * OC_STACK_OK - no errors
2447 * OC_STACK_ERROR - stack process error
2448 * OC_STACK_INVALID_PARAM - invalid collectionhandle
2450 OCStackResult OCBindResource(
2451 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2452 OCResource *resource;
2455 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2457 // Validate parameters
2458 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2459 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2460 // Container cannot contain itself
2461 if (collectionHandle == resourceHandle) {
2462 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2463 return OC_STACK_INVALID_PARAM;
2466 // Use the handle to find the resource in the resource linked list
2467 resource = findResource((OCResource *) collectionHandle);
2469 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2470 return OC_STACK_INVALID_PARAM;
2473 // Look for an open slot to add add the child resource.
2474 // If found, add it and return success
2475 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2476 if (!resource->rsrcResources[i]) {
2477 resource->rsrcResources[i] = (OCResource *) resourceHandle;
2478 OC_LOG(INFO, TAG, PCF("resource bound"));
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;
2496 * Remove a resource from a collection resource.
2498 * @param collectionHandle - handle to the collection resource
2499 * @param resourceHandle - handle to resource to be added to the collection resource
2502 * OC_STACK_OK - no errors
2503 * OC_STACK_ERROR - stack process error
2504 * OC_STACK_INVALID_PARAM - invalid collectionHandle
2506 OCStackResult OCUnBindResource(
2507 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2508 OCResource *resource;
2511 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2513 // Validate parameters
2514 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2515 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2516 // Container cannot contain itself
2517 if (collectionHandle == resourceHandle) {
2518 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2519 return OC_STACK_INVALID_PARAM;
2522 // Use the handle to find the resource in the resource linked list
2523 resource = findResource((OCResource *) collectionHandle);
2525 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2526 return OC_STACK_INVALID_PARAM;
2529 // Look for an open slot to add add the child resource.
2530 // If found, add it and return success
2531 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2532 if (resourceHandle == resource->rsrcResources[i]) {
2533 resource->rsrcResources[i] = (OCResource *) NULL;
2534 OC_LOG(INFO, TAG, PCF("resource unbound"));
2539 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2541 #ifdef WITH_PRESENCE
2542 if(presenceResource.handle)
2544 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2545 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2549 // Unable to add resourceHandle, so return error
2550 return OC_STACK_ERROR;
2553 OCStackResult BindResourceTypeToResource(OCResource* resource,
2554 const char *resourceTypeName)
2556 OCResourceType *pointer = NULL;
2559 OCStackResult result = OC_STACK_ERROR;
2561 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
2563 // Validate parameters
2564 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2565 // TODO: Does resource attribute resentation really have to be maintained in stack?
2566 // Is it presented during resource discovery?
2568 TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
2570 // Create the resourcetype and insert it into the resource list
2571 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
2576 // Set the resourceTypeName
2577 size = strlen(resourceTypeName) + 1;
2578 str = (char *) OCMalloc(size);
2582 strncpy(str, resourceTypeName, size);
2583 pointer->resourcetypename = str;
2585 insertResourceType(resource, pointer);
2586 result = OC_STACK_OK;
2588 exit: if (result != OC_STACK_OK) {
2596 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2597 const char *resourceInterfaceName)
2599 OCResourceInterface *pointer = NULL;
2602 OCStackResult result = OC_STACK_ERROR;
2604 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
2606 // Validate parameters
2607 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2609 TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
2611 // Create the resourceinterface and insert it into the resource list
2612 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
2617 // Set the resourceinterface name
2618 size = strlen(resourceInterfaceName) + 1;
2619 str = (char *) OCMalloc(size);
2623 strncpy(str, resourceInterfaceName, size);
2624 pointer->name = str;
2626 // Bind the resourceinterface to the resource
2627 insertResourceInterface(resource, pointer);
2629 result = OC_STACK_OK;
2631 exit: if (result != OC_STACK_OK) {
2640 * Bind a resourcetype to a resource.
2642 * @param handle - handle to the resource
2643 * @param resourceTypeName - name of resource type. Example: "core.led"
2646 * OC_STACK_OK - no errors
2647 * OC_STACK_ERROR - stack process error
2649 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2650 const char *resourceTypeName) {
2652 OCStackResult result = OC_STACK_ERROR;
2653 OCResource *resource;
2655 // Make sure resource exists
2656 resource = findResource((OCResource *) handle);
2658 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2659 return OC_STACK_ERROR;
2662 // call internal function
2663 result = BindResourceTypeToResource(resource, resourceTypeName);
2665 #ifdef WITH_PRESENCE
2666 if(presenceResource.handle)
2668 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2669 SendPresenceNotification(resource->rsrcType);
2677 * Bind a resourceinterface to a resource.
2679 * @param handle - handle to the resource
2680 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
2683 * OC_STACK_OK - no errors
2684 * OC_STACK_ERROR - stack process error
2687 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2688 const char *resourceInterfaceName) {
2690 OCStackResult result = OC_STACK_ERROR;
2691 OCResource *resource;
2693 // Make sure resource exists
2694 resource = findResource((OCResource *) handle);
2696 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2697 return OC_STACK_ERROR;
2700 // call internal function
2701 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2703 #ifdef WITH_PRESENCE
2704 if(presenceResource.handle)
2706 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2707 SendPresenceNotification(resource->rsrcType);
2715 * Get the number of resources that have been created in the stack.
2717 * @param numResources - pointer to count variable
2720 * OC_STACK_OK - no errors
2721 * OC_STACK_ERROR - stack process error
2724 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
2725 OCResource *pointer = headResource;
2727 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2728 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2731 *numResources = *numResources + 1;
2732 pointer = pointer->next;
2738 * Get a resource handle by index.
2740 * @param index - index of resource, 0 to Count - 1
2743 * Resource handle - if found
2744 * NULL - if not found
2746 OCResourceHandle OCGetResourceHandle(uint8_t index) {
2747 OCResource *pointer = headResource;
2750 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2752 // Iterate through the list
2753 while ((i < index) && pointer) {
2755 pointer = pointer->next;
2757 return (OCResourceHandle) pointer;
2761 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
2764 * @param handle - handle of resource to be deleted
2767 * OC_STACK_OK - no errors
2768 * OC_STACK_ERROR - stack process error
2769 * OC_STACK_NO_RESOURCE - resource not found
2770 * OC_STACK_INVALID_PARAM - invalid param
2772 OCStackResult OCDeleteResource(OCResourceHandle handle) {
2773 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2776 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2777 return OC_STACK_INVALID_PARAM;
2780 OCResource *resource = findResource((OCResource *) handle);
2781 if (resource == NULL) {
2782 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2783 return OC_STACK_NO_RESOURCE;
2786 if (deleteResource((OCResource *) handle) == 0) {
2787 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2788 return OC_STACK_ERROR;
2795 * Get the URI of the resource specified by handle.
2797 * @param handle - handle of resource
2799 * URI string - if resource found
2800 * NULL - resource not found
2802 const char *OCGetResourceUri(OCResourceHandle handle) {
2803 OCResource *resource;
2804 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2806 resource = findResource((OCResource *) handle);
2808 return resource->uri;
2810 return (const char *) NULL;
2814 * Get the properties of the resource specified by handle.
2815 * NOTE: that after a resource is created, the OC_ACTIVE property is set
2816 * for the resource by the stack.
2818 * @param handle - handle of resource
2820 * property bitmap - if resource found
2821 * NULL - resource not found
2823 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
2824 OCResource *resource;
2825 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2827 resource = findResource((OCResource *) handle);
2829 return resource->resourceProperties;
2835 * Get the number of resource types of the resource.
2837 * @param handle - handle of resource
2838 * @param numResourceTypes - pointer to count variable
2841 * OC_STACK_OK - no errors
2842 * OC_STACK_ERROR - stack process error
2844 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2845 uint8_t *numResourceTypes) {
2846 OCResource *resource;
2847 OCResourceType *pointer;
2849 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2850 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2851 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2853 *numResourceTypes = 0;
2855 resource = findResource((OCResource *) handle);
2857 pointer = resource->rsrcType;
2859 *numResourceTypes = *numResourceTypes + 1;
2860 pointer = pointer->next;
2867 * Get name of resource type of the resource.
2869 * @param handle - handle of resource
2870 * @param index - index of resource, 0 to Count - 1
2873 * resource type name - if resource found
2874 * NULL - resource not found
2876 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
2877 OCResourceType *resourceType;
2879 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2881 resourceType = findResourceTypeAtIndex(handle, index);
2883 return resourceType->resourcetypename;
2885 return (const char *) NULL;
2891 * Get the number of resource interfaces of the resource.
2893 * @param handle - handle of resource
2894 * @param numResources - pointer to count variable
2897 * OC_STACK_OK - no errors
2898 * OC_STACK_ERROR - stack process error
2900 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2901 uint8_t *numResourceInterfaces) {
2902 OCResourceInterface *pointer;
2903 OCResource *resource;
2905 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2907 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2908 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2910 *numResourceInterfaces = 0;
2911 resource = findResource((OCResource *) handle);
2913 pointer = resource->rsrcInterface;
2915 *numResourceInterfaces = *numResourceInterfaces + 1;
2916 pointer = pointer->next;
2923 * Get name of resource interface of the resource.
2925 * @param handle - handle of resource
2926 * @param index - index of resource, 0 to Count - 1
2929 * resource interface name - if resource found
2930 * NULL - resource not found
2932 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
2933 OCResourceInterface *resourceInterface;
2935 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2937 resourceInterface = findResourceInterfaceAtIndex(handle, index);
2938 if (resourceInterface) {
2939 return resourceInterface->name;
2941 return (const char *) NULL;
2945 * Get resource handle from the collection resource by index.
2947 * @param collectionHandle - handle of collection resource
2948 * @param index - index of contained resource, 0 to Count - 1
2951 * handle to resource - if resource found
2952 * NULL - resource not found
2954 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2956 OCResource *resource;
2958 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2960 if (index >= MAX_CONTAINED_RESOURCES) {
2964 resource = findResource((OCResource *) collectionHandle);
2969 return resource->rsrcResources[index];
2973 * Bind an entity handler to the resource.
2975 * @param handle - handle to the resource that the contained resource is to be bound
2976 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2978 * OC_STACK_OK - no errors
2979 * OC_STACK_ERROR - stack process error
2981 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2982 OCEntityHandler entityHandler) {
2983 OCResource *resource;
2985 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2987 // Validate parameters
2988 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2989 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2991 // Use the handle to find the resource in the resource linked list
2992 resource = findResource((OCResource *)handle);
2994 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2995 return OC_STACK_ERROR;
2999 resource->entityHandler = entityHandler;
3001 #ifdef WITH_PRESENCE
3002 if(presenceResource.handle)
3004 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3005 SendPresenceNotification(resource->rsrcType);
3013 * Get the entity handler for a resource.
3015 * @param handle - handle of resource
3018 * entity handler - if resource found
3019 * NULL - resource not found
3021 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
3022 OCResource *resource;
3024 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
3026 // Use the handle to find the resource in the resource linked list
3027 resource = findResource((OCResource *)handle);
3029 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3034 return resource->entityHandler;
3037 void incrementSequenceNumber(OCResource * resPtr)
3039 // Increment the sequence number
3040 resPtr->sequenceNum += 1;
3041 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3043 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3049 * Notify Presence subscribers that a resource has been modified
3051 * @param resourceType - Handle to the resourceType linked list of resource
3052 * that was modified.
3053 * @param qos - Quality Of Service
3056 #ifdef WITH_PRESENCE
3057 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
3059 OCResource *resPtr = NULL;
3060 OCStackResult result;
3061 OCMethod method = OC_REST_PRESENCE;
3062 uint32_t maxAge = 0;
3063 resPtr = findResource((OCResource *) presenceResource.handle);
3066 return OC_STACK_NO_RESOURCE;
3068 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3070 maxAge = presenceResource.presenceTTL;
3077 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
3081 #endif // WITH_PRESENCE
3083 * Notify observers that an observed value has changed.
3085 * @param handle - handle of resource
3088 * OC_STACK_OK - no errors
3089 * OC_STACK_NO_RESOURCE - invalid resource handle
3090 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
3092 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
3094 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
3096 OCResource *resPtr = NULL;
3097 OCStackResult result;
3098 OCMethod method = OC_REST_NOMETHOD;
3099 uint32_t maxAge = 0;
3101 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
3102 #ifdef WITH_PRESENCE
3103 if(handle == presenceResource.handle)
3107 #endif // WITH_PRESENCE
3108 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3110 // Verify that the resource exists
3111 resPtr = findResource ((OCResource *) handle);
3114 return OC_STACK_NO_RESOURCE;
3118 //only increment in the case of regular observing (not presence)
3119 incrementSequenceNumber(resPtr);
3120 method = OC_REST_OBSERVE;
3121 maxAge = MAX_OBSERVE_AGE;
3122 #ifdef WITH_PRESENCE
3123 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
3125 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3132 OCNotifyListOfObservers (OCResourceHandle handle,
3133 OCObservationId *obsIdList,
3134 uint8_t numberOfIds,
3135 unsigned char *notificationJSONPayload,
3136 OCQualityOfService qos)
3138 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
3140 OCResource *resPtr = NULL;
3141 //TODO: we should allow the server to define this
3142 uint32_t maxAge = MAX_OBSERVE_AGE;
3144 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3145 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3146 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
3148 // Verify that the resource exists
3149 resPtr = findResource ((OCResource *) handle);
3150 if (NULL == resPtr || myStackMode == OC_CLIENT)
3152 return OC_STACK_NO_RESOURCE;
3156 incrementSequenceNumber(resPtr);
3158 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3159 notificationJSONPayload, maxAge, qos));
3163 * Send a response to a request.
3164 * The response can be a regular, slow, or block (i.e. a response that
3165 * is too large to be sent in a single PDU and must span multiple transmissions)
3167 * @param response - pointer to structure that contains response parameters
3170 * OC_STACK_OK - No errors; Success
3171 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
3172 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
3173 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
3174 * persistent response buffer is necessary
3176 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3178 OCStackResult result = OC_STACK_ERROR;
3179 OCServerRequest *serverRequest = NULL;
3181 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
3183 // Validate input parameters
3184 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3185 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3187 // TODO: Placeholder for creating a response entry when implementing
3188 // block transfer feature
3190 // If a response payload is present, check if block transfer is required
3191 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
3192 (const char *)ehResponse->payload, ehResponse->payloadSize))
3194 OC_LOG(INFO, TAG, PCF("Block transfer required"));
3196 // Persistent response buffer is needed for block transfer
3197 if (!ehResponse->persistentBufferFlag)
3199 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
3200 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
3202 // TODO: Placeholder for block transfer handling
3203 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
3204 // when implementing the block transfer feature
3209 // Get pointer to request info
3210 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3213 result = serverRequest->ehResponseHandler(ehResponse);
3220 * Cancel a response. Applies to a block response
3222 * @param responseHandle - response handle set by stack in OCServerResponse after
3223 * OCDoResponse is called
3226 * OC_STACK_OK - No errors; Success
3227 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
3229 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
3231 OCStackResult result = OC_STACK_NOTIMPL;
3233 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
3235 // TODO: validate response handle
3240 //-----------------------------------------------------------------------------
3241 // Private internal function definitions
3242 //-----------------------------------------------------------------------------
3244 * Generate handle of OCDoResource invocation for callback management.
3246 static OCDoHandle GenerateInvocationHandle()
3248 OCDoHandle handle = NULL;
3249 // Generate token here, it will be deleted when the transaction is deleted
3250 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
3253 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
3258 #ifdef WITH_PRESENCE
3259 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3260 OCResourceProperty resourceProperties, uint8_t enable)
3262 if (resourceProperties
3263 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
3264 OC_LOG(ERROR, TAG, PCF("Invalid property"));
3265 return OC_STACK_INVALID_PARAM;
3269 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3273 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3280 * Initialize resource data structures, variables, etc.
3282 OCStackResult initResources() {
3283 OCStackResult result = OC_STACK_OK;
3284 // Init application resource vars
3285 headResource = NULL;
3286 // Init Virtual Resources
3287 #ifdef WITH_PRESENCE
3288 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
3289 //presenceResource.token = OCGenerateCoAPToken();
3290 result = OCCreateResource(&presenceResource.handle,
3291 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3296 //make resource inactive
3297 result = OCChangeResourceProperty(
3298 &(((OCResource *) presenceResource.handle)->resourceProperties),
3305 * Add a resource to the end of the linked list of resources.
3307 * @param resource - resource to be added
3309 void insertResource(OCResource *resource) {
3310 OCResource *pointer;
3312 if (!headResource) {
3313 headResource = resource;
3315 pointer = headResource;
3317 while (pointer->next) {
3318 pointer = pointer->next;
3320 pointer->next = resource;
3322 resource->next = NULL;
3326 * Find a resource in the linked list of resources.
3328 * @param resource - resource to be found
3330 * NULL - resource not found
3331 * pointer to resource - pointer to resource that was found in the linked list
3333 OCResource *findResource(OCResource *resource) {
3334 OCResource *pointer = headResource;
3337 if (pointer == resource) {
3340 pointer = pointer->next;
3345 void deleteAllResources()
3347 OCResource *pointer = headResource;
3352 temp = pointer->next;
3353 #ifdef WITH_PRESENCE
3354 if(pointer != (OCResource *) presenceResource.handle)
3356 #endif // WITH_PRESENCE
3357 deleteResource(pointer);
3358 #ifdef WITH_PRESENCE
3360 #endif // WITH_PRESENCE
3364 #ifdef WITH_PRESENCE
3365 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3366 // presence notification attributed to their deletion to be processed.
3367 deleteResource((OCResource *) presenceResource.handle);
3368 #endif // WITH_PRESENCE
3372 * Delete the resource from the linked list.
3374 * @param resource - resource to be deleted
3379 int deleteResource(OCResource *resource) {
3380 OCResource *prev = NULL;
3383 temp = headResource;
3385 if (temp == resource) {
3386 // Invalidate all Resource Properties.
3387 resource->resourceProperties = (OCResourceProperty) 0;
3388 #ifdef WITH_PRESENCE
3389 if(resource != (OCResource *) presenceResource.handle)
3391 #endif // WITH_PRESENCE
3392 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3393 #ifdef WITH_PRESENCE
3396 if(presenceResource.handle)
3398 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3399 if(resource != (OCResource *) presenceResource.handle)
3401 SendPresenceNotification(resource->rsrcType);
3405 SendPresenceNotification(NULL);
3410 if (temp == headResource) {
3411 headResource = temp->next;
3413 prev->next = temp->next;
3416 deleteResourceElements(temp);
3429 * Delete all of the dynamically allocated elements that were created for the resource.
3431 * @param resource - specified resource
3433 void deleteResourceElements(OCResource *resource) {
3439 OCFree(resource->uri);
3441 // Delete resourcetype linked list
3442 deleteResourceType(resource->rsrcType);
3444 // Delete resourceinterface linked list
3445 deleteResourceInterface(resource->rsrcInterface);
3449 * Delete all of the dynamically allocated elements that were created for the resource type.
3451 * @param resourceType - specified resource type
3453 void deleteResourceType(OCResourceType *resourceType) {
3454 OCResourceType *pointer = resourceType;
3455 OCResourceType *next;
3458 next = pointer->next;
3459 OCFree(pointer->resourcetypename);
3466 * Delete all of the dynamically allocated elements that were created for the resource interface.
3468 * @param resourceInterface - specified resource interface
3470 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
3471 OCResourceInterface *pointer = resourceInterface;
3472 OCResourceInterface *next;
3475 next = pointer->next;
3476 OCFree(pointer->name);
3483 * Insert a resource type into a resource's resource type linked list.
3485 * @param resource - resource where resource type is to be inserted
3486 * @param resourceType - resource type to be inserted
3488 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
3489 OCResourceType *pointer;
3491 if (resource && !resource->rsrcType) {
3492 resource->rsrcType = resourceType;
3496 pointer = resource->rsrcType;
3500 pointer = resourceType;
3502 while (pointer->next) {
3503 pointer = pointer->next;
3505 pointer->next = resourceType;
3507 resourceType->next = NULL;
3511 * Get a resource type at the specified index within a resource.
3513 * @param handle - handle of resource
3514 * @param index - index of resource type
3517 * resourcetype - if found
3520 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
3521 OCResource *resource;
3522 OCResourceType *pointer;
3525 // Find the specified resource
3526 resource = findResource((OCResource *) handle);
3531 // Make sure a resource has a resourcetype
3532 if (!resource->rsrcType) {
3536 // Iterate through the list
3537 pointer = resource->rsrcType;
3539 while ((i < index) && pointer) {
3541 pointer = pointer->next;
3547 * Finds a resource type in an OCResourceType link-list.
3549 * @param resourceTypeList - the link-list to be searched through
3550 * @param resourceTypeName - the key to search for
3553 * resourceType that matches the key (ie. resourceTypeName)
3554 * NULL - either an invalid parameter or this function was unable to find the key.
3556 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3558 if(resourceTypeList && resourceTypeName)
3560 OCResourceType * rtPointer = resourceTypeList;
3561 while(resourceTypeName && rtPointer)
3563 if(rtPointer->resourcetypename &&
3564 strcmp(resourceTypeName, (const char *)
3565 (rtPointer->resourcetypename)) == 0)
3569 rtPointer = rtPointer->next;
3576 * Insert a resource interface into a resource's resource interface linked list.
3578 * @param resource - resource where resource interface is to be inserted
3579 * @param resourceInterface - resource interface to be inserted
3581 void insertResourceInterface(OCResource *resource,
3582 OCResourceInterface *resourceInterface) {
3583 OCResourceInterface *pointer;
3585 if (!resource->rsrcInterface) {
3586 resource->rsrcInterface = resourceInterface;
3588 pointer = resource->rsrcInterface;
3589 while (pointer->next) {
3590 pointer = pointer->next;
3592 pointer->next = resourceInterface;
3594 resourceInterface->next = NULL;
3598 * Get a resource interface at the specified index within a resource.
3600 * @param handle - handle of resource
3601 * @param index - index of resource interface
3604 * resourceinterface - if found
3607 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3609 OCResource *resource;
3610 OCResourceInterface *pointer;
3613 // Find the specified resource
3614 resource = findResource((OCResource *) handle);
3619 // Make sure a resource has a resourceinterface
3620 if (!resource->rsrcInterface) {
3624 // Iterate through the list
3625 pointer = resource->rsrcInterface;
3627 while ((i < index) && pointer) {
3629 pointer = pointer->next;
3635 * Determine if a request/response must be sent in a block transfer because it is too large to be
3636 * sent in a single PDU. This function can be used for either a request or a response
3638 * @param request - NULL or pointer to request
3639 * @param response - NULL or pointer to response
3640 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
3641 * the length of the request/response
3644 * 0 - packet transfer NOT required (i.e. normal request/response)
3645 * 1 - packet transfer required (i.e. block transfer needed)
3647 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
3651 // Determine if we are checking a request or a response
3654 // If size is greater than 0, use it for the request size value, otherwise
3655 // assume request is null terminated and use strlen for size value
3656 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
3663 // If size is greater than 0, use it for the response size value, otherwise
3664 // assume response is null terminated and use strlen for size value
3665 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3674 * Retrieves a resource type based upon a query ontains only just one
3675 * resource attribute (and that has to be of type "rt").
3677 * @remark This API malloc's memory for the resource type. Do not malloc resourceType
3678 * before passing in.
3680 * @param query - The quert part of the URI
3681 * @param resourceType - The resource type to be populated; pass by reference.
3684 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
3685 * OC_STACK_OK - Success
3687 OCStackResult getResourceType(const char * query, unsigned char** resourceType)
3691 return OC_STACK_INVALID_PARAM;
3694 OCStackResult result = OC_STACK_ERROR;
3696 if(strncmp(query, "rt=", 3) == 0)
3698 *resourceType = (unsigned char *) OCMalloc(strlen(query)-3);
3701 result = OC_STACK_NO_MEMORY;
3704 strcpy((char *)*resourceType, ((const char *)&query[3]));
3705 result = OC_STACK_OK;
3711 OCStackResult getQueryFromUri(const char * uri, unsigned char** query, char ** newURI)
3715 return OC_STACK_INVALID_URI;
3717 if(!query || !newURI)
3719 return OC_STACK_INVALID_PARAM;
3721 char * leftToken = NULL;
3722 char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3727 strcpy(tempURI, uri);
3729 leftToken = strtok_r((char *)tempURI, "?", &strTokPtr);
3731 //TODO-CA: This could be simplified. Clean up required.
3732 while(leftToken != NULL)
3734 if(strncmp(leftToken, "rt=", 3) == 0 || strncmp(leftToken, "if=", 3) == 0)
3736 *query = (unsigned char *) OCMalloc(strlen(leftToken));
3742 strcpy((char *)*query, ((const char *)&leftToken[0]));
3745 leftToken = strtok_r(NULL, "?", &strTokPtr);
3753 return OC_STACK_NO_MEMORY;
3756 const ServerID OCGetServerInstanceID(void)
3758 static bool generated = false;
3759 static ServerID sid;
3766 sid = OCGetRandom();
3771 const char* OCGetServerInstanceIDString(void)
3773 // max printed length of a base 10
3774 // uint32 is 10 characters, so 11 includes null.
3775 // This will change as the representation gets switched
3777 static char buffer[11];
3778 int n = sprintf(buffer, "%u", OCGetServerInstanceID());