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 //-----------------------------------------------------------------------------
26 #include "ocstackinternal.h"
27 #include "ocresourcehandler.h"
28 #include "occlientcb.h"
29 #include "ocobserve.h"
34 #include "ocserverrequest.h"
38 #include "cainterface.h"
41 //-----------------------------------------------------------------------------
43 //-----------------------------------------------------------------------------
45 OC_STACK_UNINITIALIZED = 0, OC_STACK_INITIALIZED
50 OC_PRESENCE_UNINITIALIZED = 0, OC_PRESENCE_INITIALIZED
54 //-----------------------------------------------------------------------------
56 //-----------------------------------------------------------------------------
57 static OCStackState stackState = OC_STACK_UNINITIALIZED;
59 OCResource *headResource = NULL;
61 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
62 static PresenceResource presenceResource;
63 uint8_t PresenceTimeOutSize = 0;
64 uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
68 OCDeviceEntityHandler defaultDeviceHandler;
70 //-----------------------------------------------------------------------------
72 //-----------------------------------------------------------------------------
73 #define TAG PCF("OCStack")
74 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
75 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
76 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
77 TAG, PCF(#arg " is NULL")); return (retVal); } }
78 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
81 //TODO: we should allow the server to define this
82 #define MAX_OBSERVE_AGE (0x2FFFFUL)
84 //-----------------------------------------------------------------------------
86 //-----------------------------------------------------------------------------
87 extern void DeinitOCSecurityInfo();
89 //-----------------------------------------------------------------------------
90 // Internal API function
91 //-----------------------------------------------------------------------------
93 // This internal function is called to update the stack with the status of
94 // observers and communication failures
95 OCStackResult OCStackFeedBack(OCCoAPToken * token, uint8_t status)
97 OCStackResult result = OC_STACK_ERROR;
98 ResourceObserver * observer = NULL;
99 OCEntityHandlerRequest ehRequest = {0};
103 case OC_OBSERVER_NOT_INTERESTED:
104 OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
105 observer = GetObserverUsingToken (token);
108 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
109 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
110 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
111 if(result != OC_STACK_OK)
115 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
117 //observer is not observing anymore
118 result = DeleteObserverUsingToken (token);
119 if(result == OC_STACK_OK)
121 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
125 result = OC_STACK_OK;
126 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
129 case OC_OBSERVER_STILL_INTERESTED:
130 //observer is still interested
131 OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
132 notifications, reset the failedCount"));
133 observer = GetObserverUsingToken(token);
136 observer->forceHighQos = 0;
137 observer->failedCommCount = 0;
138 result = OC_STACK_OK;
142 result = OC_STACK_OBSERVER_NOT_FOUND;
145 case OC_OBSERVER_FAILED_COMM:
146 //observer is not reachable
147 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
148 observer = GetObserverUsingToken(token);
151 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
153 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
154 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
155 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
156 if(result != OC_STACK_OK)
158 return OC_STACK_ERROR;
160 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
161 //observer is unreachable
162 result = DeleteObserverUsingToken (token);
163 if(result == OC_STACK_OK)
165 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
169 result = OC_STACK_OK;
170 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
175 observer->failedCommCount++;
176 result = OC_STACK_CONTINUE;
178 observer->forceHighQos = 1;
179 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
183 OC_LOG(ERROR, TAG, PCF("Unknown status"));
184 result = OC_STACK_ERROR;
191 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
193 OCStackResult ret = OC_STACK_ERROR;
201 ret = OC_STACK_RESOURCE_CREATED;
204 ret = OC_STACK_RESOURCE_DELETED;
207 ret = OC_STACK_INVALID_QUERY;
210 ret = OC_STACK_INVALID_OPTION;
213 ret = OC_STACK_NO_RESOURCE;
221 //This function will be called back by CA layer when a response is received
222 void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
224 OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
225 printf ("Received payload: %s\n", (char *)responseInfo->info.payload);
226 OCStackApplicationResult result = OC_STACK_DELETE_TRANSACTION;
227 ClientCB *cbNode = GetClientCB((CAToken_t *)&responseInfo->info.token, NULL, NULL);
230 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
231 OCClientResponse response;
232 struct sockaddr_in sa;
234 inet_pton(AF_INET, endPoint->addressInfo.IP.ipAddress, &(sa.sin_addr));
235 sa.sin_port = htons(endPoint->addressInfo.IP.port);
236 static OCDevAddr address;
237 memcpy((void*)&address.addr, &(sa), sizeof(sa));
238 response.addr = &address;
239 response.result = CAToOCStackResult(responseInfo->result);
240 response.resJSONPayload = (unsigned char*)responseInfo->info.payload;
241 response.numRcvdVendorSpecificHeaderOptions = 0;
242 if(responseInfo->info.numOptions > 0)
244 //First option alwas with option ID COAP_OPTION_OBSERVE if it is availbale
245 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
247 memcpy (&(response.sequenceNumber),
248 &(responseInfo->info.options[0].optionData), 4);
252 memcpy (&(response.rcvdVendorSpecificHeaderOptions[0]),
253 &(responseInfo->info.options[0]), sizeof(OCHeaderOption));
255 for (uint8_t i = 1; i < responseInfo->info.numOptions; i++)
257 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i]),
258 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
260 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
262 result = cbNode->callBack(cbNode->context,
263 cbNode->handle, &response);
264 if (result == OC_STACK_DELETE_TRANSACTION)
266 FindAndDeleteClientCB(cbNode);
269 OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload);
270 OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
273 //This function will be called back by CA layer when a request is received
274 void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
276 CAInfo_t responseData;
277 CAResponseInfo_t responseInfo;
278 OCStackResult requestResult = OC_STACK_ERROR;
280 OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
283 if(myStackMode == OC_CLIENT)
285 //TODO: should the client be responding to requests?
289 OCServerProtocolRequest serverRequest;
291 memset (&serverRequest, 0, sizeof(OCServerProtocolRequest));
292 // copy URI of resource
293 memcpy (&(serverRequest.resourceUrl), endPoint->resourceUri, strlen(endPoint->resourceUri));
295 // TODO-CA: Is the query part of header option?
296 //copy request payload
297 if (requestInfo->info.payload)
299 memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
300 strlen(requestInfo->info.payload));
302 switch (requestInfo->method)
306 serverRequest.method = OC_REST_GET;
311 serverRequest.method = OC_REST_PUT;
316 serverRequest.method = OC_REST_POST;
321 serverRequest.method = OC_REST_DELETE;
326 OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
332 OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d", strlen(requestInfo->info.token));
333 OC_LOG_BUFFER(INFO, TAG, requestInfo->info.token, strlen(requestInfo->info.token));
334 // TODO-CA: For CA integration currently copying CAToken to OCCoapToken:
335 // Need to remove OCCoapToken
336 memcpy (&(serverRequest.requestToken.token), requestInfo->info.token,
337 strlen(requestInfo->info.token));
338 serverRequest.requestToken.tokenLength = strlen(requestInfo->info.token);
339 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
340 if (requestInfo->info.type == CA_MSG_CONFIRM)
342 serverRequest.qos = OC_HIGH_QOS;
344 else if (requestInfo->info.type == CA_MSG_NONCONFIRM)
346 serverRequest.qos = OC_LOW_QOS;
348 else if (requestInfo->info.type == CA_MSG_ACKNOWLEDGE)
350 // TODO-CA: Need to handle this
352 else if (requestInfo->info.type == CA_MSG_RESET)
354 // TODO-CA: Need to handle this
356 // CA does not need the following 3 fields
357 serverRequest.coapID = 0;
358 serverRequest.delayedResNeeded = 0;
359 serverRequest.secured = 0;
362 serverRequest.addressInfo = endPoint->addressInfo;
363 serverRequest.connectivityType = endPoint->connectivityType;
364 if (requestInfo->info.token)
366 strncpy(serverRequest.token, requestInfo->info.token, sizeof(serverRequest.token) - 1);
369 struct sockaddr_in sa;
370 inet_pton(AF_INET, endPoint->addressInfo.IP.ipAddress, &(sa.sin_addr));
371 sa.sin_port = htons(endPoint->addressInfo.IP.port);
372 memcpy((void*)&serverRequest.requesterAddr, &(sa), sizeof(sa));
374 // copy vendor specific header options
375 // TODO-CA: CA is including non-vendor header options as well, like observe.
376 // Need to filter those out
377 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
379 // TODO-CA: Need to send an error indicating the num of options is incorrect
382 serverRequest.numRcvdVendorSpecificHeaderOptions = requestInfo->info.numOptions;
383 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
385 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
386 sizeof(CAHeaderOption_t)*requestInfo->info.numOptions);
389 requestResult = HandleStackRequests (&serverRequest);
393 // generate the pdu, if the request was CON, then the response is ACK, otherwire NON
394 memset(&responseData, 0, sizeof(CAInfo_t));
395 responseData.token = (requestInfo != NULL) ? requestInfo->info.token : "";
397 // TODO : I guess we need to allocate memeory?
398 responseData.payload = "{\"oc\":[{\"href\":\"/a/led\",\"sid\":\"\",\"prop\":{\"rt\":[\"core.led\"],\"if\":[\"oc.mi.def\"],\"obs\":1}}]}";
400 //responseInfo = (CAResponseInfo*) malloc(sizeof(CAResponseInfo));
401 memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
402 responseInfo.result = 200;
403 responseInfo.info = responseData;
405 // send request (connectivityType from remoteEndpoint of request Info)
406 OC_LOG(INFO, TAG, PCF("CASendResponse in HandleCARequests"));
407 //TODO-CA: CASendResponse returns the result (we need to check if the
409 CAResult_t caResult = CASendResponse(endPoint, &responseInfo);
410 if(caResult != CA_STATUS_OK)
412 OC_LOG(ERROR, TAG, PCF("CASendResponse error"));
416 OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
421 //This function will be called back by occoap layer when a request is received
422 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
424 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
426 OCStackResult result = OC_STACK_ERROR;
427 ResourceHandling resHandling;
428 OCResource *resource;
430 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
433 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
435 result = AddServerCARequest(&request, protocolRequest->coapID,
436 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
437 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
438 protocolRequest->observationOption, protocolRequest->qos,
439 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
440 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
441 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
442 protocolRequest->reqTotalSize,
443 &protocolRequest->addressInfo, protocolRequest->connectivityType, protocolRequest->token);
445 result = AddServerRequest(&request, protocolRequest->coapID,
446 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
447 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
448 protocolRequest->observationOption, protocolRequest->qos,
449 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
450 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
451 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
452 protocolRequest->reqTotalSize);
454 if (OC_STACK_OK != result)
456 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
459 VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
461 if(!protocolRequest->reqMorePacket)
463 request->requestComplete = 1;
468 OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
471 if(request->requestComplete)
473 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
474 result = DetermineResourceHandling (request, &resHandling, &resource);
475 if (result == OC_STACK_OK)
477 result = ProcessRequest(resHandling, resource, request);
481 result = OC_STACK_ERROR;
486 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
487 result = OC_STACK_CONTINUE;
492 //This function will be called back by occoap layer when a response is received
493 OCStackResult HandleStackResponses(OCResponse * response)
495 OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)"));
496 OCStackResult result = OC_STACK_OK;
497 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
498 uint8_t isObserveNotification = 0;
499 ClientCB * cbNode = NULL;
501 uint8_t isPresenceNotification = 0;
502 uint8_t isMulticastPresence = 0;
503 char * resourceTypeName = NULL;
504 uint32_t lowerBound = 0;
505 uint32_t higherBound = 0;
507 unsigned char * bufRes = response->bufRes;
508 #endif // WITH_PRESENCE
510 cbNode = response->cbNode;
513 cbNode = GetClientCB(response->rcvdToken, NULL, NULL);
516 if(response->clientResponse->sequenceNumber >= OC_OFFSET_SEQUENCE_NUMBER)
518 isObserveNotification = 1;
519 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
522 OC_LOG_V(DEBUG, TAG, "The sequenceNumber/NONCE of this response %u",
523 response->clientResponse->sequenceNumber);
524 OC_LOG_V(DEBUG, TAG, "The maxAge/TTL of this response %u", response->maxAge);
525 OC_LOG_V(DEBUG, TAG, "The response received is %s", bufRes);
528 if(!strcmp((char *)response->rcvdUri, (char *)OC_PRESENCE_URI)){
529 isPresenceNotification = 1;
532 result = OC_STACK_INVALID_PARAM;
535 tok = strtok((char *)bufRes, "[:]}");
536 bufRes[strlen((char *)bufRes)] = ':';
537 tok = strtok(NULL, "[:]}");
538 bufRes[strlen((char *)bufRes)] = ':';
539 response->clientResponse->sequenceNumber = (uint32_t )atoi(tok);
540 OC_LOG_V(DEBUG, TAG, "The received NONCE is %u", response->clientResponse->sequenceNumber);
541 tok = strtok(NULL, "[:]}");
542 response->maxAge = (uint32_t )atoi(tok);
543 OC_LOG_V(DEBUG, TAG, "The received TTL is %u", response->maxAge);
544 tok = strtok(NULL, "[:]}");
547 resourceTypeName = (char *)OCMalloc(strlen(tok));
548 if(!resourceTypeName)
552 bufRes[strlen((char *)bufRes)] = ':';
553 strcpy(resourceTypeName, tok);
554 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
557 bufRes[strlen((char *)bufRes)] = ']';
560 // Check if the application subcribed for presence
563 cbNode = GetClientCB(NULL, NULL, response->fullUri);
566 // Check if application subscribed for multicast presence
569 snprintf((char *)response->fullUri, MAX_URI_LENGTH, "%s%s",
570 OC_MULTICAST_IP, response->rcvdUri);
571 cbNode = GetClientCB(NULL, NULL, response->fullUri);
574 isMulticastPresence = 1;
575 isPresenceNotification = 0;
579 if(cbNode && isPresenceNotification)
581 OC_LOG(INFO, TAG, PCF("Received a presence notification"));
582 if(!cbNode->presence)
584 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
585 VERIFY_NON_NULL_V(cbNode->presence);
586 cbNode->presence->timeOut = NULL;
587 cbNode->presence->timeOut = (uint32_t *)
588 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
589 if(!(cbNode->presence->timeOut)){
590 OCFree(cbNode->presence);
591 result = OC_STACK_NO_MEMORY;
594 if(response->maxAge == 0)
596 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
597 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
600 OCFree(cbNode->presence->timeOut);
601 OCFree(cbNode->presence);
602 cbNode->presence = NULL;
607 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %d", GetTime(0));
608 cbNode->presence->TTL = response->maxAge;
609 for(int index = 0; index < PresenceTimeOutSize; index++)
611 lowerBound = GetTime(((float)(PresenceTimeOut[index])
612 /(float)100)*(float)cbNode->presence->TTL);
613 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
614 /(float)100)*(float)cbNode->presence->TTL);
615 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
616 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
617 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
618 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d",
619 cbNode->presence->timeOut[index]);
621 cbNode->presence->TTLlevel = 0;
622 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
623 if(cbNode->sequenceNumber == response->clientResponse->sequenceNumber)
625 OC_LOG(INFO, TAG, PCF("===============No presence change"));
628 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
629 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;;
632 // Ensure that a filter is actually applied.
633 if(resourceTypeName && cbNode->filterResourceType)
635 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
641 else if(cbNode && isMulticastPresence)
643 // Check if the same nonce for a given host
644 OCMulticastNode* mcNode = NULL;
645 mcNode = GetMCPresenceNode(response->fullUri);
647 if(response->maxAge == 0)
649 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
650 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
653 OCFree(cbNode->presence->timeOut);
654 OCFree(cbNode->presence);
655 cbNode->presence = NULL;
658 else if(mcNode != NULL)
660 if(mcNode->nonce == response->clientResponse->sequenceNumber)
662 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
663 result = OC_STACK_NO_MEMORY;
666 mcNode->nonce = response->clientResponse->sequenceNumber;
670 uint32_t uriLen = strlen((char*)response->fullUri);
671 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
674 memcpy(uri, response->fullUri, (uriLen + 1));
679 PCF("===============No Memory for URI to store in the presence node"));
680 result = OC_STACK_NO_MEMORY;
683 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri,
684 response->clientResponse->sequenceNumber);
685 if(result == OC_STACK_NO_MEMORY)
688 PCF("===============No Memory for Multicast Presence Node"));
689 result = OC_STACK_NO_MEMORY;
694 // Ensure that a filter is actually applied.
695 if(resourceTypeName && cbNode->filterResourceType)
697 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
704 else if(!cbNode && isPresenceNotification)
706 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
707 ------------ ignoring"));
709 #endif // WITH_PRESENCE
713 if(isObserveNotification)
715 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
716 //TODO: check the standard for methods to detect wrap around condition
717 if(cbNode->method == OC_REST_OBSERVE &&
718 (response->clientResponse->sequenceNumber <= cbNode->sequenceNumber ||
719 (response->clientResponse->sequenceNumber > cbNode->sequenceNumber &&
720 response->clientResponse->sequenceNumber ==
721 MAX_SEQUENCE_NUMBER)))
723 OC_LOG_V(DEBUG, TAG, "Observe notification came out of order. \
724 Ignoring Incoming:%d Against Current:%d.",
725 response->clientResponse->sequenceNumber, cbNode->sequenceNumber);
728 if(response->clientResponse->sequenceNumber > cbNode->sequenceNumber){
729 cbNode->sequenceNumber = response->clientResponse->sequenceNumber;
733 response->clientResponse->resJSONPayload = bufRes;
735 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response->clientResponse);
737 if (cbResult == OC_STACK_DELETE_TRANSACTION ||
738 response->clientResponse->result == OC_STACK_COMM_ERROR ||
739 (response->clientResponse->result == OC_STACK_RESOURCE_DELETED &&
740 !isPresenceNotification && !isMulticastPresence))
742 FindAndDeleteClientCB(cbNode);
747 result = OC_STACK_ERROR;
752 OCFree(resourceTypeName);
757 int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
760 unsigned char *itr, *coap;
761 uint8_t dotCount = 0;
765 /* search for scheme */
767 if (!isdigit((unsigned char) *ipAddrStr))
769 coap = (unsigned char *) OC_COAP_SCHEME;
770 while (*coap && tolower(*itr) == *coap)
779 if (isdigit((unsigned char) *ipAddrStr))
782 ipAddr[index] += *ipAddrStr - '0';
784 else if ((unsigned char) *ipAddrStr == '.')
796 if(*ipAddrStr == ':')
800 if (isdigit((unsigned char) *ipAddrStr))
803 *port += *ipAddrStr - '0';
814 if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
825 //-----------------------------------------------------------------------------
826 // Private internal function prototypes
827 //-----------------------------------------------------------------------------
829 static OCDoHandle GenerateInvocationHandle();
830 static OCStackResult initResources();
831 static void insertResource(OCResource *resource);
832 static OCResource *findResource(OCResource *resource);
833 static void insertResourceType(OCResource *resource,
834 OCResourceType *resourceType);
835 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
837 static void insertResourceInterface(OCResource *resource,
838 OCResourceInterface *resourceInterface);
839 static OCResourceInterface *findResourceInterfaceAtIndex(
840 OCResourceHandle handle, uint8_t index);
841 static void deleteResourceType(OCResourceType *resourceType);
842 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
843 static void deleteResourceElements(OCResource *resource);
844 static int deleteResource(OCResource *resource);
845 static void deleteAllResources();
846 static void incrementSequenceNumber(OCResource * resPtr);
847 static OCStackResult verifyUriQueryLength(const char * inputUri,
849 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
850 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI);
852 //-----------------------------------------------------------------------------
854 //-----------------------------------------------------------------------------
857 * Initialize the OC Stack. Must be called prior to starting the stack.
860 * IP Address of host device
862 * Port of host device
864 * Host device is client, server, or client-server
867 * OC_STACK_OK - no errors
868 * OC_STACK_ERROR - stack init error
870 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
872 OCStackResult result = OC_STACK_ERROR;
873 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
877 OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
881 //It is ok to select network to CA_WIFI for now
882 CAResult_t caResult = CASelectNetwork(CA_WIFI);
883 if(caResult == CA_STATUS_OK)
885 OC_LOG(INFO, TAG, PCF("CASelectNetwork to WIFI"));
886 caResult = CARegisterHandler(HandleCARequests, HandleCAResponses);
887 if(caResult == CA_STATUS_OK)
889 OC_LOG(INFO, TAG, PCF("CARegisterHandler..."));
890 stackState = OC_STACK_INITIALIZED;
891 result = OC_STACK_OK;
895 caResult = CAStartDiscoveryServer();
896 OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
899 caResult = CAStartListeningServer();
900 OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
902 case OC_CLIENT_SERVER:
903 caResult = CAStartListeningServer();
904 if(caResult == CA_STATUS_OK)
906 caResult = CAStartDiscoveryServer();
908 OC_LOG(INFO, TAG, PCF("Client-server mode"));
911 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
912 return OC_STACK_ERROR;
917 if (caResult == CA_STATUS_OK)
919 result = OC_STACK_OK;
923 result = OC_STACK_ERROR;
930 OC_LOG(INFO, TAG, PCF("Client mode"));
933 OC_LOG(INFO, TAG, PCF("Server mode"));
935 case OC_CLIENT_SERVER:
936 OC_LOG(INFO, TAG, PCF("Client-server mode"));
939 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
940 return OC_STACK_ERROR;
944 // Make call to OCCoAP layer
945 result = OCInitCoAP(ipAddr, (uint16_t) port, myStackMode);
949 defaultDeviceHandler = NULL;
952 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
953 #endif // WITH_PRESENCE
955 if (result == OC_STACK_OK)
957 stackState = OC_STACK_INITIALIZED;
959 // Initialize resource
960 if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
962 result = initResources();
964 if(result != OC_STACK_OK)
966 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
972 * Stop the OC stack. Use for a controlled shutdown.
974 * OC_STACK_OK - no errors
975 * OC_STACK_ERROR - stack not initialized
977 OCStackResult OCStop()
979 OCStackResult result = OC_STACK_ERROR;
981 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
983 if (stackState != OC_STACK_INITIALIZED)
985 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
986 return OC_STACK_ERROR;
990 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
991 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
992 presenceResource.presenceTTL = 0;
993 #endif // WITH_PRESENCE
995 // Free memory dynamically allocated for resources
996 deleteAllResources();
998 // Make call to OCCoAP layer
999 if (OCStopCoAP() == OC_STACK_OK)
1001 // Remove all observers
1002 DeleteObserverList();
1003 // Remove all the client callbacks
1004 DeleteClientCBList();
1005 stackState = OC_STACK_UNINITIALIZED;
1006 result = OC_STACK_OK;
1008 result = OC_STACK_ERROR;
1011 // Deinit security blob
1012 DeinitOCSecurityInfo();
1014 if (result != OC_STACK_OK) {
1015 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
1022 * Verify the lengths of the URI and the query separately
1024 * @param inputUri - Input URI and query.
1025 * @param uriLen - The length of the initial URI with query.
1027 * Note: The '?' that appears after the URI is not considered as
1028 * a part of the query.
1030 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1034 query = strchr (inputUri, '?');
1038 if((query - inputUri) > MAX_URI_LENGTH)
1040 return OC_STACK_INVALID_URI;
1043 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1045 return OC_STACK_INVALID_QUERY;
1048 else if(uriLen > MAX_URI_LENGTH)
1050 return OC_STACK_INVALID_URI;
1056 * Discover or Perform requests on a specified resource (specified by that Resource's respective URI).
1058 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of calling this API.
1059 * @param method - @ref OCMethod to perform on the resource
1060 * @param requiredUri - URI of the resource to interact with
1061 * @param referenceUri - URI of the reference resource
1062 * @param request - JSON encoded request
1063 * @param qos - quality of service
1064 * @param cbData - struct that contains asynchronous callback function that is invoked
1065 * by the stack when discovery or resource interaction is complete
1066 * @param options - The address of an array containing the vendor specific header
1067 * header options to be sent with the request
1068 * @param numOptions - Number of vendor specific header options to be included
1071 * OC_STACK_OK - no errors
1072 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
1073 * OC_STACK_INVALID_METHOD - invalid resource method
1074 * OC_STACK_INVALID_URI - invalid required or reference URI
1077 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
1078 const char *referenceUri, const char *request,
1079 OCQualityOfService qos, OCCallbackData *cbData,
1080 OCHeaderOption * options, uint8_t numOptions)
1082 OCStackResult result = OC_STACK_ERROR;
1084 ClientCB *clientCB = NULL;
1085 unsigned char * requestUri = NULL;
1086 unsigned char * resourceType = NULL;
1087 char * newUri = (char *)requiredUri;
1088 (void) referenceUri;
1090 CARemoteEndpoint_t* endpoint = NULL;
1091 CAResult_t caResult;
1092 CAToken_t caToken = NULL;
1093 CAInfo_t requestData;
1094 CARequestInfo_t requestInfo;
1095 // To track if memory is allocated for additional header options
1096 uint8_t hdrOptionMemAlloc = 0;
1099 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1101 // Validate input parameters
1102 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1103 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1105 TODO ("Need to form the final query by concatenating require and reference URI's");
1106 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
1108 uint16_t uriLen = strlen(requiredUri);
1110 // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS
1116 case OC_REST_DELETE:
1117 case OC_REST_OBSERVE:
1118 case OC_REST_OBSERVE_ALL:
1119 case OC_REST_CANCEL_OBSERVE:
1121 #ifdef WITH_PRESENCE
1122 case OC_REST_PRESENCE:
1126 result = OC_STACK_INVALID_METHOD;
1130 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
1135 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
1137 result = OC_STACK_INVALID_PARAM;
1141 #ifdef WITH_PRESENCE
1142 if(method == OC_REST_PRESENCE)
1144 result = getResourceType(requiredUri, &resourceType, &newUri);
1146 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
1150 OC_LOG(DEBUG, TAG, PCF("Got Resource Type is NULL."));
1152 if(result != OC_STACK_OK)
1157 #endif // WITH_PRESENCE
1159 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
1162 memcpy(requestUri, newUri, (uriLen + 1));
1166 result = OC_STACK_NO_MEMORY;
1170 *handle = GenerateInvocationHandle();
1173 result = OC_STACK_NO_MEMORY;
1178 memset(&requestData, 0, sizeof(CAInfo_t));
1179 memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1183 case OC_REST_OBSERVE:
1184 case OC_REST_OBSERVE_ALL:
1185 case OC_REST_CANCEL_OBSERVE:
1187 requestInfo.method = CA_GET;
1192 requestInfo.method = CA_PUT;
1197 requestInfo.method = CA_POST;
1200 case OC_REST_DELETE:
1202 requestInfo.method = CA_DELETE;
1205 #ifdef WITH_PRESENCE
1206 case OC_REST_PRESENCE:
1207 //TODO-CA: What should be the CA method?
1211 result = OC_STACK_INVALID_METHOD;
1215 // TODO-CA: Handle multi-cast scenario
1216 // Create remote end point
1217 caResult = CACreateRemoteEndpoint(newUri, CA_WIFI, &endpoint);
1218 // TODO-CA: Connectivity type should be passed to API
1219 endpoint->connectivityType = CA_WIFI;
1220 if (caResult != CA_STATUS_OK)
1222 OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
1227 caResult = CAGenerateToken(&caToken);
1229 if (caResult != CA_STATUS_OK)
1231 OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
1236 // TODO-CA: Map QoS to the right CA msg type
1237 requestData.type = CA_MSG_NONCONFIRM;
1238 requestData.token = caToken;
1239 requestData.options = (CAHeaderOption_t*)options;
1240 requestData.numOptions = numOptions;
1241 requestData.payload = (char *)request;
1243 requestInfo.info = requestData;
1246 caResult = CASendRequest(endpoint, &requestInfo);
1247 if (caResult != CA_STATUS_OK)
1249 OC_LOG(ERROR, TAG, PCF("CASendRequest"));
1253 if((result = AddClientCB(&clientCB, cbData, &caToken, handle, method,
1254 requestUri, resourceType)) != OC_STACK_OK)
1256 result = OC_STACK_NO_MEMORY;
1262 // Generate token which will be used by OCStack to match responses received
1264 OCGenerateCoAPToken(&token);
1266 if((result = AddClientCB(&clientCB, cbData, &token, handle, method, requestUri, resourceType))
1269 result = OC_STACK_NO_MEMORY;
1273 #ifdef WITH_PRESENCE
1274 if(method == OC_REST_PRESENCE)
1276 // Replacing method type with GET because "presence" is a stack layer only implementation.
1277 method = OC_REST_GET;
1281 // Make call to OCCoAP layer
1282 result = OCDoCoAPResource(method, qos, &token, newUri, request, options, numOptions);
1286 if(newUri != requiredUri)
1290 if (result != OC_STACK_OK)
1292 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
1293 FindAndDeleteClientCB(clientCB);
1296 CADestroyRemoteEndpoint(endpoint);
1297 if (hdrOptionMemAlloc)
1299 OCFree(requestData.options);
1301 //TODO-CA: CADestroyToken here
1307 * Cancel a request associated with a specific @ref OCDoResource invocation.
1309 * @param handle - Used to identify a specific OCDoResource invocation.
1310 * @param qos - used to specify Quality of Service (read below for more info)
1311 * @param options- used to specify vendor specific header options when sending
1312 * explicit observe cancellation
1313 * @param numOptions- Number of header options to be included
1316 * OC_STACK_OK - No errors; Success
1317 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1319 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
1320 uint8_t numOptions) {
1322 * This ftn is implemented one of two ways in the case of observation:
1324 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
1325 * Remove the callback associated on client side.
1326 * When the next notification comes in from server,
1327 * reply with RESET message to server.
1328 * Keep in mind that the server will react to RESET only
1329 * if the last notification was sent ans CON
1331 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
1332 * and it is associated with an observe request
1333 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
1334 * Send CON Observe request to server with
1335 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
1336 * Remove the callback associated on client side.
1338 OCStackResult ret = OC_STACK_OK;
1341 return OC_STACK_INVALID_PARAM;
1344 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
1346 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
1349 switch (clientCB->method)
1351 case OC_REST_OBSERVE:
1352 case OC_REST_OBSERVE_ALL:
1353 if(qos == OC_HIGH_QOS)
1355 ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
1356 &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
1361 FindAndDeleteClientCB(clientCB);
1364 #ifdef WITH_PRESENCE
1365 case OC_REST_PRESENCE:
1366 FindAndDeleteClientCB(clientCB);
1370 return OC_STACK_INVALID_METHOD;
1375 #ifdef WITH_PRESENCE
1376 OCStackResult OCProcessPresence()
1378 OCStackResult result = OC_STACK_OK;
1379 uint8_t ipAddr[4] = { 0 };
1382 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
1383 ClientCB* cbNode = NULL;
1385 OCClientResponse clientResponse;
1386 OCResponse * response = NULL;
1388 LL_FOREACH(cbList, cbNode) {
1389 if(OC_REST_PRESENCE == cbNode->method)
1391 if(cbNode->presence)
1393 uint32_t now = GetTime(0);
1394 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
1395 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
1398 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
1403 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
1404 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
1405 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
1408 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
1410 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
1411 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
1413 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
1415 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
1416 (OCDevAddr *) &dst, 0, NULL);
1417 if(result != OC_STACK_OK)
1421 result = FormOCResponse(&response, cbNode, 0, NULL, NULL,
1422 &cbNode->token, &clientResponse, NULL);
1423 if(result != OC_STACK_OK)
1428 // Increment the TTLLevel (going to a next state), so we don't keep
1429 // sending presence notification to client.
1430 cbNode->presence->TTLlevel++;
1431 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
1432 cbNode->presence->TTLlevel);
1436 result = OC_STACK_INVALID_IP;
1439 HandleStackResponses(response);
1441 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
1443 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
1445 OCGenerateCoAPToken(&token);
1446 result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
1447 &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
1448 if(result != OC_STACK_OK)
1452 cbNode->presence->TTLlevel++;
1453 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
1459 if (result != OC_STACK_OK)
1461 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
1468 * Called in main loop of OC client or server. Allows low-level processing of
1472 * OC_STACK_OK - no errors
1473 * OC_STACK_ERROR - stack process error
1475 OCStackResult OCProcess() {
1477 OC_LOG(INFO, TAG, PCF("Entering OCProcess"));
1478 #ifdef WITH_PRESENCE
1479 OCProcessPresence();
1482 CAHandleRequestResponse();
1490 #ifdef WITH_PRESENCE
1492 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
1493 * presence notifications to clients via multicast. Once this API has been called with a success,
1494 * clients may query for this server's presence and this server's stack will respond via multicast.
1496 * Server can call this function when it comes online for the first time, or when it comes back
1497 * online from offline mode, or when it re enters network.
1499 * @param ttl - Time To Live in seconds
1500 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
1503 * OC_STACK_OK - No errors; Success
1505 OCStackResult OCStartPresence(const uint32_t ttl)
1507 OCChangeResourceProperty(
1508 &(((OCResource *)presenceResource.handle)->resourceProperties),
1513 presenceResource.presenceTTL = ttl;
1516 if(OC_PRESENCE_UNINITIALIZED == presenceState)
1518 OCDevAddr multiCastAddr;
1521 presenceState = OC_PRESENCE_INITIALIZED;
1522 OCGenerateCoAPToken(&token);
1523 OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
1524 //add the presence observer
1525 AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
1526 (OCResource *)presenceResource.handle, OC_LOW_QOS);
1529 // Each time OCStartPresence is called
1530 // a different random 32-bit integer number is used
1531 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1533 return SendPresenceNotification(NULL);
1537 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
1538 * presence notifications to clients via multicast. Once this API has been called with a success,
1539 * this server's stack will not respond to clients querying for this server's presence.
1541 * Server can call this function when it is terminating, going offline, or when going
1542 * away from network.
1545 * OC_STACK_OK - No errors; Success
1547 OCStackResult OCStopPresence()
1549 OCStackResult result = OC_STACK_ERROR;
1550 //make resource inactive
1551 result = OCChangeResourceProperty(
1552 &(((OCResource *) presenceResource.handle)->resourceProperties),
1554 result = SendPresenceNotification(NULL);
1561 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
1563 defaultDeviceHandler = entityHandler;
1571 * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource
1572 * @param resourceTypeName - name of resource type. Example: "core.led"
1573 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1574 * @param uri - URI of the resource. Example: "/a/led"
1575 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1576 * NULL for default entity handler
1577 * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE
1580 * OC_STACK_OK - no errors
1581 * OC_STACK_ERROR - stack process error
1583 OCStackResult OCCreateResource(OCResourceHandle *handle,
1584 const char *resourceTypeName,
1585 const char *resourceInterfaceName,
1586 const char *uri, OCEntityHandler entityHandler,
1587 uint8_t resourceProperties) {
1589 OCResource *pointer = NULL;
1592 OCStackResult result = OC_STACK_ERROR;
1594 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
1596 if(myStackMode == OC_CLIENT)
1600 // Validate parameters
1601 // Is it presented during resource discovery?
1602 if (!handle || !resourceTypeName || !uri) {
1603 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
1604 return OC_STACK_INVALID_PARAM;
1607 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
1608 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
1611 // Make sure resourceProperties bitmask has allowed properties specified
1612 if (resourceProperties
1613 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
1614 OC_LOG(ERROR, TAG, PCF("Invalid property"));
1615 return OC_STACK_INVALID_PARAM;
1618 // If the headResource is NULL, then no resources have been created...
1619 pointer = headResource;
1621 // At least one resources is in the resource list, so we need to search for
1622 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
1624 if (strcmp(uri, pointer->uri) == 0) {
1625 OC_LOG(ERROR, TAG, PCF("URI already in use"));
1626 return OC_STACK_INVALID_PARAM;
1628 pointer = pointer->next;
1631 // Create the pointer and insert it into the resource list
1632 pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
1636 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
1638 insertResource(pointer);
1641 size = strlen(uri) + 1;
1642 str = (char *) OCMalloc(size);
1646 strncpy(str, uri, size);
1649 // Set properties. Set OC_ACTIVE
1650 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
1653 // Add the resourcetype to the resource
1654 result = BindResourceTypeToResource(pointer, resourceTypeName);
1655 if (result != OC_STACK_OK) {
1656 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
1660 // Add the resourceinterface to the resource
1661 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
1662 if (result != OC_STACK_OK) {
1663 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
1667 // If an entity handler has been passed, attach it to the newly created
1668 // resource. Otherwise, set the default entity handler.
1671 pointer->entityHandler = entityHandler;
1675 pointer->entityHandler = defaultResourceEHandler;
1679 result = OC_STACK_OK;
1681 #ifdef WITH_PRESENCE
1682 if(presenceResource.handle)
1684 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1685 SendPresenceNotification(pointer->rsrcType);
1689 if (result != OC_STACK_OK)
1691 // Deep delete of resource and other dynamic elements that it contains
1692 deleteResource(pointer);
1701 * Create a resource. with host ip address for remote resource
1703 * @param handle - pointer to handle to newly created resource. Set by ocstack.
1704 * Used to refer to resource
1705 * @param resourceTypeName - name of resource type. Example: "core.led"
1706 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1707 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
1708 * @param uri - URI of the resource. Example: "/a/led"
1709 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1710 * NULL for default entity handler
1711 * @param resourceProperties - properties supported by resource.
1712 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
1715 * OC_STACK_OK - no errors
1716 * OC_STACK_ERROR - stack process error
1719 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
1720 const char *resourceTypeName,
1721 const char *resourceInterfaceName,
1724 OCEntityHandler entityHandler,
1725 uint8_t resourceProperties)
1729 OCStackResult result = OC_STACK_ERROR;
1731 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
1732 uri, entityHandler, resourceProperties);
1734 if (result != OC_STACK_ERROR)
1737 size = strlen(host) + 1;
1738 str = (char *) OCMalloc(size);
1741 return OC_STACK_ERROR;
1743 strncpy(str, host, size);
1744 ((OCResource *) *handle)->host = str;
1751 * Add a resource to a collection resource.
1753 * @param collectionHandle - handle to the collection resource
1754 * @param resourceHandle - handle to resource to be added to the collection resource
1757 * OC_STACK_OK - no errors
1758 * OC_STACK_ERROR - stack process error
1759 * OC_STACK_INVALID_PARAM - invalid collectionhandle
1761 OCStackResult OCBindResource(
1762 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1763 OCResource *resource;
1766 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
1768 // Validate parameters
1769 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1770 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1771 // Container cannot contain itself
1772 if (collectionHandle == resourceHandle) {
1773 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
1774 return OC_STACK_INVALID_PARAM;
1777 // Use the handle to find the resource in the resource linked list
1778 resource = findResource((OCResource *) collectionHandle);
1780 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1781 return OC_STACK_INVALID_PARAM;
1784 // Look for an open slot to add add the child resource.
1785 // If found, add it and return success
1786 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1787 if (!resource->rsrcResources[i]) {
1788 resource->rsrcResources[i] = (OCResource *) resourceHandle;
1789 OC_LOG(INFO, TAG, PCF("resource bound"));
1794 #ifdef WITH_PRESENCE
1795 if(presenceResource.handle)
1797 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1798 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1802 // Unable to add resourceHandle, so return error
1803 return OC_STACK_ERROR;
1807 * Remove a resource from a collection resource.
1809 * @param collectionHandle - handle to the collection resource
1810 * @param resourceHandle - handle to resource to be added to the collection resource
1813 * OC_STACK_OK - no errors
1814 * OC_STACK_ERROR - stack process error
1815 * OC_STACK_INVALID_PARAM - invalid collectionHandle
1817 OCStackResult OCUnBindResource(
1818 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1819 OCResource *resource;
1822 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
1824 // Validate parameters
1825 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1826 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1827 // Container cannot contain itself
1828 if (collectionHandle == resourceHandle) {
1829 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
1830 return OC_STACK_INVALID_PARAM;
1833 // Use the handle to find the resource in the resource linked list
1834 resource = findResource((OCResource *) collectionHandle);
1836 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1837 return OC_STACK_INVALID_PARAM;
1840 // Look for an open slot to add add the child resource.
1841 // If found, add it and return success
1842 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1843 if (resourceHandle == resource->rsrcResources[i]) {
1844 resource->rsrcResources[i] = (OCResource *) NULL;
1845 OC_LOG(INFO, TAG, PCF("resource unbound"));
1850 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
1852 #ifdef WITH_PRESENCE
1853 if(presenceResource.handle)
1855 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1856 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1860 // Unable to add resourceHandle, so return error
1861 return OC_STACK_ERROR;
1864 OCStackResult BindResourceTypeToResource(OCResource* resource,
1865 const char *resourceTypeName)
1867 OCResourceType *pointer = NULL;
1870 OCStackResult result = OC_STACK_ERROR;
1872 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
1874 // Validate parameters
1875 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
1876 // TODO: Does resource attribute resentation really have to be maintained in stack?
1877 // Is it presented during resource discovery?
1879 TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
1881 // Create the resourcetype and insert it into the resource list
1882 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
1887 // Set the resourceTypeName
1888 size = strlen(resourceTypeName) + 1;
1889 str = (char *) OCMalloc(size);
1893 strncpy(str, resourceTypeName, size);
1894 pointer->resourcetypename = str;
1896 insertResourceType(resource, pointer);
1897 result = OC_STACK_OK;
1899 exit: if (result != OC_STACK_OK) {
1907 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
1908 const char *resourceInterfaceName)
1910 OCResourceInterface *pointer = NULL;
1913 OCStackResult result = OC_STACK_ERROR;
1915 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
1917 // Validate parameters
1918 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
1920 TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
1922 // Create the resourceinterface and insert it into the resource list
1923 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
1928 // Set the resourceinterface name
1929 size = strlen(resourceInterfaceName) + 1;
1930 str = (char *) OCMalloc(size);
1934 strncpy(str, resourceInterfaceName, size);
1935 pointer->name = str;
1937 // Bind the resourceinterface to the resource
1938 insertResourceInterface(resource, pointer);
1940 result = OC_STACK_OK;
1942 exit: if (result != OC_STACK_OK) {
1951 * Bind a resourcetype to a resource.
1953 * @param handle - handle to the resource
1954 * @param resourceTypeName - name of resource type. Example: "core.led"
1957 * OC_STACK_OK - no errors
1958 * OC_STACK_ERROR - stack process error
1960 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
1961 const char *resourceTypeName) {
1963 OCStackResult result = OC_STACK_ERROR;
1964 OCResource *resource;
1966 // Make sure resource exists
1967 resource = findResource((OCResource *) handle);
1969 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1970 return OC_STACK_ERROR;
1973 // call internal function
1974 result = BindResourceTypeToResource(resource, resourceTypeName);
1976 #ifdef WITH_PRESENCE
1977 if(presenceResource.handle)
1979 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1980 SendPresenceNotification(resource->rsrcType);
1988 * Bind a resourceinterface to a resource.
1990 * @param handle - handle to the resource
1991 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
1994 * OC_STACK_OK - no errors
1995 * OC_STACK_ERROR - stack process error
1998 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
1999 const char *resourceInterfaceName) {
2001 OCStackResult result = OC_STACK_ERROR;
2002 OCResource *resource;
2004 // Make sure resource exists
2005 resource = findResource((OCResource *) handle);
2007 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2008 return OC_STACK_ERROR;
2011 // call internal function
2012 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2014 #ifdef WITH_PRESENCE
2015 if(presenceResource.handle)
2017 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2018 SendPresenceNotification(resource->rsrcType);
2026 * Get the number of resources that have been created in the stack.
2028 * @param numResources - pointer to count variable
2031 * OC_STACK_OK - no errors
2032 * OC_STACK_ERROR - stack process error
2035 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
2036 OCResource *pointer = headResource;
2038 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
2039 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2042 *numResources = *numResources + 1;
2043 pointer = pointer->next;
2049 * Get a resource handle by index.
2051 * @param index - index of resource, 0 to Count - 1
2054 * Resource handle - if found
2055 * NULL - if not found
2057 OCResourceHandle OCGetResourceHandle(uint8_t index) {
2058 OCResource *pointer = headResource;
2061 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
2063 // Iterate through the list
2064 while ((i < index) && pointer) {
2066 pointer = pointer->next;
2068 return (OCResourceHandle) pointer;
2072 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
2075 * @param handle - handle of resource to be deleted
2078 * OC_STACK_OK - no errors
2079 * OC_STACK_ERROR - stack process error
2080 * OC_STACK_NO_RESOURCE - resource not found
2081 * OC_STACK_INVALID_PARAM - invalid param
2083 OCStackResult OCDeleteResource(OCResourceHandle handle) {
2084 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
2087 OC_LOG(ERROR, TAG, PCF("Invalid param"));
2088 return OC_STACK_INVALID_PARAM;
2091 OCResource *resource = findResource((OCResource *) handle);
2092 if (resource == NULL) {
2093 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2094 return OC_STACK_NO_RESOURCE;
2097 if (deleteResource((OCResource *) handle) == 0) {
2098 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
2099 return OC_STACK_ERROR;
2106 * Get the URI of the resource specified by handle.
2108 * @param handle - handle of resource
2110 * URI string - if resource found
2111 * NULL - resource not found
2113 const char *OCGetResourceUri(OCResourceHandle handle) {
2114 OCResource *resource;
2115 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
2117 resource = findResource((OCResource *) handle);
2119 return resource->uri;
2121 return (const char *) NULL;
2125 * Get the properties of the resource specified by handle.
2126 * NOTE: that after a resource is created, the OC_ACTIVE property is set
2127 * for the resource by the stack.
2129 * @param handle - handle of resource
2131 * property bitmap - if resource found
2132 * NULL - resource not found
2134 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
2135 OCResource *resource;
2136 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
2138 resource = findResource((OCResource *) handle);
2140 return resource->resourceProperties;
2146 * Get the number of resource types of the resource.
2148 * @param handle - handle of resource
2149 * @param numResourceTypes - pointer to count variable
2152 * OC_STACK_OK - no errors
2153 * OC_STACK_ERROR - stack process error
2155 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
2156 uint8_t *numResourceTypes) {
2157 OCResource *resource;
2158 OCResourceType *pointer;
2160 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
2161 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
2162 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2164 *numResourceTypes = 0;
2166 resource = findResource((OCResource *) handle);
2168 pointer = resource->rsrcType;
2170 *numResourceTypes = *numResourceTypes + 1;
2171 pointer = pointer->next;
2178 * Get name of resource type of the resource.
2180 * @param handle - handle of resource
2181 * @param index - index of resource, 0 to Count - 1
2184 * resource type name - if resource found
2185 * NULL - resource not found
2187 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
2188 OCResourceType *resourceType;
2190 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
2192 resourceType = findResourceTypeAtIndex(handle, index);
2194 return resourceType->resourcetypename;
2196 return (const char *) NULL;
2202 * Get the number of resource interfaces of the resource.
2204 * @param handle - handle of resource
2205 * @param numResources - pointer to count variable
2208 * OC_STACK_OK - no errors
2209 * OC_STACK_ERROR - stack process error
2211 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
2212 uint8_t *numResourceInterfaces) {
2213 OCResourceInterface *pointer;
2214 OCResource *resource;
2216 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
2218 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2219 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
2221 *numResourceInterfaces = 0;
2222 resource = findResource((OCResource *) handle);
2224 pointer = resource->rsrcInterface;
2226 *numResourceInterfaces = *numResourceInterfaces + 1;
2227 pointer = pointer->next;
2234 * Get name of resource interface of the resource.
2236 * @param handle - handle of resource
2237 * @param index - index of resource, 0 to Count - 1
2240 * resource interface name - if resource found
2241 * NULL - resource not found
2243 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
2244 OCResourceInterface *resourceInterface;
2246 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
2248 resourceInterface = findResourceInterfaceAtIndex(handle, index);
2249 if (resourceInterface) {
2250 return resourceInterface->name;
2252 return (const char *) NULL;
2256 * Get resource handle from the collection resource by index.
2258 * @param collectionHandle - handle of collection resource
2259 * @param index - index of contained resource, 0 to Count - 1
2262 * handle to resource - if resource found
2263 * NULL - resource not found
2265 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
2267 OCResource *resource;
2269 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
2271 if (index >= MAX_CONTAINED_RESOURCES) {
2275 resource = findResource((OCResource *) collectionHandle);
2280 return resource->rsrcResources[index];
2284 * Bind an entity handler to the resource.
2286 * @param handle - handle to the resource that the contained resource is to be bound
2287 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
2289 * OC_STACK_OK - no errors
2290 * OC_STACK_ERROR - stack process error
2292 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
2293 OCEntityHandler entityHandler) {
2294 OCResource *resource;
2296 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
2298 // Validate parameters
2299 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
2300 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
2302 // Use the handle to find the resource in the resource linked list
2303 resource = findResource((OCResource *)handle);
2305 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2306 return OC_STACK_ERROR;
2310 resource->entityHandler = entityHandler;
2312 #ifdef WITH_PRESENCE
2313 if(presenceResource.handle)
2315 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2316 SendPresenceNotification(resource->rsrcType);
2324 * Get the entity handler for a resource.
2326 * @param handle - handle of resource
2329 * entity handler - if resource found
2330 * NULL - resource not found
2332 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
2333 OCResource *resource;
2335 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
2337 // Use the handle to find the resource in the resource linked list
2338 resource = findResource((OCResource *)handle);
2340 OC_LOG(ERROR, TAG, PCF("Resource not found"));
2345 return resource->entityHandler;
2348 void incrementSequenceNumber(OCResource * resPtr)
2350 // Increment the sequence number
2351 resPtr->sequenceNum += 1;
2352 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
2354 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
2360 * Notify Presence subscribers that a resource has been modified
2362 * @param resourceType - Handle to the resourceType linked list of resource
2363 * that was modified.
2364 * @param qos - Quality Of Service
2367 #ifdef WITH_PRESENCE
2368 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
2370 OCResource *resPtr = NULL;
2371 OCStackResult result;
2372 OCMethod method = OC_REST_PRESENCE;
2373 uint32_t maxAge = 0;
2374 resPtr = findResource((OCResource *) presenceResource.handle);
2377 return OC_STACK_NO_RESOURCE;
2379 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
2381 maxAge = presenceResource.presenceTTL;
2388 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
2391 #endif // WITH_PRESENCE
2393 * Notify observers that an observed value has changed.
2395 * @param handle - handle of resource
2398 * OC_STACK_OK - no errors
2399 * OC_STACK_NO_RESOURCE - invalid resource handle
2400 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
2402 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
2404 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2406 OCResource *resPtr = NULL;
2407 OCStackResult result;
2408 OCMethod method = OC_REST_NOMETHOD;
2409 uint32_t maxAge = 0;
2411 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
2412 #ifdef WITH_PRESENCE
2413 if(handle == presenceResource.handle)
2417 #endif // WITH_PRESENCE
2418 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2420 // Verify that the resource exists
2421 resPtr = findResource ((OCResource *) handle);
2424 return OC_STACK_NO_RESOURCE;
2428 //only increment in the case of regular observing (not presence)
2429 incrementSequenceNumber(resPtr);
2430 method = OC_REST_OBSERVE;
2431 maxAge = MAX_OBSERVE_AGE;
2432 #ifdef WITH_PRESENCE
2433 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
2435 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
2442 OCNotifyListOfObservers (OCResourceHandle handle,
2443 OCObservationId *obsIdList,
2444 uint8_t numberOfIds,
2445 unsigned char *notificationJSONPayload,
2446 OCQualityOfService qos)
2448 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
2450 OCResource *resPtr = NULL;
2451 //TODO: we should allow the server to define this
2452 uint32_t maxAge = MAX_OBSERVE_AGE;
2454 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
2455 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
2456 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
2458 // Verify that the resource exists
2459 resPtr = findResource ((OCResource *) handle);
2460 if (NULL == resPtr || myStackMode == OC_CLIENT)
2462 return OC_STACK_NO_RESOURCE;
2466 incrementSequenceNumber(resPtr);
2468 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
2469 notificationJSONPayload, maxAge, qos));
2473 * Send a response to a request.
2474 * The response can be a regular, slow, or block (i.e. a response that
2475 * is too large to be sent in a single PDU and must span multiple transmissions)
2477 * @param response - pointer to structure that contains response parameters
2480 * OC_STACK_OK - No errors; Success
2481 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
2482 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
2483 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
2484 * persistent response buffer is necessary
2486 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
2488 OCStackResult result = OC_STACK_ERROR;
2489 OCServerRequest *serverRequest = NULL;
2491 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
2493 // Validate input parameters
2494 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
2495 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
2497 // TODO: Placeholder for creating a response entry when implementing
2498 // block transfer feature
2500 // If a response payload is present, check if block transfer is required
2501 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
2502 (const char *)ehResponse->payload, ehResponse->payloadSize))
2504 OC_LOG(INFO, TAG, PCF("Block transfer required"));
2506 // Persistent response buffer is needed for block transfer
2507 if (!ehResponse->persistentBufferFlag)
2509 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
2510 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
2512 // TODO: Placeholder for block transfer handling
2513 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
2514 // when implementing the block transfer feature
2520 // Get pointer to request info
2521 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
2524 result = serverRequest->ehResponseHandler(ehResponse);
2531 * Cancel a response. Applies to a block response
2533 * @param responseHandle - response handle set by stack in OCServerResponse after
2534 * OCDoResponse is called
2537 * OC_STACK_OK - No errors; Success
2538 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
2540 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
2542 OCStackResult result = OC_STACK_NOTIMPL;
2544 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
2546 // TODO: validate response handle
2551 //-----------------------------------------------------------------------------
2552 // Private internal function definitions
2553 //-----------------------------------------------------------------------------
2555 * Generate handle of OCDoResource invocation for callback management.
2557 static OCDoHandle GenerateInvocationHandle()
2559 OCDoHandle handle = NULL;
2560 // Generate token here, it will be deleted when the transaction is deleted
2561 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2564 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
2569 #ifdef WITH_PRESENCE
2570 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
2571 OCResourceProperty resourceProperties, uint8_t enable)
2573 if (resourceProperties
2574 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
2575 OC_LOG(ERROR, TAG, PCF("Invalid property"));
2576 return OC_STACK_INVALID_PARAM;
2580 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
2584 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
2591 * Initialize resource data structures, variables, etc.
2593 OCStackResult initResources() {
2594 OCStackResult result = OC_STACK_OK;
2595 // Init application resource vars
2596 headResource = NULL;
2597 // Init Virtual Resources
2598 #ifdef WITH_PRESENCE
2599 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
2600 //presenceResource.token = OCGenerateCoAPToken();
2601 result = OCCreateResource(&presenceResource.handle,
2602 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
2607 //make resource inactive
2608 result = OCChangeResourceProperty(
2609 &(((OCResource *) presenceResource.handle)->resourceProperties),
2616 * Add a resource to the end of the linked list of resources.
2618 * @param resource - resource to be added
2620 void insertResource(OCResource *resource) {
2621 OCResource *pointer;
2623 if (!headResource) {
2624 headResource = resource;
2626 pointer = headResource;
2628 while (pointer->next) {
2629 pointer = pointer->next;
2631 pointer->next = resource;
2633 resource->next = NULL;
2637 * Find a resource in the linked list of resources.
2639 * @param resource - resource to be found
2641 * NULL - resource not found
2642 * pointer to resource - pointer to resource that was found in the linked list
2644 OCResource *findResource(OCResource *resource) {
2645 OCResource *pointer = headResource;
2648 if (pointer == resource) {
2651 pointer = pointer->next;
2656 void deleteAllResources()
2658 OCResource *pointer = headResource;
2663 temp = pointer->next;
2664 #ifdef WITH_PRESENCE
2665 if(pointer != (OCResource *) presenceResource.handle)
2667 #endif // WITH_PRESENCE
2668 deleteResource(pointer);
2669 #ifdef WITH_PRESENCE
2671 #endif // WITH_PRESENCE
2675 #ifdef WITH_PRESENCE
2676 // Ensure that the last resource to be deleted is the presence resource. This allows for all
2677 // presence notification attributed to their deletion to be processed.
2678 deleteResource((OCResource *) presenceResource.handle);
2679 #endif // WITH_PRESENCE
2683 * Delete the resource from the linked list.
2685 * @param resource - resource to be deleted
2690 int deleteResource(OCResource *resource) {
2691 OCResource *prev = NULL;
2694 temp = headResource;
2696 if (temp == resource) {
2697 // Invalidate all Resource Properties.
2698 resource->resourceProperties = (OCResourceProperty) 0;
2699 #ifdef WITH_PRESENCE
2700 if(resource != (OCResource *) presenceResource.handle)
2702 #endif // WITH_PRESENCE
2703 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
2704 #ifdef WITH_PRESENCE
2707 if(presenceResource.handle)
2709 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2710 if(resource != (OCResource *) presenceResource.handle)
2712 SendPresenceNotification(resource->rsrcType);
2716 SendPresenceNotification(NULL);
2721 if (temp == headResource) {
2722 headResource = temp->next;
2724 prev->next = temp->next;
2727 deleteResourceElements(temp);
2740 * Delete all of the dynamically allocated elements that were created for the resource.
2742 * @param resource - specified resource
2744 void deleteResourceElements(OCResource *resource) {
2750 OCFree(resource->uri);
2752 // Delete resourcetype linked list
2753 deleteResourceType(resource->rsrcType);
2755 // Delete resourceinterface linked list
2756 deleteResourceInterface(resource->rsrcInterface);
2760 * Delete all of the dynamically allocated elements that were created for the resource type.
2762 * @param resourceType - specified resource type
2764 void deleteResourceType(OCResourceType *resourceType) {
2765 OCResourceType *pointer = resourceType;
2766 OCResourceType *next;
2769 next = pointer->next;
2770 OCFree(pointer->resourcetypename);
2777 * Delete all of the dynamically allocated elements that were created for the resource interface.
2779 * @param resourceInterface - specified resource interface
2781 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
2782 OCResourceInterface *pointer = resourceInterface;
2783 OCResourceInterface *next;
2786 next = pointer->next;
2787 OCFree(pointer->name);
2794 * Insert a resource type into a resource's resource type linked list.
2796 * @param resource - resource where resource type is to be inserted
2797 * @param resourceType - resource type to be inserted
2799 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
2800 OCResourceType *pointer;
2802 if (resource && !resource->rsrcType) {
2803 resource->rsrcType = resourceType;
2807 pointer = resource->rsrcType;
2811 pointer = resourceType;
2813 while (pointer->next) {
2814 pointer = pointer->next;
2816 pointer->next = resourceType;
2818 resourceType->next = NULL;
2822 * Get a resource type at the specified index within a resource.
2824 * @param handle - handle of resource
2825 * @param index - index of resource type
2828 * resourcetype - if found
2831 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
2832 OCResource *resource;
2833 OCResourceType *pointer;
2836 // Find the specified resource
2837 resource = findResource((OCResource *) handle);
2842 // Make sure a resource has a resourcetype
2843 if (!resource->rsrcType) {
2847 // Iterate through the list
2848 pointer = resource->rsrcType;
2850 while ((i < index) && pointer) {
2852 pointer = pointer->next;
2858 * Finds a resource type in an OCResourceType link-list.
2860 * @param resourceTypeList - the link-list to be searched through
2861 * @param resourceTypeName - the key to search for
2864 * resourceType that matches the key (ie. resourceTypeName)
2865 * NULL - either an invalid parameter or this function was unable to find the key.
2867 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
2869 if(resourceTypeList && resourceTypeName)
2871 OCResourceType * rtPointer = resourceTypeList;
2872 while(resourceTypeName && rtPointer)
2874 if(rtPointer->resourcetypename &&
2875 strcmp(resourceTypeName, (const char *)
2876 (rtPointer->resourcetypename)) == 0)
2880 rtPointer = rtPointer->next;
2887 * Insert a resource interface into a resource's resource interface linked list.
2889 * @param resource - resource where resource interface is to be inserted
2890 * @param resourceInterface - resource interface to be inserted
2892 void insertResourceInterface(OCResource *resource,
2893 OCResourceInterface *resourceInterface) {
2894 OCResourceInterface *pointer;
2896 if (!resource->rsrcInterface) {
2897 resource->rsrcInterface = resourceInterface;
2899 pointer = resource->rsrcInterface;
2900 while (pointer->next) {
2901 pointer = pointer->next;
2903 pointer->next = resourceInterface;
2905 resourceInterface->next = NULL;
2909 * Get a resource interface at the specified index within a resource.
2911 * @param handle - handle of resource
2912 * @param index - index of resource interface
2915 * resourceinterface - if found
2918 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
2920 OCResource *resource;
2921 OCResourceInterface *pointer;
2924 // Find the specified resource
2925 resource = findResource((OCResource *) handle);
2930 // Make sure a resource has a resourceinterface
2931 if (!resource->rsrcInterface) {
2935 // Iterate through the list
2936 pointer = resource->rsrcInterface;
2938 while ((i < index) && pointer) {
2940 pointer = pointer->next;
2946 * Determine if a request/response must be sent in a block transfer because it is too large to be
2947 * sent in a single PDU. This function can be used for either a request or a response
2949 * @param request - NULL or pointer to request
2950 * @param response - NULL or pointer to response
2951 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
2952 * the length of the request/response
2955 * 0 - packet transfer NOT required (i.e. normal request/response)
2956 * 1 - packet transfer required (i.e. block transfer needed)
2958 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
2962 // Determine if we are checking a request or a response
2965 // If size is greater than 0, use it for the request size value, otherwise
2966 // assume request is null terminated and use strlen for size value
2967 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
2974 // If size is greater than 0, use it for the response size value, otherwise
2975 // assume response is null terminated and use strlen for size value
2976 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
2985 * Retrieves a resource type based upon a uri string if the uri string contains only just one
2986 * resource attribute (and that has to be of type "rt").
2988 * @remark This API malloc's memory for the resource type and newURI. Do not malloc resourceType
2989 * or newURI before passing in.
2991 * @param uri - Valid URI for "requiredUri" parameter to OCDoResource API.
2992 * @param resourceType - The resource type to be populated; pass by reference.
2993 * @param newURI - Return URI without resourceType appended to the end of it. This is used to
2994 * ensure that the uri parameter is not modified; pass by reference.
2997 * OC_STACK_INVALID_URI - Returns this if the URI is invalid/NULL.
2998 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
2999 * OC_STACK_OK - Success
3001 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI)
3005 return OC_STACK_INVALID_URI;
3007 if(!resourceType || !newURI)
3009 return OC_STACK_INVALID_PARAM;
3011 char * leftToken = NULL;
3012 char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
3017 strcpy(tempURI, uri);
3018 leftToken = strtok((char *)tempURI, "?");
3020 while(leftToken != NULL)
3022 if(strncmp(leftToken, "rt=", 3) == 0)
3024 *resourceType = (unsigned char *) OCMalloc(strlen(leftToken)-3);
3029 strcpy((char *)*resourceType, ((const char *)&leftToken[3]));
3032 leftToken = strtok(NULL, "?");
3040 return OC_STACK_NO_MEMORY;
3043 const ServerID OCGetServerInstanceID(void)
3045 static bool generated = false;
3046 static ServerID sid;
3053 sid = OCGetRandom();
3058 const char* OCGetServerInstanceIDString(void)
3060 // max printed length of a base 10
3061 // uint32 is 10 characters, so 11 includes null.
3062 // This will change as the representation gets switched
3064 static char buffer[11];
3065 int n = sprintf(buffer, "%u", OCGetServerInstanceID());