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"
36 //-----------------------------------------------------------------------------
38 //-----------------------------------------------------------------------------
40 OC_STACK_UNINITIALIZED = 0, OC_STACK_INITIALIZED
45 OC_PRESENCE_UNINITIALIZED = 0, OC_PRESENCE_INITIALIZED
49 //-----------------------------------------------------------------------------
51 //-----------------------------------------------------------------------------
52 static OCStackState stackState = OC_STACK_UNINITIALIZED;
54 OCResource *headResource = NULL;
56 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
57 static PresenceResource presenceResource;
58 uint8_t PresenceTimeOutSize = 0;
59 uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
63 OCDeviceEntityHandler defaultDeviceHandler;
65 //-----------------------------------------------------------------------------
67 //-----------------------------------------------------------------------------
68 #define TAG PCF("OCStack")
69 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
70 TAG, PCF(#arg " is NULL")); return (retVal); } }
72 //TODO: we should allow the server to define this
73 #define MAX_OBSERVE_AGE (0x2FFFFUL)
74 //-----------------------------------------------------------------------------
76 //-----------------------------------------------------------------------------
77 extern void DeinitOCSecurityInfo();
79 //-----------------------------------------------------------------------------
80 // Internal API function
81 //-----------------------------------------------------------------------------
83 // This internal function is called to update the stack with the status of
84 // observers and communication failures
85 OCStackResult OCStackFeedBack(OCCoAPToken * token, uint8_t status)
87 OCStackResult result = OC_STACK_ERROR;
88 ResourceObserver * observer = NULL;
89 OCEntityHandlerRequest ehRequest;
90 memset(&ehRequest, 0, sizeof(OCEntityHandlerRequest));
94 case OC_OBSERVER_NOT_INTERESTED:
95 OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
96 observer = GetObserverUsingToken (token);
99 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
100 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
101 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
102 if(result != OC_STACK_OK)
106 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
108 //observer is not observing anymore
109 result = DeleteObserverUsingToken (token);
110 if(result == OC_STACK_OK)
112 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
116 result = OC_STACK_OK;
117 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
120 case OC_OBSERVER_STILL_INTERESTED:
121 //observer is still interested
122 OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
123 notifications, reset the failedCount"));
124 observer = GetObserverUsingToken(token);
127 observer->forceHighQos = 0;
128 observer->failedCommCount = 0;
129 result = OC_STACK_OK;
133 result = OC_STACK_OBSERVER_NOT_FOUND;
136 case OC_OBSERVER_FAILED_COMM:
137 //observer is not reachable
138 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
139 observer = GetObserverUsingToken(token);
142 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
144 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
145 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
146 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
147 if(result != OC_STACK_OK)
149 return OC_STACK_ERROR;
151 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
152 //observer is unreachable
153 result = DeleteObserverUsingToken (token);
154 if(result == OC_STACK_OK)
156 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
160 result = OC_STACK_OK;
161 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
166 observer->failedCommCount++;
167 result = OC_STACK_CONTINUE;
169 observer->forceHighQos = 1;
170 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
174 OC_LOG(ERROR, TAG, PCF("Unknown status"));
175 result = OC_STACK_ERROR;
181 //This function will be called back by occoap layer when a request is received
182 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
184 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
186 OCStackResult result = OC_STACK_ERROR;
187 ResourceHandling resHandling;
188 OCResource *resource;
190 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
193 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
194 result = AddServerRequest(&request, protocolRequest->coapID,
195 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
196 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
197 protocolRequest->observationOption, protocolRequest->qos,
198 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
199 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
200 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
201 protocolRequest->reqTotalSize);
202 if (OC_STACK_OK != result)
204 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
207 VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
209 if(!protocolRequest->reqMorePacket)
211 request->requestComplete = 1;
216 OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
219 if(request->requestComplete)
221 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
222 result = DetermineResourceHandling (request, &resHandling, &resource);
223 if (result == OC_STACK_OK)
225 result = ProcessRequest(resHandling, resource, request);
229 result = OC_STACK_ERROR;
234 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
235 result = OC_STACK_CONTINUE;
240 //This function will be called back by occoap layer when a response is received
241 void HandleStackResponses(OCResponse * response)
243 OCStackApplicationResult result = OC_STACK_DELETE_TRANSACTION;
244 OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)"));
246 if (response->cbNode)
248 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
249 result = response->cbNode->callBack(response->cbNode->context,
250 response->cbNode->handle, response->clientResponse);
251 if (result == OC_STACK_DELETE_TRANSACTION ||
252 response->clientResponse->result == OC_STACK_COMM_ERROR ||
253 response->clientResponse->result == OC_STACK_RESOURCE_DELETED)
255 FindAndDeleteClientCB(response->cbNode);
260 int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
263 unsigned char *itr, *coap;
264 uint8_t dotCount = 0;
268 /* search for scheme */
270 if (!isdigit((unsigned char) *ipAddrStr))
272 coap = (unsigned char *) OC_COAP_SCHEME;
273 while (*coap && tolower(*itr) == *coap)
282 if (isdigit((unsigned char) *ipAddrStr))
285 ipAddr[index] += *ipAddrStr - '0';
287 else if ((unsigned char) *ipAddrStr == '.')
299 if(*ipAddrStr == ':')
303 if (isdigit((unsigned char) *ipAddrStr))
306 *port += *ipAddrStr - '0';
317 if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
328 //-----------------------------------------------------------------------------
329 // Private internal function prototypes
330 //-----------------------------------------------------------------------------
332 static OCDoHandle GenerateInvocationHandle();
333 static OCStackResult initResources();
334 static void insertResource(OCResource *resource);
335 static OCResource *findResource(OCResource *resource);
336 static void insertResourceType(OCResource *resource,
337 OCResourceType *resourceType);
338 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
340 static void insertResourceInterface(OCResource *resource,
341 OCResourceInterface *resourceInterface);
342 static OCResourceInterface *findResourceInterfaceAtIndex(
343 OCResourceHandle handle, uint8_t index);
344 static void deleteResourceType(OCResourceType *resourceType);
345 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
346 static void deleteResourceElements(OCResource *resource);
347 static int deleteResource(OCResource *resource);
348 static void deleteAllResources();
349 static void incrementSequenceNumber(OCResource * resPtr);
350 static OCStackResult verifyUriQueryLength(const char * inputUri,
352 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
353 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI);
355 //-----------------------------------------------------------------------------
357 //-----------------------------------------------------------------------------
360 * Initialize the OC Stack. Must be called prior to starting the stack.
363 * IP Address of host device
365 * Port of host device
367 * Host device is client, server, or client-server
370 * OC_STACK_OK - no errors
371 * OC_STACK_ERROR - stack init error
373 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
375 OCStackResult result = OC_STACK_ERROR;
376 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
380 OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
386 OC_LOG(INFO, TAG, PCF("Client mode"));
389 OC_LOG(INFO, TAG, PCF("Server mode"));
391 case OC_CLIENT_SERVER:
392 OC_LOG(INFO, TAG, PCF("Client-server mode"));
395 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
396 return OC_STACK_ERROR;
401 defaultDeviceHandler = NULL;
404 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
405 #endif // WITH_PRESENCE
407 // Make call to OCCoAP layer
408 result = OCInitCoAP(ipAddr, (uint16_t) port, myStackMode);
409 if (result == OC_STACK_OK)
411 stackState = OC_STACK_INITIALIZED;
413 // Initialize resource
414 if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
416 result = initResources();
418 if(result != OC_STACK_OK)
420 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
426 * Stop the OC stack. Use for a controlled shutdown.
428 * OC_STACK_OK - no errors
429 * OC_STACK_ERROR - stack not initialized
431 OCStackResult OCStop()
433 OCStackResult result = OC_STACK_ERROR;
435 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
437 if (stackState != OC_STACK_INITIALIZED)
439 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
440 return OC_STACK_ERROR;
444 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
445 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
446 presenceResource.presenceTTL = 0;
447 #endif // WITH_PRESENCE
449 // Free memory dynamically allocated for resources
450 deleteAllResources();
452 // Make call to OCCoAP layer
453 if (OCStopCoAP() == OC_STACK_OK)
455 // Remove all observers
456 DeleteObserverList();
457 // Remove all the client callbacks
458 DeleteClientCBList();
459 stackState = OC_STACK_UNINITIALIZED;
460 result = OC_STACK_OK;
462 result = OC_STACK_ERROR;
465 // Deinit security blob
466 DeinitOCSecurityInfo();
468 if (result != OC_STACK_OK) {
469 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
476 * Verify the lengths of the URI and the query separately
478 * @param inputUri - Input URI and query.
479 * @param uriLen - The length of the initial URI with query.
481 * Note: The '?' that appears after the URI is not considered as
482 * a part of the query.
484 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
488 query = strchr (inputUri, '?');
492 if((query - inputUri) > MAX_URI_LENGTH)
494 return OC_STACK_INVALID_URI;
497 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
499 return OC_STACK_INVALID_QUERY;
502 else if(uriLen > MAX_URI_LENGTH)
504 return OC_STACK_INVALID_URI;
510 * Discover or Perform requests on a specified resource (specified by that Resource's respective URI).
512 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of calling this API.
513 * @param method - @ref OCMethod to perform on the resource
514 * @param requiredUri - URI of the resource to interact with
515 * @param referenceUri - URI of the reference resource
516 * @param request - JSON encoded request
517 * @param qos - quality of service
518 * @param cbData - struct that contains asynchronous callback function that is invoked
519 * by the stack when discovery or resource interaction is complete
520 * @param options - The address of an array containing the vendor specific header
521 * header options to be sent with the request
522 * @param numOptions - Number of vendor specific header options to be included
525 * OC_STACK_OK - no errors
526 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
527 * OC_STACK_INVALID_METHOD - invalid resource method
528 * OC_STACK_INVALID_URI - invalid required or reference URI
531 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
532 const char *referenceUri, const char *request,
533 OCQualityOfService qos, OCCallbackData *cbData,
534 OCHeaderOption * options, uint8_t numOptions)
536 OCStackResult result = OC_STACK_ERROR;
538 ClientCB *clientCB = NULL;
539 unsigned char * requestUri = NULL;
540 unsigned char * resourceType = NULL;
541 char * newUri = (char *)requiredUri;
544 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
546 // Validate input parameters
547 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
548 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
550 TODO ("Need to form the final query by concatenating require and reference URI's");
551 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
553 uint16_t uriLen = strlen(requiredUri);
555 // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS
562 case OC_REST_OBSERVE:
563 case OC_REST_OBSERVE_ALL:
564 case OC_REST_CANCEL_OBSERVE:
567 case OC_REST_PRESENCE:
571 result = OC_STACK_INVALID_METHOD;
575 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
580 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
582 result = OC_STACK_INVALID_PARAM;
587 if(method == OC_REST_PRESENCE)
589 result = getResourceType(requiredUri, &resourceType, &newUri);
591 OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
595 OC_LOG(DEBUG, TAG, "Got Resource Type is NULL.");
597 if(result != OC_STACK_OK)
602 #endif // WITH_PRESENCE
604 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
607 memcpy(requestUri, newUri, (uriLen + 1));
611 result = OC_STACK_NO_MEMORY;
615 *handle = GenerateInvocationHandle();
618 result = OC_STACK_NO_MEMORY;
622 // Generate token which will be used by OCStack to match responses received
624 OCGenerateCoAPToken(&token);
626 if((result = AddClientCB(&clientCB, cbData, &token, handle, method, requestUri, resourceType))
629 result = OC_STACK_NO_MEMORY;
633 // Make call to OCCoAP layer
634 result = OCDoCoAPResource(method, qos, &token, newUri, request, options, numOptions);
637 if(newUri != requiredUri)
641 if (result != OC_STACK_OK)
643 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
644 FindAndDeleteClientCB(clientCB);
650 * Cancel a request associated with a specific @ref OCDoResource invocation.
652 * @param handle - Used to identify a specific OCDoResource invocation.
653 * @param qos - used to specify Quality of Service (read below for more info)
654 * @param options- used to specify vendor specific header options when sending
655 * explicit observe cancellation
656 * @param numOptions- Number of header options to be included
659 * OC_STACK_OK - No errors; Success
660 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
662 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
663 uint8_t numOptions) {
665 * This ftn is implemented one of two ways in the case of observation:
667 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
668 * Remove the callback associated on client side.
669 * When the next notification comes in from server,
670 * reply with RESET message to server.
671 * Keep in mind that the server will react to RESET only
672 * if the last notification was sent ans CON
674 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
675 * and it is associated with an observe request
676 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
677 * Send CON Observe request to server with
678 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
679 * Remove the callback associated on client side.
681 OCStackResult ret = OC_STACK_OK;
684 return OC_STACK_INVALID_PARAM;
687 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
689 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
692 switch (clientCB->method)
694 case OC_REST_OBSERVE:
695 case OC_REST_OBSERVE_ALL:
696 if(qos == OC_HIGH_QOS)
698 ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
699 &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
704 FindAndDeleteClientCB(clientCB);
708 case OC_REST_PRESENCE:
709 FindAndDeleteClientCB(clientCB);
713 return OC_STACK_INVALID_METHOD;
719 OCStackResult OCProcessPresence()
721 OCStackResult result = OC_STACK_OK;
722 uint8_t ipAddr[4] = { 0 };
725 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
726 ClientCB* cbNode = NULL;
728 OCClientResponse clientResponse;
729 OCResponse * response = NULL;
731 LL_FOREACH(cbList, cbNode) {
732 if(OC_REST_PRESENCE == cbNode->method)
736 uint32_t now = GetTime(0);
737 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
738 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
741 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
746 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
747 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
748 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
751 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
753 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
754 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
756 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
758 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
759 (OCDevAddr *) &dst, 0, NULL);
760 if(result != OC_STACK_OK)
764 result = FormOCResponse(&response, cbNode, 0, &clientResponse);
765 if(result != OC_STACK_OK)
770 // Increment the TTLLevel (going to a next state), so we don't keep
771 // sending presence notification to client.
772 cbNode->presence->TTLlevel++;
773 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
774 cbNode->presence->TTLlevel);
778 result = OC_STACK_INVALID_IP;
781 HandleStackResponses(response);
783 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
785 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
787 OCGenerateCoAPToken(&token);
788 result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
789 &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
790 if(result != OC_STACK_OK)
794 cbNode->presence->TTLlevel++;
795 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
801 if (result != OC_STACK_OK)
803 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
810 * Called in main loop of OC client or server. Allows low-level processing of
814 * OC_STACK_OK - no errors
815 * OC_STACK_ERROR - stack process error
817 OCStackResult OCProcess() {
819 OC_LOG(INFO, TAG, PCF("Entering OCProcess"));
830 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
831 * presence notifications to clients via multicast. Once this API has been called with a success,
832 * clients may query for this server's presence and this server's stack will respond via multicast.
834 * Server can call this function when it comes online for the first time, or when it comes back
835 * online from offline mode, or when it re enters network.
837 * @param ttl - Time To Live in seconds
838 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
841 * OC_STACK_OK - No errors; Success
843 OCStackResult OCStartPresence(const uint32_t ttl)
845 OCChangeResourceProperty(
846 &(((OCResource *)presenceResource.handle)->resourceProperties),
851 presenceResource.presenceTTL = ttl;
854 if(OC_PRESENCE_UNINITIALIZED == presenceState)
856 OCDevAddr multiCastAddr;
859 presenceState = OC_PRESENCE_INITIALIZED;
860 OCGenerateCoAPToken(&token);
861 OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
862 //add the presence observer
863 AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
864 (OCResource *)presenceResource.handle, OC_LOW_QOS);
867 // Each time OCStartPresence is called
868 // a different random 32-bit integer number is used
869 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
871 return SendPresenceNotification(NULL);
875 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
876 * presence notifications to clients via multicast. Once this API has been called with a success,
877 * this server's stack will not respond to clients querying for this server's presence.
879 * Server can call this function when it is terminating, going offline, or when going
883 * OC_STACK_OK - No errors; Success
885 OCStackResult OCStopPresence()
887 OCStackResult result = OC_STACK_ERROR;
888 //make resource inactive
889 result = OCChangeResourceProperty(
890 &(((OCResource *) presenceResource.handle)->resourceProperties),
892 result = SendPresenceNotification(NULL);
899 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
901 defaultDeviceHandler = entityHandler;
909 * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource
910 * @param resourceTypeName - name of resource type. Example: "core.led"
911 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
912 * @param uri - URI of the resource. Example: "/a/led"
913 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
914 * NULL for default entity handler
915 * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE
918 * OC_STACK_OK - no errors
919 * OC_STACK_ERROR - stack process error
921 OCStackResult OCCreateResource(OCResourceHandle *handle,
922 const char *resourceTypeName,
923 const char *resourceInterfaceName,
924 const char *uri, OCEntityHandler entityHandler,
925 uint8_t resourceProperties) {
927 OCResource *pointer = NULL;
930 OCStackResult result = OC_STACK_ERROR;
932 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
934 if(myStackMode == OC_CLIENT)
938 // Validate parameters
939 // Is it presented during resource discovery?
940 if (!handle || !resourceTypeName || !uri) {
941 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
942 return OC_STACK_INVALID_PARAM;
945 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
946 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
949 // Make sure resourceProperties bitmask has allowed properties specified
950 if (resourceProperties
951 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
952 OC_LOG(ERROR, TAG, PCF("Invalid property"));
953 return OC_STACK_INVALID_PARAM;
956 // If the headResource is NULL, then no resources have been created...
957 pointer = headResource;
959 // At least one resources is in the resource list, so we need to search for
960 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
962 if (strcmp(uri, pointer->uri) == 0) {
963 OC_LOG(ERROR, TAG, PCF("URI already in use"));
964 return OC_STACK_INVALID_PARAM;
966 pointer = pointer->next;
969 // Create the pointer and insert it into the resource list
970 pointer = (OCResource *) OCMalloc(sizeof(OCResource));
974 memset(pointer, 0, sizeof(OCResource));
975 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
977 insertResource(pointer);
980 size = strlen(uri) + 1;
981 str = (char *) OCMalloc(size);
985 strncpy(str, uri, size);
988 // Set properties. Set OC_ACTIVE
989 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
992 // Add the resourcetype to the resource
993 result = BindResourceTypeToResource(pointer, resourceTypeName);
994 if (result != OC_STACK_OK) {
995 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
999 // Add the resourceinterface to the resource
1000 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
1001 if (result != OC_STACK_OK) {
1002 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
1006 // If an entity handler has been passed, attach it to the newly created
1007 // resource. Otherwise, set the default entity handler.
1010 pointer->entityHandler = entityHandler;
1014 pointer->entityHandler = defaultResourceEHandler;
1018 result = OC_STACK_OK;
1020 #ifdef WITH_PRESENCE
1021 if(presenceResource.handle)
1023 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1024 SendPresenceNotification(pointer->rsrcType);
1028 if (result != OC_STACK_OK)
1030 // Deep delete of resource and other dynamic elements that it contains
1031 deleteResource(pointer);
1040 * Create a resource. with host ip address for remote resource
1042 * @param handle - pointer to handle to newly created resource. Set by ocstack.
1043 * Used to refer to resource
1044 * @param resourceTypeName - name of resource type. Example: "core.led"
1045 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1046 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
1047 * @param uri - URI of the resource. Example: "/a/led"
1048 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1049 * NULL for default entity handler
1050 * @param resourceProperties - properties supported by resource.
1051 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
1054 * OC_STACK_OK - no errors
1055 * OC_STACK_ERROR - stack process error
1058 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
1059 const char *resourceTypeName,
1060 const char *resourceInterfaceName,
1063 OCEntityHandler entityHandler,
1064 uint8_t resourceProperties)
1068 OCStackResult result = OC_STACK_ERROR;
1070 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
1071 uri, entityHandler, resourceProperties);
1073 if (result != OC_STACK_ERROR)
1076 size = strlen(host) + 1;
1077 str = (char *) OCMalloc(size);
1080 return OC_STACK_ERROR;
1082 strncpy(str, host, size);
1083 ((OCResource *) *handle)->host = str;
1090 * Add a resource to a collection resource.
1092 * @param collectionHandle - handle to the collection resource
1093 * @param resourceHandle - handle to resource to be added to the collection resource
1096 * OC_STACK_OK - no errors
1097 * OC_STACK_ERROR - stack process error
1098 * OC_STACK_INVALID_PARAM - invalid collectionhandle
1100 OCStackResult OCBindResource(
1101 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1102 OCResource *resource;
1105 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
1107 // Validate parameters
1108 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1109 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1110 // Container cannot contain itself
1111 if (collectionHandle == resourceHandle) {
1112 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
1113 return OC_STACK_INVALID_PARAM;
1116 // Use the handle to find the resource in the resource linked list
1117 resource = findResource((OCResource *) collectionHandle);
1119 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1120 return OC_STACK_INVALID_PARAM;
1123 // Look for an open slot to add add the child resource.
1124 // If found, add it and return success
1125 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1126 if (!resource->rsrcResources[i]) {
1127 resource->rsrcResources[i] = (OCResource *) resourceHandle;
1128 OC_LOG(INFO, TAG, PCF("resource bound"));
1133 #ifdef WITH_PRESENCE
1134 if(presenceResource.handle)
1136 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1137 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1141 // Unable to add resourceHandle, so return error
1142 return OC_STACK_ERROR;
1146 * Remove a resource from a collection resource.
1148 * @param collectionHandle - handle to the collection resource
1149 * @param resourceHandle - handle to resource to be added to the collection resource
1152 * OC_STACK_OK - no errors
1153 * OC_STACK_ERROR - stack process error
1154 * OC_STACK_INVALID_PARAM - invalid collectionHandle
1156 OCStackResult OCUnBindResource(
1157 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1158 OCResource *resource;
1161 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
1163 // Validate parameters
1164 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1165 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1166 // Container cannot contain itself
1167 if (collectionHandle == resourceHandle) {
1168 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
1169 return OC_STACK_INVALID_PARAM;
1172 // Use the handle to find the resource in the resource linked list
1173 resource = findResource((OCResource *) collectionHandle);
1175 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1176 return OC_STACK_INVALID_PARAM;
1179 // Look for an open slot to add add the child resource.
1180 // If found, add it and return success
1181 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1182 if (resourceHandle == resource->rsrcResources[i]) {
1183 resource->rsrcResources[i] = (OCResource *) NULL;
1184 OC_LOG(INFO, TAG, PCF("resource unbound"));
1189 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
1191 #ifdef WITH_PRESENCE
1192 if(presenceResource.handle)
1194 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1195 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1199 // Unable to add resourceHandle, so return error
1200 return OC_STACK_ERROR;
1203 OCStackResult BindResourceTypeToResource(OCResource* resource,
1204 const char *resourceTypeName)
1206 OCResourceType *pointer = NULL;
1209 OCStackResult result = OC_STACK_ERROR;
1211 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
1213 // Validate parameters
1214 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
1215 // TODO: Does resource attribute resentation really have to be maintained in stack?
1216 // Is it presented during resource discovery?
1218 TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
1220 // Create the resourcetype and insert it into the resource list
1221 pointer = (OCResourceType *) OCMalloc(sizeof(OCResourceType));
1225 memset(pointer, 0, sizeof(OCResourceType));
1227 // Set the resourceTypeName
1228 size = strlen(resourceTypeName) + 1;
1229 str = (char *) OCMalloc(size);
1233 strncpy(str, resourceTypeName, size);
1234 pointer->resourcetypename = str;
1236 insertResourceType(resource, pointer);
1237 result = OC_STACK_OK;
1239 exit: if (result != OC_STACK_OK) {
1247 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
1248 const char *resourceInterfaceName)
1250 OCResourceInterface *pointer = NULL;
1253 OCStackResult result = OC_STACK_ERROR;
1255 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
1257 // Validate parameters
1258 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
1260 TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
1262 // Create the resourceinterface and insert it into the resource list
1263 pointer = (OCResourceInterface *) OCMalloc(sizeof(OCResourceInterface));
1267 memset(pointer, 0, sizeof(OCResourceInterface));
1269 // Set the resourceinterface name
1270 size = strlen(resourceInterfaceName) + 1;
1271 str = (char *) OCMalloc(size);
1275 strncpy(str, resourceInterfaceName, size);
1276 pointer->name = str;
1278 // Bind the resourceinterface to the resource
1279 insertResourceInterface(resource, pointer);
1281 result = OC_STACK_OK;
1283 exit: if (result != OC_STACK_OK) {
1292 * Bind a resourcetype to a resource.
1294 * @param handle - handle to the resource
1295 * @param resourceTypeName - name of resource type. Example: "core.led"
1298 * OC_STACK_OK - no errors
1299 * OC_STACK_ERROR - stack process error
1301 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
1302 const char *resourceTypeName) {
1304 OCStackResult result = OC_STACK_ERROR;
1305 OCResource *resource;
1307 // Make sure resource exists
1308 resource = findResource((OCResource *) handle);
1310 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1311 return OC_STACK_ERROR;
1314 // call internal function
1315 result = BindResourceTypeToResource(resource, resourceTypeName);
1317 #ifdef WITH_PRESENCE
1318 if(presenceResource.handle)
1320 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1321 SendPresenceNotification(resource->rsrcType);
1329 * Bind a resourceinterface to a resource.
1331 * @param handle - handle to the resource
1332 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
1335 * OC_STACK_OK - no errors
1336 * OC_STACK_ERROR - stack process error
1339 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
1340 const char *resourceInterfaceName) {
1342 OCStackResult result = OC_STACK_ERROR;
1343 OCResource *resource;
1345 // Make sure resource exists
1346 resource = findResource((OCResource *) handle);
1348 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1349 return OC_STACK_ERROR;
1352 // call internal function
1353 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
1355 #ifdef WITH_PRESENCE
1356 if(presenceResource.handle)
1358 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1359 SendPresenceNotification(resource->rsrcType);
1367 * Get the number of resources that have been created in the stack.
1369 * @param numResources - pointer to count variable
1372 * OC_STACK_OK - no errors
1373 * OC_STACK_ERROR - stack process error
1376 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
1377 OCResource *pointer = headResource;
1379 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
1380 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
1383 *numResources = *numResources + 1;
1384 pointer = pointer->next;
1390 * Get a resource handle by index.
1392 * @param index - index of resource, 0 to Count - 1
1395 * Resource handle - if found
1396 * NULL - if not found
1398 OCResourceHandle OCGetResourceHandle(uint8_t index) {
1399 OCResource *pointer = headResource;
1402 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
1404 // Iterate through the list
1405 while ((i < index) && pointer) {
1407 pointer = pointer->next;
1409 return (OCResourceHandle) pointer;
1413 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
1416 * @param handle - handle of resource to be deleted
1419 * OC_STACK_OK - no errors
1420 * OC_STACK_ERROR - stack process error
1421 * OC_STACK_NO_RESOURCE - resource not found
1422 * OC_STACK_INVALID_PARAM - invalid param
1424 OCStackResult OCDeleteResource(OCResourceHandle handle) {
1425 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
1428 OC_LOG(ERROR, TAG, PCF("Invalid param"));
1429 return OC_STACK_INVALID_PARAM;
1432 OCResource *resource = findResource((OCResource *) handle);
1433 if (resource == NULL) {
1434 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1435 return OC_STACK_NO_RESOURCE;
1438 if (deleteResource((OCResource *) handle) == 0) {
1439 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
1440 return OC_STACK_ERROR;
1447 * Get the URI of the resource specified by handle.
1449 * @param handle - handle of resource
1451 * URI string - if resource found
1452 * NULL - resource not found
1454 const char *OCGetResourceUri(OCResourceHandle handle) {
1455 OCResource *resource;
1456 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
1458 resource = findResource((OCResource *) handle);
1460 return resource->uri;
1462 return (const char *) NULL;
1466 * Get the properties of the resource specified by handle.
1467 * NOTE: that after a resource is created, the OC_ACTIVE property is set
1468 * for the resource by the stack.
1470 * @param handle - handle of resource
1472 * property bitmap - if resource found
1473 * NULL - resource not found
1475 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
1476 OCResource *resource;
1477 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
1479 resource = findResource((OCResource *) handle);
1481 return resource->resourceProperties;
1487 * Get the number of resource types of the resource.
1489 * @param handle - handle of resource
1490 * @param numResourceTypes - pointer to count variable
1493 * OC_STACK_OK - no errors
1494 * OC_STACK_ERROR - stack process error
1496 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
1497 uint8_t *numResourceTypes) {
1498 OCResource *resource;
1499 OCResourceType *pointer;
1501 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
1502 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
1503 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
1505 *numResourceTypes = 0;
1507 resource = findResource((OCResource *) handle);
1509 pointer = resource->rsrcType;
1511 *numResourceTypes = *numResourceTypes + 1;
1512 pointer = pointer->next;
1519 * Get name of resource type of the resource.
1521 * @param handle - handle of resource
1522 * @param index - index of resource, 0 to Count - 1
1525 * resource type name - if resource found
1526 * NULL - resource not found
1528 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
1529 OCResourceType *resourceType;
1531 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
1533 resourceType = findResourceTypeAtIndex(handle, index);
1535 return resourceType->resourcetypename;
1537 return (const char *) NULL;
1543 * Get the number of resource interfaces of the resource.
1545 * @param handle - handle of resource
1546 * @param numResources - pointer to count variable
1549 * OC_STACK_OK - no errors
1550 * OC_STACK_ERROR - stack process error
1552 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
1553 uint8_t *numResourceInterfaces) {
1554 OCResourceInterface *pointer;
1555 OCResource *resource;
1557 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
1559 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
1560 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
1562 *numResourceInterfaces = 0;
1563 resource = findResource((OCResource *) handle);
1565 pointer = resource->rsrcInterface;
1567 *numResourceInterfaces = *numResourceInterfaces + 1;
1568 pointer = pointer->next;
1575 * Get name of resource interface of the resource.
1577 * @param handle - handle of resource
1578 * @param index - index of resource, 0 to Count - 1
1581 * resource interface name - if resource found
1582 * NULL - resource not found
1584 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
1585 OCResourceInterface *resourceInterface;
1587 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
1589 resourceInterface = findResourceInterfaceAtIndex(handle, index);
1590 if (resourceInterface) {
1591 return resourceInterface->name;
1593 return (const char *) NULL;
1597 * Get resource handle from the collection resource by index.
1599 * @param collectionHandle - handle of collection resource
1600 * @param index - index of contained resource, 0 to Count - 1
1603 * handle to resource - if resource found
1604 * NULL - resource not found
1606 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
1608 OCResource *resource;
1610 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
1612 if (index >= MAX_CONTAINED_RESOURCES) {
1616 resource = findResource((OCResource *) collectionHandle);
1621 return resource->rsrcResources[index];
1625 * Bind an entity handler to the resource.
1627 * @param handle - handle to the resource that the contained resource is to be bound
1628 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1630 * OC_STACK_OK - no errors
1631 * OC_STACK_ERROR - stack process error
1633 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
1634 OCEntityHandler entityHandler) {
1635 OCResource *resource;
1637 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
1639 // Validate parameters
1640 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
1641 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
1643 // Use the handle to find the resource in the resource linked list
1644 resource = findResource((OCResource *)handle);
1646 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1647 return OC_STACK_ERROR;
1651 resource->entityHandler = entityHandler;
1653 #ifdef WITH_PRESENCE
1654 if(presenceResource.handle)
1656 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1657 SendPresenceNotification(resource->rsrcType);
1665 * Get the entity handler for a resource.
1667 * @param handle - handle of resource
1670 * entity handler - if resource found
1671 * NULL - resource not found
1673 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
1674 OCResource *resource;
1676 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
1678 // Use the handle to find the resource in the resource linked list
1679 resource = findResource((OCResource *)handle);
1681 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1686 return resource->entityHandler;
1689 void incrementSequenceNumber(OCResource * resPtr)
1691 // Increment the sequence number
1692 resPtr->sequenceNum += 1;
1693 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
1695 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
1700 #ifdef WITH_PRESENCE
1702 * Notify Presence subscribers that a resource has been modified
1704 * @param resourceType - Handle to the resourceType linked list of resource
1705 * that was modified.
1706 * @param qos - Quality Of Service
1709 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
1711 OCResource *resPtr = NULL;
1712 OCStackResult result;
1713 OCMethod method = OC_REST_PRESENCE;
1714 uint32_t maxAge = 0;
1715 resPtr = findResource((OCResource *) presenceResource.handle);
1718 return OC_STACK_NO_RESOURCE;
1720 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
1722 maxAge = presenceResource.presenceTTL;
1729 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
1735 * Notify observers that an observed value has changed.
1737 * @param handle - handle of resource
1740 * OC_STACK_OK - no errors
1741 * OC_STACK_NO_RESOURCE - invalid resource handle
1742 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
1744 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
1746 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
1748 OCResource *resPtr = NULL;
1749 OCStackResult result;
1750 OCMethod method = OC_REST_NOMETHOD;
1751 uint32_t maxAge = 0;
1753 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
1754 #ifdef WITH_PRESENCE
1755 if(handle == presenceResource.handle)
1759 #endif // WITH_PRESENCE
1760 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
1762 // Verify that the resource exists
1763 resPtr = findResource ((OCResource *) handle);
1766 return OC_STACK_NO_RESOURCE;
1770 //only increment in the case of regular observing (not presence)
1771 incrementSequenceNumber(resPtr);
1772 method = OC_REST_OBSERVE;
1773 maxAge = MAX_OBSERVE_AGE;
1774 #ifdef WITH_PRESENCE
1775 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
1777 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
1784 OCNotifyListOfObservers (OCResourceHandle handle,
1785 OCObservationId *obsIdList,
1786 uint8_t numberOfIds,
1787 unsigned char *notificationJSONPayload,
1788 OCQualityOfService qos)
1790 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
1792 OCResource *resPtr = NULL;
1793 //TODO: we should allow the server to define this
1794 uint32_t maxAge = MAX_OBSERVE_AGE;
1796 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
1797 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
1798 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
1800 // Verify that the resource exists
1801 resPtr = findResource ((OCResource *) handle);
1802 if (NULL == resPtr || myStackMode == OC_CLIENT)
1804 return OC_STACK_NO_RESOURCE;
1808 incrementSequenceNumber(resPtr);
1810 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
1811 notificationJSONPayload, maxAge, qos));
1815 * Send a response to a request.
1816 * The response can be a regular, slow, or block (i.e. a response that
1817 * is too large to be sent in a single PDU and must span multiple transmissions)
1819 * @param response - pointer to structure that contains response parameters
1822 * OC_STACK_OK - No errors; Success
1823 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
1824 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
1825 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
1826 * persistent response buffer is necessary
1828 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
1830 OCStackResult result = OC_STACK_ERROR;
1831 OCServerRequest *serverRequest = NULL;
1833 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
1835 // Validate input parameters
1836 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
1837 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
1839 // TODO: Placeholder for creating a response entry when implementing
1840 // block transfer feature
1842 // If a response payload is present, check if block transfer is required
1843 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
1844 (const char *)ehResponse->payload, ehResponse->payloadSize))
1846 OC_LOG(INFO, TAG, PCF("Block transfer required"));
1848 // Persistent response buffer is needed for block transfer
1849 if (!ehResponse->persistentBufferFlag)
1851 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
1852 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
1854 // TODO: Placeholder for block transfer handling
1855 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
1856 // when implementing the block transfer feature
1862 // Get pointer to request info
1863 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
1866 result = serverRequest->ehResponseHandler(ehResponse);
1873 * Cancel a response. Applies to a block response
1875 * @param responseHandle - response handle set by stack in OCServerResponse after
1876 * OCDoResponse is called
1879 * OC_STACK_OK - No errors; Success
1880 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1882 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
1884 OCStackResult result = OC_STACK_NOTIMPL;
1886 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
1888 // TODO: validate response handle
1893 //-----------------------------------------------------------------------------
1894 // Private internal function definitions
1895 //-----------------------------------------------------------------------------
1897 * Generate handle of OCDoResource invocation for callback management.
1899 static OCDoHandle GenerateInvocationHandle()
1901 OCDoHandle handle = NULL;
1902 // Generate token here, it will be deleted when the transaction is deleted
1903 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
1906 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
1911 #ifdef WITH_PRESENCE
1912 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
1913 OCResourceProperty resourceProperties, uint8_t enable)
1915 if (resourceProperties
1916 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
1917 OC_LOG(ERROR, TAG, PCF("Invalid property"));
1918 return OC_STACK_INVALID_PARAM;
1922 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
1926 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
1933 * Initialize resource data structures, variables, etc.
1935 OCStackResult initResources() {
1936 OCStackResult result = OC_STACK_OK;
1937 // Init application resource vars
1938 headResource = NULL;
1939 // Init Virtual Resources
1940 #ifdef WITH_PRESENCE
1941 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
1942 //presenceResource.token = OCGenerateCoAPToken();
1943 result = OCCreateResource(&presenceResource.handle,
1944 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
1949 //make resource inactive
1950 result = OCChangeResourceProperty(
1951 &(((OCResource *) presenceResource.handle)->resourceProperties),
1958 * Add a resource to the end of the linked list of resources.
1960 * @param resource - resource to be added
1962 void insertResource(OCResource *resource) {
1963 OCResource *pointer;
1965 if (!headResource) {
1966 headResource = resource;
1968 pointer = headResource;
1970 while (pointer->next) {
1971 pointer = pointer->next;
1973 pointer->next = resource;
1975 resource->next = NULL;
1979 * Find a resource in the linked list of resources.
1981 * @param resource - resource to be found
1983 * NULL - resource not found
1984 * pointer to resource - pointer to resource that was found in the linked list
1986 OCResource *findResource(OCResource *resource) {
1987 OCResource *pointer = headResource;
1990 if (pointer == resource) {
1993 pointer = pointer->next;
1998 void deleteAllResources()
2000 OCResource *pointer = headResource;
2005 temp = pointer->next;
2006 #ifdef WITH_PRESENCE
2007 if(pointer != (OCResource *) presenceResource.handle)
2009 #endif // WITH_PRESENCE
2010 deleteResource(pointer);
2011 #ifdef WITH_PRESENCE
2013 #endif // WITH_PRESENCE
2017 #ifdef WITH_PRESENCE
2018 // Ensure that the last resource to be deleted is the presence resource. This allows for all
2019 // presence notification attributed to their deletion to be processed.
2020 deleteResource((OCResource *) presenceResource.handle);
2021 #endif // WITH_PRESENCE
2025 * Delete the resource from the linked list.
2027 * @param resource - resource to be deleted
2032 int deleteResource(OCResource *resource) {
2033 OCResource *prev = NULL;
2036 temp = headResource;
2038 if (temp == resource) {
2039 // Invalidate all Resource Properties.
2040 resource->resourceProperties = (OCResourceProperty) 0;
2041 #ifdef WITH_PRESENCE
2042 if(resource != (OCResource *) presenceResource.handle)
2044 #endif // WITH_PRESENCE
2045 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
2046 #ifdef WITH_PRESENCE
2049 if(presenceResource.handle)
2051 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2052 if(resource != (OCResource *) presenceResource.handle)
2054 SendPresenceNotification(resource->rsrcType);
2058 SendPresenceNotification(NULL);
2063 if (temp == headResource) {
2064 headResource = temp->next;
2066 prev->next = temp->next;
2069 deleteResourceElements(temp);
2082 * Delete all of the dynamically allocated elements that were created for the resource.
2084 * @param resource - specified resource
2086 void deleteResourceElements(OCResource *resource) {
2092 OCFree(resource->uri);
2094 // Delete resourcetype linked list
2095 deleteResourceType(resource->rsrcType);
2097 // Delete resourceinterface linked list
2098 deleteResourceInterface(resource->rsrcInterface);
2102 * Delete all of the dynamically allocated elements that were created for the resource type.
2104 * @param resourceType - specified resource type
2106 void deleteResourceType(OCResourceType *resourceType) {
2107 OCResourceType *pointer = resourceType;
2108 OCResourceType *next;
2111 next = pointer->next;
2112 OCFree(pointer->resourcetypename);
2119 * Delete all of the dynamically allocated elements that were created for the resource interface.
2121 * @param resourceInterface - specified resource interface
2123 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
2124 OCResourceInterface *pointer = resourceInterface;
2125 OCResourceInterface *next;
2128 next = pointer->next;
2129 OCFree(pointer->name);
2136 * Insert a resource type into a resource's resource type linked list.
2138 * @param resource - resource where resource type is to be inserted
2139 * @param resourceType - resource type to be inserted
2141 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
2142 OCResourceType *pointer;
2144 if (resource && !resource->rsrcType) {
2145 resource->rsrcType = resourceType;
2149 pointer = resource->rsrcType;
2153 pointer = resourceType;
2155 while (pointer->next) {
2156 pointer = pointer->next;
2158 pointer->next = resourceType;
2160 resourceType->next = NULL;
2164 * Get a resource type at the specified index within a resource.
2166 * @param handle - handle of resource
2167 * @param index - index of resource type
2170 * resourcetype - if found
2173 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
2174 OCResource *resource;
2175 OCResourceType *pointer;
2178 // Find the specified resource
2179 resource = findResource((OCResource *) handle);
2184 // Make sure a resource has a resourcetype
2185 if (!resource->rsrcType) {
2189 // Iterate through the list
2190 pointer = resource->rsrcType;
2192 while ((i < index) && pointer) {
2194 pointer = pointer->next;
2200 * Finds a resource type in an OCResourceType link-list.
2202 * @param resourceTypeList - the link-list to be searched through
2203 * @param resourceTypeName - the key to search for
2206 * resourceType that matches the key (ie. resourceTypeName)
2207 * NULL - either an invalid parameter or this function was unable to find the key.
2209 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
2211 if(resourceTypeList && resourceTypeName)
2213 OCResourceType * rtPointer = resourceTypeList;
2214 while(resourceTypeName && rtPointer)
2216 if(rtPointer->resourcetypename &&
2217 strcmp(resourceTypeName, (const char *)
2218 (rtPointer->resourcetypename)) == 0)
2222 rtPointer = rtPointer->next;
2229 * Insert a resource interface into a resource's resource interface linked list.
2231 * @param resource - resource where resource interface is to be inserted
2232 * @param resourceInterface - resource interface to be inserted
2234 void insertResourceInterface(OCResource *resource,
2235 OCResourceInterface *resourceInterface) {
2236 OCResourceInterface *pointer;
2238 if (!resource->rsrcInterface) {
2239 resource->rsrcInterface = resourceInterface;
2241 pointer = resource->rsrcInterface;
2242 while (pointer->next) {
2243 pointer = pointer->next;
2245 pointer->next = resourceInterface;
2247 resourceInterface->next = NULL;
2251 * Get a resource interface at the specified index within a resource.
2253 * @param handle - handle of resource
2254 * @param index - index of resource interface
2257 * resourceinterface - if found
2260 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
2262 OCResource *resource;
2263 OCResourceInterface *pointer;
2266 // Find the specified resource
2267 resource = findResource((OCResource *) handle);
2272 // Make sure a resource has a resourceinterface
2273 if (!resource->rsrcInterface) {
2277 // Iterate through the list
2278 pointer = resource->rsrcInterface;
2280 while ((i < index) && pointer) {
2282 pointer = pointer->next;
2288 * Determine if a request/response must be sent in a block transfer because it is too large to be
2289 * sent in a single PDU. This function can be used for either a request or a response
2291 * @param request - NULL or pointer to request
2292 * @param response - NULL or pointer to response
2293 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
2294 * the length of the request/response
2297 * 0 - packet transfer NOT required (i.e. normal request/response)
2298 * 1 - packet transfer required (i.e. block transfer needed)
2300 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
2304 // Determine if we are checking a request or a response
2307 // If size is greater than 0, use it for the request size value, otherwise
2308 // assume request is null terminated and use strlen for size value
2309 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
2316 // If size is greater than 0, use it for the response size value, otherwise
2317 // assume response is null terminated and use strlen for size value
2318 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
2327 * Retrieves a resource type based upon a uri string if the uri string contains only just one
2328 * resource attribute (and that has to be of type "rt").
2330 * @remark This API malloc's memory for the resource type and newURI. Do not malloc resourceType
2331 * or newURI before passing in.
2333 * @param uri - Valid URI for "requiredUri" parameter to OCDoResource API.
2334 * @param resourceType - The resource type to be populated; pass by reference.
2335 * @param newURI - Return URI without resourceType appended to the end of it. This is used to
2336 * ensure that the uri parameter is not modified; pass by reference.
2339 * OC_STACK_INVALID_URI - Returns this if the URI is invalid/NULL.
2340 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
2341 * OC_STACK_OK - Success
2343 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI)
2347 return OC_STACK_INVALID_URI;
2349 if(!resourceType || !newURI)
2351 return OC_STACK_INVALID_PARAM;
2353 char * leftToken = NULL;
2354 char * tempURI = (char *) OCMalloc(strlen(uri));
2359 strcpy(tempURI, uri);
2360 leftToken = strtok((char *)tempURI, "?");
2362 while(leftToken != NULL)
2364 if(strncmp(leftToken, "rt=", 3) == 0)
2366 *resourceType = (unsigned char *) OCMalloc(strlen(leftToken)-3);
2371 strcpy((char *)*resourceType, ((const char *)&leftToken[3]));
2374 leftToken = strtok(NULL, "?");
2382 return OC_STACK_NO_MEMORY;