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 printf("\n*****************************\nobservation is %u\n**********************************\n",serverRequest.observationOption);
386 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
388 // TODO-CA: Need to send an error indicating the num of options is incorrect
391 serverRequest.numRcvdVendorSpecificHeaderOptions = requestInfo->info.numOptions;
392 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
394 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
395 sizeof(CAHeaderOption_t)*requestInfo->info.numOptions);
398 requestResult = HandleStackRequests (&serverRequest);
402 // generate the pdu, if the request was CON, then the response is ACK, otherwire NON
403 memset(&responseData, 0, sizeof(CAInfo_t));
404 responseData.token = (requestInfo != NULL) ? requestInfo->info.token : "";
406 // TODO : I guess we need to allocate memeory?
407 responseData.payload = "{\"oc\":[{\"href\":\"/a/led\",\"sid\":\"\",\"prop\":{\"rt\":[\"core.led\"],\"if\":[\"oc.mi.def\"],\"obs\":1}}]}";
409 //responseInfo = (CAResponseInfo*) malloc(sizeof(CAResponseInfo));
410 memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
411 responseInfo.result = 200;
412 responseInfo.info = responseData;
414 // send request (connectivityType from remoteEndpoint of request Info)
415 OC_LOG(INFO, TAG, PCF("CASendResponse in HandleCARequests"));
416 //TODO-CA: CASendResponse returns the result (we need to check if the
418 CAResult_t caResult = CASendResponse(endPoint, &responseInfo);
419 if(caResult != CA_STATUS_OK)
421 OC_LOG(ERROR, TAG, PCF("CASendResponse error"));
425 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
430 //This function will be called back by occoap layer when a request is received
431 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
433 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
435 OCStackResult result = OC_STACK_ERROR;
436 ResourceHandling resHandling;
437 OCResource *resource;
439 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
442 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
444 result = AddServerCARequest(&request, protocolRequest->coapID,
445 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
446 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
447 protocolRequest->observationOption, protocolRequest->qos,
448 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
449 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
450 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
451 protocolRequest->reqTotalSize,
452 &protocolRequest->addressInfo, protocolRequest->connectivityType, protocolRequest->token);
454 result = AddServerRequest(&request, protocolRequest->coapID,
455 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
456 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
457 protocolRequest->observationOption, protocolRequest->qos,
458 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
459 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
460 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
461 protocolRequest->reqTotalSize);
463 if (OC_STACK_OK != result)
465 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
468 VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
470 if(!protocolRequest->reqMorePacket)
472 request->requestComplete = 1;
477 OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
480 if(request->requestComplete)
482 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
483 result = DetermineResourceHandling (request, &resHandling, &resource);
484 if (result == OC_STACK_OK)
486 result = ProcessRequest(resHandling, resource, request);
490 result = OC_STACK_ERROR;
495 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
496 result = OC_STACK_CONTINUE;
501 //This function will be called back by occoap layer when a response is received
502 OCStackResult HandleStackResponses(OCResponse * response)
504 OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)"));
505 OCStackResult result = OC_STACK_OK;
506 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
507 uint8_t isObserveNotification = 0;
508 ClientCB * cbNode = NULL;
510 uint8_t isPresenceNotification = 0;
511 uint8_t isMulticastPresence = 0;
512 char * resourceTypeName = NULL;
513 uint32_t lowerBound = 0;
514 uint32_t higherBound = 0;
516 unsigned char * bufRes = response->bufRes;
517 #endif // WITH_PRESENCE
519 cbNode = response->cbNode;
522 cbNode = GetClientCB(response->rcvdToken, NULL, NULL);
525 if(response->clientResponse->sequenceNumber >= OC_OFFSET_SEQUENCE_NUMBER)
527 isObserveNotification = 1;
528 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
531 OC_LOG_V(DEBUG, TAG, "The sequenceNumber/NONCE of this response %u",
532 response->clientResponse->sequenceNumber);
533 OC_LOG_V(DEBUG, TAG, "The maxAge/TTL of this response %u", response->maxAge);
534 OC_LOG_V(DEBUG, TAG, "The response received is %s", bufRes);
537 if(!strcmp((char *)response->rcvdUri, (char *)OC_PRESENCE_URI)){
538 isPresenceNotification = 1;
541 result = OC_STACK_INVALID_PARAM;
544 tok = strtok((char *)bufRes, "[:]}");
545 bufRes[strlen((char *)bufRes)] = ':';
546 tok = strtok(NULL, "[:]}");
547 bufRes[strlen((char *)bufRes)] = ':';
548 response->clientResponse->sequenceNumber = (uint32_t )atoi(tok);
549 OC_LOG_V(DEBUG, TAG, "The received NONCE is %u", response->clientResponse->sequenceNumber);
550 tok = strtok(NULL, "[:]}");
551 response->maxAge = (uint32_t )atoi(tok);
552 OC_LOG_V(DEBUG, TAG, "The received TTL is %u", response->maxAge);
553 tok = strtok(NULL, "[:]}");
556 resourceTypeName = (char *)OCMalloc(strlen(tok));
557 if(!resourceTypeName)
561 bufRes[strlen((char *)bufRes)] = ':';
562 strcpy(resourceTypeName, tok);
563 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
566 bufRes[strlen((char *)bufRes)] = ']';
569 // Check if the application subcribed for presence
572 cbNode = GetClientCB(NULL, NULL, response->fullUri);
575 // Check if application subscribed for multicast presence
578 snprintf((char *)response->fullUri, MAX_URI_LENGTH, "%s%s",
579 OC_MULTICAST_IP, response->rcvdUri);
580 cbNode = GetClientCB(NULL, NULL, response->fullUri);
583 isMulticastPresence = 1;
584 isPresenceNotification = 0;
588 if(cbNode && isPresenceNotification)
590 OC_LOG(INFO, TAG, PCF("Received a presence notification"));
591 if(!cbNode->presence)
593 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
594 VERIFY_NON_NULL_V(cbNode->presence);
595 cbNode->presence->timeOut = NULL;
596 cbNode->presence->timeOut = (uint32_t *)
597 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
598 if(!(cbNode->presence->timeOut)){
599 OCFree(cbNode->presence);
600 result = OC_STACK_NO_MEMORY;
603 if(response->maxAge == 0)
605 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
606 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
609 OCFree(cbNode->presence->timeOut);
610 OCFree(cbNode->presence);
611 cbNode->presence = NULL;
616 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %d", GetTime(0));
617 cbNode->presence->TTL = response->maxAge;
618 for(int index = 0; index < PresenceTimeOutSize; index++)
620 lowerBound = GetTime(((float)(PresenceTimeOut[index])
621 /(float)100)*(float)cbNode->presence->TTL);
622 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
623 /(float)100)*(float)cbNode->presence->TTL);
624 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
625 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
626 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
627 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
628 cbNode->presence->timeOut[index]);
630 cbNode->presence->TTLlevel = 0;
631 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
632 if(cbNode->sequenceNumber == response->clientResponse->sequenceNumber)
634 OC_LOG(INFO, TAG, PCF("===============No presence change"));
637 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
638 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;;
641 // Ensure that a filter is actually applied.
642 if(resourceTypeName && cbNode->filterResourceType)
644 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
650 else if(cbNode && isMulticastPresence)
652 // Check if the same nonce for a given host
653 OCMulticastNode* mcNode = NULL;
654 mcNode = GetMCPresenceNode(response->fullUri);
656 if(response->maxAge == 0)
658 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
659 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
662 OCFree(cbNode->presence->timeOut);
663 OCFree(cbNode->presence);
664 cbNode->presence = NULL;
667 else if(mcNode != NULL)
669 if(mcNode->nonce == response->clientResponse->sequenceNumber)
671 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
672 result = OC_STACK_NO_MEMORY;
675 mcNode->nonce = response->clientResponse->sequenceNumber;
679 uint32_t uriLen = strlen((char*)response->fullUri);
680 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
683 memcpy(uri, response->fullUri, (uriLen + 1));
688 PCF("===============No Memory for URI to store in the presence node"));
689 result = OC_STACK_NO_MEMORY;
692 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri,
693 response->clientResponse->sequenceNumber);
694 if(result == OC_STACK_NO_MEMORY)
697 PCF("===============No Memory for Multicast Presence Node"));
698 result = OC_STACK_NO_MEMORY;
703 // Ensure that a filter is actually applied.
704 if(resourceTypeName && cbNode->filterResourceType)
706 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
713 else if(!cbNode && isPresenceNotification)
715 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
716 ------------ ignoring"));
718 #endif // WITH_PRESENCE
722 if(isObserveNotification)
724 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
725 //TODO: check the standard for methods to detect wrap around condition
726 if(cbNode->method == OC_REST_OBSERVE &&
727 (response->clientResponse->sequenceNumber <= cbNode->sequenceNumber ||
728 (response->clientResponse->sequenceNumber > cbNode->sequenceNumber &&
729 response->clientResponse->sequenceNumber ==
730 MAX_SEQUENCE_NUMBER)))
732 OC_LOG_V(DEBUG, TAG, "Observe notification came out of order. \
733 Ignoring Incoming:%d Against Current:%d.",
734 response->clientResponse->sequenceNumber, cbNode->sequenceNumber);
737 if(response->clientResponse->sequenceNumber > cbNode->sequenceNumber){
738 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;
742 response->clientResponse->resJSONPayload = bufRes;
744 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response->clientResponse);
746 if (cbResult == OC_STACK_DELETE_TRANSACTION ||
747 response->clientResponse->result == OC_STACK_COMM_ERROR ||
748 (response->clientResponse->result == OC_STACK_RESOURCE_DELETED &&
749 !isPresenceNotification && !isMulticastPresence))
751 FindAndDeleteClientCB(cbNode);
756 result = OC_STACK_ERROR;
761 OCFree(resourceTypeName);
766 int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
769 unsigned char *itr, *coap;
770 uint8_t dotCount = 0;
774 /* search for scheme */
776 if (!isdigit((unsigned char) *ipAddrStr))
778 coap = (unsigned char *) OC_COAP_SCHEME;
779 while (*coap && tolower(*itr) == *coap)
788 if (isdigit((unsigned char) *ipAddrStr))
791 ipAddr[index] += *ipAddrStr - '0';
793 else if ((unsigned char) *ipAddrStr == '.')
805 if(*ipAddrStr == ':')
809 if (isdigit((unsigned char) *ipAddrStr))
812 *port += *ipAddrStr - '0';
823 if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
834 //-----------------------------------------------------------------------------
835 // Private internal function prototypes
836 //-----------------------------------------------------------------------------
838 static OCDoHandle GenerateInvocationHandle();
839 static OCStackResult initResources();
840 static void insertResource(OCResource *resource);
841 static OCResource *findResource(OCResource *resource);
842 static void insertResourceType(OCResource *resource,
843 OCResourceType *resourceType);
844 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
846 static void insertResourceInterface(OCResource *resource,
847 OCResourceInterface *resourceInterface);
848 static OCResourceInterface *findResourceInterfaceAtIndex(
849 OCResourceHandle handle, uint8_t index);
850 static void deleteResourceType(OCResourceType *resourceType);
851 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
852 static void deleteResourceElements(OCResource *resource);
853 static int deleteResource(OCResource *resource);
854 static void deleteAllResources();
855 static void incrementSequenceNumber(OCResource * resPtr);
856 static OCStackResult verifyUriQueryLength(const char * inputUri,
858 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
859 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI);
861 //-----------------------------------------------------------------------------
863 //-----------------------------------------------------------------------------
866 * Initialize the OC Stack. Must be called prior to starting the stack.
869 * IP Address of host device
871 * Port of host device
873 * Host device is client, server, or client-server
876 * OC_STACK_OK - no errors
877 * OC_STACK_ERROR - stack init error
879 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
881 OCStackResult result = OC_STACK_ERROR;
882 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
886 OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
890 //It is ok to select network to CA_WIFI for now
891 CAResult_t caResult = CASelectNetwork(CA_WIFI);
892 if(caResult == CA_STATUS_OK)
894 OC_LOG(INFO, TAG, PCF("CASelectNetwork to WIFI"));
895 caResult = CARegisterHandler(HandleCARequests, HandleCAResponses);
896 if(caResult == CA_STATUS_OK)
898 OC_LOG(INFO, TAG, PCF("CARegisterHandler..."));
899 stackState = OC_STACK_INITIALIZED;
900 result = OC_STACK_OK;
904 caResult = CAStartDiscoveryServer();
905 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
908 caResult = CAStartListeningServer();
909 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
911 case OC_CLIENT_SERVER:
912 caResult = CAStartListeningServer();
913 if(caResult == CA_STATUS_OK)
915 caResult = CAStartDiscoveryServer();
917 OC_LOG(INFO, TAG, PCF("Client-server mode"));
920 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
921 return OC_STACK_ERROR;
926 if (caResult == CA_STATUS_OK)
928 result = OC_STACK_OK;
932 result = OC_STACK_ERROR;
939 OC_LOG(INFO, TAG, PCF("Client mode"));
942 OC_LOG(INFO, TAG, PCF("Server mode"));
944 case OC_CLIENT_SERVER:
945 OC_LOG(INFO, TAG, PCF("Client-server mode"));
948 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
949 return OC_STACK_ERROR;
953 // Make call to OCCoAP layer
954 result = OCInitCoAP(ipAddr, (uint16_t) port, myStackMode);
958 defaultDeviceHandler = NULL;
961 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
962 #endif // WITH_PRESENCE
964 if (result == OC_STACK_OK)
966 stackState = OC_STACK_INITIALIZED;
968 // Initialize resource
969 if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
971 result = initResources();
973 if(result != OC_STACK_OK)
975 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
981 * Stop the OC stack. Use for a controlled shutdown.
983 * OC_STACK_OK - no errors
984 * OC_STACK_ERROR - stack not initialized
986 OCStackResult OCStop()
988 OCStackResult result = OC_STACK_ERROR;
990 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
992 if (stackState != OC_STACK_INITIALIZED)
994 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
995 return OC_STACK_ERROR;
999 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1000 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1001 presenceResource.presenceTTL = 0;
1002 #endif // WITH_PRESENCE
1004 // Free memory dynamically allocated for resources
1005 deleteAllResources();
1007 // Make call to OCCoAP layer
1008 if (OCStopCoAP() == OC_STACK_OK)
1010 // Remove all observers
1011 DeleteObserverList();
1012 // Remove all the client callbacks
1013 DeleteClientCBList();
1014 stackState = OC_STACK_UNINITIALIZED;
1015 result = OC_STACK_OK;
1017 result = OC_STACK_ERROR;
1020 // Deinit security blob
1021 DeinitOCSecurityInfo();
1023 if (result != OC_STACK_OK) {
1024 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
1031 * Verify the lengths of the URI and the query separately
1033 * @param inputUri - Input URI and query.
1034 * @param uriLen - The length of the initial URI with query.
1036 * Note: The '?' that appears after the URI is not considered as
1037 * a part of the query.
1039 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1043 query = strchr (inputUri, '?');
1047 if((query - inputUri) > MAX_URI_LENGTH)
1049 return OC_STACK_INVALID_URI;
1052 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1054 return OC_STACK_INVALID_QUERY;
1057 else if(uriLen > MAX_URI_LENGTH)
1059 return OC_STACK_INVALID_URI;
1065 * Discover or Perform requests on a specified resource (specified by that Resource's respective URI).
1067 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of calling this API.
1068 * @param method - @ref OCMethod to perform on the resource
1069 * @param requiredUri - URI of the resource to interact with
1070 * @param referenceUri - URI of the reference resource
1071 * @param request - JSON encoded request
1072 * @param qos - quality of service
1073 * @param cbData - struct that contains asynchronous callback function that is invoked
1074 * by the stack when discovery or resource interaction is complete
1075 * @param options - The address of an array containing the vendor specific header
1076 * header options to be sent with the request
1077 * @param numOptions - Number of vendor specific header options to be included
1080 * OC_STACK_OK - no errors
1081 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
1082 * OC_STACK_INVALID_METHOD - invalid resource method
1083 * OC_STACK_INVALID_URI - invalid required or reference URI
1086 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1087 const char *referenceUri, const char *request,
1088 OCQualityOfService qos, OCCallbackData *cbData,
1089 OCHeaderOption * options, uint8_t numOptions)
1091 OCStackResult result = OC_STACK_ERROR;
1093 ClientCB *clientCB = NULL;
1094 unsigned char * requestUri = NULL;
1095 unsigned char * resourceType = NULL;
1096 char * newUri = (char *)requiredUri;
1097 (void) referenceUri;
1099 CARemoteEndpoint_t* endpoint = NULL;
1100 CAResult_t caResult;
1101 CAToken_t caToken = NULL;
1102 CAInfo_t requestData;
1103 CARequestInfo_t requestInfo;
1104 // To track if memory is allocated for additional header options
1105 uint8_t hdrOptionMemAlloc = 0;
1108 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1110 // Validate input parameters
1111 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1112 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1114 TODO ("Need to form the final query by concatenating require and reference URI's");
1115 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
1117 uint16_t uriLen = strlen(requiredUri);
1119 // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS
1125 case OC_REST_DELETE:
1126 case OC_REST_OBSERVE:
1127 case OC_REST_OBSERVE_ALL:
1128 case OC_REST_CANCEL_OBSERVE:
1130 #ifdef WITH_PRESENCE
1131 case OC_REST_PRESENCE:
1135 result = OC_STACK_INVALID_METHOD;
1139 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
1144 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
1146 result = OC_STACK_INVALID_PARAM;
1150 #ifdef WITH_PRESENCE
1151 if(method == OC_REST_PRESENCE)
1153 result = getResourceType(requiredUri, &resourceType, &newUri);
1155 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1159 OC_LOG(DEBUG, TAG, PCF("Got Resource Type is NULL."));
1161 if(result != OC_STACK_OK)
1166 #endif // WITH_PRESENCE
1168 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
1171 memcpy(requestUri, newUri, (uriLen + 1));
1175 result = OC_STACK_NO_MEMORY;
1179 *handle = GenerateInvocationHandle();
1182 result = OC_STACK_NO_MEMORY;
1187 memset(&requestData, 0, sizeof(CAInfo_t));
1188 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1192 case OC_REST_OBSERVE:
1193 case OC_REST_OBSERVE_ALL:
1194 case OC_REST_CANCEL_OBSERVE:
1196 requestInfo.method = CA_GET;
1201 requestInfo.method = CA_PUT;
1206 requestInfo.method = CA_POST;
1209 case OC_REST_DELETE:
1211 requestInfo.method = CA_DELETE;
1214 #ifdef WITH_PRESENCE
1215 case OC_REST_PRESENCE:
1216 //TODO-CA: What should be the CA method?
1220 result = OC_STACK_INVALID_METHOD;
1224 // TODO-CA: Handle multi-cast scenario
1225 // Create remote end point
1226 caResult = CACreateRemoteEndpoint(newUri, CA_WIFI, &endpoint);
1227 // TODO-CA: Connectivity type should be passed to API
1228 endpoint->connectivityType = CA_WIFI;
1229 if (caResult != CA_STATUS_OK)
1231 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1236 caResult = CAGenerateToken(&caToken);
1238 if (caResult != CA_STATUS_OK)
1240 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1245 // TODO-CA: Map QoS to the right CA msg type
1246 requestData.type = CA_MSG_NONCONFIRM;
1247 requestData.token = caToken;
1248 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1250 result = CreateObserveHeaderOption (&(requestData.options), options,
1251 numOptions, OC_OBSERVE_REGISTER);
1252 if (result != OC_STACK_OK)
1256 hdrOptionMemAlloc = 1;
1257 requestData.numOptions = numOptions + 1;
1261 requestData.options = (CAHeaderOption_t*)options;
1262 requestData.numOptions = numOptions;
1264 requestData.payload = (char *)request;
1266 requestInfo.info = requestData;
1269 caResult = CASendRequest(endpoint, &requestInfo);
1270 if (caResult != CA_STATUS_OK)
1272 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1276 if((result = AddClientCB(&clientCB, cbData, &caToken, handle, method,
1277 requestUri, resourceType)) != OC_STACK_OK)
1279 result = OC_STACK_NO_MEMORY;
1285 // Generate token which will be used by OCStack to match responses received
1287 OCGenerateCoAPToken(&token);
1289 if((result = AddClientCB(&clientCB, cbData, &token, handle, method, requestUri, resourceType))
1292 result = OC_STACK_NO_MEMORY;
1296 #ifdef WITH_PRESENCE
1297 if(method == OC_REST_PRESENCE)
1299 // Replacing method type with GET because "presence" is a stack layer only implementation.
1300 method = OC_REST_GET;
1304 // Make call to OCCoAP layer
1305 result = OCDoCoAPResource(method, qos, &token, newUri, request, options, numOptions);
1309 if(newUri != requiredUri)
1313 if (result != OC_STACK_OK)
1315 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1316 FindAndDeleteClientCB(clientCB);
1319 CADestroyRemoteEndpoint(endpoint);
1320 if (hdrOptionMemAlloc)
1322 OCFree(requestData.options);
1324 //TODO-CA: CADestroyToken here
1330 * Cancel a request associated with a specific @ref OCDoResource invocation.
1332 * @param handle - Used to identify a specific OCDoResource invocation.
1333 * @param qos - used to specify Quality of Service (read below for more info)
1334 * @param options- used to specify vendor specific header options when sending
1335 * explicit observe cancellation
1336 * @param numOptions- Number of header options to be included
1339 * OC_STACK_OK - No errors; Success
1340 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1342 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1343 uint8_t numOptions) {
1345 * This ftn is implemented one of two ways in the case of observation:
1347 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1348 * Remove the callback associated on client side.
1349 * When the next notification comes in from server,
1350 * reply with RESET message to server.
1351 * Keep in mind that the server will react to RESET only
1352 * if the last notification was sent ans CON
1354 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1355 * and it is associated with an observe request
1356 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1357 * Send CON Observe request to server with
1358 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1359 * Remove the callback associated on client side.
1361 OCStackResult ret = OC_STACK_OK;
1364 return OC_STACK_INVALID_PARAM;
1367 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1369 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1372 switch (clientCB->method)
1374 case OC_REST_OBSERVE:
1375 case OC_REST_OBSERVE_ALL:
1376 if(qos == OC_HIGH_QOS)
1378 ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
1379 &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
1384 FindAndDeleteClientCB(clientCB);
1387 #ifdef WITH_PRESENCE
1388 case OC_REST_PRESENCE:
1389 FindAndDeleteClientCB(clientCB);
1393 return OC_STACK_INVALID_METHOD;
1398 #ifdef WITH_PRESENCE
1399 OCStackResult OCProcessPresence()
1401 OCStackResult result = OC_STACK_OK;
1402 uint8_t ipAddr[4] = { 0 };
1405 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1406 ClientCB* cbNode = NULL;
1408 OCClientResponse clientResponse;
1409 OCResponse * response = NULL;
1411 LL_FOREACH(cbList, cbNode) {
1412 if(OC_REST_PRESENCE == cbNode->method)
1414 if(cbNode->presence)
1416 uint32_t now = GetTime(0);
1417 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
1418 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1421 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1426 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1427 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1428 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1431 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1433 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1434 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1436 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1438 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
1439 (OCDevAddr *) &dst, 0, NULL);
1440 if(result != OC_STACK_OK)
1444 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1445 &cbNode->token, &clientResponse, NULL);
1446 if(result != OC_STACK_OK)
1451 // Increment the TTLLevel (going to a next state), so we don't keep
1452 // sending presence notification to client.
1453 cbNode->presence->TTLlevel++;
1454 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1455 cbNode->presence->TTLlevel);
1459 result = OC_STACK_INVALID_IP;
1462 HandleStackResponses(response);
1464 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1466 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
1468 OCGenerateCoAPToken(&token);
1469 result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
1470 &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
1471 if(result != OC_STACK_OK)
1475 cbNode->presence->TTLlevel++;
1476 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
1482 if (result != OC_STACK_OK)
1484 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
1491 * Called in main loop of OC client or server. Allows low-level processing of
1495 * OC_STACK_OK - no errors
1496 * OC_STACK_ERROR - stack process error
1498 OCStackResult OCProcess() {
1500 OC_LOG(INFO, TAG, PCF("Entering OCProcess"));
1501 #ifdef WITH_PRESENCE
1502 OCProcessPresence();
1505 CAHandleRequestResponse();
1513 #ifdef WITH_PRESENCE
1515 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
1516 * presence notifications to clients via multicast. Once this API has been called with a success,
1517 * clients may query for this server's presence and this server's stack will respond via multicast.
1519 * Server can call this function when it comes online for the first time, or when it comes back
1520 * online from offline mode, or when it re enters network.
1522 * @param ttl - Time To Live in seconds
1523 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
1526 * OC_STACK_OK - No errors; Success
1528 OCStackResult OCStartPresence(const uint32_t ttl)
1530 OCChangeResourceProperty(
1531 &(((OCResource *)presenceResource.handle)->resourceProperties),
1536 presenceResource.presenceTTL = ttl;
1539 if(OC_PRESENCE_UNINITIALIZED == presenceState)
1541 OCDevAddr multiCastAddr;
1544 presenceState = OC_PRESENCE_INITIALIZED;
1545 OCGenerateCoAPToken(&token);
1546 OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
1547 //add the presence observer
1548 AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
1549 (OCResource *)presenceResource.handle, OC_LOW_QOS);
1552 // Each time OCStartPresence is called
1553 // a different random 32-bit integer number is used
1554 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1556 return SendPresenceNotification(NULL);
1560 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
1561 * presence notifications to clients via multicast. Once this API has been called with a success,
1562 * this server's stack will not respond to clients querying for this server's presence.
1564 * Server can call this function when it is terminating, going offline, or when going
1565 * away from network.
1568 * OC_STACK_OK - No errors; Success
1570 OCStackResult OCStopPresence()
1572 OCStackResult result = OC_STACK_ERROR;
1573 //make resource inactive
1574 result = OCChangeResourceProperty(
1575 &(((OCResource *) presenceResource.handle)->resourceProperties),
1577 result = SendPresenceNotification(NULL);
1584 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
1586 defaultDeviceHandler = entityHandler;
1594 * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource
1595 * @param resourceTypeName - name of resource type. Example: "core.led"
1596 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1597 * @param uri - URI of the resource. Example: "/a/led"
1598 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1599 * NULL for default entity handler
1600 * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE
1603 * OC_STACK_OK - no errors
1604 * OC_STACK_ERROR - stack process error
1606 OCStackResult OCCreateResource(OCResourceHandle *handle,
1607 const char *resourceTypeName,
1608 const char *resourceInterfaceName,
1609 const char *uri, OCEntityHandler entityHandler,
1610 uint8_t resourceProperties) {
1612 OCResource *pointer = NULL;
1615 OCStackResult result = OC_STACK_ERROR;
1617 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
1619 if(myStackMode == OC_CLIENT)
1623 // Validate parameters
1624 // Is it presented during resource discovery?
1625 if (!handle || !resourceTypeName || !uri) {
1626 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
1627 return OC_STACK_INVALID_PARAM;
1630 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
1631 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
1634 // Make sure resourceProperties bitmask has allowed properties specified
1635 if (resourceProperties
1636 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
1637 OC_LOG(ERROR, TAG, PCF("Invalid property"));
1638 return OC_STACK_INVALID_PARAM;
1641 // If the headResource is NULL, then no resources have been created...
1642 pointer = headResource;
1644 // At least one resources is in the resource list, so we need to search for
1645 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
1647 if (strcmp(uri, pointer->uri) == 0) {
1648 OC_LOG(ERROR, TAG, PCF("URI already in use"));
1649 return OC_STACK_INVALID_PARAM;
1651 pointer = pointer->next;
1654 // Create the pointer and insert it into the resource list
1655 pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
1659 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
1661 insertResource(pointer);
1664 size = strlen(uri) + 1;
1665 str = (char *) OCMalloc(size);
1669 strncpy(str, uri, size);
1672 // Set properties. Set OC_ACTIVE
1673 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
1676 // Add the resourcetype to the resource
1677 result = BindResourceTypeToResource(pointer, resourceTypeName);
1678 if (result != OC_STACK_OK) {
1679 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
1683 // Add the resourceinterface to the resource
1684 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
1685 if (result != OC_STACK_OK) {
1686 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
1690 // If an entity handler has been passed, attach it to the newly created
1691 // resource. Otherwise, set the default entity handler.
1694 pointer->entityHandler = entityHandler;
1698 pointer->entityHandler = defaultResourceEHandler;
1702 result = OC_STACK_OK;
1704 #ifdef WITH_PRESENCE
1705 if(presenceResource.handle)
1707 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1708 SendPresenceNotification(pointer->rsrcType);
1712 if (result != OC_STACK_OK)
1714 // Deep delete of resource and other dynamic elements that it contains
1715 deleteResource(pointer);
1724 * Create a resource. with host ip address for remote resource
1726 * @param handle - pointer to handle to newly created resource. Set by ocstack.
1727 * Used to refer to resource
1728 * @param resourceTypeName - name of resource type. Example: "core.led"
1729 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1730 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
1731 * @param uri - URI of the resource. Example: "/a/led"
1732 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1733 * NULL for default entity handler
1734 * @param resourceProperties - properties supported by resource.
1735 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
1738 * OC_STACK_OK - no errors
1739 * OC_STACK_ERROR - stack process error
1742 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
1743 const char *resourceTypeName,
1744 const char *resourceInterfaceName,
1747 OCEntityHandler entityHandler,
1748 uint8_t resourceProperties)
1752 OCStackResult result = OC_STACK_ERROR;
1754 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
1755 uri, entityHandler, resourceProperties);
1757 if (result != OC_STACK_ERROR)
1760 size = strlen(host) + 1;
1761 str = (char *) OCMalloc(size);
1764 return OC_STACK_ERROR;
1766 strncpy(str, host, size);
1767 ((OCResource *) *handle)->host = str;
1774 * Add a resource to a collection resource.
1776 * @param collectionHandle - handle to the collection resource
1777 * @param resourceHandle - handle to resource to be added to the collection resource
1780 * OC_STACK_OK - no errors
1781 * OC_STACK_ERROR - stack process error
1782 * OC_STACK_INVALID_PARAM - invalid collectionhandle
1784 OCStackResult OCBindResource(
1785 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1786 OCResource *resource;
1789 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
1791 // Validate parameters
1792 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1793 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1794 // Container cannot contain itself
1795 if (collectionHandle == resourceHandle) {
1796 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
1797 return OC_STACK_INVALID_PARAM;
1800 // Use the handle to find the resource in the resource linked list
1801 resource = findResource((OCResource *) collectionHandle);
1803 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1804 return OC_STACK_INVALID_PARAM;
1807 // Look for an open slot to add add the child resource.
1808 // If found, add it and return success
1809 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1810 if (!resource->rsrcResources[i]) {
1811 resource->rsrcResources[i] = (OCResource *) resourceHandle;
1812 OC_LOG(INFO, TAG, PCF("resource bound"));
1817 #ifdef WITH_PRESENCE
1818 if(presenceResource.handle)
1820 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1821 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1825 // Unable to add resourceHandle, so return error
1826 return OC_STACK_ERROR;
1830 * Remove a resource from a collection resource.
1832 * @param collectionHandle - handle to the collection resource
1833 * @param resourceHandle - handle to resource to be added to the collection resource
1836 * OC_STACK_OK - no errors
1837 * OC_STACK_ERROR - stack process error
1838 * OC_STACK_INVALID_PARAM - invalid collectionHandle
1840 OCStackResult OCUnBindResource(
1841 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1842 OCResource *resource;
1845 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
1847 // Validate parameters
1848 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1849 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1850 // Container cannot contain itself
1851 if (collectionHandle == resourceHandle) {
1852 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
1853 return OC_STACK_INVALID_PARAM;
1856 // Use the handle to find the resource in the resource linked list
1857 resource = findResource((OCResource *) collectionHandle);
1859 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1860 return OC_STACK_INVALID_PARAM;
1863 // Look for an open slot to add add the child resource.
1864 // If found, add it and return success
1865 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1866 if (resourceHandle == resource->rsrcResources[i]) {
1867 resource->rsrcResources[i] = (OCResource *) NULL;
1868 OC_LOG(INFO, TAG, PCF("resource unbound"));
1873 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
1875 #ifdef WITH_PRESENCE
1876 if(presenceResource.handle)
1878 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1879 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1883 // Unable to add resourceHandle, so return error
1884 return OC_STACK_ERROR;
1887 OCStackResult BindResourceTypeToResource(OCResource* resource,
1888 const char *resourceTypeName)
1890 OCResourceType *pointer = NULL;
1893 OCStackResult result = OC_STACK_ERROR;
1895 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
1897 // Validate parameters
1898 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
1899 // TODO: Does resource attribute resentation really have to be maintained in stack?
1900 // Is it presented during resource discovery?
1902 TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
1904 // Create the resourcetype and insert it into the resource list
1905 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
1910 // Set the resourceTypeName
1911 size = strlen(resourceTypeName) + 1;
1912 str = (char *) OCMalloc(size);
1916 strncpy(str, resourceTypeName, size);
1917 pointer->resourcetypename = str;
1919 insertResourceType(resource, pointer);
1920 result = OC_STACK_OK;
1922 exit: if (result != OC_STACK_OK) {
1930 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
1931 const char *resourceInterfaceName)
1933 OCResourceInterface *pointer = NULL;
1936 OCStackResult result = OC_STACK_ERROR;
1938 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
1940 // Validate parameters
1941 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
1943 TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
1945 // Create the resourceinterface and insert it into the resource list
1946 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
1951 // Set the resourceinterface name
1952 size = strlen(resourceInterfaceName) + 1;
1953 str = (char *) OCMalloc(size);
1957 strncpy(str, resourceInterfaceName, size);
1958 pointer->name = str;
1960 // Bind the resourceinterface to the resource
1961 insertResourceInterface(resource, pointer);
1963 result = OC_STACK_OK;
1965 exit: if (result != OC_STACK_OK) {
1974 * Bind a resourcetype to a resource.
1976 * @param handle - handle to the resource
1977 * @param resourceTypeName - name of resource type. Example: "core.led"
1980 * OC_STACK_OK - no errors
1981 * OC_STACK_ERROR - stack process error
1983 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
1984 const char *resourceTypeName) {
1986 OCStackResult result = OC_STACK_ERROR;
1987 OCResource *resource;
1989 // Make sure resource exists
1990 resource = findResource((OCResource *) handle);
1992 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1993 return OC_STACK_ERROR;
1996 // call internal function
1997 result = BindResourceTypeToResource(resource, resourceTypeName);
1999 #ifdef WITH_PRESENCE
2000 if(presenceResource.handle)
2002 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2003 SendPresenceNotification(resource->rsrcType);
2011 * Bind a resourceinterface to a resource.
2013 * @param handle - handle to the resource
2014 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
2017 * OC_STACK_OK - no errors
2018 * OC_STACK_ERROR - stack process error
2021 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2022 const char *resourceInterfaceName) {
2024 OCStackResult result = OC_STACK_ERROR;
2025 OCResource *resource;
2027 // Make sure resource exists
2028 resource = findResource((OCResource *) handle);
2030 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2031 return OC_STACK_ERROR;
2034 // call internal function
2035 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2037 #ifdef WITH_PRESENCE
2038 if(presenceResource.handle)
2040 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2041 SendPresenceNotification(resource->rsrcType);
2049 * Get the number of resources that have been created in the stack.
2051 * @param numResources - pointer to count variable
2054 * OC_STACK_OK - no errors
2055 * OC_STACK_ERROR - stack process error
2058 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
2059 OCResource *pointer = headResource;
2061 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2062 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2065 *numResources = *numResources + 1;
2066 pointer = pointer->next;
2072 * Get a resource handle by index.
2074 * @param index - index of resource, 0 to Count - 1
2077 * Resource handle - if found
2078 * NULL - if not found
2080 OCResourceHandle OCGetResourceHandle(uint8_t index) {
2081 OCResource *pointer = headResource;
2084 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2086 // Iterate through the list
2087 while ((i < index) && pointer) {
2089 pointer = pointer->next;
2091 return (OCResourceHandle) pointer;
2095 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
2098 * @param handle - handle of resource to be deleted
2101 * OC_STACK_OK - no errors
2102 * OC_STACK_ERROR - stack process error
2103 * OC_STACK_NO_RESOURCE - resource not found
2104 * OC_STACK_INVALID_PARAM - invalid param
2106 OCStackResult OCDeleteResource(OCResourceHandle handle) {
2107 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2110 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2111 return OC_STACK_INVALID_PARAM;
2114 OCResource *resource = findResource((OCResource *) handle);
2115 if (resource == NULL) {
2116 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2117 return OC_STACK_NO_RESOURCE;
2120 if (deleteResource((OCResource *) handle) == 0) {
2121 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2122 return OC_STACK_ERROR;
2129 * Get the URI of the resource specified by handle.
2131 * @param handle - handle of resource
2133 * URI string - if resource found
2134 * NULL - resource not found
2136 const char *OCGetResourceUri(OCResourceHandle handle) {
2137 OCResource *resource;
2138 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2140 resource = findResource((OCResource *) handle);
2142 return resource->uri;
2144 return (const char *) NULL;
2148 * Get the properties of the resource specified by handle.
2149 * NOTE: that after a resource is created, the OC_ACTIVE property is set
2150 * for the resource by the stack.
2152 * @param handle - handle of resource
2154 * property bitmap - if resource found
2155 * NULL - resource not found
2157 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
2158 OCResource *resource;
2159 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2161 resource = findResource((OCResource *) handle);
2163 return resource->resourceProperties;
2169 * Get the number of resource types of the resource.
2171 * @param handle - handle of resource
2172 * @param numResourceTypes - pointer to count variable
2175 * OC_STACK_OK - no errors
2176 * OC_STACK_ERROR - stack process error
2178 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2179 uint8_t *numResourceTypes) {
2180 OCResource *resource;
2181 OCResourceType *pointer;
2183 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2184 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2185 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2187 *numResourceTypes = 0;
2189 resource = findResource((OCResource *) handle);
2191 pointer = resource->rsrcType;
2193 *numResourceTypes = *numResourceTypes + 1;
2194 pointer = pointer->next;
2201 * Get name of resource type of the resource.
2203 * @param handle - handle of resource
2204 * @param index - index of resource, 0 to Count - 1
2207 * resource type name - if resource found
2208 * NULL - resource not found
2210 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
2211 OCResourceType *resourceType;
2213 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2215 resourceType = findResourceTypeAtIndex(handle, index);
2217 return resourceType->resourcetypename;
2219 return (const char *) NULL;
2225 * Get the number of resource interfaces of the resource.
2227 * @param handle - handle of resource
2228 * @param numResources - pointer to count variable
2231 * OC_STACK_OK - no errors
2232 * OC_STACK_ERROR - stack process error
2234 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2235 uint8_t *numResourceInterfaces) {
2236 OCResourceInterface *pointer;
2237 OCResource *resource;
2239 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2241 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2242 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2244 *numResourceInterfaces = 0;
2245 resource = findResource((OCResource *) handle);
2247 pointer = resource->rsrcInterface;
2249 *numResourceInterfaces = *numResourceInterfaces + 1;
2250 pointer = pointer->next;
2257 * Get name of resource interface of the resource.
2259 * @param handle - handle of resource
2260 * @param index - index of resource, 0 to Count - 1
2263 * resource interface name - if resource found
2264 * NULL - resource not found
2266 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
2267 OCResourceInterface *resourceInterface;
2269 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2271 resourceInterface = findResourceInterfaceAtIndex(handle, index);
2272 if (resourceInterface) {
2273 return resourceInterface->name;
2275 return (const char *) NULL;
2279 * Get resource handle from the collection resource by index.
2281 * @param collectionHandle - handle of collection resource
2282 * @param index - index of contained resource, 0 to Count - 1
2285 * handle to resource - if resource found
2286 * NULL - resource not found
2288 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2290 OCResource *resource;
2292 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2294 if (index >= MAX_CONTAINED_RESOURCES) {
2298 resource = findResource((OCResource *) collectionHandle);
2303 return resource->rsrcResources[index];
2307 * Bind an entity handler to the resource.
2309 * @param handle - handle to the resource that the contained resource is to be bound
2310 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2312 * OC_STACK_OK - no errors
2313 * OC_STACK_ERROR - stack process error
2315 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2316 OCEntityHandler entityHandler) {
2317 OCResource *resource;
2319 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2321 // Validate parameters
2322 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2323 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2325 // Use the handle to find the resource in the resource linked list
2326 resource = findResource((OCResource *)handle);
2328 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2329 return OC_STACK_ERROR;
2333 resource->entityHandler = entityHandler;
2335 #ifdef WITH_PRESENCE
2336 if(presenceResource.handle)
2338 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2339 SendPresenceNotification(resource->rsrcType);
2347 * Get the entity handler for a resource.
2349 * @param handle - handle of resource
2352 * entity handler - if resource found
2353 * NULL - resource not found
2355 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
2356 OCResource *resource;
2358 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2360 // Use the handle to find the resource in the resource linked list
2361 resource = findResource((OCResource *)handle);
2363 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2368 return resource->entityHandler;
2371 void incrementSequenceNumber(OCResource * resPtr)
2373 // Increment the sequence number
2374 resPtr->sequenceNum += 1;
2375 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2377 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2383 * Notify Presence subscribers that a resource has been modified
2385 * @param resourceType - Handle to the resourceType linked list of resource
2386 * that was modified.
2387 * @param qos - Quality Of Service
2390 #ifdef WITH_PRESENCE
2391 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
2393 OCResource *resPtr = NULL;
2394 OCStackResult result;
2395 OCMethod method = OC_REST_PRESENCE;
2396 uint32_t maxAge = 0;
2397 resPtr = findResource((OCResource *) presenceResource.handle);
2400 return OC_STACK_NO_RESOURCE;
2402 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
2404 maxAge = presenceResource.presenceTTL;
2411 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
2414 #endif // WITH_PRESENCE
2416 * Notify observers that an observed value has changed.
2418 * @param handle - handle of resource
2421 * OC_STACK_OK - no errors
2422 * OC_STACK_NO_RESOURCE - invalid resource handle
2423 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
2425 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
2427 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2429 OCResource *resPtr = NULL;
2430 OCStackResult result;
2431 OCMethod method = OC_REST_NOMETHOD;
2432 uint32_t maxAge = 0;
2434 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2435 #ifdef WITH_PRESENCE
2436 if(handle == presenceResource.handle)
2440 #endif // WITH_PRESENCE
2441 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2443 // Verify that the resource exists
2444 resPtr = findResource ((OCResource *) handle);
2447 return OC_STACK_NO_RESOURCE;
2451 //only increment in the case of regular observing (not presence)
2452 incrementSequenceNumber(resPtr);
2453 method = OC_REST_OBSERVE;
2454 maxAge = MAX_OBSERVE_AGE;
2455 #ifdef WITH_PRESENCE
2456 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
2458 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
2465 OCNotifyListOfObservers (OCResourceHandle handle,
2466 OCObservationId *obsIdList,
2467 uint8_t numberOfIds,
2468 unsigned char *notificationJSONPayload,
2469 OCQualityOfService qos)
2471 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
2473 OCResource *resPtr = NULL;
2474 //TODO: we should allow the server to define this
2475 uint32_t maxAge = MAX_OBSERVE_AGE;
2477 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2478 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
2479 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
2481 // Verify that the resource exists
2482 resPtr = findResource ((OCResource *) handle);
2483 if (NULL == resPtr || myStackMode == OC_CLIENT)
2485 return OC_STACK_NO_RESOURCE;
2489 incrementSequenceNumber(resPtr);
2491 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
2492 notificationJSONPayload, maxAge, qos));
2496 * Send a response to a request.
2497 * The response can be a regular, slow, or block (i.e. a response that
2498 * is too large to be sent in a single PDU and must span multiple transmissions)
2500 * @param response - pointer to structure that contains response parameters
2503 * OC_STACK_OK - No errors; Success
2504 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
2505 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
2506 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
2507 * persistent response buffer is necessary
2509 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
2511 OCStackResult result = OC_STACK_ERROR;
2512 OCServerRequest *serverRequest = NULL;
2514 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
2516 // Validate input parameters
2517 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
2518 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
2520 // TODO: Placeholder for creating a response entry when implementing
2521 // block transfer feature
2523 // If a response payload is present, check if block transfer is required
2524 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
2525 (const char *)ehResponse->payload, ehResponse->payloadSize))
2527 OC_LOG(INFO, TAG, PCF("Block transfer required"));
2529 // Persistent response buffer is needed for block transfer
2530 if (!ehResponse->persistentBufferFlag)
2532 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
2533 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
2535 // TODO: Placeholder for block transfer handling
2536 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
2537 // when implementing the block transfer feature
2543 // Get pointer to request info
2544 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
2547 result = serverRequest->ehResponseHandler(ehResponse);
2554 * Cancel a response. Applies to a block response
2556 * @param responseHandle - response handle set by stack in OCServerResponse after
2557 * OCDoResponse is called
2560 * OC_STACK_OK - No errors; Success
2561 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
2563 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
2565 OCStackResult result = OC_STACK_NOTIMPL;
2567 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
2569 // TODO: validate response handle
2574 //-----------------------------------------------------------------------------
2575 // Private internal function definitions
2576 //-----------------------------------------------------------------------------
2578 * Generate handle of OCDoResource invocation for callback management.
2580 static OCDoHandle GenerateInvocationHandle()
2582 OCDoHandle handle = NULL;
2583 // Generate token here, it will be deleted when the transaction is deleted
2584 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2587 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2592 #ifdef WITH_PRESENCE
2593 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
2594 OCResourceProperty resourceProperties, uint8_t enable)
2596 if (resourceProperties
2597 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
2598 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2599 return OC_STACK_INVALID_PARAM;
2603 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
2607 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
2614 * Initialize resource data structures, variables, etc.
2616 OCStackResult initResources() {
2617 OCStackResult result = OC_STACK_OK;
2618 // Init application resource vars
2619 headResource = NULL;
2620 // Init Virtual Resources
2621 #ifdef WITH_PRESENCE
2622 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
2623 //presenceResource.token = OCGenerateCoAPToken();
2624 result = OCCreateResource(&presenceResource.handle,
2625 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
2630 //make resource inactive
2631 result = OCChangeResourceProperty(
2632 &(((OCResource *) presenceResource.handle)->resourceProperties),
2639 * Add a resource to the end of the linked list of resources.
2641 * @param resource - resource to be added
2643 void insertResource(OCResource *resource) {
2644 OCResource *pointer;
2646 if (!headResource) {
2647 headResource = resource;
2649 pointer = headResource;
2651 while (pointer->next) {
2652 pointer = pointer->next;
2654 pointer->next = resource;
2656 resource->next = NULL;
2660 * Find a resource in the linked list of resources.
2662 * @param resource - resource to be found
2664 * NULL - resource not found
2665 * pointer to resource - pointer to resource that was found in the linked list
2667 OCResource *findResource(OCResource *resource) {
2668 OCResource *pointer = headResource;
2671 if (pointer == resource) {
2674 pointer = pointer->next;
2679 void deleteAllResources()
2681 OCResource *pointer = headResource;
2686 temp = pointer->next;
2687 #ifdef WITH_PRESENCE
2688 if(pointer != (OCResource *) presenceResource.handle)
2690 #endif // WITH_PRESENCE
2691 deleteResource(pointer);
2692 #ifdef WITH_PRESENCE
2694 #endif // WITH_PRESENCE
2698 #ifdef WITH_PRESENCE
2699 // Ensure that the last resource to be deleted is the presence resource. This allows for all
2700 // presence notification attributed to their deletion to be processed.
2701 deleteResource((OCResource *) presenceResource.handle);
2702 #endif // WITH_PRESENCE
2706 * Delete the resource from the linked list.
2708 * @param resource - resource to be deleted
2713 int deleteResource(OCResource *resource) {
2714 OCResource *prev = NULL;
2717 temp = headResource;
2719 if (temp == resource) {
2720 // Invalidate all Resource Properties.
2721 resource->resourceProperties = (OCResourceProperty) 0;
2722 #ifdef WITH_PRESENCE
2723 if(resource != (OCResource *) presenceResource.handle)
2725 #endif // WITH_PRESENCE
2726 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
2727 #ifdef WITH_PRESENCE
2730 if(presenceResource.handle)
2732 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2733 if(resource != (OCResource *) presenceResource.handle)
2735 SendPresenceNotification(resource->rsrcType);
2739 SendPresenceNotification(NULL);
2744 if (temp == headResource) {
2745 headResource = temp->next;
2747 prev->next = temp->next;
2750 deleteResourceElements(temp);
2763 * Delete all of the dynamically allocated elements that were created for the resource.
2765 * @param resource - specified resource
2767 void deleteResourceElements(OCResource *resource) {
2773 OCFree(resource->uri);
2775 // Delete resourcetype linked list
2776 deleteResourceType(resource->rsrcType);
2778 // Delete resourceinterface linked list
2779 deleteResourceInterface(resource->rsrcInterface);
2783 * Delete all of the dynamically allocated elements that were created for the resource type.
2785 * @param resourceType - specified resource type
2787 void deleteResourceType(OCResourceType *resourceType) {
2788 OCResourceType *pointer = resourceType;
2789 OCResourceType *next;
2792 next = pointer->next;
2793 OCFree(pointer->resourcetypename);
2800 * Delete all of the dynamically allocated elements that were created for the resource interface.
2802 * @param resourceInterface - specified resource interface
2804 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
2805 OCResourceInterface *pointer = resourceInterface;
2806 OCResourceInterface *next;
2809 next = pointer->next;
2810 OCFree(pointer->name);
2817 * Insert a resource type into a resource's resource type linked list.
2819 * @param resource - resource where resource type is to be inserted
2820 * @param resourceType - resource type to be inserted
2822 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
2823 OCResourceType *pointer;
2825 if (resource && !resource->rsrcType) {
2826 resource->rsrcType = resourceType;
2830 pointer = resource->rsrcType;
2834 pointer = resourceType;
2836 while (pointer->next) {
2837 pointer = pointer->next;
2839 pointer->next = resourceType;
2841 resourceType->next = NULL;
2845 * Get a resource type at the specified index within a resource.
2847 * @param handle - handle of resource
2848 * @param index - index of resource type
2851 * resourcetype - if found
2854 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
2855 OCResource *resource;
2856 OCResourceType *pointer;
2859 // Find the specified resource
2860 resource = findResource((OCResource *) handle);
2865 // Make sure a resource has a resourcetype
2866 if (!resource->rsrcType) {
2870 // Iterate through the list
2871 pointer = resource->rsrcType;
2873 while ((i < index) && pointer) {
2875 pointer = pointer->next;
2881 * Finds a resource type in an OCResourceType link-list.
2883 * @param resourceTypeList - the link-list to be searched through
2884 * @param resourceTypeName - the key to search for
2887 * resourceType that matches the key (ie. resourceTypeName)
2888 * NULL - either an invalid parameter or this function was unable to find the key.
2890 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
2892 if(resourceTypeList && resourceTypeName)
2894 OCResourceType * rtPointer = resourceTypeList;
2895 while(resourceTypeName && rtPointer)
2897 if(rtPointer->resourcetypename &&
2898 strcmp(resourceTypeName, (const char *)
2899 (rtPointer->resourcetypename)) == 0)
2903 rtPointer = rtPointer->next;
2910 * Insert a resource interface into a resource's resource interface linked list.
2912 * @param resource - resource where resource interface is to be inserted
2913 * @param resourceInterface - resource interface to be inserted
2915 void insertResourceInterface(OCResource *resource,
2916 OCResourceInterface *resourceInterface) {
2917 OCResourceInterface *pointer;
2919 if (!resource->rsrcInterface) {
2920 resource->rsrcInterface = resourceInterface;
2922 pointer = resource->rsrcInterface;
2923 while (pointer->next) {
2924 pointer = pointer->next;
2926 pointer->next = resourceInterface;
2928 resourceInterface->next = NULL;
2932 * Get a resource interface at the specified index within a resource.
2934 * @param handle - handle of resource
2935 * @param index - index of resource interface
2938 * resourceinterface - if found
2941 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
2943 OCResource *resource;
2944 OCResourceInterface *pointer;
2947 // Find the specified resource
2948 resource = findResource((OCResource *) handle);
2953 // Make sure a resource has a resourceinterface
2954 if (!resource->rsrcInterface) {
2958 // Iterate through the list
2959 pointer = resource->rsrcInterface;
2961 while ((i < index) && pointer) {
2963 pointer = pointer->next;
2969 * Determine if a request/response must be sent in a block transfer because it is too large to be
2970 * sent in a single PDU. This function can be used for either a request or a response
2972 * @param request - NULL or pointer to request
2973 * @param response - NULL or pointer to response
2974 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
2975 * the length of the request/response
2978 * 0 - packet transfer NOT required (i.e. normal request/response)
2979 * 1 - packet transfer required (i.e. block transfer needed)
2981 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
2985 // Determine if we are checking a request or a response
2988 // If size is greater than 0, use it for the request size value, otherwise
2989 // assume request is null terminated and use strlen for size value
2990 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
2997 // If size is greater than 0, use it for the response size value, otherwise
2998 // assume response is null terminated and use strlen for size value
2999 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3008 * Retrieves a resource type based upon a uri string if the uri string contains only just one
3009 * resource attribute (and that has to be of type "rt").
3011 * @remark This API malloc's memory for the resource type and newURI. Do not malloc resourceType
3012 * or newURI before passing in.
3014 * @param uri - Valid URI for "requiredUri" parameter to OCDoResource API.
3015 * @param resourceType - The resource type to be populated; pass by reference.
3016 * @param newURI - Return URI without resourceType appended to the end of it. This is used to
3017 * ensure that the uri parameter is not modified; pass by reference.
3020 * OC_STACK_INVALID_URI - Returns this if the URI is invalid/NULL.
3021 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
3022 * OC_STACK_OK - Success
3024 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI)
3028 return OC_STACK_INVALID_URI;
3030 if(!resourceType || !newURI)
3032 return OC_STACK_INVALID_PARAM;
3034 char * leftToken = NULL;
3035 char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3040 strcpy(tempURI, uri);
3041 leftToken = strtok((char *)tempURI, "?");
3043 while(leftToken != NULL)
3045 if(strncmp(leftToken, "rt=", 3) == 0)
3047 *resourceType = (unsigned char *) OCMalloc(strlen(leftToken)-3);
3052 strcpy((char *)*resourceType, ((const char *)&leftToken[3]));
3055 leftToken = strtok(NULL, "?");
3063 return OC_STACK_NO_MEMORY;
3066 const ServerID OCGetServerInstanceID(void)
3068 static bool generated = false;
3069 static ServerID sid;
3076 sid = OCGetRandom();
3081 const char* OCGetServerInstanceIDString(void)
3083 // max printed length of a base 10
3084 // uint32 is 10 characters, so 11 includes null.
3085 // This will change as the representation gets switched
3087 static char buffer[11];
3088 int n = sprintf(buffer, "%u", OCGetServerInstanceID());