1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 //-----------------------------------------------------------------------------
24 //-----------------------------------------------------------------------------
25 #define _POSIX_C_SOURCE 200112L
29 #include "ocstackinternal.h"
30 #include "ocresourcehandler.h"
31 #include "occlientcb.h"
32 #include "ocobserve.h"
37 #include "ocserverrequest.h"
41 #include "cainterface.h"
44 //-----------------------------------------------------------------------------
46 //-----------------------------------------------------------------------------
48 OC_STACK_UNINITIALIZED = 0, OC_STACK_INITIALIZED, OC_STACK_UNINIT_IN_PROGRESS
53 OC_PRESENCE_UNINITIALIZED = 0, OC_PRESENCE_INITIALIZED
57 //-----------------------------------------------------------------------------
59 //-----------------------------------------------------------------------------
60 static OCStackState stackState = OC_STACK_UNINITIALIZED;
62 OCResource *headResource = NULL;
64 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
65 static PresenceResource presenceResource;
66 uint8_t PresenceTimeOutSize = 0;
67 uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
71 OCDeviceEntityHandler defaultDeviceHandler;
72 OCStackResult getQueryFromUri(const char * uri, unsigned char** resourceType, char ** newURI);
74 //-----------------------------------------------------------------------------
76 //-----------------------------------------------------------------------------
77 #define TAG PCF("OCStack")
78 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
79 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
80 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
81 TAG, PCF(#arg " is NULL")); return (retVal); } }
82 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
85 //TODO: we should allow the server to define this
86 #define MAX_OBSERVE_AGE (0x2FFFFUL)
88 //-----------------------------------------------------------------------------
90 //-----------------------------------------------------------------------------
91 extern void DeinitOCSecurityInfo();
93 //-----------------------------------------------------------------------------
94 // Internal API function
95 //-----------------------------------------------------------------------------
97 // This internal function is called to update the stack with the status of
98 // observers and communication failures
99 OCStackResult OCStackFeedBack(OCCoAPToken * token, uint8_t status)
101 OCStackResult result = OC_STACK_ERROR;
102 ResourceObserver * observer = NULL;
103 OCEntityHandlerRequest ehRequest = {0};
107 case OC_OBSERVER_NOT_INTERESTED:
108 OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
110 observer = GetObserverUsingToken (token->token);
112 observer = GetObserverUsingToken (token);
116 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
117 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
118 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
119 if(result != OC_STACK_OK)
123 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
125 //observer is not observing anymore
127 result = DeleteObserverUsingToken (token->token);
129 result = DeleteObserverUsingToken (token);
131 if(result == OC_STACK_OK)
133 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
137 result = OC_STACK_OK;
138 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
141 case OC_OBSERVER_STILL_INTERESTED:
142 //observer is still interested
143 OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
144 notifications, reset the failedCount"));
146 observer = GetObserverUsingToken (token->token);
148 observer = GetObserverUsingToken (token);
152 observer->forceHighQos = 0;
153 observer->failedCommCount = 0;
154 result = OC_STACK_OK;
158 result = OC_STACK_OBSERVER_NOT_FOUND;
161 case OC_OBSERVER_FAILED_COMM:
162 //observer is not reachable
163 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
165 observer = GetObserverUsingToken (token->token);
167 observer = GetObserverUsingToken (token);
171 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
173 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
174 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
175 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
176 if(result != OC_STACK_OK)
178 return OC_STACK_ERROR;
180 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
181 //observer is unreachable
182 result = DeleteObserverUsingToken (token);
183 if(result == OC_STACK_OK)
185 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
189 result = OC_STACK_OK;
190 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
195 observer->failedCommCount++;
196 result = OC_STACK_CONTINUE;
198 observer->forceHighQos = 1;
199 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
203 OC_LOG(ERROR, TAG, PCF("Unknown status"));
204 result = OC_STACK_ERROR;
211 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
213 OCStackResult ret = OC_STACK_ERROR;
221 ret = OC_STACK_RESOURCE_CREATED;
224 ret = OC_STACK_RESOURCE_DELETED;
227 ret = OC_STACK_INVALID_QUERY;
230 ret = OC_STACK_INVALID_OPTION;
233 ret = OC_STACK_NO_RESOURCE;
241 //This function will be called back by CA layer when a response is received
242 void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
244 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
245 printf ("Received payload: %s\n", (char *)responseInfo->info.payload);
246 OCStackApplicationResult result = OC_STACK_DELETE_TRANSACTION;
247 ClientCB *cbNode = GetClientCB((CAToken_t *)&responseInfo->info.token, NULL, NULL);
250 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
251 OCClientResponse response;
252 struct sockaddr_in sa;
254 inet_pton(AF_INET, endPoint->addressInfo.IP.ipAddress, &(sa.sin_addr));
255 sa.sin_port = htons(endPoint->addressInfo.IP.port);
256 static OCDevAddr address;
257 memcpy((void*)&address.addr, &(sa), sizeof(sa));
258 response.addr = &address;
259 response.result = CAToOCStackResult(responseInfo->result);
260 response.resJSONPayload = (unsigned char*)responseInfo->info.payload;
261 response.numRcvdVendorSpecificHeaderOptions = 0;
262 if(responseInfo->info.numOptions > 0)
264 //First option alwas with option ID COAP_OPTION_OBSERVE if it is availbale
265 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
267 memcpy (&(response.sequenceNumber),
268 &(responseInfo->info.options[0].optionData), 4);
272 memcpy (&(response.rcvdVendorSpecificHeaderOptions[0]),
273 &(responseInfo->info.options[0]), sizeof(OCHeaderOption));
275 for (uint8_t i = 1; i < responseInfo->info.numOptions; i++)
277 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i]),
278 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
280 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
282 result = cbNode->callBack(cbNode->context,
283 cbNode->handle, &response);
284 if (result == OC_STACK_DELETE_TRANSACTION)
286 FindAndDeleteClientCB(cbNode);
289 OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload);
290 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
293 //This function will be called back by CA layer when a request is received
294 void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
296 CAInfo_t responseData;
297 CAResponseInfo_t responseInfo;
298 OCStackResult requestResult = OC_STACK_ERROR;
300 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
303 if(myStackMode == OC_CLIENT)
305 //TODO: should the client be responding to requests?
309 OCServerProtocolRequest serverRequest;
311 memset (&serverRequest, 0, sizeof(OCServerProtocolRequest));
312 OC_LOG_V(INFO, TAG, PCF("***** Endpoint URI ***** : %s\n"), (char*)endPoint->resourceUri);
314 char * newUri = (char *)endPoint->resourceUri;
315 unsigned char * query = NULL;
316 unsigned char * resourceType = NULL;
317 getQueryFromUri(endPoint->resourceUri, &query, &newUri);
318 OC_LOG_V(INFO, TAG, PCF("**********URI without query ****: %s\n"), newUri);
319 OC_LOG_V(INFO, TAG, PCF("**********Query ****: %s\n"), query);
321 memcpy (&(serverRequest.resourceUrl), newUri, strlen(newUri));
325 memcpy (&(serverRequest.query), query, strlen(query));
327 //copy request payload
328 if (requestInfo->info.payload)
330 serverRequest.reqTotalSize = strlen(requestInfo->info.payload) + 1;
331 memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
332 strlen(requestInfo->info.payload));
333 serverRequest.reqTotalSize = strlen((const char *)requestInfo->info.payload) + 1;
337 serverRequest.reqTotalSize = 1;
340 switch (requestInfo->method)
344 serverRequest.method = OC_REST_GET;
349 serverRequest.method = OC_REST_PUT;
354 serverRequest.method = OC_REST_POST;
359 serverRequest.method = OC_REST_DELETE;
364 OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
370 OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d", strlen(requestInfo->info.token));
371 OC_LOG_BUFFER(INFO, TAG, requestInfo->info.token, strlen(requestInfo->info.token));
372 // TODO-CA: For CA integration currently copying CAToken to OCCoapToken:
373 // Need to remove OCCoapToken
374 memcpy (&(serverRequest.requestToken.token), requestInfo->info.token,
375 strlen(requestInfo->info.token));
376 serverRequest.requestToken.tokenLength = strlen(requestInfo->info.token);
378 if (requestInfo->info.type == CA_MSG_CONFIRM)
380 serverRequest.qos = OC_HIGH_QOS;
382 else if (requestInfo->info.type == CA_MSG_NONCONFIRM)
384 serverRequest.qos = OC_LOW_QOS;
386 else if (requestInfo->info.type == CA_MSG_ACKNOWLEDGE)
388 // TODO-CA: Need to handle this
390 else if (requestInfo->info.type == CA_MSG_RESET)
392 // TODO-CA: Need to handle this
394 // CA does not need the following 3 fields
395 serverRequest.coapID = 0;
396 serverRequest.delayedResNeeded = 0;
397 serverRequest.secured = endPoint->isSecured;
400 serverRequest.addressInfo = endPoint->addressInfo;
401 serverRequest.connectivityType = endPoint->connectivityType;
402 if (requestInfo->info.token)
404 strncpy(serverRequest.token, requestInfo->info.token, sizeof(serverRequest.token) - 1);
407 // copy vendor specific header options
408 // TODO-CA: CA is including non-vendor header options as well, like observe.
409 // Need to filter those out
410 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &(requestInfo->info.numOptions));
411 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
413 // TODO-CA: Need to send an error indicating the num of options is incorrect
416 serverRequest.numRcvdVendorSpecificHeaderOptions = requestInfo->info.numOptions;
417 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
419 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
420 sizeof(CAHeaderOption_t)*requestInfo->info.numOptions);
423 requestResult = HandleStackRequests (&serverRequest);
426 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
431 //This function will be called back by occoap layer when a request is received
432 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
434 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
436 OCStackResult result = OC_STACK_ERROR;
437 ResourceHandling resHandling;
438 OCResource *resource;
440 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
443 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
445 result = AddServerCARequest(&request, protocolRequest->coapID,
446 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
447 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
448 protocolRequest->observationOption, protocolRequest->qos,
449 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
450 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
451 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
452 protocolRequest->reqTotalSize,
453 &protocolRequest->addressInfo, protocolRequest->connectivityType, protocolRequest->token);
455 result = AddServerRequest(&request, protocolRequest->coapID,
456 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
457 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
458 protocolRequest->observationOption, protocolRequest->qos,
459 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
460 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
461 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
462 protocolRequest->reqTotalSize);
464 if (OC_STACK_OK != result)
466 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
469 VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
471 if(!protocolRequest->reqMorePacket)
473 request->requestComplete = 1;
478 OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
481 if(request->requestComplete)
483 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
484 result = DetermineResourceHandling (request, &resHandling, &resource);
485 if (result == OC_STACK_OK)
487 result = ProcessRequest(resHandling, resource, request);
491 result = OC_STACK_ERROR;
496 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
497 result = OC_STACK_CONTINUE;
502 //This function will be called back by occoap layer when a response is received
503 OCStackResult HandleStackResponses(OCResponse * response)
505 OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)"));
506 OCStackResult result = OC_STACK_OK;
507 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
508 uint8_t isObserveNotification = 0;
509 ClientCB * cbNode = NULL;
511 uint8_t isPresenceNotification = 0;
512 uint8_t isMulticastPresence = 0;
513 char * resourceTypeName = NULL;
514 uint32_t lowerBound = 0;
515 uint32_t higherBound = 0;
517 unsigned char * bufRes = response->bufRes;
518 #endif // WITH_PRESENCE
520 cbNode = response->cbNode;
523 cbNode = GetClientCB(response->rcvdToken, NULL, NULL);
526 if(response->clientResponse->sequenceNumber >= OC_OFFSET_SEQUENCE_NUMBER)
528 isObserveNotification = 1;
529 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
532 OC_LOG_V(DEBUG, TAG, "The sequenceNumber/NONCE of this response %u",
533 response->clientResponse->sequenceNumber);
534 OC_LOG_V(DEBUG, TAG, "The maxAge/TTL of this response %u", response->maxAge);
535 OC_LOG_V(DEBUG, TAG, "The response received is %s", bufRes);
538 if(!strcmp((char *)response->rcvdUri, (char *)OC_PRESENCE_URI)){
539 isPresenceNotification = 1;
542 result = OC_STACK_INVALID_PARAM;
545 tok = strtok((char *)bufRes, "[:]}");
546 bufRes[strlen((char *)bufRes)] = ':';
547 tok = strtok(NULL, "[:]}");
548 bufRes[strlen((char *)bufRes)] = ':';
549 response->clientResponse->sequenceNumber = (uint32_t )atoi(tok);
550 OC_LOG_V(DEBUG, TAG, "The received NONCE is %u", response->clientResponse->sequenceNumber);
551 tok = strtok(NULL, "[:]}");
552 response->maxAge = (uint32_t )atoi(tok);
553 OC_LOG_V(DEBUG, TAG, "The received TTL is %u", response->maxAge);
554 tok = strtok(NULL, "[:]}");
557 resourceTypeName = (char *)OCMalloc(strlen(tok));
558 if(!resourceTypeName)
562 bufRes[strlen((char *)bufRes)] = ':';
563 strcpy(resourceTypeName, tok);
564 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
567 bufRes[strlen((char *)bufRes)] = ']';
570 // Check if the application subcribed for presence
573 cbNode = GetClientCB(NULL, NULL, response->fullUri);
576 // Check if application subscribed for multicast presence
579 snprintf((char *)response->fullUri, MAX_URI_LENGTH, "%s%s",
580 OC_MULTICAST_IP, response->rcvdUri);
581 cbNode = GetClientCB(NULL, NULL, response->fullUri);
584 isMulticastPresence = 1;
585 isPresenceNotification = 0;
589 if(cbNode && isPresenceNotification)
591 OC_LOG(INFO, TAG, PCF("Received a presence notification"));
592 if(!cbNode->presence)
594 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
595 VERIFY_NON_NULL_V(cbNode->presence);
596 cbNode->presence->timeOut = NULL;
597 cbNode->presence->timeOut = (uint32_t *)
598 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
599 if(!(cbNode->presence->timeOut)){
600 OCFree(cbNode->presence);
601 result = OC_STACK_NO_MEMORY;
604 if(response->maxAge == 0)
606 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
607 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
610 OCFree(cbNode->presence->timeOut);
611 OCFree(cbNode->presence);
612 cbNode->presence = NULL;
617 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %d", GetTime(0));
618 cbNode->presence->TTL = response->maxAge;
619 for(int index = 0; index < PresenceTimeOutSize; index++)
621 lowerBound = GetTime(((float)(PresenceTimeOut[index])
622 /(float)100)*(float)cbNode->presence->TTL);
623 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
624 /(float)100)*(float)cbNode->presence->TTL);
625 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
626 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
627 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
628 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
629 cbNode->presence->timeOut[index]);
631 cbNode->presence->TTLlevel = 0;
632 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
633 if(cbNode->sequenceNumber == response->clientResponse->sequenceNumber)
635 OC_LOG(INFO, TAG, PCF("===============No presence change"));
638 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
639 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;;
642 // Ensure that a filter is actually applied.
643 if(resourceTypeName && cbNode->filterResourceType)
645 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
651 else if(cbNode && isMulticastPresence)
653 // Check if the same nonce for a given host
654 OCMulticastNode* mcNode = NULL;
655 mcNode = GetMCPresenceNode(response->fullUri);
657 if(response->maxAge == 0)
659 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
660 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
663 OCFree(cbNode->presence->timeOut);
664 OCFree(cbNode->presence);
665 cbNode->presence = NULL;
668 else if(mcNode != NULL)
670 if(mcNode->nonce == response->clientResponse->sequenceNumber)
672 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
673 result = OC_STACK_NO_MEMORY;
676 mcNode->nonce = response->clientResponse->sequenceNumber;
680 uint32_t uriLen = strlen((char*)response->fullUri);
681 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
684 memcpy(uri, response->fullUri, (uriLen + 1));
689 PCF("===============No Memory for URI to store in the presence node"));
690 result = OC_STACK_NO_MEMORY;
693 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri,
694 response->clientResponse->sequenceNumber);
695 if(result == OC_STACK_NO_MEMORY)
698 PCF("===============No Memory for Multicast Presence Node"));
699 result = OC_STACK_NO_MEMORY;
704 // Ensure that a filter is actually applied.
705 if(resourceTypeName && cbNode->filterResourceType)
707 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
714 else if(!cbNode && isPresenceNotification)
716 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
717 ------------ ignoring"));
719 #endif // WITH_PRESENCE
723 if(isObserveNotification)
725 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
726 //TODO: check the standard for methods to detect wrap around condition
727 if(cbNode->method == OC_REST_OBSERVE &&
728 (response->clientResponse->sequenceNumber <= cbNode->sequenceNumber ||
729 (response->clientResponse->sequenceNumber > cbNode->sequenceNumber &&
730 response->clientResponse->sequenceNumber ==
731 MAX_SEQUENCE_NUMBER)))
733 OC_LOG_V(DEBUG, TAG, "Observe notification came out of order. \
734 Ignoring Incoming:%d Against Current:%d.",
735 response->clientResponse->sequenceNumber, cbNode->sequenceNumber);
738 if(response->clientResponse->sequenceNumber > cbNode->sequenceNumber){
739 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;
743 response->clientResponse->resJSONPayload = bufRes;
745 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response->clientResponse);
747 if (cbResult == OC_STACK_DELETE_TRANSACTION ||
748 response->clientResponse->result == OC_STACK_COMM_ERROR ||
749 (response->clientResponse->result == OC_STACK_RESOURCE_DELETED &&
750 !isPresenceNotification && !isMulticastPresence))
752 FindAndDeleteClientCB(cbNode);
757 result = OC_STACK_ERROR;
762 OCFree(resourceTypeName);
767 int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
770 unsigned char *itr, *coap;
771 uint8_t dotCount = 0;
775 /* search for scheme */
777 if (!isdigit((unsigned char) *ipAddrStr))
779 coap = (unsigned char *) OC_COAP_SCHEME;
780 while (*coap && tolower(*itr) == *coap)
789 if (isdigit((unsigned char) *ipAddrStr))
792 ipAddr[index] += *ipAddrStr - '0';
794 else if ((unsigned char) *ipAddrStr == '.')
806 if(*ipAddrStr == ':')
810 if (isdigit((unsigned char) *ipAddrStr))
813 *port += *ipAddrStr - '0';
824 if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
835 //-----------------------------------------------------------------------------
836 // Private internal function prototypes
837 //-----------------------------------------------------------------------------
839 static OCDoHandle GenerateInvocationHandle();
840 static OCStackResult initResources();
841 static void insertResource(OCResource *resource);
842 static OCResource *findResource(OCResource *resource);
843 static void insertResourceType(OCResource *resource,
844 OCResourceType *resourceType);
845 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
847 static void insertResourceInterface(OCResource *resource,
848 OCResourceInterface *resourceInterface);
849 static OCResourceInterface *findResourceInterfaceAtIndex(
850 OCResourceHandle handle, uint8_t index);
851 static void deleteResourceType(OCResourceType *resourceType);
852 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
853 static void deleteResourceElements(OCResource *resource);
854 static int deleteResource(OCResource *resource);
855 static void deleteAllResources();
856 static void incrementSequenceNumber(OCResource * resPtr);
857 static OCStackResult verifyUriQueryLength(const char * inputUri,
859 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
860 OCStackResult getResourceType(const char * query, unsigned char** resourceType);
862 //-----------------------------------------------------------------------------
864 //-----------------------------------------------------------------------------
867 * Initialize the OC Stack. Must be called prior to starting the stack.
870 * IP Address of host device
872 * Port of host device
874 * Host device is client, server, or client-server
877 * OC_STACK_OK - no errors
878 * OC_STACK_ERROR - stack init error
880 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
882 OCStackResult result = OC_STACK_ERROR;
883 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
887 OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
891 //It is ok to select network to CA_WIFI for now
892 CAResult_t caResult = CASelectNetwork(CA_WIFI);
893 if(caResult == CA_STATUS_OK)
895 OC_LOG(INFO, TAG, PCF("CASelectNetwork to WIFI"));
896 caResult = CARegisterHandler(HandleCARequests, HandleCAResponses);
897 if(caResult == CA_STATUS_OK)
899 OC_LOG(INFO, TAG, PCF("CARegisterHandler..."));
900 stackState = OC_STACK_INITIALIZED;
901 result = OC_STACK_OK;
905 caResult = CAStartDiscoveryServer();
906 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
909 caResult = CAStartListeningServer();
910 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
912 case OC_CLIENT_SERVER:
913 caResult = CAStartListeningServer();
914 if(caResult == CA_STATUS_OK)
916 caResult = CAStartDiscoveryServer();
918 OC_LOG(INFO, TAG, PCF("Client-server mode"));
921 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
922 return OC_STACK_ERROR;
927 if (caResult == CA_STATUS_OK)
929 result = OC_STACK_OK;
933 result = OC_STACK_ERROR;
940 OC_LOG(INFO, TAG, PCF("Client mode"));
943 OC_LOG(INFO, TAG, PCF("Server mode"));
945 case OC_CLIENT_SERVER:
946 OC_LOG(INFO, TAG, PCF("Client-server mode"));
949 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
950 return OC_STACK_ERROR;
954 // Make call to OCCoAP layer
955 result = OCInitCoAP(ipAddr, (uint16_t) port, myStackMode);
959 defaultDeviceHandler = NULL;
962 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
963 #endif // WITH_PRESENCE
965 if (result == OC_STACK_OK)
967 stackState = OC_STACK_INITIALIZED;
969 // Initialize resource
970 if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
972 result = initResources();
974 if(result != OC_STACK_OK)
976 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
982 * Stop the OC stack. Use for a controlled shutdown.
984 * OC_STACK_OK - no errors
985 * OC_STACK_ERROR - stack not initialized
987 OCStackResult OCStop()
989 OCStackResult result = OC_STACK_ERROR;
991 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
993 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
995 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
998 else if (stackState != OC_STACK_INITIALIZED)
1000 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1001 return OC_STACK_ERROR;
1004 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1006 #ifdef WITH_PRESENCE
1007 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1008 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1009 presenceResource.presenceTTL = 0;
1010 #endif // WITH_PRESENCE
1012 // Free memory dynamically allocated for resources
1013 deleteAllResources();
1016 // Make call to OCCoAP layer
1017 if (OCStopCoAP() == OC_STACK_OK)
1019 // Remove all observers
1020 DeleteObserverList();
1021 // Remove all the client callbacks
1022 DeleteClientCBList();
1023 stackState = OC_STACK_UNINITIALIZED;
1024 result = OC_STACK_OK;
1026 stackState = OC_STACK_INITIALIZED;
1027 result = OC_STACK_ERROR;
1030 // Deinit security blob
1031 DeinitOCSecurityInfo();
1033 if (result != OC_STACK_OK) {
1034 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
1041 * Verify the lengths of the URI and the query separately
1043 * @param inputUri - Input URI and query.
1044 * @param uriLen - The length of the initial URI with query.
1046 * Note: The '?' that appears after the URI is not considered as
1047 * a part of the query.
1049 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1053 query = strchr (inputUri, '?');
1057 if((query - inputUri) > MAX_URI_LENGTH)
1059 return OC_STACK_INVALID_URI;
1062 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1064 return OC_STACK_INVALID_QUERY;
1067 else if(uriLen > MAX_URI_LENGTH)
1069 return OC_STACK_INVALID_URI;
1075 * Discover or Perform requests on a specified resource (specified by that Resource's respective URI).
1077 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of calling this API.
1078 * @param method - @ref OCMethod to perform on the resource
1079 * @param requiredUri - URI of the resource to interact with
1080 * @param referenceUri - URI of the reference resource
1081 * @param request - JSON encoded request
1082 * @param qos - quality of service
1083 * @param cbData - struct that contains asynchronous callback function that is invoked
1084 * by the stack when discovery or resource interaction is complete
1085 * @param options - The address of an array containing the vendor specific header
1086 * header options to be sent with the request
1087 * @param numOptions - Number of vendor specific header options to be included
1090 * OC_STACK_OK - no errors
1091 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
1092 * OC_STACK_INVALID_METHOD - invalid resource method
1093 * OC_STACK_INVALID_URI - invalid required or reference URI
1096 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1097 const char *referenceUri, const char *request,
1098 OCQualityOfService qos, OCCallbackData *cbData,
1099 OCHeaderOption * options, uint8_t numOptions)
1101 OCStackResult result = OC_STACK_ERROR;
1103 ClientCB *clientCB = NULL;
1104 unsigned char * requestUri = NULL;
1105 unsigned char * resourceType = NULL;
1106 unsigned char * query = NULL;
1107 char * newUri = (char *)requiredUri;
1108 (void) referenceUri;
1110 CARemoteEndpoint_t* endpoint = NULL;
1111 CAResult_t caResult;
1112 CAToken_t caToken = NULL;
1113 CAInfo_t requestData;
1114 CARequestInfo_t requestInfo;
1115 // To track if memory is allocated for additional header options
1116 uint8_t hdrOptionMemAlloc = 0;
1119 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1121 // Validate input parameters
1122 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1123 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1125 TODO ("Need to form the final query by concatenating require and reference URI's");
1126 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
1128 uint16_t uriLen = strlen(requiredUri);
1130 // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS
1136 case OC_REST_DELETE:
1137 case OC_REST_OBSERVE:
1138 case OC_REST_OBSERVE_ALL:
1139 case OC_REST_CANCEL_OBSERVE:
1141 #ifdef WITH_PRESENCE
1142 case OC_REST_PRESENCE:
1146 result = OC_STACK_INVALID_METHOD;
1150 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
1155 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
1157 result = OC_STACK_INVALID_PARAM;
1161 #ifdef WITH_PRESENCE
1162 if(method == OC_REST_PRESENCE)
1164 // Replacing method type with GET because "presence" is a stack layer only implementation.
1165 method = OC_REST_GET;
1166 result = getQueryFromUri(requiredUri, &query, &newUri);
1169 result = getResourceType((char *) query, &resourceType);
1172 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1176 OC_LOG(DEBUG, TAG, PCF("Resource type is NULL."));
1181 OC_LOG(DEBUG, TAG, PCF("Query string is NULL."));
1183 if(result != OC_STACK_OK)
1188 #endif // WITH_PRESENCE
1190 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
1193 memcpy(requestUri, newUri, (uriLen + 1));
1197 result = OC_STACK_NO_MEMORY;
1201 *handle = GenerateInvocationHandle();
1204 result = OC_STACK_NO_MEMORY;
1209 memset(&requestData, 0, sizeof(CAInfo_t));
1210 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1214 case OC_REST_OBSERVE:
1215 case OC_REST_OBSERVE_ALL:
1216 case OC_REST_CANCEL_OBSERVE:
1218 requestInfo.method = CA_GET;
1223 requestInfo.method = CA_PUT;
1228 requestInfo.method = CA_POST;
1231 case OC_REST_DELETE:
1233 requestInfo.method = CA_DELETE;
1236 #ifdef WITH_PRESENCE
1237 case OC_REST_PRESENCE:
1238 //TODO-CA: What should be the CA method?
1242 result = OC_STACK_INVALID_METHOD;
1246 // TODO-CA: Handle multi-cast scenario
1247 // Create remote end point
1248 caResult = CACreateRemoteEndpoint(newUri, CA_WIFI, &endpoint);
1249 // TODO-CA: Connectivity type should be passed to API
1250 endpoint->connectivityType = CA_WIFI;
1251 if (caResult != CA_STATUS_OK)
1253 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1258 caResult = CAGenerateToken(&caToken);
1260 if (caResult != CA_STATUS_OK)
1262 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1267 // TODO-CA: Map QoS to the right CA msg type
1268 requestData.type = CA_MSG_NONCONFIRM;
1269 requestData.token = caToken;
1270 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1272 result = CreateObserveHeaderOption (&(requestData.options), options,
1273 numOptions, OC_OBSERVE_REGISTER);
1274 if (result != OC_STACK_OK)
1278 hdrOptionMemAlloc = 1;
1279 requestData.numOptions = numOptions + 1;
1283 requestData.options = (CAHeaderOption_t*)options;
1284 requestData.numOptions = numOptions;
1286 requestData.payload = (char *)request;
1288 requestInfo.info = requestData;
1291 caResult = CASendRequest(endpoint, &requestInfo);
1292 if (caResult != CA_STATUS_OK)
1294 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1298 if((result = AddClientCB(&clientCB, cbData, &caToken, handle, method,
1299 requestUri, resourceType)) != OC_STACK_OK)
1301 result = OC_STACK_NO_MEMORY;
1307 // Generate token which will be used by OCStack to match responses received
1309 OCGenerateCoAPToken(&token);
1311 if((result = AddClientCB(&clientCB, cbData, &token, handle, method, requestUri, resourceType))
1314 result = OC_STACK_NO_MEMORY;
1318 // Make call to OCCoAP layer
1319 result = OCDoCoAPResource(method, qos, &token, newUri, request, options, numOptions);
1323 if(newUri != requiredUri)
1327 if (result != OC_STACK_OK)
1329 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1330 FindAndDeleteClientCB(clientCB);
1333 CADestroyRemoteEndpoint(endpoint);
1334 if (hdrOptionMemAlloc)
1336 OCFree(requestData.options);
1343 * Cancel a request associated with a specific @ref OCDoResource invocation.
1345 * @param handle - Used to identify a specific OCDoResource invocation.
1346 * @param qos - used to specify Quality of Service (read below for more info)
1347 * @param options- used to specify vendor specific header options when sending
1348 * explicit observe cancellation
1349 * @param numOptions- Number of header options to be included
1352 * OC_STACK_OK - No errors; Success
1353 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1355 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1359 * This ftn is implemented one of two ways in the case of observation:
1361 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1362 * Remove the callback associated on client side.
1363 * When the next notification comes in from server,
1364 * reply with RESET message to server.
1365 * Keep in mind that the server will react to RESET only
1366 * if the last notification was sent ans CON
1368 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1369 * and it is associated with an observe request
1370 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1371 * Send CON Observe request to server with
1372 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1373 * Remove the callback associated on client side.
1375 OCStackResult ret = OC_STACK_OK;
1377 CARemoteEndpoint_t* endpoint = NULL;
1378 CAResult_t caResult;
1379 CAInfo_t requestData;
1380 CARequestInfo_t requestInfo;
1381 // Track if memory is allocated for additional header options
1382 uint8_t hdrOptionMemAlloc = 0;
1386 return OC_STACK_INVALID_PARAM;
1389 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1391 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1394 switch (clientCB->method)
1396 case OC_REST_OBSERVE:
1397 case OC_REST_OBSERVE_ALL:
1399 caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri, CA_WIFI,
1401 endpoint->connectivityType = CA_WIFI;
1402 if (caResult != CA_STATUS_OK)
1404 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1405 return OC_STACK_ERROR;
1408 memset(&requestData, 0, sizeof(CAInfo_t));
1409 // TODO-CA: Map QoS to the right CA msg type
1410 requestData.type = CA_MSG_NONCONFIRM;
1411 requestData.token = clientCB->token;
1412 if (CreateObserveHeaderOption (&(requestData.options),
1413 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
1415 return OC_STACK_ERROR;
1417 hdrOptionMemAlloc = 1;
1418 requestData.numOptions = numOptions + 1;
1419 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1420 requestInfo.method = CA_GET;
1421 requestInfo.info = requestData;
1423 caResult = CASendRequest(endpoint, &requestInfo);
1424 if (caResult != CA_STATUS_OK)
1426 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1428 if(caResult == CA_STATUS_OK)
1433 if(qos == OC_HIGH_QOS)
1435 ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
1436 &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
1441 FindAndDeleteClientCB(clientCB);
1445 #ifdef WITH_PRESENCE
1446 case OC_REST_PRESENCE:
1447 FindAndDeleteClientCB(clientCB);
1451 return OC_STACK_INVALID_METHOD;
1455 CADestroyRemoteEndpoint(endpoint);
1456 if (hdrOptionMemAlloc)
1458 OCFree(requestData.options);
1464 #ifdef WITH_PRESENCE
1465 OCStackResult OCProcessPresence()
1467 OCStackResult result = OC_STACK_OK;
1468 uint8_t ipAddr[4] = { 0 };
1471 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1472 ClientCB* cbNode = NULL;
1474 OCClientResponse clientResponse;
1475 OCResponse * response = NULL;
1477 LL_FOREACH(cbList, cbNode) {
1478 if(OC_REST_PRESENCE == cbNode->method)
1480 if(cbNode->presence)
1482 uint32_t now = GetTime(0);
1483 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
1484 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1487 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1492 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1493 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1494 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1497 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1499 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1500 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1502 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1504 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
1505 (OCDevAddr *) &dst, 0, NULL);
1506 if(result != OC_STACK_OK)
1510 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1511 &cbNode->token, &clientResponse, NULL);
1512 if(result != OC_STACK_OK)
1517 // Increment the TTLLevel (going to a next state), so we don't keep
1518 // sending presence notification to client.
1519 cbNode->presence->TTLlevel++;
1520 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1521 cbNode->presence->TTLlevel);
1525 result = OC_STACK_INVALID_IP;
1528 HandleStackResponses(response);
1530 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1532 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
1534 OCGenerateCoAPToken(&token);
1535 result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
1536 &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
1537 if(result != OC_STACK_OK)
1541 cbNode->presence->TTLlevel++;
1542 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
1548 if (result != OC_STACK_OK)
1550 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
1557 * Called in main loop of OC client or server. Allows low-level processing of
1561 * OC_STACK_OK - no errors
1562 * OC_STACK_ERROR - stack process error
1564 OCStackResult OCProcess() {
1566 OC_LOG(INFO, TAG, PCF("Entering OCProcess"));
1567 #ifdef WITH_PRESENCE
1568 OCProcessPresence();
1571 CAHandleRequestResponse();
1579 #ifdef WITH_PRESENCE
1581 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
1582 * presence notifications to clients via multicast. Once this API has been called with a success,
1583 * clients may query for this server's presence and this server's stack will respond via multicast.
1585 * Server can call this function when it comes online for the first time, or when it comes back
1586 * online from offline mode, or when it re enters network.
1588 * @param ttl - Time To Live in seconds
1589 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
1592 * OC_STACK_OK - No errors; Success
1594 OCStackResult OCStartPresence(const uint32_t ttl)
1596 OCChangeResourceProperty(
1597 &(((OCResource *)presenceResource.handle)->resourceProperties),
1602 presenceResource.presenceTTL = ttl;
1605 if(OC_PRESENCE_UNINITIALIZED == presenceState)
1607 OCDevAddr multiCastAddr;
1610 presenceState = OC_PRESENCE_INITIALIZED;
1611 OCGenerateCoAPToken(&token);
1612 OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
1613 //add the presence observer
1614 AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
1615 (OCResource *)presenceResource.handle, OC_LOW_QOS);
1618 // Each time OCStartPresence is called
1619 // a different random 32-bit integer number is used
1620 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1622 return SendPresenceNotification(NULL);
1626 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
1627 * presence notifications to clients via multicast. Once this API has been called with a success,
1628 * this server's stack will not respond to clients querying for this server's presence.
1630 * Server can call this function when it is terminating, going offline, or when going
1631 * away from network.
1634 * OC_STACK_OK - No errors; Success
1636 OCStackResult OCStopPresence()
1638 OCStackResult result = OC_STACK_ERROR;
1639 //make resource inactive
1640 result = OCChangeResourceProperty(
1641 &(((OCResource *) presenceResource.handle)->resourceProperties),
1643 result = SendPresenceNotification(NULL);
1650 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
1652 defaultDeviceHandler = entityHandler;
1657 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
1659 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
1661 if(myStackMode == OC_CLIENT)
1663 return OC_STACK_ERROR;
1666 return SaveDeviceInfo(deviceInfo);
1672 * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource
1673 * @param resourceTypeName - name of resource type. Example: "core.led"
1674 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1675 * @param uri - URI of the resource. Example: "/a/led"
1676 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1677 * NULL for default entity handler
1678 * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE
1681 * OC_STACK_OK - no errors
1682 * OC_STACK_ERROR - stack process error
1684 OCStackResult OCCreateResource(OCResourceHandle *handle,
1685 const char *resourceTypeName,
1686 const char *resourceInterfaceName,
1687 const char *uri, OCEntityHandler entityHandler,
1688 uint8_t resourceProperties) {
1690 OCResource *pointer = NULL;
1693 OCStackResult result = OC_STACK_ERROR;
1695 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
1697 if(myStackMode == OC_CLIENT)
1701 // Validate parameters
1702 if(!uri || (strlen(uri) == 0))
1704 OC_LOG(ERROR, TAG, PCF("URI is invalid"));
1705 return OC_STACK_INVALID_URI;
1707 // Is it presented during resource discovery?
1708 if (!handle || !resourceTypeName) {
1709 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
1710 return OC_STACK_INVALID_PARAM;
1713 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
1714 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
1717 // Make sure resourceProperties bitmask has allowed properties specified
1718 if (resourceProperties
1719 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
1720 OC_LOG(ERROR, TAG, PCF("Invalid property"));
1721 return OC_STACK_INVALID_PARAM;
1724 // If the headResource is NULL, then no resources have been created...
1725 pointer = headResource;
1727 // At least one resources is in the resource list, so we need to search for
1728 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
1730 if (strcmp(uri, pointer->uri) == 0) {
1731 OC_LOG(ERROR, TAG, PCF("URI already in use"));
1732 return OC_STACK_INVALID_PARAM;
1734 pointer = pointer->next;
1737 // Create the pointer and insert it into the resource list
1738 pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
1742 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
1744 insertResource(pointer);
1747 size = strlen(uri) + 1;
1748 str = (char *) OCMalloc(size);
1752 strncpy(str, uri, size);
1755 // Set properties. Set OC_ACTIVE
1756 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
1759 // Add the resourcetype to the resource
1760 result = BindResourceTypeToResource(pointer, resourceTypeName);
1761 if (result != OC_STACK_OK) {
1762 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
1766 // Add the resourceinterface to the resource
1767 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
1768 if (result != OC_STACK_OK) {
1769 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
1773 // If an entity handler has been passed, attach it to the newly created
1774 // resource. Otherwise, set the default entity handler.
1777 pointer->entityHandler = entityHandler;
1781 pointer->entityHandler = defaultResourceEHandler;
1785 result = OC_STACK_OK;
1787 #ifdef WITH_PRESENCE
1788 if(presenceResource.handle)
1790 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1791 SendPresenceNotification(pointer->rsrcType);
1795 if (result != OC_STACK_OK)
1797 // Deep delete of resource and other dynamic elements that it contains
1798 deleteResource(pointer);
1807 * Create a resource. with host ip address for remote resource
1809 * @param handle - pointer to handle to newly created resource. Set by ocstack.
1810 * Used to refer to resource
1811 * @param resourceTypeName - name of resource type. Example: "core.led"
1812 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1813 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
1814 * @param uri - URI of the resource. Example: "/a/led"
1815 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1816 * NULL for default entity handler
1817 * @param resourceProperties - properties supported by resource.
1818 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
1821 * OC_STACK_OK - no errors
1822 * OC_STACK_ERROR - stack process error
1825 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
1826 const char *resourceTypeName,
1827 const char *resourceInterfaceName,
1830 OCEntityHandler entityHandler,
1831 uint8_t resourceProperties)
1835 OCStackResult result = OC_STACK_ERROR;
1837 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
1838 uri, entityHandler, resourceProperties);
1840 if (result != OC_STACK_ERROR)
1843 size = strlen(host) + 1;
1844 str = (char *) OCMalloc(size);
1847 return OC_STACK_ERROR;
1849 strncpy(str, host, size);
1850 ((OCResource *) *handle)->host = str;
1857 * Add a resource to a collection resource.
1859 * @param collectionHandle - handle to the collection resource
1860 * @param resourceHandle - handle to resource to be added to the collection resource
1863 * OC_STACK_OK - no errors
1864 * OC_STACK_ERROR - stack process error
1865 * OC_STACK_INVALID_PARAM - invalid collectionhandle
1867 OCStackResult OCBindResource(
1868 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1869 OCResource *resource;
1872 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
1874 // Validate parameters
1875 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1876 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1877 // Container cannot contain itself
1878 if (collectionHandle == resourceHandle) {
1879 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
1880 return OC_STACK_INVALID_PARAM;
1883 // Use the handle to find the resource in the resource linked list
1884 resource = findResource((OCResource *) collectionHandle);
1886 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1887 return OC_STACK_INVALID_PARAM;
1890 // Look for an open slot to add add the child resource.
1891 // If found, add it and return success
1892 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1893 if (!resource->rsrcResources[i]) {
1894 resource->rsrcResources[i] = (OCResource *) resourceHandle;
1895 OC_LOG(INFO, TAG, PCF("resource bound"));
1900 #ifdef WITH_PRESENCE
1901 if(presenceResource.handle)
1903 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1904 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1908 // Unable to add resourceHandle, so return error
1909 return OC_STACK_ERROR;
1913 * Remove a resource from a collection resource.
1915 * @param collectionHandle - handle to the collection resource
1916 * @param resourceHandle - handle to resource to be added to the collection resource
1919 * OC_STACK_OK - no errors
1920 * OC_STACK_ERROR - stack process error
1921 * OC_STACK_INVALID_PARAM - invalid collectionHandle
1923 OCStackResult OCUnBindResource(
1924 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1925 OCResource *resource;
1928 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
1930 // Validate parameters
1931 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1932 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1933 // Container cannot contain itself
1934 if (collectionHandle == resourceHandle) {
1935 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
1936 return OC_STACK_INVALID_PARAM;
1939 // Use the handle to find the resource in the resource linked list
1940 resource = findResource((OCResource *) collectionHandle);
1942 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1943 return OC_STACK_INVALID_PARAM;
1946 // Look for an open slot to add add the child resource.
1947 // If found, add it and return success
1948 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1949 if (resourceHandle == resource->rsrcResources[i]) {
1950 resource->rsrcResources[i] = (OCResource *) NULL;
1951 OC_LOG(INFO, TAG, PCF("resource unbound"));
1956 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
1958 #ifdef WITH_PRESENCE
1959 if(presenceResource.handle)
1961 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1962 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1966 // Unable to add resourceHandle, so return error
1967 return OC_STACK_ERROR;
1970 OCStackResult BindResourceTypeToResource(OCResource* resource,
1971 const char *resourceTypeName)
1973 OCResourceType *pointer = NULL;
1976 OCStackResult result = OC_STACK_ERROR;
1978 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
1980 // Validate parameters
1981 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
1982 // TODO: Does resource attribute resentation really have to be maintained in stack?
1983 // Is it presented during resource discovery?
1985 TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
1987 // Create the resourcetype and insert it into the resource list
1988 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
1993 // Set the resourceTypeName
1994 size = strlen(resourceTypeName) + 1;
1995 str = (char *) OCMalloc(size);
1999 strncpy(str, resourceTypeName, size);
2000 pointer->resourcetypename = str;
2002 insertResourceType(resource, pointer);
2003 result = OC_STACK_OK;
2005 exit: if (result != OC_STACK_OK) {
2013 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2014 const char *resourceInterfaceName)
2016 OCResourceInterface *pointer = NULL;
2019 OCStackResult result = OC_STACK_ERROR;
2021 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
2023 // Validate parameters
2024 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2026 TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
2028 // Create the resourceinterface and insert it into the resource list
2029 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
2034 // Set the resourceinterface name
2035 size = strlen(resourceInterfaceName) + 1;
2036 str = (char *) OCMalloc(size);
2040 strncpy(str, resourceInterfaceName, size);
2041 pointer->name = str;
2043 // Bind the resourceinterface to the resource
2044 insertResourceInterface(resource, pointer);
2046 result = OC_STACK_OK;
2048 exit: if (result != OC_STACK_OK) {
2057 * Bind a resourcetype to a resource.
2059 * @param handle - handle to the resource
2060 * @param resourceTypeName - name of resource type. Example: "core.led"
2063 * OC_STACK_OK - no errors
2064 * OC_STACK_ERROR - stack process error
2066 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2067 const char *resourceTypeName) {
2069 OCStackResult result = OC_STACK_ERROR;
2070 OCResource *resource;
2072 // Make sure resource exists
2073 resource = findResource((OCResource *) handle);
2075 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2076 return OC_STACK_ERROR;
2079 // call internal function
2080 result = BindResourceTypeToResource(resource, resourceTypeName);
2082 #ifdef WITH_PRESENCE
2083 if(presenceResource.handle)
2085 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2086 SendPresenceNotification(resource->rsrcType);
2094 * Bind a resourceinterface to a resource.
2096 * @param handle - handle to the resource
2097 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
2100 * OC_STACK_OK - no errors
2101 * OC_STACK_ERROR - stack process error
2104 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2105 const char *resourceInterfaceName) {
2107 OCStackResult result = OC_STACK_ERROR;
2108 OCResource *resource;
2110 // Make sure resource exists
2111 resource = findResource((OCResource *) handle);
2113 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2114 return OC_STACK_ERROR;
2117 // call internal function
2118 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2120 #ifdef WITH_PRESENCE
2121 if(presenceResource.handle)
2123 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2124 SendPresenceNotification(resource->rsrcType);
2132 * Get the number of resources that have been created in the stack.
2134 * @param numResources - pointer to count variable
2137 * OC_STACK_OK - no errors
2138 * OC_STACK_ERROR - stack process error
2141 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
2142 OCResource *pointer = headResource;
2144 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2145 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2148 *numResources = *numResources + 1;
2149 pointer = pointer->next;
2155 * Get a resource handle by index.
2157 * @param index - index of resource, 0 to Count - 1
2160 * Resource handle - if found
2161 * NULL - if not found
2163 OCResourceHandle OCGetResourceHandle(uint8_t index) {
2164 OCResource *pointer = headResource;
2167 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2169 // Iterate through the list
2170 while ((i < index) && pointer) {
2172 pointer = pointer->next;
2174 return (OCResourceHandle) pointer;
2178 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
2181 * @param handle - handle of resource to be deleted
2184 * OC_STACK_OK - no errors
2185 * OC_STACK_ERROR - stack process error
2186 * OC_STACK_NO_RESOURCE - resource not found
2187 * OC_STACK_INVALID_PARAM - invalid param
2189 OCStackResult OCDeleteResource(OCResourceHandle handle) {
2190 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2193 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2194 return OC_STACK_INVALID_PARAM;
2197 OCResource *resource = findResource((OCResource *) handle);
2198 if (resource == NULL) {
2199 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2200 return OC_STACK_NO_RESOURCE;
2203 if (deleteResource((OCResource *) handle) == 0) {
2204 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2205 return OC_STACK_ERROR;
2212 * Get the URI of the resource specified by handle.
2214 * @param handle - handle of resource
2216 * URI string - if resource found
2217 * NULL - resource not found
2219 const char *OCGetResourceUri(OCResourceHandle handle) {
2220 OCResource *resource;
2221 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2223 resource = findResource((OCResource *) handle);
2225 return resource->uri;
2227 return (const char *) NULL;
2231 * Get the properties of the resource specified by handle.
2232 * NOTE: that after a resource is created, the OC_ACTIVE property is set
2233 * for the resource by the stack.
2235 * @param handle - handle of resource
2237 * property bitmap - if resource found
2238 * NULL - resource not found
2240 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
2241 OCResource *resource;
2242 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2244 resource = findResource((OCResource *) handle);
2246 return resource->resourceProperties;
2252 * Get the number of resource types of the resource.
2254 * @param handle - handle of resource
2255 * @param numResourceTypes - pointer to count variable
2258 * OC_STACK_OK - no errors
2259 * OC_STACK_ERROR - stack process error
2261 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2262 uint8_t *numResourceTypes) {
2263 OCResource *resource;
2264 OCResourceType *pointer;
2266 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2267 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2268 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2270 *numResourceTypes = 0;
2272 resource = findResource((OCResource *) handle);
2274 pointer = resource->rsrcType;
2276 *numResourceTypes = *numResourceTypes + 1;
2277 pointer = pointer->next;
2284 * Get name of resource type of the resource.
2286 * @param handle - handle of resource
2287 * @param index - index of resource, 0 to Count - 1
2290 * resource type name - if resource found
2291 * NULL - resource not found
2293 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
2294 OCResourceType *resourceType;
2296 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2298 resourceType = findResourceTypeAtIndex(handle, index);
2300 return resourceType->resourcetypename;
2302 return (const char *) NULL;
2308 * Get the number of resource interfaces of the resource.
2310 * @param handle - handle of resource
2311 * @param numResources - pointer to count variable
2314 * OC_STACK_OK - no errors
2315 * OC_STACK_ERROR - stack process error
2317 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2318 uint8_t *numResourceInterfaces) {
2319 OCResourceInterface *pointer;
2320 OCResource *resource;
2322 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2324 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2325 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2327 *numResourceInterfaces = 0;
2328 resource = findResource((OCResource *) handle);
2330 pointer = resource->rsrcInterface;
2332 *numResourceInterfaces = *numResourceInterfaces + 1;
2333 pointer = pointer->next;
2340 * Get name of resource interface of the resource.
2342 * @param handle - handle of resource
2343 * @param index - index of resource, 0 to Count - 1
2346 * resource interface name - if resource found
2347 * NULL - resource not found
2349 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
2350 OCResourceInterface *resourceInterface;
2352 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2354 resourceInterface = findResourceInterfaceAtIndex(handle, index);
2355 if (resourceInterface) {
2356 return resourceInterface->name;
2358 return (const char *) NULL;
2362 * Get resource handle from the collection resource by index.
2364 * @param collectionHandle - handle of collection resource
2365 * @param index - index of contained resource, 0 to Count - 1
2368 * handle to resource - if resource found
2369 * NULL - resource not found
2371 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2373 OCResource *resource;
2375 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2377 if (index >= MAX_CONTAINED_RESOURCES) {
2381 resource = findResource((OCResource *) collectionHandle);
2386 return resource->rsrcResources[index];
2390 * Bind an entity handler to the resource.
2392 * @param handle - handle to the resource that the contained resource is to be bound
2393 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2395 * OC_STACK_OK - no errors
2396 * OC_STACK_ERROR - stack process error
2398 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2399 OCEntityHandler entityHandler) {
2400 OCResource *resource;
2402 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2404 // Validate parameters
2405 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2406 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2408 // Use the handle to find the resource in the resource linked list
2409 resource = findResource((OCResource *)handle);
2411 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2412 return OC_STACK_ERROR;
2416 resource->entityHandler = entityHandler;
2418 #ifdef WITH_PRESENCE
2419 if(presenceResource.handle)
2421 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2422 SendPresenceNotification(resource->rsrcType);
2430 * Get the entity handler for a resource.
2432 * @param handle - handle of resource
2435 * entity handler - if resource found
2436 * NULL - resource not found
2438 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
2439 OCResource *resource;
2441 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2443 // Use the handle to find the resource in the resource linked list
2444 resource = findResource((OCResource *)handle);
2446 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2451 return resource->entityHandler;
2454 void incrementSequenceNumber(OCResource * resPtr)
2456 // Increment the sequence number
2457 resPtr->sequenceNum += 1;
2458 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2460 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2466 * Notify Presence subscribers that a resource has been modified
2468 * @param resourceType - Handle to the resourceType linked list of resource
2469 * that was modified.
2470 * @param qos - Quality Of Service
2473 #ifdef WITH_PRESENCE
2474 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
2476 OCResource *resPtr = NULL;
2477 OCStackResult result;
2478 OCMethod method = OC_REST_PRESENCE;
2479 uint32_t maxAge = 0;
2480 resPtr = findResource((OCResource *) presenceResource.handle);
2483 return OC_STACK_NO_RESOURCE;
2485 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
2487 maxAge = presenceResource.presenceTTL;
2494 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
2497 #endif // WITH_PRESENCE
2499 * Notify observers that an observed value has changed.
2501 * @param handle - handle of resource
2504 * OC_STACK_OK - no errors
2505 * OC_STACK_NO_RESOURCE - invalid resource handle
2506 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
2508 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
2510 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2512 OCResource *resPtr = NULL;
2513 OCStackResult result;
2514 OCMethod method = OC_REST_NOMETHOD;
2515 uint32_t maxAge = 0;
2517 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2518 #ifdef WITH_PRESENCE
2519 if(handle == presenceResource.handle)
2523 #endif // WITH_PRESENCE
2524 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2526 // Verify that the resource exists
2527 resPtr = findResource ((OCResource *) handle);
2530 return OC_STACK_NO_RESOURCE;
2534 //only increment in the case of regular observing (not presence)
2535 incrementSequenceNumber(resPtr);
2536 method = OC_REST_OBSERVE;
2537 maxAge = MAX_OBSERVE_AGE;
2538 #ifdef WITH_PRESENCE
2539 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
2541 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
2548 OCNotifyListOfObservers (OCResourceHandle handle,
2549 OCObservationId *obsIdList,
2550 uint8_t numberOfIds,
2551 unsigned char *notificationJSONPayload,
2552 OCQualityOfService qos)
2554 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
2556 OCResource *resPtr = NULL;
2557 //TODO: we should allow the server to define this
2558 uint32_t maxAge = MAX_OBSERVE_AGE;
2560 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2561 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
2562 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
2564 // Verify that the resource exists
2565 resPtr = findResource ((OCResource *) handle);
2566 if (NULL == resPtr || myStackMode == OC_CLIENT)
2568 return OC_STACK_NO_RESOURCE;
2572 incrementSequenceNumber(resPtr);
2574 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
2575 notificationJSONPayload, maxAge, qos));
2579 * Send a response to a request.
2580 * The response can be a regular, slow, or block (i.e. a response that
2581 * is too large to be sent in a single PDU and must span multiple transmissions)
2583 * @param response - pointer to structure that contains response parameters
2586 * OC_STACK_OK - No errors; Success
2587 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
2588 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
2589 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
2590 * persistent response buffer is necessary
2592 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
2594 OCStackResult result = OC_STACK_ERROR;
2595 OCServerRequest *serverRequest = NULL;
2597 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
2599 // Validate input parameters
2600 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
2601 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
2603 // TODO: Placeholder for creating a response entry when implementing
2604 // block transfer feature
2606 // If a response payload is present, check if block transfer is required
2607 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
2608 (const char *)ehResponse->payload, ehResponse->payloadSize))
2610 OC_LOG(INFO, TAG, PCF("Block transfer required"));
2612 // Persistent response buffer is needed for block transfer
2613 if (!ehResponse->persistentBufferFlag)
2615 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
2616 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
2618 // TODO: Placeholder for block transfer handling
2619 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
2620 // when implementing the block transfer feature
2626 // Get pointer to request info
2627 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
2630 result = serverRequest->ehResponseHandler(ehResponse);
2637 * Cancel a response. Applies to a block response
2639 * @param responseHandle - response handle set by stack in OCServerResponse after
2640 * OCDoResponse is called
2643 * OC_STACK_OK - No errors; Success
2644 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
2646 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
2648 OCStackResult result = OC_STACK_NOTIMPL;
2650 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
2652 // TODO: validate response handle
2657 //-----------------------------------------------------------------------------
2658 // Private internal function definitions
2659 //-----------------------------------------------------------------------------
2661 * Generate handle of OCDoResource invocation for callback management.
2663 static OCDoHandle GenerateInvocationHandle()
2665 OCDoHandle handle = NULL;
2666 // Generate token here, it will be deleted when the transaction is deleted
2667 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2670 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2675 #ifdef WITH_PRESENCE
2676 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
2677 OCResourceProperty resourceProperties, uint8_t enable)
2679 if (resourceProperties
2680 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
2681 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2682 return OC_STACK_INVALID_PARAM;
2686 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
2690 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
2697 * Initialize resource data structures, variables, etc.
2699 OCStackResult initResources() {
2700 OCStackResult result = OC_STACK_OK;
2701 // Init application resource vars
2702 headResource = NULL;
2703 // Init Virtual Resources
2704 #ifdef WITH_PRESENCE
2705 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
2706 //presenceResource.token = OCGenerateCoAPToken();
2707 result = OCCreateResource(&presenceResource.handle,
2708 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
2713 //make resource inactive
2714 result = OCChangeResourceProperty(
2715 &(((OCResource *) presenceResource.handle)->resourceProperties),
2722 * Add a resource to the end of the linked list of resources.
2724 * @param resource - resource to be added
2726 void insertResource(OCResource *resource) {
2727 OCResource *pointer;
2729 if (!headResource) {
2730 headResource = resource;
2732 pointer = headResource;
2734 while (pointer->next) {
2735 pointer = pointer->next;
2737 pointer->next = resource;
2739 resource->next = NULL;
2743 * Find a resource in the linked list of resources.
2745 * @param resource - resource to be found
2747 * NULL - resource not found
2748 * pointer to resource - pointer to resource that was found in the linked list
2750 OCResource *findResource(OCResource *resource) {
2751 OCResource *pointer = headResource;
2754 if (pointer == resource) {
2757 pointer = pointer->next;
2762 void deleteAllResources()
2764 OCResource *pointer = headResource;
2769 temp = pointer->next;
2770 #ifdef WITH_PRESENCE
2771 if(pointer != (OCResource *) presenceResource.handle)
2773 #endif // WITH_PRESENCE
2774 deleteResource(pointer);
2775 #ifdef WITH_PRESENCE
2777 #endif // WITH_PRESENCE
2781 #ifdef WITH_PRESENCE
2782 // Ensure that the last resource to be deleted is the presence resource. This allows for all
2783 // presence notification attributed to their deletion to be processed.
2784 deleteResource((OCResource *) presenceResource.handle);
2785 #endif // WITH_PRESENCE
2789 * Delete the resource from the linked list.
2791 * @param resource - resource to be deleted
2796 int deleteResource(OCResource *resource) {
2797 OCResource *prev = NULL;
2800 temp = headResource;
2802 if (temp == resource) {
2803 // Invalidate all Resource Properties.
2804 resource->resourceProperties = (OCResourceProperty) 0;
2805 #ifdef WITH_PRESENCE
2806 if(resource != (OCResource *) presenceResource.handle)
2808 #endif // WITH_PRESENCE
2809 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
2810 #ifdef WITH_PRESENCE
2813 if(presenceResource.handle)
2815 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2816 if(resource != (OCResource *) presenceResource.handle)
2818 SendPresenceNotification(resource->rsrcType);
2822 SendPresenceNotification(NULL);
2827 if (temp == headResource) {
2828 headResource = temp->next;
2830 prev->next = temp->next;
2833 deleteResourceElements(temp);
2846 * Delete all of the dynamically allocated elements that were created for the resource.
2848 * @param resource - specified resource
2850 void deleteResourceElements(OCResource *resource) {
2856 OCFree(resource->uri);
2858 // Delete resourcetype linked list
2859 deleteResourceType(resource->rsrcType);
2861 // Delete resourceinterface linked list
2862 deleteResourceInterface(resource->rsrcInterface);
2866 * Delete all of the dynamically allocated elements that were created for the resource type.
2868 * @param resourceType - specified resource type
2870 void deleteResourceType(OCResourceType *resourceType) {
2871 OCResourceType *pointer = resourceType;
2872 OCResourceType *next;
2875 next = pointer->next;
2876 OCFree(pointer->resourcetypename);
2883 * Delete all of the dynamically allocated elements that were created for the resource interface.
2885 * @param resourceInterface - specified resource interface
2887 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
2888 OCResourceInterface *pointer = resourceInterface;
2889 OCResourceInterface *next;
2892 next = pointer->next;
2893 OCFree(pointer->name);
2900 * Insert a resource type into a resource's resource type linked list.
2902 * @param resource - resource where resource type is to be inserted
2903 * @param resourceType - resource type to be inserted
2905 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
2906 OCResourceType *pointer;
2908 if (resource && !resource->rsrcType) {
2909 resource->rsrcType = resourceType;
2913 pointer = resource->rsrcType;
2917 pointer = resourceType;
2919 while (pointer->next) {
2920 pointer = pointer->next;
2922 pointer->next = resourceType;
2924 resourceType->next = NULL;
2928 * Get a resource type at the specified index within a resource.
2930 * @param handle - handle of resource
2931 * @param index - index of resource type
2934 * resourcetype - if found
2937 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
2938 OCResource *resource;
2939 OCResourceType *pointer;
2942 // Find the specified resource
2943 resource = findResource((OCResource *) handle);
2948 // Make sure a resource has a resourcetype
2949 if (!resource->rsrcType) {
2953 // Iterate through the list
2954 pointer = resource->rsrcType;
2956 while ((i < index) && pointer) {
2958 pointer = pointer->next;
2964 * Finds a resource type in an OCResourceType link-list.
2966 * @param resourceTypeList - the link-list to be searched through
2967 * @param resourceTypeName - the key to search for
2970 * resourceType that matches the key (ie. resourceTypeName)
2971 * NULL - either an invalid parameter or this function was unable to find the key.
2973 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
2975 if(resourceTypeList && resourceTypeName)
2977 OCResourceType * rtPointer = resourceTypeList;
2978 while(resourceTypeName && rtPointer)
2980 if(rtPointer->resourcetypename &&
2981 strcmp(resourceTypeName, (const char *)
2982 (rtPointer->resourcetypename)) == 0)
2986 rtPointer = rtPointer->next;
2993 * Insert a resource interface into a resource's resource interface linked list.
2995 * @param resource - resource where resource interface is to be inserted
2996 * @param resourceInterface - resource interface to be inserted
2998 void insertResourceInterface(OCResource *resource,
2999 OCResourceInterface *resourceInterface) {
3000 OCResourceInterface *pointer;
3002 if (!resource->rsrcInterface) {
3003 resource->rsrcInterface = resourceInterface;
3005 pointer = resource->rsrcInterface;
3006 while (pointer->next) {
3007 pointer = pointer->next;
3009 pointer->next = resourceInterface;
3011 resourceInterface->next = NULL;
3015 * Get a resource interface at the specified index within a resource.
3017 * @param handle - handle of resource
3018 * @param index - index of resource interface
3021 * resourceinterface - if found
3024 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3026 OCResource *resource;
3027 OCResourceInterface *pointer;
3030 // Find the specified resource
3031 resource = findResource((OCResource *) handle);
3036 // Make sure a resource has a resourceinterface
3037 if (!resource->rsrcInterface) {
3041 // Iterate through the list
3042 pointer = resource->rsrcInterface;
3044 while ((i < index) && pointer) {
3046 pointer = pointer->next;
3052 * Determine if a request/response must be sent in a block transfer because it is too large to be
3053 * sent in a single PDU. This function can be used for either a request or a response
3055 * @param request - NULL or pointer to request
3056 * @param response - NULL or pointer to response
3057 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
3058 * the length of the request/response
3061 * 0 - packet transfer NOT required (i.e. normal request/response)
3062 * 1 - packet transfer required (i.e. block transfer needed)
3064 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
3068 // Determine if we are checking a request or a response
3071 // If size is greater than 0, use it for the request size value, otherwise
3072 // assume request is null terminated and use strlen for size value
3073 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
3080 // If size is greater than 0, use it for the response size value, otherwise
3081 // assume response is null terminated and use strlen for size value
3082 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3091 * Retrieves a resource type based upon a query ontains only just one
3092 * resource attribute (and that has to be of type "rt").
3094 * @remark This API malloc's memory for the resource type. Do not malloc resourceType
3095 * before passing in.
3097 * @param query - The quert part of the URI
3098 * @param resourceType - The resource type to be populated; pass by reference.
3101 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
3102 * OC_STACK_OK - Success
3104 OCStackResult getResourceType(const char * query, unsigned char** resourceType)
3108 return OC_STACK_INVALID_PARAM;
3111 OCStackResult result = OC_STACK_ERROR;
3113 if(strncmp(query, "rt=", 3) == 0)
3115 *resourceType = (unsigned char *) OCMalloc(strlen(query)-3);
3118 result = OC_STACK_NO_MEMORY;
3121 strcpy((char *)*resourceType, ((const char *)&query[3]));
3122 result = OC_STACK_OK;
3128 OCStackResult getQueryFromUri(const char * uri, unsigned char** query, char ** newURI)
3132 return OC_STACK_INVALID_URI;
3134 if(!query || !newURI)
3136 return OC_STACK_INVALID_PARAM;
3138 char * leftToken = NULL;
3139 char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3144 strcpy(tempURI, uri);
3146 leftToken = strtok_r((char *)tempURI, "?", &strTokPtr);
3148 //TODO-CA: This could be simplified. Clean up required.
3149 while(leftToken != NULL)
3151 if(strncmp(leftToken, "rt=", 3) == 0 || strncmp(leftToken, "if=", 3) == 0)
3153 *query = (unsigned char *) OCMalloc(strlen(leftToken));
3158 strcpy((char *)*query, ((const char *)&leftToken[0]));
3161 leftToken = strtok_r(NULL, "?", &strTokPtr);
3169 return OC_STACK_NO_MEMORY;
3172 const ServerID OCGetServerInstanceID(void)
3174 static bool generated = false;
3175 static ServerID sid;
3182 sid = OCGetRandom();
3187 const char* OCGetServerInstanceIDString(void)
3189 // max printed length of a base 10
3190 // uint32 is 10 characters, so 11 includes null.
3191 // This will change as the representation gets switched
3193 static char buffer[11];
3194 int n = sprintf(buffer, "%u", OCGetServerInstanceID());