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 "ocresource.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;
443 // Free memory dynamically allocated for resources
444 deleteAllResources();
446 // Make call to OCCoAP layer
447 if (OCStopCoAP() == OC_STACK_OK)
449 // Remove all observers
450 DeleteObserverList();
451 // Remove all the client callbacks
452 DeleteClientCBList();
453 stackState = OC_STACK_UNINITIALIZED;
454 result = OC_STACK_OK;
456 result = OC_STACK_ERROR;
459 // Deinit security blob
460 DeinitOCSecurityInfo();
462 if (result != OC_STACK_OK) {
463 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
470 * Verify the lengths of the URI and the query separately
472 * @param inputUri - Input URI and query.
473 * @param uriLen - The length of the initial URI with query.
475 * Note: The '?' that appears after the URI is not considered as
476 * a part of the query.
478 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
482 query = strchr (inputUri, '?');
486 if((query - inputUri) > MAX_URI_LENGTH)
488 return OC_STACK_INVALID_URI;
491 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
493 return OC_STACK_INVALID_QUERY;
496 else if(uriLen > MAX_URI_LENGTH)
498 return OC_STACK_INVALID_URI;
504 * Discover or Perform requests on a specified resource (specified by that Resource's respective URI).
506 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of calling this API.
507 * @param method - @ref OCMethod to perform on the resource
508 * @param requiredUri - URI of the resource to interact with
509 * @param referenceUri - URI of the reference resource
510 * @param request - JSON encoded request
511 * @param qos - quality of service
512 * @param cbData - struct that contains asynchronous callback function that is invoked
513 * by the stack when discovery or resource interaction is complete
514 * @param options - The address of an array containing the vendor specific header
515 * header options to be sent with the request
516 * @param numOptions - Number of vendor specific header options to be included
519 * OC_STACK_OK - no errors
520 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
521 * OC_STACK_INVALID_METHOD - invalid resource method
522 * OC_STACK_INVALID_URI - invalid required or reference URI
525 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
526 const char *referenceUri, const char *request,
527 OCQualityOfService qos, OCCallbackData *cbData,
528 OCHeaderOption * options, uint8_t numOptions)
530 OCStackResult result = OC_STACK_ERROR;
532 ClientCB *clientCB = NULL;
533 unsigned char * requestUri = NULL;
534 unsigned char * resourceType = NULL;
535 char * newURI = (char *)requiredUri;
538 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
540 // Validate input parameters
541 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
542 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
544 TODO ("Need to form the final query by concatenating require and reference URI's");
545 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
547 uint16_t uriLen = strlen(requiredUri);
549 // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS
556 case OC_REST_OBSERVE:
557 case OC_REST_OBSERVE_ALL:
558 case OC_REST_CANCEL_OBSERVE:
561 case OC_REST_PRESENCE:
565 result = OC_STACK_INVALID_METHOD;
569 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
574 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
576 result = OC_STACK_INVALID_PARAM;
581 if(method == OC_REST_PRESENCE)
583 result = getResourceType(requiredUri, &resourceType, &newURI);
584 if(result != OC_STACK_OK)
589 #endif // WITH_PRESENCE
591 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
594 memcpy(requestUri, newURI, (uriLen + 1));
598 result = OC_STACK_NO_MEMORY;
602 *handle = GenerateInvocationHandle();
605 result = OC_STACK_NO_MEMORY;
609 // Generate token which will be used by OCStack to match responses received
611 OCGenerateCoAPToken(&token);
613 if((result = AddClientCB(&clientCB, cbData, &token, *handle, method, requestUri, resourceType))
616 result = OC_STACK_NO_MEMORY;
620 // Make call to OCCoAP layer
621 result = OCDoCoAPResource(method, qos, &token, newURI, request, options, numOptions);
624 if(newURI != requiredUri)
628 if (result != OC_STACK_OK)
630 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
631 FindAndDeleteClientCB(clientCB);
637 * Cancel a request associated with a specific @ref OCDoResource invocation.
639 * @param handle - Used to identify a specific OCDoResource invocation.
640 * @param qos - used to specify Quality of Service (read below for more info)
641 * @param options- used to specify vendor specific header options when sending
642 * explicit observe cancellation
643 * @param numOptions- Number of header options to be included
646 * OC_STACK_OK - No errors; Success
647 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
649 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
650 uint8_t numOptions) {
652 * This ftn is implemented one of two ways in the case of observation:
654 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
655 * Remove the callback associated on client side.
656 * When the next notification comes in from server,
657 * reply with RESET message to server.
658 * Keep in mind that the server will react to RESET only
659 * if the last notification was sent ans CON
661 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
662 * and it is associated with an observe request
663 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
664 * Send CON Observe request to server with
665 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
666 * Remove the callback associated on client side.
668 OCStackResult ret = OC_STACK_OK;
671 return OC_STACK_INVALID_PARAM;
674 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
676 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
679 switch (clientCB->method)
681 case OC_REST_OBSERVE:
682 case OC_REST_OBSERVE_ALL:
683 if(qos == OC_HIGH_QOS)
685 ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
686 &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
691 FindAndDeleteClientCB(clientCB);
695 case OC_REST_PRESENCE:
696 FindAndDeleteClientCB(clientCB);
700 return OC_STACK_INVALID_METHOD;
706 OCStackResult OCProcessPresence()
708 OCStackResult result = OC_STACK_OK;
709 uint8_t ipAddr[4] = { 0 };
712 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
713 ClientCB* cbNode = NULL;
715 OCClientResponse clientResponse;
716 OCResponse * response = NULL;
718 LL_FOREACH(cbList, cbNode) {
719 if(OC_REST_PRESENCE == cbNode->method)
723 uint32_t now = GetTime(0);
724 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
725 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
728 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
733 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
734 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
735 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
738 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
740 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
741 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
743 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
745 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
746 (OCDevAddr *) &dst, 0, NULL);
747 if(result != OC_STACK_OK)
751 result = FormOCResponse(&response, cbNode, 0, &clientResponse);
752 if(result != OC_STACK_OK)
757 // Increment the TTLLevel (going to a next state), so we don't keep
758 // sending presence notification to client.
759 cbNode->presence->TTLlevel++;
760 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
761 cbNode->presence->TTLlevel);
765 result = OC_STACK_INVALID_IP;
768 HandleStackResponses(response);
770 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
772 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
774 OCGenerateCoAPToken(&token);
775 result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
776 &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
777 if(result != OC_STACK_OK)
781 cbNode->presence->TTLlevel++;
782 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
788 if (result != OC_STACK_OK)
790 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
797 * Called in main loop of OC client or server. Allows low-level processing of
801 * OC_STACK_OK - no errors
802 * OC_STACK_ERROR - stack process error
804 OCStackResult OCProcess() {
806 OC_LOG(INFO, TAG, PCF("Entering OCProcess"));
817 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
818 * presence notifications to clients via multicast. Once this API has been called with a success,
819 * clients may query for this server's presence and this server's stack will respond via multicast.
821 * Server can call this function when it comes online for the first time, or when it comes back
822 * online from offline mode, or when it re enters network.
824 * @param ttl - Time To Live in seconds
825 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
828 * OC_STACK_OK - No errors; Success
830 OCStackResult OCStartPresence(const uint32_t ttl)
832 OCChangeResourceProperty(
833 &(((OCResource *)presenceResource.handle)->resourceProperties),
838 presenceResource.presenceTTL = ttl;
841 if(OC_PRESENCE_UNINITIALIZED == presenceState)
843 OCDevAddr multiCastAddr;
846 presenceState = OC_PRESENCE_INITIALIZED;
847 OCGenerateCoAPToken(&token);
848 OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
849 //add the presence observer
850 AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
851 (OCResource *)presenceResource.handle, OC_LOW_QOS);
854 // Each time OCStartPresence is called
855 // a different random 32-bit integer number is used
856 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
858 return SendPresenceNotification(NULL);
862 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
863 * presence notifications to clients via multicast. Once this API has been called with a success,
864 * this server's stack will not respond to clients querying for this server's presence.
866 * Server can call this function when it is terminating, going offline, or when going
870 * OC_STACK_OK - No errors; Success
872 OCStackResult OCStopPresence()
874 OCStackResult result = OC_STACK_ERROR;
875 //make resource inactive
876 result = OCChangeResourceProperty(
877 &(((OCResource *) presenceResource.handle)->resourceProperties),
879 result = SendPresenceNotification(NULL);
886 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
888 defaultDeviceHandler = entityHandler;
896 * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource
897 * @param resourceTypeName - name of resource type. Example: "core.led"
898 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
899 * @param uri - URI of the resource. Example: "/a/led"
900 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
901 * NULL for default entity handler
902 * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE
905 * OC_STACK_OK - no errors
906 * OC_STACK_ERROR - stack process error
908 OCStackResult OCCreateResource(OCResourceHandle *handle,
909 const char *resourceTypeName,
910 const char *resourceInterfaceName,
911 const char *uri, OCEntityHandler entityHandler,
912 uint8_t resourceProperties) {
914 OCResource *pointer = NULL;
917 OCStackResult result = OC_STACK_ERROR;
919 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
921 if(myStackMode == OC_CLIENT)
925 // Validate parameters
926 // Is it presented during resource discovery?
927 if (!handle || !resourceTypeName || !uri) {
928 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
929 return OC_STACK_INVALID_PARAM;
932 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
933 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
936 // Make sure resourceProperties bitmask has allowed properties specified
937 if (resourceProperties
938 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
939 OC_LOG(ERROR, TAG, PCF("Invalid property"));
940 return OC_STACK_INVALID_PARAM;
943 // If the headResource is NULL, then no resources have been created...
944 pointer = headResource;
946 // At least one resources is in the resource list, so we need to search for
947 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
949 if (strcmp(uri, pointer->uri) == 0) {
950 OC_LOG(ERROR, TAG, PCF("URI already in use"));
951 return OC_STACK_INVALID_PARAM;
953 pointer = pointer->next;
956 // Create the pointer and insert it into the resource list
957 pointer = (OCResource *) OCMalloc(sizeof(OCResource));
961 memset(pointer, 0, sizeof(OCResource));
962 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
964 insertResource(pointer);
967 size = strlen(uri) + 1;
968 str = (char *) OCMalloc(size);
972 strncpy(str, uri, size);
975 // Set properties. Set OC_ACTIVE
976 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
979 // Add the resourcetype to the resource
980 result = BindResourceTypeToResource(pointer, resourceTypeName);
981 if (result != OC_STACK_OK) {
982 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
986 // Add the resourceinterface to the resource
987 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
988 if (result != OC_STACK_OK) {
989 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
993 // If an entity handler has been passed, attach it to the newly created
994 // resource. Otherwise, set the default entity handler.
997 pointer->entityHandler = entityHandler;
1001 pointer->entityHandler = defaultResourceEHandler;
1005 result = OC_STACK_OK;
1007 #ifdef WITH_PRESENCE
1008 if(presenceResource.handle)
1010 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1011 SendPresenceNotification(pointer->rsrcType);
1015 if (result != OC_STACK_OK)
1017 // Deep delete of resource and other dynamic elements that it contains
1018 deleteResource(pointer);
1027 * Create a resource. with host ip address for remote resource
1029 * @param handle - pointer to handle to newly created resource. Set by ocstack.
1030 * Used to refer to resource
1031 * @param resourceTypeName - name of resource type. Example: "core.led"
1032 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1033 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
1034 * @param uri - URI of the resource. Example: "/a/led"
1035 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1036 * NULL for default entity handler
1037 * @param resourceProperties - properties supported by resource.
1038 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
1041 * OC_STACK_OK - no errors
1042 * OC_STACK_ERROR - stack process error
1045 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
1046 const char *resourceTypeName,
1047 const char *resourceInterfaceName,
1050 OCEntityHandler entityHandler,
1051 uint8_t resourceProperties)
1055 OCStackResult result = OC_STACK_ERROR;
1057 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
1058 uri, entityHandler, resourceProperties);
1060 if (result != OC_STACK_ERROR)
1063 size = strlen(host) + 1;
1064 str = (char *) OCMalloc(size);
1067 return OC_STACK_ERROR;
1069 strncpy(str, host, size);
1070 ((OCResource *) *handle)->host = str;
1077 * Add a resource to a collection resource.
1079 * @param collectionHandle - handle to the collection resource
1080 * @param resourceHandle - handle to resource to be added to the collection resource
1083 * OC_STACK_OK - no errors
1084 * OC_STACK_ERROR - stack process error
1085 * OC_STACK_INVALID_PARAM - invalid collectionhandle
1087 OCStackResult OCBindResource(
1088 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1089 OCResource *resource;
1092 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
1094 // Validate parameters
1095 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1096 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1097 // Container cannot contain itself
1098 if (collectionHandle == resourceHandle) {
1099 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
1100 return OC_STACK_INVALID_PARAM;
1103 // Use the handle to find the resource in the resource linked list
1104 resource = findResource((OCResource *) collectionHandle);
1106 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1107 return OC_STACK_INVALID_PARAM;
1110 // Look for an open slot to add add the child resource.
1111 // If found, add it and return success
1112 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1113 if (!resource->rsrcResources[i]) {
1114 resource->rsrcResources[i] = (OCResource *) resourceHandle;
1115 OC_LOG(INFO, TAG, PCF("resource bound"));
1120 #ifdef WITH_PRESENCE
1121 if(presenceResource.handle)
1123 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1124 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1128 // Unable to add resourceHandle, so return error
1129 return OC_STACK_ERROR;
1133 * Remove a resource from a collection resource.
1135 * @param collectionHandle - handle to the collection resource
1136 * @param resourceHandle - handle to resource to be added to the collection resource
1139 * OC_STACK_OK - no errors
1140 * OC_STACK_ERROR - stack process error
1141 * OC_STACK_INVALID_PARAM - invalid collectionHandle
1143 OCStackResult OCUnBindResource(
1144 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1145 OCResource *resource;
1148 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
1150 // Validate parameters
1151 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1152 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1153 // Container cannot contain itself
1154 if (collectionHandle == resourceHandle) {
1155 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
1156 return OC_STACK_INVALID_PARAM;
1159 // Use the handle to find the resource in the resource linked list
1160 resource = findResource((OCResource *) collectionHandle);
1162 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1163 return OC_STACK_INVALID_PARAM;
1166 // Look for an open slot to add add the child resource.
1167 // If found, add it and return success
1168 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1169 if (resourceHandle == resource->rsrcResources[i]) {
1170 resource->rsrcResources[i] = (OCResource *) NULL;
1171 OC_LOG(INFO, TAG, PCF("resource unbound"));
1176 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
1178 #ifdef WITH_PRESENCE
1179 if(presenceResource.handle)
1181 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1182 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1186 // Unable to add resourceHandle, so return error
1187 return OC_STACK_ERROR;
1190 OCStackResult BindResourceTypeToResource(OCResource* resource,
1191 const char *resourceTypeName)
1193 OCResourceType *pointer = NULL;
1196 OCStackResult result = OC_STACK_ERROR;
1198 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
1200 // Validate parameters
1201 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
1202 // TODO: Does resource attribute resentation really have to be maintained in stack?
1203 // Is it presented during resource discovery?
1205 TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
1207 // Create the resourcetype and insert it into the resource list
1208 pointer = (OCResourceType *) OCMalloc(sizeof(OCResourceType));
1212 memset(pointer, 0, sizeof(OCResourceType));
1214 // Set the resourceTypeName
1215 size = strlen(resourceTypeName) + 1;
1216 str = (char *) OCMalloc(size);
1220 strncpy(str, resourceTypeName, size);
1221 pointer->resourcetypename = str;
1223 insertResourceType(resource, pointer);
1224 result = OC_STACK_OK;
1226 exit: if (result != OC_STACK_OK) {
1234 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
1235 const char *resourceInterfaceName)
1237 OCResourceInterface *pointer = NULL;
1240 OCStackResult result = OC_STACK_ERROR;
1242 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
1244 // Validate parameters
1245 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
1247 TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
1249 // Create the resourceinterface and insert it into the resource list
1250 pointer = (OCResourceInterface *) OCMalloc(sizeof(OCResourceInterface));
1254 memset(pointer, 0, sizeof(OCResourceInterface));
1256 // Set the resourceinterface name
1257 size = strlen(resourceInterfaceName) + 1;
1258 str = (char *) OCMalloc(size);
1262 strncpy(str, resourceInterfaceName, size);
1263 pointer->name = str;
1265 // Bind the resourceinterface to the resource
1266 insertResourceInterface(resource, pointer);
1268 result = OC_STACK_OK;
1270 exit: if (result != OC_STACK_OK) {
1279 * Bind a resourcetype to a resource.
1281 * @param handle - handle to the resource
1282 * @param resourceTypeName - name of resource type. Example: "core.led"
1285 * OC_STACK_OK - no errors
1286 * OC_STACK_ERROR - stack process error
1288 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
1289 const char *resourceTypeName) {
1291 OCStackResult result = OC_STACK_ERROR;
1292 OCResource *resource;
1294 // Make sure resource exists
1295 resource = findResource((OCResource *) handle);
1297 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1298 return OC_STACK_ERROR;
1301 // call internal function
1302 result = BindResourceTypeToResource(resource, resourceTypeName);
1304 #ifdef WITH_PRESENCE
1305 if(presenceResource.handle)
1307 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1308 SendPresenceNotification(resource->rsrcType);
1316 * Bind a resourceinterface to a resource.
1318 * @param handle - handle to the resource
1319 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
1322 * OC_STACK_OK - no errors
1323 * OC_STACK_ERROR - stack process error
1326 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
1327 const char *resourceInterfaceName) {
1329 OCStackResult result = OC_STACK_ERROR;
1330 OCResource *resource;
1332 // Make sure resource exists
1333 resource = findResource((OCResource *) handle);
1335 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1336 return OC_STACK_ERROR;
1339 // call internal function
1340 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
1342 #ifdef WITH_PRESENCE
1343 if(presenceResource.handle)
1345 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1346 SendPresenceNotification(resource->rsrcType);
1354 * Get the number of resources that have been created in the stack.
1356 * @param numResources - pointer to count variable
1359 * OC_STACK_OK - no errors
1360 * OC_STACK_ERROR - stack process error
1363 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
1364 OCResource *pointer = headResource;
1366 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
1367 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
1370 *numResources = *numResources + 1;
1371 pointer = pointer->next;
1377 * Get a resource handle by index.
1379 * @param index - index of resource, 0 to Count - 1
1382 * Resource handle - if found
1383 * NULL - if not found
1385 OCResourceHandle OCGetResourceHandle(uint8_t index) {
1386 OCResource *pointer = headResource;
1389 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
1391 // Iterate through the list
1392 while ((i < index) && pointer) {
1394 pointer = pointer->next;
1396 return (OCResourceHandle) pointer;
1400 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
1403 * @param handle - handle of resource to be deleted
1406 * OC_STACK_OK - no errors
1407 * OC_STACK_ERROR - stack process error
1408 * OC_STACK_NO_RESOURCE - resource not found
1409 * OC_STACK_INVALID_PARAM - invalid param
1411 OCStackResult OCDeleteResource(OCResourceHandle handle) {
1412 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
1415 OC_LOG(ERROR, TAG, PCF("Invalid param"));
1416 return OC_STACK_INVALID_PARAM;
1419 OCResource *resource = findResource((OCResource *) handle);
1420 if (resource == NULL) {
1421 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1422 return OC_STACK_NO_RESOURCE;
1425 if (deleteResource((OCResource *) handle) == 0) {
1426 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
1427 return OC_STACK_ERROR;
1434 * Get the URI of the resource specified by handle.
1436 * @param handle - handle of resource
1438 * URI string - if resource found
1439 * NULL - resource not found
1441 const char *OCGetResourceUri(OCResourceHandle handle) {
1442 OCResource *resource;
1443 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
1445 resource = findResource((OCResource *) handle);
1447 return resource->uri;
1449 return (const char *) NULL;
1453 * Get the properties of the resource specified by handle.
1454 * NOTE: that after a resource is created, the OC_ACTIVE property is set
1455 * for the resource by the stack.
1457 * @param handle - handle of resource
1459 * property bitmap - if resource found
1460 * NULL - resource not found
1462 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
1463 OCResource *resource;
1464 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
1466 resource = findResource((OCResource *) handle);
1468 return resource->resourceProperties;
1474 * Get the number of resource types of the resource.
1476 * @param handle - handle of resource
1477 * @param numResourceTypes - pointer to count variable
1480 * OC_STACK_OK - no errors
1481 * OC_STACK_ERROR - stack process error
1483 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
1484 uint8_t *numResourceTypes) {
1485 OCResource *resource;
1486 OCResourceType *pointer;
1488 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
1489 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
1490 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
1492 *numResourceTypes = 0;
1494 resource = findResource((OCResource *) handle);
1496 pointer = resource->rsrcType;
1498 *numResourceTypes = *numResourceTypes + 1;
1499 pointer = pointer->next;
1506 * Get name of resource type of the resource.
1508 * @param handle - handle of resource
1509 * @param index - index of resource, 0 to Count - 1
1512 * resource type name - if resource found
1513 * NULL - resource not found
1515 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
1516 OCResourceType *resourceType;
1518 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
1520 resourceType = findResourceTypeAtIndex(handle, index);
1522 return resourceType->resourcetypename;
1524 return (const char *) NULL;
1530 * Get the number of resource interfaces of the resource.
1532 * @param handle - handle of resource
1533 * @param numResources - pointer to count variable
1536 * OC_STACK_OK - no errors
1537 * OC_STACK_ERROR - stack process error
1539 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
1540 uint8_t *numResourceInterfaces) {
1541 OCResourceInterface *pointer;
1542 OCResource *resource;
1544 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
1546 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
1547 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
1549 *numResourceInterfaces = 0;
1550 resource = findResource((OCResource *) handle);
1552 pointer = resource->rsrcInterface;
1554 *numResourceInterfaces = *numResourceInterfaces + 1;
1555 pointer = pointer->next;
1562 * Get name of resource interface of the resource.
1564 * @param handle - handle of resource
1565 * @param index - index of resource, 0 to Count - 1
1568 * resource interface name - if resource found
1569 * NULL - resource not found
1571 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
1572 OCResourceInterface *resourceInterface;
1574 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
1576 resourceInterface = findResourceInterfaceAtIndex(handle, index);
1577 if (resourceInterface) {
1578 return resourceInterface->name;
1580 return (const char *) NULL;
1584 * Get resource handle from the collection resource by index.
1586 * @param collectionHandle - handle of collection resource
1587 * @param index - index of contained resource, 0 to Count - 1
1590 * handle to resource - if resource found
1591 * NULL - resource not found
1593 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
1595 OCResource *resource;
1597 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
1599 if (index >= MAX_CONTAINED_RESOURCES) {
1603 resource = findResource((OCResource *) collectionHandle);
1608 return resource->rsrcResources[index];
1612 * Bind an entity handler to the resource.
1614 * @param handle - handle to the resource that the contained resource is to be bound
1615 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1617 * OC_STACK_OK - no errors
1618 * OC_STACK_ERROR - stack process error
1620 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
1621 OCEntityHandler entityHandler) {
1622 OCResource *resource;
1624 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
1626 // Validate parameters
1627 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
1628 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
1630 // Use the handle to find the resource in the resource linked list
1631 resource = findResource((OCResource *)handle);
1633 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1634 return OC_STACK_ERROR;
1638 resource->entityHandler = entityHandler;
1640 #ifdef WITH_PRESENCE
1641 if(presenceResource.handle)
1643 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1644 SendPresenceNotification(resource->rsrcType);
1652 * Get the entity handler for a resource.
1654 * @param handle - handle of resource
1657 * entity handler - if resource found
1658 * NULL - resource not found
1660 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
1661 OCResource *resource;
1663 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
1665 // Use the handle to find the resource in the resource linked list
1666 resource = findResource((OCResource *)handle);
1668 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1673 return resource->entityHandler;
1676 void incrementSequenceNumber(OCResource * resPtr)
1678 // Increment the sequence number
1679 resPtr->sequenceNum += 1;
1680 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
1682 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
1687 #ifdef WITH_PRESENCE
1689 * Notify Presence subscribers that a resource has been modified
1691 * @param resourceType - Handle to the resourceType linked list of resource
1692 * that was modified.
1693 * @param qos - Quality Of Service
1696 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
1698 OCResource *resPtr = NULL;
1699 OCStackResult result;
1700 OCMethod method = OC_REST_PRESENCE;
1701 uint32_t maxAge = 0;
1702 resPtr = findResource((OCResource *) presenceResource.handle);
1705 return OC_STACK_NO_RESOURCE;
1707 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
1709 maxAge = presenceResource.presenceTTL;
1716 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
1722 * Notify observers that an observed value has changed.
1724 * @param handle - handle of resource
1727 * OC_STACK_OK - no errors
1728 * OC_STACK_NO_RESOURCE - invalid resource handle
1729 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
1731 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
1733 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
1735 OCResource *resPtr = NULL;
1736 OCStackResult result;
1737 OCMethod method = OC_REST_NOMETHOD;
1738 uint32_t maxAge = 0;
1740 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
1741 // Verify that the resource exists
1742 resPtr = findResource ((OCResource *) handle);
1743 if (NULL == resPtr || myStackMode == OC_CLIENT)
1745 return OC_STACK_NO_RESOURCE;
1749 //only increment in the case of regular observing (not presence)
1750 incrementSequenceNumber(resPtr);
1751 method = OC_REST_OBSERVE;
1752 maxAge = MAX_OBSERVE_AGE;
1753 #ifdef WITH_PRESENCE
1754 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
1756 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
1763 OCNotifyListOfObservers (OCResourceHandle handle,
1764 OCObservationId *obsIdList,
1765 uint8_t numberOfIds,
1766 unsigned char *notificationJSONPayload,
1767 OCQualityOfService qos)
1769 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
1771 OCResource *resPtr = NULL;
1772 //TODO: we should allow the server to define this
1773 uint32_t maxAge = MAX_OBSERVE_AGE;
1775 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
1776 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
1777 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
1779 // Verify that the resource exists
1780 resPtr = findResource ((OCResource *) handle);
1781 if (NULL == resPtr || myStackMode == OC_CLIENT)
1783 return OC_STACK_NO_RESOURCE;
1787 incrementSequenceNumber(resPtr);
1789 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
1790 notificationJSONPayload, maxAge, qos));
1794 * Send a response to a request.
1795 * The response can be a regular, slow, or block (i.e. a response that
1796 * is too large to be sent in a single PDU and must span multiple transmissions)
1798 * @param response - pointer to structure that contains response parameters
1801 * OC_STACK_OK - No errors; Success
1802 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
1803 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
1804 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
1805 * persistent response buffer is necessary
1807 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
1809 OCStackResult result = OC_STACK_ERROR;
1810 OCServerRequest *serverRequest = NULL;
1812 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
1814 // Validate input parameters
1815 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
1816 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
1818 // TODO: Placeholder for creating a response entry when implementing
1819 // block transfer feature
1821 // If a response payload is present, check if block transfer is required
1822 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
1823 (const char *)ehResponse->payload, ehResponse->payloadSize))
1825 OC_LOG(INFO, TAG, PCF("Block transfer required"));
1827 // Persistent response buffer is needed for block transfer
1828 if (!ehResponse->persistentBufferFlag)
1830 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
1831 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
1833 // TODO: Placeholder for block transfer handling
1834 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
1835 // when implementing the block transfer feature
1841 // Get pointer to request info
1842 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
1845 result = serverRequest->ehResponseHandler(ehResponse);
1852 * Cancel a response. Applies to a block response
1854 * @param responseHandle - response handle set by stack in OCServerResponse after
1855 * OCDoResponse is called
1858 * OC_STACK_OK - No errors; Success
1859 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1861 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
1863 OCStackResult result = OC_STACK_NOTIMPL;
1865 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
1867 // TODO: validate response handle
1872 //-----------------------------------------------------------------------------
1873 // Private internal function definitions
1874 //-----------------------------------------------------------------------------
1876 * Generate handle of OCDoResource invocation for callback management.
1878 static OCDoHandle GenerateInvocationHandle()
1880 OCDoHandle handle = NULL;
1881 // Generate token here, it will be deleted when the transaction is deleted
1882 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
1885 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
1890 #ifdef WITH_PRESENCE
1891 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
1892 OCResourceProperty resourceProperties, uint8_t enable)
1894 if (resourceProperties
1895 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
1896 OC_LOG(ERROR, TAG, PCF("Invalid property"));
1897 return OC_STACK_INVALID_PARAM;
1901 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
1905 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
1912 * Initialize resource data structures, variables, etc.
1914 OCStackResult initResources() {
1915 OCStackResult result = OC_STACK_OK;
1916 // Init application resource vars
1917 headResource = NULL;
1918 // Init Virtual Resources
1919 #ifdef WITH_PRESENCE
1920 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
1921 //presenceResource.token = OCGenerateCoAPToken();
1922 result = OCCreateResource(&presenceResource.handle,
1928 //make resource inactive
1929 result = OCChangeResourceProperty(
1930 &(((OCResource *) presenceResource.handle)->resourceProperties),
1937 * Add a resource to the end of the linked list of resources.
1939 * @param resource - resource to be added
1941 void insertResource(OCResource *resource) {
1942 OCResource *pointer;
1944 if (!headResource) {
1945 headResource = resource;
1947 pointer = headResource;
1949 while (pointer->next) {
1950 pointer = pointer->next;
1952 pointer->next = resource;
1954 resource->next = NULL;
1958 * Find a resource in the linked list of resources.
1960 * @param resource - resource to be found
1962 * NULL - resource not found
1963 * pointer to resource - pointer to resource that was found in the linked list
1965 OCResource *findResource(OCResource *resource) {
1966 OCResource *pointer = headResource;
1969 if (pointer == resource) {
1972 pointer = pointer->next;
1977 void deleteAllResources()
1979 OCResource *pointer = headResource;
1984 temp = pointer->next;
1985 deleteResource(pointer);
1991 * Delete the resource from the linked list.
1993 * @param resource - resource to be deleted
1998 int deleteResource(OCResource *resource) {
1999 OCResource *prev = NULL;
2002 temp = headResource;
2004 if (temp == resource) {
2005 // Invalidate all Resource Properties.
2006 resource->resourceProperties = (OCResourceProperty) 0;
2007 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
2009 #ifdef WITH_PRESENCE
2010 if(presenceResource.handle)
2012 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2013 SendPresenceNotification(resource->rsrcType);
2017 if (temp == headResource) {
2018 headResource = temp->next;
2020 prev->next = temp->next;
2023 deleteResourceElements(temp);
2036 * Delete all of the dynamically allocated elements that were created for the resource.
2038 * @param resource - specified resource
2040 void deleteResourceElements(OCResource *resource) {
2046 OCFree(resource->uri);
2048 // Delete resourcetype linked list
2049 deleteResourceType(resource->rsrcType);
2051 // Delete resourceinterface linked list
2052 deleteResourceInterface(resource->rsrcInterface);
2056 * Delete all of the dynamically allocated elements that were created for the resource type.
2058 * @param resourceType - specified resource type
2060 void deleteResourceType(OCResourceType *resourceType) {
2061 OCResourceType *pointer = resourceType;
2062 OCResourceType *next;
2065 next = pointer->next;
2066 OCFree(pointer->resourcetypename);
2073 * Delete all of the dynamically allocated elements that were created for the resource interface.
2075 * @param resourceInterface - specified resource interface
2077 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
2078 OCResourceInterface *pointer = resourceInterface;
2079 OCResourceInterface *next;
2082 next = pointer->next;
2083 OCFree(pointer->name);
2090 * Insert a resource type into a resource's resource type linked list.
2092 * @param resource - resource where resource type is to be inserted
2093 * @param resourceType - resource type to be inserted
2095 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
2096 OCResourceType *pointer;
2098 if (resource && !resource->rsrcType) {
2099 resource->rsrcType = resourceType;
2103 pointer = resource->rsrcType;
2107 pointer = resourceType;
2109 while (pointer->next) {
2110 pointer = pointer->next;
2112 pointer->next = resourceType;
2114 resourceType->next = NULL;
2118 * Get a resource type at the specified index within a resource.
2120 * @param handle - handle of resource
2121 * @param index - index of resource type
2124 * resourcetype - if found
2127 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
2128 OCResource *resource;
2129 OCResourceType *pointer;
2132 // Find the specified resource
2133 resource = findResource((OCResource *) handle);
2138 // Make sure a resource has a resourcetype
2139 if (!resource->rsrcType) {
2143 // Iterate through the list
2144 pointer = resource->rsrcType;
2146 while ((i < index) && pointer) {
2148 pointer = pointer->next;
2154 * Insert a resource interface into a resource's resource interface linked list.
2156 * @param resource - resource where resource interface is to be inserted
2157 * @param resourceInterface - resource interface to be inserted
2159 void insertResourceInterface(OCResource *resource,
2160 OCResourceInterface *resourceInterface) {
2161 OCResourceInterface *pointer;
2163 if (!resource->rsrcInterface) {
2164 resource->rsrcInterface = resourceInterface;
2166 pointer = resource->rsrcInterface;
2167 while (pointer->next) {
2168 pointer = pointer->next;
2170 pointer->next = resourceInterface;
2172 resourceInterface->next = NULL;
2176 * Get a resource interface at the specified index within a resource.
2178 * @param handle - handle of resource
2179 * @param index - index of resource interface
2182 * resourceinterface - if found
2185 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
2187 OCResource *resource;
2188 OCResourceInterface *pointer;
2191 // Find the specified resource
2192 resource = findResource((OCResource *) handle);
2197 // Make sure a resource has a resourceinterface
2198 if (!resource->rsrcInterface) {
2202 // Iterate through the list
2203 pointer = resource->rsrcInterface;
2205 while ((i < index) && pointer) {
2207 pointer = pointer->next;
2213 * Determine if a request/response must be sent in a block transfer because it is too large to be
2214 * sent in a single PDU. This function can be used for either a request or a response
2216 * @param request - NULL or pointer to request
2217 * @param response - NULL or pointer to response
2218 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
2219 * the length of the request/response
2222 * 0 - packet transfer NOT required (i.e. normal request/response)
2223 * 1 - packet transfer required (i.e. block transfer needed)
2225 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
2229 // Determine if we are checking a request or a response
2232 // If size is greater than 0, use it for the request size value, otherwise
2233 // assume request is null terminated and use strlen for size value
2234 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
2241 // If size is greater than 0, use it for the response size value, otherwise
2242 // assume response is null terminated and use strlen for size value
2243 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
2252 * Retrieves a resource type based upon a uri string if the uri string contains only just one
2253 * resource attribute (and that has to be of type "rt").
2255 * @remark This API malloc's memory for the resource type and newURI. Do not malloc resourceType
2256 * or newURI before passing in.
2258 * @param uri - Valid URI for "requiredUri" parameter to OCDoResource API.
2259 * @param resourceType - The resource type to be populated; pass by reference.
2260 * @param newURI - Return URI without resourceType appended to the end of it. This is used to
2261 * ensure that the uri parameter is not modified; pass by reference.
2264 * OC_STACK_INVALID_URI - Returns this if the URI is invalid/NULL.
2265 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
2266 * OC_STACK_OK - Success
2268 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI)
2272 return OC_STACK_INVALID_URI;
2274 if(!resourceType || !newURI)
2276 return OC_STACK_INVALID_PARAM;
2279 char * leftToken = NULL;
2280 char * tempURI = (char *) OCMalloc(strlen(uri));
2286 strcpy(tempURI, uri);
2287 leftToken = strtok((char *)tempURI, "?");
2289 while(leftToken != NULL)
2291 if(strncmp(leftToken, "rt=", 3) == 0)
2293 *resourceType = (unsigned char *) OCMalloc(strlen(leftToken)-3);
2298 strcpy((char *)*resourceType, ((const char *)&leftToken[3]));
2301 leftToken = strtok(NULL, "?");
2309 return OC_STACK_NO_MEMORY;