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 void HandlePresenceResponse(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
243 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
244 ClientCB * cbNode = NULL;
245 char *resourceTypeName = NULL;
247 char * bufRes = responseInfo->info.payload;
248 OCClientResponse *response = (OCClientResponse *) OCMalloc(sizeof(OCClientResponse));
255 tok = strtok(bufRes, "[:]}");
256 bufRes[strlen(bufRes)] = ':';
257 tok = strtok(NULL, "[:]}");
258 bufRes[strlen((char *)bufRes)] = ':';
259 response->sequenceNumber = (uint32_t )atoi(tok);
260 tok = strtok(NULL, "[:]}");
261 tok = strtok(NULL, "[:]}");
264 resourceTypeName = (char *)OCMalloc(strlen(tok));
265 if(!resourceTypeName)
269 bufRes[strlen((char *)bufRes)] = ':';
270 strcpy(resourceTypeName, tok);
271 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
274 bufRes[strlen((char *)bufRes)] = ']';
276 response->resJSONPayload = responseInfo->info.payload;
277 response->result = OC_STACK_OK;
279 char *fullUri = (char *) OCMalloc(MAX_URI_LENGTH );
280 char *ipAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
282 strncpy(ipAddress, endPoint->addressInfo.IP.ipAddress, strlen(endPoint->addressInfo.IP.ipAddress));
283 ipAddress[strlen(endPoint->addressInfo.IP.ipAddress)] = '\0';
285 snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", ipAddress, endPoint->addressInfo.IP.port,
288 cbNode = GetClientCB(NULL, NULL, fullUri);
292 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response);
295 if (cbResult == OC_STACK_DELETE_TRANSACTION)
297 FindAndDeleteClientCB(cbNode);
304 OCFree(resourceTypeName);
308 //This function will be called back by CA layer when a response is received
309 void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
311 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
312 printf ("Received payload: %s\n", (char *)responseInfo->info.payload);
313 OCStackApplicationResult result = OC_STACK_DELETE_TRANSACTION;
314 if(strcmp(endPoint->resourceUri, OC_PRESENCE_URI) == 0)
316 HandlePresenceResponse(endPoint, responseInfo);
319 ClientCB *cbNode = GetClientCB((CAToken_t *)&responseInfo->info.token, NULL, NULL);
323 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
324 OCClientResponse response;
325 struct sockaddr_in sa;
327 inet_pton(AF_INET, endPoint->addressInfo.IP.ipAddress, &(sa.sin_addr));
328 sa.sin_port = htons(endPoint->addressInfo.IP.port);
329 static OCDevAddr address;
330 memcpy((void*)&address.addr, &(sa), sizeof(sa));
331 response.addr = &address;
332 response.result = CAToOCStackResult(responseInfo->result);
333 response.resJSONPayload = (unsigned char*)responseInfo->info.payload;
334 response.numRcvdVendorSpecificHeaderOptions = 0;
335 if(responseInfo->info.numOptions > 0)
337 //First option alwas with option ID COAP_OPTION_OBSERVE if it is availbale
338 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
340 memcpy (&(response.sequenceNumber),
341 &(responseInfo->info.options[0].optionData), 4);
345 memcpy (&(response.rcvdVendorSpecificHeaderOptions[0]),
346 &(responseInfo->info.options[0]), sizeof(OCHeaderOption));
348 for (uint8_t i = 1; i < responseInfo->info.numOptions; i++)
350 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i]),
351 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
353 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
355 result = cbNode->callBack(cbNode->context,
356 cbNode->handle, &response);
357 if (result == OC_STACK_DELETE_TRANSACTION)
359 FindAndDeleteClientCB(cbNode);
362 OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload);
363 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
366 //This function will be called back by CA layer when a request is received
367 void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
369 CAInfo_t responseData;
370 CAResponseInfo_t responseInfo;
371 OCStackResult requestResult = OC_STACK_ERROR;
373 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
376 if(myStackMode == OC_CLIENT)
378 //TODO: should the client be responding to requests?
382 OCServerProtocolRequest serverRequest;
384 memset (&serverRequest, 0, sizeof(OCServerProtocolRequest));
385 OC_LOG_V(INFO, TAG, PCF("***** Endpoint URI ***** : %s\n"), (char*)endPoint->resourceUri);
387 char * newUri = (char *)endPoint->resourceUri;
388 unsigned char * query = NULL;
389 unsigned char * resourceType = NULL;
390 getQueryFromUri(endPoint->resourceUri, &query, &newUri);
391 OC_LOG_V(INFO, TAG, PCF("**********URI without query ****: %s\n"), newUri);
392 OC_LOG_V(INFO, TAG, PCF("**********Query ****: %s\n"), query);
394 memcpy (&(serverRequest.resourceUrl), newUri, strlen(newUri));
398 memcpy (&(serverRequest.query), query, strlen(query));
400 //copy request payload
401 if (requestInfo->info.payload)
403 serverRequest.reqTotalSize = strlen(requestInfo->info.payload) + 1;
404 memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
405 strlen(requestInfo->info.payload));
406 serverRequest.reqTotalSize = strlen((const char *)requestInfo->info.payload) + 1;
410 serverRequest.reqTotalSize = 1;
413 switch (requestInfo->method)
417 serverRequest.method = OC_REST_GET;
422 serverRequest.method = OC_REST_PUT;
427 serverRequest.method = OC_REST_POST;
432 serverRequest.method = OC_REST_DELETE;
437 OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
443 OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d", strlen(requestInfo->info.token));
444 OC_LOG_BUFFER(INFO, TAG, requestInfo->info.token, strlen(requestInfo->info.token));
445 // TODO-CA: For CA integration currently copying CAToken to OCCoapToken:
446 // Need to remove OCCoapToken
447 memcpy (&(serverRequest.requestToken.token), requestInfo->info.token,
448 strlen(requestInfo->info.token));
449 serverRequest.requestToken.tokenLength = strlen(requestInfo->info.token);
451 if (requestInfo->info.type == CA_MSG_CONFIRM)
453 serverRequest.qos = OC_HIGH_QOS;
455 else if (requestInfo->info.type == CA_MSG_NONCONFIRM)
457 serverRequest.qos = OC_LOW_QOS;
459 else if (requestInfo->info.type == CA_MSG_ACKNOWLEDGE)
461 // TODO-CA: Need to handle this
463 else if (requestInfo->info.type == CA_MSG_RESET)
465 // TODO-CA: Need to handle this
467 // CA does not need the following 3 fields
468 serverRequest.coapID = 0;
469 serverRequest.delayedResNeeded = 0;
470 serverRequest.secured = endPoint->isSecured;
473 serverRequest.addressInfo = endPoint->addressInfo;
474 serverRequest.connectivityType = endPoint->connectivityType;
475 if (requestInfo->info.token)
477 strncpy(serverRequest.token, requestInfo->info.token, sizeof(serverRequest.token) - 1);
480 // copy vendor specific header options
481 // TODO-CA: CA is including non-vendor header options as well, like observe.
482 // Need to filter those out
483 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &(requestInfo->info.numOptions));
484 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
486 // TODO-CA: Need to send an error indicating the num of options is incorrect
489 serverRequest.numRcvdVendorSpecificHeaderOptions = requestInfo->info.numOptions;
490 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
492 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
493 sizeof(CAHeaderOption_t)*requestInfo->info.numOptions);
496 requestResult = HandleStackRequests (&serverRequest);
499 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
504 //This function will be called back by occoap layer when a request is received
505 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
507 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
508 OCStackResult result = OC_STACK_ERROR;
509 ResourceHandling resHandling;
510 OCResource *resource;
512 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
515 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
517 result = AddServerCARequest(&request, protocolRequest->coapID,
518 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
519 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
520 protocolRequest->observationOption, protocolRequest->qos,
521 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
522 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
523 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
524 protocolRequest->reqTotalSize,
525 &protocolRequest->addressInfo, protocolRequest->connectivityType, protocolRequest->token);
527 result = AddServerRequest(&request, protocolRequest->coapID,
528 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
529 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
530 protocolRequest->observationOption, protocolRequest->qos,
531 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
532 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
533 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
534 protocolRequest->reqTotalSize);
536 if (OC_STACK_OK != result)
538 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
541 VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
543 if(!protocolRequest->reqMorePacket)
545 request->requestComplete = 1;
550 OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
553 if(request->requestComplete)
555 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
556 result = DetermineResourceHandling (request, &resHandling, &resource);
557 if (result == OC_STACK_OK)
559 result = ProcessRequest(resHandling, resource, request);
563 result = OC_STACK_ERROR;
568 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
569 result = OC_STACK_CONTINUE;
574 //This function will be called back by occoap layer when a response is received
575 OCStackResult HandleStackResponses(OCResponse * response)
577 OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)"));
578 OCStackResult result = OC_STACK_OK;
579 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
580 uint8_t isObserveNotification = 0;
581 ClientCB * cbNode = NULL;
583 uint8_t isPresenceNotification = 0;
584 uint8_t isMulticastPresence = 0;
585 char * resourceTypeName = NULL;
586 uint32_t lowerBound = 0;
587 uint32_t higherBound = 0;
589 unsigned char * bufRes = response->bufRes;
590 #endif // WITH_PRESENCE
592 cbNode = response->cbNode;
595 cbNode = GetClientCB(response->rcvdToken, NULL, NULL);
598 if(response->clientResponse->sequenceNumber >= OC_OFFSET_SEQUENCE_NUMBER)
600 isObserveNotification = 1;
601 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
604 OC_LOG_V(DEBUG, TAG, "The sequenceNumber/NONCE of this response %u",
605 response->clientResponse->sequenceNumber);
606 OC_LOG_V(DEBUG, TAG, "The maxAge/TTL of this response %u", response->maxAge);
607 OC_LOG_V(DEBUG, TAG, "The response received is %s", bufRes);
610 if(!strcmp((char *)response->rcvdUri, (char *)OC_PRESENCE_URI)){
611 isPresenceNotification = 1;
614 result = OC_STACK_INVALID_PARAM;
617 tok = strtok((char *)bufRes, "[:]}");
618 bufRes[strlen((char *)bufRes)] = ':';
619 tok = strtok(NULL, "[:]}");
620 bufRes[strlen((char *)bufRes)] = ':';
621 response->clientResponse->sequenceNumber = (uint32_t )atoi(tok);
622 OC_LOG_V(DEBUG, TAG, "The received NONCE is %u", response->clientResponse->sequenceNumber);
623 tok = strtok(NULL, "[:]}");
624 response->maxAge = (uint32_t )atoi(tok);
625 OC_LOG_V(DEBUG, TAG, "The received TTL is %u", response->maxAge);
626 tok = strtok(NULL, "[:]}");
629 resourceTypeName = (char *)OCMalloc(strlen(tok));
630 if(!resourceTypeName)
634 bufRes[strlen((char *)bufRes)] = ':';
635 strcpy(resourceTypeName, tok);
636 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
639 bufRes[strlen((char *)bufRes)] = ']';
642 // Check if the application subcribed for presence
645 cbNode = GetClientCB(NULL, NULL, response->fullUri);
648 // Check if application subscribed for multicast presence
651 snprintf((char *)response->fullUri, MAX_URI_LENGTH, "%s%s",
652 OC_MULTICAST_IP, response->rcvdUri);
653 cbNode = GetClientCB(NULL, NULL, response->fullUri);
656 isMulticastPresence = 1;
657 isPresenceNotification = 0;
661 if(cbNode && isPresenceNotification)
663 OC_LOG(INFO, TAG, PCF("Received a presence notification"));
664 if(!cbNode->presence)
666 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
667 VERIFY_NON_NULL_V(cbNode->presence);
668 cbNode->presence->timeOut = NULL;
669 cbNode->presence->timeOut = (uint32_t *)
670 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
671 if(!(cbNode->presence->timeOut)){
672 OCFree(cbNode->presence);
673 result = OC_STACK_NO_MEMORY;
676 if(response->maxAge == 0)
678 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
679 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
682 OCFree(cbNode->presence->timeOut);
683 OCFree(cbNode->presence);
684 cbNode->presence = NULL;
689 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %d", GetTime(0));
690 cbNode->presence->TTL = response->maxAge;
691 for(int index = 0; index < PresenceTimeOutSize; index++)
693 lowerBound = GetTime(((float)(PresenceTimeOut[index])
694 /(float)100)*(float)cbNode->presence->TTL);
695 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
696 /(float)100)*(float)cbNode->presence->TTL);
697 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
698 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
699 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
700 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
701 cbNode->presence->timeOut[index]);
703 cbNode->presence->TTLlevel = 0;
704 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
705 if(cbNode->sequenceNumber == response->clientResponse->sequenceNumber)
707 OC_LOG(INFO, TAG, PCF("===============No presence change"));
710 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
711 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;;
714 // Ensure that a filter is actually applied.
715 if(resourceTypeName && cbNode->filterResourceType)
717 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
723 else if(cbNode && isMulticastPresence)
725 // Check if the same nonce for a given host
726 OCMulticastNode* mcNode = NULL;
727 mcNode = GetMCPresenceNode(response->fullUri);
729 if(response->maxAge == 0)
731 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
732 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
735 OCFree(cbNode->presence->timeOut);
736 OCFree(cbNode->presence);
737 cbNode->presence = NULL;
740 else if(mcNode != NULL)
742 if(mcNode->nonce == response->clientResponse->sequenceNumber)
744 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
745 result = OC_STACK_NO_MEMORY;
748 mcNode->nonce = response->clientResponse->sequenceNumber;
752 uint32_t uriLen = strlen((char*)response->fullUri);
753 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
756 memcpy(uri, response->fullUri, (uriLen + 1));
761 PCF("===============No Memory for URI to store in the presence node"));
762 result = OC_STACK_NO_MEMORY;
765 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri,
766 response->clientResponse->sequenceNumber);
767 if(result == OC_STACK_NO_MEMORY)
770 PCF("===============No Memory for Multicast Presence Node"));
771 result = OC_STACK_NO_MEMORY;
776 // Ensure that a filter is actually applied.
777 if(resourceTypeName && cbNode->filterResourceType)
779 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
786 else if(!cbNode && isPresenceNotification)
788 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
789 ------------ ignoring"));
791 #endif // WITH_PRESENCE
795 if(isObserveNotification)
797 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
798 //TODO: check the standard for methods to detect wrap around condition
799 if(cbNode->method == OC_REST_OBSERVE &&
800 (response->clientResponse->sequenceNumber <= cbNode->sequenceNumber ||
801 (response->clientResponse->sequenceNumber > cbNode->sequenceNumber &&
802 response->clientResponse->sequenceNumber ==
803 MAX_SEQUENCE_NUMBER)))
805 OC_LOG_V(DEBUG, TAG, "Observe notification came out of order. \
806 Ignoring Incoming:%d Against Current:%d.",
807 response->clientResponse->sequenceNumber, cbNode->sequenceNumber);
810 if(response->clientResponse->sequenceNumber > cbNode->sequenceNumber){
811 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;
815 response->clientResponse->resJSONPayload = bufRes;
817 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response->clientResponse);
819 if (cbResult == OC_STACK_DELETE_TRANSACTION ||
820 response->clientResponse->result == OC_STACK_COMM_ERROR ||
821 (response->clientResponse->result == OC_STACK_RESOURCE_DELETED &&
822 !isPresenceNotification && !isMulticastPresence))
824 FindAndDeleteClientCB(cbNode);
829 result = OC_STACK_ERROR;
834 OCFree(resourceTypeName);
839 int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
842 unsigned char *itr, *coap;
843 uint8_t dotCount = 0;
847 /* search for scheme */
849 if (!isdigit((unsigned char) *ipAddrStr))
851 coap = (unsigned char *) OC_COAP_SCHEME;
852 while (*coap && tolower(*itr) == *coap)
861 if (isdigit((unsigned char) *ipAddrStr))
864 ipAddr[index] += *ipAddrStr - '0';
866 else if ((unsigned char) *ipAddrStr == '.')
878 if(*ipAddrStr == ':')
882 if (isdigit((unsigned char) *ipAddrStr))
885 *port += *ipAddrStr - '0';
896 if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
907 //-----------------------------------------------------------------------------
908 // Private internal function prototypes
909 //-----------------------------------------------------------------------------
911 static OCDoHandle GenerateInvocationHandle();
912 static OCStackResult initResources();
913 static void insertResource(OCResource *resource);
914 static OCResource *findResource(OCResource *resource);
915 static void insertResourceType(OCResource *resource,
916 OCResourceType *resourceType);
917 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
919 static void insertResourceInterface(OCResource *resource,
920 OCResourceInterface *resourceInterface);
921 static OCResourceInterface *findResourceInterfaceAtIndex(
922 OCResourceHandle handle, uint8_t index);
923 static void deleteResourceType(OCResourceType *resourceType);
924 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
925 static void deleteResourceElements(OCResource *resource);
926 static int deleteResource(OCResource *resource);
927 static void deleteAllResources();
928 static void incrementSequenceNumber(OCResource * resPtr);
929 static OCStackResult verifyUriQueryLength(const char * inputUri,
931 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
932 OCStackResult getResourceType(const char * query, unsigned char** resourceType);
934 //-----------------------------------------------------------------------------
936 //-----------------------------------------------------------------------------
939 * Initialize the OC Stack. Must be called prior to starting the stack.
942 * IP Address of host device
944 * Port of host device
946 * Host device is client, server, or client-server
949 * OC_STACK_OK - no errors
950 * OC_STACK_ERROR - stack init error
952 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
954 OCStackResult result = OC_STACK_ERROR;
955 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
959 OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
963 //It is ok to select network to CA_WIFI for now
964 CAResult_t caResult = CASelectNetwork(CA_WIFI);
965 if(caResult == CA_STATUS_OK)
967 OC_LOG(INFO, TAG, PCF("CASelectNetwork to WIFI"));
968 caResult = CARegisterHandler(HandleCARequests, HandleCAResponses);
969 if(caResult == CA_STATUS_OK)
971 OC_LOG(INFO, TAG, PCF("CARegisterHandler..."));
972 stackState = OC_STACK_INITIALIZED;
973 result = OC_STACK_OK;
977 caResult = CAStartDiscoveryServer();
978 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
981 caResult = CAStartListeningServer();
982 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
984 case OC_CLIENT_SERVER:
985 caResult = CAStartListeningServer();
986 if(caResult == CA_STATUS_OK)
988 caResult = CAStartDiscoveryServer();
990 OC_LOG(INFO, TAG, PCF("Client-server mode"));
993 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
994 return OC_STACK_ERROR;
999 if (caResult == CA_STATUS_OK)
1001 result = OC_STACK_OK;
1005 result = OC_STACK_ERROR;
1012 OC_LOG(INFO, TAG, PCF("Client mode"));
1015 OC_LOG(INFO, TAG, PCF("Server mode"));
1017 case OC_CLIENT_SERVER:
1018 OC_LOG(INFO, TAG, PCF("Client-server mode"));
1021 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1022 return OC_STACK_ERROR;
1026 // Make call to OCCoAP layer
1027 result = OCInitCoAP(ipAddr, (uint16_t) port, myStackMode);
1031 defaultDeviceHandler = NULL;
1033 #ifdef WITH_PRESENCE
1034 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
1035 #endif // WITH_PRESENCE
1037 if (result == OC_STACK_OK)
1039 stackState = OC_STACK_INITIALIZED;
1041 // Initialize resource
1042 if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
1044 result = initResources();
1046 if(result != OC_STACK_OK)
1048 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1054 * Stop the OC stack. Use for a controlled shutdown.
1056 * OC_STACK_OK - no errors
1057 * OC_STACK_ERROR - stack not initialized
1059 OCStackResult OCStop()
1061 OCStackResult result = OC_STACK_ERROR;
1063 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1065 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1067 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1070 else if (stackState != OC_STACK_INITIALIZED)
1072 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1073 return OC_STACK_ERROR;
1076 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1078 #ifdef WITH_PRESENCE
1079 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1080 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1081 presenceResource.presenceTTL = 0;
1082 #endif // WITH_PRESENCE
1084 // Free memory dynamically allocated for resources
1085 deleteAllResources();
1088 // Make call to OCCoAP layer
1089 if (OCStopCoAP() == OC_STACK_OK)
1091 // Remove all observers
1092 DeleteObserverList();
1093 // Remove all the client callbacks
1094 DeleteClientCBList();
1095 stackState = OC_STACK_UNINITIALIZED;
1096 result = OC_STACK_OK;
1098 stackState = OC_STACK_INITIALIZED;
1099 result = OC_STACK_ERROR;
1102 // Deinit security blob
1103 DeinitOCSecurityInfo();
1105 if (result != OC_STACK_OK) {
1106 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
1113 * Verify the lengths of the URI and the query separately
1115 * @param inputUri - Input URI and query.
1116 * @param uriLen - The length of the initial URI with query.
1118 * Note: The '?' that appears after the URI is not considered as
1119 * a part of the query.
1121 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1125 query = strchr (inputUri, '?');
1129 if((query - inputUri) > MAX_URI_LENGTH)
1131 return OC_STACK_INVALID_URI;
1134 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1136 return OC_STACK_INVALID_QUERY;
1139 else if(uriLen > MAX_URI_LENGTH)
1141 return OC_STACK_INVALID_URI;
1147 * Discover or Perform requests on a specified resource (specified by that Resource's respective URI).
1149 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of calling this API.
1150 * @param method - @ref OCMethod to perform on the resource
1151 * @param requiredUri - URI of the resource to interact with
1152 * @param referenceUri - URI of the reference resource
1153 * @param request - JSON encoded request
1154 * @param qos - quality of service
1155 * @param cbData - struct that contains asynchronous callback function that is invoked
1156 * by the stack when discovery or resource interaction is complete
1157 * @param options - The address of an array containing the vendor specific header
1158 * header options to be sent with the request
1159 * @param numOptions - Number of vendor specific header options to be included
1162 * OC_STACK_OK - no errors
1163 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
1164 * OC_STACK_INVALID_METHOD - invalid resource method
1165 * OC_STACK_INVALID_URI - invalid required or reference URI
1168 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1169 const char *referenceUri, const char *request, uint8_t conType,
1170 OCQualityOfService qos, OCCallbackData *cbData,
1171 OCHeaderOption * options, uint8_t numOptions)
1173 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1174 const char *referenceUri, const char *request,
1175 OCQualityOfService qos, OCCallbackData *cbData,
1176 OCHeaderOption * options, uint8_t numOptions)
1179 OCStackResult result = OC_STACK_ERROR;
1181 ClientCB *clientCB = NULL;
1182 unsigned char * requestUri = NULL;
1183 unsigned char * resourceType = NULL;
1184 unsigned char * query = NULL;
1185 char * newUri = (char *)requiredUri;
1186 (void) referenceUri;
1188 CARemoteEndpoint_t* endpoint = NULL;
1189 CAResult_t caResult;
1190 CAToken_t caToken = NULL;
1191 CAInfo_t requestData;
1192 CARequestInfo_t requestInfo;
1193 // To track if memory is allocated for additional header options
1194 uint8_t hdrOptionMemAlloc = 0;
1197 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1199 // Validate input parameters
1200 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1201 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1203 TODO ("Need to form the final query by concatenating require and reference URI's");
1204 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
1206 uint16_t uriLen = strlen(requiredUri);
1208 // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS
1214 case OC_REST_DELETE:
1215 case OC_REST_OBSERVE:
1216 case OC_REST_OBSERVE_ALL:
1217 case OC_REST_CANCEL_OBSERVE:
1219 #ifdef WITH_PRESENCE
1220 case OC_REST_PRESENCE:
1224 result = OC_STACK_INVALID_METHOD;
1228 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
1233 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
1235 result = OC_STACK_INVALID_PARAM;
1239 #ifdef WITH_PRESENCE
1240 if(method == OC_REST_PRESENCE)
1242 // Replacing method type with GET because "presence" is a stack layer only implementation.
1243 method = OC_REST_GET;
1244 result = getQueryFromUri(requiredUri, &query, &newUri);
1247 result = getResourceType((char *) query, &resourceType);
1250 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1254 OC_LOG(DEBUG, TAG, PCF("Resource type is NULL."));
1259 OC_LOG(DEBUG, TAG, PCF("Query string is NULL."));
1261 if(result != OC_STACK_OK)
1266 #endif // WITH_PRESENCE
1268 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
1271 memcpy(requestUri, newUri, (uriLen + 1));
1275 result = OC_STACK_NO_MEMORY;
1279 *handle = GenerateInvocationHandle();
1282 result = OC_STACK_NO_MEMORY;
1287 memset(&requestData, 0, sizeof(CAInfo_t));
1288 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1292 case OC_REST_OBSERVE:
1293 case OC_REST_OBSERVE_ALL:
1294 case OC_REST_CANCEL_OBSERVE:
1296 requestInfo.method = CA_GET;
1301 requestInfo.method = CA_PUT;
1306 requestInfo.method = CA_POST;
1309 case OC_REST_DELETE:
1311 requestInfo.method = CA_DELETE;
1314 #ifdef WITH_PRESENCE
1315 case OC_REST_PRESENCE:
1316 //TODO-CA: What should be the CA method?
1320 result = OC_STACK_INVALID_METHOD;
1324 // TODO-CA: Handle multi-cast scenario
1325 // Create remote end point
1326 caResult = CACreateRemoteEndpoint(newUri, CA_WIFI, &endpoint);
1327 // TODO-CA: Connectivity type should be passed to API
1328 endpoint->connectivityType = CA_WIFI;
1329 if (caResult != CA_STATUS_OK)
1331 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1336 caResult = CAGenerateToken(&caToken);
1338 if (caResult != CA_STATUS_OK)
1340 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1345 // TODO-CA: Map QoS to the right CA msg type
1346 requestData.type = CA_MSG_NONCONFIRM;
1347 requestData.token = caToken;
1348 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1350 result = CreateObserveHeaderOption (&(requestData.options), options,
1351 numOptions, OC_OBSERVE_REGISTER);
1352 if (result != OC_STACK_OK)
1356 hdrOptionMemAlloc = 1;
1357 requestData.numOptions = numOptions + 1;
1361 requestData.options = (CAHeaderOption_t*)options;
1362 requestData.numOptions = numOptions;
1364 requestData.payload = (char *)request;
1366 requestInfo.info = requestData;
1369 caResult = CASendRequest(endpoint, &requestInfo);
1370 if (caResult != CA_STATUS_OK)
1372 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1376 if((result = AddClientCB(&clientCB, cbData, &caToken, handle, method,
1377 requestUri, resourceType)) != OC_STACK_OK)
1379 result = OC_STACK_NO_MEMORY;
1385 // Generate token which will be used by OCStack to match responses received
1387 OCGenerateCoAPToken(&token);
1389 if((result = AddClientCB(&clientCB, cbData, &token, handle, method, requestUri, resourceType))
1392 result = OC_STACK_NO_MEMORY;
1396 // Make call to OCCoAP layer
1397 result = OCDoCoAPResource(method, qos, &token, newUri, request, options, numOptions);
1401 if(newUri != requiredUri)
1405 if (result != OC_STACK_OK)
1407 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1408 FindAndDeleteClientCB(clientCB);
1411 CADestroyRemoteEndpoint(endpoint);
1412 if (hdrOptionMemAlloc)
1414 OCFree(requestData.options);
1421 * Cancel a request associated with a specific @ref OCDoResource invocation.
1423 * @param handle - Used to identify a specific OCDoResource invocation.
1424 * @param qos - used to specify Quality of Service (read below for more info)
1425 * @param options- used to specify vendor specific header options when sending
1426 * explicit observe cancellation
1427 * @param numOptions- Number of header options to be included
1430 * OC_STACK_OK - No errors; Success
1431 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1433 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1437 * This ftn is implemented one of two ways in the case of observation:
1439 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1440 * Remove the callback associated on client side.
1441 * When the next notification comes in from server,
1442 * reply with RESET message to server.
1443 * Keep in mind that the server will react to RESET only
1444 * if the last notification was sent ans CON
1446 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1447 * and it is associated with an observe request
1448 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1449 * Send CON Observe request to server with
1450 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1451 * Remove the callback associated on client side.
1453 OCStackResult ret = OC_STACK_OK;
1455 CARemoteEndpoint_t* endpoint = NULL;
1456 CAResult_t caResult;
1457 CAInfo_t requestData;
1458 CARequestInfo_t requestInfo;
1459 // Track if memory is allocated for additional header options
1460 uint8_t hdrOptionMemAlloc = 0;
1464 return OC_STACK_INVALID_PARAM;
1467 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1469 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1472 switch (clientCB->method)
1474 case OC_REST_OBSERVE:
1475 case OC_REST_OBSERVE_ALL:
1477 caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri, CA_WIFI,
1479 endpoint->connectivityType = CA_WIFI;
1480 if (caResult != CA_STATUS_OK)
1482 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1483 return OC_STACK_ERROR;
1486 memset(&requestData, 0, sizeof(CAInfo_t));
1487 // TODO-CA: Map QoS to the right CA msg type
1488 requestData.type = CA_MSG_NONCONFIRM;
1489 requestData.token = clientCB->token;
1490 if (CreateObserveHeaderOption (&(requestData.options),
1491 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
1493 return OC_STACK_ERROR;
1495 hdrOptionMemAlloc = 1;
1496 requestData.numOptions = numOptions + 1;
1497 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1498 requestInfo.method = CA_GET;
1499 requestInfo.info = requestData;
1501 caResult = CASendRequest(endpoint, &requestInfo);
1502 if (caResult != CA_STATUS_OK)
1504 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1506 if(caResult == CA_STATUS_OK)
1511 if(qos == OC_HIGH_QOS)
1513 ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
1514 &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
1519 FindAndDeleteClientCB(clientCB);
1523 #ifdef WITH_PRESENCE
1524 case OC_REST_PRESENCE:
1525 FindAndDeleteClientCB(clientCB);
1529 return OC_STACK_INVALID_METHOD;
1533 CADestroyRemoteEndpoint(endpoint);
1534 if (hdrOptionMemAlloc)
1536 OCFree(requestData.options);
1542 #ifdef WITH_PRESENCE
1543 OCStackResult OCProcessPresence()
1545 OCStackResult result = OC_STACK_OK;
1546 uint8_t ipAddr[4] = { 0 };
1549 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1550 ClientCB* cbNode = NULL;
1552 OCClientResponse clientResponse;
1553 OCResponse * response = NULL;
1555 LL_FOREACH(cbList, cbNode) {
1556 if(OC_REST_PRESENCE == cbNode->method)
1558 if(cbNode->presence)
1560 uint32_t now = GetTime(0);
1561 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
1562 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1565 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1570 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1571 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1572 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1575 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1577 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1578 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1580 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1582 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
1583 (OCDevAddr *) &dst, 0, NULL);
1584 if(result != OC_STACK_OK)
1588 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1589 &cbNode->token, &clientResponse, NULL);
1590 if(result != OC_STACK_OK)
1595 // Increment the TTLLevel (going to a next state), so we don't keep
1596 // sending presence notification to client.
1597 cbNode->presence->TTLlevel++;
1598 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1599 cbNode->presence->TTLlevel);
1603 result = OC_STACK_INVALID_IP;
1606 HandleStackResponses(response);
1608 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1610 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
1612 OCGenerateCoAPToken(&token);
1613 result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
1614 &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
1615 if(result != OC_STACK_OK)
1619 cbNode->presence->TTLlevel++;
1620 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
1626 if (result != OC_STACK_OK)
1628 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
1635 * Called in main loop of OC client or server. Allows low-level processing of
1639 * OC_STACK_OK - no errors
1640 * OC_STACK_ERROR - stack process error
1642 OCStackResult OCProcess() {
1644 OC_LOG(INFO, TAG, PCF("Entering OCProcess"));
1645 #ifdef WITH_PRESENCE
1646 OCProcessPresence();
1649 CAHandleRequestResponse();
1657 #ifdef WITH_PRESENCE
1659 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
1660 * presence notifications to clients via multicast. Once this API has been called with a success,
1661 * clients may query for this server's presence and this server's stack will respond via multicast.
1663 * Server can call this function when it comes online for the first time, or when it comes back
1664 * online from offline mode, or when it re enters network.
1666 * @param ttl - Time To Live in seconds
1667 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
1670 * OC_STACK_OK - No errors; Success
1672 OCStackResult OCStartPresence(const uint32_t ttl)
1674 OCChangeResourceProperty(
1675 &(((OCResource *)presenceResource.handle)->resourceProperties),
1680 presenceResource.presenceTTL = ttl;
1683 if(OC_PRESENCE_UNINITIALIZED == presenceState)
1685 OCDevAddr multiCastAddr;
1688 presenceState = OC_PRESENCE_INITIALIZED;
1689 OCGenerateCoAPToken(&token);
1690 OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
1692 CAAddress_t addressInfo;
1693 strncpy(addressInfo.IP.ipAddress, "224.0.1.187", CA_IPADDR_SIZE);
1694 addressInfo.IP.port = 5298;
1696 CAToken_t caToken = NULL;
1697 CAGenerateToken(&caToken);
1699 AddCAObserver(OC_PRESENCE_URI, NULL, 0, &token,
1700 &multiCastAddr, (OCResource *)presenceResource.handle, OC_LOW_QOS,
1701 &addressInfo, CA_WIFI, caToken);
1703 //add the presence observer
1704 AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
1705 (OCResource *)presenceResource.handle, OC_LOW_QOS);
1709 // Each time OCStartPresence is called
1710 // a different random 32-bit integer number is used
1711 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1713 return SendPresenceNotification(NULL);
1717 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
1718 * presence notifications to clients via multicast. Once this API has been called with a success,
1719 * this server's stack will not respond to clients querying for this server's presence.
1721 * Server can call this function when it is terminating, going offline, or when going
1722 * away from network.
1725 * OC_STACK_OK - No errors; Success
1727 OCStackResult OCStopPresence()
1729 OCStackResult result = OC_STACK_ERROR;
1730 //make resource inactive
1731 result = OCChangeResourceProperty(
1732 &(((OCResource *) presenceResource.handle)->resourceProperties),
1734 result = SendPresenceNotification(NULL);
1741 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
1743 defaultDeviceHandler = entityHandler;
1748 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
1750 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
1752 if(myStackMode == OC_CLIENT)
1754 return OC_STACK_ERROR;
1757 return SaveDeviceInfo(deviceInfo);
1763 * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource
1764 * @param resourceTypeName - name of resource type. Example: "core.led"
1765 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1766 * @param uri - URI of the resource. Example: "/a/led"
1767 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1768 * NULL for default entity handler
1769 * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE
1772 * OC_STACK_OK - no errors
1773 * OC_STACK_ERROR - stack process error
1775 OCStackResult OCCreateResource(OCResourceHandle *handle,
1776 const char *resourceTypeName,
1777 const char *resourceInterfaceName,
1778 const char *uri, OCEntityHandler entityHandler,
1779 uint8_t resourceProperties) {
1781 OCResource *pointer = NULL;
1784 OCStackResult result = OC_STACK_ERROR;
1786 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
1788 if(myStackMode == OC_CLIENT)
1792 // Validate parameters
1793 if(!uri || (strlen(uri) == 0))
1795 OC_LOG(ERROR, TAG, PCF("URI is invalid"));
1796 return OC_STACK_INVALID_URI;
1798 // Is it presented during resource discovery?
1799 if (!handle || !resourceTypeName) {
1800 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
1801 return OC_STACK_INVALID_PARAM;
1804 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
1805 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
1808 // Make sure resourceProperties bitmask has allowed properties specified
1809 if (resourceProperties
1810 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
1811 OC_LOG(ERROR, TAG, PCF("Invalid property"));
1812 return OC_STACK_INVALID_PARAM;
1815 // If the headResource is NULL, then no resources have been created...
1816 pointer = headResource;
1818 // At least one resources is in the resource list, so we need to search for
1819 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
1821 if (strcmp(uri, pointer->uri) == 0) {
1822 OC_LOG(ERROR, TAG, PCF("URI already in use"));
1823 return OC_STACK_INVALID_PARAM;
1825 pointer = pointer->next;
1828 // Create the pointer and insert it into the resource list
1829 pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
1833 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
1835 insertResource(pointer);
1838 size = strlen(uri) + 1;
1839 str = (char *) OCMalloc(size);
1843 strncpy(str, uri, size);
1846 // Set properties. Set OC_ACTIVE
1847 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
1850 // Add the resourcetype to the resource
1851 result = BindResourceTypeToResource(pointer, resourceTypeName);
1852 if (result != OC_STACK_OK) {
1853 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
1857 // Add the resourceinterface to the resource
1858 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
1859 if (result != OC_STACK_OK) {
1860 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
1864 // If an entity handler has been passed, attach it to the newly created
1865 // resource. Otherwise, set the default entity handler.
1868 pointer->entityHandler = entityHandler;
1872 pointer->entityHandler = defaultResourceEHandler;
1876 result = OC_STACK_OK;
1878 #ifdef WITH_PRESENCE
1879 if(presenceResource.handle)
1881 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1882 SendPresenceNotification(pointer->rsrcType);
1886 if (result != OC_STACK_OK)
1888 // Deep delete of resource and other dynamic elements that it contains
1889 deleteResource(pointer);
1898 * Create a resource. with host ip address for remote resource
1900 * @param handle - pointer to handle to newly created resource. Set by ocstack.
1901 * Used to refer to resource
1902 * @param resourceTypeName - name of resource type. Example: "core.led"
1903 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1904 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
1905 * @param uri - URI of the resource. Example: "/a/led"
1906 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1907 * NULL for default entity handler
1908 * @param resourceProperties - properties supported by resource.
1909 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
1912 * OC_STACK_OK - no errors
1913 * OC_STACK_ERROR - stack process error
1916 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
1917 const char *resourceTypeName,
1918 const char *resourceInterfaceName,
1921 OCEntityHandler entityHandler,
1922 uint8_t resourceProperties)
1926 OCStackResult result = OC_STACK_ERROR;
1928 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
1929 uri, entityHandler, resourceProperties);
1931 if (result != OC_STACK_ERROR)
1934 size = strlen(host) + 1;
1935 str = (char *) OCMalloc(size);
1938 return OC_STACK_ERROR;
1940 strncpy(str, host, size);
1941 ((OCResource *) *handle)->host = str;
1948 * Add a resource to a collection resource.
1950 * @param collectionHandle - handle to the collection resource
1951 * @param resourceHandle - handle to resource to be added to the collection resource
1954 * OC_STACK_OK - no errors
1955 * OC_STACK_ERROR - stack process error
1956 * OC_STACK_INVALID_PARAM - invalid collectionhandle
1958 OCStackResult OCBindResource(
1959 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1960 OCResource *resource;
1963 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
1965 // Validate parameters
1966 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1967 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1968 // Container cannot contain itself
1969 if (collectionHandle == resourceHandle) {
1970 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
1971 return OC_STACK_INVALID_PARAM;
1974 // Use the handle to find the resource in the resource linked list
1975 resource = findResource((OCResource *) collectionHandle);
1977 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1978 return OC_STACK_INVALID_PARAM;
1981 // Look for an open slot to add add the child resource.
1982 // If found, add it and return success
1983 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1984 if (!resource->rsrcResources[i]) {
1985 resource->rsrcResources[i] = (OCResource *) resourceHandle;
1986 OC_LOG(INFO, TAG, PCF("resource bound"));
1991 #ifdef WITH_PRESENCE
1992 if(presenceResource.handle)
1994 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1995 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1999 // Unable to add resourceHandle, so return error
2000 return OC_STACK_ERROR;
2004 * Remove a resource from a collection resource.
2006 * @param collectionHandle - handle to the collection resource
2007 * @param resourceHandle - handle to resource to be added to the collection resource
2010 * OC_STACK_OK - no errors
2011 * OC_STACK_ERROR - stack process error
2012 * OC_STACK_INVALID_PARAM - invalid collectionHandle
2014 OCStackResult OCUnBindResource(
2015 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2016 OCResource *resource;
2019 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2021 // Validate parameters
2022 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2023 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2024 // Container cannot contain itself
2025 if (collectionHandle == resourceHandle) {
2026 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2027 return OC_STACK_INVALID_PARAM;
2030 // Use the handle to find the resource in the resource linked list
2031 resource = findResource((OCResource *) collectionHandle);
2033 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2034 return OC_STACK_INVALID_PARAM;
2037 // Look for an open slot to add add the child resource.
2038 // If found, add it and return success
2039 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2040 if (resourceHandle == resource->rsrcResources[i]) {
2041 resource->rsrcResources[i] = (OCResource *) NULL;
2042 OC_LOG(INFO, TAG, PCF("resource unbound"));
2047 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2049 #ifdef WITH_PRESENCE
2050 if(presenceResource.handle)
2052 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2053 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2057 // Unable to add resourceHandle, so return error
2058 return OC_STACK_ERROR;
2061 OCStackResult BindResourceTypeToResource(OCResource* resource,
2062 const char *resourceTypeName)
2064 OCResourceType *pointer = NULL;
2067 OCStackResult result = OC_STACK_ERROR;
2069 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
2071 // Validate parameters
2072 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2073 // TODO: Does resource attribute resentation really have to be maintained in stack?
2074 // Is it presented during resource discovery?
2076 TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
2078 // Create the resourcetype and insert it into the resource list
2079 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
2084 // Set the resourceTypeName
2085 size = strlen(resourceTypeName) + 1;
2086 str = (char *) OCMalloc(size);
2090 strncpy(str, resourceTypeName, size);
2091 pointer->resourcetypename = str;
2093 insertResourceType(resource, pointer);
2094 result = OC_STACK_OK;
2096 exit: if (result != OC_STACK_OK) {
2104 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2105 const char *resourceInterfaceName)
2107 OCResourceInterface *pointer = NULL;
2110 OCStackResult result = OC_STACK_ERROR;
2112 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
2114 // Validate parameters
2115 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2117 TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
2119 // Create the resourceinterface and insert it into the resource list
2120 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
2125 // Set the resourceinterface name
2126 size = strlen(resourceInterfaceName) + 1;
2127 str = (char *) OCMalloc(size);
2131 strncpy(str, resourceInterfaceName, size);
2132 pointer->name = str;
2134 // Bind the resourceinterface to the resource
2135 insertResourceInterface(resource, pointer);
2137 result = OC_STACK_OK;
2139 exit: if (result != OC_STACK_OK) {
2148 * Bind a resourcetype to a resource.
2150 * @param handle - handle to the resource
2151 * @param resourceTypeName - name of resource type. Example: "core.led"
2154 * OC_STACK_OK - no errors
2155 * OC_STACK_ERROR - stack process error
2157 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2158 const char *resourceTypeName) {
2160 OCStackResult result = OC_STACK_ERROR;
2161 OCResource *resource;
2163 // Make sure resource exists
2164 resource = findResource((OCResource *) handle);
2166 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2167 return OC_STACK_ERROR;
2170 // call internal function
2171 result = BindResourceTypeToResource(resource, resourceTypeName);
2173 #ifdef WITH_PRESENCE
2174 if(presenceResource.handle)
2176 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2177 SendPresenceNotification(resource->rsrcType);
2185 * Bind a resourceinterface to a resource.
2187 * @param handle - handle to the resource
2188 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
2191 * OC_STACK_OK - no errors
2192 * OC_STACK_ERROR - stack process error
2195 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2196 const char *resourceInterfaceName) {
2198 OCStackResult result = OC_STACK_ERROR;
2199 OCResource *resource;
2201 // Make sure resource exists
2202 resource = findResource((OCResource *) handle);
2204 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2205 return OC_STACK_ERROR;
2208 // call internal function
2209 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2211 #ifdef WITH_PRESENCE
2212 if(presenceResource.handle)
2214 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2215 SendPresenceNotification(resource->rsrcType);
2223 * Get the number of resources that have been created in the stack.
2225 * @param numResources - pointer to count variable
2228 * OC_STACK_OK - no errors
2229 * OC_STACK_ERROR - stack process error
2232 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
2233 OCResource *pointer = headResource;
2235 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2236 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2239 *numResources = *numResources + 1;
2240 pointer = pointer->next;
2246 * Get a resource handle by index.
2248 * @param index - index of resource, 0 to Count - 1
2251 * Resource handle - if found
2252 * NULL - if not found
2254 OCResourceHandle OCGetResourceHandle(uint8_t index) {
2255 OCResource *pointer = headResource;
2258 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2260 // Iterate through the list
2261 while ((i < index) && pointer) {
2263 pointer = pointer->next;
2265 return (OCResourceHandle) pointer;
2269 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
2272 * @param handle - handle of resource to be deleted
2275 * OC_STACK_OK - no errors
2276 * OC_STACK_ERROR - stack process error
2277 * OC_STACK_NO_RESOURCE - resource not found
2278 * OC_STACK_INVALID_PARAM - invalid param
2280 OCStackResult OCDeleteResource(OCResourceHandle handle) {
2281 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2284 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2285 return OC_STACK_INVALID_PARAM;
2288 OCResource *resource = findResource((OCResource *) handle);
2289 if (resource == NULL) {
2290 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2291 return OC_STACK_NO_RESOURCE;
2294 if (deleteResource((OCResource *) handle) == 0) {
2295 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2296 return OC_STACK_ERROR;
2303 * Get the URI of the resource specified by handle.
2305 * @param handle - handle of resource
2307 * URI string - if resource found
2308 * NULL - resource not found
2310 const char *OCGetResourceUri(OCResourceHandle handle) {
2311 OCResource *resource;
2312 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2314 resource = findResource((OCResource *) handle);
2316 return resource->uri;
2318 return (const char *) NULL;
2322 * Get the properties of the resource specified by handle.
2323 * NOTE: that after a resource is created, the OC_ACTIVE property is set
2324 * for the resource by the stack.
2326 * @param handle - handle of resource
2328 * property bitmap - if resource found
2329 * NULL - resource not found
2331 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
2332 OCResource *resource;
2333 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2335 resource = findResource((OCResource *) handle);
2337 return resource->resourceProperties;
2343 * Get the number of resource types of the resource.
2345 * @param handle - handle of resource
2346 * @param numResourceTypes - pointer to count variable
2349 * OC_STACK_OK - no errors
2350 * OC_STACK_ERROR - stack process error
2352 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2353 uint8_t *numResourceTypes) {
2354 OCResource *resource;
2355 OCResourceType *pointer;
2357 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2358 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2359 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2361 *numResourceTypes = 0;
2363 resource = findResource((OCResource *) handle);
2365 pointer = resource->rsrcType;
2367 *numResourceTypes = *numResourceTypes + 1;
2368 pointer = pointer->next;
2375 * Get name of resource type of the resource.
2377 * @param handle - handle of resource
2378 * @param index - index of resource, 0 to Count - 1
2381 * resource type name - if resource found
2382 * NULL - resource not found
2384 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
2385 OCResourceType *resourceType;
2387 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2389 resourceType = findResourceTypeAtIndex(handle, index);
2391 return resourceType->resourcetypename;
2393 return (const char *) NULL;
2399 * Get the number of resource interfaces of the resource.
2401 * @param handle - handle of resource
2402 * @param numResources - pointer to count variable
2405 * OC_STACK_OK - no errors
2406 * OC_STACK_ERROR - stack process error
2408 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2409 uint8_t *numResourceInterfaces) {
2410 OCResourceInterface *pointer;
2411 OCResource *resource;
2413 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2415 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2416 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2418 *numResourceInterfaces = 0;
2419 resource = findResource((OCResource *) handle);
2421 pointer = resource->rsrcInterface;
2423 *numResourceInterfaces = *numResourceInterfaces + 1;
2424 pointer = pointer->next;
2431 * Get name of resource interface of the resource.
2433 * @param handle - handle of resource
2434 * @param index - index of resource, 0 to Count - 1
2437 * resource interface name - if resource found
2438 * NULL - resource not found
2440 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
2441 OCResourceInterface *resourceInterface;
2443 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2445 resourceInterface = findResourceInterfaceAtIndex(handle, index);
2446 if (resourceInterface) {
2447 return resourceInterface->name;
2449 return (const char *) NULL;
2453 * Get resource handle from the collection resource by index.
2455 * @param collectionHandle - handle of collection resource
2456 * @param index - index of contained resource, 0 to Count - 1
2459 * handle to resource - if resource found
2460 * NULL - resource not found
2462 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2464 OCResource *resource;
2466 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2468 if (index >= MAX_CONTAINED_RESOURCES) {
2472 resource = findResource((OCResource *) collectionHandle);
2477 return resource->rsrcResources[index];
2481 * Bind an entity handler to the resource.
2483 * @param handle - handle to the resource that the contained resource is to be bound
2484 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2486 * OC_STACK_OK - no errors
2487 * OC_STACK_ERROR - stack process error
2489 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2490 OCEntityHandler entityHandler) {
2491 OCResource *resource;
2493 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2495 // Validate parameters
2496 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2497 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2499 // Use the handle to find the resource in the resource linked list
2500 resource = findResource((OCResource *)handle);
2502 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2503 return OC_STACK_ERROR;
2507 resource->entityHandler = entityHandler;
2509 #ifdef WITH_PRESENCE
2510 if(presenceResource.handle)
2512 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2513 SendPresenceNotification(resource->rsrcType);
2521 * Get the entity handler for a resource.
2523 * @param handle - handle of resource
2526 * entity handler - if resource found
2527 * NULL - resource not found
2529 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
2530 OCResource *resource;
2532 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2534 // Use the handle to find the resource in the resource linked list
2535 resource = findResource((OCResource *)handle);
2537 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2542 return resource->entityHandler;
2545 void incrementSequenceNumber(OCResource * resPtr)
2547 // Increment the sequence number
2548 resPtr->sequenceNum += 1;
2549 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2551 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2557 * Notify Presence subscribers that a resource has been modified
2559 * @param resourceType - Handle to the resourceType linked list of resource
2560 * that was modified.
2561 * @param qos - Quality Of Service
2564 #ifdef WITH_PRESENCE
2565 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
2567 OCResource *resPtr = NULL;
2568 OCStackResult result;
2569 OCMethod method = OC_REST_PRESENCE;
2570 uint32_t maxAge = 0;
2571 resPtr = findResource((OCResource *) presenceResource.handle);
2574 return OC_STACK_NO_RESOURCE;
2576 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
2578 maxAge = presenceResource.presenceTTL;
2585 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
2588 #endif // WITH_PRESENCE
2590 * Notify observers that an observed value has changed.
2592 * @param handle - handle of resource
2595 * OC_STACK_OK - no errors
2596 * OC_STACK_NO_RESOURCE - invalid resource handle
2597 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
2599 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
2601 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2603 OCResource *resPtr = NULL;
2604 OCStackResult result;
2605 OCMethod method = OC_REST_NOMETHOD;
2606 uint32_t maxAge = 0;
2608 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2609 #ifdef WITH_PRESENCE
2610 if(handle == presenceResource.handle)
2614 #endif // WITH_PRESENCE
2615 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2617 // Verify that the resource exists
2618 resPtr = findResource ((OCResource *) handle);
2621 return OC_STACK_NO_RESOURCE;
2625 //only increment in the case of regular observing (not presence)
2626 incrementSequenceNumber(resPtr);
2627 method = OC_REST_OBSERVE;
2628 maxAge = MAX_OBSERVE_AGE;
2629 #ifdef WITH_PRESENCE
2630 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
2632 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
2639 OCNotifyListOfObservers (OCResourceHandle handle,
2640 OCObservationId *obsIdList,
2641 uint8_t numberOfIds,
2642 unsigned char *notificationJSONPayload,
2643 OCQualityOfService qos)
2645 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
2647 OCResource *resPtr = NULL;
2648 //TODO: we should allow the server to define this
2649 uint32_t maxAge = MAX_OBSERVE_AGE;
2651 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2652 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
2653 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
2655 // Verify that the resource exists
2656 resPtr = findResource ((OCResource *) handle);
2657 if (NULL == resPtr || myStackMode == OC_CLIENT)
2659 return OC_STACK_NO_RESOURCE;
2663 incrementSequenceNumber(resPtr);
2665 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
2666 notificationJSONPayload, maxAge, qos));
2670 * Send a response to a request.
2671 * The response can be a regular, slow, or block (i.e. a response that
2672 * is too large to be sent in a single PDU and must span multiple transmissions)
2674 * @param response - pointer to structure that contains response parameters
2677 * OC_STACK_OK - No errors; Success
2678 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
2679 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
2680 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
2681 * persistent response buffer is necessary
2683 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
2685 OCStackResult result = OC_STACK_ERROR;
2686 OCServerRequest *serverRequest = NULL;
2688 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
2690 // Validate input parameters
2691 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
2692 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
2694 // TODO: Placeholder for creating a response entry when implementing
2695 // block transfer feature
2697 // If a response payload is present, check if block transfer is required
2698 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
2699 (const char *)ehResponse->payload, ehResponse->payloadSize))
2701 OC_LOG(INFO, TAG, PCF("Block transfer required"));
2703 // Persistent response buffer is needed for block transfer
2704 if (!ehResponse->persistentBufferFlag)
2706 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
2707 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
2709 // TODO: Placeholder for block transfer handling
2710 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
2711 // when implementing the block transfer feature
2716 // Get pointer to request info
2717 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
2720 result = serverRequest->ehResponseHandler(ehResponse);
2727 * Cancel a response. Applies to a block response
2729 * @param responseHandle - response handle set by stack in OCServerResponse after
2730 * OCDoResponse is called
2733 * OC_STACK_OK - No errors; Success
2734 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
2736 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
2738 OCStackResult result = OC_STACK_NOTIMPL;
2740 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
2742 // TODO: validate response handle
2747 //-----------------------------------------------------------------------------
2748 // Private internal function definitions
2749 //-----------------------------------------------------------------------------
2751 * Generate handle of OCDoResource invocation for callback management.
2753 static OCDoHandle GenerateInvocationHandle()
2755 OCDoHandle handle = NULL;
2756 // Generate token here, it will be deleted when the transaction is deleted
2757 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2760 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2765 #ifdef WITH_PRESENCE
2766 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
2767 OCResourceProperty resourceProperties, uint8_t enable)
2769 if (resourceProperties
2770 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
2771 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2772 return OC_STACK_INVALID_PARAM;
2776 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
2780 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
2787 * Initialize resource data structures, variables, etc.
2789 OCStackResult initResources() {
2790 OCStackResult result = OC_STACK_OK;
2791 // Init application resource vars
2792 headResource = NULL;
2793 // Init Virtual Resources
2794 #ifdef WITH_PRESENCE
2795 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
2796 //presenceResource.token = OCGenerateCoAPToken();
2797 result = OCCreateResource(&presenceResource.handle,
2798 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
2803 //make resource inactive
2804 result = OCChangeResourceProperty(
2805 &(((OCResource *) presenceResource.handle)->resourceProperties),
2812 * Add a resource to the end of the linked list of resources.
2814 * @param resource - resource to be added
2816 void insertResource(OCResource *resource) {
2817 OCResource *pointer;
2819 if (!headResource) {
2820 headResource = resource;
2822 pointer = headResource;
2824 while (pointer->next) {
2825 pointer = pointer->next;
2827 pointer->next = resource;
2829 resource->next = NULL;
2833 * Find a resource in the linked list of resources.
2835 * @param resource - resource to be found
2837 * NULL - resource not found
2838 * pointer to resource - pointer to resource that was found in the linked list
2840 OCResource *findResource(OCResource *resource) {
2841 OCResource *pointer = headResource;
2844 if (pointer == resource) {
2847 pointer = pointer->next;
2852 void deleteAllResources()
2854 OCResource *pointer = headResource;
2859 temp = pointer->next;
2860 #ifdef WITH_PRESENCE
2861 if(pointer != (OCResource *) presenceResource.handle)
2863 #endif // WITH_PRESENCE
2864 deleteResource(pointer);
2865 #ifdef WITH_PRESENCE
2867 #endif // WITH_PRESENCE
2871 #ifdef WITH_PRESENCE
2872 // Ensure that the last resource to be deleted is the presence resource. This allows for all
2873 // presence notification attributed to their deletion to be processed.
2874 deleteResource((OCResource *) presenceResource.handle);
2875 #endif // WITH_PRESENCE
2879 * Delete the resource from the linked list.
2881 * @param resource - resource to be deleted
2886 int deleteResource(OCResource *resource) {
2887 OCResource *prev = NULL;
2890 temp = headResource;
2892 if (temp == resource) {
2893 // Invalidate all Resource Properties.
2894 resource->resourceProperties = (OCResourceProperty) 0;
2895 #ifdef WITH_PRESENCE
2896 if(resource != (OCResource *) presenceResource.handle)
2898 #endif // WITH_PRESENCE
2899 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
2900 #ifdef WITH_PRESENCE
2903 if(presenceResource.handle)
2905 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2906 if(resource != (OCResource *) presenceResource.handle)
2908 SendPresenceNotification(resource->rsrcType);
2912 SendPresenceNotification(NULL);
2917 if (temp == headResource) {
2918 headResource = temp->next;
2920 prev->next = temp->next;
2923 deleteResourceElements(temp);
2936 * Delete all of the dynamically allocated elements that were created for the resource.
2938 * @param resource - specified resource
2940 void deleteResourceElements(OCResource *resource) {
2946 OCFree(resource->uri);
2948 // Delete resourcetype linked list
2949 deleteResourceType(resource->rsrcType);
2951 // Delete resourceinterface linked list
2952 deleteResourceInterface(resource->rsrcInterface);
2956 * Delete all of the dynamically allocated elements that were created for the resource type.
2958 * @param resourceType - specified resource type
2960 void deleteResourceType(OCResourceType *resourceType) {
2961 OCResourceType *pointer = resourceType;
2962 OCResourceType *next;
2965 next = pointer->next;
2966 OCFree(pointer->resourcetypename);
2973 * Delete all of the dynamically allocated elements that were created for the resource interface.
2975 * @param resourceInterface - specified resource interface
2977 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
2978 OCResourceInterface *pointer = resourceInterface;
2979 OCResourceInterface *next;
2982 next = pointer->next;
2983 OCFree(pointer->name);
2990 * Insert a resource type into a resource's resource type linked list.
2992 * @param resource - resource where resource type is to be inserted
2993 * @param resourceType - resource type to be inserted
2995 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
2996 OCResourceType *pointer;
2998 if (resource && !resource->rsrcType) {
2999 resource->rsrcType = resourceType;
3003 pointer = resource->rsrcType;
3007 pointer = resourceType;
3009 while (pointer->next) {
3010 pointer = pointer->next;
3012 pointer->next = resourceType;
3014 resourceType->next = NULL;
3018 * Get a resource type at the specified index within a resource.
3020 * @param handle - handle of resource
3021 * @param index - index of resource type
3024 * resourcetype - if found
3027 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
3028 OCResource *resource;
3029 OCResourceType *pointer;
3032 // Find the specified resource
3033 resource = findResource((OCResource *) handle);
3038 // Make sure a resource has a resourcetype
3039 if (!resource->rsrcType) {
3043 // Iterate through the list
3044 pointer = resource->rsrcType;
3046 while ((i < index) && pointer) {
3048 pointer = pointer->next;
3054 * Finds a resource type in an OCResourceType link-list.
3056 * @param resourceTypeList - the link-list to be searched through
3057 * @param resourceTypeName - the key to search for
3060 * resourceType that matches the key (ie. resourceTypeName)
3061 * NULL - either an invalid parameter or this function was unable to find the key.
3063 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3065 if(resourceTypeList && resourceTypeName)
3067 OCResourceType * rtPointer = resourceTypeList;
3068 while(resourceTypeName && rtPointer)
3070 if(rtPointer->resourcetypename &&
3071 strcmp(resourceTypeName, (const char *)
3072 (rtPointer->resourcetypename)) == 0)
3076 rtPointer = rtPointer->next;
3083 * Insert a resource interface into a resource's resource interface linked list.
3085 * @param resource - resource where resource interface is to be inserted
3086 * @param resourceInterface - resource interface to be inserted
3088 void insertResourceInterface(OCResource *resource,
3089 OCResourceInterface *resourceInterface) {
3090 OCResourceInterface *pointer;
3092 if (!resource->rsrcInterface) {
3093 resource->rsrcInterface = resourceInterface;
3095 pointer = resource->rsrcInterface;
3096 while (pointer->next) {
3097 pointer = pointer->next;
3099 pointer->next = resourceInterface;
3101 resourceInterface->next = NULL;
3105 * Get a resource interface at the specified index within a resource.
3107 * @param handle - handle of resource
3108 * @param index - index of resource interface
3111 * resourceinterface - if found
3114 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3116 OCResource *resource;
3117 OCResourceInterface *pointer;
3120 // Find the specified resource
3121 resource = findResource((OCResource *) handle);
3126 // Make sure a resource has a resourceinterface
3127 if (!resource->rsrcInterface) {
3131 // Iterate through the list
3132 pointer = resource->rsrcInterface;
3134 while ((i < index) && pointer) {
3136 pointer = pointer->next;
3142 * Determine if a request/response must be sent in a block transfer because it is too large to be
3143 * sent in a single PDU. This function can be used for either a request or a response
3145 * @param request - NULL or pointer to request
3146 * @param response - NULL or pointer to response
3147 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
3148 * the length of the request/response
3151 * 0 - packet transfer NOT required (i.e. normal request/response)
3152 * 1 - packet transfer required (i.e. block transfer needed)
3154 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
3158 // Determine if we are checking a request or a response
3161 // If size is greater than 0, use it for the request size value, otherwise
3162 // assume request is null terminated and use strlen for size value
3163 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
3170 // If size is greater than 0, use it for the response size value, otherwise
3171 // assume response is null terminated and use strlen for size value
3172 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3181 * Retrieves a resource type based upon a query ontains only just one
3182 * resource attribute (and that has to be of type "rt").
3184 * @remark This API malloc's memory for the resource type. Do not malloc resourceType
3185 * before passing in.
3187 * @param query - The quert part of the URI
3188 * @param resourceType - The resource type to be populated; pass by reference.
3191 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
3192 * OC_STACK_OK - Success
3194 OCStackResult getResourceType(const char * query, unsigned char** resourceType)
3198 return OC_STACK_INVALID_PARAM;
3201 OCStackResult result = OC_STACK_ERROR;
3203 if(strncmp(query, "rt=", 3) == 0)
3205 *resourceType = (unsigned char *) OCMalloc(strlen(query)-3);
3208 result = OC_STACK_NO_MEMORY;
3211 strcpy((char *)*resourceType, ((const char *)&query[3]));
3212 result = OC_STACK_OK;
3218 OCStackResult getQueryFromUri(const char * uri, unsigned char** query, char ** newURI)
3222 return OC_STACK_INVALID_URI;
3224 if(!query || !newURI)
3226 return OC_STACK_INVALID_PARAM;
3228 char * leftToken = NULL;
3229 char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3234 strcpy(tempURI, uri);
3236 leftToken = strtok_r((char *)tempURI, "?", &strTokPtr);
3238 //TODO-CA: This could be simplified. Clean up required.
3239 while(leftToken != NULL)
3241 if(strncmp(leftToken, "rt=", 3) == 0 || strncmp(leftToken, "if=", 3) == 0)
3243 *query = (unsigned char *) OCMalloc(strlen(leftToken));
3248 strcpy((char *)*query, ((const char *)&leftToken[0]));
3251 leftToken = strtok_r(NULL, "?", &strTokPtr);
3259 return OC_STACK_NO_MEMORY;
3262 const ServerID OCGetServerInstanceID(void)
3264 static bool generated = false;
3265 static ServerID sid;
3272 sid = OCGetRandom();
3277 const char* OCGetServerInstanceIDString(void)
3279 // max printed length of a base 10
3280 // uint32 is 10 characters, so 11 includes null.
3281 // This will change as the representation gets switched
3283 static char buffer[11];
3284 int n = sprintf(buffer, "%u", OCGetServerInstanceID());