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 //-----------------------------------------------------------------------------
75 // Internal API function
76 //-----------------------------------------------------------------------------
78 // This internal function is called to update the stack with the status of
79 // observers and communication failures
80 OCStackResult OCStackFeedBack(OCCoAPToken * token, uint8_t status)
82 OCStackResult result = OC_STACK_ERROR;
83 ResourceObserver * observer = NULL;
84 OCEntityHandlerRequest ehRequest;
85 memset(&ehRequest, 0, sizeof(OCEntityHandlerRequest));
89 case OC_OBSERVER_NOT_INTERESTED:
90 OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
91 observer = GetObserverUsingToken (token);
94 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
95 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
96 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
97 if(result != OC_STACK_OK)
101 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
103 //observer is not observing anymore
104 result = DeleteObserverUsingToken (token);
105 if(result == OC_STACK_OK)
107 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
111 result = OC_STACK_OK;
112 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
115 case OC_OBSERVER_STILL_INTERESTED:
116 //observer is still interested
117 OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
118 notifications, reset the failedCount"));
119 observer = GetObserverUsingToken(token);
122 observer->forceHighQos = 0;
123 observer->failedCommCount = 0;
124 result = OC_STACK_OK;
128 result = OC_STACK_OBSERVER_NOT_FOUND;
131 case OC_OBSERVER_FAILED_COMM:
132 //observer is not reachable
133 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
134 observer = GetObserverUsingToken(token);
137 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
139 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
140 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
141 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
142 if(result != OC_STACK_OK)
144 return OC_STACK_ERROR;
146 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
147 //observer is unreachable
148 result = DeleteObserverUsingToken (token);
149 if(result == OC_STACK_OK)
151 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
155 result = OC_STACK_OK;
156 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
161 observer->failedCommCount++;
162 result = OC_STACK_CONTINUE;
164 observer->forceHighQos = 1;
165 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
169 OC_LOG(ERROR, TAG, PCF("Unknown status"));
170 result = OC_STACK_ERROR;
176 //This function will be called back by occoap layer when a request is received
177 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
179 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
181 OCStackResult result = OC_STACK_ERROR;
182 ResourceHandling resHandling;
183 OCResource *resource;
185 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
188 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
189 result = AddServerRequest(&request, protocolRequest->coapID,
190 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
191 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
192 protocolRequest->observationOption, protocolRequest->qos,
193 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
194 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
195 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
196 protocolRequest->reqTotalSize);
197 if (OC_STACK_OK != result)
199 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
202 VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
204 if(!protocolRequest->reqMorePacket)
206 request->requestComplete = 1;
211 OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
214 if(request->requestComplete)
216 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
217 result = DetermineResourceHandling (request, &resHandling, &resource);
218 if (result == OC_STACK_OK)
220 result = ProcessRequest(resHandling, resource, request);
224 result = OC_STACK_ERROR;
229 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
230 result = OC_STACK_CONTINUE;
235 //This function will be called back by occoap layer when a response is received
236 void HandleStackResponses(OCResponse * response)
238 OCStackApplicationResult result = OC_STACK_DELETE_TRANSACTION;
239 OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)"));
241 if (response->cbNode)
243 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
244 result = response->cbNode->callBack(response->cbNode->context,
245 response->cbNode->handle, response->clientResponse);
246 if (result == OC_STACK_DELETE_TRANSACTION ||
247 response->clientResponse->result == OC_STACK_COMM_ERROR ||
248 response->clientResponse->result == OC_STACK_RESOURCE_DELETED)
250 FindAndDeleteClientCB(response->cbNode);
255 int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
258 unsigned char *itr, *coap;
259 uint8_t dotCount = 0;
263 /* search for scheme */
265 if (!isdigit((unsigned char) *ipAddrStr))
267 coap = (unsigned char *) OC_COAP_SCHEME;
268 while (*coap && tolower(*itr) == *coap)
277 if (isdigit((unsigned char) *ipAddrStr))
280 ipAddr[index] += *ipAddrStr - '0';
282 else if ((unsigned char) *ipAddrStr == '.')
294 if(*ipAddrStr == ':')
298 if (isdigit((unsigned char) *ipAddrStr))
301 *port += *ipAddrStr - '0';
312 if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
323 //-----------------------------------------------------------------------------
324 // Private internal function prototypes
325 //-----------------------------------------------------------------------------
327 static OCDoHandle GenerateInvocationHandle();
328 static OCStackResult initResources();
329 static void insertResource(OCResource *resource);
330 static OCResource *findResource(OCResource *resource);
331 static void insertResourceType(OCResource *resource,
332 OCResourceType *resourceType);
333 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
335 static void insertResourceInterface(OCResource *resource,
336 OCResourceInterface *resourceInterface);
337 static OCResourceInterface *findResourceInterfaceAtIndex(
338 OCResourceHandle handle, uint8_t index);
339 static void deleteResourceType(OCResourceType *resourceType);
340 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
341 static void deleteResourceElements(OCResource *resource);
342 static int deleteResource(OCResource *resource);
343 static void deleteAllResources();
344 static void incrementSequenceNumber(OCResource * resPtr);
345 static OCStackResult verifyUriQueryLength(const char * inputUri,
347 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
348 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI);
350 //-----------------------------------------------------------------------------
352 //-----------------------------------------------------------------------------
355 * Initialize the OC Stack. Must be called prior to starting the stack.
358 * IP Address of host device
360 * Port of host device
362 * Host device is client, server, or client-server
365 * OC_STACK_OK - no errors
366 * OC_STACK_ERROR - stack init error
368 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
370 OCStackResult result = OC_STACK_ERROR;
371 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
375 OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
381 OC_LOG(INFO, TAG, PCF("Client mode"));
384 OC_LOG(INFO, TAG, PCF("Server mode"));
386 case OC_CLIENT_SERVER:
387 OC_LOG(INFO, TAG, PCF("Client-server mode"));
390 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
391 return OC_STACK_ERROR;
396 defaultDeviceHandler = NULL;
399 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
400 #endif // WITH_PRESENCE
402 // Make call to OCCoAP layer
403 result = OCInitCoAP(ipAddr, (uint16_t) port, myStackMode);
404 if (result == OC_STACK_OK)
406 stackState = OC_STACK_INITIALIZED;
408 // Initialize resource
409 if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
411 result = initResources();
413 if(result != OC_STACK_OK)
415 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
421 * Stop the OC stack. Use for a controlled shutdown.
423 * OC_STACK_OK - no errors
424 * OC_STACK_ERROR - stack not initialized
426 OCStackResult OCStop()
428 OCStackResult result = OC_STACK_ERROR;
430 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
432 if (stackState != OC_STACK_INITIALIZED)
434 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
435 return OC_STACK_ERROR;
438 // Free memory dynamically allocated for resources
439 deleteAllResources();
441 // Make call to OCCoAP layer
442 if (OCStopCoAP() == OC_STACK_OK)
444 // Remove all observers
445 DeleteObserverList();
446 // Remove all the client callbacks
447 DeleteClientCBList();
448 stackState = OC_STACK_UNINITIALIZED;
449 result = OC_STACK_OK;
451 result = OC_STACK_ERROR;
454 if (result != OC_STACK_OK) {
455 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
462 * Verify the lengths of the URI and the query separately
464 * @param inputUri - Input URI and query.
465 * @param uriLen - The length of the initial URI with query.
467 * Note: The '?' that appears after the URI is not considered as
468 * a part of the query.
470 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
474 query = strchr (inputUri, '?');
478 if((query - inputUri) > MAX_URI_LENGTH)
480 return OC_STACK_INVALID_URI;
483 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
485 return OC_STACK_INVALID_QUERY;
488 else if(uriLen > MAX_URI_LENGTH)
490 return OC_STACK_INVALID_URI;
496 * Discover or Perform requests on a specified resource (specified by that Resource's respective URI).
498 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of calling this API.
499 * @param method - @ref OCMethod to perform on the resource
500 * @param requiredUri - URI of the resource to interact with
501 * @param referenceUri - URI of the reference resource
502 * @param request - JSON encoded request
503 * @param qos - quality of service
504 * @param cbData - struct that contains asynchronous callback function that is invoked
505 * by the stack when discovery or resource interaction is complete
506 * @param options - The address of an array containing the vendor specific header
507 * header options to be sent with the request
508 * @param numOptions - Number of vendor specific header options to be included
511 * OC_STACK_OK - no errors
512 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
513 * OC_STACK_INVALID_METHOD - invalid resource method
514 * OC_STACK_INVALID_URI - invalid required or reference URI
517 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
518 const char *referenceUri, const char *request,
519 OCQualityOfService qos, OCCallbackData *cbData,
520 OCHeaderOption * options, uint8_t numOptions)
522 OCStackResult result = OC_STACK_ERROR;
524 ClientCB *clientCB = NULL;
525 unsigned char * requestUri = NULL;
526 unsigned char * resourceType = NULL;
527 char * newURI = (char *)requiredUri;
530 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
532 // Validate input parameters
533 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
534 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
536 TODO ("Need to form the final query by concatenating require and reference URI's");
537 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
539 uint16_t uriLen = strlen(requiredUri);
541 // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS
548 case OC_REST_OBSERVE:
549 case OC_REST_OBSERVE_ALL:
550 case OC_REST_CANCEL_OBSERVE:
553 case OC_REST_PRESENCE:
557 result = OC_STACK_INVALID_METHOD;
561 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
566 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
568 result = OC_STACK_INVALID_PARAM;
573 if(method == OC_REST_PRESENCE)
575 result = getResourceType(requiredUri, &resourceType, &newURI);
576 if(result != OC_STACK_OK)
581 #endif // WITH_PRESENCE
583 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
586 memcpy(requestUri, newURI, (uriLen + 1));
590 result = OC_STACK_NO_MEMORY;
594 *handle = GenerateInvocationHandle();
597 result = OC_STACK_NO_MEMORY;
601 // Generate token which will be used by OCStack to match responses received
603 OCGenerateCoAPToken(&token);
605 if((result = AddClientCB(&clientCB, cbData, &token, *handle, method, requestUri, resourceType))
608 result = OC_STACK_NO_MEMORY;
612 // Make call to OCCoAP layer
613 result = OCDoCoAPResource(method, qos, &token, newURI, request, options, numOptions);
616 if(newURI != requiredUri)
620 if (result != OC_STACK_OK)
622 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
623 FindAndDeleteClientCB(clientCB);
629 * Cancel a request associated with a specific @ref OCDoResource invocation.
631 * @param handle - Used to identify a specific OCDoResource invocation.
632 * @param qos - used to specify Quality of Service (read below for more info)
633 * @param options- used to specify vendor specific header options when sending
634 * explicit observe cancellation
635 * @param numOptions- Number of header options to be included
638 * OC_STACK_OK - No errors; Success
639 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
641 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
642 uint8_t numOptions) {
644 * This ftn is implemented one of two ways in the case of observation:
646 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
647 * Remove the callback associated on client side.
648 * When the next notification comes in from server,
649 * reply with RESET message to server.
650 * Keep in mind that the server will react to RESET only
651 * if the last notification was sent ans CON
653 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
654 * and it is associated with an observe request
655 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
656 * Send CON Observe request to server with
657 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
658 * Remove the callback associated on client side.
660 OCStackResult ret = OC_STACK_OK;
663 return OC_STACK_INVALID_PARAM;
666 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
668 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
671 switch (clientCB->method)
673 case OC_REST_OBSERVE:
674 case OC_REST_OBSERVE_ALL:
675 if(qos == OC_HIGH_QOS)
677 ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
678 &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
683 FindAndDeleteClientCB(clientCB);
687 case OC_REST_PRESENCE:
688 FindAndDeleteClientCB(clientCB);
692 return OC_STACK_INVALID_METHOD;
698 OCStackResult OCProcessPresence()
700 OCStackResult result = OC_STACK_OK;
701 uint8_t ipAddr[4] = { 0 };
704 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
705 ClientCB* cbNode = NULL;
707 OCClientResponse clientResponse;
708 OCResponse * response = NULL;
710 LL_FOREACH(cbList, cbNode) {
711 if(OC_REST_PRESENCE == cbNode->method)
715 uint32_t now = GetTime(0);
716 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
717 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
720 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
725 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
726 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
727 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
730 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
732 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
733 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
735 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
737 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
738 (OCDevAddr *) &dst, 0, NULL);
739 if(result != OC_STACK_OK)
743 result = FormOCResponse(&response, cbNode, 0, &clientResponse);
744 if(result != OC_STACK_OK)
749 // Increment the TTLLevel (going to a next state), so we don't keep
750 // sending presence notification to client.
751 cbNode->presence->TTLlevel++;
752 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
753 cbNode->presence->TTLlevel);
757 result = OC_STACK_INVALID_IP;
760 HandleStackResponses(response);
762 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
764 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
766 OCGenerateCoAPToken(&token);
767 result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
768 &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
769 if(result != OC_STACK_OK)
773 cbNode->presence->TTLlevel++;
774 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
780 if (result != OC_STACK_OK)
782 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
789 * Called in main loop of OC client or server. Allows low-level processing of
793 * OC_STACK_OK - no errors
794 * OC_STACK_ERROR - stack process error
796 OCStackResult OCProcess() {
798 OC_LOG(INFO, TAG, PCF("Entering OCProcess"));
809 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
810 * presence notifications to clients via multicast. Once this API has been called with a success,
811 * clients may query for this server's presence and this server's stack will respond via multicast.
813 * Server can call this function when it comes online for the first time, or when it comes back
814 * online from offline mode, or when it re enters network.
816 * @param ttl - Time To Live in seconds
817 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
820 * OC_STACK_OK - No errors; Success
822 OCStackResult OCStartPresence(const uint32_t ttl)
824 OCChangeResourceProperty(
825 &(((OCResource *)presenceResource.handle)->resourceProperties),
830 presenceResource.presenceTTL = ttl;
833 if(OC_PRESENCE_UNINITIALIZED == presenceState)
835 OCDevAddr multiCastAddr;
838 presenceState = OC_PRESENCE_INITIALIZED;
839 OCGenerateCoAPToken(&token);
840 OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
841 //add the presence observer
842 AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
843 (OCResource *)presenceResource.handle, OC_LOW_QOS);
846 // Each time OCStartPresence is called
847 // a different random 32-bit integer number is used
848 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
850 return SendPresenceNotification(NULL);
854 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
855 * presence notifications to clients via multicast. Once this API has been called with a success,
856 * this server's stack will not respond to clients querying for this server's presence.
858 * Server can call this function when it is terminating, going offline, or when going
862 * OC_STACK_OK - No errors; Success
864 OCStackResult OCStopPresence()
866 OCStackResult result = OC_STACK_ERROR;
867 //make resource inactive
868 result = OCChangeResourceProperty(
869 &(((OCResource *) presenceResource.handle)->resourceProperties),
871 result = SendPresenceNotification(NULL);
878 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
880 defaultDeviceHandler = entityHandler;
888 * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource
889 * @param resourceTypeName - name of resource type. Example: "core.led"
890 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
891 * @param uri - URI of the resource. Example: "/a/led"
892 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
893 * NULL for default entity handler
894 * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE
897 * OC_STACK_OK - no errors
898 * OC_STACK_ERROR - stack process error
900 OCStackResult OCCreateResource(OCResourceHandle *handle,
901 const char *resourceTypeName,
902 const char *resourceInterfaceName,
903 const char *uri, OCEntityHandler entityHandler,
904 uint8_t resourceProperties) {
906 OCResource *pointer = NULL;
909 OCStackResult result = OC_STACK_ERROR;
911 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
913 if(myStackMode == OC_CLIENT)
917 // Validate parameters
918 // Is it presented during resource discovery?
919 if (!handle || !resourceTypeName || !uri) {
920 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
921 return OC_STACK_INVALID_PARAM;
924 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
925 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
928 // Make sure resourceProperties bitmask has allowed properties specified
929 if (resourceProperties
930 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
931 OC_LOG(ERROR, TAG, PCF("Invalid property"));
932 return OC_STACK_INVALID_PARAM;
935 // If the headResource is NULL, then no resources have been created...
936 pointer = headResource;
938 // At least one resources is in the resource list, so we need to search for
939 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
941 if (strcmp(uri, pointer->uri) == 0) {
942 OC_LOG(ERROR, TAG, PCF("URI already in use"));
943 return OC_STACK_INVALID_PARAM;
945 pointer = pointer->next;
948 // Create the pointer and insert it into the resource list
949 pointer = (OCResource *) OCMalloc(sizeof(OCResource));
953 memset(pointer, 0, sizeof(OCResource));
954 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
956 insertResource(pointer);
959 size = strlen(uri) + 1;
960 str = (char *) OCMalloc(size);
964 strncpy(str, uri, size);
967 // Set properties. Set OC_ACTIVE
968 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
971 // Add the resourcetype to the resource
972 result = BindResourceTypeToResource(pointer, resourceTypeName);
973 if (result != OC_STACK_OK) {
974 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
978 // Add the resourceinterface to the resource
979 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
980 if (result != OC_STACK_OK) {
981 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
985 // If an entity handler has been passed, attach it to the newly created
986 // resource. Otherwise, set the default entity handler.
989 pointer->entityHandler = entityHandler;
993 pointer->entityHandler = defaultResourceEHandler;
997 result = OC_STACK_OK;
1000 if(presenceResource.handle)
1002 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1003 SendPresenceNotification(pointer->rsrcType);
1007 if (result != OC_STACK_OK)
1009 // Deep delete of resource and other dynamic elements that it contains
1010 deleteResource(pointer);
1019 * Create a resource. with host ip address for remote resource
1021 * @param handle - pointer to handle to newly created resource. Set by ocstack.
1022 * Used to refer to resource
1023 * @param resourceTypeName - name of resource type. Example: "core.led"
1024 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1025 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
1026 * @param uri - URI of the resource. Example: "/a/led"
1027 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1028 * NULL for default entity handler
1029 * @param resourceProperties - properties supported by resource.
1030 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
1033 * OC_STACK_OK - no errors
1034 * OC_STACK_ERROR - stack process error
1037 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
1038 const char *resourceTypeName,
1039 const char *resourceInterfaceName,
1042 OCEntityHandler entityHandler,
1043 uint8_t resourceProperties)
1047 OCStackResult result = OC_STACK_ERROR;
1049 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
1050 uri, entityHandler, resourceProperties);
1052 if (result != OC_STACK_ERROR)
1055 size = strlen(host) + 1;
1056 str = (char *) OCMalloc(size);
1059 return OC_STACK_ERROR;
1061 strncpy(str, host, size);
1062 ((OCResource *) *handle)->host = str;
1069 * Add a resource to a collection resource.
1071 * @param collectionHandle - handle to the collection resource
1072 * @param resourceHandle - handle to resource to be added to the collection resource
1075 * OC_STACK_OK - no errors
1076 * OC_STACK_ERROR - stack process error
1077 * OC_STACK_INVALID_PARAM - invalid collectionhandle
1079 OCStackResult OCBindResource(
1080 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1081 OCResource *resource;
1084 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
1086 // Validate parameters
1087 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1088 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1089 // Container cannot contain itself
1090 if (collectionHandle == resourceHandle) {
1091 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
1092 return OC_STACK_INVALID_PARAM;
1095 // Use the handle to find the resource in the resource linked list
1096 resource = findResource((OCResource *) collectionHandle);
1098 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1099 return OC_STACK_INVALID_PARAM;
1102 // Look for an open slot to add add the child resource.
1103 // If found, add it and return success
1104 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1105 if (!resource->rsrcResources[i]) {
1106 resource->rsrcResources[i] = (OCResource *) resourceHandle;
1107 OC_LOG(INFO, TAG, PCF("resource bound"));
1112 #ifdef WITH_PRESENCE
1113 if(presenceResource.handle)
1115 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1116 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1120 // Unable to add resourceHandle, so return error
1121 return OC_STACK_ERROR;
1125 * Remove a resource from a collection resource.
1127 * @param collectionHandle - handle to the collection resource
1128 * @param resourceHandle - handle to resource to be added to the collection resource
1131 * OC_STACK_OK - no errors
1132 * OC_STACK_ERROR - stack process error
1133 * OC_STACK_INVALID_PARAM - invalid collectionHandle
1135 OCStackResult OCUnBindResource(
1136 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1137 OCResource *resource;
1140 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
1142 // Validate parameters
1143 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1144 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1145 // Container cannot contain itself
1146 if (collectionHandle == resourceHandle) {
1147 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
1148 return OC_STACK_INVALID_PARAM;
1151 // Use the handle to find the resource in the resource linked list
1152 resource = findResource((OCResource *) collectionHandle);
1154 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1155 return OC_STACK_INVALID_PARAM;
1158 // Look for an open slot to add add the child resource.
1159 // If found, add it and return success
1160 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1161 if (resourceHandle == resource->rsrcResources[i]) {
1162 resource->rsrcResources[i] = (OCResource *) NULL;
1163 OC_LOG(INFO, TAG, PCF("resource unbound"));
1168 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
1170 #ifdef WITH_PRESENCE
1171 if(presenceResource.handle)
1173 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1174 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1178 // Unable to add resourceHandle, so return error
1179 return OC_STACK_ERROR;
1182 OCStackResult BindResourceTypeToResource(OCResource* resource,
1183 const char *resourceTypeName)
1185 OCResourceType *pointer = NULL;
1188 OCStackResult result = OC_STACK_ERROR;
1190 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
1192 // Validate parameters
1193 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
1194 // TODO: Does resource attribute resentation really have to be maintained in stack?
1195 // Is it presented during resource discovery?
1197 TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
1199 // Create the resourcetype and insert it into the resource list
1200 pointer = (OCResourceType *) OCMalloc(sizeof(OCResourceType));
1204 memset(pointer, 0, sizeof(OCResourceType));
1206 // Set the resourceTypeName
1207 size = strlen(resourceTypeName) + 1;
1208 str = (char *) OCMalloc(size);
1212 strncpy(str, resourceTypeName, size);
1213 pointer->resourcetypename = str;
1215 insertResourceType(resource, pointer);
1216 result = OC_STACK_OK;
1218 exit: if (result != OC_STACK_OK) {
1226 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
1227 const char *resourceInterfaceName)
1229 OCResourceInterface *pointer = NULL;
1232 OCStackResult result = OC_STACK_ERROR;
1234 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
1236 // Validate parameters
1237 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
1239 TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
1241 // Create the resourceinterface and insert it into the resource list
1242 pointer = (OCResourceInterface *) OCMalloc(sizeof(OCResourceInterface));
1246 memset(pointer, 0, sizeof(OCResourceInterface));
1248 // Set the resourceinterface name
1249 size = strlen(resourceInterfaceName) + 1;
1250 str = (char *) OCMalloc(size);
1254 strncpy(str, resourceInterfaceName, size);
1255 pointer->name = str;
1257 // Bind the resourceinterface to the resource
1258 insertResourceInterface(resource, pointer);
1260 result = OC_STACK_OK;
1262 exit: if (result != OC_STACK_OK) {
1271 * Bind a resourcetype to a resource.
1273 * @param handle - handle to the resource
1274 * @param resourceTypeName - name of resource type. Example: "core.led"
1277 * OC_STACK_OK - no errors
1278 * OC_STACK_ERROR - stack process error
1280 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
1281 const char *resourceTypeName) {
1283 OCStackResult result = OC_STACK_ERROR;
1284 OCResource *resource;
1286 // Make sure resource exists
1287 resource = findResource((OCResource *) handle);
1289 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1290 return OC_STACK_ERROR;
1293 // call internal function
1294 result = BindResourceTypeToResource(resource, resourceTypeName);
1296 #ifdef WITH_PRESENCE
1297 if(presenceResource.handle)
1299 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1300 SendPresenceNotification(resource->rsrcType);
1308 * Bind a resourceinterface to a resource.
1310 * @param handle - handle to the resource
1311 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
1314 * OC_STACK_OK - no errors
1315 * OC_STACK_ERROR - stack process error
1318 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
1319 const char *resourceInterfaceName) {
1321 OCStackResult result = OC_STACK_ERROR;
1322 OCResource *resource;
1324 // Make sure resource exists
1325 resource = findResource((OCResource *) handle);
1327 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1328 return OC_STACK_ERROR;
1331 // call internal function
1332 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
1334 #ifdef WITH_PRESENCE
1335 if(presenceResource.handle)
1337 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1338 SendPresenceNotification(resource->rsrcType);
1346 * Get the number of resources that have been created in the stack.
1348 * @param numResources - pointer to count variable
1351 * OC_STACK_OK - no errors
1352 * OC_STACK_ERROR - stack process error
1355 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
1356 OCResource *pointer = headResource;
1358 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
1359 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
1362 *numResources = *numResources + 1;
1363 pointer = pointer->next;
1369 * Get a resource handle by index.
1371 * @param index - index of resource, 0 to Count - 1
1374 * Resource handle - if found
1375 * NULL - if not found
1377 OCResourceHandle OCGetResourceHandle(uint8_t index) {
1378 OCResource *pointer = headResource;
1381 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
1383 // Iterate through the list
1384 while ((i < index) && pointer) {
1386 pointer = pointer->next;
1388 return (OCResourceHandle) pointer;
1392 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
1395 * @param handle - handle of resource to be deleted
1398 * OC_STACK_OK - no errors
1399 * OC_STACK_ERROR - stack process error
1400 * OC_STACK_NO_RESOURCE - resource not found
1401 * OC_STACK_INVALID_PARAM - invalid param
1403 OCStackResult OCDeleteResource(OCResourceHandle handle) {
1404 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
1407 OC_LOG(ERROR, TAG, PCF("Invalid param"));
1408 return OC_STACK_INVALID_PARAM;
1411 OCResource *resource = findResource((OCResource *) handle);
1412 if (resource == NULL) {
1413 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1414 return OC_STACK_NO_RESOURCE;
1417 if (deleteResource((OCResource *) handle) == 0) {
1418 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
1419 return OC_STACK_ERROR;
1426 * Get the URI of the resource specified by handle.
1428 * @param handle - handle of resource
1430 * URI string - if resource found
1431 * NULL - resource not found
1433 const char *OCGetResourceUri(OCResourceHandle handle) {
1434 OCResource *resource;
1435 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
1437 resource = findResource((OCResource *) handle);
1439 return resource->uri;
1441 return (const char *) NULL;
1445 * Get the properties of the resource specified by handle.
1446 * NOTE: that after a resource is created, the OC_ACTIVE property is set
1447 * for the resource by the stack.
1449 * @param handle - handle of resource
1451 * property bitmap - if resource found
1452 * NULL - resource not found
1454 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
1455 OCResource *resource;
1456 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
1458 resource = findResource((OCResource *) handle);
1460 return resource->resourceProperties;
1466 * Get the number of resource types of the resource.
1468 * @param handle - handle of resource
1469 * @param numResourceTypes - pointer to count variable
1472 * OC_STACK_OK - no errors
1473 * OC_STACK_ERROR - stack process error
1475 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
1476 uint8_t *numResourceTypes) {
1477 OCResource *resource;
1478 OCResourceType *pointer;
1480 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
1481 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
1482 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
1484 *numResourceTypes = 0;
1486 resource = findResource((OCResource *) handle);
1488 pointer = resource->rsrcType;
1490 *numResourceTypes = *numResourceTypes + 1;
1491 pointer = pointer->next;
1498 * Get name of resource type of the resource.
1500 * @param handle - handle of resource
1501 * @param index - index of resource, 0 to Count - 1
1504 * resource type name - if resource found
1505 * NULL - resource not found
1507 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
1508 OCResourceType *resourceType;
1510 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
1512 resourceType = findResourceTypeAtIndex(handle, index);
1514 return resourceType->resourcetypename;
1516 return (const char *) NULL;
1522 * Get the number of resource interfaces of the resource.
1524 * @param handle - handle of resource
1525 * @param numResources - pointer to count variable
1528 * OC_STACK_OK - no errors
1529 * OC_STACK_ERROR - stack process error
1531 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
1532 uint8_t *numResourceInterfaces) {
1533 OCResourceInterface *pointer;
1534 OCResource *resource;
1536 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
1538 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
1539 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
1541 *numResourceInterfaces = 0;
1542 resource = findResource((OCResource *) handle);
1544 pointer = resource->rsrcInterface;
1546 *numResourceInterfaces = *numResourceInterfaces + 1;
1547 pointer = pointer->next;
1554 * Get name of resource interface of the resource.
1556 * @param handle - handle of resource
1557 * @param index - index of resource, 0 to Count - 1
1560 * resource interface name - if resource found
1561 * NULL - resource not found
1563 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
1564 OCResourceInterface *resourceInterface;
1566 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
1568 resourceInterface = findResourceInterfaceAtIndex(handle, index);
1569 if (resourceInterface) {
1570 return resourceInterface->name;
1572 return (const char *) NULL;
1576 * Get resource handle from the collection resource by index.
1578 * @param collectionHandle - handle of collection resource
1579 * @param index - index of contained resource, 0 to Count - 1
1582 * handle to resource - if resource found
1583 * NULL - resource not found
1585 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
1587 OCResource *resource;
1589 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
1591 if (index >= MAX_CONTAINED_RESOURCES) {
1595 resource = findResource((OCResource *) collectionHandle);
1600 return resource->rsrcResources[index];
1604 * Bind an entity handler to the resource.
1606 * @param handle - handle to the resource that the contained resource is to be bound
1607 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1609 * OC_STACK_OK - no errors
1610 * OC_STACK_ERROR - stack process error
1612 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
1613 OCEntityHandler entityHandler) {
1614 OCResource *resource;
1616 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
1618 // Validate parameters
1619 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
1620 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
1622 // Use the handle to find the resource in the resource linked list
1623 resource = findResource((OCResource *)handle);
1625 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1626 return OC_STACK_ERROR;
1630 resource->entityHandler = entityHandler;
1632 #ifdef WITH_PRESENCE
1633 if(presenceResource.handle)
1635 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1636 SendPresenceNotification(resource->rsrcType);
1644 * Get the entity handler for a resource.
1646 * @param handle - handle of resource
1649 * entity handler - if resource found
1650 * NULL - resource not found
1652 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
1653 OCResource *resource;
1655 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
1657 // Use the handle to find the resource in the resource linked list
1658 resource = findResource((OCResource *)handle);
1660 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1665 return resource->entityHandler;
1668 void incrementSequenceNumber(OCResource * resPtr)
1670 // Increment the sequence number
1671 resPtr->sequenceNum += 1;
1672 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
1674 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
1679 #ifdef WITH_PRESENCE
1681 * Notify Presence subscribers that a resource has been modified
1683 * @param resourceType - Handle to the resourceType linked list of resource
1684 * that was modified.
1685 * @param qos - Quality Of Service
1688 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
1690 OCResource *resPtr = NULL;
1691 OCStackResult result;
1692 OCMethod method = OC_REST_PRESENCE;
1693 uint32_t maxAge = 0;
1694 resPtr = findResource((OCResource *) presenceResource.handle);
1697 return OC_STACK_NO_RESOURCE;
1699 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
1701 maxAge = presenceResource.presenceTTL;
1708 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
1714 * Notify observers that an observed value has changed.
1716 * @param handle - handle of resource
1719 * OC_STACK_OK - no errors
1720 * OC_STACK_NO_RESOURCE - invalid resource handle
1721 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
1723 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
1725 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
1727 OCResource *resPtr = NULL;
1728 OCStackResult result;
1729 OCMethod method = OC_REST_NOMETHOD;
1730 uint32_t maxAge = 0;
1732 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
1733 // Verify that the resource exists
1734 resPtr = findResource ((OCResource *) handle);
1735 if (NULL == resPtr || myStackMode == OC_CLIENT)
1737 return OC_STACK_NO_RESOURCE;
1741 //only increment in the case of regular observing (not presence)
1742 incrementSequenceNumber(resPtr);
1743 method = OC_REST_OBSERVE;
1744 maxAge = MAX_OBSERVE_AGE;
1745 #ifdef WITH_PRESENCE
1746 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
1748 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
1755 OCNotifyListOfObservers (OCResourceHandle handle,
1756 OCObservationId *obsIdList,
1757 uint8_t numberOfIds,
1758 unsigned char *notificationJSONPayload,
1759 OCQualityOfService qos)
1761 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
1763 OCResource *resPtr = NULL;
1764 //TODO: we should allow the server to define this
1765 uint32_t maxAge = MAX_OBSERVE_AGE;
1767 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
1768 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
1769 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
1771 // Verify that the resource exists
1772 resPtr = findResource ((OCResource *) handle);
1773 if (NULL == resPtr || myStackMode == OC_CLIENT)
1775 return OC_STACK_NO_RESOURCE;
1779 incrementSequenceNumber(resPtr);
1781 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
1782 notificationJSONPayload, maxAge, qos));
1786 * Send a response to a request.
1787 * The response can be a regular, slow, or block (i.e. a response that
1788 * is too large to be sent in a single PDU and must span multiple transmissions)
1790 * @param response - pointer to structure that contains response parameters
1793 * OC_STACK_OK - No errors; Success
1794 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
1795 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
1796 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
1797 * persistent response buffer is necessary
1799 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
1801 OCStackResult result = OC_STACK_ERROR;
1802 OCServerRequest *serverRequest = NULL;
1804 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
1806 // Validate input parameters
1807 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
1808 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
1810 // TODO: Placeholder for creating a response entry when implementing
1811 // block transfer feature
1813 // If a response payload is present, check if block transfer is required
1814 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
1815 (const char *)ehResponse->payload, ehResponse->payloadSize))
1817 OC_LOG(INFO, TAG, PCF("Block transfer required"));
1819 // Persistent response buffer is needed for block transfer
1820 if (!ehResponse->persistentBufferFlag)
1822 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
1823 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
1825 // TODO: Placeholder for block transfer handling
1826 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
1827 // when implementing the block transfer feature
1833 // Get pointer to request info
1834 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
1837 result = serverRequest->ehResponseHandler(ehResponse);
1844 * Cancel a response. Applies to a block response
1846 * @param responseHandle - response handle set by stack in OCServerResponse after
1847 * OCDoResponse is called
1850 * OC_STACK_OK - No errors; Success
1851 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1853 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
1855 OCStackResult result = OC_STACK_NOTIMPL;
1857 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
1859 // TODO: validate response handle
1864 //-----------------------------------------------------------------------------
1865 // Private internal function definitions
1866 //-----------------------------------------------------------------------------
1868 * Generate handle of OCDoResource invocation for callback management.
1870 static OCDoHandle GenerateInvocationHandle()
1872 OCDoHandle handle = NULL;
1873 // Generate token here, it will be deleted when the transaction is deleted
1874 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
1877 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
1882 #ifdef WITH_PRESENCE
1883 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
1884 OCResourceProperty resourceProperties, uint8_t enable)
1886 if (resourceProperties
1887 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
1888 OC_LOG(ERROR, TAG, PCF("Invalid property"));
1889 return OC_STACK_INVALID_PARAM;
1893 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
1897 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
1904 * Initialize resource data structures, variables, etc.
1906 OCStackResult initResources() {
1907 OCStackResult result = OC_STACK_OK;
1908 // Init application resource vars
1909 headResource = NULL;
1910 // Init Virtual Resources
1911 #ifdef WITH_PRESENCE
1912 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
1913 //presenceResource.token = OCGenerateCoAPToken();
1914 result = OCCreateResource(&presenceResource.handle,
1920 //make resource inactive
1921 result = OCChangeResourceProperty(
1922 &(((OCResource *) presenceResource.handle)->resourceProperties),
1929 * Add a resource to the end of the linked list of resources.
1931 * @param resource - resource to be added
1933 void insertResource(OCResource *resource) {
1934 OCResource *pointer;
1936 if (!headResource) {
1937 headResource = resource;
1939 pointer = headResource;
1941 while (pointer->next) {
1942 pointer = pointer->next;
1944 pointer->next = resource;
1946 resource->next = NULL;
1950 * Find a resource in the linked list of resources.
1952 * @param resource - resource to be found
1954 * NULL - resource not found
1955 * pointer to resource - pointer to resource that was found in the linked list
1957 OCResource *findResource(OCResource *resource) {
1958 OCResource *pointer = headResource;
1961 if (pointer == resource) {
1964 pointer = pointer->next;
1969 void deleteAllResources()
1971 OCResource *pointer = headResource;
1976 temp = pointer->next;
1977 deleteResource(pointer);
1983 * Delete the resource from the linked list.
1985 * @param resource - resource to be deleted
1990 int deleteResource(OCResource *resource) {
1991 OCResource *prev = NULL;
1994 temp = headResource;
1996 if (temp == resource) {
1997 // Invalidate all Resource Properties.
1998 resource->resourceProperties = (OCResourceProperty) 0;
1999 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
2001 #ifdef WITH_PRESENCE
2002 if(presenceResource.handle)
2004 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2005 SendPresenceNotification(resource->rsrcType);
2009 if (temp == headResource) {
2010 headResource = temp->next;
2012 prev->next = temp->next;
2015 deleteResourceElements(temp);
2028 * Delete all of the dynamically allocated elements that were created for the resource.
2030 * @param resource - specified resource
2032 void deleteResourceElements(OCResource *resource) {
2038 OCFree(resource->uri);
2040 // Delete resourcetype linked list
2041 deleteResourceType(resource->rsrcType);
2043 // Delete resourceinterface linked list
2044 deleteResourceInterface(resource->rsrcInterface);
2048 * Delete all of the dynamically allocated elements that were created for the resource type.
2050 * @param resourceType - specified resource type
2052 void deleteResourceType(OCResourceType *resourceType) {
2053 OCResourceType *pointer = resourceType;
2054 OCResourceType *next;
2057 next = pointer->next;
2058 OCFree(pointer->resourcetypename);
2065 * Delete all of the dynamically allocated elements that were created for the resource interface.
2067 * @param resourceInterface - specified resource interface
2069 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
2070 OCResourceInterface *pointer = resourceInterface;
2071 OCResourceInterface *next;
2074 next = pointer->next;
2075 OCFree(pointer->name);
2082 * Insert a resource type into a resource's resource type linked list.
2084 * @param resource - resource where resource type is to be inserted
2085 * @param resourceType - resource type to be inserted
2087 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
2088 OCResourceType *pointer;
2090 if (resource && !resource->rsrcType) {
2091 resource->rsrcType = resourceType;
2095 pointer = resource->rsrcType;
2099 pointer = resourceType;
2101 while (pointer->next) {
2102 pointer = pointer->next;
2104 pointer->next = resourceType;
2106 resourceType->next = NULL;
2110 * Get a resource type at the specified index within a resource.
2112 * @param handle - handle of resource
2113 * @param index - index of resource type
2116 * resourcetype - if found
2119 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
2120 OCResource *resource;
2121 OCResourceType *pointer;
2124 // Find the specified resource
2125 resource = findResource((OCResource *) handle);
2130 // Make sure a resource has a resourcetype
2131 if (!resource->rsrcType) {
2135 // Iterate through the list
2136 pointer = resource->rsrcType;
2138 while ((i < index) && pointer) {
2140 pointer = pointer->next;
2146 * Insert a resource interface into a resource's resource interface linked list.
2148 * @param resource - resource where resource interface is to be inserted
2149 * @param resourceInterface - resource interface to be inserted
2151 void insertResourceInterface(OCResource *resource,
2152 OCResourceInterface *resourceInterface) {
2153 OCResourceInterface *pointer;
2155 if (!resource->rsrcInterface) {
2156 resource->rsrcInterface = resourceInterface;
2158 pointer = resource->rsrcInterface;
2159 while (pointer->next) {
2160 pointer = pointer->next;
2162 pointer->next = resourceInterface;
2164 resourceInterface->next = NULL;
2168 * Get a resource interface at the specified index within a resource.
2170 * @param handle - handle of resource
2171 * @param index - index of resource interface
2174 * resourceinterface - if found
2177 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
2179 OCResource *resource;
2180 OCResourceInterface *pointer;
2183 // Find the specified resource
2184 resource = findResource((OCResource *) handle);
2189 // Make sure a resource has a resourceinterface
2190 if (!resource->rsrcInterface) {
2194 // Iterate through the list
2195 pointer = resource->rsrcInterface;
2197 while ((i < index) && pointer) {
2199 pointer = pointer->next;
2205 * Determine if a request/response must be sent in a block transfer because it is too large to be
2206 * sent in a single PDU. This function can be used for either a request or a response
2208 * @param request - NULL or pointer to request
2209 * @param response - NULL or pointer to response
2210 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
2211 * the length of the request/response
2214 * 0 - packet transfer NOT required (i.e. normal request/response)
2215 * 1 - packet transfer required (i.e. block transfer needed)
2217 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
2221 // Determine if we are checking a request or a response
2224 // If size is greater than 0, use it for the request size value, otherwise
2225 // assume request is null terminated and use strlen for size value
2226 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
2233 // If size is greater than 0, use it for the response size value, otherwise
2234 // assume response is null terminated and use strlen for size value
2235 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
2244 * Retrieves a resource type based upon a uri string if the uri string contains only just one
2245 * resource attribute (and that has to be of type "rt").
2247 * @remark This API malloc's memory for the resource type and newURI. Do not malloc resourceType
2248 * or newURI before passing in.
2250 * @param uri - Valid URI for "requiredUri" parameter to OCDoResource API.
2251 * @param resourceType - The resource type to be populated; pass by reference.
2252 * @param newURI - Return URI without resourceType appended to the end of it. This is used to
2253 * ensure that the uri parameter is not modified; pass by reference.
2256 * OC_STACK_INVALID_URI - Returns this if the URI is invalid/NULL.
2257 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
2258 * OC_STACK_OK - Success
2260 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI)
2264 return OC_STACK_INVALID_URI;
2266 if(!resourceType || !newURI)
2268 return OC_STACK_INVALID_PARAM;
2271 char * leftToken = NULL;
2272 char * tempURI = (char *) OCMalloc(strlen(uri));
2278 strcpy(tempURI, uri);
2279 leftToken = strtok((char *)tempURI, "?");
2281 while(leftToken != NULL)
2283 if(strncmp(leftToken, "rt=", 3) == 0)
2285 *resourceType = (unsigned char *) OCMalloc(strlen(leftToken)-3);
2290 strcpy((char *)*resourceType, ((const char *)&leftToken[3]));
2293 leftToken = strtok(NULL, "?");
2301 return OC_STACK_NO_MEMORY;