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 // update response.addr appropriately from endPoint.addressInfo
242 void UpdateResponseAddr(OCClientResponse *response, const CARemoteEndpoint_t* endPoint)
244 struct sockaddr_in sa;
245 inet_pton(AF_INET, endPoint->addressInfo.IP.ipAddress, &(sa.sin_addr));
246 sa.sin_port = htons(endPoint->addressInfo.IP.port);
247 static OCDevAddr address;
248 memcpy((void*)&address.addr, &(sa), sizeof(sa));
249 response->addr = &address;
252 void HandlePresenceResponse(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
254 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
255 ClientCB * cbNode = NULL;
256 char *resourceTypeName = NULL;
258 char * bufRes = responseInfo->info.payload;
259 OCClientResponse *response = (OCClientResponse *) OCMalloc(sizeof(OCClientResponse));
261 UpdateResponseAddr(response, endPoint);
268 tok = strtok(bufRes, "[:]}");
269 bufRes[strlen(bufRes)] = ':';
270 tok = strtok(NULL, "[:]}");
271 bufRes[strlen((char *)bufRes)] = ':';
272 response->sequenceNumber = (uint32_t )atoi(tok);
273 tok = strtok(NULL, "[:]}");
274 tok = strtok(NULL, "[:]}");
277 resourceTypeName = (char *)OCMalloc(strlen(tok));
278 if(!resourceTypeName)
282 bufRes[strlen((char *)bufRes)] = ':';
283 strcpy(resourceTypeName, tok);
284 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
287 bufRes[strlen((char *)bufRes)] = ']';
289 response->resJSONPayload = responseInfo->info.payload;
290 response->result = OC_STACK_OK;
292 char *fullUri = (char *) OCMalloc(MAX_URI_LENGTH );
293 char *ipAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
295 strncpy(ipAddress, endPoint->addressInfo.IP.ipAddress, strlen(endPoint->addressInfo.IP.ipAddress));
296 ipAddress[strlen(endPoint->addressInfo.IP.ipAddress)] = '\0';
298 snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", ipAddress, endPoint->addressInfo.IP.port,
301 cbNode = GetClientCB(NULL, NULL, fullUri);
305 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response);
308 if (cbResult == OC_STACK_DELETE_TRANSACTION)
310 FindAndDeleteClientCB(cbNode);
317 OCFree(resourceTypeName);
321 //This function will be called back by CA layer when a response is received
322 void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
324 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
325 OCStackApplicationResult result = OC_STACK_DELETE_TRANSACTION;
326 if(strcmp(endPoint->resourceUri, OC_PRESENCE_URI) == 0)
328 HandlePresenceResponse(endPoint, responseInfo);
331 ClientCB *cbNode = GetClientCB((CAToken_t *)&responseInfo->info.token, NULL, NULL);
335 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
336 OCClientResponse response;
338 UpdateResponseAddr(&response, endPoint);
339 response.connType = endPoint->connectivityType;
341 response.result = CAToOCStackResult(responseInfo->result);
342 response.resJSONPayload = (unsigned char*)responseInfo->info.payload;
343 response.numRcvdVendorSpecificHeaderOptions = 0;
344 if(responseInfo->info.numOptions > 0)
346 //First option alwas with option ID COAP_OPTION_OBSERVE if it is availbale
347 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
349 memcpy (&(response.sequenceNumber),
350 &(responseInfo->info.options[0].optionData), 4);
354 memcpy (&(response.rcvdVendorSpecificHeaderOptions[0]),
355 &(responseInfo->info.options[0]), sizeof(OCHeaderOption));
357 for (uint8_t i = 1; i < responseInfo->info.numOptions; i++)
359 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i]),
360 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
362 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
364 result = cbNode->callBack(cbNode->context,
365 cbNode->handle, &response);
366 if (result == OC_STACK_DELETE_TRANSACTION)
368 FindAndDeleteClientCB(cbNode);
371 OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload);
372 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
375 //This function will be called back by CA layer when a request is received
376 void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
378 CAInfo_t responseData;
379 CAResponseInfo_t responseInfo;
380 OCStackResult requestResult = OC_STACK_ERROR;
382 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
385 if(myStackMode == OC_CLIENT)
387 //TODO: should the client be responding to requests?
391 OCServerProtocolRequest serverRequest;
393 memset (&serverRequest, 0, sizeof(OCServerProtocolRequest));
394 OC_LOG_V(INFO, TAG, PCF("***** Endpoint URI ***** : %s\n"), (char*)endPoint->resourceUri);
396 char * newUri = (char *)endPoint->resourceUri;
397 unsigned char * query = NULL;
398 unsigned char * resourceType = NULL;
399 getQueryFromUri(endPoint->resourceUri, &query, &newUri);
400 OC_LOG_V(INFO, TAG, PCF("**********URI without query ****: %s\n"), newUri);
401 OC_LOG_V(INFO, TAG, PCF("**********Query ****: %s\n"), query);
403 memcpy (&(serverRequest.resourceUrl), newUri, strlen(newUri));
407 memcpy (&(serverRequest.query), query, strlen(query));
409 //copy request payload
410 if (requestInfo->info.payload)
412 serverRequest.reqTotalSize = strlen(requestInfo->info.payload) + 1;
413 memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
414 strlen(requestInfo->info.payload));
415 serverRequest.reqTotalSize = strlen((const char *)requestInfo->info.payload) + 1;
419 serverRequest.reqTotalSize = 1;
422 switch (requestInfo->method)
426 serverRequest.method = OC_REST_GET;
431 serverRequest.method = OC_REST_PUT;
436 serverRequest.method = OC_REST_POST;
441 serverRequest.method = OC_REST_DELETE;
446 OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
452 OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d", strlen(requestInfo->info.token));
453 OC_LOG_BUFFER(INFO, TAG, requestInfo->info.token, strlen(requestInfo->info.token));
454 // TODO-CA: For CA integration currently copying CAToken to OCCoapToken:
455 // Need to remove OCCoapToken
456 memcpy (&(serverRequest.requestToken.token), requestInfo->info.token,
457 strlen(requestInfo->info.token));
458 serverRequest.requestToken.tokenLength = strlen(requestInfo->info.token);
460 if (requestInfo->info.type == CA_MSG_CONFIRM)
462 serverRequest.qos = OC_HIGH_QOS;
464 else if (requestInfo->info.type == CA_MSG_NONCONFIRM)
466 serverRequest.qos = OC_LOW_QOS;
468 else if (requestInfo->info.type == CA_MSG_ACKNOWLEDGE)
470 // TODO-CA: Need to handle this
472 else if (requestInfo->info.type == CA_MSG_RESET)
474 // TODO-CA: Need to handle this
476 // CA does not need the following 3 fields
477 serverRequest.coapID = 0;
478 serverRequest.delayedResNeeded = 0;
479 serverRequest.secured = endPoint->isSecured;
482 serverRequest.addressInfo = endPoint->addressInfo;
483 serverRequest.connectivityType = endPoint->connectivityType;
484 if (requestInfo->info.token)
486 strncpy(serverRequest.token, requestInfo->info.token, sizeof(serverRequest.token) - 1);
489 // copy vendor specific header options
490 // TODO-CA: CA is including non-vendor header options as well, like observe.
491 // Need to filter those out
492 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &(requestInfo->info.numOptions));
493 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
495 // TODO-CA: Need to send an error indicating the num of options is incorrect
498 serverRequest.numRcvdVendorSpecificHeaderOptions = requestInfo->info.numOptions;
499 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
501 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
502 sizeof(CAHeaderOption_t)*requestInfo->info.numOptions);
505 requestResult = HandleStackRequests (&serverRequest);
508 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
513 //This function will be called back by occoap layer when a request is received
514 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
516 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
517 OCStackResult result = OC_STACK_ERROR;
518 ResourceHandling resHandling;
519 OCResource *resource;
521 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
524 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
526 result = AddServerCARequest(&request, protocolRequest->coapID,
527 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
528 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
529 protocolRequest->observationOption, protocolRequest->qos,
530 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
531 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
532 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
533 protocolRequest->reqTotalSize,
534 &protocolRequest->addressInfo, protocolRequest->connectivityType, protocolRequest->token);
536 result = AddServerRequest(&request, protocolRequest->coapID,
537 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
538 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
539 protocolRequest->observationOption, protocolRequest->qos,
540 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
541 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
542 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
543 protocolRequest->reqTotalSize);
545 if (OC_STACK_OK != result)
547 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
550 VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
552 if(!protocolRequest->reqMorePacket)
554 request->requestComplete = 1;
559 OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
562 if(request->requestComplete)
564 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
565 result = DetermineResourceHandling (request, &resHandling, &resource);
566 if (result == OC_STACK_OK)
568 result = ProcessRequest(resHandling, resource, request);
572 result = OC_STACK_ERROR;
577 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
578 result = OC_STACK_CONTINUE;
583 //This function will be called back by occoap layer when a response is received
584 OCStackResult HandleStackResponses(OCResponse * response)
586 OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)"));
587 OCStackResult result = OC_STACK_OK;
588 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
589 uint8_t isObserveNotification = 0;
590 ClientCB * cbNode = NULL;
592 uint8_t isPresenceNotification = 0;
593 uint8_t isMulticastPresence = 0;
594 char * resourceTypeName = NULL;
595 uint32_t lowerBound = 0;
596 uint32_t higherBound = 0;
598 unsigned char * bufRes = response->bufRes;
599 #endif // WITH_PRESENCE
601 cbNode = response->cbNode;
604 cbNode = GetClientCB(response->rcvdToken, NULL, NULL);
607 if(response->clientResponse->sequenceNumber >= OC_OFFSET_SEQUENCE_NUMBER)
609 isObserveNotification = 1;
610 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
613 OC_LOG_V(DEBUG, TAG, "The sequenceNumber/NONCE of this response %u",
614 response->clientResponse->sequenceNumber);
615 OC_LOG_V(DEBUG, TAG, "The maxAge/TTL of this response %u", response->maxAge);
616 OC_LOG_V(DEBUG, TAG, "The response received is %s", bufRes);
619 if(!strcmp((char *)response->rcvdUri, (char *)OC_PRESENCE_URI)){
620 isPresenceNotification = 1;
623 result = OC_STACK_INVALID_PARAM;
626 tok = strtok((char *)bufRes, "[:]}");
627 bufRes[strlen((char *)bufRes)] = ':';
628 tok = strtok(NULL, "[:]}");
629 bufRes[strlen((char *)bufRes)] = ':';
630 response->clientResponse->sequenceNumber = (uint32_t )atoi(tok);
631 OC_LOG_V(DEBUG, TAG, "The received NONCE is %u", response->clientResponse->sequenceNumber);
632 tok = strtok(NULL, "[:]}");
633 response->maxAge = (uint32_t )atoi(tok);
634 OC_LOG_V(DEBUG, TAG, "The received TTL is %u", response->maxAge);
635 tok = strtok(NULL, "[:]}");
638 resourceTypeName = (char *)OCMalloc(strlen(tok));
639 if(!resourceTypeName)
643 bufRes[strlen((char *)bufRes)] = ':';
644 strcpy(resourceTypeName, tok);
645 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
648 bufRes[strlen((char *)bufRes)] = ']';
651 // Check if the application subcribed for presence
654 cbNode = GetClientCB(NULL, NULL, response->fullUri);
657 // Check if application subscribed for multicast presence
660 snprintf((char *)response->fullUri, MAX_URI_LENGTH, "%s%s",
661 OC_MULTICAST_IP, response->rcvdUri);
662 cbNode = GetClientCB(NULL, NULL, response->fullUri);
665 isMulticastPresence = 1;
666 isPresenceNotification = 0;
670 if(cbNode && isPresenceNotification)
672 OC_LOG(INFO, TAG, PCF("Received a presence notification"));
673 if(!cbNode->presence)
675 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
676 VERIFY_NON_NULL_V(cbNode->presence);
677 cbNode->presence->timeOut = NULL;
678 cbNode->presence->timeOut = (uint32_t *)
679 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
680 if(!(cbNode->presence->timeOut)){
681 OCFree(cbNode->presence);
682 result = OC_STACK_NO_MEMORY;
685 if(response->maxAge == 0)
687 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
688 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
691 OCFree(cbNode->presence->timeOut);
692 OCFree(cbNode->presence);
693 cbNode->presence = NULL;
698 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %d", GetTime(0));
699 cbNode->presence->TTL = response->maxAge;
700 for(int index = 0; index < PresenceTimeOutSize; index++)
702 lowerBound = GetTime(((float)(PresenceTimeOut[index])
703 /(float)100)*(float)cbNode->presence->TTL);
704 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
705 /(float)100)*(float)cbNode->presence->TTL);
706 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
707 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
708 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
709 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
710 cbNode->presence->timeOut[index]);
712 cbNode->presence->TTLlevel = 0;
713 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
714 if(cbNode->sequenceNumber == response->clientResponse->sequenceNumber)
716 OC_LOG(INFO, TAG, PCF("===============No presence change"));
719 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
720 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;;
723 // Ensure that a filter is actually applied.
724 if(resourceTypeName && cbNode->filterResourceType)
726 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
732 else if(cbNode && isMulticastPresence)
734 // Check if the same nonce for a given host
735 OCMulticastNode* mcNode = NULL;
736 mcNode = GetMCPresenceNode(response->fullUri);
738 if(response->maxAge == 0)
740 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
741 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
744 OCFree(cbNode->presence->timeOut);
745 OCFree(cbNode->presence);
746 cbNode->presence = NULL;
749 else if(mcNode != NULL)
751 if(mcNode->nonce == response->clientResponse->sequenceNumber)
753 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
754 result = OC_STACK_NO_MEMORY;
757 mcNode->nonce = response->clientResponse->sequenceNumber;
761 uint32_t uriLen = strlen((char*)response->fullUri);
762 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
765 memcpy(uri, response->fullUri, (uriLen + 1));
770 PCF("===============No Memory for URI to store in the presence node"));
771 result = OC_STACK_NO_MEMORY;
774 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri,
775 response->clientResponse->sequenceNumber);
776 if(result == OC_STACK_NO_MEMORY)
779 PCF("===============No Memory for Multicast Presence Node"));
780 result = OC_STACK_NO_MEMORY;
785 // Ensure that a filter is actually applied.
786 if(resourceTypeName && cbNode->filterResourceType)
788 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
795 else if(!cbNode && isPresenceNotification)
797 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
798 ------------ ignoring"));
800 #endif // WITH_PRESENCE
804 if(isObserveNotification)
806 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
807 //TODO: check the standard for methods to detect wrap around condition
808 if(cbNode->method == OC_REST_OBSERVE &&
809 (response->clientResponse->sequenceNumber <= cbNode->sequenceNumber ||
810 (response->clientResponse->sequenceNumber > cbNode->sequenceNumber &&
811 response->clientResponse->sequenceNumber ==
812 MAX_SEQUENCE_NUMBER)))
814 OC_LOG_V(DEBUG, TAG, "Observe notification came out of order. \
815 Ignoring Incoming:%d Against Current:%d.",
816 response->clientResponse->sequenceNumber, cbNode->sequenceNumber);
819 if(response->clientResponse->sequenceNumber > cbNode->sequenceNumber){
820 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;
824 response->clientResponse->resJSONPayload = bufRes;
826 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response->clientResponse);
828 if (cbResult == OC_STACK_DELETE_TRANSACTION ||
829 response->clientResponse->result == OC_STACK_COMM_ERROR ||
830 (response->clientResponse->result == OC_STACK_RESOURCE_DELETED &&
831 !isPresenceNotification && !isMulticastPresence))
833 FindAndDeleteClientCB(cbNode);
838 result = OC_STACK_ERROR;
843 OCFree(resourceTypeName);
848 int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
851 unsigned char *itr, *coap;
852 uint8_t dotCount = 0;
856 /* search for scheme */
858 if (!isdigit((unsigned char) *ipAddrStr))
860 coap = (unsigned char *) OC_COAP_SCHEME;
861 while (*coap && tolower(*itr) == *coap)
870 if (isdigit((unsigned char) *ipAddrStr))
873 ipAddr[index] += *ipAddrStr - '0';
875 else if ((unsigned char) *ipAddrStr == '.')
887 if(*ipAddrStr == ':')
891 if (isdigit((unsigned char) *ipAddrStr))
894 *port += *ipAddrStr - '0';
905 if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
916 //-----------------------------------------------------------------------------
917 // Private internal function prototypes
918 //-----------------------------------------------------------------------------
920 static OCDoHandle GenerateInvocationHandle();
921 static OCStackResult initResources();
922 static void insertResource(OCResource *resource);
923 static OCResource *findResource(OCResource *resource);
924 static void insertResourceType(OCResource *resource,
925 OCResourceType *resourceType);
926 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
928 static void insertResourceInterface(OCResource *resource,
929 OCResourceInterface *resourceInterface);
930 static OCResourceInterface *findResourceInterfaceAtIndex(
931 OCResourceHandle handle, uint8_t index);
932 static void deleteResourceType(OCResourceType *resourceType);
933 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
934 static void deleteResourceElements(OCResource *resource);
935 static int deleteResource(OCResource *resource);
936 static void deleteAllResources();
937 static void incrementSequenceNumber(OCResource * resPtr);
938 static OCStackResult verifyUriQueryLength(const char * inputUri,
940 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
941 OCStackResult getResourceType(const char * query, unsigned char** resourceType);
943 //-----------------------------------------------------------------------------
945 //-----------------------------------------------------------------------------
948 * Initialize the OC Stack. Must be called prior to starting the stack.
951 * IP Address of host device
953 * Port of host device
955 * Host device is client, server, or client-server
958 * OC_STACK_OK - no errors
959 * OC_STACK_ERROR - stack init error
961 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
963 OCStackResult result = OC_STACK_ERROR;
964 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
968 OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
974 //It is ok to select network to CA_WIFI for now
975 CAResult_t caResult = CASelectNetwork(CA_WIFI|CA_ETHERNET);
976 if(caResult == CA_STATUS_OK)
978 OC_LOG(INFO, TAG, PCF("CASelectNetwork to WIFI"));
979 caResult = CARegisterHandler(HandleCARequests, HandleCAResponses);
980 if(caResult == CA_STATUS_OK)
982 OC_LOG(INFO, TAG, PCF("CARegisterHandler..."));
983 stackState = OC_STACK_INITIALIZED;
984 result = OC_STACK_OK;
988 caResult = CAStartDiscoveryServer();
989 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
992 caResult = CAStartListeningServer();
993 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
995 case OC_CLIENT_SERVER:
996 caResult = CAStartListeningServer();
997 if(caResult == CA_STATUS_OK)
999 caResult = CAStartDiscoveryServer();
1001 OC_LOG(INFO, TAG, PCF("Client-server mode"));
1004 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1005 return OC_STACK_ERROR;
1010 if (caResult == CA_STATUS_OK)
1012 result = OC_STACK_OK;
1016 result = OC_STACK_ERROR;
1023 OC_LOG(INFO, TAG, PCF("Client mode"));
1026 OC_LOG(INFO, TAG, PCF("Server mode"));
1028 case OC_CLIENT_SERVER:
1029 OC_LOG(INFO, TAG, PCF("Client-server mode"));
1032 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1033 return OC_STACK_ERROR;
1037 // Make call to OCCoAP layer
1038 result = OCInitCoAP(ipAddr, (uint16_t) port, myStackMode);
1042 defaultDeviceHandler = NULL;
1044 #ifdef WITH_PRESENCE
1045 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
1046 #endif // WITH_PRESENCE
1048 if (result == OC_STACK_OK)
1050 stackState = OC_STACK_INITIALIZED;
1052 // Initialize resource
1053 if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
1055 result = initResources();
1057 if(result != OC_STACK_OK)
1059 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1065 * Stop the OC stack. Use for a controlled shutdown.
1067 * OC_STACK_OK - no errors
1068 * OC_STACK_ERROR - stack not initialized
1070 OCStackResult OCStop()
1072 OCStackResult result = OC_STACK_ERROR;
1074 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1076 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1078 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1081 else if (stackState != OC_STACK_INITIALIZED)
1083 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1084 return OC_STACK_ERROR;
1087 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1089 #ifdef WITH_PRESENCE
1090 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1091 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1092 presenceResource.presenceTTL = 0;
1093 #endif // WITH_PRESENCE
1095 // Free memory dynamically allocated for resources
1096 deleteAllResources();
1099 // Make call to OCCoAP layer
1100 if (OCStopCoAP() == OC_STACK_OK)
1102 // Remove all observers
1103 DeleteObserverList();
1104 // Remove all the client callbacks
1105 DeleteClientCBList();
1106 stackState = OC_STACK_UNINITIALIZED;
1107 result = OC_STACK_OK;
1109 stackState = OC_STACK_INITIALIZED;
1110 result = OC_STACK_ERROR;
1113 // Deinit security blob
1114 DeinitOCSecurityInfo();
1116 if (result != OC_STACK_OK) {
1117 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
1124 * Verify the lengths of the URI and the query separately
1126 * @param inputUri - Input URI and query.
1127 * @param uriLen - The length of the initial URI with query.
1129 * Note: The '?' that appears after the URI is not considered as
1130 * a part of the query.
1132 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1136 query = strchr (inputUri, '?');
1140 if((query - inputUri) > MAX_URI_LENGTH)
1142 return OC_STACK_INVALID_URI;
1145 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1147 return OC_STACK_INVALID_QUERY;
1150 else if(uriLen > MAX_URI_LENGTH)
1152 return OC_STACK_INVALID_URI;
1158 * Discover or Perform requests on a specified resource (specified by that Resource's respective URI).
1160 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of calling this API.
1161 * @param method - @ref OCMethod to perform on the resource
1162 * @param requiredUri - URI of the resource to interact with
1163 * @param referenceUri - URI of the reference resource
1164 * @param request - JSON encoded request
1165 * @param qos - quality of service
1166 * @param cbData - struct that contains asynchronous callback function that is invoked
1167 * by the stack when discovery or resource interaction is complete
1168 * @param options - The address of an array containing the vendor specific header
1169 * header options to be sent with the request
1170 * @param numOptions - Number of vendor specific header options to be included
1173 * OC_STACK_OK - no errors
1174 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
1175 * OC_STACK_INVALID_METHOD - invalid resource method
1176 * OC_STACK_INVALID_URI - invalid required or reference URI
1179 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1180 const char *referenceUri, const char *request, uint8_t conType,
1181 OCQualityOfService qos, OCCallbackData *cbData,
1182 OCHeaderOption * options, uint8_t numOptions)
1184 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1185 const char *referenceUri, const char *request,
1186 OCQualityOfService qos, OCCallbackData *cbData,
1187 OCHeaderOption * options, uint8_t numOptions)
1190 OCStackResult result = OC_STACK_ERROR;
1192 ClientCB *clientCB = NULL;
1193 unsigned char * requestUri = NULL;
1194 unsigned char * resourceType = NULL;
1195 unsigned char * query = NULL;
1196 char * newUri = (char *)requiredUri;
1197 (void) referenceUri;
1199 CARemoteEndpoint_t* endpoint = NULL;
1200 CAResult_t caResult;
1201 CAToken_t caToken = NULL;
1202 CAInfo_t requestData;
1203 CARequestInfo_t requestInfo;
1204 CAGroupEndpoint_t grpEnd;
1206 // To track if memory is allocated for additional header options
1207 uint8_t hdrOptionMemAlloc = 0;
1210 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1212 // Validate input parameters
1213 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1214 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1216 TODO ("Need to form the final query by concatenating require and reference URI's");
1217 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
1219 uint16_t uriLen = strlen(requiredUri);
1221 // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS
1227 case OC_REST_DELETE:
1228 case OC_REST_OBSERVE:
1229 case OC_REST_OBSERVE_ALL:
1230 case OC_REST_CANCEL_OBSERVE:
1232 #ifdef WITH_PRESENCE
1233 case OC_REST_PRESENCE:
1237 result = OC_STACK_INVALID_METHOD;
1241 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
1246 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
1248 result = OC_STACK_INVALID_PARAM;
1252 #ifdef WITH_PRESENCE
1253 if(method == OC_REST_PRESENCE)
1255 // Replacing method type with GET because "presence" is a stack layer only implementation.
1256 method = OC_REST_GET;
1257 result = getQueryFromUri(requiredUri, &query, &newUri);
1260 result = getResourceType((char *) query, &resourceType);
1263 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1267 OC_LOG(DEBUG, TAG, PCF("Resource type is NULL."));
1272 OC_LOG(DEBUG, TAG, PCF("Query string is NULL."));
1274 if(result != OC_STACK_OK)
1279 #endif // WITH_PRESENCE
1281 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
1284 memcpy(requestUri, newUri, (uriLen + 1));
1288 result = OC_STACK_NO_MEMORY;
1292 *handle = GenerateInvocationHandle();
1295 result = OC_STACK_NO_MEMORY;
1300 memset(&requestData, 0, sizeof(CAInfo_t));
1301 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1302 memset(&grpEnd, 0, sizeof(CAGroupEndpoint_t));
1306 case OC_REST_OBSERVE:
1307 case OC_REST_OBSERVE_ALL:
1308 case OC_REST_CANCEL_OBSERVE:
1310 requestInfo.method = CA_GET;
1315 requestInfo.method = CA_PUT;
1320 requestInfo.method = CA_POST;
1323 case OC_REST_DELETE:
1325 requestInfo.method = CA_DELETE;
1328 #ifdef WITH_PRESENCE
1329 case OC_REST_PRESENCE:
1330 //TODO-CA: What should be the CA method?
1334 result = OC_STACK_INVALID_METHOD;
1338 //High QoS is not supported
1339 if(qos == OC_HIGH_QOS)
1341 result = OC_STACK_INVALID_PARAM;
1344 // TODO-CA: Handle multi-cast scenario
1345 // Create remote end point
1346 caResult = CACreateRemoteEndpoint(newUri, conType, &endpoint);
1347 // TODO-CA: Connectivity type should be passed to API
1348 endpoint->connectivityType = conType;
1350 if (caResult != CA_STATUS_OK)
1352 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1357 caResult = CAGenerateToken(&caToken);
1359 //TODO-CA Remove this temporary fix (for some reason same token is being generated)
1362 caToken[0] += count;
1364 if (caResult != CA_STATUS_OK)
1366 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1371 // TODO-CA: Map QoS to the right CA msg type
1372 requestData.type = CA_MSG_NONCONFIRM;
1373 requestData.token = caToken;
1374 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1376 result = CreateObserveHeaderOption (&(requestData.options), options,
1377 numOptions, OC_OBSERVE_REGISTER);
1378 if (result != OC_STACK_OK)
1382 hdrOptionMemAlloc = 1;
1383 requestData.numOptions = numOptions + 1;
1387 requestData.options = (CAHeaderOption_t*)options;
1388 requestData.numOptions = numOptions;
1390 requestData.payload = (char *)request;
1392 requestInfo.info = requestData;
1395 //TODO-CA Change This logic. Currently hardcoded to WIFI & ETHERNET
1396 //Need to support other adapter types.
1397 if(conType == (CA_WIFI | CA_ETHERNET))
1399 //TODO-CA remove hardcoded resource uri. Instead, extract it from newUri
1400 grpEnd.connectivityType = conType;
1401 grpEnd.resourceUri = "/oc/core";
1403 caResult = CASendRequestToAll(&grpEnd, &requestInfo);
1407 caResult = CASendRequest(endpoint, &requestInfo);
1409 if (caResult != CA_STATUS_OK)
1411 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1415 if((result = AddClientCB(&clientCB, cbData, &caToken, handle, method,
1416 requestUri, resourceType)) != OC_STACK_OK)
1418 result = OC_STACK_NO_MEMORY;
1424 // Generate token which will be used by OCStack to match responses received
1426 OCGenerateCoAPToken(&token);
1428 if((result = AddClientCB(&clientCB, cbData, &token, handle, method, requestUri, resourceType))
1431 result = OC_STACK_NO_MEMORY;
1435 // Make call to OCCoAP layer
1436 result = OCDoCoAPResource(method, qos, &token, newUri, request, options, numOptions);
1440 if(newUri != requiredUri)
1444 if (result != OC_STACK_OK)
1446 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1447 FindAndDeleteClientCB(clientCB);
1450 CADestroyRemoteEndpoint(endpoint);
1451 if (hdrOptionMemAlloc)
1453 OCFree(requestData.options);
1460 * Cancel a request associated with a specific @ref OCDoResource invocation.
1462 * @param handle - Used to identify a specific OCDoResource invocation.
1463 * @param qos - used to specify Quality of Service (read below for more info)
1464 * @param options- used to specify vendor specific header options when sending
1465 * explicit observe cancellation
1466 * @param numOptions- Number of header options to be included
1469 * OC_STACK_OK - No errors; Success
1470 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1472 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1476 * This ftn is implemented one of two ways in the case of observation:
1478 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1479 * Remove the callback associated on client side.
1480 * When the next notification comes in from server,
1481 * reply with RESET message to server.
1482 * Keep in mind that the server will react to RESET only
1483 * if the last notification was sent ans CON
1485 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1486 * and it is associated with an observe request
1487 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1488 * Send CON Observe request to server with
1489 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1490 * Remove the callback associated on client side.
1492 OCStackResult ret = OC_STACK_OK;
1494 CARemoteEndpoint_t* endpoint = NULL;
1495 CAResult_t caResult;
1496 CAInfo_t requestData;
1497 CARequestInfo_t requestInfo;
1498 // Track if memory is allocated for additional header options
1499 uint8_t hdrOptionMemAlloc = 0;
1503 return OC_STACK_INVALID_PARAM;
1506 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1508 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1511 switch (clientCB->method)
1513 case OC_REST_OBSERVE:
1514 case OC_REST_OBSERVE_ALL:
1516 caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri, CA_WIFI,
1518 endpoint->connectivityType = CA_WIFI;
1519 if (caResult != CA_STATUS_OK)
1521 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1522 return OC_STACK_ERROR;
1525 memset(&requestData, 0, sizeof(CAInfo_t));
1526 // TODO-CA: Map QoS to the right CA msg type
1527 requestData.type = CA_MSG_NONCONFIRM;
1528 requestData.token = clientCB->token;
1529 if (CreateObserveHeaderOption (&(requestData.options),
1530 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
1532 return OC_STACK_ERROR;
1534 hdrOptionMemAlloc = 1;
1535 requestData.numOptions = numOptions + 1;
1536 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1537 requestInfo.method = CA_GET;
1538 requestInfo.info = requestData;
1540 caResult = CASendRequest(endpoint, &requestInfo);
1541 if (caResult != CA_STATUS_OK)
1543 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1545 if(caResult == CA_STATUS_OK)
1550 if(qos == OC_HIGH_QOS)
1552 ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
1553 &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
1558 FindAndDeleteClientCB(clientCB);
1562 #ifdef WITH_PRESENCE
1563 case OC_REST_PRESENCE:
1564 FindAndDeleteClientCB(clientCB);
1568 return OC_STACK_INVALID_METHOD;
1572 CADestroyRemoteEndpoint(endpoint);
1573 if (hdrOptionMemAlloc)
1575 OCFree(requestData.options);
1581 #ifdef WITH_PRESENCE
1582 OCStackResult OCProcessPresence()
1584 OCStackResult result = OC_STACK_OK;
1585 uint8_t ipAddr[4] = { 0 };
1588 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1589 ClientCB* cbNode = NULL;
1591 OCClientResponse clientResponse;
1592 OCResponse * response = NULL;
1594 LL_FOREACH(cbList, cbNode) {
1595 if(OC_REST_PRESENCE == cbNode->method)
1597 if(cbNode->presence)
1599 uint32_t now = GetTime(0);
1600 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
1601 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1604 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1609 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1610 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1611 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1614 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1616 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1617 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1619 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1621 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
1622 (OCDevAddr *) &dst, 0, NULL);
1623 if(result != OC_STACK_OK)
1627 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1628 &cbNode->token, &clientResponse, NULL);
1629 if(result != OC_STACK_OK)
1634 // Increment the TTLLevel (going to a next state), so we don't keep
1635 // sending presence notification to client.
1636 cbNode->presence->TTLlevel++;
1637 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1638 cbNode->presence->TTLlevel);
1642 result = OC_STACK_INVALID_IP;
1645 HandleStackResponses(response);
1647 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1649 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
1651 OCGenerateCoAPToken(&token);
1652 result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
1653 &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
1654 if(result != OC_STACK_OK)
1658 cbNode->presence->TTLlevel++;
1659 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
1665 if (result != OC_STACK_OK)
1667 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
1674 * Called in main loop of OC client or server. Allows low-level processing of
1678 * OC_STACK_OK - no errors
1679 * OC_STACK_ERROR - stack process error
1681 OCStackResult OCProcess() {
1683 OC_LOG(INFO, TAG, PCF("Entering OCProcess"));
1684 #ifdef WITH_PRESENCE
1685 OCProcessPresence();
1688 CAHandleRequestResponse();
1696 #ifdef WITH_PRESENCE
1698 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
1699 * presence notifications to clients via multicast. Once this API has been called with a success,
1700 * clients may query for this server's presence and this server's stack will respond via multicast.
1702 * Server can call this function when it comes online for the first time, or when it comes back
1703 * online from offline mode, or when it re enters network.
1705 * @param ttl - Time To Live in seconds
1706 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
1709 * OC_STACK_OK - No errors; Success
1711 OCStackResult OCStartPresence(const uint32_t ttl)
1713 OCChangeResourceProperty(
1714 &(((OCResource *)presenceResource.handle)->resourceProperties),
1719 presenceResource.presenceTTL = ttl;
1722 if(OC_PRESENCE_UNINITIALIZED == presenceState)
1724 OCDevAddr multiCastAddr;
1727 presenceState = OC_PRESENCE_INITIALIZED;
1728 OCGenerateCoAPToken(&token);
1729 OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
1731 CAAddress_t addressInfo;
1732 strncpy(addressInfo.IP.ipAddress, "224.0.1.187", CA_IPADDR_SIZE);
1733 addressInfo.IP.port = 5298;
1735 CAToken_t caToken = NULL;
1736 CAGenerateToken(&caToken);
1738 AddCAObserver(OC_PRESENCE_URI, NULL, 0, &token,
1739 &multiCastAddr, (OCResource *)presenceResource.handle, OC_LOW_QOS,
1740 &addressInfo, CA_WIFI, caToken);
1742 //add the presence observer
1743 AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
1744 (OCResource *)presenceResource.handle, OC_LOW_QOS);
1748 // Each time OCStartPresence is called
1749 // a different random 32-bit integer number is used
1750 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1752 return SendPresenceNotification(NULL);
1756 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
1757 * presence notifications to clients via multicast. Once this API has been called with a success,
1758 * this server's stack will not respond to clients querying for this server's presence.
1760 * Server can call this function when it is terminating, going offline, or when going
1761 * away from network.
1764 * OC_STACK_OK - No errors; Success
1766 OCStackResult OCStopPresence()
1768 OCStackResult result = OC_STACK_ERROR;
1769 //make resource inactive
1770 result = OCChangeResourceProperty(
1771 &(((OCResource *) presenceResource.handle)->resourceProperties),
1773 result = SendPresenceNotification(NULL);
1780 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
1782 defaultDeviceHandler = entityHandler;
1787 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
1789 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
1791 if(myStackMode == OC_CLIENT)
1793 return OC_STACK_ERROR;
1796 return SaveDeviceInfo(deviceInfo);
1802 * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource
1803 * @param resourceTypeName - name of resource type. Example: "core.led"
1804 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1805 * @param uri - URI of the resource. Example: "/a/led"
1806 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1807 * NULL for default entity handler
1808 * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE
1811 * OC_STACK_OK - no errors
1812 * OC_STACK_ERROR - stack process error
1814 OCStackResult OCCreateResource(OCResourceHandle *handle,
1815 const char *resourceTypeName,
1816 const char *resourceInterfaceName,
1817 const char *uri, OCEntityHandler entityHandler,
1818 uint8_t resourceProperties) {
1820 OCResource *pointer = NULL;
1823 OCStackResult result = OC_STACK_ERROR;
1825 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
1827 if(myStackMode == OC_CLIENT)
1831 // Validate parameters
1832 if(!uri || (strlen(uri) == 0))
1834 OC_LOG(ERROR, TAG, PCF("URI is invalid"));
1835 return OC_STACK_INVALID_URI;
1837 // Is it presented during resource discovery?
1838 if (!handle || !resourceTypeName) {
1839 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
1840 return OC_STACK_INVALID_PARAM;
1843 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
1844 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
1847 // Make sure resourceProperties bitmask has allowed properties specified
1848 if (resourceProperties
1849 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
1850 OC_LOG(ERROR, TAG, PCF("Invalid property"));
1851 return OC_STACK_INVALID_PARAM;
1854 // If the headResource is NULL, then no resources have been created...
1855 pointer = headResource;
1857 // At least one resources is in the resource list, so we need to search for
1858 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
1860 if (strcmp(uri, pointer->uri) == 0) {
1861 OC_LOG(ERROR, TAG, PCF("URI already in use"));
1862 return OC_STACK_INVALID_PARAM;
1864 pointer = pointer->next;
1867 // Create the pointer and insert it into the resource list
1868 pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
1872 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
1874 insertResource(pointer);
1877 size = strlen(uri) + 1;
1878 str = (char *) OCMalloc(size);
1882 strncpy(str, uri, size);
1885 // Set properties. Set OC_ACTIVE
1886 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
1889 // Add the resourcetype to the resource
1890 result = BindResourceTypeToResource(pointer, resourceTypeName);
1891 if (result != OC_STACK_OK) {
1892 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
1896 // Add the resourceinterface to the resource
1897 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
1898 if (result != OC_STACK_OK) {
1899 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
1903 // If an entity handler has been passed, attach it to the newly created
1904 // resource. Otherwise, set the default entity handler.
1907 pointer->entityHandler = entityHandler;
1911 pointer->entityHandler = defaultResourceEHandler;
1915 result = OC_STACK_OK;
1917 #ifdef WITH_PRESENCE
1918 if(presenceResource.handle)
1920 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1921 SendPresenceNotification(pointer->rsrcType);
1925 if (result != OC_STACK_OK)
1927 // Deep delete of resource and other dynamic elements that it contains
1928 deleteResource(pointer);
1937 * Create a resource. with host ip address for remote resource
1939 * @param handle - pointer to handle to newly created resource. Set by ocstack.
1940 * Used to refer to resource
1941 * @param resourceTypeName - name of resource type. Example: "core.led"
1942 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1943 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
1944 * @param uri - URI of the resource. Example: "/a/led"
1945 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1946 * NULL for default entity handler
1947 * @param resourceProperties - properties supported by resource.
1948 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
1951 * OC_STACK_OK - no errors
1952 * OC_STACK_ERROR - stack process error
1955 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
1956 const char *resourceTypeName,
1957 const char *resourceInterfaceName,
1960 OCEntityHandler entityHandler,
1961 uint8_t resourceProperties)
1965 OCStackResult result = OC_STACK_ERROR;
1967 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
1968 uri, entityHandler, resourceProperties);
1970 if (result != OC_STACK_ERROR)
1973 size = strlen(host) + 1;
1974 str = (char *) OCMalloc(size);
1977 return OC_STACK_ERROR;
1979 strncpy(str, host, size);
1980 ((OCResource *) *handle)->host = str;
1987 * Add a resource to a collection resource.
1989 * @param collectionHandle - handle to the collection resource
1990 * @param resourceHandle - handle to resource to be added to the collection resource
1993 * OC_STACK_OK - no errors
1994 * OC_STACK_ERROR - stack process error
1995 * OC_STACK_INVALID_PARAM - invalid collectionhandle
1997 OCStackResult OCBindResource(
1998 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1999 OCResource *resource;
2002 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2004 // Validate parameters
2005 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2006 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2007 // Container cannot contain itself
2008 if (collectionHandle == resourceHandle) {
2009 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2010 return OC_STACK_INVALID_PARAM;
2013 // Use the handle to find the resource in the resource linked list
2014 resource = findResource((OCResource *) collectionHandle);
2016 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2017 return OC_STACK_INVALID_PARAM;
2020 // Look for an open slot to add add the child resource.
2021 // If found, add it and return success
2022 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2023 if (!resource->rsrcResources[i]) {
2024 resource->rsrcResources[i] = (OCResource *) resourceHandle;
2025 OC_LOG(INFO, TAG, PCF("resource bound"));
2030 #ifdef WITH_PRESENCE
2031 if(presenceResource.handle)
2033 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2034 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2038 // Unable to add resourceHandle, so return error
2039 return OC_STACK_ERROR;
2043 * Remove a resource from a collection resource.
2045 * @param collectionHandle - handle to the collection resource
2046 * @param resourceHandle - handle to resource to be added to the collection resource
2049 * OC_STACK_OK - no errors
2050 * OC_STACK_ERROR - stack process error
2051 * OC_STACK_INVALID_PARAM - invalid collectionHandle
2053 OCStackResult OCUnBindResource(
2054 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
2055 OCResource *resource;
2058 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2060 // Validate parameters
2061 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2062 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2063 // Container cannot contain itself
2064 if (collectionHandle == resourceHandle) {
2065 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2066 return OC_STACK_INVALID_PARAM;
2069 // Use the handle to find the resource in the resource linked list
2070 resource = findResource((OCResource *) collectionHandle);
2072 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2073 return OC_STACK_INVALID_PARAM;
2076 // Look for an open slot to add add the child resource.
2077 // If found, add it and return success
2078 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
2079 if (resourceHandle == resource->rsrcResources[i]) {
2080 resource->rsrcResources[i] = (OCResource *) NULL;
2081 OC_LOG(INFO, TAG, PCF("resource unbound"));
2086 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2088 #ifdef WITH_PRESENCE
2089 if(presenceResource.handle)
2091 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2092 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
2096 // Unable to add resourceHandle, so return error
2097 return OC_STACK_ERROR;
2100 OCStackResult BindResourceTypeToResource(OCResource* resource,
2101 const char *resourceTypeName)
2103 OCResourceType *pointer = NULL;
2106 OCStackResult result = OC_STACK_ERROR;
2108 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
2110 // Validate parameters
2111 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2112 // TODO: Does resource attribute resentation really have to be maintained in stack?
2113 // Is it presented during resource discovery?
2115 TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
2117 // Create the resourcetype and insert it into the resource list
2118 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
2123 // Set the resourceTypeName
2124 size = strlen(resourceTypeName) + 1;
2125 str = (char *) OCMalloc(size);
2129 strncpy(str, resourceTypeName, size);
2130 pointer->resourcetypename = str;
2132 insertResourceType(resource, pointer);
2133 result = OC_STACK_OK;
2135 exit: if (result != OC_STACK_OK) {
2143 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2144 const char *resourceInterfaceName)
2146 OCResourceInterface *pointer = NULL;
2149 OCStackResult result = OC_STACK_ERROR;
2151 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
2153 // Validate parameters
2154 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2156 TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
2158 // Create the resourceinterface and insert it into the resource list
2159 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
2164 // Set the resourceinterface name
2165 size = strlen(resourceInterfaceName) + 1;
2166 str = (char *) OCMalloc(size);
2170 strncpy(str, resourceInterfaceName, size);
2171 pointer->name = str;
2173 // Bind the resourceinterface to the resource
2174 insertResourceInterface(resource, pointer);
2176 result = OC_STACK_OK;
2178 exit: if (result != OC_STACK_OK) {
2187 * Bind a resourcetype to a resource.
2189 * @param handle - handle to the resource
2190 * @param resourceTypeName - name of resource type. Example: "core.led"
2193 * OC_STACK_OK - no errors
2194 * OC_STACK_ERROR - stack process error
2196 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2197 const char *resourceTypeName) {
2199 OCStackResult result = OC_STACK_ERROR;
2200 OCResource *resource;
2202 // Make sure resource exists
2203 resource = findResource((OCResource *) handle);
2205 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2206 return OC_STACK_ERROR;
2209 // call internal function
2210 result = BindResourceTypeToResource(resource, resourceTypeName);
2212 #ifdef WITH_PRESENCE
2213 if(presenceResource.handle)
2215 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2216 SendPresenceNotification(resource->rsrcType);
2224 * Bind a resourceinterface to a resource.
2226 * @param handle - handle to the resource
2227 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
2230 * OC_STACK_OK - no errors
2231 * OC_STACK_ERROR - stack process error
2234 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2235 const char *resourceInterfaceName) {
2237 OCStackResult result = OC_STACK_ERROR;
2238 OCResource *resource;
2240 // Make sure resource exists
2241 resource = findResource((OCResource *) handle);
2243 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2244 return OC_STACK_ERROR;
2247 // call internal function
2248 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2250 #ifdef WITH_PRESENCE
2251 if(presenceResource.handle)
2253 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2254 SendPresenceNotification(resource->rsrcType);
2262 * Get the number of resources that have been created in the stack.
2264 * @param numResources - pointer to count variable
2267 * OC_STACK_OK - no errors
2268 * OC_STACK_ERROR - stack process error
2271 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
2272 OCResource *pointer = headResource;
2274 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2275 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2278 *numResources = *numResources + 1;
2279 pointer = pointer->next;
2285 * Get a resource handle by index.
2287 * @param index - index of resource, 0 to Count - 1
2290 * Resource handle - if found
2291 * NULL - if not found
2293 OCResourceHandle OCGetResourceHandle(uint8_t index) {
2294 OCResource *pointer = headResource;
2297 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2299 // Iterate through the list
2300 while ((i < index) && pointer) {
2302 pointer = pointer->next;
2304 return (OCResourceHandle) pointer;
2308 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
2311 * @param handle - handle of resource to be deleted
2314 * OC_STACK_OK - no errors
2315 * OC_STACK_ERROR - stack process error
2316 * OC_STACK_NO_RESOURCE - resource not found
2317 * OC_STACK_INVALID_PARAM - invalid param
2319 OCStackResult OCDeleteResource(OCResourceHandle handle) {
2320 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2323 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2324 return OC_STACK_INVALID_PARAM;
2327 OCResource *resource = findResource((OCResource *) handle);
2328 if (resource == NULL) {
2329 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2330 return OC_STACK_NO_RESOURCE;
2333 if (deleteResource((OCResource *) handle) == 0) {
2334 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2335 return OC_STACK_ERROR;
2342 * Get the URI of the resource specified by handle.
2344 * @param handle - handle of resource
2346 * URI string - if resource found
2347 * NULL - resource not found
2349 const char *OCGetResourceUri(OCResourceHandle handle) {
2350 OCResource *resource;
2351 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2353 resource = findResource((OCResource *) handle);
2355 return resource->uri;
2357 return (const char *) NULL;
2361 * Get the properties of the resource specified by handle.
2362 * NOTE: that after a resource is created, the OC_ACTIVE property is set
2363 * for the resource by the stack.
2365 * @param handle - handle of resource
2367 * property bitmap - if resource found
2368 * NULL - resource not found
2370 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
2371 OCResource *resource;
2372 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2374 resource = findResource((OCResource *) handle);
2376 return resource->resourceProperties;
2382 * Get the number of resource types of the resource.
2384 * @param handle - handle of resource
2385 * @param numResourceTypes - pointer to count variable
2388 * OC_STACK_OK - no errors
2389 * OC_STACK_ERROR - stack process error
2391 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2392 uint8_t *numResourceTypes) {
2393 OCResource *resource;
2394 OCResourceType *pointer;
2396 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2397 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2398 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2400 *numResourceTypes = 0;
2402 resource = findResource((OCResource *) handle);
2404 pointer = resource->rsrcType;
2406 *numResourceTypes = *numResourceTypes + 1;
2407 pointer = pointer->next;
2414 * Get name of resource type of the resource.
2416 * @param handle - handle of resource
2417 * @param index - index of resource, 0 to Count - 1
2420 * resource type name - if resource found
2421 * NULL - resource not found
2423 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
2424 OCResourceType *resourceType;
2426 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2428 resourceType = findResourceTypeAtIndex(handle, index);
2430 return resourceType->resourcetypename;
2432 return (const char *) NULL;
2438 * Get the number of resource interfaces of the resource.
2440 * @param handle - handle of resource
2441 * @param numResources - pointer to count variable
2444 * OC_STACK_OK - no errors
2445 * OC_STACK_ERROR - stack process error
2447 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2448 uint8_t *numResourceInterfaces) {
2449 OCResourceInterface *pointer;
2450 OCResource *resource;
2452 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2454 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2455 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2457 *numResourceInterfaces = 0;
2458 resource = findResource((OCResource *) handle);
2460 pointer = resource->rsrcInterface;
2462 *numResourceInterfaces = *numResourceInterfaces + 1;
2463 pointer = pointer->next;
2470 * Get name of resource interface of the resource.
2472 * @param handle - handle of resource
2473 * @param index - index of resource, 0 to Count - 1
2476 * resource interface name - if resource found
2477 * NULL - resource not found
2479 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
2480 OCResourceInterface *resourceInterface;
2482 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2484 resourceInterface = findResourceInterfaceAtIndex(handle, index);
2485 if (resourceInterface) {
2486 return resourceInterface->name;
2488 return (const char *) NULL;
2492 * Get resource handle from the collection resource by index.
2494 * @param collectionHandle - handle of collection resource
2495 * @param index - index of contained resource, 0 to Count - 1
2498 * handle to resource - if resource found
2499 * NULL - resource not found
2501 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2503 OCResource *resource;
2505 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2507 if (index >= MAX_CONTAINED_RESOURCES) {
2511 resource = findResource((OCResource *) collectionHandle);
2516 return resource->rsrcResources[index];
2520 * Bind an entity handler to the resource.
2522 * @param handle - handle to the resource that the contained resource is to be bound
2523 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2525 * OC_STACK_OK - no errors
2526 * OC_STACK_ERROR - stack process error
2528 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2529 OCEntityHandler entityHandler) {
2530 OCResource *resource;
2532 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2534 // Validate parameters
2535 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2536 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2538 // Use the handle to find the resource in the resource linked list
2539 resource = findResource((OCResource *)handle);
2541 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2542 return OC_STACK_ERROR;
2546 resource->entityHandler = entityHandler;
2548 #ifdef WITH_PRESENCE
2549 if(presenceResource.handle)
2551 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2552 SendPresenceNotification(resource->rsrcType);
2560 * Get the entity handler for a resource.
2562 * @param handle - handle of resource
2565 * entity handler - if resource found
2566 * NULL - resource not found
2568 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
2569 OCResource *resource;
2571 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2573 // Use the handle to find the resource in the resource linked list
2574 resource = findResource((OCResource *)handle);
2576 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2581 return resource->entityHandler;
2584 void incrementSequenceNumber(OCResource * resPtr)
2586 // Increment the sequence number
2587 resPtr->sequenceNum += 1;
2588 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2590 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2596 * Notify Presence subscribers that a resource has been modified
2598 * @param resourceType - Handle to the resourceType linked list of resource
2599 * that was modified.
2600 * @param qos - Quality Of Service
2603 #ifdef WITH_PRESENCE
2604 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
2606 OCResource *resPtr = NULL;
2607 OCStackResult result;
2608 OCMethod method = OC_REST_PRESENCE;
2609 uint32_t maxAge = 0;
2610 resPtr = findResource((OCResource *) presenceResource.handle);
2613 return OC_STACK_NO_RESOURCE;
2615 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
2617 maxAge = presenceResource.presenceTTL;
2624 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
2627 #endif // WITH_PRESENCE
2629 * Notify observers that an observed value has changed.
2631 * @param handle - handle of resource
2634 * OC_STACK_OK - no errors
2635 * OC_STACK_NO_RESOURCE - invalid resource handle
2636 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
2638 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
2640 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2642 OCResource *resPtr = NULL;
2643 OCStackResult result;
2644 OCMethod method = OC_REST_NOMETHOD;
2645 uint32_t maxAge = 0;
2647 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2648 #ifdef WITH_PRESENCE
2649 if(handle == presenceResource.handle)
2653 #endif // WITH_PRESENCE
2654 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2656 // Verify that the resource exists
2657 resPtr = findResource ((OCResource *) handle);
2660 return OC_STACK_NO_RESOURCE;
2664 //only increment in the case of regular observing (not presence)
2665 incrementSequenceNumber(resPtr);
2666 method = OC_REST_OBSERVE;
2667 maxAge = MAX_OBSERVE_AGE;
2668 #ifdef WITH_PRESENCE
2669 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
2671 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
2678 OCNotifyListOfObservers (OCResourceHandle handle,
2679 OCObservationId *obsIdList,
2680 uint8_t numberOfIds,
2681 unsigned char *notificationJSONPayload,
2682 OCQualityOfService qos)
2684 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
2686 OCResource *resPtr = NULL;
2687 //TODO: we should allow the server to define this
2688 uint32_t maxAge = MAX_OBSERVE_AGE;
2690 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2691 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
2692 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
2694 // Verify that the resource exists
2695 resPtr = findResource ((OCResource *) handle);
2696 if (NULL == resPtr || myStackMode == OC_CLIENT)
2698 return OC_STACK_NO_RESOURCE;
2702 incrementSequenceNumber(resPtr);
2704 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
2705 notificationJSONPayload, maxAge, qos));
2709 * Send a response to a request.
2710 * The response can be a regular, slow, or block (i.e. a response that
2711 * is too large to be sent in a single PDU and must span multiple transmissions)
2713 * @param response - pointer to structure that contains response parameters
2716 * OC_STACK_OK - No errors; Success
2717 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
2718 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
2719 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
2720 * persistent response buffer is necessary
2722 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
2724 OCStackResult result = OC_STACK_ERROR;
2725 OCServerRequest *serverRequest = NULL;
2727 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
2729 // Validate input parameters
2730 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
2731 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
2733 // TODO: Placeholder for creating a response entry when implementing
2734 // block transfer feature
2736 // If a response payload is present, check if block transfer is required
2737 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
2738 (const char *)ehResponse->payload, ehResponse->payloadSize))
2740 OC_LOG(INFO, TAG, PCF("Block transfer required"));
2742 // Persistent response buffer is needed for block transfer
2743 if (!ehResponse->persistentBufferFlag)
2745 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
2746 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
2748 // TODO: Placeholder for block transfer handling
2749 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
2750 // when implementing the block transfer feature
2755 // Get pointer to request info
2756 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
2759 result = serverRequest->ehResponseHandler(ehResponse);
2766 * Cancel a response. Applies to a block response
2768 * @param responseHandle - response handle set by stack in OCServerResponse after
2769 * OCDoResponse is called
2772 * OC_STACK_OK - No errors; Success
2773 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
2775 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
2777 OCStackResult result = OC_STACK_NOTIMPL;
2779 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
2781 // TODO: validate response handle
2786 //-----------------------------------------------------------------------------
2787 // Private internal function definitions
2788 //-----------------------------------------------------------------------------
2790 * Generate handle of OCDoResource invocation for callback management.
2792 static OCDoHandle GenerateInvocationHandle()
2794 OCDoHandle handle = NULL;
2795 // Generate token here, it will be deleted when the transaction is deleted
2796 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2799 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2804 #ifdef WITH_PRESENCE
2805 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
2806 OCResourceProperty resourceProperties, uint8_t enable)
2808 if (resourceProperties
2809 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
2810 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2811 return OC_STACK_INVALID_PARAM;
2815 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
2819 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
2826 * Initialize resource data structures, variables, etc.
2828 OCStackResult initResources() {
2829 OCStackResult result = OC_STACK_OK;
2830 // Init application resource vars
2831 headResource = NULL;
2832 // Init Virtual Resources
2833 #ifdef WITH_PRESENCE
2834 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
2835 //presenceResource.token = OCGenerateCoAPToken();
2836 result = OCCreateResource(&presenceResource.handle,
2837 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
2842 //make resource inactive
2843 result = OCChangeResourceProperty(
2844 &(((OCResource *) presenceResource.handle)->resourceProperties),
2851 * Add a resource to the end of the linked list of resources.
2853 * @param resource - resource to be added
2855 void insertResource(OCResource *resource) {
2856 OCResource *pointer;
2858 if (!headResource) {
2859 headResource = resource;
2861 pointer = headResource;
2863 while (pointer->next) {
2864 pointer = pointer->next;
2866 pointer->next = resource;
2868 resource->next = NULL;
2872 * Find a resource in the linked list of resources.
2874 * @param resource - resource to be found
2876 * NULL - resource not found
2877 * pointer to resource - pointer to resource that was found in the linked list
2879 OCResource *findResource(OCResource *resource) {
2880 OCResource *pointer = headResource;
2883 if (pointer == resource) {
2886 pointer = pointer->next;
2891 void deleteAllResources()
2893 OCResource *pointer = headResource;
2898 temp = pointer->next;
2899 #ifdef WITH_PRESENCE
2900 if(pointer != (OCResource *) presenceResource.handle)
2902 #endif // WITH_PRESENCE
2903 deleteResource(pointer);
2904 #ifdef WITH_PRESENCE
2906 #endif // WITH_PRESENCE
2910 #ifdef WITH_PRESENCE
2911 // Ensure that the last resource to be deleted is the presence resource. This allows for all
2912 // presence notification attributed to their deletion to be processed.
2913 deleteResource((OCResource *) presenceResource.handle);
2914 #endif // WITH_PRESENCE
2918 * Delete the resource from the linked list.
2920 * @param resource - resource to be deleted
2925 int deleteResource(OCResource *resource) {
2926 OCResource *prev = NULL;
2929 temp = headResource;
2931 if (temp == resource) {
2932 // Invalidate all Resource Properties.
2933 resource->resourceProperties = (OCResourceProperty) 0;
2934 #ifdef WITH_PRESENCE
2935 if(resource != (OCResource *) presenceResource.handle)
2937 #endif // WITH_PRESENCE
2938 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
2939 #ifdef WITH_PRESENCE
2942 if(presenceResource.handle)
2944 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2945 if(resource != (OCResource *) presenceResource.handle)
2947 SendPresenceNotification(resource->rsrcType);
2951 SendPresenceNotification(NULL);
2956 if (temp == headResource) {
2957 headResource = temp->next;
2959 prev->next = temp->next;
2962 deleteResourceElements(temp);
2975 * Delete all of the dynamically allocated elements that were created for the resource.
2977 * @param resource - specified resource
2979 void deleteResourceElements(OCResource *resource) {
2985 OCFree(resource->uri);
2987 // Delete resourcetype linked list
2988 deleteResourceType(resource->rsrcType);
2990 // Delete resourceinterface linked list
2991 deleteResourceInterface(resource->rsrcInterface);
2995 * Delete all of the dynamically allocated elements that were created for the resource type.
2997 * @param resourceType - specified resource type
2999 void deleteResourceType(OCResourceType *resourceType) {
3000 OCResourceType *pointer = resourceType;
3001 OCResourceType *next;
3004 next = pointer->next;
3005 OCFree(pointer->resourcetypename);
3012 * Delete all of the dynamically allocated elements that were created for the resource interface.
3014 * @param resourceInterface - specified resource interface
3016 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
3017 OCResourceInterface *pointer = resourceInterface;
3018 OCResourceInterface *next;
3021 next = pointer->next;
3022 OCFree(pointer->name);
3029 * Insert a resource type into a resource's resource type linked list.
3031 * @param resource - resource where resource type is to be inserted
3032 * @param resourceType - resource type to be inserted
3034 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
3035 OCResourceType *pointer;
3037 if (resource && !resource->rsrcType) {
3038 resource->rsrcType = resourceType;
3042 pointer = resource->rsrcType;
3046 pointer = resourceType;
3048 while (pointer->next) {
3049 pointer = pointer->next;
3051 pointer->next = resourceType;
3053 resourceType->next = NULL;
3057 * Get a resource type at the specified index within a resource.
3059 * @param handle - handle of resource
3060 * @param index - index of resource type
3063 * resourcetype - if found
3066 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
3067 OCResource *resource;
3068 OCResourceType *pointer;
3071 // Find the specified resource
3072 resource = findResource((OCResource *) handle);
3077 // Make sure a resource has a resourcetype
3078 if (!resource->rsrcType) {
3082 // Iterate through the list
3083 pointer = resource->rsrcType;
3085 while ((i < index) && pointer) {
3087 pointer = pointer->next;
3093 * Finds a resource type in an OCResourceType link-list.
3095 * @param resourceTypeList - the link-list to be searched through
3096 * @param resourceTypeName - the key to search for
3099 * resourceType that matches the key (ie. resourceTypeName)
3100 * NULL - either an invalid parameter or this function was unable to find the key.
3102 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3104 if(resourceTypeList && resourceTypeName)
3106 OCResourceType * rtPointer = resourceTypeList;
3107 while(resourceTypeName && rtPointer)
3109 if(rtPointer->resourcetypename &&
3110 strcmp(resourceTypeName, (const char *)
3111 (rtPointer->resourcetypename)) == 0)
3115 rtPointer = rtPointer->next;
3122 * Insert a resource interface into a resource's resource interface linked list.
3124 * @param resource - resource where resource interface is to be inserted
3125 * @param resourceInterface - resource interface to be inserted
3127 void insertResourceInterface(OCResource *resource,
3128 OCResourceInterface *resourceInterface) {
3129 OCResourceInterface *pointer;
3131 if (!resource->rsrcInterface) {
3132 resource->rsrcInterface = resourceInterface;
3134 pointer = resource->rsrcInterface;
3135 while (pointer->next) {
3136 pointer = pointer->next;
3138 pointer->next = resourceInterface;
3140 resourceInterface->next = NULL;
3144 * Get a resource interface at the specified index within a resource.
3146 * @param handle - handle of resource
3147 * @param index - index of resource interface
3150 * resourceinterface - if found
3153 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3155 OCResource *resource;
3156 OCResourceInterface *pointer;
3159 // Find the specified resource
3160 resource = findResource((OCResource *) handle);
3165 // Make sure a resource has a resourceinterface
3166 if (!resource->rsrcInterface) {
3170 // Iterate through the list
3171 pointer = resource->rsrcInterface;
3173 while ((i < index) && pointer) {
3175 pointer = pointer->next;
3181 * Determine if a request/response must be sent in a block transfer because it is too large to be
3182 * sent in a single PDU. This function can be used for either a request or a response
3184 * @param request - NULL or pointer to request
3185 * @param response - NULL or pointer to response
3186 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
3187 * the length of the request/response
3190 * 0 - packet transfer NOT required (i.e. normal request/response)
3191 * 1 - packet transfer required (i.e. block transfer needed)
3193 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
3197 // Determine if we are checking a request or a response
3200 // If size is greater than 0, use it for the request size value, otherwise
3201 // assume request is null terminated and use strlen for size value
3202 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
3209 // If size is greater than 0, use it for the response size value, otherwise
3210 // assume response is null terminated and use strlen for size value
3211 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3220 * Retrieves a resource type based upon a query ontains only just one
3221 * resource attribute (and that has to be of type "rt").
3223 * @remark This API malloc's memory for the resource type. Do not malloc resourceType
3224 * before passing in.
3226 * @param query - The quert part of the URI
3227 * @param resourceType - The resource type to be populated; pass by reference.
3230 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
3231 * OC_STACK_OK - Success
3233 OCStackResult getResourceType(const char * query, unsigned char** resourceType)
3237 return OC_STACK_INVALID_PARAM;
3240 OCStackResult result = OC_STACK_ERROR;
3242 if(strncmp(query, "rt=", 3) == 0)
3244 *resourceType = (unsigned char *) OCMalloc(strlen(query)-3);
3247 result = OC_STACK_NO_MEMORY;
3250 strcpy((char *)*resourceType, ((const char *)&query[3]));
3251 result = OC_STACK_OK;
3257 OCStackResult getQueryFromUri(const char * uri, unsigned char** query, char ** newURI)
3261 return OC_STACK_INVALID_URI;
3263 if(!query || !newURI)
3265 return OC_STACK_INVALID_PARAM;
3267 char * leftToken = NULL;
3268 char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3273 strcpy(tempURI, uri);
3275 leftToken = strtok_r((char *)tempURI, "?", &strTokPtr);
3277 //TODO-CA: This could be simplified. Clean up required.
3278 while(leftToken != NULL)
3280 if(strncmp(leftToken, "rt=", 3) == 0 || strncmp(leftToken, "if=", 3) == 0)
3282 *query = (unsigned char *) OCMalloc(strlen(leftToken));
3287 strcpy((char *)*query, ((const char *)&leftToken[0]));
3290 leftToken = strtok_r(NULL, "?", &strTokPtr);
3298 return OC_STACK_NO_MEMORY;
3301 const ServerID OCGetServerInstanceID(void)
3303 static bool generated = false;
3304 static ServerID sid;
3311 sid = OCGetRandom();
3316 const char* OCGetServerInstanceIDString(void)
3318 // max printed length of a base 10
3319 // uint32 is 10 characters, so 11 includes null.
3320 // This will change as the representation gets switched
3322 static char buffer[11];
3323 int n = sprintf(buffer, "%u", OCGetServerInstanceID());