1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 //-----------------------------------------------------------------------------
24 //-----------------------------------------------------------------------------
25 #define _POSIX_C_SOURCE 200112L
29 #include "ocstackinternal.h"
30 #include "ocresourcehandler.h"
31 #include "occlientcb.h"
32 #include "ocobserve.h"
37 #include "ocserverrequest.h"
41 #include "cainterface.h"
42 #include <arpa/inet.h>
46 //-----------------------------------------------------------------------------
48 //-----------------------------------------------------------------------------
50 OC_STACK_UNINITIALIZED = 0, OC_STACK_INITIALIZED, OC_STACK_UNINIT_IN_PROGRESS
54 OC_PRESENCE_UNINITIALIZED = 0, OC_PRESENCE_INITIALIZED
58 //-----------------------------------------------------------------------------
60 //-----------------------------------------------------------------------------
61 static OCStackState stackState = OC_STACK_UNINITIALIZED;
63 OCResource *headResource = NULL;
65 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
66 static PresenceResource presenceResource;
67 uint8_t PresenceTimeOutSize = 0;
68 uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
72 OCDeviceEntityHandler defaultDeviceHandler;
73 OCStackResult getQueryFromUri(const char * uri, unsigned char** resourceType, char ** newURI);
75 //-----------------------------------------------------------------------------
77 //-----------------------------------------------------------------------------
78 #define TAG PCF("OCStack")
79 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
80 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
81 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
82 TAG, PCF(#arg " is NULL")); return (retVal); } }
83 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
86 //TODO: we should allow the server to define this
87 #define MAX_OBSERVE_AGE (0x2FFFFUL)
89 //-----------------------------------------------------------------------------
90 // Internal API function
91 //-----------------------------------------------------------------------------
93 // This internal function is called to update the stack with the status of
94 // observers and communication failures
96 OCStackResult OCStackFeedBack(CAToken_t * token, uint8_t status)
98 OCStackResult OCStackFeedBack(OCCoAPToken * token, uint8_t status)
101 OCStackResult result = OC_STACK_ERROR;
102 ResourceObserver * observer = NULL;
103 OCEntityHandlerRequest ehRequest = {0};
107 case OC_OBSERVER_NOT_INTERESTED:
108 OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
109 observer = GetObserverUsingToken (token);
112 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
113 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
114 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
115 if(result != OC_STACK_OK)
119 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
121 //observer is not observing anymore
122 result = DeleteObserverUsingToken (token);
123 if(result == OC_STACK_OK)
125 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
129 result = OC_STACK_OK;
130 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
133 case OC_OBSERVER_STILL_INTERESTED:
134 //observer is still interested
135 OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
136 notifications, reset the failedCount"));
137 observer = GetObserverUsingToken (token);
140 observer->forceHighQos = 0;
141 observer->failedCommCount = 0;
142 result = OC_STACK_OK;
146 result = OC_STACK_OBSERVER_NOT_FOUND;
149 case OC_OBSERVER_FAILED_COMM:
150 //observer is not reachable
151 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
152 observer = GetObserverUsingToken (token);
155 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
157 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
158 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
159 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
160 if(result != OC_STACK_OK)
162 return OC_STACK_ERROR;
164 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
165 //observer is unreachable
166 result = DeleteObserverUsingToken (token);
167 if(result == OC_STACK_OK)
169 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
173 result = OC_STACK_OK;
174 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
179 observer->failedCommCount++;
180 result = OC_STACK_CONTINUE;
182 observer->forceHighQos = 1;
183 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
187 OC_LOG(ERROR, TAG, PCF("Unknown status"));
188 result = OC_STACK_ERROR;
195 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
197 OCStackResult ret = OC_STACK_ERROR;
205 ret = OC_STACK_RESOURCE_CREATED;
208 ret = OC_STACK_RESOURCE_DELETED;
211 ret = OC_STACK_INVALID_QUERY;
214 ret = OC_STACK_INVALID_OPTION;
217 ret = OC_STACK_NO_RESOURCE;
225 OCStackResult OCToCAConnectivityType(OCConnectivityType ocConType, CAConnectivityType_t* caConType)
227 OCStackResult ret = OC_STACK_OK;
232 *caConType = CA_ETHERNET;
235 *caConType = CA_WIFI;
244 // Currently OC_ALL represents WIFI and ETHERNET
245 // Add other connectivity types as they are enabled in future
246 *caConType = (CA_WIFI|CA_ETHERNET);
249 ret = OC_STACK_INVALID_PARAM;
255 OCStackResult CAToOCConnectivityType(CAConnectivityType_t caConType, OCConnectivityType *ocConType)
257 OCStackResult ret = OC_STACK_OK;
262 *ocConType = OC_ETHERNET;
265 *ocConType = OC_WIFI;
274 ret = OC_STACK_INVALID_PARAM;
280 // update response.addr appropriately from endPoint.addressInfo
281 OCStackResult UpdateResponseAddr(OCClientResponse *response, const CARemoteEndpoint_t* endPoint)
283 struct sockaddr_in sa;
284 OCStackResult ret = OC_STACK_INVALID_PARAM;
288 OC_LOG(ERROR, TAG, PCF("CA Remote end-point is NULL!"));
291 inet_pton(AF_INET, endPoint->addressInfo.IP.ipAddress, &(sa.sin_addr));
292 sa.sin_port = htons(endPoint->addressInfo.IP.port);
293 static OCDevAddr address;
294 memcpy((void*)&address.addr, &(sa), sizeof(sa));
297 response->addr = &address;
298 ret = CAToOCConnectivityType(endPoint->connectivityType, &(response->connType));
302 OC_LOG(ERROR, TAG, PCF("OCClientResponse is NULL!"));
307 void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge, char** resType)
311 // The format of the payload is {"oc":[%u:%u:%s]}
312 // %u : sequence number,
314 // %s : Resource Type (Optional)
315 tok = strtok(payload, "[:]}");
316 payload[strlen(payload)] = ':';
317 tok = strtok(NULL, "[:]}");
318 payload[strlen((char *)payload)] = ':';
319 *seqNum = (uint32_t) atoi(tok);
320 tok = strtok(NULL, "[:]}");
321 *maxAge = (uint32_t) atoi(tok);
322 tok = strtok(NULL, "[:]}");
326 *resType = (char *)OCMalloc(strlen(tok));
331 payload[strlen((char *)payload)] = ':';
332 strcpy(*resType, tok);
333 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s", *resType);
335 payload[strlen((char *)payload)] = ']';
338 OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
339 const CAResponseInfo_t* responseInfo)
341 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
342 ClientCB * cbNode = NULL;
343 char *resourceTypeName = NULL;
344 OCClientResponse response;
345 OCStackResult result = OC_STACK_ERROR;
346 uint32_t lowerBound = 0;
347 uint32_t higherBound = 0;
350 char *fullUri = NULL;
351 char *ipAddress = NULL;
352 int presenceSubscribe = 0;
353 int multicastPresenceSubscribe = 0;
355 if (responseInfo->result != CA_SUCCESS)
357 OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
358 return OC_STACK_ERROR;
361 fullUri = (char *) OCMalloc(MAX_URI_LENGTH );
365 OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for fullUri"));
366 result = OC_STACK_NO_MEMORY;
370 ipAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
372 if(NULL == ipAddress)
374 OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for ipAddress"));
375 result = OC_STACK_NO_MEMORY;
379 strncpy(ipAddress, endPoint->addressInfo.IP.ipAddress,
380 strlen(endPoint->addressInfo.IP.ipAddress));
381 ipAddress[strlen(endPoint->addressInfo.IP.ipAddress)] = '\0';
383 snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", ipAddress, endPoint->addressInfo.IP.port,
386 cbNode = GetClientCB(NULL, NULL, (unsigned char *)fullUri);
390 presenceSubscribe = 1;
394 snprintf(fullUri, MAX_URI_LENGTH, "%s%s", OC_MULTICAST_IP, endPoint->resourceUri);
395 cbNode = GetClientCB(NULL, NULL, (unsigned char *)fullUri);
398 multicastPresenceSubscribe = 1;
402 if(!presenceSubscribe && !multicastPresenceSubscribe)
404 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
405 ------------ ignoring"));
409 // No payload to the application in case of presence
410 response.resJSONPayload = NULL;
411 response.result = OC_STACK_OK;
413 UpdateResponseAddr(&response, endPoint);
415 if(responseInfo->info.payload)
417 parsePresencePayload(responseInfo->info.payload,
418 &(response.sequenceNumber),
425 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
426 response.result = OC_STACK_PRESENCE_STOPPED;
429 OCFree(cbNode->presence->timeOut);
430 OCFree(cbNode->presence);
431 cbNode->presence = NULL;
434 else if(presenceSubscribe)
436 if(!cbNode->presence)
438 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
439 VERIFY_NON_NULL_V(cbNode->presence);
440 cbNode->presence->timeOut = NULL;
441 cbNode->presence->timeOut = (uint32_t *)
442 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
443 if(!(cbNode->presence->timeOut)){
444 OCFree(cbNode->presence);
445 result = OC_STACK_NO_MEMORY;
449 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %u", GetTime(0));
450 cbNode->presence->TTL = maxAge;
451 for(int index = 0; index < PresenceTimeOutSize; index++)
453 lowerBound = GetTime(((float)(PresenceTimeOut[index])
454 /(float)100)*(float)cbNode->presence->TTL);
455 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
456 /(float)100)*(float)cbNode->presence->TTL);
457 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
458 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
459 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
460 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
461 cbNode->presence->timeOut[index]);
463 cbNode->presence->TTLlevel = 0;
464 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
465 if(cbNode->sequenceNumber == response.sequenceNumber)
467 OC_LOG(INFO, TAG, PCF("===============No presence change"));
470 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
471 cbNode->sequenceNumber = response.sequenceNumber;
473 // Ensure that a filter is actually applied.
474 if(resourceTypeName && cbNode->filterResourceType)
476 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
484 // This is the multicast case
486 OCMulticastNode* mcNode = NULL;
487 mcNode = GetMCPresenceNode((const unsigned char *)fullUri);
491 if(mcNode->nonce == response.sequenceNumber)
493 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
496 mcNode->nonce = response.sequenceNumber;
500 uint32_t uriLen = strlen((char*)fullUri);
501 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
504 memcpy(uri, fullUri, (uriLen + 1));
509 PCF("===============No Memory for URI to store in the presence node"));
510 result = OC_STACK_NO_MEMORY;
513 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri, response.sequenceNumber);
514 if(result == OC_STACK_NO_MEMORY)
517 PCF("===============No Memory for Multicast Presence Node"));
518 result = OC_STACK_NO_MEMORY;
523 // Ensure that a filter is actually applied.
524 if(resourceTypeName && cbNode->filterResourceType)
526 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
533 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
535 if (cbResult == OC_STACK_DELETE_TRANSACTION)
537 FindAndDeleteClientCB(cbNode);
543 OCFree(resourceTypeName);
548 //This function will be called back by CA layer when a response is received
549 void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
551 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
555 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
559 if(NULL == responseInfo)
561 OC_LOG(ERROR, TAG, PCF("responseInfo is NULL"));
565 if(strcmp(endPoint->resourceUri, OC_PRESENCE_URI) == 0)
567 HandlePresenceResponse(endPoint, responseInfo);
571 ClientCB *cbNode = GetClientCB(&(responseInfo->info.token), NULL, NULL);
575 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
576 OCClientResponse response;
578 OCStackResult result = UpdateResponseAddr(&response, endPoint);
579 if(result != OC_STACK_OK)
581 OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint"));
585 response.result = CAToOCStackResult(responseInfo->result);
586 response.resJSONPayload = (unsigned char*)responseInfo->info.payload;
587 response.numRcvdVendorSpecificHeaderOptions = 0;
588 if(responseInfo->info.numOptions > 0)
591 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
592 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
594 memcpy (&(response.sequenceNumber),
595 &(responseInfo->info.options[0].optionData), sizeof(uint32_t));
596 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
601 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
604 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
606 OC_LOG(ERROR, TAG, PCF("#header options are more than MAX_HEADER_OPTIONS"));
610 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
612 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
613 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
616 if (cbNode->callBack(cbNode->context,
617 cbNode->handle, &response) == OC_STACK_DELETE_TRANSACTION)
619 FindAndDeleteClientCB(cbNode);
622 OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload);
623 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
626 //This function will be called back by CA layer when a request is received
627 void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
629 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
632 OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
638 OC_LOG(ERROR, TAG, PCF("requestInfo is NULL"));
642 if(myStackMode == OC_CLIENT)
644 //TODO: should the client be responding to requests?
648 OCServerProtocolRequest serverRequest;
650 memset (&serverRequest, 0, sizeof(OCServerProtocolRequest));
651 OC_LOG_V(INFO, TAG, PCF("***** Endpoint URI ***** : %s\n"), (char*)endPoint->resourceUri);
653 char * newUri = (char *)endPoint->resourceUri;
654 unsigned char * query = NULL;
655 getQueryFromUri(endPoint->resourceUri, &query, &newUri);
656 OC_LOG_V(INFO, TAG, PCF("**********URI without query ****: %s\n"), newUri);
657 OC_LOG_V(INFO, TAG, PCF("**********Query ****: %s\n"), query);
659 memcpy (&(serverRequest.resourceUrl), newUri, strlen(newUri));
663 memcpy (&(serverRequest.query), query, strlen((char*)query));
665 //copy request payload
666 if (requestInfo->info.payload)
668 serverRequest.reqTotalSize = strlen(requestInfo->info.payload) + 1;
669 memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
670 strlen(requestInfo->info.payload));
671 serverRequest.reqTotalSize = strlen((const char *)requestInfo->info.payload) + 1;
675 serverRequest.reqTotalSize = 1;
678 switch (requestInfo->method)
682 serverRequest.method = OC_REST_GET;
687 serverRequest.method = OC_REST_PUT;
692 serverRequest.method = OC_REST_POST;
697 serverRequest.method = OC_REST_DELETE;
702 OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
707 OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d", CA_MAX_TOKEN_LEN);
708 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token, CA_MAX_TOKEN_LEN);
710 serverRequest.requestToken = (CAToken_t)OCMalloc(CA_MAX_TOKEN_LEN+1);
712 if (!serverRequest.requestToken)
714 OC_LOG(FATAL, TAG, "Server Request Token is NULL");
717 memset(serverRequest.requestToken, 0, CA_MAX_TOKEN_LEN + 1);
718 memcpy(serverRequest.requestToken, requestInfo->info.token, CA_MAX_TOKEN_LEN);
720 if (requestInfo->info.type == CA_MSG_CONFIRM)
722 serverRequest.qos = OC_HIGH_QOS;
724 else if (requestInfo->info.type == CA_MSG_NONCONFIRM)
726 serverRequest.qos = OC_LOW_QOS;
728 else if (requestInfo->info.type == CA_MSG_ACKNOWLEDGE)
730 // TODO-CA: Need to handle this
732 else if (requestInfo->info.type == CA_MSG_RESET)
734 // TODO-CA: Need to handle this
736 // CA does not need the following 3 fields
737 serverRequest.coapID = 0;
738 serverRequest.delayedResNeeded = 0;
739 serverRequest.secured = endPoint->isSecured;
742 serverRequest.addressInfo = endPoint->addressInfo;
743 serverRequest.connectivityType = endPoint->connectivityType;
745 // copy vendor specific header options
746 // TODO-CA: CA is including non-vendor header options as well, like observe.
747 // Need to filter those out
748 GetObserveHeaderOption(&serverRequest.observationOption,
749 requestInfo->info.options, (uint8_t *)&(requestInfo->info.numOptions));
750 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
753 PCF("The request info numOptions is greater than MAX_HEADER_OPTIONS"));
756 serverRequest.numRcvdVendorSpecificHeaderOptions = requestInfo->info.numOptions;
757 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
759 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
760 sizeof(CAHeaderOption_t)*requestInfo->info.numOptions);
764 if(HandleStackRequests (&serverRequest) != OC_STACK_OK)
766 OC_LOG(ERROR, TAG, PCF("HandleStackRequests failed"));
768 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
773 //This function will be called back by occoap layer when a request is received
774 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
776 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
777 OCStackResult result = OC_STACK_ERROR;
778 ResourceHandling resHandling;
779 OCResource *resource;
782 OC_LOG(ERROR, TAG, PCF("protocolRequest is NULL"));
783 return OC_STACK_INVALID_PARAM;
786 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
789 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
791 result = AddServerRequest(&request, protocolRequest->coapID,
792 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
793 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
794 protocolRequest->observationOption, protocolRequest->qos,
795 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
796 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
797 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
798 protocolRequest->reqTotalSize,
799 &protocolRequest->addressInfo, protocolRequest->connectivityType);
801 result = AddServerRequest(&request, protocolRequest->coapID,
802 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
803 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
804 protocolRequest->observationOption, protocolRequest->qos,
805 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
806 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
807 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
808 protocolRequest->reqTotalSize);
810 if (OC_STACK_OK != result)
812 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
815 VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
817 if(!protocolRequest->reqMorePacket)
819 request->requestComplete = 1;
824 OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
827 if(request->requestComplete)
829 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
830 result = DetermineResourceHandling (request, &resHandling, &resource);
831 if (result == OC_STACK_OK)
833 result = ProcessRequest(resHandling, resource, request);
837 result = OC_STACK_ERROR;
842 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
843 result = OC_STACK_CONTINUE;
848 //This function will be called back by occoap layer when a response is received
849 OCStackResult HandleStackResponses(OCResponse * response)
851 OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)"));
852 OCStackResult result = OC_STACK_OK;
853 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
854 uint8_t isObserveNotification = 0;
855 ClientCB * cbNode = NULL;
858 OC_LOG(ERROR, TAG, PCF("response is NULL"));
859 return OC_STACK_INVALID_PARAM;
862 uint8_t isPresenceNotification = 0;
863 uint8_t isMulticastPresence = 0;
864 char * resourceTypeName = NULL;
865 uint32_t lowerBound = 0;
866 uint32_t higherBound = 0;
868 unsigned char * bufRes = response->bufRes;
869 #endif // WITH_PRESENCE
871 cbNode = response->cbNode;
874 cbNode = GetClientCB(response->rcvdToken, NULL, NULL);
877 if(response->clientResponse->sequenceNumber >= OC_OFFSET_SEQUENCE_NUMBER)
879 isObserveNotification = 1;
880 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
883 OC_LOG_V(DEBUG, TAG, "The sequenceNumber/NONCE of this response %u",
884 response->clientResponse->sequenceNumber);
885 OC_LOG_V(DEBUG, TAG, "The maxAge/TTL of this response %u", response->maxAge);
886 OC_LOG_V(DEBUG, TAG, "The response received is %s", bufRes);
889 if(!strcmp((char *)response->rcvdUri, (char *)OC_PRESENCE_URI)){
890 isPresenceNotification = 1;
893 result = OC_STACK_INVALID_PARAM;
896 tok = strtok((char *)bufRes, "[:]}");
897 bufRes[strlen((char *)bufRes)] = ':';
898 tok = strtok(NULL, "[:]}");
899 bufRes[strlen((char *)bufRes)] = ':';
900 response->clientResponse->sequenceNumber = (uint32_t )atoi(tok);
901 OC_LOG_V(DEBUG, TAG, "The received NONCE is %u", response->clientResponse->sequenceNumber);
902 tok = strtok(NULL, "[:]}");
903 response->maxAge = (uint32_t )atoi(tok);
904 OC_LOG_V(DEBUG, TAG, "The received TTL is %u", response->maxAge);
905 tok = strtok(NULL, "[:]}");
908 resourceTypeName = (char *)OCMalloc(strlen(tok));
909 if(!resourceTypeName)
913 bufRes[strlen((char *)bufRes)] = ':';
914 strcpy(resourceTypeName, tok);
915 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
918 bufRes[strlen((char *)bufRes)] = ']';
921 // Check if the application subcribed for presence
924 cbNode = GetClientCB(NULL, NULL, response->fullUri);
927 // Check if application subscribed for multicast presence
930 snprintf((char *)response->fullUri, MAX_URI_LENGTH, "%s%s",
931 OC_MULTICAST_IP, response->rcvdUri);
932 cbNode = GetClientCB(NULL, NULL, response->fullUri);
935 isMulticastPresence = 1;
936 isPresenceNotification = 0;
940 if(cbNode && isPresenceNotification)
942 OC_LOG(INFO, TAG, PCF("Received a presence notification"));
943 if(!cbNode->presence)
945 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
946 VERIFY_NON_NULL_V(cbNode->presence);
947 cbNode->presence->timeOut = NULL;
948 cbNode->presence->timeOut = (uint32_t *)
949 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
950 if(!(cbNode->presence->timeOut)){
951 OCFree(cbNode->presence);
952 result = OC_STACK_NO_MEMORY;
955 if(response->maxAge == 0)
957 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
958 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
961 OCFree(cbNode->presence->timeOut);
962 OCFree(cbNode->presence);
963 cbNode->presence = NULL;
968 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %d", GetTime(0));
969 cbNode->presence->TTL = response->maxAge;
970 for(int index = 0; index < PresenceTimeOutSize; index++)
972 lowerBound = GetTime(((float)(PresenceTimeOut[index])
973 /(float)100)*(float)cbNode->presence->TTL);
974 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
975 /(float)100)*(float)cbNode->presence->TTL);
976 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
977 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
978 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
979 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
980 cbNode->presence->timeOut[index]);
982 cbNode->presence->TTLlevel = 0;
983 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
984 if(cbNode->sequenceNumber == response->clientResponse->sequenceNumber)
986 OC_LOG(INFO, TAG, PCF("===============No presence change"));
989 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
990 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;;
993 // Ensure that a filter is actually applied.
994 if(resourceTypeName && cbNode->filterResourceType)
996 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1002 else if(cbNode && isMulticastPresence)
1004 // Check if the same nonce for a given host
1005 OCMulticastNode* mcNode = NULL;
1006 mcNode = GetMCPresenceNode(response->fullUri);
1008 if(response->maxAge == 0)
1010 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
1011 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
1012 if(cbNode->presence)
1014 OCFree(cbNode->presence->timeOut);
1015 OCFree(cbNode->presence);
1016 cbNode->presence = NULL;
1019 else if(mcNode != NULL)
1021 if(mcNode->nonce == response->clientResponse->sequenceNumber)
1023 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
1024 result = OC_STACK_NO_MEMORY;
1027 mcNode->nonce = response->clientResponse->sequenceNumber;
1031 uint32_t uriLen = strlen((char*)response->fullUri);
1032 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
1035 memcpy(uri, response->fullUri, (uriLen + 1));
1040 PCF("===============No Memory for URI to store in the presence node"));
1041 result = OC_STACK_NO_MEMORY;
1044 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri,
1045 response->clientResponse->sequenceNumber);
1046 if(result == OC_STACK_NO_MEMORY)
1049 PCF("===============No Memory for Multicast Presence Node"));
1050 result = OC_STACK_NO_MEMORY;
1055 // Ensure that a filter is actually applied.
1056 if(resourceTypeName && cbNode->filterResourceType)
1058 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1065 else if(!cbNode && isPresenceNotification)
1067 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
1068 ------------ ignoring"));
1070 #endif // WITH_PRESENCE
1074 if(isObserveNotification)
1076 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
1077 //TODO: check the standard for methods to detect wrap around condition
1078 if(cbNode->method == OC_REST_OBSERVE &&
1079 (response->clientResponse->sequenceNumber <= cbNode->sequenceNumber ||
1080 (response->clientResponse->sequenceNumber > cbNode->sequenceNumber &&
1081 response->clientResponse->sequenceNumber ==
1082 MAX_SEQUENCE_NUMBER)))
1084 OC_LOG_V(DEBUG, TAG, "Observe notification came out of order. \
1085 Ignoring Incoming:%d Against Current:%d.",
1086 response->clientResponse->sequenceNumber, cbNode->sequenceNumber);
1089 if(response->clientResponse->sequenceNumber > cbNode->sequenceNumber){
1090 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;
1094 response->clientResponse->resJSONPayload = bufRes;
1096 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response->clientResponse);
1098 if (cbResult == OC_STACK_DELETE_TRANSACTION ||
1099 response->clientResponse->result == OC_STACK_COMM_ERROR ||
1100 (response->clientResponse->result == OC_STACK_RESOURCE_DELETED &&
1101 !isPresenceNotification && !isMulticastPresence))
1103 FindAndDeleteClientCB(cbNode);
1108 result = OC_STACK_ERROR;
1112 #ifdef WITH_PRESENCE
1113 OCFree(resourceTypeName);
1118 int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
1121 unsigned char *itr, *coap;
1122 uint8_t dotCount = 0;
1126 /* search for scheme */
1128 if (!isdigit((unsigned char) *ipAddrStr))
1130 coap = (unsigned char *) OC_COAP_SCHEME;
1131 while (*coap && tolower(*itr) == *coap)
1139 while (*ipAddrStr) {
1140 if (isdigit((unsigned char) *ipAddrStr))
1142 ipAddr[index] *= 10;
1143 ipAddr[index] += *ipAddrStr - '0';
1145 else if ((unsigned char) *ipAddrStr == '.')
1157 if(*ipAddrStr == ':')
1161 if (isdigit((unsigned char) *ipAddrStr))
1164 *port += *ipAddrStr - '0';
1175 if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
1186 //-----------------------------------------------------------------------------
1187 // Private internal function prototypes
1188 //-----------------------------------------------------------------------------
1190 static OCDoHandle GenerateInvocationHandle();
1191 static OCStackResult initResources();
1192 static void insertResource(OCResource *resource);
1193 static OCResource *findResource(OCResource *resource);
1194 static void insertResourceType(OCResource *resource,
1195 OCResourceType *resourceType);
1196 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
1198 static void insertResourceInterface(OCResource *resource,
1199 OCResourceInterface *resourceInterface);
1200 static OCResourceInterface *findResourceInterfaceAtIndex(
1201 OCResourceHandle handle, uint8_t index);
1202 static void deleteResourceType(OCResourceType *resourceType);
1203 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
1204 static void deleteResourceElements(OCResource *resource);
1205 static int deleteResource(OCResource *resource);
1206 static void deleteAllResources();
1207 static void incrementSequenceNumber(OCResource * resPtr);
1208 static OCStackResult verifyUriQueryLength(const char * inputUri,
1210 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
1211 OCStackResult getResourceType(const char * query, unsigned char** resourceType);
1213 //-----------------------------------------------------------------------------
1215 //-----------------------------------------------------------------------------
1218 * Initialize the OC Stack. Must be called prior to starting the stack.
1221 * IP Address of host device
1223 * Port of host device
1225 * Host device is client, server, or client-server
1228 * OC_STACK_OK - no errors
1229 * OC_STACK_ERROR - stack init error
1231 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1233 OCStackResult result = OC_STACK_ERROR;
1234 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
1238 OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
1244 //It is ok to select network to CA_WIFI for now
1245 CAResult_t caResult = CASelectNetwork(CA_WIFI|CA_ETHERNET);
1246 if(caResult == CA_STATUS_OK)
1248 OC_LOG(INFO, TAG, PCF("CASelectNetwork to WIFI"));
1249 CARegisterHandler(HandleCARequests, HandleCAResponses);
1251 OC_LOG(INFO, TAG, PCF("CARegisterHandler..."));
1252 stackState = OC_STACK_INITIALIZED;
1253 result = OC_STACK_OK;
1257 caResult = CAStartDiscoveryServer();
1258 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
1261 caResult = CAStartListeningServer();
1262 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
1264 case OC_CLIENT_SERVER:
1265 caResult = CAStartListeningServer();
1266 if(caResult == CA_STATUS_OK)
1268 caResult = CAStartDiscoveryServer();
1270 OC_LOG(INFO, TAG, PCF("Client-server mode"));
1273 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1274 return OC_STACK_ERROR;
1279 if (caResult == CA_STATUS_OK)
1281 result = OC_STACK_OK;
1285 result = OC_STACK_ERROR;
1292 OC_LOG(INFO, TAG, PCF("Client mode"));
1295 OC_LOG(INFO, TAG, PCF("Server mode"));
1297 case OC_CLIENT_SERVER:
1298 OC_LOG(INFO, TAG, PCF("Client-server mode"));
1301 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1302 return OC_STACK_ERROR;
1306 // Make call to OCCoAP layer
1307 result = OCInitCoAP(ipAddr, (uint16_t) port, myStackMode);
1311 defaultDeviceHandler = NULL;
1313 #if defined(CA_INT) && defined(__WITH_DTLS__)
1314 caResult = CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials);
1315 result = (caResult == CA_STATUS_OK) ? OC_STACK_OK : OC_STACK_ERROR;
1316 #endif //(CA_INT) && (__WITH_DTLS__)
1317 #ifdef WITH_PRESENCE
1318 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
1319 #endif // WITH_PRESENCE
1321 if (result == OC_STACK_OK)
1323 stackState = OC_STACK_INITIALIZED;
1325 // Initialize resource
1326 if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
1328 result = initResources();
1330 if(result != OC_STACK_OK)
1332 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1338 * Stop the OC stack. Use for a controlled shutdown.
1340 * OC_STACK_OK - no errors
1341 * OC_STACK_ERROR - stack not initialized
1343 OCStackResult OCStop()
1345 OCStackResult result = OC_STACK_ERROR;
1347 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1349 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1351 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1354 else if (stackState != OC_STACK_INITIALIZED)
1356 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1357 return OC_STACK_ERROR;
1360 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1362 #ifdef WITH_PRESENCE
1363 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1364 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1365 presenceResource.presenceTTL = 0;
1366 #endif // WITH_PRESENCE
1368 // Free memory dynamically allocated for resources
1369 deleteAllResources();
1373 //CATerminate does not return any error code. It is OK to assign result to OC_STACK_OK.
1374 result = OC_STACK_OK;
1376 result = OCStopCoAP();
1379 if (result == OC_STACK_OK)
1381 // Remove all observers
1382 DeleteObserverList();
1383 // Remove all the client callbacks
1384 DeleteClientCBList();
1385 stackState = OC_STACK_UNINITIALIZED;
1386 result = OC_STACK_OK;
1388 stackState = OC_STACK_INITIALIZED;
1389 result = OC_STACK_ERROR;
1392 // Deinit security blob
1393 DeinitOCSecurityInfo();
1395 if (result != OC_STACK_OK) {
1396 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
1403 * Map OCQualityOfService to CAMessageType
1405 * @param OCQualityOfService - Input qos.
1407 * Returns CA message type for a given qos.
1409 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
1414 return CA_MSG_CONFIRM;
1419 return CA_MSG_NONCONFIRM;
1424 * Verify the lengths of the URI and the query separately
1426 * @param inputUri - Input URI and query.
1427 * @param uriLen - The length of the initial URI with query.
1429 * Note: The '?' that appears after the URI is not considered as
1430 * a part of the query.
1432 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1436 query = strchr (inputUri, '?');
1440 if((query - inputUri) > MAX_URI_LENGTH)
1442 return OC_STACK_INVALID_URI;
1445 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1447 return OC_STACK_INVALID_QUERY;
1450 else if(uriLen > MAX_URI_LENGTH)
1452 return OC_STACK_INVALID_URI;
1458 * Discover or Perform requests on a specified resource (specified by that Resource's respective URI).
1460 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of calling this API.
1461 * @param method - @ref OCMethod to perform on the resource
1462 * @param requiredUri - URI of the resource to interact with
1463 * @param referenceUri - URI of the reference resource
1464 * @param request - JSON encoded request
1465 * @param qos - quality of service
1466 * @param cbData - struct that contains asynchronous callback function that is invoked
1467 * by the stack when discovery or resource interaction is complete
1468 * @param options - The address of an array containing the vendor specific header
1469 * header options to be sent with the request
1470 * @param numOptions - Number of vendor specific header options to be included
1473 * OC_STACK_OK - no errors
1474 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
1475 * OC_STACK_INVALID_METHOD - invalid resource method
1476 * OC_STACK_INVALID_URI - invalid required or reference URI
1478 * Note: IN case of CA, when using multicast, the required URI should not contain IP address.
1479 * Instead, it just contains the URI to the resource such as "/oc/core".
1482 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1483 const char *referenceUri, const char *request, OCConnectivityType conType,
1484 OCQualityOfService qos, OCCallbackData *cbData,
1485 OCHeaderOption * options, uint8_t numOptions)
1487 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1488 const char *referenceUri, const char *request,
1489 OCQualityOfService qos, OCCallbackData *cbData,
1490 OCHeaderOption * options, uint8_t numOptions)
1493 OCStackResult result = OC_STACK_ERROR;
1494 ClientCB *clientCB = NULL;
1495 unsigned char * requestUri = NULL;
1496 unsigned char * resourceType = NULL;
1497 unsigned char * query = NULL;
1498 char * newUri = (char *)requiredUri;
1499 (void) referenceUri;
1501 CARemoteEndpoint_t* endpoint = NULL;
1502 CAResult_t caResult;
1503 CAToken_t token = NULL;
1504 CAInfo_t requestData;
1505 CARequestInfo_t requestInfo;
1506 CAGroupEndpoint_t grpEnd;
1508 // To track if memory is allocated for additional header options
1509 uint8_t hdrOptionMemAlloc = 0;
1514 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1516 // Validate input parameters
1517 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1518 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1520 TODO ("Need to form the final query by concatenating require and reference URI's");
1521 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
1523 uint16_t uriLen = strlen(requiredUri);
1525 // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS
1531 case OC_REST_DELETE:
1532 case OC_REST_OBSERVE:
1533 case OC_REST_OBSERVE_ALL:
1534 case OC_REST_CANCEL_OBSERVE:
1536 #ifdef WITH_PRESENCE
1537 case OC_REST_PRESENCE:
1541 result = OC_STACK_INVALID_METHOD;
1545 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
1550 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
1552 result = OC_STACK_INVALID_PARAM;
1556 #ifdef WITH_PRESENCE
1557 if(method == OC_REST_PRESENCE)
1559 result = getQueryFromUri(requiredUri, &query, &newUri);
1562 result = getResourceType((char *) query, &resourceType);
1565 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1569 OC_LOG(DEBUG, TAG, PCF("Resource type is NULL."));
1574 OC_LOG(DEBUG, TAG, PCF("Query string is NULL."));
1576 if(result != OC_STACK_OK)
1581 #endif // WITH_PRESENCE
1583 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
1586 memcpy(requestUri, newUri, (uriLen + 1));
1590 result = OC_STACK_NO_MEMORY;
1594 *handle = GenerateInvocationHandle();
1597 result = OC_STACK_NO_MEMORY;
1602 memset(&requestData, 0, sizeof(CAInfo_t));
1603 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1604 memset(&grpEnd, 0, sizeof(CAGroupEndpoint_t));
1608 case OC_REST_OBSERVE:
1609 case OC_REST_OBSERVE_ALL:
1610 case OC_REST_CANCEL_OBSERVE:
1612 requestInfo.method = CA_GET;
1617 requestInfo.method = CA_PUT;
1622 requestInfo.method = CA_POST;
1625 case OC_REST_DELETE:
1627 requestInfo.method = CA_DELETE;
1630 #ifdef WITH_PRESENCE
1631 case OC_REST_PRESENCE:
1633 // Replacing method type with GET because "presence"
1634 // is a stack layer only implementation.
1635 requestInfo.method = CA_GET;
1640 result = OC_STACK_INVALID_METHOD;
1644 //High QoS is not supported
1645 if(qos == OC_HIGH_QOS)
1647 result = OC_STACK_INVALID_PARAM;
1653 caResult = CAGenerateToken(&token);
1654 if (caResult != CA_STATUS_OK)
1656 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1657 CADestroyToken(token);
1661 requestData.type = qualityOfServiceToMessageType(qos);
1662 requestData.token = token;
1663 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1665 result = CreateObserveHeaderOption (&(requestData.options), options,
1666 numOptions, OC_OBSERVE_REGISTER);
1667 if (result != OC_STACK_OK)
1671 hdrOptionMemAlloc = 1;
1672 requestData.numOptions = numOptions + 1;
1676 requestData.options = (CAHeaderOption_t*)options;
1677 requestData.numOptions = numOptions;
1679 requestData.payload = (char *)request;
1681 requestInfo.info = requestData;
1683 CAConnectivityType_t caConType;
1685 result = OCToCAConnectivityType(conType, &caConType);
1686 if (result != OC_STACK_OK)
1688 OC_LOG(ERROR, TAG, PCF("Invalid Connectivity Type"));
1693 if(conType == OC_ALL)
1695 grpEnd.connectivityType = caConType;
1697 grpEnd.resourceUri = (CAURI_t) OCMalloc(uriLen + 1);
1698 strncpy(grpEnd.resourceUri, requiredUri, (uriLen + 1));
1700 caResult = CASendRequestToAll(&grpEnd, &requestInfo);
1704 caResult = CACreateRemoteEndpoint(newUri, caConType, &endpoint);
1706 if (caResult != CA_STATUS_OK)
1708 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1712 caResult = CASendRequest(endpoint, &requestInfo);
1715 if (caResult != CA_STATUS_OK)
1717 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1721 if((result = AddClientCB(&clientCB, cbData, &token, handle, method,
1722 requestUri, resourceType)) != OC_STACK_OK)
1724 result = OC_STACK_NO_MEMORY;
1730 // Generate token which will be used by OCStack to match responses received
1732 OCGenerateCoAPToken(&token);
1734 if((result = AddClientCB(&clientCB, cbData, &token, handle, method, requestUri, resourceType))
1737 result = OC_STACK_NO_MEMORY;
1741 // Make call to OCCoAP layer
1742 result = OCDoCoAPResource(method, qos, &token, newUri, request, options, numOptions);
1746 if(newUri != requiredUri)
1750 if (result != OC_STACK_OK)
1752 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1753 FindAndDeleteClientCB(clientCB);
1756 CADestroyRemoteEndpoint(endpoint);
1757 OCFree(grpEnd.resourceUri);
1758 if (hdrOptionMemAlloc)
1760 OCFree(requestData.options);
1767 * Cancel a request associated with a specific @ref OCDoResource invocation.
1769 * @param handle - Used to identify a specific OCDoResource invocation.
1770 * @param qos - used to specify Quality of Service (read below for more info)
1771 * @param options- used to specify vendor specific header options when sending
1772 * explicit observe cancellation
1773 * @param numOptions- Number of header options to be included
1776 * OC_STACK_OK - No errors; Success
1777 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1779 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1783 * This ftn is implemented one of two ways in the case of observation:
1785 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1786 * Remove the callback associated on client side.
1787 * When the next notification comes in from server,
1788 * reply with RESET message to server.
1789 * Keep in mind that the server will react to RESET only
1790 * if the last notification was sent ans CON
1792 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1793 * and it is associated with an observe request
1794 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1795 * Send CON Observe request to server with
1796 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1797 * Remove the callback associated on client side.
1799 OCStackResult ret = OC_STACK_OK;
1801 CARemoteEndpoint_t* endpoint = NULL;
1802 CAResult_t caResult;
1803 CAInfo_t requestData;
1804 CARequestInfo_t requestInfo;
1805 // Track if memory is allocated for additional header options
1806 uint8_t hdrOptionMemAlloc = 0;
1810 return OC_STACK_INVALID_PARAM;
1813 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1815 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1818 switch (clientCB->method)
1820 case OC_REST_OBSERVE:
1821 case OC_REST_OBSERVE_ALL:
1823 //TODO-CA : Why CA_WIFI alone?
1824 caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri, CA_WIFI,
1826 if (caResult != CA_STATUS_OK)
1828 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1829 return OC_STACK_ERROR;
1832 memset(&requestData, 0, sizeof(CAInfo_t));
1833 requestData.type = qualityOfServiceToMessageType(qos);
1834 requestData.token = clientCB->token;
1835 if (CreateObserveHeaderOption (&(requestData.options),
1836 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
1838 return OC_STACK_ERROR;
1840 hdrOptionMemAlloc = 1;
1841 requestData.numOptions = numOptions + 1;
1842 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1843 requestInfo.method = CA_GET;
1844 requestInfo.info = requestData;
1846 caResult = CASendRequest(endpoint, &requestInfo);
1847 if (caResult != CA_STATUS_OK)
1849 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1851 if(caResult == CA_STATUS_OK)
1856 if(qos == OC_HIGH_QOS)
1858 ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
1859 &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
1864 FindAndDeleteClientCB(clientCB);
1868 #ifdef WITH_PRESENCE
1869 case OC_REST_PRESENCE:
1870 FindAndDeleteClientCB(clientCB);
1874 return OC_STACK_INVALID_METHOD;
1878 CADestroyRemoteEndpoint(endpoint);
1879 if (hdrOptionMemAlloc)
1881 OCFree(requestData.options);
1888 #ifdef WITH_PRESENCE
1890 OCStackResult OCProcessPresence()
1892 OCStackResult result = OC_STACK_OK;
1893 uint8_t ipAddr[4] = { 0 };
1896 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1897 ClientCB* cbNode = NULL;
1899 OCClientResponse clientResponse;
1900 OCResponse * response = NULL;
1901 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1903 LL_FOREACH(cbList, cbNode) {
1904 if(OC_REST_PRESENCE == cbNode->method)
1906 if(cbNode->presence)
1908 uint32_t now = GetTime(0);
1909 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d",
1910 cbNode->presence->TTLlevel);
1911 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1914 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1919 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1920 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1921 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1924 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1926 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1927 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1929 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1931 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
1932 (OCDevAddr *) &dst, 0, NULL);
1933 if(result != OC_STACK_OK)
1937 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1938 &cbNode->token, &clientResponse, NULL);
1939 if(result != OC_STACK_OK)
1944 // Increment the TTLLevel (going to a next state), so we don't keep
1945 // sending presence notification to client.
1946 cbNode->presence->TTLlevel++;
1947 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1948 cbNode->presence->TTLlevel);
1952 result = OC_STACK_INVALID_IP;
1956 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
1957 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1959 FindAndDeleteClientCB(cbNode);
1963 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1965 CAResult_t caResult;
1966 CARemoteEndpoint_t* endpoint = NULL;
1967 CAInfo_t requestData;
1968 CARequestInfo_t requestInfo;
1970 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
1972 //TODO-CA : Why CA_WIFI alone?
1973 caResult = CACreateRemoteEndpoint((char *)cbNode->requestUri, CA_WIFI,
1976 if (caResult != CA_STATUS_OK)
1978 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1982 memset(&requestData, 0, sizeof(CAInfo_t));
1983 requestData.type = CA_MSG_NONCONFIRM;
1984 requestData.token = cbNode->token;
1986 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1987 requestInfo.method = CA_GET;
1988 requestInfo.info = requestData;
1990 caResult = CASendRequest(endpoint, &requestInfo);
1992 if (caResult != CA_STATUS_OK)
1994 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1998 cbNode->presence->TTLlevel++;
1999 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
2000 cbNode->presence->TTLlevel);
2006 if (result != OC_STACK_OK)
2008 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
2013 OCStackResult OCProcessPresence()
2015 OCStackResult result = OC_STACK_OK;
2016 uint8_t ipAddr[4] = { 0 };
2019 ClientCB* cbNode = NULL;
2021 OCClientResponse clientResponse;
2022 OCResponse * response = NULL;
2024 LL_FOREACH(cbList, cbNode) {
2025 if(OC_REST_PRESENCE == cbNode->method)
2027 if(cbNode->presence)
2029 uint32_t now = GetTime(0);
2030 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
2031 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
2034 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
2039 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
2040 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
2041 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2044 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2046 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
2047 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
2049 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
2051 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
2052 (OCDevAddr *) &dst, 0, NULL);
2053 if(result != OC_STACK_OK)
2057 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
2058 &cbNode->token, &clientResponse, NULL);
2059 if(result != OC_STACK_OK)
2064 // Increment the TTLLevel (going to a next state), so we don't keep
2065 // sending presence notification to client.
2066 cbNode->presence->TTLlevel++;
2067 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
2068 cbNode->presence->TTLlevel);
2072 result = OC_STACK_INVALID_IP;
2075 HandleStackResponses(response);
2077 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2079 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
2082 CAToken_t token = NULL;
2083 CAResult_t caResult = CAGenerateToken(&token);
2084 if (caResult != CA_STATUS_OK)
2086 CADestroyToken(token);
2091 OCGenerateCoAPToken(&token);
2093 result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
2094 &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
2096 if(result != OC_STACK_OK)
2101 cbNode->presence->TTLlevel++;
2102 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
2108 if (result != OC_STACK_OK)
2110 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
2115 #endif // WITH_PRESENCE
2118 * Called in main loop of OC client or server. Allows low-level processing of
2122 * OC_STACK_OK - no errors
2123 * OC_STACK_ERROR - stack process error
2125 OCStackResult OCProcess()
2127 #ifdef WITH_PRESENCE
2128 OCProcessPresence();
2131 CAHandleRequestResponse();
2139 #ifdef WITH_PRESENCE
2141 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
2142 * presence notifications to clients via multicast. Once this API has been called with a success,
2143 * clients may query for this server's presence and this server's stack will respond via multicast.
2145 * Server can call this function when it comes online for the first time, or when it comes back
2146 * online from offline mode, or when it re enters network.
2148 * @param ttl - Time To Live in seconds
2149 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
2152 * OC_STACK_OK - No errors; Success
2154 OCStackResult OCStartPresence(const uint32_t ttl)
2156 OCChangeResourceProperty(
2157 &(((OCResource *)presenceResource.handle)->resourceProperties),
2162 presenceResource.presenceTTL = ttl;
2165 if(OC_PRESENCE_UNINITIALIZED == presenceState)
2167 OCDevAddr multiCastAddr;
2168 presenceState = OC_PRESENCE_INITIALIZED;
2170 OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
2173 CAAddress_t addressInfo;
2174 strncpy(addressInfo.IP.ipAddress, "224.0.1.187", CA_IPADDR_SIZE);
2175 addressInfo.IP.port = 5683;
2177 //TODO make sure there is no memory leak here since another copy
2178 //of token is being created inside AddObserver
2179 CAToken_t caToken = NULL;
2180 CAResult_t caResult = CAGenerateToken(&caToken);
2181 if (caResult != CA_STATUS_OK)
2183 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2184 CADestroyToken(caToken);
2185 return OC_STACK_ERROR;
2188 AddObserver(OC_PRESENCE_URI, NULL, 0, &caToken,
2189 &multiCastAddr, (OCResource *)presenceResource.handle, OC_LOW_QOS,
2190 &addressInfo, CA_WIFI);
2193 OCGenerateCoAPToken(&token);
2194 //add the presence observer
2195 AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
2196 (OCResource *)presenceResource.handle, OC_LOW_QOS);
2200 // Each time OCStartPresence is called
2201 // a different random 32-bit integer number is used
2202 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2204 return SendPresenceNotification(NULL);
2208 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
2209 * presence notifications to clients via multicast. Once this API has been called with a success,
2210 * this server's stack will not respond to clients querying for this server's presence.
2212 * Server can call this function when it is terminating, going offline, or when going
2213 * away from network.
2216 * OC_STACK_OK - No errors; Success
2218 OCStackResult OCStopPresence()
2220 OCStackResult result = OC_STACK_ERROR;
2221 //make resource inactive
2222 result = OCChangeResourceProperty(
2223 &(((OCResource *) presenceResource.handle)->resourceProperties),
2225 result = SendPresenceNotification(NULL);
2232 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
2234 defaultDeviceHandler = entityHandler;
2239 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2241 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
2243 if(myStackMode == OC_CLIENT)
2245 return OC_STACK_ERROR;
2248 return SaveDeviceInfo(deviceInfo);
2254 * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource
2255 * @param resourceTypeName - name of resource type. Example: "core.led"
2256 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
2257 * @param uri - URI of the resource. Example: "/a/led"
2258 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2259 * NULL for default entity handler
2260 * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE
2263 * OC_STACK_OK - no errors
2264 * OC_STACK_ERROR - stack process error
2266 OCStackResult OCCreateResource(OCResourceHandle *handle,
2267 const char *resourceTypeName,
2268 const char *resourceInterfaceName,
2269 const char *uri, OCEntityHandler entityHandler,
2270 uint8_t resourceProperties) {
2272 OCResource *pointer = NULL;
2275 OCStackResult result = OC_STACK_ERROR;
2277 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
2279 if(myStackMode == OC_CLIENT)
2283 // Validate parameters
2284 if(!uri || (strlen(uri) == 0))
2286 OC_LOG(ERROR, TAG, PCF("URI is invalid"));
2287 return OC_STACK_INVALID_URI;
2289 // Is it presented during resource discovery?
2290 if (!handle || !resourceTypeName) {
2291 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
2292 return OC_STACK_INVALID_PARAM;
2295 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
2296 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2299 // Make sure resourceProperties bitmask has allowed properties specified
2300 if (resourceProperties
2301 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
2302 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2303 return OC_STACK_INVALID_PARAM;
2306 // If the headResource is NULL, then no resources have been created...
2307 pointer = headResource;
2309 // At least one resources is in the resource list, so we need to search for
2310 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2312 if (strcmp(uri, pointer->uri) == 0) {
2313 OC_LOG(ERROR, TAG, PCF("URI already in use"));
2314 return OC_STACK_INVALID_PARAM;
2316 pointer = pointer->next;
2319 // Create the pointer and insert it into the resource list
2320 pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
2324 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2326 insertResource(pointer);
2329 size = strlen(uri) + 1;
2330 str = (char *) OCMalloc(size);
2334 strncpy(str, uri, size);
2337 // Set properties. Set OC_ACTIVE
2338 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2341 // Add the resourcetype to the resource
2342 result = BindResourceTypeToResource(pointer, resourceTypeName);
2343 if (result != OC_STACK_OK) {
2344 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
2348 // Add the resourceinterface to the resource
2349 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2350 if (result != OC_STACK_OK) {
2351 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
2355 // If an entity handler has been passed, attach it to the newly created
2356 // resource. Otherwise, set the default entity handler.
2359 pointer->entityHandler = entityHandler;
2363 pointer->entityHandler = defaultResourceEHandler;
2367 result = OC_STACK_OK;
2369 #ifdef WITH_PRESENCE
2370 if(presenceResource.handle)
2372 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2373 SendPresenceNotification(pointer->rsrcType);
2377 if (result != OC_STACK_OK)
2379 // Deep delete of resource and other dynamic elements that it contains
2380 deleteResource(pointer);
2389 * Create a resource. with host ip address for remote resource
2391 * @param handle - pointer to handle to newly created resource. Set by ocstack.
2392 * Used to refer to resource
2393 * @param resourceTypeName - name of resource type. Example: "core.led"
2394 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
2395 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
2396 * @param uri - URI of the resource. Example: "/a/led"
2397 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2398 * NULL for default entity handler
2399 * @param resourceProperties - properties supported by resource.
2400 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
2403 * OC_STACK_OK - no errors
2404 * OC_STACK_ERROR - stack process error
2407 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
2408 const char *resourceTypeName,
2409 const char *resourceInterfaceName,
2412 OCEntityHandler entityHandler,
2413 uint8_t resourceProperties)
2417 OCStackResult result = OC_STACK_ERROR;
2419 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
2420 uri, entityHandler, resourceProperties);
2422 if (result != OC_STACK_ERROR)
2425 size = strlen(host) + 1;
2426 str = (char *) OCMalloc(size);
2429 return OC_STACK_ERROR;
2431 strncpy(str, host, size);
2432 ((OCResource *) *handle)->host = str;
2439 * Add a resource to a collection resource.
2441 * @param collectionHandle - handle to the collection resource
2442 * @param resourceHandle - handle to resource to be added to the collection resource
2445 * OC_STACK_OK - no errors
2446 * OC_STACK_ERROR - stack process error
2447 * OC_STACK_INVALID_PARAM - invalid collectionhandle
2449 OCStackResult OCBindResource(
2450 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2451 OCResource *resource;
2454 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2456 // Validate parameters
2457 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2458 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2459 // Container cannot contain itself
2460 if (collectionHandle == resourceHandle) {
2461 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2462 return OC_STACK_INVALID_PARAM;
2465 // Use the handle to find the resource in the resource linked list
2466 resource = findResource((OCResource *) collectionHandle);
2468 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2469 return OC_STACK_INVALID_PARAM;
2472 // Look for an open slot to add add the child resource.
2473 // If found, add it and return success
2474 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2475 if (!resource->rsrcResources[i]) {
2476 resource->rsrcResources[i] = (OCResource *) resourceHandle;
2477 OC_LOG(INFO, TAG, PCF("resource bound"));
2482 #ifdef WITH_PRESENCE
2483 if(presenceResource.handle)
2485 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2486 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2490 // Unable to add resourceHandle, so return error
2491 return OC_STACK_ERROR;
2495 * Remove a resource from a collection resource.
2497 * @param collectionHandle - handle to the collection resource
2498 * @param resourceHandle - handle to resource to be added to the collection resource
2501 * OC_STACK_OK - no errors
2502 * OC_STACK_ERROR - stack process error
2503 * OC_STACK_INVALID_PARAM - invalid collectionHandle
2505 OCStackResult OCUnBindResource(
2506 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2507 OCResource *resource;
2510 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2512 // Validate parameters
2513 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2514 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2515 // Container cannot contain itself
2516 if (collectionHandle == resourceHandle) {
2517 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2518 return OC_STACK_INVALID_PARAM;
2521 // Use the handle to find the resource in the resource linked list
2522 resource = findResource((OCResource *) collectionHandle);
2524 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2525 return OC_STACK_INVALID_PARAM;
2528 // Look for an open slot to add add the child resource.
2529 // If found, add it and return success
2530 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2531 if (resourceHandle == resource->rsrcResources[i]) {
2532 resource->rsrcResources[i] = (OCResource *) NULL;
2533 OC_LOG(INFO, TAG, PCF("resource unbound"));
2538 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2540 #ifdef WITH_PRESENCE
2541 if(presenceResource.handle)
2543 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2544 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2548 // Unable to add resourceHandle, so return error
2549 return OC_STACK_ERROR;
2552 OCStackResult BindResourceTypeToResource(OCResource* resource,
2553 const char *resourceTypeName)
2555 OCResourceType *pointer = NULL;
2558 OCStackResult result = OC_STACK_ERROR;
2560 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
2562 // Validate parameters
2563 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2564 // TODO: Does resource attribute resentation really have to be maintained in stack?
2565 // Is it presented during resource discovery?
2567 TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
2569 // Create the resourcetype and insert it into the resource list
2570 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
2575 // Set the resourceTypeName
2576 size = strlen(resourceTypeName) + 1;
2577 str = (char *) OCMalloc(size);
2581 strncpy(str, resourceTypeName, size);
2582 pointer->resourcetypename = str;
2584 insertResourceType(resource, pointer);
2585 result = OC_STACK_OK;
2587 exit: if (result != OC_STACK_OK) {
2595 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2596 const char *resourceInterfaceName)
2598 OCResourceInterface *pointer = NULL;
2601 OCStackResult result = OC_STACK_ERROR;
2603 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
2605 // Validate parameters
2606 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2608 TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
2610 // Create the resourceinterface and insert it into the resource list
2611 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
2616 // Set the resourceinterface name
2617 size = strlen(resourceInterfaceName) + 1;
2618 str = (char *) OCMalloc(size);
2622 strncpy(str, resourceInterfaceName, size);
2623 pointer->name = str;
2625 // Bind the resourceinterface to the resource
2626 insertResourceInterface(resource, pointer);
2628 result = OC_STACK_OK;
2630 exit: if (result != OC_STACK_OK) {
2639 * Bind a resourcetype to a resource.
2641 * @param handle - handle to the resource
2642 * @param resourceTypeName - name of resource type. Example: "core.led"
2645 * OC_STACK_OK - no errors
2646 * OC_STACK_ERROR - stack process error
2648 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2649 const char *resourceTypeName) {
2651 OCStackResult result = OC_STACK_ERROR;
2652 OCResource *resource;
2654 // Make sure resource exists
2655 resource = findResource((OCResource *) handle);
2657 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2658 return OC_STACK_ERROR;
2661 // call internal function
2662 result = BindResourceTypeToResource(resource, resourceTypeName);
2664 #ifdef WITH_PRESENCE
2665 if(presenceResource.handle)
2667 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2668 SendPresenceNotification(resource->rsrcType);
2676 * Bind a resourceinterface to a resource.
2678 * @param handle - handle to the resource
2679 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
2682 * OC_STACK_OK - no errors
2683 * OC_STACK_ERROR - stack process error
2686 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2687 const char *resourceInterfaceName) {
2689 OCStackResult result = OC_STACK_ERROR;
2690 OCResource *resource;
2692 // Make sure resource exists
2693 resource = findResource((OCResource *) handle);
2695 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2696 return OC_STACK_ERROR;
2699 // call internal function
2700 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2702 #ifdef WITH_PRESENCE
2703 if(presenceResource.handle)
2705 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2706 SendPresenceNotification(resource->rsrcType);
2714 * Get the number of resources that have been created in the stack.
2716 * @param numResources - pointer to count variable
2719 * OC_STACK_OK - no errors
2720 * OC_STACK_ERROR - stack process error
2723 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
2724 OCResource *pointer = headResource;
2726 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2727 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2730 *numResources = *numResources + 1;
2731 pointer = pointer->next;
2737 * Get a resource handle by index.
2739 * @param index - index of resource, 0 to Count - 1
2742 * Resource handle - if found
2743 * NULL - if not found
2745 OCResourceHandle OCGetResourceHandle(uint8_t index) {
2746 OCResource *pointer = headResource;
2749 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2751 // Iterate through the list
2752 while ((i < index) && pointer) {
2754 pointer = pointer->next;
2756 return (OCResourceHandle) pointer;
2760 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
2763 * @param handle - handle of resource to be deleted
2766 * OC_STACK_OK - no errors
2767 * OC_STACK_ERROR - stack process error
2768 * OC_STACK_NO_RESOURCE - resource not found
2769 * OC_STACK_INVALID_PARAM - invalid param
2771 OCStackResult OCDeleteResource(OCResourceHandle handle) {
2772 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2775 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2776 return OC_STACK_INVALID_PARAM;
2779 OCResource *resource = findResource((OCResource *) handle);
2780 if (resource == NULL) {
2781 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2782 return OC_STACK_NO_RESOURCE;
2785 if (deleteResource((OCResource *) handle) == 0) {
2786 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2787 return OC_STACK_ERROR;
2794 * Get the URI of the resource specified by handle.
2796 * @param handle - handle of resource
2798 * URI string - if resource found
2799 * NULL - resource not found
2801 const char *OCGetResourceUri(OCResourceHandle handle) {
2802 OCResource *resource;
2803 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2805 resource = findResource((OCResource *) handle);
2807 return resource->uri;
2809 return (const char *) NULL;
2813 * Get the properties of the resource specified by handle.
2814 * NOTE: that after a resource is created, the OC_ACTIVE property is set
2815 * for the resource by the stack.
2817 * @param handle - handle of resource
2819 * property bitmap - if resource found
2820 * NULL - resource not found
2822 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
2823 OCResource *resource;
2824 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2826 resource = findResource((OCResource *) handle);
2828 return resource->resourceProperties;
2834 * Get the number of resource types of the resource.
2836 * @param handle - handle of resource
2837 * @param numResourceTypes - pointer to count variable
2840 * OC_STACK_OK - no errors
2841 * OC_STACK_ERROR - stack process error
2843 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2844 uint8_t *numResourceTypes) {
2845 OCResource *resource;
2846 OCResourceType *pointer;
2848 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2849 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2850 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2852 *numResourceTypes = 0;
2854 resource = findResource((OCResource *) handle);
2856 pointer = resource->rsrcType;
2858 *numResourceTypes = *numResourceTypes + 1;
2859 pointer = pointer->next;
2866 * Get name of resource type of the resource.
2868 * @param handle - handle of resource
2869 * @param index - index of resource, 0 to Count - 1
2872 * resource type name - if resource found
2873 * NULL - resource not found
2875 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
2876 OCResourceType *resourceType;
2878 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2880 resourceType = findResourceTypeAtIndex(handle, index);
2882 return resourceType->resourcetypename;
2884 return (const char *) NULL;
2890 * Get the number of resource interfaces of the resource.
2892 * @param handle - handle of resource
2893 * @param numResources - pointer to count variable
2896 * OC_STACK_OK - no errors
2897 * OC_STACK_ERROR - stack process error
2899 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2900 uint8_t *numResourceInterfaces) {
2901 OCResourceInterface *pointer;
2902 OCResource *resource;
2904 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2906 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2907 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2909 *numResourceInterfaces = 0;
2910 resource = findResource((OCResource *) handle);
2912 pointer = resource->rsrcInterface;
2914 *numResourceInterfaces = *numResourceInterfaces + 1;
2915 pointer = pointer->next;
2922 * Get name of resource interface of the resource.
2924 * @param handle - handle of resource
2925 * @param index - index of resource, 0 to Count - 1
2928 * resource interface name - if resource found
2929 * NULL - resource not found
2931 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
2932 OCResourceInterface *resourceInterface;
2934 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2936 resourceInterface = findResourceInterfaceAtIndex(handle, index);
2937 if (resourceInterface) {
2938 return resourceInterface->name;
2940 return (const char *) NULL;
2944 * Get resource handle from the collection resource by index.
2946 * @param collectionHandle - handle of collection resource
2947 * @param index - index of contained resource, 0 to Count - 1
2950 * handle to resource - if resource found
2951 * NULL - resource not found
2953 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2955 OCResource *resource;
2957 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2959 if (index >= MAX_CONTAINED_RESOURCES) {
2963 resource = findResource((OCResource *) collectionHandle);
2968 return resource->rsrcResources[index];
2972 * Bind an entity handler to the resource.
2974 * @param handle - handle to the resource that the contained resource is to be bound
2975 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2977 * OC_STACK_OK - no errors
2978 * OC_STACK_ERROR - stack process error
2980 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2981 OCEntityHandler entityHandler) {
2982 OCResource *resource;
2984 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2986 // Validate parameters
2987 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2988 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2990 // Use the handle to find the resource in the resource linked list
2991 resource = findResource((OCResource *)handle);
2993 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2994 return OC_STACK_ERROR;
2998 resource->entityHandler = entityHandler;
3000 #ifdef WITH_PRESENCE
3001 if(presenceResource.handle)
3003 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3004 SendPresenceNotification(resource->rsrcType);
3012 * Get the entity handler for a resource.
3014 * @param handle - handle of resource
3017 * entity handler - if resource found
3018 * NULL - resource not found
3020 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
3021 OCResource *resource;
3023 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
3025 // Use the handle to find the resource in the resource linked list
3026 resource = findResource((OCResource *)handle);
3028 OC_LOG(ERROR, TAG, PCF("Resource not found"));
3033 return resource->entityHandler;
3036 void incrementSequenceNumber(OCResource * resPtr)
3038 // Increment the sequence number
3039 resPtr->sequenceNum += 1;
3040 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3042 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3048 * Notify Presence subscribers that a resource has been modified
3050 * @param resourceType - Handle to the resourceType linked list of resource
3051 * that was modified.
3052 * @param qos - Quality Of Service
3055 #ifdef WITH_PRESENCE
3056 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
3058 OCResource *resPtr = NULL;
3059 OCStackResult result;
3060 OCMethod method = OC_REST_PRESENCE;
3061 uint32_t maxAge = 0;
3062 resPtr = findResource((OCResource *) presenceResource.handle);
3065 return OC_STACK_NO_RESOURCE;
3067 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3069 maxAge = presenceResource.presenceTTL;
3076 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
3080 #endif // WITH_PRESENCE
3082 * Notify observers that an observed value has changed.
3084 * @param handle - handle of resource
3087 * OC_STACK_OK - no errors
3088 * OC_STACK_NO_RESOURCE - invalid resource handle
3089 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
3091 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
3093 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
3095 OCResource *resPtr = NULL;
3096 OCStackResult result;
3097 OCMethod method = OC_REST_NOMETHOD;
3098 uint32_t maxAge = 0;
3100 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
3101 #ifdef WITH_PRESENCE
3102 if(handle == presenceResource.handle)
3106 #endif // WITH_PRESENCE
3107 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3109 // Verify that the resource exists
3110 resPtr = findResource ((OCResource *) handle);
3113 return OC_STACK_NO_RESOURCE;
3117 //only increment in the case of regular observing (not presence)
3118 incrementSequenceNumber(resPtr);
3119 method = OC_REST_OBSERVE;
3120 maxAge = MAX_OBSERVE_AGE;
3121 #ifdef WITH_PRESENCE
3122 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
3124 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3131 OCNotifyListOfObservers (OCResourceHandle handle,
3132 OCObservationId *obsIdList,
3133 uint8_t numberOfIds,
3134 unsigned char *notificationJSONPayload,
3135 OCQualityOfService qos)
3137 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
3139 OCResource *resPtr = NULL;
3140 //TODO: we should allow the server to define this
3141 uint32_t maxAge = MAX_OBSERVE_AGE;
3143 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3144 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3145 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
3147 // Verify that the resource exists
3148 resPtr = findResource ((OCResource *) handle);
3149 if (NULL == resPtr || myStackMode == OC_CLIENT)
3151 return OC_STACK_NO_RESOURCE;
3155 incrementSequenceNumber(resPtr);
3157 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3158 notificationJSONPayload, maxAge, qos));
3162 * Send a response to a request.
3163 * The response can be a regular, slow, or block (i.e. a response that
3164 * is too large to be sent in a single PDU and must span multiple transmissions)
3166 * @param response - pointer to structure that contains response parameters
3169 * OC_STACK_OK - No errors; Success
3170 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
3171 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
3172 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
3173 * persistent response buffer is necessary
3175 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3177 OCStackResult result = OC_STACK_ERROR;
3178 OCServerRequest *serverRequest = NULL;
3180 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
3182 // Validate input parameters
3183 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3184 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3186 // TODO: Placeholder for creating a response entry when implementing
3187 // block transfer feature
3189 // If a response payload is present, check if block transfer is required
3190 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
3191 (const char *)ehResponse->payload, ehResponse->payloadSize))
3193 OC_LOG(INFO, TAG, PCF("Block transfer required"));
3195 // Persistent response buffer is needed for block transfer
3196 if (!ehResponse->persistentBufferFlag)
3198 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
3199 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
3201 // TODO: Placeholder for block transfer handling
3202 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
3203 // when implementing the block transfer feature
3208 // Get pointer to request info
3209 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3212 result = serverRequest->ehResponseHandler(ehResponse);
3219 * Cancel a response. Applies to a block response
3221 * @param responseHandle - response handle set by stack in OCServerResponse after
3222 * OCDoResponse is called
3225 * OC_STACK_OK - No errors; Success
3226 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
3228 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
3230 OCStackResult result = OC_STACK_NOTIMPL;
3232 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
3234 // TODO: validate response handle
3239 //-----------------------------------------------------------------------------
3240 // Private internal function definitions
3241 //-----------------------------------------------------------------------------
3243 * Generate handle of OCDoResource invocation for callback management.
3245 static OCDoHandle GenerateInvocationHandle()
3247 OCDoHandle handle = NULL;
3248 // Generate token here, it will be deleted when the transaction is deleted
3249 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
3252 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
3257 #ifdef WITH_PRESENCE
3258 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3259 OCResourceProperty resourceProperties, uint8_t enable)
3261 if (resourceProperties
3262 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
3263 OC_LOG(ERROR, TAG, PCF("Invalid property"));
3264 return OC_STACK_INVALID_PARAM;
3268 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3272 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3279 * Initialize resource data structures, variables, etc.
3281 OCStackResult initResources() {
3282 OCStackResult result = OC_STACK_OK;
3283 // Init application resource vars
3284 headResource = NULL;
3285 // Init Virtual Resources
3286 #ifdef WITH_PRESENCE
3287 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
3288 //presenceResource.token = OCGenerateCoAPToken();
3289 result = OCCreateResource(&presenceResource.handle,
3290 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3295 //make resource inactive
3296 result = OCChangeResourceProperty(
3297 &(((OCResource *) presenceResource.handle)->resourceProperties),
3304 * Add a resource to the end of the linked list of resources.
3306 * @param resource - resource to be added
3308 void insertResource(OCResource *resource) {
3309 OCResource *pointer;
3311 if (!headResource) {
3312 headResource = resource;
3314 pointer = headResource;
3316 while (pointer->next) {
3317 pointer = pointer->next;
3319 pointer->next = resource;
3321 resource->next = NULL;
3325 * Find a resource in the linked list of resources.
3327 * @param resource - resource to be found
3329 * NULL - resource not found
3330 * pointer to resource - pointer to resource that was found in the linked list
3332 OCResource *findResource(OCResource *resource) {
3333 OCResource *pointer = headResource;
3336 if (pointer == resource) {
3339 pointer = pointer->next;
3344 void deleteAllResources()
3346 OCResource *pointer = headResource;
3351 temp = pointer->next;
3352 #ifdef WITH_PRESENCE
3353 if(pointer != (OCResource *) presenceResource.handle)
3355 #endif // WITH_PRESENCE
3356 deleteResource(pointer);
3357 #ifdef WITH_PRESENCE
3359 #endif // WITH_PRESENCE
3363 #ifdef WITH_PRESENCE
3364 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3365 // presence notification attributed to their deletion to be processed.
3366 deleteResource((OCResource *) presenceResource.handle);
3367 #endif // WITH_PRESENCE
3371 * Delete the resource from the linked list.
3373 * @param resource - resource to be deleted
3378 int deleteResource(OCResource *resource) {
3379 OCResource *prev = NULL;
3382 temp = headResource;
3384 if (temp == resource) {
3385 // Invalidate all Resource Properties.
3386 resource->resourceProperties = (OCResourceProperty) 0;
3387 #ifdef WITH_PRESENCE
3388 if(resource != (OCResource *) presenceResource.handle)
3390 #endif // WITH_PRESENCE
3391 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3392 #ifdef WITH_PRESENCE
3395 if(presenceResource.handle)
3397 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3398 if(resource != (OCResource *) presenceResource.handle)
3400 SendPresenceNotification(resource->rsrcType);
3404 SendPresenceNotification(NULL);
3409 if (temp == headResource) {
3410 headResource = temp->next;
3412 prev->next = temp->next;
3415 deleteResourceElements(temp);
3428 * Delete all of the dynamically allocated elements that were created for the resource.
3430 * @param resource - specified resource
3432 void deleteResourceElements(OCResource *resource) {
3438 OCFree(resource->uri);
3440 // Delete resourcetype linked list
3441 deleteResourceType(resource->rsrcType);
3443 // Delete resourceinterface linked list
3444 deleteResourceInterface(resource->rsrcInterface);
3448 * Delete all of the dynamically allocated elements that were created for the resource type.
3450 * @param resourceType - specified resource type
3452 void deleteResourceType(OCResourceType *resourceType) {
3453 OCResourceType *pointer = resourceType;
3454 OCResourceType *next;
3457 next = pointer->next;
3458 OCFree(pointer->resourcetypename);
3465 * Delete all of the dynamically allocated elements that were created for the resource interface.
3467 * @param resourceInterface - specified resource interface
3469 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
3470 OCResourceInterface *pointer = resourceInterface;
3471 OCResourceInterface *next;
3474 next = pointer->next;
3475 OCFree(pointer->name);
3482 * Insert a resource type into a resource's resource type linked list.
3484 * @param resource - resource where resource type is to be inserted
3485 * @param resourceType - resource type to be inserted
3487 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
3488 OCResourceType *pointer;
3490 if (resource && !resource->rsrcType) {
3491 resource->rsrcType = resourceType;
3495 pointer = resource->rsrcType;
3499 pointer = resourceType;
3501 while (pointer->next) {
3502 pointer = pointer->next;
3504 pointer->next = resourceType;
3506 resourceType->next = NULL;
3510 * Get a resource type at the specified index within a resource.
3512 * @param handle - handle of resource
3513 * @param index - index of resource type
3516 * resourcetype - if found
3519 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
3520 OCResource *resource;
3521 OCResourceType *pointer;
3524 // Find the specified resource
3525 resource = findResource((OCResource *) handle);
3530 // Make sure a resource has a resourcetype
3531 if (!resource->rsrcType) {
3535 // Iterate through the list
3536 pointer = resource->rsrcType;
3538 while ((i < index) && pointer) {
3540 pointer = pointer->next;
3546 * Finds a resource type in an OCResourceType link-list.
3548 * @param resourceTypeList - the link-list to be searched through
3549 * @param resourceTypeName - the key to search for
3552 * resourceType that matches the key (ie. resourceTypeName)
3553 * NULL - either an invalid parameter or this function was unable to find the key.
3555 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3557 if(resourceTypeList && resourceTypeName)
3559 OCResourceType * rtPointer = resourceTypeList;
3560 while(resourceTypeName && rtPointer)
3562 if(rtPointer->resourcetypename &&
3563 strcmp(resourceTypeName, (const char *)
3564 (rtPointer->resourcetypename)) == 0)
3568 rtPointer = rtPointer->next;
3575 * Insert a resource interface into a resource's resource interface linked list.
3577 * @param resource - resource where resource interface is to be inserted
3578 * @param resourceInterface - resource interface to be inserted
3580 void insertResourceInterface(OCResource *resource,
3581 OCResourceInterface *resourceInterface) {
3582 OCResourceInterface *pointer;
3584 if (!resource->rsrcInterface) {
3585 resource->rsrcInterface = resourceInterface;
3587 pointer = resource->rsrcInterface;
3588 while (pointer->next) {
3589 pointer = pointer->next;
3591 pointer->next = resourceInterface;
3593 resourceInterface->next = NULL;
3597 * Get a resource interface at the specified index within a resource.
3599 * @param handle - handle of resource
3600 * @param index - index of resource interface
3603 * resourceinterface - if found
3606 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3608 OCResource *resource;
3609 OCResourceInterface *pointer;
3612 // Find the specified resource
3613 resource = findResource((OCResource *) handle);
3618 // Make sure a resource has a resourceinterface
3619 if (!resource->rsrcInterface) {
3623 // Iterate through the list
3624 pointer = resource->rsrcInterface;
3626 while ((i < index) && pointer) {
3628 pointer = pointer->next;
3634 * Determine if a request/response must be sent in a block transfer because it is too large to be
3635 * sent in a single PDU. This function can be used for either a request or a response
3637 * @param request - NULL or pointer to request
3638 * @param response - NULL or pointer to response
3639 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
3640 * the length of the request/response
3643 * 0 - packet transfer NOT required (i.e. normal request/response)
3644 * 1 - packet transfer required (i.e. block transfer needed)
3646 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
3650 // Determine if we are checking a request or a response
3653 // If size is greater than 0, use it for the request size value, otherwise
3654 // assume request is null terminated and use strlen for size value
3655 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
3662 // If size is greater than 0, use it for the response size value, otherwise
3663 // assume response is null terminated and use strlen for size value
3664 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3673 * Retrieves a resource type based upon a query ontains only just one
3674 * resource attribute (and that has to be of type "rt").
3676 * @remark This API malloc's memory for the resource type. Do not malloc resourceType
3677 * before passing in.
3679 * @param query - The quert part of the URI
3680 * @param resourceType - The resource type to be populated; pass by reference.
3683 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
3684 * OC_STACK_OK - Success
3686 OCStackResult getResourceType(const char * query, unsigned char** resourceType)
3690 return OC_STACK_INVALID_PARAM;
3693 OCStackResult result = OC_STACK_ERROR;
3695 if(strncmp(query, "rt=", 3) == 0)
3697 *resourceType = (unsigned char *) OCMalloc(strlen(query)-3);
3700 result = OC_STACK_NO_MEMORY;
3703 strcpy((char *)*resourceType, ((const char *)&query[3]));
3704 result = OC_STACK_OK;
3710 OCStackResult getQueryFromUri(const char * uri, unsigned char** query, char ** newURI)
3714 return OC_STACK_INVALID_URI;
3716 if(!query || !newURI)
3718 return OC_STACK_INVALID_PARAM;
3720 char * leftToken = NULL;
3721 char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3726 strcpy(tempURI, uri);
3728 leftToken = strtok_r((char *)tempURI, "?", &strTokPtr);
3730 //TODO-CA: This could be simplified. Clean up required.
3731 while(leftToken != NULL)
3733 if(strncmp(leftToken, "rt=", 3) == 0 || strncmp(leftToken, "if=", 3) == 0)
3735 *query = (unsigned char *) OCMalloc(strlen(leftToken));
3741 strcpy((char *)*query, ((const char *)&leftToken[0]));
3744 leftToken = strtok_r(NULL, "?", &strTokPtr);
3752 return OC_STACK_NO_MEMORY;
3755 const ServerID OCGetServerInstanceID(void)
3757 static bool generated = false;
3758 static ServerID sid;
3765 sid = OCGetRandom();
3770 const char* OCGetServerInstanceIDString(void)
3772 // max printed length of a base 10
3773 // uint32 is 10 characters, so 11 includes null.
3774 // This will change as the representation gets switched
3776 static char buffer[11];
3777 int n = sprintf(buffer, "%u", OCGetServerInstanceID());