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 //-----------------------------------------------------------------------------
26 #include "ocstackinternal.h"
27 #include "ocresourcehandler.h"
28 #include "occlientcb.h"
29 #include "ocobserve.h"
34 #include "ocserverrequest.h"
38 #include "cainterface.h"
41 //-----------------------------------------------------------------------------
43 //-----------------------------------------------------------------------------
45 OC_STACK_UNINITIALIZED = 0, OC_STACK_INITIALIZED
50 OC_PRESENCE_UNINITIALIZED = 0, OC_PRESENCE_INITIALIZED
54 //-----------------------------------------------------------------------------
56 //-----------------------------------------------------------------------------
57 static OCStackState stackState = OC_STACK_UNINITIALIZED;
59 OCResource *headResource = NULL;
61 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
62 static PresenceResource presenceResource;
63 uint8_t PresenceTimeOutSize = 0;
64 uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
68 OCDeviceEntityHandler defaultDeviceHandler;
70 //-----------------------------------------------------------------------------
72 //-----------------------------------------------------------------------------
73 #define TAG PCF("OCStack")
74 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
75 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
76 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
77 TAG, PCF(#arg " is NULL")); return (retVal); } }
78 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
81 //TODO: we should allow the server to define this
82 #define MAX_OBSERVE_AGE (0x2FFFFUL)
84 //-----------------------------------------------------------------------------
86 //-----------------------------------------------------------------------------
87 extern void DeinitOCSecurityInfo();
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
95 OCStackResult OCStackFeedBack(OCCoAPToken * token, uint8_t status)
97 OCStackResult result = OC_STACK_ERROR;
98 ResourceObserver * observer = NULL;
99 OCEntityHandlerRequest ehRequest = {0};
103 case OC_OBSERVER_NOT_INTERESTED:
104 OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
105 observer = GetObserverUsingToken (token);
108 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
109 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
110 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
111 if(result != OC_STACK_OK)
115 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
117 //observer is not observing anymore
118 result = DeleteObserverUsingToken (token);
119 if(result == OC_STACK_OK)
121 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
125 result = OC_STACK_OK;
126 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
129 case OC_OBSERVER_STILL_INTERESTED:
130 //observer is still interested
131 OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
132 notifications, reset the failedCount"));
133 observer = GetObserverUsingToken(token);
136 observer->forceHighQos = 0;
137 observer->failedCommCount = 0;
138 result = OC_STACK_OK;
142 result = OC_STACK_OBSERVER_NOT_FOUND;
145 case OC_OBSERVER_FAILED_COMM:
146 //observer is not reachable
147 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
148 observer = GetObserverUsingToken(token);
151 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
153 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
154 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
155 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
156 if(result != OC_STACK_OK)
158 return OC_STACK_ERROR;
160 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
161 //observer is unreachable
162 result = DeleteObserverUsingToken (token);
163 if(result == OC_STACK_OK)
165 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
169 result = OC_STACK_OK;
170 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
175 observer->failedCommCount++;
176 result = OC_STACK_CONTINUE;
178 observer->forceHighQos = 1;
179 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
183 OC_LOG(ERROR, TAG, PCF("Unknown status"));
184 result = OC_STACK_ERROR;
191 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
193 OCStackResult ret = OC_STACK_ERROR;
201 ret = OC_STACK_RESOURCE_CREATED;
204 ret = OC_STACK_RESOURCE_DELETED;
207 ret = OC_STACK_INVALID_QUERY;
210 ret = OC_STACK_INVALID_OPTION;
213 ret = OC_STACK_NO_RESOURCE;
221 //This function will be called back by CA layer when a response is received
222 void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
224 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
225 printf ("Received payload: %s\n", (char *)responseInfo->info.payload);
226 OCStackApplicationResult result = OC_STACK_DELETE_TRANSACTION;
227 ClientCB *cbNode = GetClientCB((CAToken_t *)&responseInfo->info.token, NULL, NULL);
230 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
231 OCClientResponse response;
232 struct sockaddr_in sa;
234 inet_pton(AF_INET, endPoint->addressInfo.IP.ipAddress, &(sa.sin_addr));
235 sa.sin_port = htons(endPoint->addressInfo.IP.port);
236 static OCDevAddr address;
237 memcpy((void*)&address.addr, &(sa), sizeof(sa));
238 response.addr = &address;
239 response.result = CAToOCStackResult(responseInfo->result);
240 response.resJSONPayload = (unsigned char*)responseInfo->info.payload;
241 response.numRcvdVendorSpecificHeaderOptions = 0;
242 if(responseInfo->info.numOptions > 0)
244 //First option alwas with option ID COAP_OPTION_OBSERVE if it is availbale
245 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
247 memcpy (&(response.sequenceNumber),
248 &(responseInfo->info.options[0].optionData), 4);
252 memcpy (&(response.rcvdVendorSpecificHeaderOptions[0]),
253 &(responseInfo->info.options[0]), sizeof(OCHeaderOption));
255 for (uint8_t i = 1; i < responseInfo->info.numOptions; i++)
257 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i]),
258 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
260 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
262 result = cbNode->callBack(cbNode->context,
263 cbNode->handle, &response);
264 if (result == OC_STACK_DELETE_TRANSACTION)
266 FindAndDeleteClientCB(cbNode);
269 OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload);
270 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
273 //This function will be called back by CA layer when a request is received
274 void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
276 CAInfo_t responseData;
277 CAResponseInfo_t responseInfo;
278 OCStackResult requestResult = OC_STACK_ERROR;
280 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
283 if(myStackMode == OC_CLIENT)
285 //TODO: should the client be responding to requests?
289 OCServerProtocolRequest serverRequest;
291 memset (&serverRequest, 0, sizeof(OCServerProtocolRequest));
292 // copy URI of resource
293 memcpy (&(serverRequest.resourceUrl), endPoint->resourceUri, strlen(endPoint->resourceUri));
295 // TODO-CA: Is the query part of header option?
296 //copy request payload
297 if (requestInfo->info.payload)
299 serverRequest.reqTotalSize = strlen(requestInfo->info.payload) + 1;
300 memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
301 strlen(requestInfo->info.payload));
305 serverRequest.reqTotalSize = 1;
308 switch (requestInfo->method)
312 serverRequest.method = OC_REST_GET;
317 serverRequest.method = OC_REST_PUT;
322 serverRequest.method = OC_REST_POST;
327 serverRequest.method = OC_REST_DELETE;
332 OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
338 OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d", strlen(requestInfo->info.token));
339 OC_LOG_BUFFER(INFO, TAG, requestInfo->info.token, strlen(requestInfo->info.token));
340 // TODO-CA: For CA integration currently copying CAToken to OCCoapToken:
341 // Need to remove OCCoapToken
342 memcpy (&(serverRequest.requestToken.token), requestInfo->info.token,
343 strlen(requestInfo->info.token));
344 serverRequest.requestToken.tokenLength = strlen(requestInfo->info.token);
345 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
346 if (requestInfo->info.type == CA_MSG_CONFIRM)
348 serverRequest.qos = OC_HIGH_QOS;
350 else if (requestInfo->info.type == CA_MSG_NONCONFIRM)
352 serverRequest.qos = OC_LOW_QOS;
354 else if (requestInfo->info.type == CA_MSG_ACKNOWLEDGE)
356 // TODO-CA: Need to handle this
358 else if (requestInfo->info.type == CA_MSG_RESET)
360 // TODO-CA: Need to handle this
362 // CA does not need the following 3 fields
363 serverRequest.coapID = 0;
364 serverRequest.delayedResNeeded = 0;
365 serverRequest.secured = 0;
368 serverRequest.addressInfo = endPoint->addressInfo;
369 serverRequest.connectivityType = endPoint->connectivityType;
370 if (requestInfo->info.token)
372 strncpy(serverRequest.token, requestInfo->info.token, sizeof(serverRequest.token) - 1);
375 struct sockaddr_in sa;
376 inet_pton(AF_INET, endPoint->addressInfo.IP.ipAddress, &(sa.sin_addr));
377 sa.sin_port = htons(endPoint->addressInfo.IP.port);
378 memcpy((void*)&serverRequest.requesterAddr, &(sa), sizeof(sa));
380 // copy vendor specific header options
381 // TODO-CA: CA is including non-vendor header options as well, like observe.
382 // Need to filter those out
383 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
385 // TODO-CA: Need to send an error indicating the num of options is incorrect
388 serverRequest.numRcvdVendorSpecificHeaderOptions = requestInfo->info.numOptions;
389 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
391 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
392 sizeof(CAHeaderOption_t)*requestInfo->info.numOptions);
395 requestResult = HandleStackRequests (&serverRequest);
399 // generate the pdu, if the request was CON, then the response is ACK, otherwire NON
400 memset(&responseData, 0, sizeof(CAInfo_t));
401 responseData.token = (requestInfo != NULL) ? requestInfo->info.token : "";
403 // TODO : I guess we need to allocate memeory?
404 responseData.payload = "{\"oc\":[{\"href\":\"/a/led\",\"sid\":\"\",\"prop\":{\"rt\":[\"core.led\"],\"if\":[\"oc.mi.def\"],\"obs\":1}}]}";
406 //responseInfo = (CAResponseInfo*) malloc(sizeof(CAResponseInfo));
407 memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
408 responseInfo.result = 200;
409 responseInfo.info = responseData;
411 // send request (connectivityType from remoteEndpoint of request Info)
412 OC_LOG(INFO, TAG, PCF("CASendResponse in HandleCARequests"));
413 //TODO-CA: CASendResponse returns the result (we need to check if the
415 CAResult_t caResult = CASendResponse(endPoint, &responseInfo);
416 if(caResult != CA_STATUS_OK)
418 OC_LOG(ERROR, TAG, PCF("CASendResponse error"));
422 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
427 //This function will be called back by occoap layer when a request is received
428 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
430 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
432 OCStackResult result = OC_STACK_ERROR;
433 ResourceHandling resHandling;
434 OCResource *resource;
436 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
439 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
441 result = AddServerCARequest(&request, protocolRequest->coapID,
442 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
443 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
444 protocolRequest->observationOption, protocolRequest->qos,
445 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
446 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
447 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
448 protocolRequest->reqTotalSize,
449 &protocolRequest->addressInfo, protocolRequest->connectivityType, protocolRequest->token);
451 result = AddServerRequest(&request, protocolRequest->coapID,
452 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
453 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
454 protocolRequest->observationOption, protocolRequest->qos,
455 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
456 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
457 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
458 protocolRequest->reqTotalSize);
460 if (OC_STACK_OK != result)
462 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
465 VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
467 if(!protocolRequest->reqMorePacket)
469 request->requestComplete = 1;
474 OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
477 if(request->requestComplete)
479 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
480 result = DetermineResourceHandling (request, &resHandling, &resource);
481 if (result == OC_STACK_OK)
483 result = ProcessRequest(resHandling, resource, request);
487 result = OC_STACK_ERROR;
492 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
493 result = OC_STACK_CONTINUE;
498 //This function will be called back by occoap layer when a response is received
499 OCStackResult HandleStackResponses(OCResponse * response)
501 OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)"));
502 OCStackResult result = OC_STACK_OK;
503 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
504 uint8_t isObserveNotification = 0;
505 ClientCB * cbNode = NULL;
507 uint8_t isPresenceNotification = 0;
508 uint8_t isMulticastPresence = 0;
509 char * resourceTypeName = NULL;
510 uint32_t lowerBound = 0;
511 uint32_t higherBound = 0;
513 unsigned char * bufRes = response->bufRes;
514 #endif // WITH_PRESENCE
516 cbNode = response->cbNode;
519 cbNode = GetClientCB(response->rcvdToken, NULL, NULL);
522 if(response->clientResponse->sequenceNumber >= OC_OFFSET_SEQUENCE_NUMBER)
524 isObserveNotification = 1;
525 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
528 OC_LOG_V(DEBUG, TAG, "The sequenceNumber/NONCE of this response %u",
529 response->clientResponse->sequenceNumber);
530 OC_LOG_V(DEBUG, TAG, "The maxAge/TTL of this response %u", response->maxAge);
531 OC_LOG_V(DEBUG, TAG, "The response received is %s", bufRes);
534 if(!strcmp((char *)response->rcvdUri, (char *)OC_PRESENCE_URI)){
535 isPresenceNotification = 1;
538 result = OC_STACK_INVALID_PARAM;
541 tok = strtok((char *)bufRes, "[:]}");
542 bufRes[strlen((char *)bufRes)] = ':';
543 tok = strtok(NULL, "[:]}");
544 bufRes[strlen((char *)bufRes)] = ':';
545 response->clientResponse->sequenceNumber = (uint32_t )atoi(tok);
546 OC_LOG_V(DEBUG, TAG, "The received NONCE is %u", response->clientResponse->sequenceNumber);
547 tok = strtok(NULL, "[:]}");
548 response->maxAge = (uint32_t )atoi(tok);
549 OC_LOG_V(DEBUG, TAG, "The received TTL is %u", response->maxAge);
550 tok = strtok(NULL, "[:]}");
553 resourceTypeName = (char *)OCMalloc(strlen(tok));
554 if(!resourceTypeName)
558 bufRes[strlen((char *)bufRes)] = ':';
559 strcpy(resourceTypeName, tok);
560 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
563 bufRes[strlen((char *)bufRes)] = ']';
566 // Check if the application subcribed for presence
569 cbNode = GetClientCB(NULL, NULL, response->fullUri);
572 // Check if application subscribed for multicast presence
575 snprintf((char *)response->fullUri, MAX_URI_LENGTH, "%s%s",
576 OC_MULTICAST_IP, response->rcvdUri);
577 cbNode = GetClientCB(NULL, NULL, response->fullUri);
580 isMulticastPresence = 1;
581 isPresenceNotification = 0;
585 if(cbNode && isPresenceNotification)
587 OC_LOG(INFO, TAG, PCF("Received a presence notification"));
588 if(!cbNode->presence)
590 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
591 VERIFY_NON_NULL_V(cbNode->presence);
592 cbNode->presence->timeOut = NULL;
593 cbNode->presence->timeOut = (uint32_t *)
594 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
595 if(!(cbNode->presence->timeOut)){
596 OCFree(cbNode->presence);
597 result = OC_STACK_NO_MEMORY;
600 if(response->maxAge == 0)
602 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
603 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
606 OCFree(cbNode->presence->timeOut);
607 OCFree(cbNode->presence);
608 cbNode->presence = NULL;
613 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %d", GetTime(0));
614 cbNode->presence->TTL = response->maxAge;
615 for(int index = 0; index < PresenceTimeOutSize; index++)
617 lowerBound = GetTime(((float)(PresenceTimeOut[index])
618 /(float)100)*(float)cbNode->presence->TTL);
619 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
620 /(float)100)*(float)cbNode->presence->TTL);
621 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
622 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
623 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
624 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
625 cbNode->presence->timeOut[index]);
627 cbNode->presence->TTLlevel = 0;
628 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
629 if(cbNode->sequenceNumber == response->clientResponse->sequenceNumber)
631 OC_LOG(INFO, TAG, PCF("===============No presence change"));
634 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
635 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;;
638 // Ensure that a filter is actually applied.
639 if(resourceTypeName && cbNode->filterResourceType)
641 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
647 else if(cbNode && isMulticastPresence)
649 // Check if the same nonce for a given host
650 OCMulticastNode* mcNode = NULL;
651 mcNode = GetMCPresenceNode(response->fullUri);
653 if(response->maxAge == 0)
655 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
656 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
659 OCFree(cbNode->presence->timeOut);
660 OCFree(cbNode->presence);
661 cbNode->presence = NULL;
664 else if(mcNode != NULL)
666 if(mcNode->nonce == response->clientResponse->sequenceNumber)
668 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
669 result = OC_STACK_NO_MEMORY;
672 mcNode->nonce = response->clientResponse->sequenceNumber;
676 uint32_t uriLen = strlen((char*)response->fullUri);
677 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
680 memcpy(uri, response->fullUri, (uriLen + 1));
685 PCF("===============No Memory for URI to store in the presence node"));
686 result = OC_STACK_NO_MEMORY;
689 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri,
690 response->clientResponse->sequenceNumber);
691 if(result == OC_STACK_NO_MEMORY)
694 PCF("===============No Memory for Multicast Presence Node"));
695 result = OC_STACK_NO_MEMORY;
700 // Ensure that a filter is actually applied.
701 if(resourceTypeName && cbNode->filterResourceType)
703 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
710 else if(!cbNode && isPresenceNotification)
712 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
713 ------------ ignoring"));
715 #endif // WITH_PRESENCE
719 if(isObserveNotification)
721 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
722 //TODO: check the standard for methods to detect wrap around condition
723 if(cbNode->method == OC_REST_OBSERVE &&
724 (response->clientResponse->sequenceNumber <= cbNode->sequenceNumber ||
725 (response->clientResponse->sequenceNumber > cbNode->sequenceNumber &&
726 response->clientResponse->sequenceNumber ==
727 MAX_SEQUENCE_NUMBER)))
729 OC_LOG_V(DEBUG, TAG, "Observe notification came out of order. \
730 Ignoring Incoming:%d Against Current:%d.",
731 response->clientResponse->sequenceNumber, cbNode->sequenceNumber);
734 if(response->clientResponse->sequenceNumber > cbNode->sequenceNumber){
735 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;
739 response->clientResponse->resJSONPayload = bufRes;
741 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response->clientResponse);
743 if (cbResult == OC_STACK_DELETE_TRANSACTION ||
744 response->clientResponse->result == OC_STACK_COMM_ERROR ||
745 (response->clientResponse->result == OC_STACK_RESOURCE_DELETED &&
746 !isPresenceNotification && !isMulticastPresence))
748 FindAndDeleteClientCB(cbNode);
753 result = OC_STACK_ERROR;
758 OCFree(resourceTypeName);
763 int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
766 unsigned char *itr, *coap;
767 uint8_t dotCount = 0;
771 /* search for scheme */
773 if (!isdigit((unsigned char) *ipAddrStr))
775 coap = (unsigned char *) OC_COAP_SCHEME;
776 while (*coap && tolower(*itr) == *coap)
785 if (isdigit((unsigned char) *ipAddrStr))
788 ipAddr[index] += *ipAddrStr - '0';
790 else if ((unsigned char) *ipAddrStr == '.')
802 if(*ipAddrStr == ':')
806 if (isdigit((unsigned char) *ipAddrStr))
809 *port += *ipAddrStr - '0';
820 if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
831 //-----------------------------------------------------------------------------
832 // Private internal function prototypes
833 //-----------------------------------------------------------------------------
835 static OCDoHandle GenerateInvocationHandle();
836 static OCStackResult initResources();
837 static void insertResource(OCResource *resource);
838 static OCResource *findResource(OCResource *resource);
839 static void insertResourceType(OCResource *resource,
840 OCResourceType *resourceType);
841 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
843 static void insertResourceInterface(OCResource *resource,
844 OCResourceInterface *resourceInterface);
845 static OCResourceInterface *findResourceInterfaceAtIndex(
846 OCResourceHandle handle, uint8_t index);
847 static void deleteResourceType(OCResourceType *resourceType);
848 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
849 static void deleteResourceElements(OCResource *resource);
850 static int deleteResource(OCResource *resource);
851 static void deleteAllResources();
852 static void incrementSequenceNumber(OCResource * resPtr);
853 static OCStackResult verifyUriQueryLength(const char * inputUri,
855 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
856 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI);
858 //-----------------------------------------------------------------------------
860 //-----------------------------------------------------------------------------
863 * Initialize the OC Stack. Must be called prior to starting the stack.
866 * IP Address of host device
868 * Port of host device
870 * Host device is client, server, or client-server
873 * OC_STACK_OK - no errors
874 * OC_STACK_ERROR - stack init error
876 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
878 OCStackResult result = OC_STACK_ERROR;
879 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
883 OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
887 //It is ok to select network to CA_WIFI for now
888 CAResult_t caResult = CASelectNetwork(CA_WIFI);
889 if(caResult == CA_STATUS_OK)
891 OC_LOG(INFO, TAG, PCF("CASelectNetwork to WIFI"));
892 caResult = CARegisterHandler(HandleCARequests, HandleCAResponses);
893 if(caResult == CA_STATUS_OK)
895 OC_LOG(INFO, TAG, PCF("CARegisterHandler..."));
896 stackState = OC_STACK_INITIALIZED;
897 result = OC_STACK_OK;
901 caResult = CAStartDiscoveryServer();
902 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
905 caResult = CAStartListeningServer();
906 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
908 case OC_CLIENT_SERVER:
909 caResult = CAStartListeningServer();
910 if(caResult == CA_STATUS_OK)
912 caResult = CAStartDiscoveryServer();
914 OC_LOG(INFO, TAG, PCF("Client-server mode"));
917 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
918 return OC_STACK_ERROR;
923 if (caResult == CA_STATUS_OK)
925 result = OC_STACK_OK;
929 result = OC_STACK_ERROR;
936 OC_LOG(INFO, TAG, PCF("Client mode"));
939 OC_LOG(INFO, TAG, PCF("Server mode"));
941 case OC_CLIENT_SERVER:
942 OC_LOG(INFO, TAG, PCF("Client-server mode"));
945 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
946 return OC_STACK_ERROR;
950 // Make call to OCCoAP layer
951 result = OCInitCoAP(ipAddr, (uint16_t) port, myStackMode);
955 defaultDeviceHandler = NULL;
958 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
959 #endif // WITH_PRESENCE
961 if (result == OC_STACK_OK)
963 stackState = OC_STACK_INITIALIZED;
965 // Initialize resource
966 if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
968 result = initResources();
970 if(result != OC_STACK_OK)
972 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
978 * Stop the OC stack. Use for a controlled shutdown.
980 * OC_STACK_OK - no errors
981 * OC_STACK_ERROR - stack not initialized
983 OCStackResult OCStop()
985 OCStackResult result = OC_STACK_ERROR;
987 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
989 if (stackState != OC_STACK_INITIALIZED)
991 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
992 return OC_STACK_ERROR;
996 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
997 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
998 presenceResource.presenceTTL = 0;
999 #endif // WITH_PRESENCE
1001 // Free memory dynamically allocated for resources
1002 deleteAllResources();
1004 // Make call to OCCoAP layer
1005 if (OCStopCoAP() == OC_STACK_OK)
1007 // Remove all observers
1008 DeleteObserverList();
1009 // Remove all the client callbacks
1010 DeleteClientCBList();
1011 stackState = OC_STACK_UNINITIALIZED;
1012 result = OC_STACK_OK;
1014 result = OC_STACK_ERROR;
1017 // Deinit security blob
1018 DeinitOCSecurityInfo();
1020 if (result != OC_STACK_OK) {
1021 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
1028 * Verify the lengths of the URI and the query separately
1030 * @param inputUri - Input URI and query.
1031 * @param uriLen - The length of the initial URI with query.
1033 * Note: The '?' that appears after the URI is not considered as
1034 * a part of the query.
1036 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1040 query = strchr (inputUri, '?');
1044 if((query - inputUri) > MAX_URI_LENGTH)
1046 return OC_STACK_INVALID_URI;
1049 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1051 return OC_STACK_INVALID_QUERY;
1054 else if(uriLen > MAX_URI_LENGTH)
1056 return OC_STACK_INVALID_URI;
1062 * Discover or Perform requests on a specified resource (specified by that Resource's respective URI).
1064 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of calling this API.
1065 * @param method - @ref OCMethod to perform on the resource
1066 * @param requiredUri - URI of the resource to interact with
1067 * @param referenceUri - URI of the reference resource
1068 * @param request - JSON encoded request
1069 * @param qos - quality of service
1070 * @param cbData - struct that contains asynchronous callback function that is invoked
1071 * by the stack when discovery or resource interaction is complete
1072 * @param options - The address of an array containing the vendor specific header
1073 * header options to be sent with the request
1074 * @param numOptions - Number of vendor specific header options to be included
1077 * OC_STACK_OK - no errors
1078 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
1079 * OC_STACK_INVALID_METHOD - invalid resource method
1080 * OC_STACK_INVALID_URI - invalid required or reference URI
1083 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1084 const char *referenceUri, const char *request,
1085 OCQualityOfService qos, OCCallbackData *cbData,
1086 OCHeaderOption * options, uint8_t numOptions)
1088 OCStackResult result = OC_STACK_ERROR;
1090 ClientCB *clientCB = NULL;
1091 unsigned char * requestUri = NULL;
1092 unsigned char * resourceType = NULL;
1093 char * newUri = (char *)requiredUri;
1094 (void) referenceUri;
1096 CARemoteEndpoint_t* endpoint = NULL;
1097 CAResult_t caResult;
1098 CAToken_t caToken = NULL;
1099 CAInfo_t requestData;
1100 CARequestInfo_t requestInfo;
1101 // To track if memory is allocated for additional header options
1102 uint8_t hdrOptionMemAlloc = 0;
1105 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1107 // Validate input parameters
1108 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1109 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1111 TODO ("Need to form the final query by concatenating require and reference URI's");
1112 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
1114 uint16_t uriLen = strlen(requiredUri);
1116 // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS
1122 case OC_REST_DELETE:
1123 case OC_REST_OBSERVE:
1124 case OC_REST_OBSERVE_ALL:
1125 case OC_REST_CANCEL_OBSERVE:
1127 #ifdef WITH_PRESENCE
1128 case OC_REST_PRESENCE:
1132 result = OC_STACK_INVALID_METHOD;
1136 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
1141 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
1143 result = OC_STACK_INVALID_PARAM;
1147 #ifdef WITH_PRESENCE
1148 if(method == OC_REST_PRESENCE)
1150 result = getResourceType(requiredUri, &resourceType, &newUri);
1152 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1156 OC_LOG(DEBUG, TAG, PCF("Got Resource Type is NULL."));
1158 if(result != OC_STACK_OK)
1163 #endif // WITH_PRESENCE
1165 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
1168 memcpy(requestUri, newUri, (uriLen + 1));
1172 result = OC_STACK_NO_MEMORY;
1176 *handle = GenerateInvocationHandle();
1179 result = OC_STACK_NO_MEMORY;
1184 memset(&requestData, 0, sizeof(CAInfo_t));
1185 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1189 case OC_REST_OBSERVE:
1190 case OC_REST_OBSERVE_ALL:
1191 case OC_REST_CANCEL_OBSERVE:
1193 requestInfo.method = CA_GET;
1198 requestInfo.method = CA_PUT;
1203 requestInfo.method = CA_POST;
1206 case OC_REST_DELETE:
1208 requestInfo.method = CA_DELETE;
1211 #ifdef WITH_PRESENCE
1212 case OC_REST_PRESENCE:
1213 //TODO-CA: What should be the CA method?
1217 result = OC_STACK_INVALID_METHOD;
1221 // TODO-CA: Handle multi-cast scenario
1222 // Create remote end point
1223 caResult = CACreateRemoteEndpoint(newUri, CA_WIFI, &endpoint);
1224 // TODO-CA: Connectivity type should be passed to API
1225 endpoint->connectivityType = CA_WIFI;
1226 if (caResult != CA_STATUS_OK)
1228 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1233 caResult = CAGenerateToken(&caToken);
1235 if (caResult != CA_STATUS_OK)
1237 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1242 // TODO-CA: Map QoS to the right CA msg type
1243 requestData.type = CA_MSG_NONCONFIRM;
1244 requestData.token = caToken;
1245 requestData.options = (CAHeaderOption_t*)options;
1246 requestData.numOptions = numOptions;
1247 requestData.payload = (char *)request;
1249 requestInfo.info = requestData;
1252 caResult = CASendRequest(endpoint, &requestInfo);
1253 if (caResult != CA_STATUS_OK)
1255 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1259 if((result = AddClientCB(&clientCB, cbData, &caToken, handle, method,
1260 requestUri, resourceType)) != OC_STACK_OK)
1262 result = OC_STACK_NO_MEMORY;
1268 // Generate token which will be used by OCStack to match responses received
1270 OCGenerateCoAPToken(&token);
1272 if((result = AddClientCB(&clientCB, cbData, &token, handle, method, requestUri, resourceType))
1275 result = OC_STACK_NO_MEMORY;
1279 #ifdef WITH_PRESENCE
1280 if(method == OC_REST_PRESENCE)
1282 // Replacing method type with GET because "presence" is a stack layer only implementation.
1283 method = OC_REST_GET;
1287 // Make call to OCCoAP layer
1288 result = OCDoCoAPResource(method, qos, &token, newUri, request, options, numOptions);
1292 if(newUri != requiredUri)
1296 if (result != OC_STACK_OK)
1298 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1299 FindAndDeleteClientCB(clientCB);
1302 CADestroyRemoteEndpoint(endpoint);
1303 if (hdrOptionMemAlloc)
1305 OCFree(requestData.options);
1307 //TODO-CA: CADestroyToken here
1313 * Cancel a request associated with a specific @ref OCDoResource invocation.
1315 * @param handle - Used to identify a specific OCDoResource invocation.
1316 * @param qos - used to specify Quality of Service (read below for more info)
1317 * @param options- used to specify vendor specific header options when sending
1318 * explicit observe cancellation
1319 * @param numOptions- Number of header options to be included
1322 * OC_STACK_OK - No errors; Success
1323 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1325 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1326 uint8_t numOptions) {
1328 * This ftn is implemented one of two ways in the case of observation:
1330 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1331 * Remove the callback associated on client side.
1332 * When the next notification comes in from server,
1333 * reply with RESET message to server.
1334 * Keep in mind that the server will react to RESET only
1335 * if the last notification was sent ans CON
1337 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1338 * and it is associated with an observe request
1339 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1340 * Send CON Observe request to server with
1341 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1342 * Remove the callback associated on client side.
1344 OCStackResult ret = OC_STACK_OK;
1347 return OC_STACK_INVALID_PARAM;
1350 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1352 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1355 switch (clientCB->method)
1357 case OC_REST_OBSERVE:
1358 case OC_REST_OBSERVE_ALL:
1359 if(qos == OC_HIGH_QOS)
1361 ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
1362 &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
1367 FindAndDeleteClientCB(clientCB);
1370 #ifdef WITH_PRESENCE
1371 case OC_REST_PRESENCE:
1372 FindAndDeleteClientCB(clientCB);
1376 return OC_STACK_INVALID_METHOD;
1381 #ifdef WITH_PRESENCE
1382 OCStackResult OCProcessPresence()
1384 OCStackResult result = OC_STACK_OK;
1385 uint8_t ipAddr[4] = { 0 };
1388 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1389 ClientCB* cbNode = NULL;
1391 OCClientResponse clientResponse;
1392 OCResponse * response = NULL;
1394 LL_FOREACH(cbList, cbNode) {
1395 if(OC_REST_PRESENCE == cbNode->method)
1397 if(cbNode->presence)
1399 uint32_t now = GetTime(0);
1400 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
1401 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1404 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1409 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1410 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1411 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1414 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1416 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1417 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1419 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1421 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
1422 (OCDevAddr *) &dst, 0, NULL);
1423 if(result != OC_STACK_OK)
1427 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1428 &cbNode->token, &clientResponse, NULL);
1429 if(result != OC_STACK_OK)
1434 // Increment the TTLLevel (going to a next state), so we don't keep
1435 // sending presence notification to client.
1436 cbNode->presence->TTLlevel++;
1437 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1438 cbNode->presence->TTLlevel);
1442 result = OC_STACK_INVALID_IP;
1445 HandleStackResponses(response);
1447 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1449 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
1451 OCGenerateCoAPToken(&token);
1452 result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
1453 &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
1454 if(result != OC_STACK_OK)
1458 cbNode->presence->TTLlevel++;
1459 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
1465 if (result != OC_STACK_OK)
1467 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
1474 * Called in main loop of OC client or server. Allows low-level processing of
1478 * OC_STACK_OK - no errors
1479 * OC_STACK_ERROR - stack process error
1481 OCStackResult OCProcess() {
1483 OC_LOG(INFO, TAG, PCF("Entering OCProcess"));
1484 #ifdef WITH_PRESENCE
1485 OCProcessPresence();
1488 CAHandleRequestResponse();
1496 #ifdef WITH_PRESENCE
1498 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
1499 * presence notifications to clients via multicast. Once this API has been called with a success,
1500 * clients may query for this server's presence and this server's stack will respond via multicast.
1502 * Server can call this function when it comes online for the first time, or when it comes back
1503 * online from offline mode, or when it re enters network.
1505 * @param ttl - Time To Live in seconds
1506 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
1509 * OC_STACK_OK - No errors; Success
1511 OCStackResult OCStartPresence(const uint32_t ttl)
1513 OCChangeResourceProperty(
1514 &(((OCResource *)presenceResource.handle)->resourceProperties),
1519 presenceResource.presenceTTL = ttl;
1522 if(OC_PRESENCE_UNINITIALIZED == presenceState)
1524 OCDevAddr multiCastAddr;
1527 presenceState = OC_PRESENCE_INITIALIZED;
1528 OCGenerateCoAPToken(&token);
1529 OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
1530 //add the presence observer
1531 AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
1532 (OCResource *)presenceResource.handle, OC_LOW_QOS);
1535 // Each time OCStartPresence is called
1536 // a different random 32-bit integer number is used
1537 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1539 return SendPresenceNotification(NULL);
1543 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
1544 * presence notifications to clients via multicast. Once this API has been called with a success,
1545 * this server's stack will not respond to clients querying for this server's presence.
1547 * Server can call this function when it is terminating, going offline, or when going
1548 * away from network.
1551 * OC_STACK_OK - No errors; Success
1553 OCStackResult OCStopPresence()
1555 OCStackResult result = OC_STACK_ERROR;
1556 //make resource inactive
1557 result = OCChangeResourceProperty(
1558 &(((OCResource *) presenceResource.handle)->resourceProperties),
1560 result = SendPresenceNotification(NULL);
1567 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
1569 defaultDeviceHandler = entityHandler;
1577 * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource
1578 * @param resourceTypeName - name of resource type. Example: "core.led"
1579 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1580 * @param uri - URI of the resource. Example: "/a/led"
1581 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1582 * NULL for default entity handler
1583 * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE
1586 * OC_STACK_OK - no errors
1587 * OC_STACK_ERROR - stack process error
1589 OCStackResult OCCreateResource(OCResourceHandle *handle,
1590 const char *resourceTypeName,
1591 const char *resourceInterfaceName,
1592 const char *uri, OCEntityHandler entityHandler,
1593 uint8_t resourceProperties) {
1595 OCResource *pointer = NULL;
1598 OCStackResult result = OC_STACK_ERROR;
1600 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
1602 if(myStackMode == OC_CLIENT)
1606 // Validate parameters
1607 // Is it presented during resource discovery?
1608 if (!handle || !resourceTypeName || !uri) {
1609 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
1610 return OC_STACK_INVALID_PARAM;
1613 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
1614 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
1617 // Make sure resourceProperties bitmask has allowed properties specified
1618 if (resourceProperties
1619 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
1620 OC_LOG(ERROR, TAG, PCF("Invalid property"));
1621 return OC_STACK_INVALID_PARAM;
1624 // If the headResource is NULL, then no resources have been created...
1625 pointer = headResource;
1627 // At least one resources is in the resource list, so we need to search for
1628 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
1630 if (strcmp(uri, pointer->uri) == 0) {
1631 OC_LOG(ERROR, TAG, PCF("URI already in use"));
1632 return OC_STACK_INVALID_PARAM;
1634 pointer = pointer->next;
1637 // Create the pointer and insert it into the resource list
1638 pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
1642 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
1644 insertResource(pointer);
1647 size = strlen(uri) + 1;
1648 str = (char *) OCMalloc(size);
1652 strncpy(str, uri, size);
1655 // Set properties. Set OC_ACTIVE
1656 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
1659 // Add the resourcetype to the resource
1660 result = BindResourceTypeToResource(pointer, resourceTypeName);
1661 if (result != OC_STACK_OK) {
1662 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
1666 // Add the resourceinterface to the resource
1667 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
1668 if (result != OC_STACK_OK) {
1669 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
1673 // If an entity handler has been passed, attach it to the newly created
1674 // resource. Otherwise, set the default entity handler.
1677 pointer->entityHandler = entityHandler;
1681 pointer->entityHandler = defaultResourceEHandler;
1685 result = OC_STACK_OK;
1687 #ifdef WITH_PRESENCE
1688 if(presenceResource.handle)
1690 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1691 SendPresenceNotification(pointer->rsrcType);
1695 if (result != OC_STACK_OK)
1697 // Deep delete of resource and other dynamic elements that it contains
1698 deleteResource(pointer);
1707 * Create a resource. with host ip address for remote resource
1709 * @param handle - pointer to handle to newly created resource. Set by ocstack.
1710 * Used to refer to resource
1711 * @param resourceTypeName - name of resource type. Example: "core.led"
1712 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1713 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
1714 * @param uri - URI of the resource. Example: "/a/led"
1715 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1716 * NULL for default entity handler
1717 * @param resourceProperties - properties supported by resource.
1718 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
1721 * OC_STACK_OK - no errors
1722 * OC_STACK_ERROR - stack process error
1725 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
1726 const char *resourceTypeName,
1727 const char *resourceInterfaceName,
1730 OCEntityHandler entityHandler,
1731 uint8_t resourceProperties)
1735 OCStackResult result = OC_STACK_ERROR;
1737 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
1738 uri, entityHandler, resourceProperties);
1740 if (result != OC_STACK_ERROR)
1743 size = strlen(host) + 1;
1744 str = (char *) OCMalloc(size);
1747 return OC_STACK_ERROR;
1749 strncpy(str, host, size);
1750 ((OCResource *) *handle)->host = str;
1757 * Add a resource to a collection resource.
1759 * @param collectionHandle - handle to the collection resource
1760 * @param resourceHandle - handle to resource to be added to the collection resource
1763 * OC_STACK_OK - no errors
1764 * OC_STACK_ERROR - stack process error
1765 * OC_STACK_INVALID_PARAM - invalid collectionhandle
1767 OCStackResult OCBindResource(
1768 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1769 OCResource *resource;
1772 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
1774 // Validate parameters
1775 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1776 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1777 // Container cannot contain itself
1778 if (collectionHandle == resourceHandle) {
1779 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
1780 return OC_STACK_INVALID_PARAM;
1783 // Use the handle to find the resource in the resource linked list
1784 resource = findResource((OCResource *) collectionHandle);
1786 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1787 return OC_STACK_INVALID_PARAM;
1790 // Look for an open slot to add add the child resource.
1791 // If found, add it and return success
1792 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1793 if (!resource->rsrcResources[i]) {
1794 resource->rsrcResources[i] = (OCResource *) resourceHandle;
1795 OC_LOG(INFO, TAG, PCF("resource bound"));
1800 #ifdef WITH_PRESENCE
1801 if(presenceResource.handle)
1803 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1804 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1808 // Unable to add resourceHandle, so return error
1809 return OC_STACK_ERROR;
1813 * Remove a resource from a collection resource.
1815 * @param collectionHandle - handle to the collection resource
1816 * @param resourceHandle - handle to resource to be added to the collection resource
1819 * OC_STACK_OK - no errors
1820 * OC_STACK_ERROR - stack process error
1821 * OC_STACK_INVALID_PARAM - invalid collectionHandle
1823 OCStackResult OCUnBindResource(
1824 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1825 OCResource *resource;
1828 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
1830 // Validate parameters
1831 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1832 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1833 // Container cannot contain itself
1834 if (collectionHandle == resourceHandle) {
1835 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
1836 return OC_STACK_INVALID_PARAM;
1839 // Use the handle to find the resource in the resource linked list
1840 resource = findResource((OCResource *) collectionHandle);
1842 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1843 return OC_STACK_INVALID_PARAM;
1846 // Look for an open slot to add add the child resource.
1847 // If found, add it and return success
1848 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1849 if (resourceHandle == resource->rsrcResources[i]) {
1850 resource->rsrcResources[i] = (OCResource *) NULL;
1851 OC_LOG(INFO, TAG, PCF("resource unbound"));
1856 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
1858 #ifdef WITH_PRESENCE
1859 if(presenceResource.handle)
1861 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1862 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1866 // Unable to add resourceHandle, so return error
1867 return OC_STACK_ERROR;
1870 OCStackResult BindResourceTypeToResource(OCResource* resource,
1871 const char *resourceTypeName)
1873 OCResourceType *pointer = NULL;
1876 OCStackResult result = OC_STACK_ERROR;
1878 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
1880 // Validate parameters
1881 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
1882 // TODO: Does resource attribute resentation really have to be maintained in stack?
1883 // Is it presented during resource discovery?
1885 TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
1887 // Create the resourcetype and insert it into the resource list
1888 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
1893 // Set the resourceTypeName
1894 size = strlen(resourceTypeName) + 1;
1895 str = (char *) OCMalloc(size);
1899 strncpy(str, resourceTypeName, size);
1900 pointer->resourcetypename = str;
1902 insertResourceType(resource, pointer);
1903 result = OC_STACK_OK;
1905 exit: if (result != OC_STACK_OK) {
1913 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
1914 const char *resourceInterfaceName)
1916 OCResourceInterface *pointer = NULL;
1919 OCStackResult result = OC_STACK_ERROR;
1921 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
1923 // Validate parameters
1924 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
1926 TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
1928 // Create the resourceinterface and insert it into the resource list
1929 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
1934 // Set the resourceinterface name
1935 size = strlen(resourceInterfaceName) + 1;
1936 str = (char *) OCMalloc(size);
1940 strncpy(str, resourceInterfaceName, size);
1941 pointer->name = str;
1943 // Bind the resourceinterface to the resource
1944 insertResourceInterface(resource, pointer);
1946 result = OC_STACK_OK;
1948 exit: if (result != OC_STACK_OK) {
1957 * Bind a resourcetype to a resource.
1959 * @param handle - handle to the resource
1960 * @param resourceTypeName - name of resource type. Example: "core.led"
1963 * OC_STACK_OK - no errors
1964 * OC_STACK_ERROR - stack process error
1966 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
1967 const char *resourceTypeName) {
1969 OCStackResult result = OC_STACK_ERROR;
1970 OCResource *resource;
1972 // Make sure resource exists
1973 resource = findResource((OCResource *) handle);
1975 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1976 return OC_STACK_ERROR;
1979 // call internal function
1980 result = BindResourceTypeToResource(resource, resourceTypeName);
1982 #ifdef WITH_PRESENCE
1983 if(presenceResource.handle)
1985 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1986 SendPresenceNotification(resource->rsrcType);
1994 * Bind a resourceinterface to a resource.
1996 * @param handle - handle to the resource
1997 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
2000 * OC_STACK_OK - no errors
2001 * OC_STACK_ERROR - stack process error
2004 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2005 const char *resourceInterfaceName) {
2007 OCStackResult result = OC_STACK_ERROR;
2008 OCResource *resource;
2010 // Make sure resource exists
2011 resource = findResource((OCResource *) handle);
2013 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2014 return OC_STACK_ERROR;
2017 // call internal function
2018 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2020 #ifdef WITH_PRESENCE
2021 if(presenceResource.handle)
2023 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2024 SendPresenceNotification(resource->rsrcType);
2032 * Get the number of resources that have been created in the stack.
2034 * @param numResources - pointer to count variable
2037 * OC_STACK_OK - no errors
2038 * OC_STACK_ERROR - stack process error
2041 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
2042 OCResource *pointer = headResource;
2044 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2045 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2048 *numResources = *numResources + 1;
2049 pointer = pointer->next;
2055 * Get a resource handle by index.
2057 * @param index - index of resource, 0 to Count - 1
2060 * Resource handle - if found
2061 * NULL - if not found
2063 OCResourceHandle OCGetResourceHandle(uint8_t index) {
2064 OCResource *pointer = headResource;
2067 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2069 // Iterate through the list
2070 while ((i < index) && pointer) {
2072 pointer = pointer->next;
2074 return (OCResourceHandle) pointer;
2078 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
2081 * @param handle - handle of resource to be deleted
2084 * OC_STACK_OK - no errors
2085 * OC_STACK_ERROR - stack process error
2086 * OC_STACK_NO_RESOURCE - resource not found
2087 * OC_STACK_INVALID_PARAM - invalid param
2089 OCStackResult OCDeleteResource(OCResourceHandle handle) {
2090 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2093 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2094 return OC_STACK_INVALID_PARAM;
2097 OCResource *resource = findResource((OCResource *) handle);
2098 if (resource == NULL) {
2099 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2100 return OC_STACK_NO_RESOURCE;
2103 if (deleteResource((OCResource *) handle) == 0) {
2104 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2105 return OC_STACK_ERROR;
2112 * Get the URI of the resource specified by handle.
2114 * @param handle - handle of resource
2116 * URI string - if resource found
2117 * NULL - resource not found
2119 const char *OCGetResourceUri(OCResourceHandle handle) {
2120 OCResource *resource;
2121 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2123 resource = findResource((OCResource *) handle);
2125 return resource->uri;
2127 return (const char *) NULL;
2131 * Get the properties of the resource specified by handle.
2132 * NOTE: that after a resource is created, the OC_ACTIVE property is set
2133 * for the resource by the stack.
2135 * @param handle - handle of resource
2137 * property bitmap - if resource found
2138 * NULL - resource not found
2140 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
2141 OCResource *resource;
2142 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2144 resource = findResource((OCResource *) handle);
2146 return resource->resourceProperties;
2152 * Get the number of resource types of the resource.
2154 * @param handle - handle of resource
2155 * @param numResourceTypes - pointer to count variable
2158 * OC_STACK_OK - no errors
2159 * OC_STACK_ERROR - stack process error
2161 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2162 uint8_t *numResourceTypes) {
2163 OCResource *resource;
2164 OCResourceType *pointer;
2166 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2167 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2168 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2170 *numResourceTypes = 0;
2172 resource = findResource((OCResource *) handle);
2174 pointer = resource->rsrcType;
2176 *numResourceTypes = *numResourceTypes + 1;
2177 pointer = pointer->next;
2184 * Get name of resource type of the resource.
2186 * @param handle - handle of resource
2187 * @param index - index of resource, 0 to Count - 1
2190 * resource type name - if resource found
2191 * NULL - resource not found
2193 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
2194 OCResourceType *resourceType;
2196 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2198 resourceType = findResourceTypeAtIndex(handle, index);
2200 return resourceType->resourcetypename;
2202 return (const char *) NULL;
2208 * Get the number of resource interfaces of the resource.
2210 * @param handle - handle of resource
2211 * @param numResources - pointer to count variable
2214 * OC_STACK_OK - no errors
2215 * OC_STACK_ERROR - stack process error
2217 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2218 uint8_t *numResourceInterfaces) {
2219 OCResourceInterface *pointer;
2220 OCResource *resource;
2222 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2224 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2225 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2227 *numResourceInterfaces = 0;
2228 resource = findResource((OCResource *) handle);
2230 pointer = resource->rsrcInterface;
2232 *numResourceInterfaces = *numResourceInterfaces + 1;
2233 pointer = pointer->next;
2240 * Get name of resource interface of the resource.
2242 * @param handle - handle of resource
2243 * @param index - index of resource, 0 to Count - 1
2246 * resource interface name - if resource found
2247 * NULL - resource not found
2249 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
2250 OCResourceInterface *resourceInterface;
2252 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2254 resourceInterface = findResourceInterfaceAtIndex(handle, index);
2255 if (resourceInterface) {
2256 return resourceInterface->name;
2258 return (const char *) NULL;
2262 * Get resource handle from the collection resource by index.
2264 * @param collectionHandle - handle of collection resource
2265 * @param index - index of contained resource, 0 to Count - 1
2268 * handle to resource - if resource found
2269 * NULL - resource not found
2271 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2273 OCResource *resource;
2275 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2277 if (index >= MAX_CONTAINED_RESOURCES) {
2281 resource = findResource((OCResource *) collectionHandle);
2286 return resource->rsrcResources[index];
2290 * Bind an entity handler to the resource.
2292 * @param handle - handle to the resource that the contained resource is to be bound
2293 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2295 * OC_STACK_OK - no errors
2296 * OC_STACK_ERROR - stack process error
2298 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2299 OCEntityHandler entityHandler) {
2300 OCResource *resource;
2302 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2304 // Validate parameters
2305 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2306 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2308 // Use the handle to find the resource in the resource linked list
2309 resource = findResource((OCResource *)handle);
2311 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2312 return OC_STACK_ERROR;
2316 resource->entityHandler = entityHandler;
2318 #ifdef WITH_PRESENCE
2319 if(presenceResource.handle)
2321 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2322 SendPresenceNotification(resource->rsrcType);
2330 * Get the entity handler for a resource.
2332 * @param handle - handle of resource
2335 * entity handler - if resource found
2336 * NULL - resource not found
2338 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
2339 OCResource *resource;
2341 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2343 // Use the handle to find the resource in the resource linked list
2344 resource = findResource((OCResource *)handle);
2346 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2351 return resource->entityHandler;
2354 void incrementSequenceNumber(OCResource * resPtr)
2356 // Increment the sequence number
2357 resPtr->sequenceNum += 1;
2358 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2360 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2366 * Notify Presence subscribers that a resource has been modified
2368 * @param resourceType - Handle to the resourceType linked list of resource
2369 * that was modified.
2370 * @param qos - Quality Of Service
2373 #ifdef WITH_PRESENCE
2374 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
2376 OCResource *resPtr = NULL;
2377 OCStackResult result;
2378 OCMethod method = OC_REST_PRESENCE;
2379 uint32_t maxAge = 0;
2380 resPtr = findResource((OCResource *) presenceResource.handle);
2383 return OC_STACK_NO_RESOURCE;
2385 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
2387 maxAge = presenceResource.presenceTTL;
2394 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
2397 #endif // WITH_PRESENCE
2399 * Notify observers that an observed value has changed.
2401 * @param handle - handle of resource
2404 * OC_STACK_OK - no errors
2405 * OC_STACK_NO_RESOURCE - invalid resource handle
2406 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
2408 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
2410 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2412 OCResource *resPtr = NULL;
2413 OCStackResult result;
2414 OCMethod method = OC_REST_NOMETHOD;
2415 uint32_t maxAge = 0;
2417 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2418 #ifdef WITH_PRESENCE
2419 if(handle == presenceResource.handle)
2423 #endif // WITH_PRESENCE
2424 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2426 // Verify that the resource exists
2427 resPtr = findResource ((OCResource *) handle);
2430 return OC_STACK_NO_RESOURCE;
2434 //only increment in the case of regular observing (not presence)
2435 incrementSequenceNumber(resPtr);
2436 method = OC_REST_OBSERVE;
2437 maxAge = MAX_OBSERVE_AGE;
2438 #ifdef WITH_PRESENCE
2439 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
2441 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
2448 OCNotifyListOfObservers (OCResourceHandle handle,
2449 OCObservationId *obsIdList,
2450 uint8_t numberOfIds,
2451 unsigned char *notificationJSONPayload,
2452 OCQualityOfService qos)
2454 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
2456 OCResource *resPtr = NULL;
2457 //TODO: we should allow the server to define this
2458 uint32_t maxAge = MAX_OBSERVE_AGE;
2460 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2461 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
2462 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
2464 // Verify that the resource exists
2465 resPtr = findResource ((OCResource *) handle);
2466 if (NULL == resPtr || myStackMode == OC_CLIENT)
2468 return OC_STACK_NO_RESOURCE;
2472 incrementSequenceNumber(resPtr);
2474 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
2475 notificationJSONPayload, maxAge, qos));
2479 * Send a response to a request.
2480 * The response can be a regular, slow, or block (i.e. a response that
2481 * is too large to be sent in a single PDU and must span multiple transmissions)
2483 * @param response - pointer to structure that contains response parameters
2486 * OC_STACK_OK - No errors; Success
2487 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
2488 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
2489 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
2490 * persistent response buffer is necessary
2492 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
2494 OCStackResult result = OC_STACK_ERROR;
2495 OCServerRequest *serverRequest = NULL;
2497 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
2499 // Validate input parameters
2500 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
2501 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
2503 // TODO: Placeholder for creating a response entry when implementing
2504 // block transfer feature
2506 // If a response payload is present, check if block transfer is required
2507 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
2508 (const char *)ehResponse->payload, ehResponse->payloadSize))
2510 OC_LOG(INFO, TAG, PCF("Block transfer required"));
2512 // Persistent response buffer is needed for block transfer
2513 if (!ehResponse->persistentBufferFlag)
2515 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
2516 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
2518 // TODO: Placeholder for block transfer handling
2519 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
2520 // when implementing the block transfer feature
2526 // Get pointer to request info
2527 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
2530 result = serverRequest->ehResponseHandler(ehResponse);
2537 * Cancel a response. Applies to a block response
2539 * @param responseHandle - response handle set by stack in OCServerResponse after
2540 * OCDoResponse is called
2543 * OC_STACK_OK - No errors; Success
2544 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
2546 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
2548 OCStackResult result = OC_STACK_NOTIMPL;
2550 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
2552 // TODO: validate response handle
2557 //-----------------------------------------------------------------------------
2558 // Private internal function definitions
2559 //-----------------------------------------------------------------------------
2561 * Generate handle of OCDoResource invocation for callback management.
2563 static OCDoHandle GenerateInvocationHandle()
2565 OCDoHandle handle = NULL;
2566 // Generate token here, it will be deleted when the transaction is deleted
2567 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2570 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2575 #ifdef WITH_PRESENCE
2576 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
2577 OCResourceProperty resourceProperties, uint8_t enable)
2579 if (resourceProperties
2580 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
2581 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2582 return OC_STACK_INVALID_PARAM;
2586 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
2590 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
2597 * Initialize resource data structures, variables, etc.
2599 OCStackResult initResources() {
2600 OCStackResult result = OC_STACK_OK;
2601 // Init application resource vars
2602 headResource = NULL;
2603 // Init Virtual Resources
2604 #ifdef WITH_PRESENCE
2605 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
2606 //presenceResource.token = OCGenerateCoAPToken();
2607 result = OCCreateResource(&presenceResource.handle,
2608 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
2613 //make resource inactive
2614 result = OCChangeResourceProperty(
2615 &(((OCResource *) presenceResource.handle)->resourceProperties),
2622 * Add a resource to the end of the linked list of resources.
2624 * @param resource - resource to be added
2626 void insertResource(OCResource *resource) {
2627 OCResource *pointer;
2629 if (!headResource) {
2630 headResource = resource;
2632 pointer = headResource;
2634 while (pointer->next) {
2635 pointer = pointer->next;
2637 pointer->next = resource;
2639 resource->next = NULL;
2643 * Find a resource in the linked list of resources.
2645 * @param resource - resource to be found
2647 * NULL - resource not found
2648 * pointer to resource - pointer to resource that was found in the linked list
2650 OCResource *findResource(OCResource *resource) {
2651 OCResource *pointer = headResource;
2654 if (pointer == resource) {
2657 pointer = pointer->next;
2662 void deleteAllResources()
2664 OCResource *pointer = headResource;
2669 temp = pointer->next;
2670 #ifdef WITH_PRESENCE
2671 if(pointer != (OCResource *) presenceResource.handle)
2673 #endif // WITH_PRESENCE
2674 deleteResource(pointer);
2675 #ifdef WITH_PRESENCE
2677 #endif // WITH_PRESENCE
2681 #ifdef WITH_PRESENCE
2682 // Ensure that the last resource to be deleted is the presence resource. This allows for all
2683 // presence notification attributed to their deletion to be processed.
2684 deleteResource((OCResource *) presenceResource.handle);
2685 #endif // WITH_PRESENCE
2689 * Delete the resource from the linked list.
2691 * @param resource - resource to be deleted
2696 int deleteResource(OCResource *resource) {
2697 OCResource *prev = NULL;
2700 temp = headResource;
2702 if (temp == resource) {
2703 // Invalidate all Resource Properties.
2704 resource->resourceProperties = (OCResourceProperty) 0;
2705 #ifdef WITH_PRESENCE
2706 if(resource != (OCResource *) presenceResource.handle)
2708 #endif // WITH_PRESENCE
2709 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
2710 #ifdef WITH_PRESENCE
2713 if(presenceResource.handle)
2715 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2716 if(resource != (OCResource *) presenceResource.handle)
2718 SendPresenceNotification(resource->rsrcType);
2722 SendPresenceNotification(NULL);
2727 if (temp == headResource) {
2728 headResource = temp->next;
2730 prev->next = temp->next;
2733 deleteResourceElements(temp);
2746 * Delete all of the dynamically allocated elements that were created for the resource.
2748 * @param resource - specified resource
2750 void deleteResourceElements(OCResource *resource) {
2756 OCFree(resource->uri);
2758 // Delete resourcetype linked list
2759 deleteResourceType(resource->rsrcType);
2761 // Delete resourceinterface linked list
2762 deleteResourceInterface(resource->rsrcInterface);
2766 * Delete all of the dynamically allocated elements that were created for the resource type.
2768 * @param resourceType - specified resource type
2770 void deleteResourceType(OCResourceType *resourceType) {
2771 OCResourceType *pointer = resourceType;
2772 OCResourceType *next;
2775 next = pointer->next;
2776 OCFree(pointer->resourcetypename);
2783 * Delete all of the dynamically allocated elements that were created for the resource interface.
2785 * @param resourceInterface - specified resource interface
2787 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
2788 OCResourceInterface *pointer = resourceInterface;
2789 OCResourceInterface *next;
2792 next = pointer->next;
2793 OCFree(pointer->name);
2800 * Insert a resource type into a resource's resource type linked list.
2802 * @param resource - resource where resource type is to be inserted
2803 * @param resourceType - resource type to be inserted
2805 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
2806 OCResourceType *pointer;
2808 if (resource && !resource->rsrcType) {
2809 resource->rsrcType = resourceType;
2813 pointer = resource->rsrcType;
2817 pointer = resourceType;
2819 while (pointer->next) {
2820 pointer = pointer->next;
2822 pointer->next = resourceType;
2824 resourceType->next = NULL;
2828 * Get a resource type at the specified index within a resource.
2830 * @param handle - handle of resource
2831 * @param index - index of resource type
2834 * resourcetype - if found
2837 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
2838 OCResource *resource;
2839 OCResourceType *pointer;
2842 // Find the specified resource
2843 resource = findResource((OCResource *) handle);
2848 // Make sure a resource has a resourcetype
2849 if (!resource->rsrcType) {
2853 // Iterate through the list
2854 pointer = resource->rsrcType;
2856 while ((i < index) && pointer) {
2858 pointer = pointer->next;
2864 * Finds a resource type in an OCResourceType link-list.
2866 * @param resourceTypeList - the link-list to be searched through
2867 * @param resourceTypeName - the key to search for
2870 * resourceType that matches the key (ie. resourceTypeName)
2871 * NULL - either an invalid parameter or this function was unable to find the key.
2873 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
2875 if(resourceTypeList && resourceTypeName)
2877 OCResourceType * rtPointer = resourceTypeList;
2878 while(resourceTypeName && rtPointer)
2880 if(rtPointer->resourcetypename &&
2881 strcmp(resourceTypeName, (const char *)
2882 (rtPointer->resourcetypename)) == 0)
2886 rtPointer = rtPointer->next;
2893 * Insert a resource interface into a resource's resource interface linked list.
2895 * @param resource - resource where resource interface is to be inserted
2896 * @param resourceInterface - resource interface to be inserted
2898 void insertResourceInterface(OCResource *resource,
2899 OCResourceInterface *resourceInterface) {
2900 OCResourceInterface *pointer;
2902 if (!resource->rsrcInterface) {
2903 resource->rsrcInterface = resourceInterface;
2905 pointer = resource->rsrcInterface;
2906 while (pointer->next) {
2907 pointer = pointer->next;
2909 pointer->next = resourceInterface;
2911 resourceInterface->next = NULL;
2915 * Get a resource interface at the specified index within a resource.
2917 * @param handle - handle of resource
2918 * @param index - index of resource interface
2921 * resourceinterface - if found
2924 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
2926 OCResource *resource;
2927 OCResourceInterface *pointer;
2930 // Find the specified resource
2931 resource = findResource((OCResource *) handle);
2936 // Make sure a resource has a resourceinterface
2937 if (!resource->rsrcInterface) {
2941 // Iterate through the list
2942 pointer = resource->rsrcInterface;
2944 while ((i < index) && pointer) {
2946 pointer = pointer->next;
2952 * Determine if a request/response must be sent in a block transfer because it is too large to be
2953 * sent in a single PDU. This function can be used for either a request or a response
2955 * @param request - NULL or pointer to request
2956 * @param response - NULL or pointer to response
2957 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
2958 * the length of the request/response
2961 * 0 - packet transfer NOT required (i.e. normal request/response)
2962 * 1 - packet transfer required (i.e. block transfer needed)
2964 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
2968 // Determine if we are checking a request or a response
2971 // If size is greater than 0, use it for the request size value, otherwise
2972 // assume request is null terminated and use strlen for size value
2973 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
2980 // If size is greater than 0, use it for the response size value, otherwise
2981 // assume response is null terminated and use strlen for size value
2982 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
2991 * Retrieves a resource type based upon a uri string if the uri string contains only just one
2992 * resource attribute (and that has to be of type "rt").
2994 * @remark This API malloc's memory for the resource type and newURI. Do not malloc resourceType
2995 * or newURI before passing in.
2997 * @param uri - Valid URI for "requiredUri" parameter to OCDoResource API.
2998 * @param resourceType - The resource type to be populated; pass by reference.
2999 * @param newURI - Return URI without resourceType appended to the end of it. This is used to
3000 * ensure that the uri parameter is not modified; pass by reference.
3003 * OC_STACK_INVALID_URI - Returns this if the URI is invalid/NULL.
3004 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
3005 * OC_STACK_OK - Success
3007 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI)
3011 return OC_STACK_INVALID_URI;
3013 if(!resourceType || !newURI)
3015 return OC_STACK_INVALID_PARAM;
3017 char * leftToken = NULL;
3018 char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3023 strcpy(tempURI, uri);
3024 leftToken = strtok((char *)tempURI, "?");
3026 while(leftToken != NULL)
3028 if(strncmp(leftToken, "rt=", 3) == 0)
3030 *resourceType = (unsigned char *) OCMalloc(strlen(leftToken)-3);
3035 strcpy((char *)*resourceType, ((const char *)&leftToken[3]));
3038 leftToken = strtok(NULL, "?");
3046 return OC_STACK_NO_MEMORY;
3049 const ServerID OCGetServerInstanceID(void)
3051 static bool generated = false;
3052 static ServerID sid;
3059 sid = OCGetRandom();
3064 const char* OCGetServerInstanceIDString(void)
3066 // max printed length of a base 10
3067 // uint32 is 10 characters, so 11 includes null.
3068 // This will change as the representation gets switched
3070 static char buffer[11];
3071 int n = sprintf(buffer, "%u", OCGetServerInstanceID());