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));
302 serverRequest.reqTotalSize = strlen((const char *)requestInfo->info.payload) + 1;
306 serverRequest.reqTotalSize = 1;
309 switch (requestInfo->method)
313 serverRequest.method = OC_REST_GET;
318 serverRequest.method = OC_REST_PUT;
323 serverRequest.method = OC_REST_POST;
328 serverRequest.method = OC_REST_DELETE;
333 OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
339 OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d", strlen(requestInfo->info.token));
340 OC_LOG_BUFFER(INFO, TAG, requestInfo->info.token, strlen(requestInfo->info.token));
341 // TODO-CA: For CA integration currently copying CAToken to OCCoapToken:
342 // Need to remove OCCoapToken
343 memcpy (&(serverRequest.requestToken.token), requestInfo->info.token,
344 strlen(requestInfo->info.token));
345 serverRequest.requestToken.tokenLength = strlen(requestInfo->info.token);
347 if (requestInfo->info.type == CA_MSG_CONFIRM)
349 serverRequest.qos = OC_HIGH_QOS;
351 else if (requestInfo->info.type == CA_MSG_NONCONFIRM)
353 serverRequest.qos = OC_LOW_QOS;
355 else if (requestInfo->info.type == CA_MSG_ACKNOWLEDGE)
357 // TODO-CA: Need to handle this
359 else if (requestInfo->info.type == CA_MSG_RESET)
361 // TODO-CA: Need to handle this
363 // CA does not need the following 3 fields
364 serverRequest.coapID = 0;
365 serverRequest.delayedResNeeded = 0;
366 serverRequest.secured = 0;
369 serverRequest.addressInfo = endPoint->addressInfo;
370 serverRequest.connectivityType = endPoint->connectivityType;
371 if (requestInfo->info.token)
373 strncpy(serverRequest.token, requestInfo->info.token, sizeof(serverRequest.token) - 1);
376 struct sockaddr_in sa;
377 inet_pton(AF_INET, endPoint->addressInfo.IP.ipAddress, &(sa.sin_addr));
378 sa.sin_port = htons(endPoint->addressInfo.IP.port);
379 memcpy((void*)&serverRequest.requesterAddr, &(sa), sizeof(sa));
381 // copy vendor specific header options
382 // TODO-CA: CA is including non-vendor header options as well, like observe.
383 // Need to filter those out
384 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &(requestInfo->info.numOptions));
385 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
387 // TODO-CA: Need to send an error indicating the num of options is incorrect
390 serverRequest.numRcvdVendorSpecificHeaderOptions = requestInfo->info.numOptions;
391 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
393 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
394 sizeof(CAHeaderOption_t)*requestInfo->info.numOptions);
397 requestResult = HandleStackRequests (&serverRequest);
401 // generate the pdu, if the request was CON, then the response is ACK, otherwire NON
402 memset(&responseData, 0, sizeof(CAInfo_t));
403 responseData.token = (requestInfo != NULL) ? requestInfo->info.token : "";
405 // TODO : I guess we need to allocate memeory?
406 responseData.payload = "{\"oc\":[{\"href\":\"/a/led\",\"sid\":\"\",\"prop\":{\"rt\":[\"core.led\"],\"if\":[\"oc.mi.def\"],\"obs\":1}}]}";
408 //responseInfo = (CAResponseInfo*) malloc(sizeof(CAResponseInfo));
409 memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
410 responseInfo.result = 200;
411 responseInfo.info = responseData;
413 // send request (connectivityType from remoteEndpoint of request Info)
414 OC_LOG(INFO, TAG, PCF("CASendResponse in HandleCARequests"));
415 //TODO-CA: CASendResponse returns the result (we need to check if the
417 CAResult_t caResult = CASendResponse(endPoint, &responseInfo);
418 if(caResult != CA_STATUS_OK)
420 OC_LOG(ERROR, TAG, PCF("CASendResponse error"));
424 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
429 //This function will be called back by occoap layer when a request is received
430 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
432 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
434 OCStackResult result = OC_STACK_ERROR;
435 ResourceHandling resHandling;
436 OCResource *resource;
438 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
441 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
443 result = AddServerCARequest(&request, protocolRequest->coapID,
444 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
445 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
446 protocolRequest->observationOption, protocolRequest->qos,
447 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
448 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
449 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
450 protocolRequest->reqTotalSize,
451 &protocolRequest->addressInfo, protocolRequest->connectivityType, protocolRequest->token);
453 result = AddServerRequest(&request, protocolRequest->coapID,
454 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
455 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
456 protocolRequest->observationOption, protocolRequest->qos,
457 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
458 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
459 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
460 protocolRequest->reqTotalSize);
462 if (OC_STACK_OK != result)
464 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
467 VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
469 if(!protocolRequest->reqMorePacket)
471 request->requestComplete = 1;
476 OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
479 if(request->requestComplete)
481 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
482 result = DetermineResourceHandling (request, &resHandling, &resource);
483 if (result == OC_STACK_OK)
485 result = ProcessRequest(resHandling, resource, request);
489 result = OC_STACK_ERROR;
494 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
495 result = OC_STACK_CONTINUE;
500 //This function will be called back by occoap layer when a response is received
501 OCStackResult HandleStackResponses(OCResponse * response)
503 OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)"));
504 OCStackResult result = OC_STACK_OK;
505 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
506 uint8_t isObserveNotification = 0;
507 ClientCB * cbNode = NULL;
509 uint8_t isPresenceNotification = 0;
510 uint8_t isMulticastPresence = 0;
511 char * resourceTypeName = NULL;
512 uint32_t lowerBound = 0;
513 uint32_t higherBound = 0;
515 unsigned char * bufRes = response->bufRes;
516 #endif // WITH_PRESENCE
518 cbNode = response->cbNode;
521 cbNode = GetClientCB(response->rcvdToken, NULL, NULL);
524 if(response->clientResponse->sequenceNumber >= OC_OFFSET_SEQUENCE_NUMBER)
526 isObserveNotification = 1;
527 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
530 OC_LOG_V(DEBUG, TAG, "The sequenceNumber/NONCE of this response %u",
531 response->clientResponse->sequenceNumber);
532 OC_LOG_V(DEBUG, TAG, "The maxAge/TTL of this response %u", response->maxAge);
533 OC_LOG_V(DEBUG, TAG, "The response received is %s", bufRes);
536 if(!strcmp((char *)response->rcvdUri, (char *)OC_PRESENCE_URI)){
537 isPresenceNotification = 1;
540 result = OC_STACK_INVALID_PARAM;
543 tok = strtok((char *)bufRes, "[:]}");
544 bufRes[strlen((char *)bufRes)] = ':';
545 tok = strtok(NULL, "[:]}");
546 bufRes[strlen((char *)bufRes)] = ':';
547 response->clientResponse->sequenceNumber = (uint32_t )atoi(tok);
548 OC_LOG_V(DEBUG, TAG, "The received NONCE is %u", response->clientResponse->sequenceNumber);
549 tok = strtok(NULL, "[:]}");
550 response->maxAge = (uint32_t )atoi(tok);
551 OC_LOG_V(DEBUG, TAG, "The received TTL is %u", response->maxAge);
552 tok = strtok(NULL, "[:]}");
555 resourceTypeName = (char *)OCMalloc(strlen(tok));
556 if(!resourceTypeName)
560 bufRes[strlen((char *)bufRes)] = ':';
561 strcpy(resourceTypeName, tok);
562 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
565 bufRes[strlen((char *)bufRes)] = ']';
568 // Check if the application subcribed for presence
571 cbNode = GetClientCB(NULL, NULL, response->fullUri);
574 // Check if application subscribed for multicast presence
577 snprintf((char *)response->fullUri, MAX_URI_LENGTH, "%s%s",
578 OC_MULTICAST_IP, response->rcvdUri);
579 cbNode = GetClientCB(NULL, NULL, response->fullUri);
582 isMulticastPresence = 1;
583 isPresenceNotification = 0;
587 if(cbNode && isPresenceNotification)
589 OC_LOG(INFO, TAG, PCF("Received a presence notification"));
590 if(!cbNode->presence)
592 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
593 VERIFY_NON_NULL_V(cbNode->presence);
594 cbNode->presence->timeOut = NULL;
595 cbNode->presence->timeOut = (uint32_t *)
596 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
597 if(!(cbNode->presence->timeOut)){
598 OCFree(cbNode->presence);
599 result = OC_STACK_NO_MEMORY;
602 if(response->maxAge == 0)
604 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
605 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
608 OCFree(cbNode->presence->timeOut);
609 OCFree(cbNode->presence);
610 cbNode->presence = NULL;
615 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %d", GetTime(0));
616 cbNode->presence->TTL = response->maxAge;
617 for(int index = 0; index < PresenceTimeOutSize; index++)
619 lowerBound = GetTime(((float)(PresenceTimeOut[index])
620 /(float)100)*(float)cbNode->presence->TTL);
621 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
622 /(float)100)*(float)cbNode->presence->TTL);
623 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
624 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
625 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
626 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
627 cbNode->presence->timeOut[index]);
629 cbNode->presence->TTLlevel = 0;
630 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
631 if(cbNode->sequenceNumber == response->clientResponse->sequenceNumber)
633 OC_LOG(INFO, TAG, PCF("===============No presence change"));
636 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
637 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;;
640 // Ensure that a filter is actually applied.
641 if(resourceTypeName && cbNode->filterResourceType)
643 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
649 else if(cbNode && isMulticastPresence)
651 // Check if the same nonce for a given host
652 OCMulticastNode* mcNode = NULL;
653 mcNode = GetMCPresenceNode(response->fullUri);
655 if(response->maxAge == 0)
657 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
658 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
661 OCFree(cbNode->presence->timeOut);
662 OCFree(cbNode->presence);
663 cbNode->presence = NULL;
666 else if(mcNode != NULL)
668 if(mcNode->nonce == response->clientResponse->sequenceNumber)
670 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
671 result = OC_STACK_NO_MEMORY;
674 mcNode->nonce = response->clientResponse->sequenceNumber;
678 uint32_t uriLen = strlen((char*)response->fullUri);
679 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
682 memcpy(uri, response->fullUri, (uriLen + 1));
687 PCF("===============No Memory for URI to store in the presence node"));
688 result = OC_STACK_NO_MEMORY;
691 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri,
692 response->clientResponse->sequenceNumber);
693 if(result == OC_STACK_NO_MEMORY)
696 PCF("===============No Memory for Multicast Presence Node"));
697 result = OC_STACK_NO_MEMORY;
702 // Ensure that a filter is actually applied.
703 if(resourceTypeName && cbNode->filterResourceType)
705 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
712 else if(!cbNode && isPresenceNotification)
714 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
715 ------------ ignoring"));
717 #endif // WITH_PRESENCE
721 if(isObserveNotification)
723 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
724 //TODO: check the standard for methods to detect wrap around condition
725 if(cbNode->method == OC_REST_OBSERVE &&
726 (response->clientResponse->sequenceNumber <= cbNode->sequenceNumber ||
727 (response->clientResponse->sequenceNumber > cbNode->sequenceNumber &&
728 response->clientResponse->sequenceNumber ==
729 MAX_SEQUENCE_NUMBER)))
731 OC_LOG_V(DEBUG, TAG, "Observe notification came out of order. \
732 Ignoring Incoming:%d Against Current:%d.",
733 response->clientResponse->sequenceNumber, cbNode->sequenceNumber);
736 if(response->clientResponse->sequenceNumber > cbNode->sequenceNumber){
737 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;
741 response->clientResponse->resJSONPayload = bufRes;
743 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response->clientResponse);
745 if (cbResult == OC_STACK_DELETE_TRANSACTION ||
746 response->clientResponse->result == OC_STACK_COMM_ERROR ||
747 (response->clientResponse->result == OC_STACK_RESOURCE_DELETED &&
748 !isPresenceNotification && !isMulticastPresence))
750 FindAndDeleteClientCB(cbNode);
755 result = OC_STACK_ERROR;
760 OCFree(resourceTypeName);
765 int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
768 unsigned char *itr, *coap;
769 uint8_t dotCount = 0;
773 /* search for scheme */
775 if (!isdigit((unsigned char) *ipAddrStr))
777 coap = (unsigned char *) OC_COAP_SCHEME;
778 while (*coap && tolower(*itr) == *coap)
787 if (isdigit((unsigned char) *ipAddrStr))
790 ipAddr[index] += *ipAddrStr - '0';
792 else if ((unsigned char) *ipAddrStr == '.')
804 if(*ipAddrStr == ':')
808 if (isdigit((unsigned char) *ipAddrStr))
811 *port += *ipAddrStr - '0';
822 if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
833 //-----------------------------------------------------------------------------
834 // Private internal function prototypes
835 //-----------------------------------------------------------------------------
837 static OCDoHandle GenerateInvocationHandle();
838 static OCStackResult initResources();
839 static void insertResource(OCResource *resource);
840 static OCResource *findResource(OCResource *resource);
841 static void insertResourceType(OCResource *resource,
842 OCResourceType *resourceType);
843 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
845 static void insertResourceInterface(OCResource *resource,
846 OCResourceInterface *resourceInterface);
847 static OCResourceInterface *findResourceInterfaceAtIndex(
848 OCResourceHandle handle, uint8_t index);
849 static void deleteResourceType(OCResourceType *resourceType);
850 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
851 static void deleteResourceElements(OCResource *resource);
852 static int deleteResource(OCResource *resource);
853 static void deleteAllResources();
854 static void incrementSequenceNumber(OCResource * resPtr);
855 static OCStackResult verifyUriQueryLength(const char * inputUri,
857 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
858 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI);
860 //-----------------------------------------------------------------------------
862 //-----------------------------------------------------------------------------
865 * Initialize the OC Stack. Must be called prior to starting the stack.
868 * IP Address of host device
870 * Port of host device
872 * Host device is client, server, or client-server
875 * OC_STACK_OK - no errors
876 * OC_STACK_ERROR - stack init error
878 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
880 OCStackResult result = OC_STACK_ERROR;
881 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
885 OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
889 //It is ok to select network to CA_WIFI for now
890 CAResult_t caResult = CASelectNetwork(CA_WIFI);
891 if(caResult == CA_STATUS_OK)
893 OC_LOG(INFO, TAG, PCF("CASelectNetwork to WIFI"));
894 caResult = CARegisterHandler(HandleCARequests, HandleCAResponses);
895 if(caResult == CA_STATUS_OK)
897 OC_LOG(INFO, TAG, PCF("CARegisterHandler..."));
898 stackState = OC_STACK_INITIALIZED;
899 result = OC_STACK_OK;
903 caResult = CAStartDiscoveryServer();
904 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
907 caResult = CAStartListeningServer();
908 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
910 case OC_CLIENT_SERVER:
911 caResult = CAStartListeningServer();
912 if(caResult == CA_STATUS_OK)
914 caResult = CAStartDiscoveryServer();
916 OC_LOG(INFO, TAG, PCF("Client-server mode"));
919 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
920 return OC_STACK_ERROR;
925 if (caResult == CA_STATUS_OK)
927 result = OC_STACK_OK;
931 result = OC_STACK_ERROR;
938 OC_LOG(INFO, TAG, PCF("Client mode"));
941 OC_LOG(INFO, TAG, PCF("Server mode"));
943 case OC_CLIENT_SERVER:
944 OC_LOG(INFO, TAG, PCF("Client-server mode"));
947 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
948 return OC_STACK_ERROR;
952 // Make call to OCCoAP layer
953 result = OCInitCoAP(ipAddr, (uint16_t) port, myStackMode);
957 defaultDeviceHandler = NULL;
960 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
961 #endif // WITH_PRESENCE
963 if (result == OC_STACK_OK)
965 stackState = OC_STACK_INITIALIZED;
967 // Initialize resource
968 if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
970 result = initResources();
972 if(result != OC_STACK_OK)
974 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
980 * Stop the OC stack. Use for a controlled shutdown.
982 * OC_STACK_OK - no errors
983 * OC_STACK_ERROR - stack not initialized
985 OCStackResult OCStop()
987 OCStackResult result = OC_STACK_ERROR;
989 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
991 if (stackState != OC_STACK_INITIALIZED)
993 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
994 return OC_STACK_ERROR;
998 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
999 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1000 presenceResource.presenceTTL = 0;
1001 #endif // WITH_PRESENCE
1003 // Free memory dynamically allocated for resources
1004 deleteAllResources();
1006 // Make call to OCCoAP layer
1007 if (OCStopCoAP() == OC_STACK_OK)
1009 // Remove all observers
1010 DeleteObserverList();
1011 // Remove all the client callbacks
1012 DeleteClientCBList();
1013 stackState = OC_STACK_UNINITIALIZED;
1014 result = OC_STACK_OK;
1016 result = OC_STACK_ERROR;
1019 // Deinit security blob
1020 DeinitOCSecurityInfo();
1022 if (result != OC_STACK_OK) {
1023 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
1030 * Verify the lengths of the URI and the query separately
1032 * @param inputUri - Input URI and query.
1033 * @param uriLen - The length of the initial URI with query.
1035 * Note: The '?' that appears after the URI is not considered as
1036 * a part of the query.
1038 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1042 query = strchr (inputUri, '?');
1046 if((query - inputUri) > MAX_URI_LENGTH)
1048 return OC_STACK_INVALID_URI;
1051 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1053 return OC_STACK_INVALID_QUERY;
1056 else if(uriLen > MAX_URI_LENGTH)
1058 return OC_STACK_INVALID_URI;
1064 * Discover or Perform requests on a specified resource (specified by that Resource's respective URI).
1066 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of calling this API.
1067 * @param method - @ref OCMethod to perform on the resource
1068 * @param requiredUri - URI of the resource to interact with
1069 * @param referenceUri - URI of the reference resource
1070 * @param request - JSON encoded request
1071 * @param qos - quality of service
1072 * @param cbData - struct that contains asynchronous callback function that is invoked
1073 * by the stack when discovery or resource interaction is complete
1074 * @param options - The address of an array containing the vendor specific header
1075 * header options to be sent with the request
1076 * @param numOptions - Number of vendor specific header options to be included
1079 * OC_STACK_OK - no errors
1080 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
1081 * OC_STACK_INVALID_METHOD - invalid resource method
1082 * OC_STACK_INVALID_URI - invalid required or reference URI
1085 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1086 const char *referenceUri, const char *request,
1087 OCQualityOfService qos, OCCallbackData *cbData,
1088 OCHeaderOption * options, uint8_t numOptions)
1090 OCStackResult result = OC_STACK_ERROR;
1092 ClientCB *clientCB = NULL;
1093 unsigned char * requestUri = NULL;
1094 unsigned char * resourceType = NULL;
1095 char * newUri = (char *)requiredUri;
1096 (void) referenceUri;
1098 CARemoteEndpoint_t* endpoint = NULL;
1099 CAResult_t caResult;
1100 CAToken_t caToken = NULL;
1101 CAInfo_t requestData;
1102 CARequestInfo_t requestInfo;
1103 // To track if memory is allocated for additional header options
1104 uint8_t hdrOptionMemAlloc = 0;
1107 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1109 // Validate input parameters
1110 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1111 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1113 TODO ("Need to form the final query by concatenating require and reference URI's");
1114 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
1116 uint16_t uriLen = strlen(requiredUri);
1118 // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS
1124 case OC_REST_DELETE:
1125 case OC_REST_OBSERVE:
1126 case OC_REST_OBSERVE_ALL:
1127 case OC_REST_CANCEL_OBSERVE:
1129 #ifdef WITH_PRESENCE
1130 case OC_REST_PRESENCE:
1134 result = OC_STACK_INVALID_METHOD;
1138 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
1143 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
1145 result = OC_STACK_INVALID_PARAM;
1149 #ifdef WITH_PRESENCE
1150 if(method == OC_REST_PRESENCE)
1152 result = getResourceType(requiredUri, &resourceType, &newUri);
1154 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1158 OC_LOG(DEBUG, TAG, PCF("Got Resource Type is NULL."));
1160 if(result != OC_STACK_OK)
1165 #endif // WITH_PRESENCE
1167 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
1170 memcpy(requestUri, newUri, (uriLen + 1));
1174 result = OC_STACK_NO_MEMORY;
1178 *handle = GenerateInvocationHandle();
1181 result = OC_STACK_NO_MEMORY;
1186 memset(&requestData, 0, sizeof(CAInfo_t));
1187 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1191 case OC_REST_OBSERVE:
1192 case OC_REST_OBSERVE_ALL:
1193 case OC_REST_CANCEL_OBSERVE:
1195 requestInfo.method = CA_GET;
1200 requestInfo.method = CA_PUT;
1205 requestInfo.method = CA_POST;
1208 case OC_REST_DELETE:
1210 requestInfo.method = CA_DELETE;
1213 #ifdef WITH_PRESENCE
1214 case OC_REST_PRESENCE:
1215 //TODO-CA: What should be the CA method?
1219 result = OC_STACK_INVALID_METHOD;
1223 // TODO-CA: Handle multi-cast scenario
1224 // Create remote end point
1225 caResult = CACreateRemoteEndpoint(newUri, CA_WIFI, &endpoint);
1226 // TODO-CA: Connectivity type should be passed to API
1227 endpoint->connectivityType = CA_WIFI;
1228 if (caResult != CA_STATUS_OK)
1230 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1235 caResult = CAGenerateToken(&caToken);
1237 if (caResult != CA_STATUS_OK)
1239 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1244 // TODO-CA: Map QoS to the right CA msg type
1245 requestData.type = CA_MSG_NONCONFIRM;
1246 requestData.token = caToken;
1247 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1249 result = CreateObserveHeaderOption (&(requestData.options), options,
1250 numOptions, OC_OBSERVE_REGISTER);
1251 if (result != OC_STACK_OK)
1255 hdrOptionMemAlloc = 1;
1256 requestData.numOptions = numOptions + 1;
1260 requestData.options = (CAHeaderOption_t*)options;
1261 requestData.numOptions = numOptions;
1263 requestData.payload = (char *)request;
1265 requestInfo.info = requestData;
1268 caResult = CASendRequest(endpoint, &requestInfo);
1269 if (caResult != CA_STATUS_OK)
1271 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1275 if((result = AddClientCB(&clientCB, cbData, &caToken, handle, method,
1276 requestUri, resourceType)) != OC_STACK_OK)
1278 result = OC_STACK_NO_MEMORY;
1284 // Generate token which will be used by OCStack to match responses received
1286 OCGenerateCoAPToken(&token);
1288 if((result = AddClientCB(&clientCB, cbData, &token, handle, method, requestUri, resourceType))
1291 result = OC_STACK_NO_MEMORY;
1295 #ifdef WITH_PRESENCE
1296 if(method == OC_REST_PRESENCE)
1298 // Replacing method type with GET because "presence" is a stack layer only implementation.
1299 method = OC_REST_GET;
1303 // Make call to OCCoAP layer
1304 result = OCDoCoAPResource(method, qos, &token, newUri, request, options, numOptions);
1308 if(newUri != requiredUri)
1312 if (result != OC_STACK_OK)
1314 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1315 FindAndDeleteClientCB(clientCB);
1318 CADestroyRemoteEndpoint(endpoint);
1319 if (hdrOptionMemAlloc)
1321 OCFree(requestData.options);
1323 //TODO-CA: CADestroyToken here
1329 * Cancel a request associated with a specific @ref OCDoResource invocation.
1331 * @param handle - Used to identify a specific OCDoResource invocation.
1332 * @param qos - used to specify Quality of Service (read below for more info)
1333 * @param options- used to specify vendor specific header options when sending
1334 * explicit observe cancellation
1335 * @param numOptions- Number of header options to be included
1338 * OC_STACK_OK - No errors; Success
1339 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1341 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1342 uint8_t numOptions) {
1344 * This ftn is implemented one of two ways in the case of observation:
1346 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1347 * Remove the callback associated on client side.
1348 * When the next notification comes in from server,
1349 * reply with RESET message to server.
1350 * Keep in mind that the server will react to RESET only
1351 * if the last notification was sent ans CON
1353 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1354 * and it is associated with an observe request
1355 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1356 * Send CON Observe request to server with
1357 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1358 * Remove the callback associated on client side.
1360 OCStackResult ret = OC_STACK_OK;
1363 return OC_STACK_INVALID_PARAM;
1366 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1368 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1371 switch (clientCB->method)
1373 case OC_REST_OBSERVE:
1374 case OC_REST_OBSERVE_ALL:
1375 if(qos == OC_HIGH_QOS)
1377 ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
1378 &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
1383 FindAndDeleteClientCB(clientCB);
1386 #ifdef WITH_PRESENCE
1387 case OC_REST_PRESENCE:
1388 FindAndDeleteClientCB(clientCB);
1392 return OC_STACK_INVALID_METHOD;
1397 #ifdef WITH_PRESENCE
1398 OCStackResult OCProcessPresence()
1400 OCStackResult result = OC_STACK_OK;
1401 uint8_t ipAddr[4] = { 0 };
1404 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1405 ClientCB* cbNode = NULL;
1407 OCClientResponse clientResponse;
1408 OCResponse * response = NULL;
1410 LL_FOREACH(cbList, cbNode) {
1411 if(OC_REST_PRESENCE == cbNode->method)
1413 if(cbNode->presence)
1415 uint32_t now = GetTime(0);
1416 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
1417 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1420 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1425 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1426 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1427 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1430 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1432 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1433 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1435 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1437 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
1438 (OCDevAddr *) &dst, 0, NULL);
1439 if(result != OC_STACK_OK)
1443 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1444 &cbNode->token, &clientResponse, NULL);
1445 if(result != OC_STACK_OK)
1450 // Increment the TTLLevel (going to a next state), so we don't keep
1451 // sending presence notification to client.
1452 cbNode->presence->TTLlevel++;
1453 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1454 cbNode->presence->TTLlevel);
1458 result = OC_STACK_INVALID_IP;
1461 HandleStackResponses(response);
1463 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1465 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
1467 OCGenerateCoAPToken(&token);
1468 result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
1469 &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
1470 if(result != OC_STACK_OK)
1474 cbNode->presence->TTLlevel++;
1475 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
1481 if (result != OC_STACK_OK)
1483 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
1490 * Called in main loop of OC client or server. Allows low-level processing of
1494 * OC_STACK_OK - no errors
1495 * OC_STACK_ERROR - stack process error
1497 OCStackResult OCProcess() {
1499 OC_LOG(INFO, TAG, PCF("Entering OCProcess"));
1500 #ifdef WITH_PRESENCE
1501 OCProcessPresence();
1504 CAHandleRequestResponse();
1512 #ifdef WITH_PRESENCE
1514 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
1515 * presence notifications to clients via multicast. Once this API has been called with a success,
1516 * clients may query for this server's presence and this server's stack will respond via multicast.
1518 * Server can call this function when it comes online for the first time, or when it comes back
1519 * online from offline mode, or when it re enters network.
1521 * @param ttl - Time To Live in seconds
1522 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
1525 * OC_STACK_OK - No errors; Success
1527 OCStackResult OCStartPresence(const uint32_t ttl)
1529 OCChangeResourceProperty(
1530 &(((OCResource *)presenceResource.handle)->resourceProperties),
1535 presenceResource.presenceTTL = ttl;
1538 if(OC_PRESENCE_UNINITIALIZED == presenceState)
1540 OCDevAddr multiCastAddr;
1543 presenceState = OC_PRESENCE_INITIALIZED;
1544 OCGenerateCoAPToken(&token);
1545 OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
1546 //add the presence observer
1547 AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
1548 (OCResource *)presenceResource.handle, OC_LOW_QOS);
1551 // Each time OCStartPresence is called
1552 // a different random 32-bit integer number is used
1553 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1555 return SendPresenceNotification(NULL);
1559 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
1560 * presence notifications to clients via multicast. Once this API has been called with a success,
1561 * this server's stack will not respond to clients querying for this server's presence.
1563 * Server can call this function when it is terminating, going offline, or when going
1564 * away from network.
1567 * OC_STACK_OK - No errors; Success
1569 OCStackResult OCStopPresence()
1571 OCStackResult result = OC_STACK_ERROR;
1572 //make resource inactive
1573 result = OCChangeResourceProperty(
1574 &(((OCResource *) presenceResource.handle)->resourceProperties),
1576 result = SendPresenceNotification(NULL);
1583 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
1585 defaultDeviceHandler = entityHandler;
1593 * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource
1594 * @param resourceTypeName - name of resource type. Example: "core.led"
1595 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1596 * @param uri - URI of the resource. Example: "/a/led"
1597 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1598 * NULL for default entity handler
1599 * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE
1602 * OC_STACK_OK - no errors
1603 * OC_STACK_ERROR - stack process error
1605 OCStackResult OCCreateResource(OCResourceHandle *handle,
1606 const char *resourceTypeName,
1607 const char *resourceInterfaceName,
1608 const char *uri, OCEntityHandler entityHandler,
1609 uint8_t resourceProperties) {
1611 OCResource *pointer = NULL;
1614 OCStackResult result = OC_STACK_ERROR;
1616 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
1618 if(myStackMode == OC_CLIENT)
1622 // Validate parameters
1623 // Is it presented during resource discovery?
1624 if (!handle || !resourceTypeName || !uri) {
1625 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
1626 return OC_STACK_INVALID_PARAM;
1629 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
1630 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
1633 // Make sure resourceProperties bitmask has allowed properties specified
1634 if (resourceProperties
1635 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
1636 OC_LOG(ERROR, TAG, PCF("Invalid property"));
1637 return OC_STACK_INVALID_PARAM;
1640 // If the headResource is NULL, then no resources have been created...
1641 pointer = headResource;
1643 // At least one resources is in the resource list, so we need to search for
1644 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
1646 if (strcmp(uri, pointer->uri) == 0) {
1647 OC_LOG(ERROR, TAG, PCF("URI already in use"));
1648 return OC_STACK_INVALID_PARAM;
1650 pointer = pointer->next;
1653 // Create the pointer and insert it into the resource list
1654 pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
1658 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
1660 insertResource(pointer);
1663 size = strlen(uri) + 1;
1664 str = (char *) OCMalloc(size);
1668 strncpy(str, uri, size);
1671 // Set properties. Set OC_ACTIVE
1672 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
1675 // Add the resourcetype to the resource
1676 result = BindResourceTypeToResource(pointer, resourceTypeName);
1677 if (result != OC_STACK_OK) {
1678 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
1682 // Add the resourceinterface to the resource
1683 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
1684 if (result != OC_STACK_OK) {
1685 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
1689 // If an entity handler has been passed, attach it to the newly created
1690 // resource. Otherwise, set the default entity handler.
1693 pointer->entityHandler = entityHandler;
1697 pointer->entityHandler = defaultResourceEHandler;
1701 result = OC_STACK_OK;
1703 #ifdef WITH_PRESENCE
1704 if(presenceResource.handle)
1706 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1707 SendPresenceNotification(pointer->rsrcType);
1711 if (result != OC_STACK_OK)
1713 // Deep delete of resource and other dynamic elements that it contains
1714 deleteResource(pointer);
1723 * Create a resource. with host ip address for remote resource
1725 * @param handle - pointer to handle to newly created resource. Set by ocstack.
1726 * Used to refer to resource
1727 * @param resourceTypeName - name of resource type. Example: "core.led"
1728 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1729 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
1730 * @param uri - URI of the resource. Example: "/a/led"
1731 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1732 * NULL for default entity handler
1733 * @param resourceProperties - properties supported by resource.
1734 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
1737 * OC_STACK_OK - no errors
1738 * OC_STACK_ERROR - stack process error
1741 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
1742 const char *resourceTypeName,
1743 const char *resourceInterfaceName,
1746 OCEntityHandler entityHandler,
1747 uint8_t resourceProperties)
1751 OCStackResult result = OC_STACK_ERROR;
1753 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
1754 uri, entityHandler, resourceProperties);
1756 if (result != OC_STACK_ERROR)
1759 size = strlen(host) + 1;
1760 str = (char *) OCMalloc(size);
1763 return OC_STACK_ERROR;
1765 strncpy(str, host, size);
1766 ((OCResource *) *handle)->host = str;
1773 * Add a resource to a collection resource.
1775 * @param collectionHandle - handle to the collection resource
1776 * @param resourceHandle - handle to resource to be added to the collection resource
1779 * OC_STACK_OK - no errors
1780 * OC_STACK_ERROR - stack process error
1781 * OC_STACK_INVALID_PARAM - invalid collectionhandle
1783 OCStackResult OCBindResource(
1784 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1785 OCResource *resource;
1788 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
1790 // Validate parameters
1791 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1792 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1793 // Container cannot contain itself
1794 if (collectionHandle == resourceHandle) {
1795 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
1796 return OC_STACK_INVALID_PARAM;
1799 // Use the handle to find the resource in the resource linked list
1800 resource = findResource((OCResource *) collectionHandle);
1802 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1803 return OC_STACK_INVALID_PARAM;
1806 // Look for an open slot to add add the child resource.
1807 // If found, add it and return success
1808 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1809 if (!resource->rsrcResources[i]) {
1810 resource->rsrcResources[i] = (OCResource *) resourceHandle;
1811 OC_LOG(INFO, TAG, PCF("resource bound"));
1816 #ifdef WITH_PRESENCE
1817 if(presenceResource.handle)
1819 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1820 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1824 // Unable to add resourceHandle, so return error
1825 return OC_STACK_ERROR;
1829 * Remove a resource from a collection resource.
1831 * @param collectionHandle - handle to the collection resource
1832 * @param resourceHandle - handle to resource to be added to the collection resource
1835 * OC_STACK_OK - no errors
1836 * OC_STACK_ERROR - stack process error
1837 * OC_STACK_INVALID_PARAM - invalid collectionHandle
1839 OCStackResult OCUnBindResource(
1840 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1841 OCResource *resource;
1844 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
1846 // Validate parameters
1847 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1848 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1849 // Container cannot contain itself
1850 if (collectionHandle == resourceHandle) {
1851 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
1852 return OC_STACK_INVALID_PARAM;
1855 // Use the handle to find the resource in the resource linked list
1856 resource = findResource((OCResource *) collectionHandle);
1858 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1859 return OC_STACK_INVALID_PARAM;
1862 // Look for an open slot to add add the child resource.
1863 // If found, add it and return success
1864 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1865 if (resourceHandle == resource->rsrcResources[i]) {
1866 resource->rsrcResources[i] = (OCResource *) NULL;
1867 OC_LOG(INFO, TAG, PCF("resource unbound"));
1872 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
1874 #ifdef WITH_PRESENCE
1875 if(presenceResource.handle)
1877 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1878 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1882 // Unable to add resourceHandle, so return error
1883 return OC_STACK_ERROR;
1886 OCStackResult BindResourceTypeToResource(OCResource* resource,
1887 const char *resourceTypeName)
1889 OCResourceType *pointer = NULL;
1892 OCStackResult result = OC_STACK_ERROR;
1894 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
1896 // Validate parameters
1897 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
1898 // TODO: Does resource attribute resentation really have to be maintained in stack?
1899 // Is it presented during resource discovery?
1901 TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
1903 // Create the resourcetype and insert it into the resource list
1904 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
1909 // Set the resourceTypeName
1910 size = strlen(resourceTypeName) + 1;
1911 str = (char *) OCMalloc(size);
1915 strncpy(str, resourceTypeName, size);
1916 pointer->resourcetypename = str;
1918 insertResourceType(resource, pointer);
1919 result = OC_STACK_OK;
1921 exit: if (result != OC_STACK_OK) {
1929 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
1930 const char *resourceInterfaceName)
1932 OCResourceInterface *pointer = NULL;
1935 OCStackResult result = OC_STACK_ERROR;
1937 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
1939 // Validate parameters
1940 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
1942 TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
1944 // Create the resourceinterface and insert it into the resource list
1945 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
1950 // Set the resourceinterface name
1951 size = strlen(resourceInterfaceName) + 1;
1952 str = (char *) OCMalloc(size);
1956 strncpy(str, resourceInterfaceName, size);
1957 pointer->name = str;
1959 // Bind the resourceinterface to the resource
1960 insertResourceInterface(resource, pointer);
1962 result = OC_STACK_OK;
1964 exit: if (result != OC_STACK_OK) {
1973 * Bind a resourcetype to a resource.
1975 * @param handle - handle to the resource
1976 * @param resourceTypeName - name of resource type. Example: "core.led"
1979 * OC_STACK_OK - no errors
1980 * OC_STACK_ERROR - stack process error
1982 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
1983 const char *resourceTypeName) {
1985 OCStackResult result = OC_STACK_ERROR;
1986 OCResource *resource;
1988 // Make sure resource exists
1989 resource = findResource((OCResource *) handle);
1991 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1992 return OC_STACK_ERROR;
1995 // call internal function
1996 result = BindResourceTypeToResource(resource, resourceTypeName);
1998 #ifdef WITH_PRESENCE
1999 if(presenceResource.handle)
2001 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2002 SendPresenceNotification(resource->rsrcType);
2010 * Bind a resourceinterface to a resource.
2012 * @param handle - handle to the resource
2013 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
2016 * OC_STACK_OK - no errors
2017 * OC_STACK_ERROR - stack process error
2020 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2021 const char *resourceInterfaceName) {
2023 OCStackResult result = OC_STACK_ERROR;
2024 OCResource *resource;
2026 // Make sure resource exists
2027 resource = findResource((OCResource *) handle);
2029 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2030 return OC_STACK_ERROR;
2033 // call internal function
2034 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2036 #ifdef WITH_PRESENCE
2037 if(presenceResource.handle)
2039 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2040 SendPresenceNotification(resource->rsrcType);
2048 * Get the number of resources that have been created in the stack.
2050 * @param numResources - pointer to count variable
2053 * OC_STACK_OK - no errors
2054 * OC_STACK_ERROR - stack process error
2057 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
2058 OCResource *pointer = headResource;
2060 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2061 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2064 *numResources = *numResources + 1;
2065 pointer = pointer->next;
2071 * Get a resource handle by index.
2073 * @param index - index of resource, 0 to Count - 1
2076 * Resource handle - if found
2077 * NULL - if not found
2079 OCResourceHandle OCGetResourceHandle(uint8_t index) {
2080 OCResource *pointer = headResource;
2083 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2085 // Iterate through the list
2086 while ((i < index) && pointer) {
2088 pointer = pointer->next;
2090 return (OCResourceHandle) pointer;
2094 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
2097 * @param handle - handle of resource to be deleted
2100 * OC_STACK_OK - no errors
2101 * OC_STACK_ERROR - stack process error
2102 * OC_STACK_NO_RESOURCE - resource not found
2103 * OC_STACK_INVALID_PARAM - invalid param
2105 OCStackResult OCDeleteResource(OCResourceHandle handle) {
2106 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2109 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2110 return OC_STACK_INVALID_PARAM;
2113 OCResource *resource = findResource((OCResource *) handle);
2114 if (resource == NULL) {
2115 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2116 return OC_STACK_NO_RESOURCE;
2119 if (deleteResource((OCResource *) handle) == 0) {
2120 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2121 return OC_STACK_ERROR;
2128 * Get the URI of the resource specified by handle.
2130 * @param handle - handle of resource
2132 * URI string - if resource found
2133 * NULL - resource not found
2135 const char *OCGetResourceUri(OCResourceHandle handle) {
2136 OCResource *resource;
2137 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2139 resource = findResource((OCResource *) handle);
2141 return resource->uri;
2143 return (const char *) NULL;
2147 * Get the properties of the resource specified by handle.
2148 * NOTE: that after a resource is created, the OC_ACTIVE property is set
2149 * for the resource by the stack.
2151 * @param handle - handle of resource
2153 * property bitmap - if resource found
2154 * NULL - resource not found
2156 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
2157 OCResource *resource;
2158 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2160 resource = findResource((OCResource *) handle);
2162 return resource->resourceProperties;
2168 * Get the number of resource types of the resource.
2170 * @param handle - handle of resource
2171 * @param numResourceTypes - pointer to count variable
2174 * OC_STACK_OK - no errors
2175 * OC_STACK_ERROR - stack process error
2177 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2178 uint8_t *numResourceTypes) {
2179 OCResource *resource;
2180 OCResourceType *pointer;
2182 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2183 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2184 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2186 *numResourceTypes = 0;
2188 resource = findResource((OCResource *) handle);
2190 pointer = resource->rsrcType;
2192 *numResourceTypes = *numResourceTypes + 1;
2193 pointer = pointer->next;
2200 * Get name of resource type of the resource.
2202 * @param handle - handle of resource
2203 * @param index - index of resource, 0 to Count - 1
2206 * resource type name - if resource found
2207 * NULL - resource not found
2209 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
2210 OCResourceType *resourceType;
2212 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2214 resourceType = findResourceTypeAtIndex(handle, index);
2216 return resourceType->resourcetypename;
2218 return (const char *) NULL;
2224 * Get the number of resource interfaces of the resource.
2226 * @param handle - handle of resource
2227 * @param numResources - pointer to count variable
2230 * OC_STACK_OK - no errors
2231 * OC_STACK_ERROR - stack process error
2233 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2234 uint8_t *numResourceInterfaces) {
2235 OCResourceInterface *pointer;
2236 OCResource *resource;
2238 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2240 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2241 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2243 *numResourceInterfaces = 0;
2244 resource = findResource((OCResource *) handle);
2246 pointer = resource->rsrcInterface;
2248 *numResourceInterfaces = *numResourceInterfaces + 1;
2249 pointer = pointer->next;
2256 * Get name of resource interface of the resource.
2258 * @param handle - handle of resource
2259 * @param index - index of resource, 0 to Count - 1
2262 * resource interface name - if resource found
2263 * NULL - resource not found
2265 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
2266 OCResourceInterface *resourceInterface;
2268 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2270 resourceInterface = findResourceInterfaceAtIndex(handle, index);
2271 if (resourceInterface) {
2272 return resourceInterface->name;
2274 return (const char *) NULL;
2278 * Get resource handle from the collection resource by index.
2280 * @param collectionHandle - handle of collection resource
2281 * @param index - index of contained resource, 0 to Count - 1
2284 * handle to resource - if resource found
2285 * NULL - resource not found
2287 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2289 OCResource *resource;
2291 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2293 if (index >= MAX_CONTAINED_RESOURCES) {
2297 resource = findResource((OCResource *) collectionHandle);
2302 return resource->rsrcResources[index];
2306 * Bind an entity handler to the resource.
2308 * @param handle - handle to the resource that the contained resource is to be bound
2309 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2311 * OC_STACK_OK - no errors
2312 * OC_STACK_ERROR - stack process error
2314 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2315 OCEntityHandler entityHandler) {
2316 OCResource *resource;
2318 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2320 // Validate parameters
2321 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2322 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2324 // Use the handle to find the resource in the resource linked list
2325 resource = findResource((OCResource *)handle);
2327 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2328 return OC_STACK_ERROR;
2332 resource->entityHandler = entityHandler;
2334 #ifdef WITH_PRESENCE
2335 if(presenceResource.handle)
2337 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2338 SendPresenceNotification(resource->rsrcType);
2346 * Get the entity handler for a resource.
2348 * @param handle - handle of resource
2351 * entity handler - if resource found
2352 * NULL - resource not found
2354 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
2355 OCResource *resource;
2357 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2359 // Use the handle to find the resource in the resource linked list
2360 resource = findResource((OCResource *)handle);
2362 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2367 return resource->entityHandler;
2370 void incrementSequenceNumber(OCResource * resPtr)
2372 // Increment the sequence number
2373 resPtr->sequenceNum += 1;
2374 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2376 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2382 * Notify Presence subscribers that a resource has been modified
2384 * @param resourceType - Handle to the resourceType linked list of resource
2385 * that was modified.
2386 * @param qos - Quality Of Service
2389 #ifdef WITH_PRESENCE
2390 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
2392 OCResource *resPtr = NULL;
2393 OCStackResult result;
2394 OCMethod method = OC_REST_PRESENCE;
2395 uint32_t maxAge = 0;
2396 resPtr = findResource((OCResource *) presenceResource.handle);
2399 return OC_STACK_NO_RESOURCE;
2401 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
2403 maxAge = presenceResource.presenceTTL;
2410 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
2413 #endif // WITH_PRESENCE
2415 * Notify observers that an observed value has changed.
2417 * @param handle - handle of resource
2420 * OC_STACK_OK - no errors
2421 * OC_STACK_NO_RESOURCE - invalid resource handle
2422 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
2424 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
2426 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2428 OCResource *resPtr = NULL;
2429 OCStackResult result;
2430 OCMethod method = OC_REST_NOMETHOD;
2431 uint32_t maxAge = 0;
2433 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2434 #ifdef WITH_PRESENCE
2435 if(handle == presenceResource.handle)
2439 #endif // WITH_PRESENCE
2440 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2442 // Verify that the resource exists
2443 resPtr = findResource ((OCResource *) handle);
2446 return OC_STACK_NO_RESOURCE;
2450 //only increment in the case of regular observing (not presence)
2451 incrementSequenceNumber(resPtr);
2452 method = OC_REST_OBSERVE;
2453 maxAge = MAX_OBSERVE_AGE;
2454 #ifdef WITH_PRESENCE
2455 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
2457 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
2464 OCNotifyListOfObservers (OCResourceHandle handle,
2465 OCObservationId *obsIdList,
2466 uint8_t numberOfIds,
2467 unsigned char *notificationJSONPayload,
2468 OCQualityOfService qos)
2470 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
2472 OCResource *resPtr = NULL;
2473 //TODO: we should allow the server to define this
2474 uint32_t maxAge = MAX_OBSERVE_AGE;
2476 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2477 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
2478 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
2480 // Verify that the resource exists
2481 resPtr = findResource ((OCResource *) handle);
2482 if (NULL == resPtr || myStackMode == OC_CLIENT)
2484 return OC_STACK_NO_RESOURCE;
2488 incrementSequenceNumber(resPtr);
2490 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
2491 notificationJSONPayload, maxAge, qos));
2495 * Send a response to a request.
2496 * The response can be a regular, slow, or block (i.e. a response that
2497 * is too large to be sent in a single PDU and must span multiple transmissions)
2499 * @param response - pointer to structure that contains response parameters
2502 * OC_STACK_OK - No errors; Success
2503 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
2504 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
2505 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
2506 * persistent response buffer is necessary
2508 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
2510 OCStackResult result = OC_STACK_ERROR;
2511 OCServerRequest *serverRequest = NULL;
2513 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
2515 // Validate input parameters
2516 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
2517 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
2519 // TODO: Placeholder for creating a response entry when implementing
2520 // block transfer feature
2522 // If a response payload is present, check if block transfer is required
2523 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
2524 (const char *)ehResponse->payload, ehResponse->payloadSize))
2526 OC_LOG(INFO, TAG, PCF("Block transfer required"));
2528 // Persistent response buffer is needed for block transfer
2529 if (!ehResponse->persistentBufferFlag)
2531 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
2532 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
2534 // TODO: Placeholder for block transfer handling
2535 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
2536 // when implementing the block transfer feature
2542 // Get pointer to request info
2543 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
2546 result = serverRequest->ehResponseHandler(ehResponse);
2553 * Cancel a response. Applies to a block response
2555 * @param responseHandle - response handle set by stack in OCServerResponse after
2556 * OCDoResponse is called
2559 * OC_STACK_OK - No errors; Success
2560 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
2562 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
2564 OCStackResult result = OC_STACK_NOTIMPL;
2566 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
2568 // TODO: validate response handle
2573 //-----------------------------------------------------------------------------
2574 // Private internal function definitions
2575 //-----------------------------------------------------------------------------
2577 * Generate handle of OCDoResource invocation for callback management.
2579 static OCDoHandle GenerateInvocationHandle()
2581 OCDoHandle handle = NULL;
2582 // Generate token here, it will be deleted when the transaction is deleted
2583 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2586 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2591 #ifdef WITH_PRESENCE
2592 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
2593 OCResourceProperty resourceProperties, uint8_t enable)
2595 if (resourceProperties
2596 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
2597 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2598 return OC_STACK_INVALID_PARAM;
2602 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
2606 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
2613 * Initialize resource data structures, variables, etc.
2615 OCStackResult initResources() {
2616 OCStackResult result = OC_STACK_OK;
2617 // Init application resource vars
2618 headResource = NULL;
2619 // Init Virtual Resources
2620 #ifdef WITH_PRESENCE
2621 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
2622 //presenceResource.token = OCGenerateCoAPToken();
2623 result = OCCreateResource(&presenceResource.handle,
2624 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
2629 //make resource inactive
2630 result = OCChangeResourceProperty(
2631 &(((OCResource *) presenceResource.handle)->resourceProperties),
2638 * Add a resource to the end of the linked list of resources.
2640 * @param resource - resource to be added
2642 void insertResource(OCResource *resource) {
2643 OCResource *pointer;
2645 if (!headResource) {
2646 headResource = resource;
2648 pointer = headResource;
2650 while (pointer->next) {
2651 pointer = pointer->next;
2653 pointer->next = resource;
2655 resource->next = NULL;
2659 * Find a resource in the linked list of resources.
2661 * @param resource - resource to be found
2663 * NULL - resource not found
2664 * pointer to resource - pointer to resource that was found in the linked list
2666 OCResource *findResource(OCResource *resource) {
2667 OCResource *pointer = headResource;
2670 if (pointer == resource) {
2673 pointer = pointer->next;
2678 void deleteAllResources()
2680 OCResource *pointer = headResource;
2685 temp = pointer->next;
2686 #ifdef WITH_PRESENCE
2687 if(pointer != (OCResource *) presenceResource.handle)
2689 #endif // WITH_PRESENCE
2690 deleteResource(pointer);
2691 #ifdef WITH_PRESENCE
2693 #endif // WITH_PRESENCE
2697 #ifdef WITH_PRESENCE
2698 // Ensure that the last resource to be deleted is the presence resource. This allows for all
2699 // presence notification attributed to their deletion to be processed.
2700 deleteResource((OCResource *) presenceResource.handle);
2701 #endif // WITH_PRESENCE
2705 * Delete the resource from the linked list.
2707 * @param resource - resource to be deleted
2712 int deleteResource(OCResource *resource) {
2713 OCResource *prev = NULL;
2716 temp = headResource;
2718 if (temp == resource) {
2719 // Invalidate all Resource Properties.
2720 resource->resourceProperties = (OCResourceProperty) 0;
2721 #ifdef WITH_PRESENCE
2722 if(resource != (OCResource *) presenceResource.handle)
2724 #endif // WITH_PRESENCE
2725 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
2726 #ifdef WITH_PRESENCE
2729 if(presenceResource.handle)
2731 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2732 if(resource != (OCResource *) presenceResource.handle)
2734 SendPresenceNotification(resource->rsrcType);
2738 SendPresenceNotification(NULL);
2743 if (temp == headResource) {
2744 headResource = temp->next;
2746 prev->next = temp->next;
2749 deleteResourceElements(temp);
2762 * Delete all of the dynamically allocated elements that were created for the resource.
2764 * @param resource - specified resource
2766 void deleteResourceElements(OCResource *resource) {
2772 OCFree(resource->uri);
2774 // Delete resourcetype linked list
2775 deleteResourceType(resource->rsrcType);
2777 // Delete resourceinterface linked list
2778 deleteResourceInterface(resource->rsrcInterface);
2782 * Delete all of the dynamically allocated elements that were created for the resource type.
2784 * @param resourceType - specified resource type
2786 void deleteResourceType(OCResourceType *resourceType) {
2787 OCResourceType *pointer = resourceType;
2788 OCResourceType *next;
2791 next = pointer->next;
2792 OCFree(pointer->resourcetypename);
2799 * Delete all of the dynamically allocated elements that were created for the resource interface.
2801 * @param resourceInterface - specified resource interface
2803 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
2804 OCResourceInterface *pointer = resourceInterface;
2805 OCResourceInterface *next;
2808 next = pointer->next;
2809 OCFree(pointer->name);
2816 * Insert a resource type into a resource's resource type linked list.
2818 * @param resource - resource where resource type is to be inserted
2819 * @param resourceType - resource type to be inserted
2821 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
2822 OCResourceType *pointer;
2824 if (resource && !resource->rsrcType) {
2825 resource->rsrcType = resourceType;
2829 pointer = resource->rsrcType;
2833 pointer = resourceType;
2835 while (pointer->next) {
2836 pointer = pointer->next;
2838 pointer->next = resourceType;
2840 resourceType->next = NULL;
2844 * Get a resource type at the specified index within a resource.
2846 * @param handle - handle of resource
2847 * @param index - index of resource type
2850 * resourcetype - if found
2853 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
2854 OCResource *resource;
2855 OCResourceType *pointer;
2858 // Find the specified resource
2859 resource = findResource((OCResource *) handle);
2864 // Make sure a resource has a resourcetype
2865 if (!resource->rsrcType) {
2869 // Iterate through the list
2870 pointer = resource->rsrcType;
2872 while ((i < index) && pointer) {
2874 pointer = pointer->next;
2880 * Finds a resource type in an OCResourceType link-list.
2882 * @param resourceTypeList - the link-list to be searched through
2883 * @param resourceTypeName - the key to search for
2886 * resourceType that matches the key (ie. resourceTypeName)
2887 * NULL - either an invalid parameter or this function was unable to find the key.
2889 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
2891 if(resourceTypeList && resourceTypeName)
2893 OCResourceType * rtPointer = resourceTypeList;
2894 while(resourceTypeName && rtPointer)
2896 if(rtPointer->resourcetypename &&
2897 strcmp(resourceTypeName, (const char *)
2898 (rtPointer->resourcetypename)) == 0)
2902 rtPointer = rtPointer->next;
2909 * Insert a resource interface into a resource's resource interface linked list.
2911 * @param resource - resource where resource interface is to be inserted
2912 * @param resourceInterface - resource interface to be inserted
2914 void insertResourceInterface(OCResource *resource,
2915 OCResourceInterface *resourceInterface) {
2916 OCResourceInterface *pointer;
2918 if (!resource->rsrcInterface) {
2919 resource->rsrcInterface = resourceInterface;
2921 pointer = resource->rsrcInterface;
2922 while (pointer->next) {
2923 pointer = pointer->next;
2925 pointer->next = resourceInterface;
2927 resourceInterface->next = NULL;
2931 * Get a resource interface at the specified index within a resource.
2933 * @param handle - handle of resource
2934 * @param index - index of resource interface
2937 * resourceinterface - if found
2940 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
2942 OCResource *resource;
2943 OCResourceInterface *pointer;
2946 // Find the specified resource
2947 resource = findResource((OCResource *) handle);
2952 // Make sure a resource has a resourceinterface
2953 if (!resource->rsrcInterface) {
2957 // Iterate through the list
2958 pointer = resource->rsrcInterface;
2960 while ((i < index) && pointer) {
2962 pointer = pointer->next;
2968 * Determine if a request/response must be sent in a block transfer because it is too large to be
2969 * sent in a single PDU. This function can be used for either a request or a response
2971 * @param request - NULL or pointer to request
2972 * @param response - NULL or pointer to response
2973 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
2974 * the length of the request/response
2977 * 0 - packet transfer NOT required (i.e. normal request/response)
2978 * 1 - packet transfer required (i.e. block transfer needed)
2980 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
2984 // Determine if we are checking a request or a response
2987 // If size is greater than 0, use it for the request size value, otherwise
2988 // assume request is null terminated and use strlen for size value
2989 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
2996 // If size is greater than 0, use it for the response size value, otherwise
2997 // assume response is null terminated and use strlen for size value
2998 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3007 * Retrieves a resource type based upon a uri string if the uri string contains only just one
3008 * resource attribute (and that has to be of type "rt").
3010 * @remark This API malloc's memory for the resource type and newURI. Do not malloc resourceType
3011 * or newURI before passing in.
3013 * @param uri - Valid URI for "requiredUri" parameter to OCDoResource API.
3014 * @param resourceType - The resource type to be populated; pass by reference.
3015 * @param newURI - Return URI without resourceType appended to the end of it. This is used to
3016 * ensure that the uri parameter is not modified; pass by reference.
3019 * OC_STACK_INVALID_URI - Returns this if the URI is invalid/NULL.
3020 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
3021 * OC_STACK_OK - Success
3023 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI)
3027 return OC_STACK_INVALID_URI;
3029 if(!resourceType || !newURI)
3031 return OC_STACK_INVALID_PARAM;
3033 char * leftToken = NULL;
3034 char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3039 strcpy(tempURI, uri);
3040 leftToken = strtok((char *)tempURI, "?");
3042 while(leftToken != NULL)
3044 if(strncmp(leftToken, "rt=", 3) == 0)
3046 *resourceType = (unsigned char *) OCMalloc(strlen(leftToken)-3);
3051 strcpy((char *)*resourceType, ((const char *)&leftToken[3]));
3054 leftToken = strtok(NULL, "?");
3062 return OC_STACK_NO_MEMORY;
3065 const ServerID OCGetServerInstanceID(void)
3067 static bool generated = false;
3068 static ServerID sid;
3075 sid = OCGetRandom();
3080 const char* OCGetServerInstanceIDString(void)
3082 // max printed length of a base 10
3083 // uint32 is 10 characters, so 11 includes null.
3084 // This will change as the representation gets switched
3086 static char buffer[11];
3087 int n = sprintf(buffer, "%u", OCGetServerInstanceID());