1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 //-----------------------------------------------------------------------------
24 //-----------------------------------------------------------------------------
25 #define _POSIX_C_SOURCE 200112L
29 #include "ocstackinternal.h"
30 #include "ocresourcehandler.h"
31 #include "occlientcb.h"
32 #include "ocobserve.h"
37 #include "ocserverrequest.h"
41 #include "cainterface.h"
44 //-----------------------------------------------------------------------------
46 //-----------------------------------------------------------------------------
48 OC_STACK_UNINITIALIZED = 0, OC_STACK_INITIALIZED, OC_STACK_UNINIT_IN_PROGRESS
53 OC_PRESENCE_UNINITIALIZED = 0, OC_PRESENCE_INITIALIZED
57 //-----------------------------------------------------------------------------
59 //-----------------------------------------------------------------------------
60 static OCStackState stackState = OC_STACK_UNINITIALIZED;
62 OCResource *headResource = NULL;
64 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
65 static PresenceResource presenceResource;
66 uint8_t PresenceTimeOutSize = 0;
67 uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
71 OCDeviceEntityHandler defaultDeviceHandler;
72 OCStackResult getQueryFromUri(const char * uri, unsigned char** resourceType, char ** newURI);
74 //-----------------------------------------------------------------------------
76 //-----------------------------------------------------------------------------
77 #define TAG PCF("OCStack")
78 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
79 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
80 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
81 TAG, PCF(#arg " is NULL")); return (retVal); } }
82 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
85 //TODO: we should allow the server to define this
86 #define MAX_OBSERVE_AGE (0x2FFFFUL)
88 //-----------------------------------------------------------------------------
90 //-----------------------------------------------------------------------------
91 extern void DeinitOCSecurityInfo();
93 //-----------------------------------------------------------------------------
94 // Internal API function
95 //-----------------------------------------------------------------------------
97 // This internal function is called to update the stack with the status of
98 // observers and communication failures
99 OCStackResult OCStackFeedBack(OCCoAPToken * token, uint8_t status)
101 OCStackResult result = OC_STACK_ERROR;
102 ResourceObserver * observer = NULL;
103 OCEntityHandlerRequest ehRequest = {0};
107 case OC_OBSERVER_NOT_INTERESTED:
108 OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
110 observer = GetObserverUsingToken (token->token);
112 observer = GetObserverUsingToken (token);
116 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
117 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
118 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
119 if(result != OC_STACK_OK)
123 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
125 //observer is not observing anymore
127 result = DeleteObserverUsingToken (token->token);
129 result = DeleteObserverUsingToken (token);
131 if(result == OC_STACK_OK)
133 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
137 result = OC_STACK_OK;
138 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
141 case OC_OBSERVER_STILL_INTERESTED:
142 //observer is still interested
143 OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
144 notifications, reset the failedCount"));
146 observer = GetObserverUsingToken (token->token);
148 observer = GetObserverUsingToken (token);
152 observer->forceHighQos = 0;
153 observer->failedCommCount = 0;
154 result = OC_STACK_OK;
158 result = OC_STACK_OBSERVER_NOT_FOUND;
161 case OC_OBSERVER_FAILED_COMM:
162 //observer is not reachable
163 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
165 observer = GetObserverUsingToken (token->token);
167 observer = GetObserverUsingToken (token);
171 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
173 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
174 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
175 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
176 if(result != OC_STACK_OK)
178 return OC_STACK_ERROR;
180 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
181 //observer is unreachable
182 result = DeleteObserverUsingToken (token);
183 if(result == OC_STACK_OK)
185 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
189 result = OC_STACK_OK;
190 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
195 observer->failedCommCount++;
196 result = OC_STACK_CONTINUE;
198 observer->forceHighQos = 1;
199 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
203 OC_LOG(ERROR, TAG, PCF("Unknown status"));
204 result = OC_STACK_ERROR;
211 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
213 OCStackResult ret = OC_STACK_ERROR;
221 ret = OC_STACK_RESOURCE_CREATED;
224 ret = OC_STACK_RESOURCE_DELETED;
227 ret = OC_STACK_INVALID_QUERY;
230 ret = OC_STACK_INVALID_OPTION;
233 ret = OC_STACK_NO_RESOURCE;
241 OCStackResult OCToCAConnectivityType(OCConnectivityType ocConType, CAConnectivityType_t* caConType)
243 OCStackResult ret = OC_STACK_OK;
248 *caConType = CA_ETHERNET;
251 *caConType = CA_WIFI;
260 //TODO-CA Add other connectivity types as they are enabled
261 *caConType = (CA_WIFI|CA_ETHERNET);
264 ret = OC_STACK_INVALID_PARAM;
270 OCStackResult CAToOCConnectivityType(CAConnectivityType_t caConType, OCConnectivityType *ocConType)
272 OCStackResult ret = OC_STACK_OK;
277 *ocConType = OC_ETHERNET;
280 *ocConType = OC_WIFI;
289 ret = OC_STACK_INVALID_PARAM;
295 // update response.addr appropriately from endPoint.addressInfo
296 OCStackResult UpdateResponseAddr(OCClientResponse *response, const CARemoteEndpoint_t* endPoint)
298 struct sockaddr_in sa;
299 OCStackResult ret = OC_STACK_INVALID_PARAM;
300 //TODO-CA Check validity of the endPoint pointer
301 inet_pton(AF_INET, endPoint->addressInfo.IP.ipAddress, &(sa.sin_addr));
302 sa.sin_port = htons(endPoint->addressInfo.IP.port);
303 static OCDevAddr address;
304 memcpy((void*)&address.addr, &(sa), sizeof(sa));
307 response->addr = &address;
308 ret = CAToOCConnectivityType(endPoint->connectivityType, &(response->connType));
313 void HandlePresenceResponse(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
315 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
316 ClientCB * cbNode = NULL;
317 char *resourceTypeName = NULL;
319 char * bufRes = responseInfo->info.payload;
320 OCClientResponse *response = (OCClientResponse *) OCMalloc(sizeof(OCClientResponse));
322 OCStackResult result = UpdateResponseAddr(response, endPoint);
323 if(result != OC_STACK_OK)
333 tok = strtok(bufRes, "[:]}");
334 bufRes[strlen(bufRes)] = ':';
335 tok = strtok(NULL, "[:]}");
336 bufRes[strlen((char *)bufRes)] = ':';
337 response->sequenceNumber = (uint32_t )atoi(tok);
338 tok = strtok(NULL, "[:]}");
339 tok = strtok(NULL, "[:]}");
342 resourceTypeName = (char *)OCMalloc(strlen(tok));
343 if(!resourceTypeName)
347 bufRes[strlen((char *)bufRes)] = ':';
348 strcpy(resourceTypeName, tok);
349 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
352 bufRes[strlen((char *)bufRes)] = ']';
354 response->resJSONPayload = responseInfo->info.payload;
355 response->result = OC_STACK_OK;
357 char *fullUri = (char *) OCMalloc(MAX_URI_LENGTH );
358 char *ipAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
360 strncpy(ipAddress, endPoint->addressInfo.IP.ipAddress, strlen(endPoint->addressInfo.IP.ipAddress));
361 ipAddress[strlen(endPoint->addressInfo.IP.ipAddress)] = '\0';
363 snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", ipAddress, endPoint->addressInfo.IP.port,
366 cbNode = GetClientCB(NULL, NULL, fullUri);
370 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response);
373 if (cbResult == OC_STACK_DELETE_TRANSACTION)
375 FindAndDeleteClientCB(cbNode);
382 OCFree(resourceTypeName);
386 //This function will be called back by CA layer when a response is received
387 void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
389 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
390 OCStackApplicationResult result = OC_STACK_DELETE_TRANSACTION;
391 if(strcmp(endPoint->resourceUri, OC_PRESENCE_URI) == 0)
393 HandlePresenceResponse(endPoint, responseInfo);
396 ClientCB *cbNode = GetClientCB((CAToken_t *)&responseInfo->info.token, NULL, NULL);
400 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
401 OCClientResponse response;
403 OCStackResult result = UpdateResponseAddr(&response, endPoint);
404 if(result != OC_STACK_OK)
406 OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint"));
410 response.result = CAToOCStackResult(responseInfo->result);
411 response.resJSONPayload = (unsigned char*)responseInfo->info.payload;
412 response.numRcvdVendorSpecificHeaderOptions = 0;
413 if(responseInfo->info.numOptions > 0)
416 //First option alwas with option ID COAP_OPTION_OBSERVE if it is availbale
417 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
419 memcpy (&(response.sequenceNumber),
420 &(responseInfo->info.options[0].optionData), 4);
421 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
426 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
429 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
431 OC_LOG(ERROR, TAG, PCF("#header options are more than MAX_HEADER_OPTIONS"));
435 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
437 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
438 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
441 result = cbNode->callBack(cbNode->context,
442 cbNode->handle, &response);
443 if (result == OC_STACK_DELETE_TRANSACTION)
445 FindAndDeleteClientCB(cbNode);
448 OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload);
449 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
452 //This function will be called back by CA layer when a request is received
453 void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
455 CAInfo_t responseData;
456 CAResponseInfo_t responseInfo;
457 OCStackResult requestResult = OC_STACK_ERROR;
459 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
462 if(myStackMode == OC_CLIENT)
464 //TODO: should the client be responding to requests?
468 OCServerProtocolRequest serverRequest;
470 memset (&serverRequest, 0, sizeof(OCServerProtocolRequest));
471 OC_LOG_V(INFO, TAG, PCF("***** Endpoint URI ***** : %s\n"), (char*)endPoint->resourceUri);
473 char * newUri = (char *)endPoint->resourceUri;
474 unsigned char * query = NULL;
475 unsigned char * resourceType = NULL;
476 getQueryFromUri(endPoint->resourceUri, &query, &newUri);
477 OC_LOG_V(INFO, TAG, PCF("**********URI without query ****: %s\n"), newUri);
478 OC_LOG_V(INFO, TAG, PCF("**********Query ****: %s\n"), query);
480 memcpy (&(serverRequest.resourceUrl), newUri, strlen(newUri));
484 memcpy (&(serverRequest.query), query, strlen(query));
486 //copy request payload
487 if (requestInfo->info.payload)
489 serverRequest.reqTotalSize = strlen(requestInfo->info.payload) + 1;
490 memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
491 strlen(requestInfo->info.payload));
492 serverRequest.reqTotalSize = strlen((const char *)requestInfo->info.payload) + 1;
496 serverRequest.reqTotalSize = 1;
499 switch (requestInfo->method)
503 serverRequest.method = OC_REST_GET;
508 serverRequest.method = OC_REST_PUT;
513 serverRequest.method = OC_REST_POST;
518 serverRequest.method = OC_REST_DELETE;
523 OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
529 OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d", strlen(requestInfo->info.token));
530 OC_LOG_BUFFER(INFO, TAG, requestInfo->info.token, strlen(requestInfo->info.token));
531 // TODO-CA: For CA integration currently copying CAToken to OCCoapToken:
532 // Need to remove OCCoapToken
533 memcpy (&(serverRequest.requestToken.token), requestInfo->info.token,
535 serverRequest.requestToken.tokenLength = MAX_TOKEN_LENGTH;
537 if (requestInfo->info.type == CA_MSG_CONFIRM)
539 serverRequest.qos = OC_HIGH_QOS;
541 else if (requestInfo->info.type == CA_MSG_NONCONFIRM)
543 serverRequest.qos = OC_LOW_QOS;
545 else if (requestInfo->info.type == CA_MSG_ACKNOWLEDGE)
547 // TODO-CA: Need to handle this
549 else if (requestInfo->info.type == CA_MSG_RESET)
551 // TODO-CA: Need to handle this
553 // CA does not need the following 3 fields
554 serverRequest.coapID = 0;
555 serverRequest.delayedResNeeded = 0;
556 serverRequest.secured = endPoint->isSecured;
559 serverRequest.addressInfo = endPoint->addressInfo;
560 serverRequest.connectivityType = endPoint->connectivityType;
561 if (requestInfo->info.token)
563 strncpy(serverRequest.token, requestInfo->info.token, sizeof(serverRequest.token) - 1);
566 // copy vendor specific header options
567 // TODO-CA: CA is including non-vendor header options as well, like observe.
568 // Need to filter those out
569 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &(requestInfo->info.numOptions));
570 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
572 // TODO-CA: Need to send an error indicating the num of options is incorrect
575 serverRequest.numRcvdVendorSpecificHeaderOptions = requestInfo->info.numOptions;
576 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
578 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
579 sizeof(CAHeaderOption_t)*requestInfo->info.numOptions);
582 requestResult = HandleStackRequests (&serverRequest);
585 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
590 //This function will be called back by occoap layer when a request is received
591 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
593 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
594 OCStackResult result = OC_STACK_ERROR;
595 ResourceHandling resHandling;
596 OCResource *resource;
598 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
601 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
603 result = AddServerCARequest(&request, protocolRequest->coapID,
604 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
605 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
606 protocolRequest->observationOption, protocolRequest->qos,
607 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
608 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
609 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
610 protocolRequest->reqTotalSize,
611 &protocolRequest->addressInfo, protocolRequest->connectivityType, protocolRequest->token);
613 result = AddServerRequest(&request, protocolRequest->coapID,
614 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
615 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
616 protocolRequest->observationOption, protocolRequest->qos,
617 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
618 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
619 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
620 protocolRequest->reqTotalSize);
622 if (OC_STACK_OK != result)
624 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
627 VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
629 if(!protocolRequest->reqMorePacket)
631 request->requestComplete = 1;
636 OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
639 if(request->requestComplete)
641 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
642 result = DetermineResourceHandling (request, &resHandling, &resource);
643 if (result == OC_STACK_OK)
645 result = ProcessRequest(resHandling, resource, request);
649 result = OC_STACK_ERROR;
654 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
655 result = OC_STACK_CONTINUE;
660 //This function will be called back by occoap layer when a response is received
661 OCStackResult HandleStackResponses(OCResponse * response)
663 OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)"));
664 OCStackResult result = OC_STACK_OK;
665 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
666 uint8_t isObserveNotification = 0;
667 ClientCB * cbNode = NULL;
669 uint8_t isPresenceNotification = 0;
670 uint8_t isMulticastPresence = 0;
671 char * resourceTypeName = NULL;
672 uint32_t lowerBound = 0;
673 uint32_t higherBound = 0;
675 unsigned char * bufRes = response->bufRes;
676 #endif // WITH_PRESENCE
678 cbNode = response->cbNode;
681 cbNode = GetClientCB(response->rcvdToken, NULL, NULL);
684 if(response->clientResponse->sequenceNumber >= OC_OFFSET_SEQUENCE_NUMBER)
686 isObserveNotification = 1;
687 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
690 OC_LOG_V(DEBUG, TAG, "The sequenceNumber/NONCE of this response %u",
691 response->clientResponse->sequenceNumber);
692 OC_LOG_V(DEBUG, TAG, "The maxAge/TTL of this response %u", response->maxAge);
693 OC_LOG_V(DEBUG, TAG, "The response received is %s", bufRes);
696 if(!strcmp((char *)response->rcvdUri, (char *)OC_PRESENCE_URI)){
697 isPresenceNotification = 1;
700 result = OC_STACK_INVALID_PARAM;
703 tok = strtok((char *)bufRes, "[:]}");
704 bufRes[strlen((char *)bufRes)] = ':';
705 tok = strtok(NULL, "[:]}");
706 bufRes[strlen((char *)bufRes)] = ':';
707 response->clientResponse->sequenceNumber = (uint32_t )atoi(tok);
708 OC_LOG_V(DEBUG, TAG, "The received NONCE is %u", response->clientResponse->sequenceNumber);
709 tok = strtok(NULL, "[:]}");
710 response->maxAge = (uint32_t )atoi(tok);
711 OC_LOG_V(DEBUG, TAG, "The received TTL is %u", response->maxAge);
712 tok = strtok(NULL, "[:]}");
715 resourceTypeName = (char *)OCMalloc(strlen(tok));
716 if(!resourceTypeName)
720 bufRes[strlen((char *)bufRes)] = ':';
721 strcpy(resourceTypeName, tok);
722 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
725 bufRes[strlen((char *)bufRes)] = ']';
728 // Check if the application subcribed for presence
731 cbNode = GetClientCB(NULL, NULL, response->fullUri);
734 // Check if application subscribed for multicast presence
737 snprintf((char *)response->fullUri, MAX_URI_LENGTH, "%s%s",
738 OC_MULTICAST_IP, response->rcvdUri);
739 cbNode = GetClientCB(NULL, NULL, response->fullUri);
742 isMulticastPresence = 1;
743 isPresenceNotification = 0;
747 if(cbNode && isPresenceNotification)
749 OC_LOG(INFO, TAG, PCF("Received a presence notification"));
750 if(!cbNode->presence)
752 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
753 VERIFY_NON_NULL_V(cbNode->presence);
754 cbNode->presence->timeOut = NULL;
755 cbNode->presence->timeOut = (uint32_t *)
756 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
757 if(!(cbNode->presence->timeOut)){
758 OCFree(cbNode->presence);
759 result = OC_STACK_NO_MEMORY;
762 if(response->maxAge == 0)
764 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
765 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
768 OCFree(cbNode->presence->timeOut);
769 OCFree(cbNode->presence);
770 cbNode->presence = NULL;
775 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %d", GetTime(0));
776 cbNode->presence->TTL = response->maxAge;
777 for(int index = 0; index < PresenceTimeOutSize; index++)
779 lowerBound = GetTime(((float)(PresenceTimeOut[index])
780 /(float)100)*(float)cbNode->presence->TTL);
781 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
782 /(float)100)*(float)cbNode->presence->TTL);
783 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
784 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
785 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
786 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
787 cbNode->presence->timeOut[index]);
789 cbNode->presence->TTLlevel = 0;
790 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
791 if(cbNode->sequenceNumber == response->clientResponse->sequenceNumber)
793 OC_LOG(INFO, TAG, PCF("===============No presence change"));
796 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
797 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;;
800 // Ensure that a filter is actually applied.
801 if(resourceTypeName && cbNode->filterResourceType)
803 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
809 else if(cbNode && isMulticastPresence)
811 // Check if the same nonce for a given host
812 OCMulticastNode* mcNode = NULL;
813 mcNode = GetMCPresenceNode(response->fullUri);
815 if(response->maxAge == 0)
817 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
818 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
821 OCFree(cbNode->presence->timeOut);
822 OCFree(cbNode->presence);
823 cbNode->presence = NULL;
826 else if(mcNode != NULL)
828 if(mcNode->nonce == response->clientResponse->sequenceNumber)
830 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
831 result = OC_STACK_NO_MEMORY;
834 mcNode->nonce = response->clientResponse->sequenceNumber;
838 uint32_t uriLen = strlen((char*)response->fullUri);
839 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
842 memcpy(uri, response->fullUri, (uriLen + 1));
847 PCF("===============No Memory for URI to store in the presence node"));
848 result = OC_STACK_NO_MEMORY;
851 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri,
852 response->clientResponse->sequenceNumber);
853 if(result == OC_STACK_NO_MEMORY)
856 PCF("===============No Memory for Multicast Presence Node"));
857 result = OC_STACK_NO_MEMORY;
862 // Ensure that a filter is actually applied.
863 if(resourceTypeName && cbNode->filterResourceType)
865 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
872 else if(!cbNode && isPresenceNotification)
874 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
875 ------------ ignoring"));
877 #endif // WITH_PRESENCE
881 if(isObserveNotification)
883 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
884 //TODO: check the standard for methods to detect wrap around condition
885 if(cbNode->method == OC_REST_OBSERVE &&
886 (response->clientResponse->sequenceNumber <= cbNode->sequenceNumber ||
887 (response->clientResponse->sequenceNumber > cbNode->sequenceNumber &&
888 response->clientResponse->sequenceNumber ==
889 MAX_SEQUENCE_NUMBER)))
891 OC_LOG_V(DEBUG, TAG, "Observe notification came out of order. \
892 Ignoring Incoming:%d Against Current:%d.",
893 response->clientResponse->sequenceNumber, cbNode->sequenceNumber);
896 if(response->clientResponse->sequenceNumber > cbNode->sequenceNumber){
897 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;
901 response->clientResponse->resJSONPayload = bufRes;
903 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response->clientResponse);
905 if (cbResult == OC_STACK_DELETE_TRANSACTION ||
906 response->clientResponse->result == OC_STACK_COMM_ERROR ||
907 (response->clientResponse->result == OC_STACK_RESOURCE_DELETED &&
908 !isPresenceNotification && !isMulticastPresence))
910 FindAndDeleteClientCB(cbNode);
915 result = OC_STACK_ERROR;
920 OCFree(resourceTypeName);
925 int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
928 unsigned char *itr, *coap;
929 uint8_t dotCount = 0;
933 /* search for scheme */
935 if (!isdigit((unsigned char) *ipAddrStr))
937 coap = (unsigned char *) OC_COAP_SCHEME;
938 while (*coap && tolower(*itr) == *coap)
947 if (isdigit((unsigned char) *ipAddrStr))
950 ipAddr[index] += *ipAddrStr - '0';
952 else if ((unsigned char) *ipAddrStr == '.')
964 if(*ipAddrStr == ':')
968 if (isdigit((unsigned char) *ipAddrStr))
971 *port += *ipAddrStr - '0';
982 if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
993 //-----------------------------------------------------------------------------
994 // Private internal function prototypes
995 //-----------------------------------------------------------------------------
997 static OCDoHandle GenerateInvocationHandle();
998 static OCStackResult initResources();
999 static void insertResource(OCResource *resource);
1000 static OCResource *findResource(OCResource *resource);
1001 static void insertResourceType(OCResource *resource,
1002 OCResourceType *resourceType);
1003 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
1005 static void insertResourceInterface(OCResource *resource,
1006 OCResourceInterface *resourceInterface);
1007 static OCResourceInterface *findResourceInterfaceAtIndex(
1008 OCResourceHandle handle, uint8_t index);
1009 static void deleteResourceType(OCResourceType *resourceType);
1010 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
1011 static void deleteResourceElements(OCResource *resource);
1012 static int deleteResource(OCResource *resource);
1013 static void deleteAllResources();
1014 static void incrementSequenceNumber(OCResource * resPtr);
1015 static OCStackResult verifyUriQueryLength(const char * inputUri,
1017 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
1018 OCStackResult getResourceType(const char * query, unsigned char** resourceType);
1020 //-----------------------------------------------------------------------------
1022 //-----------------------------------------------------------------------------
1025 * Initialize the OC Stack. Must be called prior to starting the stack.
1028 * IP Address of host device
1030 * Port of host device
1032 * Host device is client, server, or client-server
1035 * OC_STACK_OK - no errors
1036 * OC_STACK_ERROR - stack init error
1038 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1040 OCStackResult result = OC_STACK_ERROR;
1041 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
1045 OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
1051 //It is ok to select network to CA_WIFI for now
1052 CAResult_t caResult = CASelectNetwork(CA_WIFI|CA_ETHERNET);
1053 if(caResult == CA_STATUS_OK)
1055 OC_LOG(INFO, TAG, PCF("CASelectNetwork to WIFI"));
1056 caResult = CARegisterHandler(HandleCARequests, HandleCAResponses);
1057 if(caResult == CA_STATUS_OK)
1059 OC_LOG(INFO, TAG, PCF("CARegisterHandler..."));
1060 stackState = OC_STACK_INITIALIZED;
1061 result = OC_STACK_OK;
1065 caResult = CAStartDiscoveryServer();
1066 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
1069 caResult = CAStartListeningServer();
1070 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
1072 case OC_CLIENT_SERVER:
1073 caResult = CAStartListeningServer();
1074 if(caResult == CA_STATUS_OK)
1076 caResult = CAStartDiscoveryServer();
1078 OC_LOG(INFO, TAG, PCF("Client-server mode"));
1081 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1082 return OC_STACK_ERROR;
1087 if (caResult == CA_STATUS_OK)
1089 result = OC_STACK_OK;
1093 result = OC_STACK_ERROR;
1100 OC_LOG(INFO, TAG, PCF("Client mode"));
1103 OC_LOG(INFO, TAG, PCF("Server mode"));
1105 case OC_CLIENT_SERVER:
1106 OC_LOG(INFO, TAG, PCF("Client-server mode"));
1109 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1110 return OC_STACK_ERROR;
1114 // Make call to OCCoAP layer
1115 result = OCInitCoAP(ipAddr, (uint16_t) port, myStackMode);
1119 defaultDeviceHandler = NULL;
1121 #ifdef WITH_PRESENCE
1122 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
1123 #endif // WITH_PRESENCE
1125 if (result == OC_STACK_OK)
1127 stackState = OC_STACK_INITIALIZED;
1129 // Initialize resource
1130 if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
1132 result = initResources();
1134 if(result != OC_STACK_OK)
1136 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1142 * Stop the OC stack. Use for a controlled shutdown.
1144 * OC_STACK_OK - no errors
1145 * OC_STACK_ERROR - stack not initialized
1147 OCStackResult OCStop()
1149 OCStackResult result = OC_STACK_ERROR;
1151 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1153 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1155 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1158 else if (stackState != OC_STACK_INITIALIZED)
1160 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1161 return OC_STACK_ERROR;
1164 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1166 #ifdef WITH_PRESENCE
1167 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1168 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1169 presenceResource.presenceTTL = 0;
1170 #endif // WITH_PRESENCE
1172 // Free memory dynamically allocated for resources
1173 deleteAllResources();
1176 // Make call to OCCoAP layer
1177 if (OCStopCoAP() == OC_STACK_OK)
1179 // Remove all observers
1180 DeleteObserverList();
1181 // Remove all the client callbacks
1182 DeleteClientCBList();
1183 stackState = OC_STACK_UNINITIALIZED;
1184 result = OC_STACK_OK;
1186 stackState = OC_STACK_INITIALIZED;
1187 result = OC_STACK_ERROR;
1190 // Deinit security blob
1191 DeinitOCSecurityInfo();
1193 if (result != OC_STACK_OK) {
1194 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
1201 * Verify the lengths of the URI and the query separately
1203 * @param inputUri - Input URI and query.
1204 * @param uriLen - The length of the initial URI with query.
1206 * Note: The '?' that appears after the URI is not considered as
1207 * a part of the query.
1209 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1213 query = strchr (inputUri, '?');
1217 if((query - inputUri) > MAX_URI_LENGTH)
1219 return OC_STACK_INVALID_URI;
1222 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1224 return OC_STACK_INVALID_QUERY;
1227 else if(uriLen > MAX_URI_LENGTH)
1229 return OC_STACK_INVALID_URI;
1235 * Discover or Perform requests on a specified resource (specified by that Resource's respective URI).
1237 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of calling this API.
1238 * @param method - @ref OCMethod to perform on the resource
1239 * @param requiredUri - URI of the resource to interact with
1240 * @param referenceUri - URI of the reference resource
1241 * @param request - JSON encoded request
1242 * @param qos - quality of service
1243 * @param cbData - struct that contains asynchronous callback function that is invoked
1244 * by the stack when discovery or resource interaction is complete
1245 * @param options - The address of an array containing the vendor specific header
1246 * header options to be sent with the request
1247 * @param numOptions - Number of vendor specific header options to be included
1250 * OC_STACK_OK - no errors
1251 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
1252 * OC_STACK_INVALID_METHOD - invalid resource method
1253 * OC_STACK_INVALID_URI - invalid required or reference URI
1255 * Note: IN case of CA, when using multicast, the required URI should not contain IP address.
1256 * Instead, it just contains the URI to the resource such as "/oc/core".
1259 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1260 const char *referenceUri, const char *request, uint8_t conType,
1261 OCQualityOfService qos, OCCallbackData *cbData,
1262 OCHeaderOption * options, uint8_t numOptions)
1264 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1265 const char *referenceUri, const char *request,
1266 OCQualityOfService qos, OCCallbackData *cbData,
1267 OCHeaderOption * options, uint8_t numOptions)
1270 OCStackResult result = OC_STACK_ERROR;
1272 ClientCB *clientCB = NULL;
1273 unsigned char * requestUri = NULL;
1274 unsigned char * resourceType = NULL;
1275 unsigned char * query = NULL;
1276 char * newUri = (char *)requiredUri;
1277 (void) referenceUri;
1279 CARemoteEndpoint_t* endpoint = NULL;
1280 CAResult_t caResult;
1281 CAToken_t caToken = NULL;
1282 CAInfo_t requestData;
1283 CARequestInfo_t requestInfo;
1284 CAGroupEndpoint_t grpEnd;
1286 // To track if memory is allocated for additional header options
1287 uint8_t hdrOptionMemAlloc = 0;
1290 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1292 // Validate input parameters
1293 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1294 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1296 TODO ("Need to form the final query by concatenating require and reference URI's");
1297 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
1299 uint16_t uriLen = strlen(requiredUri);
1301 // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS
1307 case OC_REST_DELETE:
1308 case OC_REST_OBSERVE:
1309 case OC_REST_OBSERVE_ALL:
1310 case OC_REST_CANCEL_OBSERVE:
1312 #ifdef WITH_PRESENCE
1313 case OC_REST_PRESENCE:
1317 result = OC_STACK_INVALID_METHOD;
1321 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
1326 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
1328 result = OC_STACK_INVALID_PARAM;
1332 #ifdef WITH_PRESENCE
1333 if(method == OC_REST_PRESENCE)
1335 // Replacing method type with GET because "presence" is a stack layer only implementation.
1336 method = OC_REST_GET;
1337 result = getQueryFromUri(requiredUri, &query, &newUri);
1340 result = getResourceType((char *) query, &resourceType);
1343 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1347 OC_LOG(DEBUG, TAG, PCF("Resource type is NULL."));
1352 OC_LOG(DEBUG, TAG, PCF("Query string is NULL."));
1354 if(result != OC_STACK_OK)
1359 #endif // WITH_PRESENCE
1361 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
1364 memcpy(requestUri, newUri, (uriLen + 1));
1368 result = OC_STACK_NO_MEMORY;
1372 *handle = GenerateInvocationHandle();
1375 result = OC_STACK_NO_MEMORY;
1380 memset(&requestData, 0, sizeof(CAInfo_t));
1381 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1382 memset(&grpEnd, 0, sizeof(CAGroupEndpoint_t));
1386 case OC_REST_OBSERVE:
1387 case OC_REST_OBSERVE_ALL:
1388 case OC_REST_CANCEL_OBSERVE:
1390 requestInfo.method = CA_GET;
1395 requestInfo.method = CA_PUT;
1400 requestInfo.method = CA_POST;
1403 case OC_REST_DELETE:
1405 requestInfo.method = CA_DELETE;
1408 #ifdef WITH_PRESENCE
1409 case OC_REST_PRESENCE:
1410 //TODO-CA: What should be the CA method?
1414 result = OC_STACK_INVALID_METHOD;
1418 //High QoS is not supported
1419 if(qos == OC_HIGH_QOS)
1421 result = OC_STACK_INVALID_PARAM;
1426 caResult = CAGenerateToken(&caToken);
1428 //TODO-CA Remove this temporary fix (for some reason same token is being generated)
1431 caToken[0] += count;
1433 if (caResult != CA_STATUS_OK)
1435 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1440 // TODO-CA: Map QoS to the right CA msg type
1441 requestData.type = CA_MSG_NONCONFIRM;
1442 requestData.token = caToken;
1443 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1445 result = CreateObserveHeaderOption (&(requestData.options), options,
1446 numOptions, OC_OBSERVE_REGISTER);
1447 if (result != OC_STACK_OK)
1451 hdrOptionMemAlloc = 1;
1452 requestData.numOptions = numOptions + 1;
1456 requestData.options = (CAHeaderOption_t*)options;
1457 requestData.numOptions = numOptions;
1459 requestData.payload = (char *)request;
1461 requestInfo.info = requestData;
1463 CAConnectivityType_t caConType;
1465 result = OCToCAConnectivityType(conType, &caConType);
1466 if (result != OC_STACK_OK)
1468 OC_LOG(ERROR, TAG, PCF("Invalid Connectivity Type"));
1473 if(conType == OC_ALL)
1475 grpEnd.connectivityType = caConType;
1477 grpEnd.resourceUri = (CAURI_t) OICMalloc(uriLen + 1);
1478 strncpy(grpEnd.resourceUri, requiredUri, (uriLen + 1));
1480 caResult = CASendRequestToAll(&grpEnd, &requestInfo);
1484 caResult = CACreateRemoteEndpoint(newUri, caConType, &endpoint);
1486 if (caResult != CA_STATUS_OK)
1488 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1492 caResult = CASendRequest(endpoint, &requestInfo);
1495 if (caResult != CA_STATUS_OK)
1497 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1501 if((result = AddClientCB(&clientCB, cbData, &caToken, handle, method,
1502 requestUri, resourceType)) != OC_STACK_OK)
1504 result = OC_STACK_NO_MEMORY;
1510 // Generate token which will be used by OCStack to match responses received
1512 OCGenerateCoAPToken(&token);
1514 if((result = AddClientCB(&clientCB, cbData, &token, handle, method, requestUri, resourceType))
1517 result = OC_STACK_NO_MEMORY;
1521 // Make call to OCCoAP layer
1522 result = OCDoCoAPResource(method, qos, &token, newUri, request, options, numOptions);
1526 if(newUri != requiredUri)
1530 if (result != OC_STACK_OK)
1532 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1533 FindAndDeleteClientCB(clientCB);
1536 CADestroyRemoteEndpoint(endpoint);
1537 OCFree(grpEnd.resourceUri);
1538 if (hdrOptionMemAlloc)
1540 OCFree(requestData.options);
1547 * Cancel a request associated with a specific @ref OCDoResource invocation.
1549 * @param handle - Used to identify a specific OCDoResource invocation.
1550 * @param qos - used to specify Quality of Service (read below for more info)
1551 * @param options- used to specify vendor specific header options when sending
1552 * explicit observe cancellation
1553 * @param numOptions- Number of header options to be included
1556 * OC_STACK_OK - No errors; Success
1557 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1559 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1563 * This ftn is implemented one of two ways in the case of observation:
1565 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1566 * Remove the callback associated on client side.
1567 * When the next notification comes in from server,
1568 * reply with RESET message to server.
1569 * Keep in mind that the server will react to RESET only
1570 * if the last notification was sent ans CON
1572 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1573 * and it is associated with an observe request
1574 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1575 * Send CON Observe request to server with
1576 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1577 * Remove the callback associated on client side.
1579 OCStackResult ret = OC_STACK_OK;
1581 CARemoteEndpoint_t* endpoint = NULL;
1582 CAResult_t caResult;
1583 CAInfo_t requestData;
1584 CARequestInfo_t requestInfo;
1585 // Track if memory is allocated for additional header options
1586 uint8_t hdrOptionMemAlloc = 0;
1590 return OC_STACK_INVALID_PARAM;
1593 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1595 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1598 switch (clientCB->method)
1600 case OC_REST_OBSERVE:
1601 case OC_REST_OBSERVE_ALL:
1603 caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri, CA_WIFI,
1605 endpoint->connectivityType = CA_WIFI;
1606 if (caResult != CA_STATUS_OK)
1608 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1609 return OC_STACK_ERROR;
1612 memset(&requestData, 0, sizeof(CAInfo_t));
1613 // TODO-CA: Map QoS to the right CA msg type
1614 requestData.type = CA_MSG_NONCONFIRM;
1615 requestData.token = clientCB->token;
1616 if (CreateObserveHeaderOption (&(requestData.options),
1617 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
1619 return OC_STACK_ERROR;
1621 hdrOptionMemAlloc = 1;
1622 requestData.numOptions = numOptions + 1;
1623 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1624 requestInfo.method = CA_GET;
1625 requestInfo.info = requestData;
1627 caResult = CASendRequest(endpoint, &requestInfo);
1628 if (caResult != CA_STATUS_OK)
1630 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1632 if(caResult == CA_STATUS_OK)
1637 if(qos == OC_HIGH_QOS)
1639 ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
1640 &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
1645 FindAndDeleteClientCB(clientCB);
1649 #ifdef WITH_PRESENCE
1650 case OC_REST_PRESENCE:
1651 FindAndDeleteClientCB(clientCB);
1655 return OC_STACK_INVALID_METHOD;
1659 CADestroyRemoteEndpoint(endpoint);
1660 if (hdrOptionMemAlloc)
1662 OCFree(requestData.options);
1668 #ifdef WITH_PRESENCE
1669 OCStackResult OCProcessPresence()
1671 OCStackResult result = OC_STACK_OK;
1672 uint8_t ipAddr[4] = { 0 };
1675 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1676 ClientCB* cbNode = NULL;
1678 OCClientResponse clientResponse;
1679 OCResponse * response = NULL;
1681 LL_FOREACH(cbList, cbNode) {
1682 if(OC_REST_PRESENCE == cbNode->method)
1684 if(cbNode->presence)
1686 uint32_t now = GetTime(0);
1687 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
1688 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1691 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1696 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1697 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1698 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1701 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1703 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1704 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1706 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1708 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
1709 (OCDevAddr *) &dst, 0, NULL);
1710 if(result != OC_STACK_OK)
1714 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1715 &cbNode->token, &clientResponse, NULL);
1716 if(result != OC_STACK_OK)
1721 // Increment the TTLLevel (going to a next state), so we don't keep
1722 // sending presence notification to client.
1723 cbNode->presence->TTLlevel++;
1724 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1725 cbNode->presence->TTLlevel);
1729 result = OC_STACK_INVALID_IP;
1732 HandleStackResponses(response);
1734 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1736 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
1738 OCGenerateCoAPToken(&token);
1739 result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
1740 &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
1741 if(result != OC_STACK_OK)
1745 cbNode->presence->TTLlevel++;
1746 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
1752 if (result != OC_STACK_OK)
1754 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
1761 * Called in main loop of OC client or server. Allows low-level processing of
1765 * OC_STACK_OK - no errors
1766 * OC_STACK_ERROR - stack process error
1768 OCStackResult OCProcess() {
1770 OC_LOG(INFO, TAG, PCF("Entering OCProcess"));
1771 #ifdef WITH_PRESENCE
1772 OCProcessPresence();
1775 CAHandleRequestResponse();
1783 #ifdef WITH_PRESENCE
1785 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
1786 * presence notifications to clients via multicast. Once this API has been called with a success,
1787 * clients may query for this server's presence and this server's stack will respond via multicast.
1789 * Server can call this function when it comes online for the first time, or when it comes back
1790 * online from offline mode, or when it re enters network.
1792 * @param ttl - Time To Live in seconds
1793 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
1796 * OC_STACK_OK - No errors; Success
1798 OCStackResult OCStartPresence(const uint32_t ttl)
1800 OCChangeResourceProperty(
1801 &(((OCResource *)presenceResource.handle)->resourceProperties),
1806 presenceResource.presenceTTL = ttl;
1809 if(OC_PRESENCE_UNINITIALIZED == presenceState)
1811 OCDevAddr multiCastAddr;
1814 presenceState = OC_PRESENCE_INITIALIZED;
1815 OCGenerateCoAPToken(&token);
1816 OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
1818 CAAddress_t addressInfo;
1819 strncpy(addressInfo.IP.ipAddress, "224.0.1.187", CA_IPADDR_SIZE);
1820 addressInfo.IP.port = 5298;
1822 CAToken_t caToken = NULL;
1823 CAGenerateToken(&caToken);
1825 AddCAObserver(OC_PRESENCE_URI, NULL, 0, &token,
1826 &multiCastAddr, (OCResource *)presenceResource.handle, OC_LOW_QOS,
1827 &addressInfo, CA_WIFI, caToken);
1829 //add the presence observer
1830 AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
1831 (OCResource *)presenceResource.handle, OC_LOW_QOS);
1835 // Each time OCStartPresence is called
1836 // a different random 32-bit integer number is used
1837 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1839 return SendPresenceNotification(NULL);
1843 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
1844 * presence notifications to clients via multicast. Once this API has been called with a success,
1845 * this server's stack will not respond to clients querying for this server's presence.
1847 * Server can call this function when it is terminating, going offline, or when going
1848 * away from network.
1851 * OC_STACK_OK - No errors; Success
1853 OCStackResult OCStopPresence()
1855 OCStackResult result = OC_STACK_ERROR;
1856 //make resource inactive
1857 result = OCChangeResourceProperty(
1858 &(((OCResource *) presenceResource.handle)->resourceProperties),
1860 result = SendPresenceNotification(NULL);
1867 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
1869 defaultDeviceHandler = entityHandler;
1874 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
1876 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
1878 if(myStackMode == OC_CLIENT)
1880 return OC_STACK_ERROR;
1883 return SaveDeviceInfo(deviceInfo);
1889 * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource
1890 * @param resourceTypeName - name of resource type. Example: "core.led"
1891 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1892 * @param uri - URI of the resource. Example: "/a/led"
1893 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1894 * NULL for default entity handler
1895 * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE
1898 * OC_STACK_OK - no errors
1899 * OC_STACK_ERROR - stack process error
1901 OCStackResult OCCreateResource(OCResourceHandle *handle,
1902 const char *resourceTypeName,
1903 const char *resourceInterfaceName,
1904 const char *uri, OCEntityHandler entityHandler,
1905 uint8_t resourceProperties) {
1907 OCResource *pointer = NULL;
1910 OCStackResult result = OC_STACK_ERROR;
1912 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
1914 if(myStackMode == OC_CLIENT)
1918 // Validate parameters
1919 if(!uri || (strlen(uri) == 0))
1921 OC_LOG(ERROR, TAG, PCF("URI is invalid"));
1922 return OC_STACK_INVALID_URI;
1924 // Is it presented during resource discovery?
1925 if (!handle || !resourceTypeName) {
1926 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
1927 return OC_STACK_INVALID_PARAM;
1930 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
1931 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
1934 // Make sure resourceProperties bitmask has allowed properties specified
1935 if (resourceProperties
1936 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
1937 OC_LOG(ERROR, TAG, PCF("Invalid property"));
1938 return OC_STACK_INVALID_PARAM;
1941 // If the headResource is NULL, then no resources have been created...
1942 pointer = headResource;
1944 // At least one resources is in the resource list, so we need to search for
1945 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
1947 if (strcmp(uri, pointer->uri) == 0) {
1948 OC_LOG(ERROR, TAG, PCF("URI already in use"));
1949 return OC_STACK_INVALID_PARAM;
1951 pointer = pointer->next;
1954 // Create the pointer and insert it into the resource list
1955 pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
1959 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
1961 insertResource(pointer);
1964 size = strlen(uri) + 1;
1965 str = (char *) OCMalloc(size);
1969 strncpy(str, uri, size);
1972 // Set properties. Set OC_ACTIVE
1973 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
1976 // Add the resourcetype to the resource
1977 result = BindResourceTypeToResource(pointer, resourceTypeName);
1978 if (result != OC_STACK_OK) {
1979 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
1983 // Add the resourceinterface to the resource
1984 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
1985 if (result != OC_STACK_OK) {
1986 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
1990 // If an entity handler has been passed, attach it to the newly created
1991 // resource. Otherwise, set the default entity handler.
1994 pointer->entityHandler = entityHandler;
1998 pointer->entityHandler = defaultResourceEHandler;
2002 result = OC_STACK_OK;
2004 #ifdef WITH_PRESENCE
2005 if(presenceResource.handle)
2007 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2008 SendPresenceNotification(pointer->rsrcType);
2012 if (result != OC_STACK_OK)
2014 // Deep delete of resource and other dynamic elements that it contains
2015 deleteResource(pointer);
2024 * Create a resource. with host ip address for remote resource
2026 * @param handle - pointer to handle to newly created resource. Set by ocstack.
2027 * Used to refer to resource
2028 * @param resourceTypeName - name of resource type. Example: "core.led"
2029 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
2030 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
2031 * @param uri - URI of the resource. Example: "/a/led"
2032 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2033 * NULL for default entity handler
2034 * @param resourceProperties - properties supported by resource.
2035 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
2038 * OC_STACK_OK - no errors
2039 * OC_STACK_ERROR - stack process error
2042 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
2043 const char *resourceTypeName,
2044 const char *resourceInterfaceName,
2047 OCEntityHandler entityHandler,
2048 uint8_t resourceProperties)
2052 OCStackResult result = OC_STACK_ERROR;
2054 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
2055 uri, entityHandler, resourceProperties);
2057 if (result != OC_STACK_ERROR)
2060 size = strlen(host) + 1;
2061 str = (char *) OCMalloc(size);
2064 return OC_STACK_ERROR;
2066 strncpy(str, host, size);
2067 ((OCResource *) *handle)->host = str;
2074 * Add a resource to a collection resource.
2076 * @param collectionHandle - handle to the collection resource
2077 * @param resourceHandle - handle to resource to be added to the collection resource
2080 * OC_STACK_OK - no errors
2081 * OC_STACK_ERROR - stack process error
2082 * OC_STACK_INVALID_PARAM - invalid collectionhandle
2084 OCStackResult OCBindResource(
2085 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2086 OCResource *resource;
2089 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2091 // Validate parameters
2092 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2093 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2094 // Container cannot contain itself
2095 if (collectionHandle == resourceHandle) {
2096 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2097 return OC_STACK_INVALID_PARAM;
2100 // Use the handle to find the resource in the resource linked list
2101 resource = findResource((OCResource *) collectionHandle);
2103 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2104 return OC_STACK_INVALID_PARAM;
2107 // Look for an open slot to add add the child resource.
2108 // If found, add it and return success
2109 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2110 if (!resource->rsrcResources[i]) {
2111 resource->rsrcResources[i] = (OCResource *) resourceHandle;
2112 OC_LOG(INFO, TAG, PCF("resource bound"));
2117 #ifdef WITH_PRESENCE
2118 if(presenceResource.handle)
2120 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2121 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2125 // Unable to add resourceHandle, so return error
2126 return OC_STACK_ERROR;
2130 * Remove a resource from a collection resource.
2132 * @param collectionHandle - handle to the collection resource
2133 * @param resourceHandle - handle to resource to be added to the collection resource
2136 * OC_STACK_OK - no errors
2137 * OC_STACK_ERROR - stack process error
2138 * OC_STACK_INVALID_PARAM - invalid collectionHandle
2140 OCStackResult OCUnBindResource(
2141 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2142 OCResource *resource;
2145 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2147 // Validate parameters
2148 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2149 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2150 // Container cannot contain itself
2151 if (collectionHandle == resourceHandle) {
2152 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2153 return OC_STACK_INVALID_PARAM;
2156 // Use the handle to find the resource in the resource linked list
2157 resource = findResource((OCResource *) collectionHandle);
2159 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2160 return OC_STACK_INVALID_PARAM;
2163 // Look for an open slot to add add the child resource.
2164 // If found, add it and return success
2165 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2166 if (resourceHandle == resource->rsrcResources[i]) {
2167 resource->rsrcResources[i] = (OCResource *) NULL;
2168 OC_LOG(INFO, TAG, PCF("resource unbound"));
2173 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2175 #ifdef WITH_PRESENCE
2176 if(presenceResource.handle)
2178 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2179 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2183 // Unable to add resourceHandle, so return error
2184 return OC_STACK_ERROR;
2187 OCStackResult BindResourceTypeToResource(OCResource* resource,
2188 const char *resourceTypeName)
2190 OCResourceType *pointer = NULL;
2193 OCStackResult result = OC_STACK_ERROR;
2195 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
2197 // Validate parameters
2198 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2199 // TODO: Does resource attribute resentation really have to be maintained in stack?
2200 // Is it presented during resource discovery?
2202 TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
2204 // Create the resourcetype and insert it into the resource list
2205 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
2210 // Set the resourceTypeName
2211 size = strlen(resourceTypeName) + 1;
2212 str = (char *) OCMalloc(size);
2216 strncpy(str, resourceTypeName, size);
2217 pointer->resourcetypename = str;
2219 insertResourceType(resource, pointer);
2220 result = OC_STACK_OK;
2222 exit: if (result != OC_STACK_OK) {
2230 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2231 const char *resourceInterfaceName)
2233 OCResourceInterface *pointer = NULL;
2236 OCStackResult result = OC_STACK_ERROR;
2238 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
2240 // Validate parameters
2241 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2243 TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
2245 // Create the resourceinterface and insert it into the resource list
2246 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
2251 // Set the resourceinterface name
2252 size = strlen(resourceInterfaceName) + 1;
2253 str = (char *) OCMalloc(size);
2257 strncpy(str, resourceInterfaceName, size);
2258 pointer->name = str;
2260 // Bind the resourceinterface to the resource
2261 insertResourceInterface(resource, pointer);
2263 result = OC_STACK_OK;
2265 exit: if (result != OC_STACK_OK) {
2274 * Bind a resourcetype to a resource.
2276 * @param handle - handle to the resource
2277 * @param resourceTypeName - name of resource type. Example: "core.led"
2280 * OC_STACK_OK - no errors
2281 * OC_STACK_ERROR - stack process error
2283 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2284 const char *resourceTypeName) {
2286 OCStackResult result = OC_STACK_ERROR;
2287 OCResource *resource;
2289 // Make sure resource exists
2290 resource = findResource((OCResource *) handle);
2292 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2293 return OC_STACK_ERROR;
2296 // call internal function
2297 result = BindResourceTypeToResource(resource, resourceTypeName);
2299 #ifdef WITH_PRESENCE
2300 if(presenceResource.handle)
2302 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2303 SendPresenceNotification(resource->rsrcType);
2311 * Bind a resourceinterface to a resource.
2313 * @param handle - handle to the resource
2314 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
2317 * OC_STACK_OK - no errors
2318 * OC_STACK_ERROR - stack process error
2321 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2322 const char *resourceInterfaceName) {
2324 OCStackResult result = OC_STACK_ERROR;
2325 OCResource *resource;
2327 // Make sure resource exists
2328 resource = findResource((OCResource *) handle);
2330 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2331 return OC_STACK_ERROR;
2334 // call internal function
2335 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2337 #ifdef WITH_PRESENCE
2338 if(presenceResource.handle)
2340 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2341 SendPresenceNotification(resource->rsrcType);
2349 * Get the number of resources that have been created in the stack.
2351 * @param numResources - pointer to count variable
2354 * OC_STACK_OK - no errors
2355 * OC_STACK_ERROR - stack process error
2358 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
2359 OCResource *pointer = headResource;
2361 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2362 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2365 *numResources = *numResources + 1;
2366 pointer = pointer->next;
2372 * Get a resource handle by index.
2374 * @param index - index of resource, 0 to Count - 1
2377 * Resource handle - if found
2378 * NULL - if not found
2380 OCResourceHandle OCGetResourceHandle(uint8_t index) {
2381 OCResource *pointer = headResource;
2384 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2386 // Iterate through the list
2387 while ((i < index) && pointer) {
2389 pointer = pointer->next;
2391 return (OCResourceHandle) pointer;
2395 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
2398 * @param handle - handle of resource to be deleted
2401 * OC_STACK_OK - no errors
2402 * OC_STACK_ERROR - stack process error
2403 * OC_STACK_NO_RESOURCE - resource not found
2404 * OC_STACK_INVALID_PARAM - invalid param
2406 OCStackResult OCDeleteResource(OCResourceHandle handle) {
2407 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2410 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2411 return OC_STACK_INVALID_PARAM;
2414 OCResource *resource = findResource((OCResource *) handle);
2415 if (resource == NULL) {
2416 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2417 return OC_STACK_NO_RESOURCE;
2420 if (deleteResource((OCResource *) handle) == 0) {
2421 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2422 return OC_STACK_ERROR;
2429 * Get the URI of the resource specified by handle.
2431 * @param handle - handle of resource
2433 * URI string - if resource found
2434 * NULL - resource not found
2436 const char *OCGetResourceUri(OCResourceHandle handle) {
2437 OCResource *resource;
2438 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2440 resource = findResource((OCResource *) handle);
2442 return resource->uri;
2444 return (const char *) NULL;
2448 * Get the properties of the resource specified by handle.
2449 * NOTE: that after a resource is created, the OC_ACTIVE property is set
2450 * for the resource by the stack.
2452 * @param handle - handle of resource
2454 * property bitmap - if resource found
2455 * NULL - resource not found
2457 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
2458 OCResource *resource;
2459 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2461 resource = findResource((OCResource *) handle);
2463 return resource->resourceProperties;
2469 * Get the number of resource types of the resource.
2471 * @param handle - handle of resource
2472 * @param numResourceTypes - pointer to count variable
2475 * OC_STACK_OK - no errors
2476 * OC_STACK_ERROR - stack process error
2478 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2479 uint8_t *numResourceTypes) {
2480 OCResource *resource;
2481 OCResourceType *pointer;
2483 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2484 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2485 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2487 *numResourceTypes = 0;
2489 resource = findResource((OCResource *) handle);
2491 pointer = resource->rsrcType;
2493 *numResourceTypes = *numResourceTypes + 1;
2494 pointer = pointer->next;
2501 * Get name of resource type of the resource.
2503 * @param handle - handle of resource
2504 * @param index - index of resource, 0 to Count - 1
2507 * resource type name - if resource found
2508 * NULL - resource not found
2510 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
2511 OCResourceType *resourceType;
2513 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2515 resourceType = findResourceTypeAtIndex(handle, index);
2517 return resourceType->resourcetypename;
2519 return (const char *) NULL;
2525 * Get the number of resource interfaces of the resource.
2527 * @param handle - handle of resource
2528 * @param numResources - pointer to count variable
2531 * OC_STACK_OK - no errors
2532 * OC_STACK_ERROR - stack process error
2534 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2535 uint8_t *numResourceInterfaces) {
2536 OCResourceInterface *pointer;
2537 OCResource *resource;
2539 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2541 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2542 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2544 *numResourceInterfaces = 0;
2545 resource = findResource((OCResource *) handle);
2547 pointer = resource->rsrcInterface;
2549 *numResourceInterfaces = *numResourceInterfaces + 1;
2550 pointer = pointer->next;
2557 * Get name of resource interface of the resource.
2559 * @param handle - handle of resource
2560 * @param index - index of resource, 0 to Count - 1
2563 * resource interface name - if resource found
2564 * NULL - resource not found
2566 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
2567 OCResourceInterface *resourceInterface;
2569 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2571 resourceInterface = findResourceInterfaceAtIndex(handle, index);
2572 if (resourceInterface) {
2573 return resourceInterface->name;
2575 return (const char *) NULL;
2579 * Get resource handle from the collection resource by index.
2581 * @param collectionHandle - handle of collection resource
2582 * @param index - index of contained resource, 0 to Count - 1
2585 * handle to resource - if resource found
2586 * NULL - resource not found
2588 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2590 OCResource *resource;
2592 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2594 if (index >= MAX_CONTAINED_RESOURCES) {
2598 resource = findResource((OCResource *) collectionHandle);
2603 return resource->rsrcResources[index];
2607 * Bind an entity handler to the resource.
2609 * @param handle - handle to the resource that the contained resource is to be bound
2610 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2612 * OC_STACK_OK - no errors
2613 * OC_STACK_ERROR - stack process error
2615 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2616 OCEntityHandler entityHandler) {
2617 OCResource *resource;
2619 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2621 // Validate parameters
2622 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2623 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2625 // Use the handle to find the resource in the resource linked list
2626 resource = findResource((OCResource *)handle);
2628 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2629 return OC_STACK_ERROR;
2633 resource->entityHandler = entityHandler;
2635 #ifdef WITH_PRESENCE
2636 if(presenceResource.handle)
2638 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2639 SendPresenceNotification(resource->rsrcType);
2647 * Get the entity handler for a resource.
2649 * @param handle - handle of resource
2652 * entity handler - if resource found
2653 * NULL - resource not found
2655 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
2656 OCResource *resource;
2658 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2660 // Use the handle to find the resource in the resource linked list
2661 resource = findResource((OCResource *)handle);
2663 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2668 return resource->entityHandler;
2671 void incrementSequenceNumber(OCResource * resPtr)
2673 // Increment the sequence number
2674 resPtr->sequenceNum += 1;
2675 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2677 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2683 * Notify Presence subscribers that a resource has been modified
2685 * @param resourceType - Handle to the resourceType linked list of resource
2686 * that was modified.
2687 * @param qos - Quality Of Service
2690 #ifdef WITH_PRESENCE
2691 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
2693 OCResource *resPtr = NULL;
2694 OCStackResult result;
2695 OCMethod method = OC_REST_PRESENCE;
2696 uint32_t maxAge = 0;
2697 resPtr = findResource((OCResource *) presenceResource.handle);
2700 return OC_STACK_NO_RESOURCE;
2702 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
2704 maxAge = presenceResource.presenceTTL;
2711 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
2714 #endif // WITH_PRESENCE
2716 * Notify observers that an observed value has changed.
2718 * @param handle - handle of resource
2721 * OC_STACK_OK - no errors
2722 * OC_STACK_NO_RESOURCE - invalid resource handle
2723 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
2725 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
2727 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2729 OCResource *resPtr = NULL;
2730 OCStackResult result;
2731 OCMethod method = OC_REST_NOMETHOD;
2732 uint32_t maxAge = 0;
2734 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2735 #ifdef WITH_PRESENCE
2736 if(handle == presenceResource.handle)
2740 #endif // WITH_PRESENCE
2741 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2743 // Verify that the resource exists
2744 resPtr = findResource ((OCResource *) handle);
2747 return OC_STACK_NO_RESOURCE;
2751 //only increment in the case of regular observing (not presence)
2752 incrementSequenceNumber(resPtr);
2753 method = OC_REST_OBSERVE;
2754 maxAge = MAX_OBSERVE_AGE;
2755 #ifdef WITH_PRESENCE
2756 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
2758 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
2765 OCNotifyListOfObservers (OCResourceHandle handle,
2766 OCObservationId *obsIdList,
2767 uint8_t numberOfIds,
2768 unsigned char *notificationJSONPayload,
2769 OCQualityOfService qos)
2771 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
2773 OCResource *resPtr = NULL;
2774 //TODO: we should allow the server to define this
2775 uint32_t maxAge = MAX_OBSERVE_AGE;
2777 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2778 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
2779 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
2781 // Verify that the resource exists
2782 resPtr = findResource ((OCResource *) handle);
2783 if (NULL == resPtr || myStackMode == OC_CLIENT)
2785 return OC_STACK_NO_RESOURCE;
2789 incrementSequenceNumber(resPtr);
2791 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
2792 notificationJSONPayload, maxAge, qos));
2796 * Send a response to a request.
2797 * The response can be a regular, slow, or block (i.e. a response that
2798 * is too large to be sent in a single PDU and must span multiple transmissions)
2800 * @param response - pointer to structure that contains response parameters
2803 * OC_STACK_OK - No errors; Success
2804 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
2805 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
2806 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
2807 * persistent response buffer is necessary
2809 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
2811 OCStackResult result = OC_STACK_ERROR;
2812 OCServerRequest *serverRequest = NULL;
2814 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
2816 // Validate input parameters
2817 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
2818 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
2820 // TODO: Placeholder for creating a response entry when implementing
2821 // block transfer feature
2823 // If a response payload is present, check if block transfer is required
2824 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
2825 (const char *)ehResponse->payload, ehResponse->payloadSize))
2827 OC_LOG(INFO, TAG, PCF("Block transfer required"));
2829 // Persistent response buffer is needed for block transfer
2830 if (!ehResponse->persistentBufferFlag)
2832 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
2833 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
2835 // TODO: Placeholder for block transfer handling
2836 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
2837 // when implementing the block transfer feature
2842 // Get pointer to request info
2843 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
2846 result = serverRequest->ehResponseHandler(ehResponse);
2853 * Cancel a response. Applies to a block response
2855 * @param responseHandle - response handle set by stack in OCServerResponse after
2856 * OCDoResponse is called
2859 * OC_STACK_OK - No errors; Success
2860 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
2862 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
2864 OCStackResult result = OC_STACK_NOTIMPL;
2866 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
2868 // TODO: validate response handle
2873 //-----------------------------------------------------------------------------
2874 // Private internal function definitions
2875 //-----------------------------------------------------------------------------
2877 * Generate handle of OCDoResource invocation for callback management.
2879 static OCDoHandle GenerateInvocationHandle()
2881 OCDoHandle handle = NULL;
2882 // Generate token here, it will be deleted when the transaction is deleted
2883 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2886 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2891 #ifdef WITH_PRESENCE
2892 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
2893 OCResourceProperty resourceProperties, uint8_t enable)
2895 if (resourceProperties
2896 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
2897 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2898 return OC_STACK_INVALID_PARAM;
2902 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
2906 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
2913 * Initialize resource data structures, variables, etc.
2915 OCStackResult initResources() {
2916 OCStackResult result = OC_STACK_OK;
2917 // Init application resource vars
2918 headResource = NULL;
2919 // Init Virtual Resources
2920 #ifdef WITH_PRESENCE
2921 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
2922 //presenceResource.token = OCGenerateCoAPToken();
2923 result = OCCreateResource(&presenceResource.handle,
2924 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
2929 //make resource inactive
2930 result = OCChangeResourceProperty(
2931 &(((OCResource *) presenceResource.handle)->resourceProperties),
2938 * Add a resource to the end of the linked list of resources.
2940 * @param resource - resource to be added
2942 void insertResource(OCResource *resource) {
2943 OCResource *pointer;
2945 if (!headResource) {
2946 headResource = resource;
2948 pointer = headResource;
2950 while (pointer->next) {
2951 pointer = pointer->next;
2953 pointer->next = resource;
2955 resource->next = NULL;
2959 * Find a resource in the linked list of resources.
2961 * @param resource - resource to be found
2963 * NULL - resource not found
2964 * pointer to resource - pointer to resource that was found in the linked list
2966 OCResource *findResource(OCResource *resource) {
2967 OCResource *pointer = headResource;
2970 if (pointer == resource) {
2973 pointer = pointer->next;
2978 void deleteAllResources()
2980 OCResource *pointer = headResource;
2985 temp = pointer->next;
2986 #ifdef WITH_PRESENCE
2987 if(pointer != (OCResource *) presenceResource.handle)
2989 #endif // WITH_PRESENCE
2990 deleteResource(pointer);
2991 #ifdef WITH_PRESENCE
2993 #endif // WITH_PRESENCE
2997 #ifdef WITH_PRESENCE
2998 // Ensure that the last resource to be deleted is the presence resource. This allows for all
2999 // presence notification attributed to their deletion to be processed.
3000 deleteResource((OCResource *) presenceResource.handle);
3001 #endif // WITH_PRESENCE
3005 * Delete the resource from the linked list.
3007 * @param resource - resource to be deleted
3012 int deleteResource(OCResource *resource) {
3013 OCResource *prev = NULL;
3016 temp = headResource;
3018 if (temp == resource) {
3019 // Invalidate all Resource Properties.
3020 resource->resourceProperties = (OCResourceProperty) 0;
3021 #ifdef WITH_PRESENCE
3022 if(resource != (OCResource *) presenceResource.handle)
3024 #endif // WITH_PRESENCE
3025 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3026 #ifdef WITH_PRESENCE
3029 if(presenceResource.handle)
3031 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3032 if(resource != (OCResource *) presenceResource.handle)
3034 SendPresenceNotification(resource->rsrcType);
3038 SendPresenceNotification(NULL);
3043 if (temp == headResource) {
3044 headResource = temp->next;
3046 prev->next = temp->next;
3049 deleteResourceElements(temp);
3062 * Delete all of the dynamically allocated elements that were created for the resource.
3064 * @param resource - specified resource
3066 void deleteResourceElements(OCResource *resource) {
3072 OCFree(resource->uri);
3074 // Delete resourcetype linked list
3075 deleteResourceType(resource->rsrcType);
3077 // Delete resourceinterface linked list
3078 deleteResourceInterface(resource->rsrcInterface);
3082 * Delete all of the dynamically allocated elements that were created for the resource type.
3084 * @param resourceType - specified resource type
3086 void deleteResourceType(OCResourceType *resourceType) {
3087 OCResourceType *pointer = resourceType;
3088 OCResourceType *next;
3091 next = pointer->next;
3092 OCFree(pointer->resourcetypename);
3099 * Delete all of the dynamically allocated elements that were created for the resource interface.
3101 * @param resourceInterface - specified resource interface
3103 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
3104 OCResourceInterface *pointer = resourceInterface;
3105 OCResourceInterface *next;
3108 next = pointer->next;
3109 OCFree(pointer->name);
3116 * Insert a resource type into a resource's resource type linked list.
3118 * @param resource - resource where resource type is to be inserted
3119 * @param resourceType - resource type to be inserted
3121 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
3122 OCResourceType *pointer;
3124 if (resource && !resource->rsrcType) {
3125 resource->rsrcType = resourceType;
3129 pointer = resource->rsrcType;
3133 pointer = resourceType;
3135 while (pointer->next) {
3136 pointer = pointer->next;
3138 pointer->next = resourceType;
3140 resourceType->next = NULL;
3144 * Get a resource type at the specified index within a resource.
3146 * @param handle - handle of resource
3147 * @param index - index of resource type
3150 * resourcetype - if found
3153 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
3154 OCResource *resource;
3155 OCResourceType *pointer;
3158 // Find the specified resource
3159 resource = findResource((OCResource *) handle);
3164 // Make sure a resource has a resourcetype
3165 if (!resource->rsrcType) {
3169 // Iterate through the list
3170 pointer = resource->rsrcType;
3172 while ((i < index) && pointer) {
3174 pointer = pointer->next;
3180 * Finds a resource type in an OCResourceType link-list.
3182 * @param resourceTypeList - the link-list to be searched through
3183 * @param resourceTypeName - the key to search for
3186 * resourceType that matches the key (ie. resourceTypeName)
3187 * NULL - either an invalid parameter or this function was unable to find the key.
3189 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3191 if(resourceTypeList && resourceTypeName)
3193 OCResourceType * rtPointer = resourceTypeList;
3194 while(resourceTypeName && rtPointer)
3196 if(rtPointer->resourcetypename &&
3197 strcmp(resourceTypeName, (const char *)
3198 (rtPointer->resourcetypename)) == 0)
3202 rtPointer = rtPointer->next;
3209 * Insert a resource interface into a resource's resource interface linked list.
3211 * @param resource - resource where resource interface is to be inserted
3212 * @param resourceInterface - resource interface to be inserted
3214 void insertResourceInterface(OCResource *resource,
3215 OCResourceInterface *resourceInterface) {
3216 OCResourceInterface *pointer;
3218 if (!resource->rsrcInterface) {
3219 resource->rsrcInterface = resourceInterface;
3221 pointer = resource->rsrcInterface;
3222 while (pointer->next) {
3223 pointer = pointer->next;
3225 pointer->next = resourceInterface;
3227 resourceInterface->next = NULL;
3231 * Get a resource interface at the specified index within a resource.
3233 * @param handle - handle of resource
3234 * @param index - index of resource interface
3237 * resourceinterface - if found
3240 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3242 OCResource *resource;
3243 OCResourceInterface *pointer;
3246 // Find the specified resource
3247 resource = findResource((OCResource *) handle);
3252 // Make sure a resource has a resourceinterface
3253 if (!resource->rsrcInterface) {
3257 // Iterate through the list
3258 pointer = resource->rsrcInterface;
3260 while ((i < index) && pointer) {
3262 pointer = pointer->next;
3268 * Determine if a request/response must be sent in a block transfer because it is too large to be
3269 * sent in a single PDU. This function can be used for either a request or a response
3271 * @param request - NULL or pointer to request
3272 * @param response - NULL or pointer to response
3273 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
3274 * the length of the request/response
3277 * 0 - packet transfer NOT required (i.e. normal request/response)
3278 * 1 - packet transfer required (i.e. block transfer needed)
3280 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
3284 // Determine if we are checking a request or a response
3287 // If size is greater than 0, use it for the request size value, otherwise
3288 // assume request is null terminated and use strlen for size value
3289 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
3296 // If size is greater than 0, use it for the response size value, otherwise
3297 // assume response is null terminated and use strlen for size value
3298 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3307 * Retrieves a resource type based upon a query ontains only just one
3308 * resource attribute (and that has to be of type "rt").
3310 * @remark This API malloc's memory for the resource type. Do not malloc resourceType
3311 * before passing in.
3313 * @param query - The quert part of the URI
3314 * @param resourceType - The resource type to be populated; pass by reference.
3317 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
3318 * OC_STACK_OK - Success
3320 OCStackResult getResourceType(const char * query, unsigned char** resourceType)
3324 return OC_STACK_INVALID_PARAM;
3327 OCStackResult result = OC_STACK_ERROR;
3329 if(strncmp(query, "rt=", 3) == 0)
3331 *resourceType = (unsigned char *) OCMalloc(strlen(query)-3);
3334 result = OC_STACK_NO_MEMORY;
3337 strcpy((char *)*resourceType, ((const char *)&query[3]));
3338 result = OC_STACK_OK;
3344 OCStackResult getQueryFromUri(const char * uri, unsigned char** query, char ** newURI)
3348 return OC_STACK_INVALID_URI;
3350 if(!query || !newURI)
3352 return OC_STACK_INVALID_PARAM;
3354 char * leftToken = NULL;
3355 char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3360 strcpy(tempURI, uri);
3362 leftToken = strtok_r((char *)tempURI, "?", &strTokPtr);
3364 //TODO-CA: This could be simplified. Clean up required.
3365 while(leftToken != NULL)
3367 if(strncmp(leftToken, "rt=", 3) == 0 || strncmp(leftToken, "if=", 3) == 0)
3369 *query = (unsigned char *) OCMalloc(strlen(leftToken));
3374 strcpy((char *)*query, ((const char *)&leftToken[0]));
3377 leftToken = strtok_r(NULL, "?", &strTokPtr);
3385 return OC_STACK_NO_MEMORY;
3388 const ServerID OCGetServerInstanceID(void)
3390 static bool generated = false;
3391 static ServerID sid;
3398 sid = OCGetRandom();
3403 const char* OCGetServerInstanceIDString(void)
3405 // max printed length of a base 10
3406 // uint32 is 10 characters, so 11 includes null.
3407 // This will change as the representation gets switched
3409 static char buffer[11];
3410 int n = sprintf(buffer, "%u", OCGetServerInstanceID());