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, uint8_t conType,
1086 OCQualityOfService qos, OCCallbackData *cbData,
1087 OCHeaderOption * options, uint8_t numOptions)
1089 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1090 const char *referenceUri, const char *request,
1091 OCQualityOfService qos, OCCallbackData *cbData,
1092 OCHeaderOption * options, uint8_t numOptions)
1095 OCStackResult result = OC_STACK_ERROR;
1097 ClientCB *clientCB = NULL;
1098 unsigned char * requestUri = NULL;
1099 unsigned char * resourceType = NULL;
1100 char * newUri = (char *)requiredUri;
1101 (void) referenceUri;
1103 CARemoteEndpoint_t* endpoint = NULL;
1104 CAResult_t caResult;
1105 CAToken_t caToken = NULL;
1106 CAInfo_t requestData;
1107 CARequestInfo_t requestInfo;
1108 // To track if memory is allocated for additional header options
1109 uint8_t hdrOptionMemAlloc = 0;
1112 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1114 // Validate input parameters
1115 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1116 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1118 TODO ("Need to form the final query by concatenating require and reference URI's");
1119 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
1121 uint16_t uriLen = strlen(requiredUri);
1123 // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS
1129 case OC_REST_DELETE:
1130 case OC_REST_OBSERVE:
1131 case OC_REST_OBSERVE_ALL:
1132 case OC_REST_CANCEL_OBSERVE:
1134 #ifdef WITH_PRESENCE
1135 case OC_REST_PRESENCE:
1139 result = OC_STACK_INVALID_METHOD;
1143 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
1148 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
1150 result = OC_STACK_INVALID_PARAM;
1154 #ifdef WITH_PRESENCE
1155 if(method == OC_REST_PRESENCE)
1157 result = getResourceType(requiredUri, &resourceType, &newUri);
1159 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1163 OC_LOG(DEBUG, TAG, PCF("Got Resource Type is NULL."));
1165 if(result != OC_STACK_OK)
1170 #endif // WITH_PRESENCE
1172 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
1175 memcpy(requestUri, newUri, (uriLen + 1));
1179 result = OC_STACK_NO_MEMORY;
1183 *handle = GenerateInvocationHandle();
1186 result = OC_STACK_NO_MEMORY;
1191 memset(&requestData, 0, sizeof(CAInfo_t));
1192 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1196 case OC_REST_OBSERVE:
1197 case OC_REST_OBSERVE_ALL:
1198 case OC_REST_CANCEL_OBSERVE:
1200 requestInfo.method = CA_GET;
1205 requestInfo.method = CA_PUT;
1210 requestInfo.method = CA_POST;
1213 case OC_REST_DELETE:
1215 requestInfo.method = CA_DELETE;
1218 #ifdef WITH_PRESENCE
1219 case OC_REST_PRESENCE:
1220 //TODO-CA: What should be the CA method?
1224 result = OC_STACK_INVALID_METHOD;
1228 // TODO-CA: Handle multi-cast scenario
1229 // Create remote end point
1230 caResult = CACreateRemoteEndpoint(newUri, CA_WIFI, &endpoint);
1231 // TODO-CA: Connectivity type should be passed to API
1232 endpoint->connectivityType = CA_WIFI;
1233 if (caResult != CA_STATUS_OK)
1235 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1240 caResult = CAGenerateToken(&caToken);
1242 if (caResult != CA_STATUS_OK)
1244 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1249 // TODO-CA: Map QoS to the right CA msg type
1250 requestData.type = CA_MSG_NONCONFIRM;
1251 requestData.token = caToken;
1252 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
1254 result = CreateObserveHeaderOption (&(requestData.options), options,
1255 numOptions, OC_OBSERVE_REGISTER);
1256 if (result != OC_STACK_OK)
1260 hdrOptionMemAlloc = 1;
1261 requestData.numOptions = numOptions + 1;
1265 requestData.options = (CAHeaderOption_t*)options;
1266 requestData.numOptions = numOptions;
1268 requestData.payload = (char *)request;
1270 requestInfo.info = requestData;
1273 caResult = CASendRequest(endpoint, &requestInfo);
1274 if (caResult != CA_STATUS_OK)
1276 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1280 if((result = AddClientCB(&clientCB, cbData, &caToken, handle, method,
1281 requestUri, resourceType)) != OC_STACK_OK)
1283 result = OC_STACK_NO_MEMORY;
1289 // Generate token which will be used by OCStack to match responses received
1291 OCGenerateCoAPToken(&token);
1293 if((result = AddClientCB(&clientCB, cbData, &token, handle, method, requestUri, resourceType))
1296 result = OC_STACK_NO_MEMORY;
1300 #ifdef WITH_PRESENCE
1301 if(method == OC_REST_PRESENCE)
1303 // Replacing method type with GET because "presence" is a stack layer only implementation.
1304 method = OC_REST_GET;
1308 // Make call to OCCoAP layer
1309 result = OCDoCoAPResource(method, qos, &token, newUri, request, options, numOptions);
1313 if(newUri != requiredUri)
1317 if (result != OC_STACK_OK)
1319 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1320 FindAndDeleteClientCB(clientCB);
1323 CADestroyRemoteEndpoint(endpoint);
1324 if (hdrOptionMemAlloc)
1326 OCFree(requestData.options);
1333 * Cancel a request associated with a specific @ref OCDoResource invocation.
1335 * @param handle - Used to identify a specific OCDoResource invocation.
1336 * @param qos - used to specify Quality of Service (read below for more info)
1337 * @param options- used to specify vendor specific header options when sending
1338 * explicit observe cancellation
1339 * @param numOptions- Number of header options to be included
1342 * OC_STACK_OK - No errors; Success
1343 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1345 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1349 * This ftn is implemented one of two ways in the case of observation:
1351 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1352 * Remove the callback associated on client side.
1353 * When the next notification comes in from server,
1354 * reply with RESET message to server.
1355 * Keep in mind that the server will react to RESET only
1356 * if the last notification was sent ans CON
1358 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1359 * and it is associated with an observe request
1360 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1361 * Send CON Observe request to server with
1362 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1363 * Remove the callback associated on client side.
1365 OCStackResult ret = OC_STACK_OK;
1367 CARemoteEndpoint_t* endpoint = NULL;
1368 CAResult_t caResult;
1369 CAInfo_t requestData;
1370 CARequestInfo_t requestInfo;
1371 // Track if memory is allocated for additional header options
1372 uint8_t hdrOptionMemAlloc = 0;
1376 return OC_STACK_INVALID_PARAM;
1379 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1381 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1384 switch (clientCB->method)
1386 case OC_REST_OBSERVE:
1387 case OC_REST_OBSERVE_ALL:
1389 caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri, CA_WIFI,
1391 endpoint->connectivityType = CA_WIFI;
1392 if (caResult != CA_STATUS_OK)
1394 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1395 return OC_STACK_ERROR;
1398 memset(&requestData, 0, sizeof(CAInfo_t));
1399 // TODO-CA: Map QoS to the right CA msg type
1400 requestData.type = CA_MSG_NONCONFIRM;
1401 requestData.token = clientCB->token;
1402 if (CreateObserveHeaderOption (&(requestData.options),
1403 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
1405 return OC_STACK_ERROR;
1407 hdrOptionMemAlloc = 1;
1408 requestData.numOptions = numOptions + 1;
1409 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1410 requestInfo.method = CA_GET;
1411 requestInfo.info = requestData;
1413 caResult = CASendRequest(endpoint, &requestInfo);
1414 if (caResult != CA_STATUS_OK)
1416 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
1418 if(caResult == CA_STATUS_OK)
1423 if(qos == OC_HIGH_QOS)
1425 ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
1426 &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
1431 FindAndDeleteClientCB(clientCB);
1435 #ifdef WITH_PRESENCE
1436 case OC_REST_PRESENCE:
1437 FindAndDeleteClientCB(clientCB);
1441 return OC_STACK_INVALID_METHOD;
1445 CADestroyRemoteEndpoint(endpoint);
1446 if (hdrOptionMemAlloc)
1448 OCFree(requestData.options);
1454 #ifdef WITH_PRESENCE
1455 OCStackResult OCProcessPresence()
1457 OCStackResult result = OC_STACK_OK;
1458 uint8_t ipAddr[4] = { 0 };
1461 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1462 ClientCB* cbNode = NULL;
1464 OCClientResponse clientResponse;
1465 OCResponse * response = NULL;
1467 LL_FOREACH(cbList, cbNode) {
1468 if(OC_REST_PRESENCE == cbNode->method)
1470 if(cbNode->presence)
1472 uint32_t now = GetTime(0);
1473 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
1474 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1477 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1482 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1483 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1484 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1487 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1489 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1490 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1492 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1494 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
1495 (OCDevAddr *) &dst, 0, NULL);
1496 if(result != OC_STACK_OK)
1500 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1501 &cbNode->token, &clientResponse, NULL);
1502 if(result != OC_STACK_OK)
1507 // Increment the TTLLevel (going to a next state), so we don't keep
1508 // sending presence notification to client.
1509 cbNode->presence->TTLlevel++;
1510 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1511 cbNode->presence->TTLlevel);
1515 result = OC_STACK_INVALID_IP;
1518 HandleStackResponses(response);
1520 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1522 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
1524 OCGenerateCoAPToken(&token);
1525 result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
1526 &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
1527 if(result != OC_STACK_OK)
1531 cbNode->presence->TTLlevel++;
1532 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
1538 if (result != OC_STACK_OK)
1540 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
1547 * Called in main loop of OC client or server. Allows low-level processing of
1551 * OC_STACK_OK - no errors
1552 * OC_STACK_ERROR - stack process error
1554 OCStackResult OCProcess() {
1556 OC_LOG(INFO, TAG, PCF("Entering OCProcess"));
1557 #ifdef WITH_PRESENCE
1558 OCProcessPresence();
1561 CAHandleRequestResponse();
1569 #ifdef WITH_PRESENCE
1571 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
1572 * presence notifications to clients via multicast. Once this API has been called with a success,
1573 * clients may query for this server's presence and this server's stack will respond via multicast.
1575 * Server can call this function when it comes online for the first time, or when it comes back
1576 * online from offline mode, or when it re enters network.
1578 * @param ttl - Time To Live in seconds
1579 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
1582 * OC_STACK_OK - No errors; Success
1584 OCStackResult OCStartPresence(const uint32_t ttl)
1586 OCChangeResourceProperty(
1587 &(((OCResource *)presenceResource.handle)->resourceProperties),
1592 presenceResource.presenceTTL = ttl;
1595 if(OC_PRESENCE_UNINITIALIZED == presenceState)
1597 OCDevAddr multiCastAddr;
1600 presenceState = OC_PRESENCE_INITIALIZED;
1601 OCGenerateCoAPToken(&token);
1602 OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
1603 //add the presence observer
1604 AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
1605 (OCResource *)presenceResource.handle, OC_LOW_QOS);
1608 // Each time OCStartPresence is called
1609 // a different random 32-bit integer number is used
1610 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1612 return SendPresenceNotification(NULL);
1616 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
1617 * presence notifications to clients via multicast. Once this API has been called with a success,
1618 * this server's stack will not respond to clients querying for this server's presence.
1620 * Server can call this function when it is terminating, going offline, or when going
1621 * away from network.
1624 * OC_STACK_OK - No errors; Success
1626 OCStackResult OCStopPresence()
1628 OCStackResult result = OC_STACK_ERROR;
1629 //make resource inactive
1630 result = OCChangeResourceProperty(
1631 &(((OCResource *) presenceResource.handle)->resourceProperties),
1633 result = SendPresenceNotification(NULL);
1640 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
1642 defaultDeviceHandler = entityHandler;
1647 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
1649 OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
1651 if(myStackMode == OC_CLIENT)
1653 return OC_STACK_ERROR;
1656 return SaveDeviceInfo(deviceInfo);
1662 * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource
1663 * @param resourceTypeName - name of resource type. Example: "core.led"
1664 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1665 * @param uri - URI of the resource. Example: "/a/led"
1666 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1667 * NULL for default entity handler
1668 * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE
1671 * OC_STACK_OK - no errors
1672 * OC_STACK_ERROR - stack process error
1674 OCStackResult OCCreateResource(OCResourceHandle *handle,
1675 const char *resourceTypeName,
1676 const char *resourceInterfaceName,
1677 const char *uri, OCEntityHandler entityHandler,
1678 uint8_t resourceProperties) {
1680 OCResource *pointer = NULL;
1683 OCStackResult result = OC_STACK_ERROR;
1685 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
1687 if(myStackMode == OC_CLIENT)
1691 // Validate parameters
1692 if(!uri || (strlen(uri) == 0))
1694 OC_LOG(ERROR, TAG, PCF("URI is invalid"));
1695 return OC_STACK_INVALID_URI;
1697 // Is it presented during resource discovery?
1698 if (!handle || !resourceTypeName) {
1699 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
1700 return OC_STACK_INVALID_PARAM;
1703 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
1704 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
1707 // Make sure resourceProperties bitmask has allowed properties specified
1708 if (resourceProperties
1709 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
1710 OC_LOG(ERROR, TAG, PCF("Invalid property"));
1711 return OC_STACK_INVALID_PARAM;
1714 // If the headResource is NULL, then no resources have been created...
1715 pointer = headResource;
1717 // At least one resources is in the resource list, so we need to search for
1718 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
1720 if (strcmp(uri, pointer->uri) == 0) {
1721 OC_LOG(ERROR, TAG, PCF("URI already in use"));
1722 return OC_STACK_INVALID_PARAM;
1724 pointer = pointer->next;
1727 // Create the pointer and insert it into the resource list
1728 pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
1732 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
1734 insertResource(pointer);
1737 size = strlen(uri) + 1;
1738 str = (char *) OCMalloc(size);
1742 strncpy(str, uri, size);
1745 // Set properties. Set OC_ACTIVE
1746 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
1749 // Add the resourcetype to the resource
1750 result = BindResourceTypeToResource(pointer, resourceTypeName);
1751 if (result != OC_STACK_OK) {
1752 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
1756 // Add the resourceinterface to the resource
1757 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
1758 if (result != OC_STACK_OK) {
1759 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
1763 // If an entity handler has been passed, attach it to the newly created
1764 // resource. Otherwise, set the default entity handler.
1767 pointer->entityHandler = entityHandler;
1771 pointer->entityHandler = defaultResourceEHandler;
1775 result = OC_STACK_OK;
1777 #ifdef WITH_PRESENCE
1778 if(presenceResource.handle)
1780 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1781 SendPresenceNotification(pointer->rsrcType);
1785 if (result != OC_STACK_OK)
1787 // Deep delete of resource and other dynamic elements that it contains
1788 deleteResource(pointer);
1797 * Create a resource. with host ip address for remote resource
1799 * @param handle - pointer to handle to newly created resource. Set by ocstack.
1800 * Used to refer to resource
1801 * @param resourceTypeName - name of resource type. Example: "core.led"
1802 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1803 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
1804 * @param uri - URI of the resource. Example: "/a/led"
1805 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1806 * NULL for default entity handler
1807 * @param resourceProperties - properties supported by resource.
1808 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
1811 * OC_STACK_OK - no errors
1812 * OC_STACK_ERROR - stack process error
1815 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
1816 const char *resourceTypeName,
1817 const char *resourceInterfaceName,
1820 OCEntityHandler entityHandler,
1821 uint8_t resourceProperties)
1825 OCStackResult result = OC_STACK_ERROR;
1827 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
1828 uri, entityHandler, resourceProperties);
1830 if (result != OC_STACK_ERROR)
1833 size = strlen(host) + 1;
1834 str = (char *) OCMalloc(size);
1837 return OC_STACK_ERROR;
1839 strncpy(str, host, size);
1840 ((OCResource *) *handle)->host = str;
1847 * Add a resource to a collection resource.
1849 * @param collectionHandle - handle to the collection resource
1850 * @param resourceHandle - handle to resource to be added to the collection resource
1853 * OC_STACK_OK - no errors
1854 * OC_STACK_ERROR - stack process error
1855 * OC_STACK_INVALID_PARAM - invalid collectionhandle
1857 OCStackResult OCBindResource(
1858 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1859 OCResource *resource;
1862 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
1864 // Validate parameters
1865 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1866 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1867 // Container cannot contain itself
1868 if (collectionHandle == resourceHandle) {
1869 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
1870 return OC_STACK_INVALID_PARAM;
1873 // Use the handle to find the resource in the resource linked list
1874 resource = findResource((OCResource *) collectionHandle);
1876 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1877 return OC_STACK_INVALID_PARAM;
1880 // Look for an open slot to add add the child resource.
1881 // If found, add it and return success
1882 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1883 if (!resource->rsrcResources[i]) {
1884 resource->rsrcResources[i] = (OCResource *) resourceHandle;
1885 OC_LOG(INFO, TAG, PCF("resource bound"));
1890 #ifdef WITH_PRESENCE
1891 if(presenceResource.handle)
1893 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1894 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1898 // Unable to add resourceHandle, so return error
1899 return OC_STACK_ERROR;
1903 * Remove a resource from a collection resource.
1905 * @param collectionHandle - handle to the collection resource
1906 * @param resourceHandle - handle to resource to be added to the collection resource
1909 * OC_STACK_OK - no errors
1910 * OC_STACK_ERROR - stack process error
1911 * OC_STACK_INVALID_PARAM - invalid collectionHandle
1913 OCStackResult OCUnBindResource(
1914 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1915 OCResource *resource;
1918 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
1920 // Validate parameters
1921 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1922 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1923 // Container cannot contain itself
1924 if (collectionHandle == resourceHandle) {
1925 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
1926 return OC_STACK_INVALID_PARAM;
1929 // Use the handle to find the resource in the resource linked list
1930 resource = findResource((OCResource *) collectionHandle);
1932 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1933 return OC_STACK_INVALID_PARAM;
1936 // Look for an open slot to add add the child resource.
1937 // If found, add it and return success
1938 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1939 if (resourceHandle == resource->rsrcResources[i]) {
1940 resource->rsrcResources[i] = (OCResource *) NULL;
1941 OC_LOG(INFO, TAG, PCF("resource unbound"));
1946 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
1948 #ifdef WITH_PRESENCE
1949 if(presenceResource.handle)
1951 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1952 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1956 // Unable to add resourceHandle, so return error
1957 return OC_STACK_ERROR;
1960 OCStackResult BindResourceTypeToResource(OCResource* resource,
1961 const char *resourceTypeName)
1963 OCResourceType *pointer = NULL;
1966 OCStackResult result = OC_STACK_ERROR;
1968 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
1970 // Validate parameters
1971 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
1972 // TODO: Does resource attribute resentation really have to be maintained in stack?
1973 // Is it presented during resource discovery?
1975 TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
1977 // Create the resourcetype and insert it into the resource list
1978 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
1983 // Set the resourceTypeName
1984 size = strlen(resourceTypeName) + 1;
1985 str = (char *) OCMalloc(size);
1989 strncpy(str, resourceTypeName, size);
1990 pointer->resourcetypename = str;
1992 insertResourceType(resource, pointer);
1993 result = OC_STACK_OK;
1995 exit: if (result != OC_STACK_OK) {
2003 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2004 const char *resourceInterfaceName)
2006 OCResourceInterface *pointer = NULL;
2009 OCStackResult result = OC_STACK_ERROR;
2011 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
2013 // Validate parameters
2014 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2016 TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
2018 // Create the resourceinterface and insert it into the resource list
2019 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
2024 // Set the resourceinterface name
2025 size = strlen(resourceInterfaceName) + 1;
2026 str = (char *) OCMalloc(size);
2030 strncpy(str, resourceInterfaceName, size);
2031 pointer->name = str;
2033 // Bind the resourceinterface to the resource
2034 insertResourceInterface(resource, pointer);
2036 result = OC_STACK_OK;
2038 exit: if (result != OC_STACK_OK) {
2047 * Bind a resourcetype to a resource.
2049 * @param handle - handle to the resource
2050 * @param resourceTypeName - name of resource type. Example: "core.led"
2053 * OC_STACK_OK - no errors
2054 * OC_STACK_ERROR - stack process error
2056 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2057 const char *resourceTypeName) {
2059 OCStackResult result = OC_STACK_ERROR;
2060 OCResource *resource;
2062 // Make sure resource exists
2063 resource = findResource((OCResource *) handle);
2065 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2066 return OC_STACK_ERROR;
2069 // call internal function
2070 result = BindResourceTypeToResource(resource, resourceTypeName);
2072 #ifdef WITH_PRESENCE
2073 if(presenceResource.handle)
2075 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2076 SendPresenceNotification(resource->rsrcType);
2084 * Bind a resourceinterface to a resource.
2086 * @param handle - handle to the resource
2087 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
2090 * OC_STACK_OK - no errors
2091 * OC_STACK_ERROR - stack process error
2094 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2095 const char *resourceInterfaceName) {
2097 OCStackResult result = OC_STACK_ERROR;
2098 OCResource *resource;
2100 // Make sure resource exists
2101 resource = findResource((OCResource *) handle);
2103 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2104 return OC_STACK_ERROR;
2107 // call internal function
2108 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2110 #ifdef WITH_PRESENCE
2111 if(presenceResource.handle)
2113 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2114 SendPresenceNotification(resource->rsrcType);
2122 * Get the number of resources that have been created in the stack.
2124 * @param numResources - pointer to count variable
2127 * OC_STACK_OK - no errors
2128 * OC_STACK_ERROR - stack process error
2131 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
2132 OCResource *pointer = headResource;
2134 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2135 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2138 *numResources = *numResources + 1;
2139 pointer = pointer->next;
2145 * Get a resource handle by index.
2147 * @param index - index of resource, 0 to Count - 1
2150 * Resource handle - if found
2151 * NULL - if not found
2153 OCResourceHandle OCGetResourceHandle(uint8_t index) {
2154 OCResource *pointer = headResource;
2157 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2159 // Iterate through the list
2160 while ((i < index) && pointer) {
2162 pointer = pointer->next;
2164 return (OCResourceHandle) pointer;
2168 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
2171 * @param handle - handle of resource to be deleted
2174 * OC_STACK_OK - no errors
2175 * OC_STACK_ERROR - stack process error
2176 * OC_STACK_NO_RESOURCE - resource not found
2177 * OC_STACK_INVALID_PARAM - invalid param
2179 OCStackResult OCDeleteResource(OCResourceHandle handle) {
2180 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2183 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2184 return OC_STACK_INVALID_PARAM;
2187 OCResource *resource = findResource((OCResource *) handle);
2188 if (resource == NULL) {
2189 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2190 return OC_STACK_NO_RESOURCE;
2193 if (deleteResource((OCResource *) handle) == 0) {
2194 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2195 return OC_STACK_ERROR;
2202 * Get the URI of the resource specified by handle.
2204 * @param handle - handle of resource
2206 * URI string - if resource found
2207 * NULL - resource not found
2209 const char *OCGetResourceUri(OCResourceHandle handle) {
2210 OCResource *resource;
2211 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2213 resource = findResource((OCResource *) handle);
2215 return resource->uri;
2217 return (const char *) NULL;
2221 * Get the properties of the resource specified by handle.
2222 * NOTE: that after a resource is created, the OC_ACTIVE property is set
2223 * for the resource by the stack.
2225 * @param handle - handle of resource
2227 * property bitmap - if resource found
2228 * NULL - resource not found
2230 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
2231 OCResource *resource;
2232 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2234 resource = findResource((OCResource *) handle);
2236 return resource->resourceProperties;
2242 * Get the number of resource types of the resource.
2244 * @param handle - handle of resource
2245 * @param numResourceTypes - pointer to count variable
2248 * OC_STACK_OK - no errors
2249 * OC_STACK_ERROR - stack process error
2251 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2252 uint8_t *numResourceTypes) {
2253 OCResource *resource;
2254 OCResourceType *pointer;
2256 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2257 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2258 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2260 *numResourceTypes = 0;
2262 resource = findResource((OCResource *) handle);
2264 pointer = resource->rsrcType;
2266 *numResourceTypes = *numResourceTypes + 1;
2267 pointer = pointer->next;
2274 * Get name of resource type of the resource.
2276 * @param handle - handle of resource
2277 * @param index - index of resource, 0 to Count - 1
2280 * resource type name - if resource found
2281 * NULL - resource not found
2283 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
2284 OCResourceType *resourceType;
2286 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2288 resourceType = findResourceTypeAtIndex(handle, index);
2290 return resourceType->resourcetypename;
2292 return (const char *) NULL;
2298 * Get the number of resource interfaces of the resource.
2300 * @param handle - handle of resource
2301 * @param numResources - pointer to count variable
2304 * OC_STACK_OK - no errors
2305 * OC_STACK_ERROR - stack process error
2307 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2308 uint8_t *numResourceInterfaces) {
2309 OCResourceInterface *pointer;
2310 OCResource *resource;
2312 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2314 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2315 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2317 *numResourceInterfaces = 0;
2318 resource = findResource((OCResource *) handle);
2320 pointer = resource->rsrcInterface;
2322 *numResourceInterfaces = *numResourceInterfaces + 1;
2323 pointer = pointer->next;
2330 * Get name of resource interface of the resource.
2332 * @param handle - handle of resource
2333 * @param index - index of resource, 0 to Count - 1
2336 * resource interface name - if resource found
2337 * NULL - resource not found
2339 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
2340 OCResourceInterface *resourceInterface;
2342 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2344 resourceInterface = findResourceInterfaceAtIndex(handle, index);
2345 if (resourceInterface) {
2346 return resourceInterface->name;
2348 return (const char *) NULL;
2352 * Get resource handle from the collection resource by index.
2354 * @param collectionHandle - handle of collection resource
2355 * @param index - index of contained resource, 0 to Count - 1
2358 * handle to resource - if resource found
2359 * NULL - resource not found
2361 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2363 OCResource *resource;
2365 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2367 if (index >= MAX_CONTAINED_RESOURCES) {
2371 resource = findResource((OCResource *) collectionHandle);
2376 return resource->rsrcResources[index];
2380 * Bind an entity handler to the resource.
2382 * @param handle - handle to the resource that the contained resource is to be bound
2383 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2385 * OC_STACK_OK - no errors
2386 * OC_STACK_ERROR - stack process error
2388 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2389 OCEntityHandler entityHandler) {
2390 OCResource *resource;
2392 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2394 // Validate parameters
2395 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2396 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2398 // Use the handle to find the resource in the resource linked list
2399 resource = findResource((OCResource *)handle);
2401 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2402 return OC_STACK_ERROR;
2406 resource->entityHandler = entityHandler;
2408 #ifdef WITH_PRESENCE
2409 if(presenceResource.handle)
2411 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2412 SendPresenceNotification(resource->rsrcType);
2420 * Get the entity handler for a resource.
2422 * @param handle - handle of resource
2425 * entity handler - if resource found
2426 * NULL - resource not found
2428 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
2429 OCResource *resource;
2431 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2433 // Use the handle to find the resource in the resource linked list
2434 resource = findResource((OCResource *)handle);
2436 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2441 return resource->entityHandler;
2444 void incrementSequenceNumber(OCResource * resPtr)
2446 // Increment the sequence number
2447 resPtr->sequenceNum += 1;
2448 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2450 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2456 * Notify Presence subscribers that a resource has been modified
2458 * @param resourceType - Handle to the resourceType linked list of resource
2459 * that was modified.
2460 * @param qos - Quality Of Service
2463 #ifdef WITH_PRESENCE
2464 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
2466 OCResource *resPtr = NULL;
2467 OCStackResult result;
2468 OCMethod method = OC_REST_PRESENCE;
2469 uint32_t maxAge = 0;
2470 resPtr = findResource((OCResource *) presenceResource.handle);
2473 return OC_STACK_NO_RESOURCE;
2475 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
2477 maxAge = presenceResource.presenceTTL;
2484 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
2487 #endif // WITH_PRESENCE
2489 * Notify observers that an observed value has changed.
2491 * @param handle - handle of resource
2494 * OC_STACK_OK - no errors
2495 * OC_STACK_NO_RESOURCE - invalid resource handle
2496 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
2498 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
2500 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2502 OCResource *resPtr = NULL;
2503 OCStackResult result;
2504 OCMethod method = OC_REST_NOMETHOD;
2505 uint32_t maxAge = 0;
2507 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2508 #ifdef WITH_PRESENCE
2509 if(handle == presenceResource.handle)
2513 #endif // WITH_PRESENCE
2514 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2516 // Verify that the resource exists
2517 resPtr = findResource ((OCResource *) handle);
2520 return OC_STACK_NO_RESOURCE;
2524 //only increment in the case of regular observing (not presence)
2525 incrementSequenceNumber(resPtr);
2526 method = OC_REST_OBSERVE;
2527 maxAge = MAX_OBSERVE_AGE;
2528 #ifdef WITH_PRESENCE
2529 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
2531 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
2538 OCNotifyListOfObservers (OCResourceHandle handle,
2539 OCObservationId *obsIdList,
2540 uint8_t numberOfIds,
2541 unsigned char *notificationJSONPayload,
2542 OCQualityOfService qos)
2544 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
2546 OCResource *resPtr = NULL;
2547 //TODO: we should allow the server to define this
2548 uint32_t maxAge = MAX_OBSERVE_AGE;
2550 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2551 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
2552 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
2554 // Verify that the resource exists
2555 resPtr = findResource ((OCResource *) handle);
2556 if (NULL == resPtr || myStackMode == OC_CLIENT)
2558 return OC_STACK_NO_RESOURCE;
2562 incrementSequenceNumber(resPtr);
2564 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
2565 notificationJSONPayload, maxAge, qos));
2569 * Send a response to a request.
2570 * The response can be a regular, slow, or block (i.e. a response that
2571 * is too large to be sent in a single PDU and must span multiple transmissions)
2573 * @param response - pointer to structure that contains response parameters
2576 * OC_STACK_OK - No errors; Success
2577 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
2578 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
2579 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
2580 * persistent response buffer is necessary
2582 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
2584 OCStackResult result = OC_STACK_ERROR;
2585 OCServerRequest *serverRequest = NULL;
2587 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
2589 // Validate input parameters
2590 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
2591 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
2593 // TODO: Placeholder for creating a response entry when implementing
2594 // block transfer feature
2596 // If a response payload is present, check if block transfer is required
2597 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
2598 (const char *)ehResponse->payload, ehResponse->payloadSize))
2600 OC_LOG(INFO, TAG, PCF("Block transfer required"));
2602 // Persistent response buffer is needed for block transfer
2603 if (!ehResponse->persistentBufferFlag)
2605 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
2606 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
2608 // TODO: Placeholder for block transfer handling
2609 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
2610 // when implementing the block transfer feature
2616 // Get pointer to request info
2617 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
2620 result = serverRequest->ehResponseHandler(ehResponse);
2627 * Cancel a response. Applies to a block response
2629 * @param responseHandle - response handle set by stack in OCServerResponse after
2630 * OCDoResponse is called
2633 * OC_STACK_OK - No errors; Success
2634 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
2636 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
2638 OCStackResult result = OC_STACK_NOTIMPL;
2640 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
2642 // TODO: validate response handle
2647 //-----------------------------------------------------------------------------
2648 // Private internal function definitions
2649 //-----------------------------------------------------------------------------
2651 * Generate handle of OCDoResource invocation for callback management.
2653 static OCDoHandle GenerateInvocationHandle()
2655 OCDoHandle handle = NULL;
2656 // Generate token here, it will be deleted when the transaction is deleted
2657 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2660 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2665 #ifdef WITH_PRESENCE
2666 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
2667 OCResourceProperty resourceProperties, uint8_t enable)
2669 if (resourceProperties
2670 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
2671 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2672 return OC_STACK_INVALID_PARAM;
2676 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
2680 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
2687 * Initialize resource data structures, variables, etc.
2689 OCStackResult initResources() {
2690 OCStackResult result = OC_STACK_OK;
2691 // Init application resource vars
2692 headResource = NULL;
2693 // Init Virtual Resources
2694 #ifdef WITH_PRESENCE
2695 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
2696 //presenceResource.token = OCGenerateCoAPToken();
2697 result = OCCreateResource(&presenceResource.handle,
2698 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
2703 //make resource inactive
2704 result = OCChangeResourceProperty(
2705 &(((OCResource *) presenceResource.handle)->resourceProperties),
2712 * Add a resource to the end of the linked list of resources.
2714 * @param resource - resource to be added
2716 void insertResource(OCResource *resource) {
2717 OCResource *pointer;
2719 if (!headResource) {
2720 headResource = resource;
2722 pointer = headResource;
2724 while (pointer->next) {
2725 pointer = pointer->next;
2727 pointer->next = resource;
2729 resource->next = NULL;
2733 * Find a resource in the linked list of resources.
2735 * @param resource - resource to be found
2737 * NULL - resource not found
2738 * pointer to resource - pointer to resource that was found in the linked list
2740 OCResource *findResource(OCResource *resource) {
2741 OCResource *pointer = headResource;
2744 if (pointer == resource) {
2747 pointer = pointer->next;
2752 void deleteAllResources()
2754 OCResource *pointer = headResource;
2759 temp = pointer->next;
2760 #ifdef WITH_PRESENCE
2761 if(pointer != (OCResource *) presenceResource.handle)
2763 #endif // WITH_PRESENCE
2764 deleteResource(pointer);
2765 #ifdef WITH_PRESENCE
2767 #endif // WITH_PRESENCE
2771 #ifdef WITH_PRESENCE
2772 // Ensure that the last resource to be deleted is the presence resource. This allows for all
2773 // presence notification attributed to their deletion to be processed.
2774 deleteResource((OCResource *) presenceResource.handle);
2775 #endif // WITH_PRESENCE
2779 * Delete the resource from the linked list.
2781 * @param resource - resource to be deleted
2786 int deleteResource(OCResource *resource) {
2787 OCResource *prev = NULL;
2790 temp = headResource;
2792 if (temp == resource) {
2793 // Invalidate all Resource Properties.
2794 resource->resourceProperties = (OCResourceProperty) 0;
2795 #ifdef WITH_PRESENCE
2796 if(resource != (OCResource *) presenceResource.handle)
2798 #endif // WITH_PRESENCE
2799 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
2800 #ifdef WITH_PRESENCE
2803 if(presenceResource.handle)
2805 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2806 if(resource != (OCResource *) presenceResource.handle)
2808 SendPresenceNotification(resource->rsrcType);
2812 SendPresenceNotification(NULL);
2817 if (temp == headResource) {
2818 headResource = temp->next;
2820 prev->next = temp->next;
2823 deleteResourceElements(temp);
2836 * Delete all of the dynamically allocated elements that were created for the resource.
2838 * @param resource - specified resource
2840 void deleteResourceElements(OCResource *resource) {
2846 OCFree(resource->uri);
2848 // Delete resourcetype linked list
2849 deleteResourceType(resource->rsrcType);
2851 // Delete resourceinterface linked list
2852 deleteResourceInterface(resource->rsrcInterface);
2856 * Delete all of the dynamically allocated elements that were created for the resource type.
2858 * @param resourceType - specified resource type
2860 void deleteResourceType(OCResourceType *resourceType) {
2861 OCResourceType *pointer = resourceType;
2862 OCResourceType *next;
2865 next = pointer->next;
2866 OCFree(pointer->resourcetypename);
2873 * Delete all of the dynamically allocated elements that were created for the resource interface.
2875 * @param resourceInterface - specified resource interface
2877 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
2878 OCResourceInterface *pointer = resourceInterface;
2879 OCResourceInterface *next;
2882 next = pointer->next;
2883 OCFree(pointer->name);
2890 * Insert a resource type into a resource's resource type linked list.
2892 * @param resource - resource where resource type is to be inserted
2893 * @param resourceType - resource type to be inserted
2895 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
2896 OCResourceType *pointer;
2898 if (resource && !resource->rsrcType) {
2899 resource->rsrcType = resourceType;
2903 pointer = resource->rsrcType;
2907 pointer = resourceType;
2909 while (pointer->next) {
2910 pointer = pointer->next;
2912 pointer->next = resourceType;
2914 resourceType->next = NULL;
2918 * Get a resource type at the specified index within a resource.
2920 * @param handle - handle of resource
2921 * @param index - index of resource type
2924 * resourcetype - if found
2927 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
2928 OCResource *resource;
2929 OCResourceType *pointer;
2932 // Find the specified resource
2933 resource = findResource((OCResource *) handle);
2938 // Make sure a resource has a resourcetype
2939 if (!resource->rsrcType) {
2943 // Iterate through the list
2944 pointer = resource->rsrcType;
2946 while ((i < index) && pointer) {
2948 pointer = pointer->next;
2954 * Finds a resource type in an OCResourceType link-list.
2956 * @param resourceTypeList - the link-list to be searched through
2957 * @param resourceTypeName - the key to search for
2960 * resourceType that matches the key (ie. resourceTypeName)
2961 * NULL - either an invalid parameter or this function was unable to find the key.
2963 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
2965 if(resourceTypeList && resourceTypeName)
2967 OCResourceType * rtPointer = resourceTypeList;
2968 while(resourceTypeName && rtPointer)
2970 if(rtPointer->resourcetypename &&
2971 strcmp(resourceTypeName, (const char *)
2972 (rtPointer->resourcetypename)) == 0)
2976 rtPointer = rtPointer->next;
2983 * Insert a resource interface into a resource's resource interface linked list.
2985 * @param resource - resource where resource interface is to be inserted
2986 * @param resourceInterface - resource interface to be inserted
2988 void insertResourceInterface(OCResource *resource,
2989 OCResourceInterface *resourceInterface) {
2990 OCResourceInterface *pointer;
2992 if (!resource->rsrcInterface) {
2993 resource->rsrcInterface = resourceInterface;
2995 pointer = resource->rsrcInterface;
2996 while (pointer->next) {
2997 pointer = pointer->next;
2999 pointer->next = resourceInterface;
3001 resourceInterface->next = NULL;
3005 * Get a resource interface at the specified index within a resource.
3007 * @param handle - handle of resource
3008 * @param index - index of resource interface
3011 * resourceinterface - if found
3014 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3016 OCResource *resource;
3017 OCResourceInterface *pointer;
3020 // Find the specified resource
3021 resource = findResource((OCResource *) handle);
3026 // Make sure a resource has a resourceinterface
3027 if (!resource->rsrcInterface) {
3031 // Iterate through the list
3032 pointer = resource->rsrcInterface;
3034 while ((i < index) && pointer) {
3036 pointer = pointer->next;
3042 * Determine if a request/response must be sent in a block transfer because it is too large to be
3043 * sent in a single PDU. This function can be used for either a request or a response
3045 * @param request - NULL or pointer to request
3046 * @param response - NULL or pointer to response
3047 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
3048 * the length of the request/response
3051 * 0 - packet transfer NOT required (i.e. normal request/response)
3052 * 1 - packet transfer required (i.e. block transfer needed)
3054 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
3058 // Determine if we are checking a request or a response
3061 // If size is greater than 0, use it for the request size value, otherwise
3062 // assume request is null terminated and use strlen for size value
3063 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
3070 // If size is greater than 0, use it for the response size value, otherwise
3071 // assume response is null terminated and use strlen for size value
3072 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
3081 * Retrieves a resource type based upon a uri string if the uri string contains only just one
3082 * resource attribute (and that has to be of type "rt").
3084 * @remark This API malloc's memory for the resource type and newURI. Do not malloc resourceType
3085 * or newURI before passing in.
3087 * @param uri - Valid URI for "requiredUri" parameter to OCDoResource API.
3088 * @param resourceType - The resource type to be populated; pass by reference.
3089 * @param newURI - Return URI without resourceType appended to the end of it. This is used to
3090 * ensure that the uri parameter is not modified; pass by reference.
3093 * OC_STACK_INVALID_URI - Returns this if the URI is invalid/NULL.
3094 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
3095 * OC_STACK_OK - Success
3097 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI)
3101 return OC_STACK_INVALID_URI;
3103 if(!resourceType || !newURI)
3105 return OC_STACK_INVALID_PARAM;
3107 char * leftToken = NULL;
3108 char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3113 strcpy(tempURI, uri);
3115 leftToken = strtok_r((char *)tempURI, "?", &strTokPtr);
3117 while(leftToken != NULL)
3119 if(strncmp(leftToken, "rt=", 3) == 0)
3121 *resourceType = (unsigned char *) OCMalloc(strlen(leftToken)-3);
3126 strcpy((char *)*resourceType, ((const char *)&leftToken[3]));
3129 leftToken = strtok_r(NULL, "?", &strTokPtr);
3137 return OC_STACK_NO_MEMORY;
3140 const ServerID OCGetServerInstanceID(void)
3142 static bool generated = false;
3143 static ServerID sid;
3150 sid = OCGetRandom();
3155 const char* OCGetServerInstanceIDString(void)
3157 // max printed length of a base 10
3158 // uint32 is 10 characters, so 11 includes null.
3159 // This will change as the representation gets switched
3161 static char buffer[11];
3162 int n = sprintf(buffer, "%u", OCGetServerInstanceID());