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;
73 //-----------------------------------------------------------------------------
75 //-----------------------------------------------------------------------------
76 #define TAG PCF("OCStack")
77 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
78 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
79 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
80 TAG, PCF(#arg " is NULL")); return (retVal); } }
81 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
84 //TODO: we should allow the server to define this
85 #define MAX_OBSERVE_AGE (0x2FFFFUL)
87 //-----------------------------------------------------------------------------
89 //-----------------------------------------------------------------------------
90 extern void DeinitOCSecurityInfo();
92 //-----------------------------------------------------------------------------
93 // Internal API function
94 //-----------------------------------------------------------------------------
96 // This internal function is called to update the stack with the status of
97 // observers and communication failures
98 OCStackResult OCStackFeedBack(OCCoAPToken * token, uint8_t status)
100 OCStackResult result = OC_STACK_ERROR;
101 ResourceObserver * observer = NULL;
102 OCEntityHandlerRequest ehRequest = {0};
106 case OC_OBSERVER_NOT_INTERESTED:
107 OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
109 observer = GetObserverUsingToken (token->token);
111 observer = GetObserverUsingToken (token);
115 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
116 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
117 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
118 if(result != OC_STACK_OK)
122 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
124 //observer is not observing anymore
126 result = DeleteObserverUsingToken (token->token);
128 result = DeleteObserverUsingToken (token);
130 if(result == OC_STACK_OK)
132 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
136 result = OC_STACK_OK;
137 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
140 case OC_OBSERVER_STILL_INTERESTED:
141 //observer is still interested
142 OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
143 notifications, reset the failedCount"));
145 observer = GetObserverUsingToken (token->token);
147 observer = GetObserverUsingToken (token);
151 observer->forceHighQos = 0;
152 observer->failedCommCount = 0;
153 result = OC_STACK_OK;
157 result = OC_STACK_OBSERVER_NOT_FOUND;
160 case OC_OBSERVER_FAILED_COMM:
161 //observer is not reachable
162 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
164 observer = GetObserverUsingToken (token->token);
166 observer = GetObserverUsingToken (token);
170 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
172 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
173 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
174 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
175 if(result != OC_STACK_OK)
177 return OC_STACK_ERROR;
179 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
180 //observer is unreachable
181 result = DeleteObserverUsingToken (token);
182 if(result == OC_STACK_OK)
184 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
188 result = OC_STACK_OK;
189 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
194 observer->failedCommCount++;
195 result = OC_STACK_CONTINUE;
197 observer->forceHighQos = 1;
198 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
202 OC_LOG(ERROR, TAG, PCF("Unknown status"));
203 result = OC_STACK_ERROR;
210 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
212 OCStackResult ret = OC_STACK_ERROR;
220 ret = OC_STACK_RESOURCE_CREATED;
223 ret = OC_STACK_RESOURCE_DELETED;
226 ret = OC_STACK_INVALID_QUERY;
229 ret = OC_STACK_INVALID_OPTION;
232 ret = OC_STACK_NO_RESOURCE;
240 //This function will be called back by CA layer when a response is received
241 void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
243 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
244 printf ("Received payload: %s\n", (char *)responseInfo->info.payload);
245 OCStackApplicationResult result = OC_STACK_DELETE_TRANSACTION;
246 ClientCB *cbNode = GetClientCB((CAToken_t *)&responseInfo->info.token, NULL, NULL);
249 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
250 OCClientResponse response;
251 struct sockaddr_in sa;
253 inet_pton(AF_INET, endPoint->addressInfo.IP.ipAddress, &(sa.sin_addr));
254 sa.sin_port = htons(endPoint->addressInfo.IP.port);
255 static OCDevAddr address;
256 memcpy((void*)&address.addr, &(sa), sizeof(sa));
257 response.addr = &address;
258 response.result = CAToOCStackResult(responseInfo->result);
259 response.resJSONPayload = (unsigned char*)responseInfo->info.payload;
260 response.numRcvdVendorSpecificHeaderOptions = 0;
261 if(responseInfo->info.numOptions > 0)
263 //First option alwas with option ID COAP_OPTION_OBSERVE if it is availbale
264 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
266 memcpy (&(response.sequenceNumber),
267 &(responseInfo->info.options[0].optionData), 4);
271 memcpy (&(response.rcvdVendorSpecificHeaderOptions[0]),
272 &(responseInfo->info.options[0]), sizeof(OCHeaderOption));
274 for (uint8_t i = 1; i < responseInfo->info.numOptions; i++)
276 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i]),
277 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
279 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
281 result = cbNode->callBack(cbNode->context,
282 cbNode->handle, &response);
283 if (result == OC_STACK_DELETE_TRANSACTION)
285 FindAndDeleteClientCB(cbNode);
288 OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload);
289 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
292 //This function will be called back by CA layer when a request is received
293 void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
295 CAInfo_t responseData;
296 CAResponseInfo_t responseInfo;
297 OCStackResult requestResult = OC_STACK_ERROR;
299 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
302 if(myStackMode == OC_CLIENT)
304 //TODO: should the client be responding to requests?
308 OCServerProtocolRequest serverRequest;
310 memset (&serverRequest, 0, sizeof(OCServerProtocolRequest));
311 // copy URI of resource
312 memcpy (&(serverRequest.resourceUrl), endPoint->resourceUri, strlen(endPoint->resourceUri));
314 // TODO-CA: Is the query part of header option?
315 //copy request payload
316 if (requestInfo->info.payload)
318 serverRequest.reqTotalSize = strlen(requestInfo->info.payload) + 1;
319 memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
320 strlen(requestInfo->info.payload));
321 serverRequest.reqTotalSize = strlen((const char *)requestInfo->info.payload) + 1;
325 serverRequest.reqTotalSize = 1;
328 switch (requestInfo->method)
332 serverRequest.method = OC_REST_GET;
337 serverRequest.method = OC_REST_PUT;
342 serverRequest.method = OC_REST_POST;
347 serverRequest.method = OC_REST_DELETE;
352 OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
358 OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d", strlen(requestInfo->info.token));
359 OC_LOG_BUFFER(INFO, TAG, requestInfo->info.token, strlen(requestInfo->info.token));
360 // TODO-CA: For CA integration currently copying CAToken to OCCoapToken:
361 // Need to remove OCCoapToken
362 memcpy (&(serverRequest.requestToken.token), requestInfo->info.token,
363 strlen(requestInfo->info.token));
364 serverRequest.requestToken.tokenLength = strlen(requestInfo->info.token);
366 if (requestInfo->info.type == CA_MSG_CONFIRM)
368 serverRequest.qos = OC_HIGH_QOS;
370 else if (requestInfo->info.type == CA_MSG_NONCONFIRM)
372 serverRequest.qos = OC_LOW_QOS;
374 else if (requestInfo->info.type == CA_MSG_ACKNOWLEDGE)
376 // TODO-CA: Need to handle this
378 else if (requestInfo->info.type == CA_MSG_RESET)
380 // TODO-CA: Need to handle this
382 // CA does not need the following 3 fields
383 serverRequest.coapID = 0;
384 serverRequest.delayedResNeeded = 0;
385 serverRequest.secured = endPoint->isSecured;
388 serverRequest.addressInfo = endPoint->addressInfo;
389 serverRequest.connectivityType = endPoint->connectivityType;
390 if (requestInfo->info.token)
392 strncpy(serverRequest.token, requestInfo->info.token, sizeof(serverRequest.token) - 1);
395 // copy vendor specific header options
396 // TODO-CA: CA is including non-vendor header options as well, like observe.
397 // Need to filter those out
398 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &(requestInfo->info.numOptions));
399 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
401 // TODO-CA: Need to send an error indicating the num of options is incorrect
404 serverRequest.numRcvdVendorSpecificHeaderOptions = requestInfo->info.numOptions;
405 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
407 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
408 sizeof(CAHeaderOption_t)*requestInfo->info.numOptions);
411 requestResult = HandleStackRequests (&serverRequest);
414 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
419 //This function will be called back by occoap layer when a request is received
420 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
422 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
424 OCStackResult result = OC_STACK_ERROR;
425 ResourceHandling resHandling;
426 OCResource *resource;
428 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
431 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
433 result = AddServerCARequest(&request, protocolRequest->coapID,
434 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
435 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
436 protocolRequest->observationOption, protocolRequest->qos,
437 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
438 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
439 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
440 protocolRequest->reqTotalSize,
441 &protocolRequest->addressInfo, protocolRequest->connectivityType, protocolRequest->token);
443 result = AddServerRequest(&request, protocolRequest->coapID,
444 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
445 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
446 protocolRequest->observationOption, protocolRequest->qos,
447 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
448 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
449 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
450 protocolRequest->reqTotalSize);
452 if (OC_STACK_OK != result)
454 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
457 VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
459 if(!protocolRequest->reqMorePacket)
461 request->requestComplete = 1;
466 OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
469 if(request->requestComplete)
471 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
472 result = DetermineResourceHandling (request, &resHandling, &resource);
473 if (result == OC_STACK_OK)
475 result = ProcessRequest(resHandling, resource, request);
479 result = OC_STACK_ERROR;
484 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
485 result = OC_STACK_CONTINUE;
490 //This function will be called back by occoap layer when a response is received
491 OCStackResult HandleStackResponses(OCResponse * response)
493 OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)"));
494 OCStackResult result = OC_STACK_OK;
495 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
496 uint8_t isObserveNotification = 0;
497 ClientCB * cbNode = NULL;
499 uint8_t isPresenceNotification = 0;
500 uint8_t isMulticastPresence = 0;
501 char * resourceTypeName = NULL;
502 uint32_t lowerBound = 0;
503 uint32_t higherBound = 0;
505 unsigned char * bufRes = response->bufRes;
506 #endif // WITH_PRESENCE
508 cbNode = response->cbNode;
511 cbNode = GetClientCB(response->rcvdToken, NULL, NULL);
514 if(response->clientResponse->sequenceNumber >= OC_OFFSET_SEQUENCE_NUMBER)
516 isObserveNotification = 1;
517 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
520 OC_LOG_V(DEBUG, TAG, "The sequenceNumber/NONCE of this response %u",
521 response->clientResponse->sequenceNumber);
522 OC_LOG_V(DEBUG, TAG, "The maxAge/TTL of this response %u", response->maxAge);
523 OC_LOG_V(DEBUG, TAG, "The response received is %s", bufRes);
526 if(!strcmp((char *)response->rcvdUri, (char *)OC_PRESENCE_URI)){
527 isPresenceNotification = 1;
530 result = OC_STACK_INVALID_PARAM;
533 tok = strtok((char *)bufRes, "[:]}");
534 bufRes[strlen((char *)bufRes)] = ':';
535 tok = strtok(NULL, "[:]}");
536 bufRes[strlen((char *)bufRes)] = ':';
537 response->clientResponse->sequenceNumber = (uint32_t )atoi(tok);
538 OC_LOG_V(DEBUG, TAG, "The received NONCE is %u", response->clientResponse->sequenceNumber);
539 tok = strtok(NULL, "[:]}");
540 response->maxAge = (uint32_t )atoi(tok);
541 OC_LOG_V(DEBUG, TAG, "The received TTL is %u", response->maxAge);
542 tok = strtok(NULL, "[:]}");
545 resourceTypeName = (char *)OCMalloc(strlen(tok));
546 if(!resourceTypeName)
550 bufRes[strlen((char *)bufRes)] = ':';
551 strcpy(resourceTypeName, tok);
552 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
555 bufRes[strlen((char *)bufRes)] = ']';
558 // Check if the application subcribed for presence
561 cbNode = GetClientCB(NULL, NULL, response->fullUri);
564 // Check if application subscribed for multicast presence
567 snprintf((char *)response->fullUri, MAX_URI_LENGTH, "%s%s",
568 OC_MULTICAST_IP, response->rcvdUri);
569 cbNode = GetClientCB(NULL, NULL, response->fullUri);
572 isMulticastPresence = 1;
573 isPresenceNotification = 0;
577 if(cbNode && isPresenceNotification)
579 OC_LOG(INFO, TAG, PCF("Received a presence notification"));
580 if(!cbNode->presence)
582 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
583 VERIFY_NON_NULL_V(cbNode->presence);
584 cbNode->presence->timeOut = NULL;
585 cbNode->presence->timeOut = (uint32_t *)
586 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
587 if(!(cbNode->presence->timeOut)){
588 OCFree(cbNode->presence);
589 result = OC_STACK_NO_MEMORY;
592 if(response->maxAge == 0)
594 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
595 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
598 OCFree(cbNode->presence->timeOut);
599 OCFree(cbNode->presence);
600 cbNode->presence = NULL;
605 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %d", GetTime(0));
606 cbNode->presence->TTL = response->maxAge;
607 for(int index = 0; index < PresenceTimeOutSize; index++)
609 lowerBound = GetTime(((float)(PresenceTimeOut[index])
610 /(float)100)*(float)cbNode->presence->TTL);
611 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
612 /(float)100)*(float)cbNode->presence->TTL);
613 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
614 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
615 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
616 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
617 cbNode->presence->timeOut[index]);
619 cbNode->presence->TTLlevel = 0;
620 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
621 if(cbNode->sequenceNumber == response->clientResponse->sequenceNumber)
623 OC_LOG(INFO, TAG, PCF("===============No presence change"));
626 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
627 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;;
630 // Ensure that a filter is actually applied.
631 if(resourceTypeName && cbNode->filterResourceType)
633 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
639 else if(cbNode && isMulticastPresence)
641 // Check if the same nonce for a given host
642 OCMulticastNode* mcNode = NULL;
643 mcNode = GetMCPresenceNode(response->fullUri);
645 if(response->maxAge == 0)
647 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
648 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
651 OCFree(cbNode->presence->timeOut);
652 OCFree(cbNode->presence);
653 cbNode->presence = NULL;
656 else if(mcNode != NULL)
658 if(mcNode->nonce == response->clientResponse->sequenceNumber)
660 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
661 result = OC_STACK_NO_MEMORY;
664 mcNode->nonce = response->clientResponse->sequenceNumber;
668 uint32_t uriLen = strlen((char*)response->fullUri);
669 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
672 memcpy(uri, response->fullUri, (uriLen + 1));
677 PCF("===============No Memory for URI to store in the presence node"));
678 result = OC_STACK_NO_MEMORY;
681 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri,
682 response->clientResponse->sequenceNumber);
683 if(result == OC_STACK_NO_MEMORY)
686 PCF("===============No Memory for Multicast Presence Node"));
687 result = OC_STACK_NO_MEMORY;
692 // Ensure that a filter is actually applied.
693 if(resourceTypeName && cbNode->filterResourceType)
695 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
702 else if(!cbNode && isPresenceNotification)
704 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
705 ------------ ignoring"));
707 #endif // WITH_PRESENCE
711 if(isObserveNotification)
713 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
714 //TODO: check the standard for methods to detect wrap around condition
715 if(cbNode->method == OC_REST_OBSERVE &&
716 (response->clientResponse->sequenceNumber <= cbNode->sequenceNumber ||
717 (response->clientResponse->sequenceNumber > cbNode->sequenceNumber &&
718 response->clientResponse->sequenceNumber ==
719 MAX_SEQUENCE_NUMBER)))
721 OC_LOG_V(DEBUG, TAG, "Observe notification came out of order. \
722 Ignoring Incoming:%d Against Current:%d.",
723 response->clientResponse->sequenceNumber, cbNode->sequenceNumber);
726 if(response->clientResponse->sequenceNumber > cbNode->sequenceNumber){
727 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;
731 response->clientResponse->resJSONPayload = bufRes;
733 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response->clientResponse);
735 if (cbResult == OC_STACK_DELETE_TRANSACTION ||
736 response->clientResponse->result == OC_STACK_COMM_ERROR ||
737 (response->clientResponse->result == OC_STACK_RESOURCE_DELETED &&
738 !isPresenceNotification && !isMulticastPresence))
740 FindAndDeleteClientCB(cbNode);
745 result = OC_STACK_ERROR;
750 OCFree(resourceTypeName);
755 int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
758 unsigned char *itr, *coap;
759 uint8_t dotCount = 0;
763 /* search for scheme */
765 if (!isdigit((unsigned char) *ipAddrStr))
767 coap = (unsigned char *) OC_COAP_SCHEME;
768 while (*coap && tolower(*itr) == *coap)
777 if (isdigit((unsigned char) *ipAddrStr))
780 ipAddr[index] += *ipAddrStr - '0';
782 else if ((unsigned char) *ipAddrStr == '.')
794 if(*ipAddrStr == ':')
798 if (isdigit((unsigned char) *ipAddrStr))
801 *port += *ipAddrStr - '0';
812 if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
823 //-----------------------------------------------------------------------------
824 // Private internal function prototypes
825 //-----------------------------------------------------------------------------
827 static OCDoHandle GenerateInvocationHandle();
828 static OCStackResult initResources();
829 static void insertResource(OCResource *resource);
830 static OCResource *findResource(OCResource *resource);
831 static void insertResourceType(OCResource *resource,
832 OCResourceType *resourceType);
833 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
835 static void insertResourceInterface(OCResource *resource,
836 OCResourceInterface *resourceInterface);
837 static OCResourceInterface *findResourceInterfaceAtIndex(
838 OCResourceHandle handle, uint8_t index);
839 static void deleteResourceType(OCResourceType *resourceType);
840 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
841 static void deleteResourceElements(OCResource *resource);
842 static int deleteResource(OCResource *resource);
843 static void deleteAllResources();
844 static void incrementSequenceNumber(OCResource * resPtr);
845 static OCStackResult verifyUriQueryLength(const char * inputUri,
847 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
848 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI);
850 //-----------------------------------------------------------------------------
852 //-----------------------------------------------------------------------------
855 * Initialize the OC Stack. Must be called prior to starting the stack.
858 * IP Address of host device
860 * Port of host device
862 * Host device is client, server, or client-server
865 * OC_STACK_OK - no errors
866 * OC_STACK_ERROR - stack init error
868 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
870 OCStackResult result = OC_STACK_ERROR;
871 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
875 OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
879 //It is ok to select network to CA_WIFI for now
880 CAResult_t caResult = CASelectNetwork(CA_WIFI);
881 if(caResult == CA_STATUS_OK)
883 OC_LOG(INFO, TAG, PCF("CASelectNetwork to WIFI"));
884 caResult = CARegisterHandler(HandleCARequests, HandleCAResponses);
885 if(caResult == CA_STATUS_OK)
887 OC_LOG(INFO, TAG, PCF("CARegisterHandler..."));
888 stackState = OC_STACK_INITIALIZED;
889 result = OC_STACK_OK;
893 caResult = CAStartDiscoveryServer();
894 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
897 caResult = CAStartListeningServer();
898 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
900 case OC_CLIENT_SERVER:
901 caResult = CAStartListeningServer();
902 if(caResult == CA_STATUS_OK)
904 caResult = CAStartDiscoveryServer();
906 OC_LOG(INFO, TAG, PCF("Client-server mode"));
909 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
910 return OC_STACK_ERROR;
915 if (caResult == CA_STATUS_OK)
917 result = OC_STACK_OK;
921 result = OC_STACK_ERROR;
928 OC_LOG(INFO, TAG, PCF("Client mode"));
931 OC_LOG(INFO, TAG, PCF("Server mode"));
933 case OC_CLIENT_SERVER:
934 OC_LOG(INFO, TAG, PCF("Client-server mode"));
937 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
938 return OC_STACK_ERROR;
942 // Make call to OCCoAP layer
943 result = OCInitCoAP(ipAddr, (uint16_t) port, myStackMode);
947 defaultDeviceHandler = NULL;
950 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
951 #endif // WITH_PRESENCE
953 if (result == OC_STACK_OK)
955 stackState = OC_STACK_INITIALIZED;
957 // Initialize resource
958 if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
960 result = initResources();
962 if(result != OC_STACK_OK)
964 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
970 * Stop the OC stack. Use for a controlled shutdown.
972 * OC_STACK_OK - no errors
973 * OC_STACK_ERROR - stack not initialized
975 OCStackResult OCStop()
977 OCStackResult result = OC_STACK_ERROR;
979 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
981 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
983 OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
986 else if (stackState != OC_STACK_INITIALIZED)
988 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
989 return OC_STACK_ERROR;
992 stackState = OC_STACK_UNINIT_IN_PROGRESS;
995 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
996 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
997 presenceResource.presenceTTL = 0;
998 #endif // WITH_PRESENCE
1000 // Free memory dynamically allocated for resources
1001 deleteAllResources();
1004 // Make call to OCCoAP layer
1005 if (OCStopCoAP() == OC_STACK_OK)
1007 // Remove all observers
1008 DeleteObserverList();
1009 // Remove all the client callbacks
1010 DeleteClientCBList();
1011 stackState = OC_STACK_UNINITIALIZED;
1012 result = OC_STACK_OK;
1014 stackState = OC_STACK_INITIALIZED;
1015 result = OC_STACK_ERROR;
1018 // Deinit security blob
1019 DeinitOCSecurityInfo();
1021 if (result != OC_STACK_OK) {
1022 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
1029 * Verify the lengths of the URI and the query separately
1031 * @param inputUri - Input URI and query.
1032 * @param uriLen - The length of the initial URI with query.
1034 * Note: The '?' that appears after the URI is not considered as
1035 * a part of the query.
1037 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1041 query = strchr (inputUri, '?');
1045 if((query - inputUri) > MAX_URI_LENGTH)
1047 return OC_STACK_INVALID_URI;
1050 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1052 return OC_STACK_INVALID_QUERY;
1055 else if(uriLen > MAX_URI_LENGTH)
1057 return OC_STACK_INVALID_URI;
1063 * Discover or Perform requests on a specified resource (specified by that Resource's respective URI).
1065 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of calling this API.
1066 * @param method - @ref OCMethod to perform on the resource
1067 * @param requiredUri - URI of the resource to interact with
1068 * @param referenceUri - URI of the reference resource
1069 * @param request - JSON encoded request
1070 * @param qos - quality of service
1071 * @param cbData - struct that contains asynchronous callback function that is invoked
1072 * by the stack when discovery or resource interaction is complete
1073 * @param options - The address of an array containing the vendor specific header
1074 * header options to be sent with the request
1075 * @param numOptions - Number of vendor specific header options to be included
1078 * OC_STACK_OK - no errors
1079 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
1080 * OC_STACK_INVALID_METHOD - invalid resource method
1081 * OC_STACK_INVALID_URI - invalid required or reference URI
1084 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1085 const char *referenceUri, const char *request,
1086 OCQualityOfService qos, OCCallbackData *cbData,
1087 OCHeaderOption * options, uint8_t numOptions)
1089 OCStackResult result = OC_STACK_ERROR;
1091 ClientCB *clientCB = NULL;
1092 unsigned char * requestUri = NULL;
1093 unsigned char * resourceType = NULL;
1094 char * newUri = (char *)requiredUri;
1095 (void) referenceUri;
1097 CARemoteEndpoint_t* endpoint = NULL;
1098 CAResult_t caResult;
1099 CAToken_t caToken = NULL;
1100 CAInfo_t requestData;
1101 CARequestInfo_t requestInfo;
1102 // To track if memory is allocated for additional header options
1103 uint8_t hdrOptionMemAlloc = 0;
1106 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1108 // Validate input parameters
1109 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1110 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1112 TODO ("Need to form the final query by concatenating require and reference URI's");
1113 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
1115 uint16_t uriLen = strlen(requiredUri);
1117 // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS
1123 case OC_REST_DELETE:
1124 case OC_REST_OBSERVE:
1125 case OC_REST_OBSERVE_ALL:
1126 case OC_REST_CANCEL_OBSERVE:
1128 #ifdef WITH_PRESENCE
1129 case OC_REST_PRESENCE:
1133 result = OC_STACK_INVALID_METHOD;
1137 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
1142 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
1144 result = OC_STACK_INVALID_PARAM;
1148 #ifdef WITH_PRESENCE
1149 if(method == OC_REST_PRESENCE)
1151 result = getResourceType(requiredUri, &resourceType, &newUri);
1153 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1157 OC_LOG(DEBUG, TAG, PCF("Got Resource Type is NULL."));
1159 if(result != OC_STACK_OK)
1164 #endif // WITH_PRESENCE
1166 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
1169 memcpy(requestUri, newUri, (uriLen + 1));
1173 result = OC_STACK_NO_MEMORY;
1177 *handle = GenerateInvocationHandle();
1180 result = OC_STACK_NO_MEMORY;
1185 memset(&requestData, 0, sizeof(CAInfo_t));
1186 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1190 case OC_REST_OBSERVE:
1191 case OC_REST_OBSERVE_ALL:
1192 case OC_REST_CANCEL_OBSERVE:
1194 requestInfo.method = CA_GET;
1199 requestInfo.method = CA_PUT;
1204 requestInfo.method = CA_POST;
1207 case OC_REST_DELETE:
1209 requestInfo.method = CA_DELETE;
1212 #ifdef WITH_PRESENCE
1213 case OC_REST_PRESENCE:
1214 //TODO-CA: What should be the CA method?
1218 result = OC_STACK_INVALID_METHOD;
1222 // TODO-CA: Handle multi-cast scenario
1223 // Create remote end point
1224 caResult = CACreateRemoteEndpoint(newUri, CA_WIFI, &endpoint);
1225 // TODO-CA: Connectivity type should be passed to API
1226 endpoint->connectivityType = CA_WIFI;
1227 if (caResult != CA_STATUS_OK)
1229 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1234 caResult = CAGenerateToken(&caToken);
1236 if (caResult != CA_STATUS_OK)
1238 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1243 // TODO-CA: Map QoS to the right CA msg type
1244 requestData.type = CA_MSG_NONCONFIRM;
1245 requestData.token = caToken;
1246 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1248 result = CreateObserveHeaderOption (&(requestData.options), options,
1249 numOptions, OC_OBSERVE_REGISTER);
1250 if (result != OC_STACK_OK)
1254 hdrOptionMemAlloc = 1;
1255 requestData.numOptions = numOptions + 1;
1259 requestData.options = (CAHeaderOption_t*)options;
1260 requestData.numOptions = numOptions;
1262 requestData.payload = (char *)request;
1264 requestInfo.info = requestData;
1267 caResult = CASendRequest(endpoint, &requestInfo);
1268 if (caResult != CA_STATUS_OK)
1270 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1274 if((result = AddClientCB(&clientCB, cbData, &caToken, handle, method,
1275 requestUri, resourceType)) != OC_STACK_OK)
1277 result = OC_STACK_NO_MEMORY;
1283 // Generate token which will be used by OCStack to match responses received
1285 OCGenerateCoAPToken(&token);
1287 if((result = AddClientCB(&clientCB, cbData, &token, handle, method, requestUri, resourceType))
1290 result = OC_STACK_NO_MEMORY;
1294 #ifdef WITH_PRESENCE
1295 if(method == OC_REST_PRESENCE)
1297 // Replacing method type with GET because "presence" is a stack layer only implementation.
1298 method = OC_REST_GET;
1302 // Make call to OCCoAP layer
1303 result = OCDoCoAPResource(method, qos, &token, newUri, request, options, numOptions);
1307 if(newUri != requiredUri)
1311 if (result != OC_STACK_OK)
1313 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1314 FindAndDeleteClientCB(clientCB);
1317 CADestroyRemoteEndpoint(endpoint);
1318 if (hdrOptionMemAlloc)
1320 OCFree(requestData.options);
1327 * Cancel a request associated with a specific @ref OCDoResource invocation.
1329 * @param handle - Used to identify a specific OCDoResource invocation.
1330 * @param qos - used to specify Quality of Service (read below for more info)
1331 * @param options- used to specify vendor specific header options when sending
1332 * explicit observe cancellation
1333 * @param numOptions- Number of header options to be included
1336 * OC_STACK_OK - No errors; Success
1337 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1339 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1343 * This ftn is implemented one of two ways in the case of observation:
1345 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1346 * Remove the callback associated on client side.
1347 * When the next notification comes in from server,
1348 * reply with RESET message to server.
1349 * Keep in mind that the server will react to RESET only
1350 * if the last notification was sent ans CON
1352 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1353 * and it is associated with an observe request
1354 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1355 * Send CON Observe request to server with
1356 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1357 * Remove the callback associated on client side.
1359 OCStackResult ret = OC_STACK_OK;
1361 CARemoteEndpoint_t* endpoint = NULL;
1362 CAResult_t caResult;
1363 CAInfo_t requestData;
1364 CARequestInfo_t requestInfo;
1365 // Track if memory is allocated for additional header options
1366 uint8_t hdrOptionMemAlloc = 0;
1370 return OC_STACK_INVALID_PARAM;
1373 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1375 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1378 switch (clientCB->method)
1380 case OC_REST_OBSERVE:
1381 case OC_REST_OBSERVE_ALL:
1383 caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri, CA_WIFI,
1385 endpoint->connectivityType = CA_WIFI;
1386 if (caResult != CA_STATUS_OK)
1388 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1389 return OC_STACK_ERROR;
1392 memset(&requestData, 0, sizeof(CAInfo_t));
1393 // TODO-CA: Map QoS to the right CA msg type
1394 requestData.type = CA_MSG_NONCONFIRM;
1395 requestData.token = clientCB->token;
1396 if (CreateObserveHeaderOption (&(requestData.options),
1397 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
1399 return OC_STACK_ERROR;
1401 hdrOptionMemAlloc = 1;
1402 requestData.numOptions = numOptions + 1;
1403 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1404 requestInfo.method = CA_GET;
1405 requestInfo.info = requestData;
1407 caResult = CASendRequest(endpoint, &requestInfo);
1408 if (caResult != CA_STATUS_OK)
1410 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1412 if(caResult == CA_STATUS_OK)
1417 if(qos == OC_HIGH_QOS)
1419 ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
1420 &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
1425 FindAndDeleteClientCB(clientCB);
1429 #ifdef WITH_PRESENCE
1430 case OC_REST_PRESENCE:
1431 FindAndDeleteClientCB(clientCB);
1435 return OC_STACK_INVALID_METHOD;
1439 CADestroyRemoteEndpoint(endpoint);
1440 if (hdrOptionMemAlloc)
1442 OCFree(requestData.options);
1448 #ifdef WITH_PRESENCE
1449 OCStackResult OCProcessPresence()
1451 OCStackResult result = OC_STACK_OK;
1452 uint8_t ipAddr[4] = { 0 };
1455 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1456 ClientCB* cbNode = NULL;
1458 OCClientResponse clientResponse;
1459 OCResponse * response = NULL;
1461 LL_FOREACH(cbList, cbNode) {
1462 if(OC_REST_PRESENCE == cbNode->method)
1464 if(cbNode->presence)
1466 uint32_t now = GetTime(0);
1467 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
1468 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1471 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1476 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1477 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1478 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1481 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1483 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1484 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1486 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1488 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
1489 (OCDevAddr *) &dst, 0, NULL);
1490 if(result != OC_STACK_OK)
1494 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1495 &cbNode->token, &clientResponse, NULL);
1496 if(result != OC_STACK_OK)
1501 // Increment the TTLLevel (going to a next state), so we don't keep
1502 // sending presence notification to client.
1503 cbNode->presence->TTLlevel++;
1504 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1505 cbNode->presence->TTLlevel);
1509 result = OC_STACK_INVALID_IP;
1512 HandleStackResponses(response);
1514 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1516 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
1518 OCGenerateCoAPToken(&token);
1519 result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
1520 &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
1521 if(result != OC_STACK_OK)
1525 cbNode->presence->TTLlevel++;
1526 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
1532 if (result != OC_STACK_OK)
1534 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
1541 * Called in main loop of OC client or server. Allows low-level processing of
1545 * OC_STACK_OK - no errors
1546 * OC_STACK_ERROR - stack process error
1548 OCStackResult OCProcess() {
1550 OC_LOG(INFO, TAG, PCF("Entering OCProcess"));
1551 #ifdef WITH_PRESENCE
1552 OCProcessPresence();
1555 CAHandleRequestResponse();
1563 #ifdef WITH_PRESENCE
1565 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
1566 * presence notifications to clients via multicast. Once this API has been called with a success,
1567 * clients may query for this server's presence and this server's stack will respond via multicast.
1569 * Server can call this function when it comes online for the first time, or when it comes back
1570 * online from offline mode, or when it re enters network.
1572 * @param ttl - Time To Live in seconds
1573 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
1576 * OC_STACK_OK - No errors; Success
1578 OCStackResult OCStartPresence(const uint32_t ttl)
1580 OCChangeResourceProperty(
1581 &(((OCResource *)presenceResource.handle)->resourceProperties),
1586 presenceResource.presenceTTL = ttl;
1589 if(OC_PRESENCE_UNINITIALIZED == presenceState)
1591 OCDevAddr multiCastAddr;
1594 presenceState = OC_PRESENCE_INITIALIZED;
1595 OCGenerateCoAPToken(&token);
1596 OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
1597 //add the presence observer
1598 AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
1599 (OCResource *)presenceResource.handle, OC_LOW_QOS);
1602 // Each time OCStartPresence is called
1603 // a different random 32-bit integer number is used
1604 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1606 return SendPresenceNotification(NULL);
1610 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
1611 * presence notifications to clients via multicast. Once this API has been called with a success,
1612 * this server's stack will not respond to clients querying for this server's presence.
1614 * Server can call this function when it is terminating, going offline, or when going
1615 * away from network.
1618 * OC_STACK_OK - No errors; Success
1620 OCStackResult OCStopPresence()
1622 OCStackResult result = OC_STACK_ERROR;
1623 //make resource inactive
1624 result = OCChangeResourceProperty(
1625 &(((OCResource *) presenceResource.handle)->resourceProperties),
1627 result = SendPresenceNotification(NULL);
1634 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
1636 defaultDeviceHandler = entityHandler;
1641 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
1643 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
1645 if(myStackMode == OC_CLIENT)
1647 return OC_STACK_ERROR;
1650 return SaveDeviceInfo(deviceInfo);
1656 * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource
1657 * @param resourceTypeName - name of resource type. Example: "core.led"
1658 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1659 * @param uri - URI of the resource. Example: "/a/led"
1660 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1661 * NULL for default entity handler
1662 * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE
1665 * OC_STACK_OK - no errors
1666 * OC_STACK_ERROR - stack process error
1668 OCStackResult OCCreateResource(OCResourceHandle *handle,
1669 const char *resourceTypeName,
1670 const char *resourceInterfaceName,
1671 const char *uri, OCEntityHandler entityHandler,
1672 uint8_t resourceProperties) {
1674 OCResource *pointer = NULL;
1677 OCStackResult result = OC_STACK_ERROR;
1679 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
1681 if(myStackMode == OC_CLIENT)
1685 // Validate parameters
1686 if(!uri || (strlen(uri) == 0))
1688 OC_LOG(ERROR, TAG, PCF("URI is invalid"));
1689 return OC_STACK_INVALID_URI;
1691 // Is it presented during resource discovery?
1692 if (!handle || !resourceTypeName) {
1693 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
1694 return OC_STACK_INVALID_PARAM;
1697 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
1698 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
1701 // Make sure resourceProperties bitmask has allowed properties specified
1702 if (resourceProperties
1703 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
1704 OC_LOG(ERROR, TAG, PCF("Invalid property"));
1705 return OC_STACK_INVALID_PARAM;
1708 // If the headResource is NULL, then no resources have been created...
1709 pointer = headResource;
1711 // At least one resources is in the resource list, so we need to search for
1712 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
1714 if (strcmp(uri, pointer->uri) == 0) {
1715 OC_LOG(ERROR, TAG, PCF("URI already in use"));
1716 return OC_STACK_INVALID_PARAM;
1718 pointer = pointer->next;
1721 // Create the pointer and insert it into the resource list
1722 pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
1726 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
1728 insertResource(pointer);
1731 size = strlen(uri) + 1;
1732 str = (char *) OCMalloc(size);
1736 strncpy(str, uri, size);
1739 // Set properties. Set OC_ACTIVE
1740 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
1743 // Add the resourcetype to the resource
1744 result = BindResourceTypeToResource(pointer, resourceTypeName);
1745 if (result != OC_STACK_OK) {
1746 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
1750 // Add the resourceinterface to the resource
1751 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
1752 if (result != OC_STACK_OK) {
1753 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
1757 // If an entity handler has been passed, attach it to the newly created
1758 // resource. Otherwise, set the default entity handler.
1761 pointer->entityHandler = entityHandler;
1765 pointer->entityHandler = defaultResourceEHandler;
1769 result = OC_STACK_OK;
1771 #ifdef WITH_PRESENCE
1772 if(presenceResource.handle)
1774 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1775 SendPresenceNotification(pointer->rsrcType);
1779 if (result != OC_STACK_OK)
1781 // Deep delete of resource and other dynamic elements that it contains
1782 deleteResource(pointer);
1791 * Create a resource. with host ip address for remote resource
1793 * @param handle - pointer to handle to newly created resource. Set by ocstack.
1794 * Used to refer to resource
1795 * @param resourceTypeName - name of resource type. Example: "core.led"
1796 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1797 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
1798 * @param uri - URI of the resource. Example: "/a/led"
1799 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1800 * NULL for default entity handler
1801 * @param resourceProperties - properties supported by resource.
1802 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
1805 * OC_STACK_OK - no errors
1806 * OC_STACK_ERROR - stack process error
1809 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
1810 const char *resourceTypeName,
1811 const char *resourceInterfaceName,
1814 OCEntityHandler entityHandler,
1815 uint8_t resourceProperties)
1819 OCStackResult result = OC_STACK_ERROR;
1821 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
1822 uri, entityHandler, resourceProperties);
1824 if (result != OC_STACK_ERROR)
1827 size = strlen(host) + 1;
1828 str = (char *) OCMalloc(size);
1831 return OC_STACK_ERROR;
1833 strncpy(str, host, size);
1834 ((OCResource *) *handle)->host = str;
1841 * Add a resource to a collection resource.
1843 * @param collectionHandle - handle to the collection resource
1844 * @param resourceHandle - handle to resource to be added to the collection resource
1847 * OC_STACK_OK - no errors
1848 * OC_STACK_ERROR - stack process error
1849 * OC_STACK_INVALID_PARAM - invalid collectionhandle
1851 OCStackResult OCBindResource(
1852 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1853 OCResource *resource;
1856 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
1858 // Validate parameters
1859 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1860 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1861 // Container cannot contain itself
1862 if (collectionHandle == resourceHandle) {
1863 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
1864 return OC_STACK_INVALID_PARAM;
1867 // Use the handle to find the resource in the resource linked list
1868 resource = findResource((OCResource *) collectionHandle);
1870 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1871 return OC_STACK_INVALID_PARAM;
1874 // Look for an open slot to add add the child resource.
1875 // If found, add it and return success
1876 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1877 if (!resource->rsrcResources[i]) {
1878 resource->rsrcResources[i] = (OCResource *) resourceHandle;
1879 OC_LOG(INFO, TAG, PCF("resource bound"));
1884 #ifdef WITH_PRESENCE
1885 if(presenceResource.handle)
1887 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1888 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1892 // Unable to add resourceHandle, so return error
1893 return OC_STACK_ERROR;
1897 * Remove a resource from a collection resource.
1899 * @param collectionHandle - handle to the collection resource
1900 * @param resourceHandle - handle to resource to be added to the collection resource
1903 * OC_STACK_OK - no errors
1904 * OC_STACK_ERROR - stack process error
1905 * OC_STACK_INVALID_PARAM - invalid collectionHandle
1907 OCStackResult OCUnBindResource(
1908 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1909 OCResource *resource;
1912 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
1914 // Validate parameters
1915 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1916 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1917 // Container cannot contain itself
1918 if (collectionHandle == resourceHandle) {
1919 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
1920 return OC_STACK_INVALID_PARAM;
1923 // Use the handle to find the resource in the resource linked list
1924 resource = findResource((OCResource *) collectionHandle);
1926 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1927 return OC_STACK_INVALID_PARAM;
1930 // Look for an open slot to add add the child resource.
1931 // If found, add it and return success
1932 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1933 if (resourceHandle == resource->rsrcResources[i]) {
1934 resource->rsrcResources[i] = (OCResource *) NULL;
1935 OC_LOG(INFO, TAG, PCF("resource unbound"));
1940 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
1942 #ifdef WITH_PRESENCE
1943 if(presenceResource.handle)
1945 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1946 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1950 // Unable to add resourceHandle, so return error
1951 return OC_STACK_ERROR;
1954 OCStackResult BindResourceTypeToResource(OCResource* resource,
1955 const char *resourceTypeName)
1957 OCResourceType *pointer = NULL;
1960 OCStackResult result = OC_STACK_ERROR;
1962 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
1964 // Validate parameters
1965 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
1966 // TODO: Does resource attribute resentation really have to be maintained in stack?
1967 // Is it presented during resource discovery?
1969 TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
1971 // Create the resourcetype and insert it into the resource list
1972 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
1977 // Set the resourceTypeName
1978 size = strlen(resourceTypeName) + 1;
1979 str = (char *) OCMalloc(size);
1983 strncpy(str, resourceTypeName, size);
1984 pointer->resourcetypename = str;
1986 insertResourceType(resource, pointer);
1987 result = OC_STACK_OK;
1989 exit: if (result != OC_STACK_OK) {
1997 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
1998 const char *resourceInterfaceName)
2000 OCResourceInterface *pointer = NULL;
2003 OCStackResult result = OC_STACK_ERROR;
2005 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
2007 // Validate parameters
2008 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2010 TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
2012 // Create the resourceinterface and insert it into the resource list
2013 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
2018 // Set the resourceinterface name
2019 size = strlen(resourceInterfaceName) + 1;
2020 str = (char *) OCMalloc(size);
2024 strncpy(str, resourceInterfaceName, size);
2025 pointer->name = str;
2027 // Bind the resourceinterface to the resource
2028 insertResourceInterface(resource, pointer);
2030 result = OC_STACK_OK;
2032 exit: if (result != OC_STACK_OK) {
2041 * Bind a resourcetype to a resource.
2043 * @param handle - handle to the resource
2044 * @param resourceTypeName - name of resource type. Example: "core.led"
2047 * OC_STACK_OK - no errors
2048 * OC_STACK_ERROR - stack process error
2050 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2051 const char *resourceTypeName) {
2053 OCStackResult result = OC_STACK_ERROR;
2054 OCResource *resource;
2056 // Make sure resource exists
2057 resource = findResource((OCResource *) handle);
2059 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2060 return OC_STACK_ERROR;
2063 // call internal function
2064 result = BindResourceTypeToResource(resource, resourceTypeName);
2066 #ifdef WITH_PRESENCE
2067 if(presenceResource.handle)
2069 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2070 SendPresenceNotification(resource->rsrcType);
2078 * Bind a resourceinterface to a resource.
2080 * @param handle - handle to the resource
2081 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
2084 * OC_STACK_OK - no errors
2085 * OC_STACK_ERROR - stack process error
2088 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2089 const char *resourceInterfaceName) {
2091 OCStackResult result = OC_STACK_ERROR;
2092 OCResource *resource;
2094 // Make sure resource exists
2095 resource = findResource((OCResource *) handle);
2097 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2098 return OC_STACK_ERROR;
2101 // call internal function
2102 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2104 #ifdef WITH_PRESENCE
2105 if(presenceResource.handle)
2107 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2108 SendPresenceNotification(resource->rsrcType);
2116 * Get the number of resources that have been created in the stack.
2118 * @param numResources - pointer to count variable
2121 * OC_STACK_OK - no errors
2122 * OC_STACK_ERROR - stack process error
2125 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
2126 OCResource *pointer = headResource;
2128 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2129 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2132 *numResources = *numResources + 1;
2133 pointer = pointer->next;
2139 * Get a resource handle by index.
2141 * @param index - index of resource, 0 to Count - 1
2144 * Resource handle - if found
2145 * NULL - if not found
2147 OCResourceHandle OCGetResourceHandle(uint8_t index) {
2148 OCResource *pointer = headResource;
2151 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2153 // Iterate through the list
2154 while ((i < index) && pointer) {
2156 pointer = pointer->next;
2158 return (OCResourceHandle) pointer;
2162 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
2165 * @param handle - handle of resource to be deleted
2168 * OC_STACK_OK - no errors
2169 * OC_STACK_ERROR - stack process error
2170 * OC_STACK_NO_RESOURCE - resource not found
2171 * OC_STACK_INVALID_PARAM - invalid param
2173 OCStackResult OCDeleteResource(OCResourceHandle handle) {
2174 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2177 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2178 return OC_STACK_INVALID_PARAM;
2181 OCResource *resource = findResource((OCResource *) handle);
2182 if (resource == NULL) {
2183 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2184 return OC_STACK_NO_RESOURCE;
2187 if (deleteResource((OCResource *) handle) == 0) {
2188 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2189 return OC_STACK_ERROR;
2196 * Get the URI of the resource specified by handle.
2198 * @param handle - handle of resource
2200 * URI string - if resource found
2201 * NULL - resource not found
2203 const char *OCGetResourceUri(OCResourceHandle handle) {
2204 OCResource *resource;
2205 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2207 resource = findResource((OCResource *) handle);
2209 return resource->uri;
2211 return (const char *) NULL;
2215 * Get the properties of the resource specified by handle.
2216 * NOTE: that after a resource is created, the OC_ACTIVE property is set
2217 * for the resource by the stack.
2219 * @param handle - handle of resource
2221 * property bitmap - if resource found
2222 * NULL - resource not found
2224 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
2225 OCResource *resource;
2226 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2228 resource = findResource((OCResource *) handle);
2230 return resource->resourceProperties;
2236 * Get the number of resource types of the resource.
2238 * @param handle - handle of resource
2239 * @param numResourceTypes - pointer to count variable
2242 * OC_STACK_OK - no errors
2243 * OC_STACK_ERROR - stack process error
2245 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2246 uint8_t *numResourceTypes) {
2247 OCResource *resource;
2248 OCResourceType *pointer;
2250 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2251 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2252 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2254 *numResourceTypes = 0;
2256 resource = findResource((OCResource *) handle);
2258 pointer = resource->rsrcType;
2260 *numResourceTypes = *numResourceTypes + 1;
2261 pointer = pointer->next;
2268 * Get name of resource type of the resource.
2270 * @param handle - handle of resource
2271 * @param index - index of resource, 0 to Count - 1
2274 * resource type name - if resource found
2275 * NULL - resource not found
2277 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
2278 OCResourceType *resourceType;
2280 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2282 resourceType = findResourceTypeAtIndex(handle, index);
2284 return resourceType->resourcetypename;
2286 return (const char *) NULL;
2292 * Get the number of resource interfaces of the resource.
2294 * @param handle - handle of resource
2295 * @param numResources - pointer to count variable
2298 * OC_STACK_OK - no errors
2299 * OC_STACK_ERROR - stack process error
2301 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2302 uint8_t *numResourceInterfaces) {
2303 OCResourceInterface *pointer;
2304 OCResource *resource;
2306 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2308 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2309 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2311 *numResourceInterfaces = 0;
2312 resource = findResource((OCResource *) handle);
2314 pointer = resource->rsrcInterface;
2316 *numResourceInterfaces = *numResourceInterfaces + 1;
2317 pointer = pointer->next;
2324 * Get name of resource interface of the resource.
2326 * @param handle - handle of resource
2327 * @param index - index of resource, 0 to Count - 1
2330 * resource interface name - if resource found
2331 * NULL - resource not found
2333 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
2334 OCResourceInterface *resourceInterface;
2336 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2338 resourceInterface = findResourceInterfaceAtIndex(handle, index);
2339 if (resourceInterface) {
2340 return resourceInterface->name;
2342 return (const char *) NULL;
2346 * Get resource handle from the collection resource by index.
2348 * @param collectionHandle - handle of collection resource
2349 * @param index - index of contained resource, 0 to Count - 1
2352 * handle to resource - if resource found
2353 * NULL - resource not found
2355 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2357 OCResource *resource;
2359 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2361 if (index >= MAX_CONTAINED_RESOURCES) {
2365 resource = findResource((OCResource *) collectionHandle);
2370 return resource->rsrcResources[index];
2374 * Bind an entity handler to the resource.
2376 * @param handle - handle to the resource that the contained resource is to be bound
2377 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2379 * OC_STACK_OK - no errors
2380 * OC_STACK_ERROR - stack process error
2382 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2383 OCEntityHandler entityHandler) {
2384 OCResource *resource;
2386 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2388 // Validate parameters
2389 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2390 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2392 // Use the handle to find the resource in the resource linked list
2393 resource = findResource((OCResource *)handle);
2395 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2396 return OC_STACK_ERROR;
2400 resource->entityHandler = entityHandler;
2402 #ifdef WITH_PRESENCE
2403 if(presenceResource.handle)
2405 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2406 SendPresenceNotification(resource->rsrcType);
2414 * Get the entity handler for a resource.
2416 * @param handle - handle of resource
2419 * entity handler - if resource found
2420 * NULL - resource not found
2422 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
2423 OCResource *resource;
2425 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2427 // Use the handle to find the resource in the resource linked list
2428 resource = findResource((OCResource *)handle);
2430 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2435 return resource->entityHandler;
2438 void incrementSequenceNumber(OCResource * resPtr)
2440 // Increment the sequence number
2441 resPtr->sequenceNum += 1;
2442 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2444 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2450 * Notify Presence subscribers that a resource has been modified
2452 * @param resourceType - Handle to the resourceType linked list of resource
2453 * that was modified.
2454 * @param qos - Quality Of Service
2457 #ifdef WITH_PRESENCE
2458 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
2460 OCResource *resPtr = NULL;
2461 OCStackResult result;
2462 OCMethod method = OC_REST_PRESENCE;
2463 uint32_t maxAge = 0;
2464 resPtr = findResource((OCResource *) presenceResource.handle);
2467 return OC_STACK_NO_RESOURCE;
2469 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
2471 maxAge = presenceResource.presenceTTL;
2478 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
2481 #endif // WITH_PRESENCE
2483 * Notify observers that an observed value has changed.
2485 * @param handle - handle of resource
2488 * OC_STACK_OK - no errors
2489 * OC_STACK_NO_RESOURCE - invalid resource handle
2490 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
2492 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
2494 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2496 OCResource *resPtr = NULL;
2497 OCStackResult result;
2498 OCMethod method = OC_REST_NOMETHOD;
2499 uint32_t maxAge = 0;
2501 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2502 #ifdef WITH_PRESENCE
2503 if(handle == presenceResource.handle)
2507 #endif // WITH_PRESENCE
2508 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2510 // Verify that the resource exists
2511 resPtr = findResource ((OCResource *) handle);
2514 return OC_STACK_NO_RESOURCE;
2518 //only increment in the case of regular observing (not presence)
2519 incrementSequenceNumber(resPtr);
2520 method = OC_REST_OBSERVE;
2521 maxAge = MAX_OBSERVE_AGE;
2522 #ifdef WITH_PRESENCE
2523 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
2525 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
2532 OCNotifyListOfObservers (OCResourceHandle handle,
2533 OCObservationId *obsIdList,
2534 uint8_t numberOfIds,
2535 unsigned char *notificationJSONPayload,
2536 OCQualityOfService qos)
2538 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
2540 OCResource *resPtr = NULL;
2541 //TODO: we should allow the server to define this
2542 uint32_t maxAge = MAX_OBSERVE_AGE;
2544 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2545 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
2546 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
2548 // Verify that the resource exists
2549 resPtr = findResource ((OCResource *) handle);
2550 if (NULL == resPtr || myStackMode == OC_CLIENT)
2552 return OC_STACK_NO_RESOURCE;
2556 incrementSequenceNumber(resPtr);
2558 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
2559 notificationJSONPayload, maxAge, qos));
2563 * Send a response to a request.
2564 * The response can be a regular, slow, or block (i.e. a response that
2565 * is too large to be sent in a single PDU and must span multiple transmissions)
2567 * @param response - pointer to structure that contains response parameters
2570 * OC_STACK_OK - No errors; Success
2571 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
2572 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
2573 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
2574 * persistent response buffer is necessary
2576 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
2578 OCStackResult result = OC_STACK_ERROR;
2579 OCServerRequest *serverRequest = NULL;
2581 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
2583 // Validate input parameters
2584 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
2585 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
2587 // TODO: Placeholder for creating a response entry when implementing
2588 // block transfer feature
2590 // If a response payload is present, check if block transfer is required
2591 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
2592 (const char *)ehResponse->payload, ehResponse->payloadSize))
2594 OC_LOG(INFO, TAG, PCF("Block transfer required"));
2596 // Persistent response buffer is needed for block transfer
2597 if (!ehResponse->persistentBufferFlag)
2599 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
2600 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
2602 // TODO: Placeholder for block transfer handling
2603 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
2604 // when implementing the block transfer feature
2610 // Get pointer to request info
2611 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
2614 result = serverRequest->ehResponseHandler(ehResponse);
2621 * Cancel a response. Applies to a block response
2623 * @param responseHandle - response handle set by stack in OCServerResponse after
2624 * OCDoResponse is called
2627 * OC_STACK_OK - No errors; Success
2628 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
2630 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
2632 OCStackResult result = OC_STACK_NOTIMPL;
2634 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
2636 // TODO: validate response handle
2641 //-----------------------------------------------------------------------------
2642 // Private internal function definitions
2643 //-----------------------------------------------------------------------------
2645 * Generate handle of OCDoResource invocation for callback management.
2647 static OCDoHandle GenerateInvocationHandle()
2649 OCDoHandle handle = NULL;
2650 // Generate token here, it will be deleted when the transaction is deleted
2651 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2654 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2659 #ifdef WITH_PRESENCE
2660 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
2661 OCResourceProperty resourceProperties, uint8_t enable)
2663 if (resourceProperties
2664 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
2665 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2666 return OC_STACK_INVALID_PARAM;
2670 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
2674 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
2681 * Initialize resource data structures, variables, etc.
2683 OCStackResult initResources() {
2684 OCStackResult result = OC_STACK_OK;
2685 // Init application resource vars
2686 headResource = NULL;
2687 // Init Virtual Resources
2688 #ifdef WITH_PRESENCE
2689 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
2690 //presenceResource.token = OCGenerateCoAPToken();
2691 result = OCCreateResource(&presenceResource.handle,
2692 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
2697 //make resource inactive
2698 result = OCChangeResourceProperty(
2699 &(((OCResource *) presenceResource.handle)->resourceProperties),
2706 * Add a resource to the end of the linked list of resources.
2708 * @param resource - resource to be added
2710 void insertResource(OCResource *resource) {
2711 OCResource *pointer;
2713 if (!headResource) {
2714 headResource = resource;
2716 pointer = headResource;
2718 while (pointer->next) {
2719 pointer = pointer->next;
2721 pointer->next = resource;
2723 resource->next = NULL;
2727 * Find a resource in the linked list of resources.
2729 * @param resource - resource to be found
2731 * NULL - resource not found
2732 * pointer to resource - pointer to resource that was found in the linked list
2734 OCResource *findResource(OCResource *resource) {
2735 OCResource *pointer = headResource;
2738 if (pointer == resource) {
2741 pointer = pointer->next;
2746 void deleteAllResources()
2748 OCResource *pointer = headResource;
2753 temp = pointer->next;
2754 #ifdef WITH_PRESENCE
2755 if(pointer != (OCResource *) presenceResource.handle)
2757 #endif // WITH_PRESENCE
2758 deleteResource(pointer);
2759 #ifdef WITH_PRESENCE
2761 #endif // WITH_PRESENCE
2765 #ifdef WITH_PRESENCE
2766 // Ensure that the last resource to be deleted is the presence resource. This allows for all
2767 // presence notification attributed to their deletion to be processed.
2768 deleteResource((OCResource *) presenceResource.handle);
2769 #endif // WITH_PRESENCE
2773 * Delete the resource from the linked list.
2775 * @param resource - resource to be deleted
2780 int deleteResource(OCResource *resource) {
2781 OCResource *prev = NULL;
2784 temp = headResource;
2786 if (temp == resource) {
2787 // Invalidate all Resource Properties.
2788 resource->resourceProperties = (OCResourceProperty) 0;
2789 #ifdef WITH_PRESENCE
2790 if(resource != (OCResource *) presenceResource.handle)
2792 #endif // WITH_PRESENCE
2793 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
2794 #ifdef WITH_PRESENCE
2797 if(presenceResource.handle)
2799 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2800 if(resource != (OCResource *) presenceResource.handle)
2802 SendPresenceNotification(resource->rsrcType);
2806 SendPresenceNotification(NULL);
2811 if (temp == headResource) {
2812 headResource = temp->next;
2814 prev->next = temp->next;
2817 deleteResourceElements(temp);
2830 * Delete all of the dynamically allocated elements that were created for the resource.
2832 * @param resource - specified resource
2834 void deleteResourceElements(OCResource *resource) {
2840 OCFree(resource->uri);
2842 // Delete resourcetype linked list
2843 deleteResourceType(resource->rsrcType);
2845 // Delete resourceinterface linked list
2846 deleteResourceInterface(resource->rsrcInterface);
2850 * Delete all of the dynamically allocated elements that were created for the resource type.
2852 * @param resourceType - specified resource type
2854 void deleteResourceType(OCResourceType *resourceType) {
2855 OCResourceType *pointer = resourceType;
2856 OCResourceType *next;
2859 next = pointer->next;
2860 OCFree(pointer->resourcetypename);
2867 * Delete all of the dynamically allocated elements that were created for the resource interface.
2869 * @param resourceInterface - specified resource interface
2871 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
2872 OCResourceInterface *pointer = resourceInterface;
2873 OCResourceInterface *next;
2876 next = pointer->next;
2877 OCFree(pointer->name);
2884 * Insert a resource type into a resource's resource type linked list.
2886 * @param resource - resource where resource type is to be inserted
2887 * @param resourceType - resource type to be inserted
2889 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
2890 OCResourceType *pointer;
2892 if (resource && !resource->rsrcType) {
2893 resource->rsrcType = resourceType;
2897 pointer = resource->rsrcType;
2901 pointer = resourceType;
2903 while (pointer->next) {
2904 pointer = pointer->next;
2906 pointer->next = resourceType;
2908 resourceType->next = NULL;
2912 * Get a resource type at the specified index within a resource.
2914 * @param handle - handle of resource
2915 * @param index - index of resource type
2918 * resourcetype - if found
2921 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
2922 OCResource *resource;
2923 OCResourceType *pointer;
2926 // Find the specified resource
2927 resource = findResource((OCResource *) handle);
2932 // Make sure a resource has a resourcetype
2933 if (!resource->rsrcType) {
2937 // Iterate through the list
2938 pointer = resource->rsrcType;
2940 while ((i < index) && pointer) {
2942 pointer = pointer->next;
2948 * Finds a resource type in an OCResourceType link-list.
2950 * @param resourceTypeList - the link-list to be searched through
2951 * @param resourceTypeName - the key to search for
2954 * resourceType that matches the key (ie. resourceTypeName)
2955 * NULL - either an invalid parameter or this function was unable to find the key.
2957 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
2959 if(resourceTypeList && resourceTypeName)
2961 OCResourceType * rtPointer = resourceTypeList;
2962 while(resourceTypeName && rtPointer)
2964 if(rtPointer->resourcetypename &&
2965 strcmp(resourceTypeName, (const char *)
2966 (rtPointer->resourcetypename)) == 0)
2970 rtPointer = rtPointer->next;
2977 * Insert a resource interface into a resource's resource interface linked list.
2979 * @param resource - resource where resource interface is to be inserted
2980 * @param resourceInterface - resource interface to be inserted
2982 void insertResourceInterface(OCResource *resource,
2983 OCResourceInterface *resourceInterface) {
2984 OCResourceInterface *pointer;
2986 if (!resource->rsrcInterface) {
2987 resource->rsrcInterface = resourceInterface;
2989 pointer = resource->rsrcInterface;
2990 while (pointer->next) {
2991 pointer = pointer->next;
2993 pointer->next = resourceInterface;
2995 resourceInterface->next = NULL;
2999 * Get a resource interface at the specified index within a resource.
3001 * @param handle - handle of resource
3002 * @param index - index of resource interface
3005 * resourceinterface - if found
3008 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3010 OCResource *resource;
3011 OCResourceInterface *pointer;
3014 // Find the specified resource
3015 resource = findResource((OCResource *) handle);
3020 // Make sure a resource has a resourceinterface
3021 if (!resource->rsrcInterface) {
3025 // Iterate through the list
3026 pointer = resource->rsrcInterface;
3028 while ((i < index) && pointer) {
3030 pointer = pointer->next;
3036 * Determine if a request/response must be sent in a block transfer because it is too large to be
3037 * sent in a single PDU. This function can be used for either a request or a response
3039 * @param request - NULL or pointer to request
3040 * @param response - NULL or pointer to response
3041 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
3042 * the length of the request/response
3045 * 0 - packet transfer NOT required (i.e. normal request/response)
3046 * 1 - packet transfer required (i.e. block transfer needed)
3048 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
3052 // Determine if we are checking a request or a response
3055 // If size is greater than 0, use it for the request size value, otherwise
3056 // assume request is null terminated and use strlen for size value
3057 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
3064 // If size is greater than 0, use it for the response size value, otherwise
3065 // assume response is null terminated and use strlen for size value
3066 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3075 * Retrieves a resource type based upon a uri string if the uri string contains only just one
3076 * resource attribute (and that has to be of type "rt").
3078 * @remark This API malloc's memory for the resource type and newURI. Do not malloc resourceType
3079 * or newURI before passing in.
3081 * @param uri - Valid URI for "requiredUri" parameter to OCDoResource API.
3082 * @param resourceType - The resource type to be populated; pass by reference.
3083 * @param newURI - Return URI without resourceType appended to the end of it. This is used to
3084 * ensure that the uri parameter is not modified; pass by reference.
3087 * OC_STACK_INVALID_URI - Returns this if the URI is invalid/NULL.
3088 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
3089 * OC_STACK_OK - Success
3091 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI)
3095 return OC_STACK_INVALID_URI;
3097 if(!resourceType || !newURI)
3099 return OC_STACK_INVALID_PARAM;
3101 char * leftToken = NULL;
3102 char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3107 strcpy(tempURI, uri);
3109 leftToken = strtok_r((char *)tempURI, "?", &strTokPtr);
3111 while(leftToken != NULL)
3113 if(strncmp(leftToken, "rt=", 3) == 0)
3115 *resourceType = (unsigned char *) OCMalloc(strlen(leftToken)-3);
3120 strcpy((char *)*resourceType, ((const char *)&leftToken[3]));
3123 leftToken = strtok_r(NULL, "?", &strTokPtr);
3131 return OC_STACK_NO_MEMORY;
3134 const ServerID OCGetServerInstanceID(void)
3136 static bool generated = false;
3137 static ServerID sid;
3144 sid = OCGetRandom();
3149 const char* OCGetServerInstanceIDString(void)
3151 // max printed length of a base 10
3152 // uint32 is 10 characters, so 11 includes null.
3153 // This will change as the representation gets switched
3155 static char buffer[11];
3156 int n = sprintf(buffer, "%u", OCGetServerInstanceID());