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)
83 //-----------------------------------------------------------------------------
85 //-----------------------------------------------------------------------------
86 extern void DeinitOCSecurityInfo();
88 //-----------------------------------------------------------------------------
89 // Internal API function
90 //-----------------------------------------------------------------------------
92 // This internal function is called to update the stack with the status of
93 // observers and communication failures
94 OCStackResult OCStackFeedBack(OCCoAPToken * token, uint8_t status)
96 OCStackResult result = OC_STACK_ERROR;
97 ResourceObserver * observer = NULL;
98 OCEntityHandlerRequest ehRequest = {0};
102 case OC_OBSERVER_NOT_INTERESTED:
103 OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
104 observer = GetObserverUsingToken (token);
107 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
108 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
109 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
110 if(result != OC_STACK_OK)
114 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
116 //observer is not observing anymore
117 result = DeleteObserverUsingToken (token);
118 if(result == OC_STACK_OK)
120 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
124 result = OC_STACK_OK;
125 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
128 case OC_OBSERVER_STILL_INTERESTED:
129 //observer is still interested
130 OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
131 notifications, reset the failedCount"));
132 observer = GetObserverUsingToken(token);
135 observer->forceHighQos = 0;
136 observer->failedCommCount = 0;
137 result = OC_STACK_OK;
141 result = OC_STACK_OBSERVER_NOT_FOUND;
144 case OC_OBSERVER_FAILED_COMM:
145 //observer is not reachable
146 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
147 observer = GetObserverUsingToken(token);
150 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
152 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
153 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
154 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
155 if(result != OC_STACK_OK)
157 return OC_STACK_ERROR;
159 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
160 //observer is unreachable
161 result = DeleteObserverUsingToken (token);
162 if(result == OC_STACK_OK)
164 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
168 result = OC_STACK_OK;
169 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
174 observer->failedCommCount++;
175 result = OC_STACK_CONTINUE;
177 observer->forceHighQos = 1;
178 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
182 OC_LOG(ERROR, TAG, PCF("Unknown status"));
183 result = OC_STACK_ERROR;
190 OCStackResult CAResultToOCStackResult(CAResult_t caResult)
192 OCStackResult ret = OC_STACK_ERROR;
199 //TODO-CA Add other CA Results
206 //This function will be called back by CA layer when a response is received
207 void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
209 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
210 OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload);
211 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
214 //This function will be called back by CA layer when a request is received
215 void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
217 CAInfo_t responseData;
218 CAResponseInfo_t responseInfo;
220 // generate the pdu, if the request was CON, then the response is ACK, otherwire NON
221 memset(&responseData, 0, sizeof(CAInfo_t));
222 responseData.token = (requestInfo != NULL) ? requestInfo->info.token : "";
224 // TODO : I guess we need to allocate memeory?
225 responseData.payload = "Test data";
227 //responseInfo = (CAResponseInfo*) malloc(sizeof(CAResponseInfo));
228 memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
229 responseInfo.result = 200;
230 responseInfo.info = responseData;
232 // send request (connectivityType from remoteEndpoint of request Info)
233 OC_LOG(INFO, TAG, PCF("CASendResponse in HandleCARequests"));
234 //TODO-CA: CASendResponse returns the result (we need to check if the
236 CAResult_t caResult = CASendResponse(endPoint, &responseInfo);
237 if(caResult != CA_STATUS_OK)
239 OC_LOG(ERROR, TAG, PCF("CASendResponse error"));
242 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
243 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
248 //This function will be called back by occoap layer when a request is received
249 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
251 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
253 OCStackResult result = OC_STACK_ERROR;
254 ResourceHandling resHandling;
255 OCResource *resource;
257 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
260 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
261 result = AddServerRequest(&request, protocolRequest->coapID,
262 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
263 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
264 protocolRequest->observationOption, protocolRequest->qos,
265 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
266 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
267 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
268 protocolRequest->reqTotalSize);
269 if (OC_STACK_OK != result)
271 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
274 VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
276 if(!protocolRequest->reqMorePacket)
278 request->requestComplete = 1;
283 OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
286 if(request->requestComplete)
288 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
289 result = DetermineResourceHandling (request, &resHandling, &resource);
290 if (result == OC_STACK_OK)
292 result = ProcessRequest(resHandling, resource, request);
296 result = OC_STACK_ERROR;
301 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
302 result = OC_STACK_CONTINUE;
307 //This function will be called back by occoap layer when a response is received
308 OCStackResult HandleStackResponses(OCResponse * response)
310 OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)"));
311 OCStackResult result = OC_STACK_OK;
312 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
313 uint8_t isObserveNotification = 0;
314 ClientCB * cbNode = NULL;
316 uint8_t isPresenceNotification = 0;
317 uint8_t isMulticastPresence = 0;
318 char * resourceTypeName = NULL;
319 uint32_t lowerBound = 0;
320 uint32_t higherBound = 0;
322 unsigned char * bufRes = response->bufRes;
323 #endif // WITH_PRESENCE
325 cbNode = response->cbNode;
328 cbNode = GetClientCB(response->rcvdToken, NULL, NULL);
331 if(response->clientResponse->sequenceNumber >= OC_OFFSET_SEQUENCE_NUMBER)
333 isObserveNotification = 1;
334 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
337 OC_LOG_V(DEBUG, TAG, "The sequenceNumber/NONCE of this response %u",
338 response->clientResponse->sequenceNumber);
339 OC_LOG_V(DEBUG, TAG, "The maxAge/TTL of this response %u", response->maxAge);
340 OC_LOG_V(DEBUG, TAG, "The response received is %s", bufRes);
343 if(!strcmp((char *)response->rcvdUri, (char *)OC_PRESENCE_URI)){
344 isPresenceNotification = 1;
347 result = OC_STACK_INVALID_PARAM;
350 tok = strtok((char *)bufRes, "[:]}");
351 bufRes[strlen((char *)bufRes)] = ':';
352 tok = strtok(NULL, "[:]}");
353 bufRes[strlen((char *)bufRes)] = ':';
354 response->clientResponse->sequenceNumber = (uint32_t )atoi(tok);
355 OC_LOG_V(DEBUG, TAG, "The received NONCE is %u", response->clientResponse->sequenceNumber);
356 tok = strtok(NULL, "[:]}");
357 response->maxAge = (uint32_t )atoi(tok);
358 OC_LOG_V(DEBUG, TAG, "The received TTL is %u", response->maxAge);
359 tok = strtok(NULL, "[:]}");
362 resourceTypeName = (char *)OCMalloc(strlen(tok));
363 if(!resourceTypeName)
367 bufRes[strlen((char *)bufRes)] = ':';
368 strcpy(resourceTypeName, tok);
369 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
372 bufRes[strlen((char *)bufRes)] = ']';
375 // Check if the application subcribed for presence
378 cbNode = GetClientCB(NULL, NULL, response->fullUri);
381 // Check if application subscribed for multicast presence
384 snprintf((char *)response->fullUri, MAX_URI_LENGTH, "%s%s",
385 OC_MULTICAST_IP, response->rcvdUri);
386 cbNode = GetClientCB(NULL, NULL, response->fullUri);
389 isMulticastPresence = 1;
390 isPresenceNotification = 0;
394 if(cbNode && isPresenceNotification)
396 OC_LOG(INFO, TAG, PCF("Received a presence notification"));
397 if(!cbNode->presence)
399 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
400 VERIFY_NON_NULL_V(cbNode->presence);
401 cbNode->presence->timeOut = NULL;
402 cbNode->presence->timeOut = (uint32_t *)
403 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
404 if(!(cbNode->presence->timeOut)){
405 OCFree(cbNode->presence);
406 result = OC_STACK_NO_MEMORY;
409 if(response->maxAge == 0)
411 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
412 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
415 OCFree(cbNode->presence->timeOut);
416 OCFree(cbNode->presence);
417 cbNode->presence = NULL;
422 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %d", GetTime(0));
423 cbNode->presence->TTL = response->maxAge;
424 for(int index = 0; index < PresenceTimeOutSize; index++)
426 lowerBound = GetTime(((float)(PresenceTimeOut[index])
427 /(float)100)*(float)cbNode->presence->TTL);
428 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
429 /(float)100)*(float)cbNode->presence->TTL);
430 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
431 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
432 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
433 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
434 cbNode->presence->timeOut[index]);
436 cbNode->presence->TTLlevel = 0;
437 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
438 if(cbNode->sequenceNumber == response->clientResponse->sequenceNumber)
440 OC_LOG(INFO, TAG, PCF("===============No presence change"));
443 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
444 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;;
447 // Ensure that a filter is actually applied.
448 if(resourceTypeName && cbNode->filterResourceType)
450 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
456 else if(cbNode && isMulticastPresence)
458 // Check if the same nonce for a given host
459 OCMulticastNode* mcNode = NULL;
460 mcNode = GetMCPresenceNode(response->fullUri);
462 if(response->maxAge == 0)
464 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
465 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
468 OCFree(cbNode->presence->timeOut);
469 OCFree(cbNode->presence);
470 cbNode->presence = NULL;
473 else if(mcNode != NULL)
475 if(mcNode->nonce == response->clientResponse->sequenceNumber)
477 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
478 result = OC_STACK_NO_MEMORY;
481 mcNode->nonce = response->clientResponse->sequenceNumber;
485 uint32_t uriLen = strlen((char*)response->fullUri);
486 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
489 memcpy(uri, response->fullUri, (uriLen + 1));
494 PCF("===============No Memory for URI to store in the presence node"));
495 result = OC_STACK_NO_MEMORY;
498 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri,
499 response->clientResponse->sequenceNumber);
500 if(result == OC_STACK_NO_MEMORY)
503 PCF("===============No Memory for Multicast Presence Node"));
504 result = OC_STACK_NO_MEMORY;
509 // Ensure that a filter is actually applied.
510 if(resourceTypeName && cbNode->filterResourceType)
512 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
519 else if(!cbNode && isPresenceNotification)
521 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
522 ------------ ignoring"));
524 #endif // WITH_PRESENCE
528 if(isObserveNotification)
530 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
531 //TODO: check the standard for methods to detect wrap around condition
532 if(cbNode->method == OC_REST_OBSERVE &&
533 (response->clientResponse->sequenceNumber <= cbNode->sequenceNumber ||
534 (response->clientResponse->sequenceNumber > cbNode->sequenceNumber &&
535 response->clientResponse->sequenceNumber ==
536 MAX_SEQUENCE_NUMBER)))
538 OC_LOG_V(DEBUG, TAG, "Observe notification came out of order. \
539 Ignoring Incoming:%d Against Current:%d.",
540 response->clientResponse->sequenceNumber, cbNode->sequenceNumber);
543 if(response->clientResponse->sequenceNumber > cbNode->sequenceNumber){
544 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;
548 response->clientResponse->resJSONPayload = bufRes;
550 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response->clientResponse);
552 if (cbResult == OC_STACK_DELETE_TRANSACTION ||
553 response->clientResponse->result == OC_STACK_COMM_ERROR ||
554 (response->clientResponse->result == OC_STACK_RESOURCE_DELETED &&
555 !isPresenceNotification && !isMulticastPresence))
557 FindAndDeleteClientCB(cbNode);
562 result = OC_STACK_ERROR;
567 OCFree(resourceTypeName);
572 int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
575 unsigned char *itr, *coap;
576 uint8_t dotCount = 0;
580 /* search for scheme */
582 if (!isdigit((unsigned char) *ipAddrStr))
584 coap = (unsigned char *) OC_COAP_SCHEME;
585 while (*coap && tolower(*itr) == *coap)
594 if (isdigit((unsigned char) *ipAddrStr))
597 ipAddr[index] += *ipAddrStr - '0';
599 else if ((unsigned char) *ipAddrStr == '.')
611 if(*ipAddrStr == ':')
615 if (isdigit((unsigned char) *ipAddrStr))
618 *port += *ipAddrStr - '0';
629 if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
640 //-----------------------------------------------------------------------------
641 // Private internal function prototypes
642 //-----------------------------------------------------------------------------
644 static OCDoHandle GenerateInvocationHandle();
645 static OCStackResult initResources();
646 static void insertResource(OCResource *resource);
647 static OCResource *findResource(OCResource *resource);
648 static void insertResourceType(OCResource *resource,
649 OCResourceType *resourceType);
650 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
652 static void insertResourceInterface(OCResource *resource,
653 OCResourceInterface *resourceInterface);
654 static OCResourceInterface *findResourceInterfaceAtIndex(
655 OCResourceHandle handle, uint8_t index);
656 static void deleteResourceType(OCResourceType *resourceType);
657 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
658 static void deleteResourceElements(OCResource *resource);
659 static int deleteResource(OCResource *resource);
660 static void deleteAllResources();
661 static void incrementSequenceNumber(OCResource * resPtr);
662 static OCStackResult verifyUriQueryLength(const char * inputUri,
664 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
665 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI);
667 //-----------------------------------------------------------------------------
669 //-----------------------------------------------------------------------------
672 * Initialize the OC Stack. Must be called prior to starting the stack.
675 * IP Address of host device
677 * Port of host device
679 * Host device is client, server, or client-server
682 * OC_STACK_OK - no errors
683 * OC_STACK_ERROR - stack init error
685 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
687 OCStackResult result = OC_STACK_ERROR;
688 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
692 OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
696 //It is ok to select network to CA_WIFI for now
697 CAResult_t caResult = CASelectNetwork(CA_WIFI);
698 if(caResult == CA_STATUS_OK)
700 OC_LOG(INFO, TAG, PCF("CASelectNetwork to WIFI"));
701 caResult = CARegisterHandler(HandleCARequests, HandleCAResponses);
702 if(caResult == CA_STATUS_OK)
704 OC_LOG(INFO, TAG, PCF("CARegisterHandler..."));
705 stackState = OC_STACK_INITIALIZED;
706 result = OC_STACK_OK;
710 caResult = CAStartDiscoveryServer();
711 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
714 caResult = CAStartListeningServer();
715 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
717 case OC_CLIENT_SERVER:
718 caResult = CAStartListeningServer();
719 if(caResult == CA_STATUS_OK)
721 caResult = CAStartDiscoveryServer();
723 OC_LOG(INFO, TAG, PCF("Client-server mode"));
726 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
727 return OC_STACK_ERROR;
732 result = CAResultToOCStackResult(caResult);
738 OC_LOG(INFO, TAG, PCF("Client mode"));
741 OC_LOG(INFO, TAG, PCF("Server mode"));
743 case OC_CLIENT_SERVER:
744 OC_LOG(INFO, TAG, PCF("Client-server mode"));
747 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
748 return OC_STACK_ERROR;
752 // Make call to OCCoAP layer
753 result = OCInitCoAP(ipAddr, (uint16_t) port, myStackMode);
757 defaultDeviceHandler = NULL;
760 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
761 #endif // WITH_PRESENCE
763 if (result == OC_STACK_OK)
765 stackState = OC_STACK_INITIALIZED;
767 // Initialize resource
768 if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
770 result = initResources();
772 if(result != OC_STACK_OK)
774 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
780 * Stop the OC stack. Use for a controlled shutdown.
782 * OC_STACK_OK - no errors
783 * OC_STACK_ERROR - stack not initialized
785 OCStackResult OCStop()
787 OCStackResult result = OC_STACK_ERROR;
789 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
791 if (stackState != OC_STACK_INITIALIZED)
793 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
794 return OC_STACK_ERROR;
798 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
799 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
800 presenceResource.presenceTTL = 0;
801 #endif // WITH_PRESENCE
803 // Free memory dynamically allocated for resources
804 deleteAllResources();
806 // Make call to OCCoAP layer
807 if (OCStopCoAP() == OC_STACK_OK)
809 // Remove all observers
810 DeleteObserverList();
811 // Remove all the client callbacks
812 DeleteClientCBList();
813 stackState = OC_STACK_UNINITIALIZED;
814 result = OC_STACK_OK;
816 result = OC_STACK_ERROR;
819 // Deinit security blob
820 DeinitOCSecurityInfo();
822 if (result != OC_STACK_OK) {
823 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
830 * Verify the lengths of the URI and the query separately
832 * @param inputUri - Input URI and query.
833 * @param uriLen - The length of the initial URI with query.
835 * Note: The '?' that appears after the URI is not considered as
836 * a part of the query.
838 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
842 query = strchr (inputUri, '?');
846 if((query - inputUri) > MAX_URI_LENGTH)
848 return OC_STACK_INVALID_URI;
851 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
853 return OC_STACK_INVALID_QUERY;
856 else if(uriLen > MAX_URI_LENGTH)
858 return OC_STACK_INVALID_URI;
864 * Discover or Perform requests on a specified resource (specified by that Resource's respective URI).
866 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of calling this API.
867 * @param method - @ref OCMethod to perform on the resource
868 * @param requiredUri - URI of the resource to interact with
869 * @param referenceUri - URI of the reference resource
870 * @param request - JSON encoded request
871 * @param qos - quality of service
872 * @param cbData - struct that contains asynchronous callback function that is invoked
873 * by the stack when discovery or resource interaction is complete
874 * @param options - The address of an array containing the vendor specific header
875 * header options to be sent with the request
876 * @param numOptions - Number of vendor specific header options to be included
879 * OC_STACK_OK - no errors
880 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
881 * OC_STACK_INVALID_METHOD - invalid resource method
882 * OC_STACK_INVALID_URI - invalid required or reference URI
885 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
886 const char *referenceUri, const char *request,
887 OCQualityOfService qos, OCCallbackData *cbData,
888 OCHeaderOption * options, uint8_t numOptions)
890 OCStackResult result = OC_STACK_ERROR;
892 ClientCB *clientCB = NULL;
893 unsigned char * requestUri = NULL;
894 unsigned char * resourceType = NULL;
895 char * newUri = (char *)requiredUri;
898 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
900 // Validate input parameters
901 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
902 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
904 TODO ("Need to form the final query by concatenating require and reference URI's");
905 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
907 uint16_t uriLen = strlen(requiredUri);
909 // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS
916 case OC_REST_OBSERVE:
917 case OC_REST_OBSERVE_ALL:
918 case OC_REST_CANCEL_OBSERVE:
921 case OC_REST_PRESENCE:
925 result = OC_STACK_INVALID_METHOD;
929 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
934 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
936 result = OC_STACK_INVALID_PARAM;
941 if(method == OC_REST_PRESENCE)
943 result = getResourceType(requiredUri, &resourceType, &newUri);
945 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
949 OC_LOG(DEBUG, TAG, PCF("Got Resource Type is NULL."));
951 if(result != OC_STACK_OK)
956 #endif // WITH_PRESENCE
958 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
961 memcpy(requestUri, newUri, (uriLen + 1));
965 result = OC_STACK_NO_MEMORY;
969 *handle = GenerateInvocationHandle();
972 result = OC_STACK_NO_MEMORY;
976 // Generate token which will be used by OCStack to match responses received
978 OCGenerateCoAPToken(&token);
980 if((result = AddClientCB(&clientCB, cbData, &token, handle, method, requestUri, resourceType))
983 result = OC_STACK_NO_MEMORY;
988 if(method == OC_REST_PRESENCE)
990 // Replacing method type with GET because "presence" is a stack layer only implementation.
991 method = OC_REST_GET;
995 // Make call to OCCoAP layer
996 result = OCDoCoAPResource(method, qos, &token, newUri, request, options, numOptions);
999 if(newUri != requiredUri)
1003 if (result != OC_STACK_OK)
1005 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1006 FindAndDeleteClientCB(clientCB);
1012 * Cancel a request associated with a specific @ref OCDoResource invocation.
1014 * @param handle - Used to identify a specific OCDoResource invocation.
1015 * @param qos - used to specify Quality of Service (read below for more info)
1016 * @param options- used to specify vendor specific header options when sending
1017 * explicit observe cancellation
1018 * @param numOptions- Number of header options to be included
1021 * OC_STACK_OK - No errors; Success
1022 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1024 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1025 uint8_t numOptions) {
1027 * This ftn is implemented one of two ways in the case of observation:
1029 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1030 * Remove the callback associated on client side.
1031 * When the next notification comes in from server,
1032 * reply with RESET message to server.
1033 * Keep in mind that the server will react to RESET only
1034 * if the last notification was sent ans CON
1036 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1037 * and it is associated with an observe request
1038 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1039 * Send CON Observe request to server with
1040 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1041 * Remove the callback associated on client side.
1043 OCStackResult ret = OC_STACK_OK;
1046 return OC_STACK_INVALID_PARAM;
1049 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1051 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1054 switch (clientCB->method)
1056 case OC_REST_OBSERVE:
1057 case OC_REST_OBSERVE_ALL:
1058 if(qos == OC_HIGH_QOS)
1060 ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
1061 &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
1066 FindAndDeleteClientCB(clientCB);
1069 #ifdef WITH_PRESENCE
1070 case OC_REST_PRESENCE:
1071 FindAndDeleteClientCB(clientCB);
1075 return OC_STACK_INVALID_METHOD;
1080 #ifdef WITH_PRESENCE
1081 OCStackResult OCProcessPresence()
1083 OCStackResult result = OC_STACK_OK;
1084 uint8_t ipAddr[4] = { 0 };
1087 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1088 ClientCB* cbNode = NULL;
1090 OCClientResponse clientResponse;
1091 OCResponse * response = NULL;
1093 LL_FOREACH(cbList, cbNode) {
1094 if(OC_REST_PRESENCE == cbNode->method)
1096 if(cbNode->presence)
1098 uint32_t now = GetTime(0);
1099 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
1100 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1103 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1108 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1109 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1110 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1113 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1115 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1116 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1118 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1120 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
1121 (OCDevAddr *) &dst, 0, NULL);
1122 if(result != OC_STACK_OK)
1126 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1127 &cbNode->token, &clientResponse, NULL);
1128 if(result != OC_STACK_OK)
1133 // Increment the TTLLevel (going to a next state), so we don't keep
1134 // sending presence notification to client.
1135 cbNode->presence->TTLlevel++;
1136 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1137 cbNode->presence->TTLlevel);
1141 result = OC_STACK_INVALID_IP;
1144 HandleStackResponses(response);
1146 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1148 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
1150 OCGenerateCoAPToken(&token);
1151 result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
1152 &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
1153 if(result != OC_STACK_OK)
1157 cbNode->presence->TTLlevel++;
1158 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
1164 if (result != OC_STACK_OK)
1166 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
1173 * Called in main loop of OC client or server. Allows low-level processing of
1177 * OC_STACK_OK - no errors
1178 * OC_STACK_ERROR - stack process error
1180 OCStackResult OCProcess() {
1182 OC_LOG(INFO, TAG, PCF("Entering OCProcess"));
1183 #ifdef WITH_PRESENCE
1184 OCProcessPresence();
1187 CAHandleRequestResponse();
1195 #ifdef WITH_PRESENCE
1197 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
1198 * presence notifications to clients via multicast. Once this API has been called with a success,
1199 * clients may query for this server's presence and this server's stack will respond via multicast.
1201 * Server can call this function when it comes online for the first time, or when it comes back
1202 * online from offline mode, or when it re enters network.
1204 * @param ttl - Time To Live in seconds
1205 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
1208 * OC_STACK_OK - No errors; Success
1210 OCStackResult OCStartPresence(const uint32_t ttl)
1212 OCChangeResourceProperty(
1213 &(((OCResource *)presenceResource.handle)->resourceProperties),
1218 presenceResource.presenceTTL = ttl;
1221 if(OC_PRESENCE_UNINITIALIZED == presenceState)
1223 OCDevAddr multiCastAddr;
1226 presenceState = OC_PRESENCE_INITIALIZED;
1227 OCGenerateCoAPToken(&token);
1228 OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
1229 //add the presence observer
1230 AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
1231 (OCResource *)presenceResource.handle, OC_LOW_QOS);
1234 // Each time OCStartPresence is called
1235 // a different random 32-bit integer number is used
1236 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1238 return SendPresenceNotification(NULL);
1242 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
1243 * presence notifications to clients via multicast. Once this API has been called with a success,
1244 * this server's stack will not respond to clients querying for this server's presence.
1246 * Server can call this function when it is terminating, going offline, or when going
1247 * away from network.
1250 * OC_STACK_OK - No errors; Success
1252 OCStackResult OCStopPresence()
1254 OCStackResult result = OC_STACK_ERROR;
1255 //make resource inactive
1256 result = OCChangeResourceProperty(
1257 &(((OCResource *) presenceResource.handle)->resourceProperties),
1259 result = SendPresenceNotification(NULL);
1266 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
1268 defaultDeviceHandler = entityHandler;
1276 * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource
1277 * @param resourceTypeName - name of resource type. Example: "core.led"
1278 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1279 * @param uri - URI of the resource. Example: "/a/led"
1280 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1281 * NULL for default entity handler
1282 * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE
1285 * OC_STACK_OK - no errors
1286 * OC_STACK_ERROR - stack process error
1288 OCStackResult OCCreateResource(OCResourceHandle *handle,
1289 const char *resourceTypeName,
1290 const char *resourceInterfaceName,
1291 const char *uri, OCEntityHandler entityHandler,
1292 uint8_t resourceProperties) {
1294 OCResource *pointer = NULL;
1297 OCStackResult result = OC_STACK_ERROR;
1299 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
1301 if(myStackMode == OC_CLIENT)
1305 // Validate parameters
1306 // Is it presented during resource discovery?
1307 if (!handle || !resourceTypeName || !uri) {
1308 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
1309 return OC_STACK_INVALID_PARAM;
1312 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
1313 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
1316 // Make sure resourceProperties bitmask has allowed properties specified
1317 if (resourceProperties
1318 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
1319 OC_LOG(ERROR, TAG, PCF("Invalid property"));
1320 return OC_STACK_INVALID_PARAM;
1323 // If the headResource is NULL, then no resources have been created...
1324 pointer = headResource;
1326 // At least one resources is in the resource list, so we need to search for
1327 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
1329 if (strcmp(uri, pointer->uri) == 0) {
1330 OC_LOG(ERROR, TAG, PCF("URI already in use"));
1331 return OC_STACK_INVALID_PARAM;
1333 pointer = pointer->next;
1336 // Create the pointer and insert it into the resource list
1337 pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
1341 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
1343 insertResource(pointer);
1346 size = strlen(uri) + 1;
1347 str = (char *) OCMalloc(size);
1351 strncpy(str, uri, size);
1354 // Set properties. Set OC_ACTIVE
1355 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
1358 // Add the resourcetype to the resource
1359 result = BindResourceTypeToResource(pointer, resourceTypeName);
1360 if (result != OC_STACK_OK) {
1361 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
1365 // Add the resourceinterface to the resource
1366 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
1367 if (result != OC_STACK_OK) {
1368 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
1372 // If an entity handler has been passed, attach it to the newly created
1373 // resource. Otherwise, set the default entity handler.
1376 pointer->entityHandler = entityHandler;
1380 pointer->entityHandler = defaultResourceEHandler;
1384 result = OC_STACK_OK;
1386 #ifdef WITH_PRESENCE
1387 if(presenceResource.handle)
1389 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1390 SendPresenceNotification(pointer->rsrcType);
1394 if (result != OC_STACK_OK)
1396 // Deep delete of resource and other dynamic elements that it contains
1397 deleteResource(pointer);
1406 * Create a resource. with host ip address for remote resource
1408 * @param handle - pointer to handle to newly created resource. Set by ocstack.
1409 * Used to refer to resource
1410 * @param resourceTypeName - name of resource type. Example: "core.led"
1411 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1412 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
1413 * @param uri - URI of the resource. Example: "/a/led"
1414 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1415 * NULL for default entity handler
1416 * @param resourceProperties - properties supported by resource.
1417 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
1420 * OC_STACK_OK - no errors
1421 * OC_STACK_ERROR - stack process error
1424 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
1425 const char *resourceTypeName,
1426 const char *resourceInterfaceName,
1429 OCEntityHandler entityHandler,
1430 uint8_t resourceProperties)
1434 OCStackResult result = OC_STACK_ERROR;
1436 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
1437 uri, entityHandler, resourceProperties);
1439 if (result != OC_STACK_ERROR)
1442 size = strlen(host) + 1;
1443 str = (char *) OCMalloc(size);
1446 return OC_STACK_ERROR;
1448 strncpy(str, host, size);
1449 ((OCResource *) *handle)->host = str;
1456 * Add a resource to a collection resource.
1458 * @param collectionHandle - handle to the collection resource
1459 * @param resourceHandle - handle to resource to be added to the collection resource
1462 * OC_STACK_OK - no errors
1463 * OC_STACK_ERROR - stack process error
1464 * OC_STACK_INVALID_PARAM - invalid collectionhandle
1466 OCStackResult OCBindResource(
1467 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1468 OCResource *resource;
1471 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
1473 // Validate parameters
1474 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1475 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1476 // Container cannot contain itself
1477 if (collectionHandle == resourceHandle) {
1478 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
1479 return OC_STACK_INVALID_PARAM;
1482 // Use the handle to find the resource in the resource linked list
1483 resource = findResource((OCResource *) collectionHandle);
1485 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1486 return OC_STACK_INVALID_PARAM;
1489 // Look for an open slot to add add the child resource.
1490 // If found, add it and return success
1491 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1492 if (!resource->rsrcResources[i]) {
1493 resource->rsrcResources[i] = (OCResource *) resourceHandle;
1494 OC_LOG(INFO, TAG, PCF("resource bound"));
1499 #ifdef WITH_PRESENCE
1500 if(presenceResource.handle)
1502 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1503 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1507 // Unable to add resourceHandle, so return error
1508 return OC_STACK_ERROR;
1512 * Remove a resource from a collection resource.
1514 * @param collectionHandle - handle to the collection resource
1515 * @param resourceHandle - handle to resource to be added to the collection resource
1518 * OC_STACK_OK - no errors
1519 * OC_STACK_ERROR - stack process error
1520 * OC_STACK_INVALID_PARAM - invalid collectionHandle
1522 OCStackResult OCUnBindResource(
1523 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1524 OCResource *resource;
1527 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
1529 // Validate parameters
1530 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1531 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1532 // Container cannot contain itself
1533 if (collectionHandle == resourceHandle) {
1534 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
1535 return OC_STACK_INVALID_PARAM;
1538 // Use the handle to find the resource in the resource linked list
1539 resource = findResource((OCResource *) collectionHandle);
1541 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1542 return OC_STACK_INVALID_PARAM;
1545 // Look for an open slot to add add the child resource.
1546 // If found, add it and return success
1547 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1548 if (resourceHandle == resource->rsrcResources[i]) {
1549 resource->rsrcResources[i] = (OCResource *) NULL;
1550 OC_LOG(INFO, TAG, PCF("resource unbound"));
1555 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
1557 #ifdef WITH_PRESENCE
1558 if(presenceResource.handle)
1560 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1561 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1565 // Unable to add resourceHandle, so return error
1566 return OC_STACK_ERROR;
1569 OCStackResult BindResourceTypeToResource(OCResource* resource,
1570 const char *resourceTypeName)
1572 OCResourceType *pointer = NULL;
1575 OCStackResult result = OC_STACK_ERROR;
1577 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
1579 // Validate parameters
1580 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
1581 // TODO: Does resource attribute resentation really have to be maintained in stack?
1582 // Is it presented during resource discovery?
1584 TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
1586 // Create the resourcetype and insert it into the resource list
1587 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
1592 // Set the resourceTypeName
1593 size = strlen(resourceTypeName) + 1;
1594 str = (char *) OCMalloc(size);
1598 strncpy(str, resourceTypeName, size);
1599 pointer->resourcetypename = str;
1601 insertResourceType(resource, pointer);
1602 result = OC_STACK_OK;
1604 exit: if (result != OC_STACK_OK) {
1612 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
1613 const char *resourceInterfaceName)
1615 OCResourceInterface *pointer = NULL;
1618 OCStackResult result = OC_STACK_ERROR;
1620 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
1622 // Validate parameters
1623 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
1625 TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
1627 // Create the resourceinterface and insert it into the resource list
1628 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
1633 // Set the resourceinterface name
1634 size = strlen(resourceInterfaceName) + 1;
1635 str = (char *) OCMalloc(size);
1639 strncpy(str, resourceInterfaceName, size);
1640 pointer->name = str;
1642 // Bind the resourceinterface to the resource
1643 insertResourceInterface(resource, pointer);
1645 result = OC_STACK_OK;
1647 exit: if (result != OC_STACK_OK) {
1656 * Bind a resourcetype to a resource.
1658 * @param handle - handle to the resource
1659 * @param resourceTypeName - name of resource type. Example: "core.led"
1662 * OC_STACK_OK - no errors
1663 * OC_STACK_ERROR - stack process error
1665 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
1666 const char *resourceTypeName) {
1668 OCStackResult result = OC_STACK_ERROR;
1669 OCResource *resource;
1671 // Make sure resource exists
1672 resource = findResource((OCResource *) handle);
1674 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1675 return OC_STACK_ERROR;
1678 // call internal function
1679 result = BindResourceTypeToResource(resource, resourceTypeName);
1681 #ifdef WITH_PRESENCE
1682 if(presenceResource.handle)
1684 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1685 SendPresenceNotification(resource->rsrcType);
1693 * Bind a resourceinterface to a resource.
1695 * @param handle - handle to the resource
1696 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
1699 * OC_STACK_OK - no errors
1700 * OC_STACK_ERROR - stack process error
1703 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
1704 const char *resourceInterfaceName) {
1706 OCStackResult result = OC_STACK_ERROR;
1707 OCResource *resource;
1709 // Make sure resource exists
1710 resource = findResource((OCResource *) handle);
1712 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1713 return OC_STACK_ERROR;
1716 // call internal function
1717 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
1719 #ifdef WITH_PRESENCE
1720 if(presenceResource.handle)
1722 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1723 SendPresenceNotification(resource->rsrcType);
1731 * Get the number of resources that have been created in the stack.
1733 * @param numResources - pointer to count variable
1736 * OC_STACK_OK - no errors
1737 * OC_STACK_ERROR - stack process error
1740 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
1741 OCResource *pointer = headResource;
1743 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
1744 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
1747 *numResources = *numResources + 1;
1748 pointer = pointer->next;
1754 * Get a resource handle by index.
1756 * @param index - index of resource, 0 to Count - 1
1759 * Resource handle - if found
1760 * NULL - if not found
1762 OCResourceHandle OCGetResourceHandle(uint8_t index) {
1763 OCResource *pointer = headResource;
1766 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
1768 // Iterate through the list
1769 while ((i < index) && pointer) {
1771 pointer = pointer->next;
1773 return (OCResourceHandle) pointer;
1777 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
1780 * @param handle - handle of resource to be deleted
1783 * OC_STACK_OK - no errors
1784 * OC_STACK_ERROR - stack process error
1785 * OC_STACK_NO_RESOURCE - resource not found
1786 * OC_STACK_INVALID_PARAM - invalid param
1788 OCStackResult OCDeleteResource(OCResourceHandle handle) {
1789 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
1792 OC_LOG(ERROR, TAG, PCF("Invalid param"));
1793 return OC_STACK_INVALID_PARAM;
1796 OCResource *resource = findResource((OCResource *) handle);
1797 if (resource == NULL) {
1798 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1799 return OC_STACK_NO_RESOURCE;
1802 if (deleteResource((OCResource *) handle) == 0) {
1803 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
1804 return OC_STACK_ERROR;
1811 * Get the URI of the resource specified by handle.
1813 * @param handle - handle of resource
1815 * URI string - if resource found
1816 * NULL - resource not found
1818 const char *OCGetResourceUri(OCResourceHandle handle) {
1819 OCResource *resource;
1820 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
1822 resource = findResource((OCResource *) handle);
1824 return resource->uri;
1826 return (const char *) NULL;
1830 * Get the properties of the resource specified by handle.
1831 * NOTE: that after a resource is created, the OC_ACTIVE property is set
1832 * for the resource by the stack.
1834 * @param handle - handle of resource
1836 * property bitmap - if resource found
1837 * NULL - resource not found
1839 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
1840 OCResource *resource;
1841 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
1843 resource = findResource((OCResource *) handle);
1845 return resource->resourceProperties;
1851 * Get the number of resource types of the resource.
1853 * @param handle - handle of resource
1854 * @param numResourceTypes - pointer to count variable
1857 * OC_STACK_OK - no errors
1858 * OC_STACK_ERROR - stack process error
1860 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
1861 uint8_t *numResourceTypes) {
1862 OCResource *resource;
1863 OCResourceType *pointer;
1865 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
1866 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
1867 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
1869 *numResourceTypes = 0;
1871 resource = findResource((OCResource *) handle);
1873 pointer = resource->rsrcType;
1875 *numResourceTypes = *numResourceTypes + 1;
1876 pointer = pointer->next;
1883 * Get name of resource type of the resource.
1885 * @param handle - handle of resource
1886 * @param index - index of resource, 0 to Count - 1
1889 * resource type name - if resource found
1890 * NULL - resource not found
1892 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
1893 OCResourceType *resourceType;
1895 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
1897 resourceType = findResourceTypeAtIndex(handle, index);
1899 return resourceType->resourcetypename;
1901 return (const char *) NULL;
1907 * Get the number of resource interfaces of the resource.
1909 * @param handle - handle of resource
1910 * @param numResources - pointer to count variable
1913 * OC_STACK_OK - no errors
1914 * OC_STACK_ERROR - stack process error
1916 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
1917 uint8_t *numResourceInterfaces) {
1918 OCResourceInterface *pointer;
1919 OCResource *resource;
1921 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
1923 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
1924 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
1926 *numResourceInterfaces = 0;
1927 resource = findResource((OCResource *) handle);
1929 pointer = resource->rsrcInterface;
1931 *numResourceInterfaces = *numResourceInterfaces + 1;
1932 pointer = pointer->next;
1939 * Get name of resource interface of the resource.
1941 * @param handle - handle of resource
1942 * @param index - index of resource, 0 to Count - 1
1945 * resource interface name - if resource found
1946 * NULL - resource not found
1948 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
1949 OCResourceInterface *resourceInterface;
1951 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
1953 resourceInterface = findResourceInterfaceAtIndex(handle, index);
1954 if (resourceInterface) {
1955 return resourceInterface->name;
1957 return (const char *) NULL;
1961 * Get resource handle from the collection resource by index.
1963 * @param collectionHandle - handle of collection resource
1964 * @param index - index of contained resource, 0 to Count - 1
1967 * handle to resource - if resource found
1968 * NULL - resource not found
1970 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
1972 OCResource *resource;
1974 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
1976 if (index >= MAX_CONTAINED_RESOURCES) {
1980 resource = findResource((OCResource *) collectionHandle);
1985 return resource->rsrcResources[index];
1989 * Bind an entity handler to the resource.
1991 * @param handle - handle to the resource that the contained resource is to be bound
1992 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1994 * OC_STACK_OK - no errors
1995 * OC_STACK_ERROR - stack process error
1997 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
1998 OCEntityHandler entityHandler) {
1999 OCResource *resource;
2001 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2003 // Validate parameters
2004 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2005 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2007 // Use the handle to find the resource in the resource linked list
2008 resource = findResource((OCResource *)handle);
2010 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2011 return OC_STACK_ERROR;
2015 resource->entityHandler = entityHandler;
2017 #ifdef WITH_PRESENCE
2018 if(presenceResource.handle)
2020 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2021 SendPresenceNotification(resource->rsrcType);
2029 * Get the entity handler for a resource.
2031 * @param handle - handle of resource
2034 * entity handler - if resource found
2035 * NULL - resource not found
2037 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
2038 OCResource *resource;
2040 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2042 // Use the handle to find the resource in the resource linked list
2043 resource = findResource((OCResource *)handle);
2045 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2050 return resource->entityHandler;
2053 void incrementSequenceNumber(OCResource * resPtr)
2055 // Increment the sequence number
2056 resPtr->sequenceNum += 1;
2057 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2059 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2065 * Notify Presence subscribers that a resource has been modified
2067 * @param resourceType - Handle to the resourceType linked list of resource
2068 * that was modified.
2069 * @param qos - Quality Of Service
2072 #ifdef WITH_PRESENCE
2073 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
2075 OCResource *resPtr = NULL;
2076 OCStackResult result;
2077 OCMethod method = OC_REST_PRESENCE;
2078 uint32_t maxAge = 0;
2079 resPtr = findResource((OCResource *) presenceResource.handle);
2082 return OC_STACK_NO_RESOURCE;
2084 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
2086 maxAge = presenceResource.presenceTTL;
2093 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
2096 #endif // WITH_PRESENCE
2098 * Notify observers that an observed value has changed.
2100 * @param handle - handle of resource
2103 * OC_STACK_OK - no errors
2104 * OC_STACK_NO_RESOURCE - invalid resource handle
2105 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
2107 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
2109 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2111 OCResource *resPtr = NULL;
2112 OCStackResult result;
2113 OCMethod method = OC_REST_NOMETHOD;
2114 uint32_t maxAge = 0;
2116 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2117 #ifdef WITH_PRESENCE
2118 if(handle == presenceResource.handle)
2122 #endif // WITH_PRESENCE
2123 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2125 // Verify that the resource exists
2126 resPtr = findResource ((OCResource *) handle);
2129 return OC_STACK_NO_RESOURCE;
2133 //only increment in the case of regular observing (not presence)
2134 incrementSequenceNumber(resPtr);
2135 method = OC_REST_OBSERVE;
2136 maxAge = MAX_OBSERVE_AGE;
2137 #ifdef WITH_PRESENCE
2138 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
2140 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
2147 OCNotifyListOfObservers (OCResourceHandle handle,
2148 OCObservationId *obsIdList,
2149 uint8_t numberOfIds,
2150 unsigned char *notificationJSONPayload,
2151 OCQualityOfService qos)
2153 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
2155 OCResource *resPtr = NULL;
2156 //TODO: we should allow the server to define this
2157 uint32_t maxAge = MAX_OBSERVE_AGE;
2159 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2160 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
2161 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
2163 // Verify that the resource exists
2164 resPtr = findResource ((OCResource *) handle);
2165 if (NULL == resPtr || myStackMode == OC_CLIENT)
2167 return OC_STACK_NO_RESOURCE;
2171 incrementSequenceNumber(resPtr);
2173 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
2174 notificationJSONPayload, maxAge, qos));
2178 * Send a response to a request.
2179 * The response can be a regular, slow, or block (i.e. a response that
2180 * is too large to be sent in a single PDU and must span multiple transmissions)
2182 * @param response - pointer to structure that contains response parameters
2185 * OC_STACK_OK - No errors; Success
2186 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
2187 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
2188 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
2189 * persistent response buffer is necessary
2191 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
2193 OCStackResult result = OC_STACK_ERROR;
2194 OCServerRequest *serverRequest = NULL;
2196 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
2198 // Validate input parameters
2199 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
2200 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
2202 // TODO: Placeholder for creating a response entry when implementing
2203 // block transfer feature
2205 // If a response payload is present, check if block transfer is required
2206 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
2207 (const char *)ehResponse->payload, ehResponse->payloadSize))
2209 OC_LOG(INFO, TAG, PCF("Block transfer required"));
2211 // Persistent response buffer is needed for block transfer
2212 if (!ehResponse->persistentBufferFlag)
2214 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
2215 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
2217 // TODO: Placeholder for block transfer handling
2218 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
2219 // when implementing the block transfer feature
2225 // Get pointer to request info
2226 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
2229 result = serverRequest->ehResponseHandler(ehResponse);
2236 * Cancel a response. Applies to a block response
2238 * @param responseHandle - response handle set by stack in OCServerResponse after
2239 * OCDoResponse is called
2242 * OC_STACK_OK - No errors; Success
2243 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
2245 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
2247 OCStackResult result = OC_STACK_NOTIMPL;
2249 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
2251 // TODO: validate response handle
2256 //-----------------------------------------------------------------------------
2257 // Private internal function definitions
2258 //-----------------------------------------------------------------------------
2260 * Generate handle of OCDoResource invocation for callback management.
2262 static OCDoHandle GenerateInvocationHandle()
2264 OCDoHandle handle = NULL;
2265 // Generate token here, it will be deleted when the transaction is deleted
2266 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2269 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2274 #ifdef WITH_PRESENCE
2275 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
2276 OCResourceProperty resourceProperties, uint8_t enable)
2278 if (resourceProperties
2279 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
2280 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2281 return OC_STACK_INVALID_PARAM;
2285 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
2289 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
2296 * Initialize resource data structures, variables, etc.
2298 OCStackResult initResources() {
2299 OCStackResult result = OC_STACK_OK;
2300 // Init application resource vars
2301 headResource = NULL;
2302 // Init Virtual Resources
2303 #ifdef WITH_PRESENCE
2304 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
2305 //presenceResource.token = OCGenerateCoAPToken();
2306 result = OCCreateResource(&presenceResource.handle,
2307 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
2312 //make resource inactive
2313 result = OCChangeResourceProperty(
2314 &(((OCResource *) presenceResource.handle)->resourceProperties),
2321 * Add a resource to the end of the linked list of resources.
2323 * @param resource - resource to be added
2325 void insertResource(OCResource *resource) {
2326 OCResource *pointer;
2328 if (!headResource) {
2329 headResource = resource;
2331 pointer = headResource;
2333 while (pointer->next) {
2334 pointer = pointer->next;
2336 pointer->next = resource;
2338 resource->next = NULL;
2342 * Find a resource in the linked list of resources.
2344 * @param resource - resource to be found
2346 * NULL - resource not found
2347 * pointer to resource - pointer to resource that was found in the linked list
2349 OCResource *findResource(OCResource *resource) {
2350 OCResource *pointer = headResource;
2353 if (pointer == resource) {
2356 pointer = pointer->next;
2361 void deleteAllResources()
2363 OCResource *pointer = headResource;
2368 temp = pointer->next;
2369 #ifdef WITH_PRESENCE
2370 if(pointer != (OCResource *) presenceResource.handle)
2372 #endif // WITH_PRESENCE
2373 deleteResource(pointer);
2374 #ifdef WITH_PRESENCE
2376 #endif // WITH_PRESENCE
2380 #ifdef WITH_PRESENCE
2381 // Ensure that the last resource to be deleted is the presence resource. This allows for all
2382 // presence notification attributed to their deletion to be processed.
2383 deleteResource((OCResource *) presenceResource.handle);
2384 #endif // WITH_PRESENCE
2388 * Delete the resource from the linked list.
2390 * @param resource - resource to be deleted
2395 int deleteResource(OCResource *resource) {
2396 OCResource *prev = NULL;
2399 temp = headResource;
2401 if (temp == resource) {
2402 // Invalidate all Resource Properties.
2403 resource->resourceProperties = (OCResourceProperty) 0;
2404 #ifdef WITH_PRESENCE
2405 if(resource != (OCResource *) presenceResource.handle)
2407 #endif // WITH_PRESENCE
2408 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
2409 #ifdef WITH_PRESENCE
2412 if(presenceResource.handle)
2414 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2415 if(resource != (OCResource *) presenceResource.handle)
2417 SendPresenceNotification(resource->rsrcType);
2421 SendPresenceNotification(NULL);
2426 if (temp == headResource) {
2427 headResource = temp->next;
2429 prev->next = temp->next;
2432 deleteResourceElements(temp);
2445 * Delete all of the dynamically allocated elements that were created for the resource.
2447 * @param resource - specified resource
2449 void deleteResourceElements(OCResource *resource) {
2455 OCFree(resource->uri);
2457 // Delete resourcetype linked list
2458 deleteResourceType(resource->rsrcType);
2460 // Delete resourceinterface linked list
2461 deleteResourceInterface(resource->rsrcInterface);
2465 * Delete all of the dynamically allocated elements that were created for the resource type.
2467 * @param resourceType - specified resource type
2469 void deleteResourceType(OCResourceType *resourceType) {
2470 OCResourceType *pointer = resourceType;
2471 OCResourceType *next;
2474 next = pointer->next;
2475 OCFree(pointer->resourcetypename);
2482 * Delete all of the dynamically allocated elements that were created for the resource interface.
2484 * @param resourceInterface - specified resource interface
2486 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
2487 OCResourceInterface *pointer = resourceInterface;
2488 OCResourceInterface *next;
2491 next = pointer->next;
2492 OCFree(pointer->name);
2499 * Insert a resource type into a resource's resource type linked list.
2501 * @param resource - resource where resource type is to be inserted
2502 * @param resourceType - resource type to be inserted
2504 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
2505 OCResourceType *pointer;
2507 if (resource && !resource->rsrcType) {
2508 resource->rsrcType = resourceType;
2512 pointer = resource->rsrcType;
2516 pointer = resourceType;
2518 while (pointer->next) {
2519 pointer = pointer->next;
2521 pointer->next = resourceType;
2523 resourceType->next = NULL;
2527 * Get a resource type at the specified index within a resource.
2529 * @param handle - handle of resource
2530 * @param index - index of resource type
2533 * resourcetype - if found
2536 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
2537 OCResource *resource;
2538 OCResourceType *pointer;
2541 // Find the specified resource
2542 resource = findResource((OCResource *) handle);
2547 // Make sure a resource has a resourcetype
2548 if (!resource->rsrcType) {
2552 // Iterate through the list
2553 pointer = resource->rsrcType;
2555 while ((i < index) && pointer) {
2557 pointer = pointer->next;
2563 * Finds a resource type in an OCResourceType link-list.
2565 * @param resourceTypeList - the link-list to be searched through
2566 * @param resourceTypeName - the key to search for
2569 * resourceType that matches the key (ie. resourceTypeName)
2570 * NULL - either an invalid parameter or this function was unable to find the key.
2572 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
2574 if(resourceTypeList && resourceTypeName)
2576 OCResourceType * rtPointer = resourceTypeList;
2577 while(resourceTypeName && rtPointer)
2579 if(rtPointer->resourcetypename &&
2580 strcmp(resourceTypeName, (const char *)
2581 (rtPointer->resourcetypename)) == 0)
2585 rtPointer = rtPointer->next;
2592 * Insert a resource interface into a resource's resource interface linked list.
2594 * @param resource - resource where resource interface is to be inserted
2595 * @param resourceInterface - resource interface to be inserted
2597 void insertResourceInterface(OCResource *resource,
2598 OCResourceInterface *resourceInterface) {
2599 OCResourceInterface *pointer;
2601 if (!resource->rsrcInterface) {
2602 resource->rsrcInterface = resourceInterface;
2604 pointer = resource->rsrcInterface;
2605 while (pointer->next) {
2606 pointer = pointer->next;
2608 pointer->next = resourceInterface;
2610 resourceInterface->next = NULL;
2614 * Get a resource interface at the specified index within a resource.
2616 * @param handle - handle of resource
2617 * @param index - index of resource interface
2620 * resourceinterface - if found
2623 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
2625 OCResource *resource;
2626 OCResourceInterface *pointer;
2629 // Find the specified resource
2630 resource = findResource((OCResource *) handle);
2635 // Make sure a resource has a resourceinterface
2636 if (!resource->rsrcInterface) {
2640 // Iterate through the list
2641 pointer = resource->rsrcInterface;
2643 while ((i < index) && pointer) {
2645 pointer = pointer->next;
2651 * Determine if a request/response must be sent in a block transfer because it is too large to be
2652 * sent in a single PDU. This function can be used for either a request or a response
2654 * @param request - NULL or pointer to request
2655 * @param response - NULL or pointer to response
2656 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
2657 * the length of the request/response
2660 * 0 - packet transfer NOT required (i.e. normal request/response)
2661 * 1 - packet transfer required (i.e. block transfer needed)
2663 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
2667 // Determine if we are checking a request or a response
2670 // If size is greater than 0, use it for the request size value, otherwise
2671 // assume request is null terminated and use strlen for size value
2672 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
2679 // If size is greater than 0, use it for the response size value, otherwise
2680 // assume response is null terminated and use strlen for size value
2681 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
2690 * Retrieves a resource type based upon a uri string if the uri string contains only just one
2691 * resource attribute (and that has to be of type "rt").
2693 * @remark This API malloc's memory for the resource type and newURI. Do not malloc resourceType
2694 * or newURI before passing in.
2696 * @param uri - Valid URI for "requiredUri" parameter to OCDoResource API.
2697 * @param resourceType - The resource type to be populated; pass by reference.
2698 * @param newURI - Return URI without resourceType appended to the end of it. This is used to
2699 * ensure that the uri parameter is not modified; pass by reference.
2702 * OC_STACK_INVALID_URI - Returns this if the URI is invalid/NULL.
2703 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
2704 * OC_STACK_OK - Success
2706 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI)
2710 return OC_STACK_INVALID_URI;
2712 if(!resourceType || !newURI)
2714 return OC_STACK_INVALID_PARAM;
2716 char * leftToken = NULL;
2717 char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
2722 strcpy(tempURI, uri);
2723 leftToken = strtok((char *)tempURI, "?");
2725 while(leftToken != NULL)
2727 if(strncmp(leftToken, "rt=", 3) == 0)
2729 *resourceType = (unsigned char *) OCMalloc(strlen(leftToken)-3);
2734 strcpy((char *)*resourceType, ((const char *)&leftToken[3]));
2737 leftToken = strtok(NULL, "?");
2745 return OC_STACK_NO_MEMORY;
2748 const ServerID OCGetServerInstanceID(void)
2750 static bool generated = false;
2751 static ServerID sid;
2758 sid = OCGetRandom();
2763 const char* OCGetServerInstanceIDString(void)
2765 // max printed length of a base 10
2766 // uint32 is 10 characters, so 11 includes null.
2767 // This will change as the representation gets switched
2769 static char buffer[11];
2770 int n = sprintf(buffer, "%u", OCGetServerInstanceID());