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 = {0};
93 case OC_OBSERVER_NOT_INTERESTED:
94 OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
95 observer = GetObserverUsingToken (token);
98 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
99 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
100 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
101 if(result != OC_STACK_OK)
105 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
107 //observer is not observing anymore
108 result = DeleteObserverUsingToken (token);
109 if(result == OC_STACK_OK)
111 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
115 result = OC_STACK_OK;
116 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
119 case OC_OBSERVER_STILL_INTERESTED:
120 //observer is still interested
121 OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
122 notifications, reset the failedCount"));
123 observer = GetObserverUsingToken(token);
126 observer->forceHighQos = 0;
127 observer->failedCommCount = 0;
128 result = OC_STACK_OK;
132 result = OC_STACK_OBSERVER_NOT_FOUND;
135 case OC_OBSERVER_FAILED_COMM:
136 //observer is not reachable
137 OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
138 observer = GetObserverUsingToken(token);
141 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
143 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
144 OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0,
145 NULL, OC_OBSERVE_DEREGISTER, observer->observeId);
146 if(result != OC_STACK_OK)
148 return OC_STACK_ERROR;
150 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
151 //observer is unreachable
152 result = DeleteObserverUsingToken (token);
153 if(result == OC_STACK_OK)
155 OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
159 result = OC_STACK_OK;
160 OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
165 observer->failedCommCount++;
166 result = OC_STACK_CONTINUE;
168 observer->forceHighQos = 1;
169 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
173 OC_LOG(ERROR, TAG, PCF("Unknown status"));
174 result = OC_STACK_ERROR;
180 //This function will be called back by occoap layer when a request is received
181 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
183 OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
185 OCStackResult result = OC_STACK_ERROR;
186 ResourceHandling resHandling;
187 OCResource *resource;
189 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
192 OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
193 result = AddServerRequest(&request, protocolRequest->coapID,
194 protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
195 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
196 protocolRequest->observationOption, protocolRequest->qos,
197 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
198 protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
199 &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
200 protocolRequest->reqTotalSize);
201 if (OC_STACK_OK != result)
203 OC_LOG(ERROR, TAG, PCF("Error adding server request"));
206 VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
208 if(!protocolRequest->reqMorePacket)
210 request->requestComplete = 1;
215 OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
218 if(request->requestComplete)
220 OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
221 result = DetermineResourceHandling (request, &resHandling, &resource);
222 if (result == OC_STACK_OK)
224 result = ProcessRequest(resHandling, resource, request);
228 result = OC_STACK_ERROR;
233 OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
234 result = OC_STACK_CONTINUE;
239 //This function will be called back by occoap layer when a response is received
240 void HandleStackResponses(OCResponse * response)
242 OCStackApplicationResult result = OC_STACK_DELETE_TRANSACTION;
243 OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)"));
245 if (response->cbNode)
247 OC_LOG(INFO, TAG, PCF("Calling into application address space"));
248 result = response->cbNode->callBack(response->cbNode->context,
249 response->cbNode->handle, response->clientResponse);
250 if (result == OC_STACK_DELETE_TRANSACTION ||
251 response->clientResponse->result == OC_STACK_COMM_ERROR ||
252 response->clientResponse->result == OC_STACK_RESOURCE_DELETED)
254 FindAndDeleteClientCB(response->cbNode);
259 int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
262 unsigned char *itr, *coap;
263 uint8_t dotCount = 0;
267 /* search for scheme */
269 if (!isdigit((unsigned char) *ipAddrStr))
271 coap = (unsigned char *) OC_COAP_SCHEME;
272 while (*coap && tolower(*itr) == *coap)
281 if (isdigit((unsigned char) *ipAddrStr))
284 ipAddr[index] += *ipAddrStr - '0';
286 else if ((unsigned char) *ipAddrStr == '.')
298 if(*ipAddrStr == ':')
302 if (isdigit((unsigned char) *ipAddrStr))
305 *port += *ipAddrStr - '0';
316 if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
327 //-----------------------------------------------------------------------------
328 // Private internal function prototypes
329 //-----------------------------------------------------------------------------
331 static OCDoHandle GenerateInvocationHandle();
332 static OCStackResult initResources();
333 static void insertResource(OCResource *resource);
334 static OCResource *findResource(OCResource *resource);
335 static void insertResourceType(OCResource *resource,
336 OCResourceType *resourceType);
337 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
339 static void insertResourceInterface(OCResource *resource,
340 OCResourceInterface *resourceInterface);
341 static OCResourceInterface *findResourceInterfaceAtIndex(
342 OCResourceHandle handle, uint8_t index);
343 static void deleteResourceType(OCResourceType *resourceType);
344 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
345 static void deleteResourceElements(OCResource *resource);
346 static int deleteResource(OCResource *resource);
347 static void deleteAllResources();
348 static void incrementSequenceNumber(OCResource * resPtr);
349 static OCStackResult verifyUriQueryLength(const char * inputUri,
351 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
352 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI);
354 //-----------------------------------------------------------------------------
356 //-----------------------------------------------------------------------------
359 * Initialize the OC Stack. Must be called prior to starting the stack.
362 * IP Address of host device
364 * Port of host device
366 * Host device is client, server, or client-server
369 * OC_STACK_OK - no errors
370 * OC_STACK_ERROR - stack init error
372 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
374 OCStackResult result = OC_STACK_ERROR;
375 OC_LOG(INFO, TAG, PCF("Entering OCInit"));
379 OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
385 OC_LOG(INFO, TAG, PCF("Client mode"));
388 OC_LOG(INFO, TAG, PCF("Server mode"));
390 case OC_CLIENT_SERVER:
391 OC_LOG(INFO, TAG, PCF("Client-server mode"));
394 OC_LOG(ERROR, TAG, PCF("Invalid mode"));
395 return OC_STACK_ERROR;
400 defaultDeviceHandler = NULL;
403 PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
404 #endif // WITH_PRESENCE
406 // Make call to OCCoAP layer
407 result = OCInitCoAP(ipAddr, (uint16_t) port, myStackMode);
408 if (result == OC_STACK_OK)
410 stackState = OC_STACK_INITIALIZED;
412 // Initialize resource
413 if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
415 result = initResources();
417 if(result != OC_STACK_OK)
419 OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
425 * Stop the OC stack. Use for a controlled shutdown.
427 * OC_STACK_OK - no errors
428 * OC_STACK_ERROR - stack not initialized
430 OCStackResult OCStop()
432 OCStackResult result = OC_STACK_ERROR;
434 OC_LOG(INFO, TAG, PCF("Entering OCStop"));
436 if (stackState != OC_STACK_INITIALIZED)
438 OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
439 return OC_STACK_ERROR;
442 // Free memory dynamically allocated for resources
443 deleteAllResources();
445 // Make call to OCCoAP layer
446 if (OCStopCoAP() == OC_STACK_OK)
448 // Remove all observers
449 DeleteObserverList();
450 // Remove all the client callbacks
451 DeleteClientCBList();
452 stackState = OC_STACK_UNINITIALIZED;
453 result = OC_STACK_OK;
455 result = OC_STACK_ERROR;
458 // Deinit security blob
459 DeinitOCSecurityInfo();
461 if (result != OC_STACK_OK) {
462 OC_LOG(ERROR, TAG, PCF("Stack stop error"));
469 * Verify the lengths of the URI and the query separately
471 * @param inputUri - Input URI and query.
472 * @param uriLen - The length of the initial URI with query.
474 * Note: The '?' that appears after the URI is not considered as
475 * a part of the query.
477 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
481 query = strchr (inputUri, '?');
485 if((query - inputUri) > MAX_URI_LENGTH)
487 return OC_STACK_INVALID_URI;
490 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
492 return OC_STACK_INVALID_QUERY;
495 else if(uriLen > MAX_URI_LENGTH)
497 return OC_STACK_INVALID_URI;
503 * Discover or Perform requests on a specified resource (specified by that Resource's respective URI).
505 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of calling this API.
506 * @param method - @ref OCMethod to perform on the resource
507 * @param requiredUri - URI of the resource to interact with
508 * @param referenceUri - URI of the reference resource
509 * @param request - JSON encoded request
510 * @param qos - quality of service
511 * @param cbData - struct that contains asynchronous callback function that is invoked
512 * by the stack when discovery or resource interaction is complete
513 * @param options - The address of an array containing the vendor specific header
514 * header options to be sent with the request
515 * @param numOptions - Number of vendor specific header options to be included
518 * OC_STACK_OK - no errors
519 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
520 * OC_STACK_INVALID_METHOD - invalid resource method
521 * OC_STACK_INVALID_URI - invalid required or reference URI
524 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
525 const char *referenceUri, const char *request,
526 OCQualityOfService qos, OCCallbackData *cbData,
527 OCHeaderOption * options, uint8_t numOptions)
529 OCStackResult result = OC_STACK_ERROR;
531 ClientCB *clientCB = NULL;
532 unsigned char * requestUri = NULL;
533 unsigned char * resourceType = NULL;
534 char * newURI = (char *)requiredUri;
537 OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
539 // Validate input parameters
540 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
541 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
543 TODO ("Need to form the final query by concatenating require and reference URI's");
544 VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
546 uint16_t uriLen = strlen(requiredUri);
548 // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS
555 case OC_REST_OBSERVE:
556 case OC_REST_OBSERVE_ALL:
557 case OC_REST_CANCEL_OBSERVE:
560 case OC_REST_PRESENCE:
564 result = OC_STACK_INVALID_METHOD;
568 if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
573 if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
575 result = OC_STACK_INVALID_PARAM;
580 if(method == OC_REST_PRESENCE)
582 result = getResourceType(requiredUri, &resourceType, &newURI);
583 if(result != OC_STACK_OK)
588 #endif // WITH_PRESENCE
590 requestUri = (unsigned char *) OCMalloc(uriLen + 1);
593 memcpy(requestUri, newURI, (uriLen + 1));
597 result = OC_STACK_NO_MEMORY;
601 *handle = GenerateInvocationHandle();
604 result = OC_STACK_NO_MEMORY;
608 // Generate token which will be used by OCStack to match responses received
610 OCGenerateCoAPToken(&token);
612 if((result = AddClientCB(&clientCB, cbData, &token, *handle, method, requestUri, resourceType))
615 result = OC_STACK_NO_MEMORY;
619 // Make call to OCCoAP layer
620 result = OCDoCoAPResource(method, qos, &token, newURI, request, options, numOptions);
623 if(newURI != requiredUri)
627 if (result != OC_STACK_OK)
629 OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
630 FindAndDeleteClientCB(clientCB);
636 * Cancel a request associated with a specific @ref OCDoResource invocation.
638 * @param handle - Used to identify a specific OCDoResource invocation.
639 * @param qos - used to specify Quality of Service (read below for more info)
640 * @param options- used to specify vendor specific header options when sending
641 * explicit observe cancellation
642 * @param numOptions- Number of header options to be included
645 * OC_STACK_OK - No errors; Success
646 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
648 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
649 uint8_t numOptions) {
651 * This ftn is implemented one of two ways in the case of observation:
653 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
654 * Remove the callback associated on client side.
655 * When the next notification comes in from server,
656 * reply with RESET message to server.
657 * Keep in mind that the server will react to RESET only
658 * if the last notification was sent ans CON
660 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
661 * and it is associated with an observe request
662 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
663 * Send CON Observe request to server with
664 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
665 * Remove the callback associated on client side.
667 OCStackResult ret = OC_STACK_OK;
670 return OC_STACK_INVALID_PARAM;
673 OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
675 ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
678 switch (clientCB->method)
680 case OC_REST_OBSERVE:
681 case OC_REST_OBSERVE_ALL:
682 if(qos == OC_HIGH_QOS)
684 ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
685 &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
690 FindAndDeleteClientCB(clientCB);
694 case OC_REST_PRESENCE:
695 FindAndDeleteClientCB(clientCB);
699 return OC_STACK_INVALID_METHOD;
705 OCStackResult OCProcessPresence()
707 OCStackResult result = OC_STACK_OK;
708 uint8_t ipAddr[4] = { 0 };
711 OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
712 ClientCB* cbNode = NULL;
714 OCClientResponse clientResponse;
715 OCResponse * response = NULL;
717 LL_FOREACH(cbList, cbNode) {
718 if(OC_REST_PRESENCE == cbNode->method)
722 uint32_t now = GetTime(0);
723 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
724 OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
727 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
732 if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
733 OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
734 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
737 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
739 OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
740 if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
742 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
744 result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
745 (OCDevAddr *) &dst, 0, NULL);
746 if(result != OC_STACK_OK)
750 result = FormOCResponse(&response, cbNode, 0, &clientResponse);
751 if(result != OC_STACK_OK)
756 // Increment the TTLLevel (going to a next state), so we don't keep
757 // sending presence notification to client.
758 cbNode->presence->TTLlevel++;
759 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
760 cbNode->presence->TTLlevel);
764 result = OC_STACK_INVALID_IP;
767 HandleStackResponses(response);
769 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
771 OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
773 OCGenerateCoAPToken(&token);
774 result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
775 &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
776 if(result != OC_STACK_OK)
780 cbNode->presence->TTLlevel++;
781 OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
787 if (result != OC_STACK_OK)
789 OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
796 * Called in main loop of OC client or server. Allows low-level processing of
800 * OC_STACK_OK - no errors
801 * OC_STACK_ERROR - stack process error
803 OCStackResult OCProcess() {
805 OC_LOG(INFO, TAG, PCF("Entering OCProcess"));
816 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
817 * presence notifications to clients via multicast. Once this API has been called with a success,
818 * clients may query for this server's presence and this server's stack will respond via multicast.
820 * Server can call this function when it comes online for the first time, or when it comes back
821 * online from offline mode, or when it re enters network.
823 * @param ttl - Time To Live in seconds
824 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
827 * OC_STACK_OK - No errors; Success
829 OCStackResult OCStartPresence(const uint32_t ttl)
831 OCChangeResourceProperty(
832 &(((OCResource *)presenceResource.handle)->resourceProperties),
837 presenceResource.presenceTTL = ttl;
840 if(OC_PRESENCE_UNINITIALIZED == presenceState)
842 OCDevAddr multiCastAddr;
845 presenceState = OC_PRESENCE_INITIALIZED;
846 OCGenerateCoAPToken(&token);
847 OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
848 //add the presence observer
849 AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
850 (OCResource *)presenceResource.handle, OC_LOW_QOS);
853 // Each time OCStartPresence is called
854 // a different random 32-bit integer number is used
855 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
857 return SendPresenceNotification(NULL);
861 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
862 * presence notifications to clients via multicast. Once this API has been called with a success,
863 * this server's stack will not respond to clients querying for this server's presence.
865 * Server can call this function when it is terminating, going offline, or when going
869 * OC_STACK_OK - No errors; Success
871 OCStackResult OCStopPresence()
873 OCStackResult result = OC_STACK_ERROR;
874 //make resource inactive
875 result = OCChangeResourceProperty(
876 &(((OCResource *) presenceResource.handle)->resourceProperties),
878 result = SendPresenceNotification(NULL);
885 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
887 defaultDeviceHandler = entityHandler;
895 * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource
896 * @param resourceTypeName - name of resource type. Example: "core.led"
897 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
898 * @param uri - URI of the resource. Example: "/a/led"
899 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
900 * NULL for default entity handler
901 * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE
904 * OC_STACK_OK - no errors
905 * OC_STACK_ERROR - stack process error
907 OCStackResult OCCreateResource(OCResourceHandle *handle,
908 const char *resourceTypeName,
909 const char *resourceInterfaceName,
910 const char *uri, OCEntityHandler entityHandler,
911 uint8_t resourceProperties) {
913 OCResource *pointer = NULL;
916 OCStackResult result = OC_STACK_ERROR;
918 OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
920 if(myStackMode == OC_CLIENT)
924 // Validate parameters
925 // Is it presented during resource discovery?
926 if (!handle || !resourceTypeName || !uri) {
927 OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
928 return OC_STACK_INVALID_PARAM;
931 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
932 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
935 // Make sure resourceProperties bitmask has allowed properties specified
936 if (resourceProperties
937 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
938 OC_LOG(ERROR, TAG, PCF("Invalid property"));
939 return OC_STACK_INVALID_PARAM;
942 // If the headResource is NULL, then no resources have been created...
943 pointer = headResource;
945 // At least one resources is in the resource list, so we need to search for
946 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
948 if (strcmp(uri, pointer->uri) == 0) {
949 OC_LOG(ERROR, TAG, PCF("URI already in use"));
950 return OC_STACK_INVALID_PARAM;
952 pointer = pointer->next;
955 // Create the pointer and insert it into the resource list
956 pointer = (OCResource *) OCMalloc(sizeof(OCResource));
960 memset(pointer, 0, sizeof(OCResource));
961 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
963 insertResource(pointer);
966 size = strlen(uri) + 1;
967 str = (char *) OCMalloc(size);
971 strncpy(str, uri, size);
974 // Set properties. Set OC_ACTIVE
975 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
978 // Add the resourcetype to the resource
979 result = BindResourceTypeToResource(pointer, resourceTypeName);
980 if (result != OC_STACK_OK) {
981 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
985 // Add the resourceinterface to the resource
986 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
987 if (result != OC_STACK_OK) {
988 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
992 // If an entity handler has been passed, attach it to the newly created
993 // resource. Otherwise, set the default entity handler.
996 pointer->entityHandler = entityHandler;
1000 pointer->entityHandler = defaultResourceEHandler;
1004 result = OC_STACK_OK;
1006 #ifdef WITH_PRESENCE
1007 if(presenceResource.handle)
1009 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1010 SendPresenceNotification(pointer->rsrcType);
1014 if (result != OC_STACK_OK)
1016 // Deep delete of resource and other dynamic elements that it contains
1017 deleteResource(pointer);
1026 * Create a resource. with host ip address for remote resource
1028 * @param handle - pointer to handle to newly created resource. Set by ocstack.
1029 * Used to refer to resource
1030 * @param resourceTypeName - name of resource type. Example: "core.led"
1031 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1032 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
1033 * @param uri - URI of the resource. Example: "/a/led"
1034 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1035 * NULL for default entity handler
1036 * @param resourceProperties - properties supported by resource.
1037 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
1040 * OC_STACK_OK - no errors
1041 * OC_STACK_ERROR - stack process error
1044 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
1045 const char *resourceTypeName,
1046 const char *resourceInterfaceName,
1049 OCEntityHandler entityHandler,
1050 uint8_t resourceProperties)
1054 OCStackResult result = OC_STACK_ERROR;
1056 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
1057 uri, entityHandler, resourceProperties);
1059 if (result != OC_STACK_ERROR)
1062 size = strlen(host) + 1;
1063 str = (char *) OCMalloc(size);
1066 return OC_STACK_ERROR;
1068 strncpy(str, host, size);
1069 ((OCResource *) *handle)->host = str;
1076 * Add a resource to a collection resource.
1078 * @param collectionHandle - handle to the collection resource
1079 * @param resourceHandle - handle to resource to be added to the collection resource
1082 * OC_STACK_OK - no errors
1083 * OC_STACK_ERROR - stack process error
1084 * OC_STACK_INVALID_PARAM - invalid collectionhandle
1086 OCStackResult OCBindResource(
1087 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1088 OCResource *resource;
1091 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
1093 // Validate parameters
1094 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1095 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1096 // Container cannot contain itself
1097 if (collectionHandle == resourceHandle) {
1098 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
1099 return OC_STACK_INVALID_PARAM;
1102 // Use the handle to find the resource in the resource linked list
1103 resource = findResource((OCResource *) collectionHandle);
1105 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1106 return OC_STACK_INVALID_PARAM;
1109 // Look for an open slot to add add the child resource.
1110 // If found, add it and return success
1111 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1112 if (!resource->rsrcResources[i]) {
1113 resource->rsrcResources[i] = (OCResource *) resourceHandle;
1114 OC_LOG(INFO, TAG, PCF("resource bound"));
1119 #ifdef WITH_PRESENCE
1120 if(presenceResource.handle)
1122 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1123 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1127 // Unable to add resourceHandle, so return error
1128 return OC_STACK_ERROR;
1132 * Remove a resource from a collection resource.
1134 * @param collectionHandle - handle to the collection resource
1135 * @param resourceHandle - handle to resource to be added to the collection resource
1138 * OC_STACK_OK - no errors
1139 * OC_STACK_ERROR - stack process error
1140 * OC_STACK_INVALID_PARAM - invalid collectionHandle
1142 OCStackResult OCUnBindResource(
1143 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1144 OCResource *resource;
1147 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
1149 // Validate parameters
1150 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1151 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1152 // Container cannot contain itself
1153 if (collectionHandle == resourceHandle) {
1154 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
1155 return OC_STACK_INVALID_PARAM;
1158 // Use the handle to find the resource in the resource linked list
1159 resource = findResource((OCResource *) collectionHandle);
1161 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1162 return OC_STACK_INVALID_PARAM;
1165 // Look for an open slot to add add the child resource.
1166 // If found, add it and return success
1167 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1168 if (resourceHandle == resource->rsrcResources[i]) {
1169 resource->rsrcResources[i] = (OCResource *) NULL;
1170 OC_LOG(INFO, TAG, PCF("resource unbound"));
1175 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
1177 #ifdef WITH_PRESENCE
1178 if(presenceResource.handle)
1180 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1181 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1185 // Unable to add resourceHandle, so return error
1186 return OC_STACK_ERROR;
1189 OCStackResult BindResourceTypeToResource(OCResource* resource,
1190 const char *resourceTypeName)
1192 OCResourceType *pointer = NULL;
1195 OCStackResult result = OC_STACK_ERROR;
1197 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
1199 // Validate parameters
1200 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
1201 // TODO: Does resource attribute resentation really have to be maintained in stack?
1202 // Is it presented during resource discovery?
1204 TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
1206 // Create the resourcetype and insert it into the resource list
1207 pointer = (OCResourceType *) OCMalloc(sizeof(OCResourceType));
1211 memset(pointer, 0, sizeof(OCResourceType));
1213 // Set the resourceTypeName
1214 size = strlen(resourceTypeName) + 1;
1215 str = (char *) OCMalloc(size);
1219 strncpy(str, resourceTypeName, size);
1220 pointer->resourcetypename = str;
1222 insertResourceType(resource, pointer);
1223 result = OC_STACK_OK;
1225 exit: if (result != OC_STACK_OK) {
1233 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
1234 const char *resourceInterfaceName)
1236 OCResourceInterface *pointer = NULL;
1239 OCStackResult result = OC_STACK_ERROR;
1241 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
1243 // Validate parameters
1244 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
1246 TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
1248 // Create the resourceinterface and insert it into the resource list
1249 pointer = (OCResourceInterface *) OCMalloc(sizeof(OCResourceInterface));
1253 memset(pointer, 0, sizeof(OCResourceInterface));
1255 // Set the resourceinterface name
1256 size = strlen(resourceInterfaceName) + 1;
1257 str = (char *) OCMalloc(size);
1261 strncpy(str, resourceInterfaceName, size);
1262 pointer->name = str;
1264 // Bind the resourceinterface to the resource
1265 insertResourceInterface(resource, pointer);
1267 result = OC_STACK_OK;
1269 exit: if (result != OC_STACK_OK) {
1278 * Bind a resourcetype to a resource.
1280 * @param handle - handle to the resource
1281 * @param resourceTypeName - name of resource type. Example: "core.led"
1284 * OC_STACK_OK - no errors
1285 * OC_STACK_ERROR - stack process error
1287 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
1288 const char *resourceTypeName) {
1290 OCStackResult result = OC_STACK_ERROR;
1291 OCResource *resource;
1293 // Make sure resource exists
1294 resource = findResource((OCResource *) handle);
1296 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1297 return OC_STACK_ERROR;
1300 // call internal function
1301 result = BindResourceTypeToResource(resource, resourceTypeName);
1303 #ifdef WITH_PRESENCE
1304 if(presenceResource.handle)
1306 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1307 SendPresenceNotification(resource->rsrcType);
1315 * Bind a resourceinterface to a resource.
1317 * @param handle - handle to the resource
1318 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
1321 * OC_STACK_OK - no errors
1322 * OC_STACK_ERROR - stack process error
1325 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
1326 const char *resourceInterfaceName) {
1328 OCStackResult result = OC_STACK_ERROR;
1329 OCResource *resource;
1331 // Make sure resource exists
1332 resource = findResource((OCResource *) handle);
1334 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1335 return OC_STACK_ERROR;
1338 // call internal function
1339 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
1341 #ifdef WITH_PRESENCE
1342 if(presenceResource.handle)
1344 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1345 SendPresenceNotification(resource->rsrcType);
1353 * Get the number of resources that have been created in the stack.
1355 * @param numResources - pointer to count variable
1358 * OC_STACK_OK - no errors
1359 * OC_STACK_ERROR - stack process error
1362 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
1363 OCResource *pointer = headResource;
1365 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
1366 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
1369 *numResources = *numResources + 1;
1370 pointer = pointer->next;
1376 * Get a resource handle by index.
1378 * @param index - index of resource, 0 to Count - 1
1381 * Resource handle - if found
1382 * NULL - if not found
1384 OCResourceHandle OCGetResourceHandle(uint8_t index) {
1385 OCResource *pointer = headResource;
1388 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
1390 // Iterate through the list
1391 while ((i < index) && pointer) {
1393 pointer = pointer->next;
1395 return (OCResourceHandle) pointer;
1399 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
1402 * @param handle - handle of resource to be deleted
1405 * OC_STACK_OK - no errors
1406 * OC_STACK_ERROR - stack process error
1407 * OC_STACK_NO_RESOURCE - resource not found
1408 * OC_STACK_INVALID_PARAM - invalid param
1410 OCStackResult OCDeleteResource(OCResourceHandle handle) {
1411 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
1414 OC_LOG(ERROR, TAG, PCF("Invalid param"));
1415 return OC_STACK_INVALID_PARAM;
1418 OCResource *resource = findResource((OCResource *) handle);
1419 if (resource == NULL) {
1420 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1421 return OC_STACK_NO_RESOURCE;
1424 if (deleteResource((OCResource *) handle) == 0) {
1425 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
1426 return OC_STACK_ERROR;
1433 * Get the URI of the resource specified by handle.
1435 * @param handle - handle of resource
1437 * URI string - if resource found
1438 * NULL - resource not found
1440 const char *OCGetResourceUri(OCResourceHandle handle) {
1441 OCResource *resource;
1442 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
1444 resource = findResource((OCResource *) handle);
1446 return resource->uri;
1448 return (const char *) NULL;
1452 * Get the properties of the resource specified by handle.
1453 * NOTE: that after a resource is created, the OC_ACTIVE property is set
1454 * for the resource by the stack.
1456 * @param handle - handle of resource
1458 * property bitmap - if resource found
1459 * NULL - resource not found
1461 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
1462 OCResource *resource;
1463 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
1465 resource = findResource((OCResource *) handle);
1467 return resource->resourceProperties;
1473 * Get the number of resource types of the resource.
1475 * @param handle - handle of resource
1476 * @param numResourceTypes - pointer to count variable
1479 * OC_STACK_OK - no errors
1480 * OC_STACK_ERROR - stack process error
1482 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
1483 uint8_t *numResourceTypes) {
1484 OCResource *resource;
1485 OCResourceType *pointer;
1487 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
1488 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
1489 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
1491 *numResourceTypes = 0;
1493 resource = findResource((OCResource *) handle);
1495 pointer = resource->rsrcType;
1497 *numResourceTypes = *numResourceTypes + 1;
1498 pointer = pointer->next;
1505 * Get name of resource type of the resource.
1507 * @param handle - handle of resource
1508 * @param index - index of resource, 0 to Count - 1
1511 * resource type name - if resource found
1512 * NULL - resource not found
1514 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
1515 OCResourceType *resourceType;
1517 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
1519 resourceType = findResourceTypeAtIndex(handle, index);
1521 return resourceType->resourcetypename;
1523 return (const char *) NULL;
1529 * Get the number of resource interfaces of the resource.
1531 * @param handle - handle of resource
1532 * @param numResources - pointer to count variable
1535 * OC_STACK_OK - no errors
1536 * OC_STACK_ERROR - stack process error
1538 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
1539 uint8_t *numResourceInterfaces) {
1540 OCResourceInterface *pointer;
1541 OCResource *resource;
1543 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
1545 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
1546 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
1548 *numResourceInterfaces = 0;
1549 resource = findResource((OCResource *) handle);
1551 pointer = resource->rsrcInterface;
1553 *numResourceInterfaces = *numResourceInterfaces + 1;
1554 pointer = pointer->next;
1561 * Get name of resource interface of the resource.
1563 * @param handle - handle of resource
1564 * @param index - index of resource, 0 to Count - 1
1567 * resource interface name - if resource found
1568 * NULL - resource not found
1570 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
1571 OCResourceInterface *resourceInterface;
1573 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
1575 resourceInterface = findResourceInterfaceAtIndex(handle, index);
1576 if (resourceInterface) {
1577 return resourceInterface->name;
1579 return (const char *) NULL;
1583 * Get resource handle from the collection resource by index.
1585 * @param collectionHandle - handle of collection resource
1586 * @param index - index of contained resource, 0 to Count - 1
1589 * handle to resource - if resource found
1590 * NULL - resource not found
1592 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
1594 OCResource *resource;
1596 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
1598 if (index >= MAX_CONTAINED_RESOURCES) {
1602 resource = findResource((OCResource *) collectionHandle);
1607 return resource->rsrcResources[index];
1611 * Bind an entity handler to the resource.
1613 * @param handle - handle to the resource that the contained resource is to be bound
1614 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1616 * OC_STACK_OK - no errors
1617 * OC_STACK_ERROR - stack process error
1619 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
1620 OCEntityHandler entityHandler) {
1621 OCResource *resource;
1623 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
1625 // Validate parameters
1626 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
1627 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
1629 // Use the handle to find the resource in the resource linked list
1630 resource = findResource((OCResource *)handle);
1632 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1633 return OC_STACK_ERROR;
1637 resource->entityHandler = entityHandler;
1639 #ifdef WITH_PRESENCE
1640 if(presenceResource.handle)
1642 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1643 SendPresenceNotification(resource->rsrcType);
1651 * Get the entity handler for a resource.
1653 * @param handle - handle of resource
1656 * entity handler - if resource found
1657 * NULL - resource not found
1659 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
1660 OCResource *resource;
1662 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
1664 // Use the handle to find the resource in the resource linked list
1665 resource = findResource((OCResource *)handle);
1667 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1672 return resource->entityHandler;
1675 void incrementSequenceNumber(OCResource * resPtr)
1677 // Increment the sequence number
1678 resPtr->sequenceNum += 1;
1679 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
1681 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
1686 #ifdef WITH_PRESENCE
1688 * Notify Presence subscribers that a resource has been modified
1690 * @param resourceType - Handle to the resourceType linked list of resource
1691 * that was modified.
1692 * @param qos - Quality Of Service
1695 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
1697 OCResource *resPtr = NULL;
1698 OCStackResult result;
1699 OCMethod method = OC_REST_PRESENCE;
1700 uint32_t maxAge = 0;
1701 resPtr = findResource((OCResource *) presenceResource.handle);
1704 return OC_STACK_NO_RESOURCE;
1706 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
1708 maxAge = presenceResource.presenceTTL;
1715 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
1721 * Notify observers that an observed value has changed.
1723 * @param handle - handle of resource
1726 * OC_STACK_OK - no errors
1727 * OC_STACK_NO_RESOURCE - invalid resource handle
1728 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
1730 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
1732 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
1734 OCResource *resPtr = NULL;
1735 OCStackResult result;
1736 OCMethod method = OC_REST_NOMETHOD;
1737 uint32_t maxAge = 0;
1739 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
1740 // Verify that the resource exists
1741 resPtr = findResource ((OCResource *) handle);
1742 if (NULL == resPtr || myStackMode == OC_CLIENT)
1744 return OC_STACK_NO_RESOURCE;
1748 //only increment in the case of regular observing (not presence)
1749 incrementSequenceNumber(resPtr);
1750 method = OC_REST_OBSERVE;
1751 maxAge = MAX_OBSERVE_AGE;
1752 #ifdef WITH_PRESENCE
1753 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
1755 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
1762 OCNotifyListOfObservers (OCResourceHandle handle,
1763 OCObservationId *obsIdList,
1764 uint8_t numberOfIds,
1765 unsigned char *notificationJSONPayload,
1766 OCQualityOfService qos)
1768 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
1770 OCResource *resPtr = NULL;
1771 //TODO: we should allow the server to define this
1772 uint32_t maxAge = MAX_OBSERVE_AGE;
1774 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
1775 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
1776 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
1778 // Verify that the resource exists
1779 resPtr = findResource ((OCResource *) handle);
1780 if (NULL == resPtr || myStackMode == OC_CLIENT)
1782 return OC_STACK_NO_RESOURCE;
1786 incrementSequenceNumber(resPtr);
1788 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
1789 notificationJSONPayload, maxAge, qos));
1793 * Send a response to a request.
1794 * The response can be a regular, slow, or block (i.e. a response that
1795 * is too large to be sent in a single PDU and must span multiple transmissions)
1797 * @param response - pointer to structure that contains response parameters
1800 * OC_STACK_OK - No errors; Success
1801 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
1802 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
1803 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
1804 * persistent response buffer is necessary
1806 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
1808 OCStackResult result = OC_STACK_ERROR;
1809 OCServerRequest *serverRequest = NULL;
1811 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
1813 // Validate input parameters
1814 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
1815 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
1817 // TODO: Placeholder for creating a response entry when implementing
1818 // block transfer feature
1820 // If a response payload is present, check if block transfer is required
1821 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
1822 (const char *)ehResponse->payload, ehResponse->payloadSize))
1824 OC_LOG(INFO, TAG, PCF("Block transfer required"));
1826 // Persistent response buffer is needed for block transfer
1827 if (!ehResponse->persistentBufferFlag)
1829 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
1830 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
1832 // TODO: Placeholder for block transfer handling
1833 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
1834 // when implementing the block transfer feature
1840 // Get pointer to request info
1841 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
1844 result = serverRequest->ehResponseHandler(ehResponse);
1851 * Cancel a response. Applies to a block response
1853 * @param responseHandle - response handle set by stack in OCServerResponse after
1854 * OCDoResponse is called
1857 * OC_STACK_OK - No errors; Success
1858 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1860 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
1862 OCStackResult result = OC_STACK_NOTIMPL;
1864 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
1866 // TODO: validate response handle
1871 //-----------------------------------------------------------------------------
1872 // Private internal function definitions
1873 //-----------------------------------------------------------------------------
1875 * Generate handle of OCDoResource invocation for callback management.
1877 static OCDoHandle GenerateInvocationHandle()
1879 OCDoHandle handle = NULL;
1880 // Generate token here, it will be deleted when the transaction is deleted
1881 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
1884 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
1889 #ifdef WITH_PRESENCE
1890 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
1891 OCResourceProperty resourceProperties, uint8_t enable)
1893 if (resourceProperties
1894 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
1895 OC_LOG(ERROR, TAG, PCF("Invalid property"));
1896 return OC_STACK_INVALID_PARAM;
1900 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
1904 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
1911 * Initialize resource data structures, variables, etc.
1913 OCStackResult initResources() {
1914 OCStackResult result = OC_STACK_OK;
1915 // Init application resource vars
1916 headResource = NULL;
1917 // Init Virtual Resources
1918 #ifdef WITH_PRESENCE
1919 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
1920 //presenceResource.token = OCGenerateCoAPToken();
1921 result = OCCreateResource(&presenceResource.handle,
1927 //make resource inactive
1928 result = OCChangeResourceProperty(
1929 &(((OCResource *) presenceResource.handle)->resourceProperties),
1936 * Add a resource to the end of the linked list of resources.
1938 * @param resource - resource to be added
1940 void insertResource(OCResource *resource) {
1941 OCResource *pointer;
1943 if (!headResource) {
1944 headResource = resource;
1946 pointer = headResource;
1948 while (pointer->next) {
1949 pointer = pointer->next;
1951 pointer->next = resource;
1953 resource->next = NULL;
1957 * Find a resource in the linked list of resources.
1959 * @param resource - resource to be found
1961 * NULL - resource not found
1962 * pointer to resource - pointer to resource that was found in the linked list
1964 OCResource *findResource(OCResource *resource) {
1965 OCResource *pointer = headResource;
1968 if (pointer == resource) {
1971 pointer = pointer->next;
1976 void deleteAllResources()
1978 OCResource *pointer = headResource;
1983 temp = pointer->next;
1984 deleteResource(pointer);
1990 * Delete the resource from the linked list.
1992 * @param resource - resource to be deleted
1997 int deleteResource(OCResource *resource) {
1998 OCResource *prev = NULL;
2001 temp = headResource;
2003 if (temp == resource) {
2004 // Invalidate all Resource Properties.
2005 resource->resourceProperties = (OCResourceProperty) 0;
2006 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
2008 #ifdef WITH_PRESENCE
2009 if(presenceResource.handle)
2011 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2012 SendPresenceNotification(resource->rsrcType);
2016 if (temp == headResource) {
2017 headResource = temp->next;
2019 prev->next = temp->next;
2022 deleteResourceElements(temp);
2035 * Delete all of the dynamically allocated elements that were created for the resource.
2037 * @param resource - specified resource
2039 void deleteResourceElements(OCResource *resource) {
2045 OCFree(resource->uri);
2047 // Delete resourcetype linked list
2048 deleteResourceType(resource->rsrcType);
2050 // Delete resourceinterface linked list
2051 deleteResourceInterface(resource->rsrcInterface);
2055 * Delete all of the dynamically allocated elements that were created for the resource type.
2057 * @param resourceType - specified resource type
2059 void deleteResourceType(OCResourceType *resourceType) {
2060 OCResourceType *pointer = resourceType;
2061 OCResourceType *next;
2064 next = pointer->next;
2065 OCFree(pointer->resourcetypename);
2072 * Delete all of the dynamically allocated elements that were created for the resource interface.
2074 * @param resourceInterface - specified resource interface
2076 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
2077 OCResourceInterface *pointer = resourceInterface;
2078 OCResourceInterface *next;
2081 next = pointer->next;
2082 OCFree(pointer->name);
2089 * Insert a resource type into a resource's resource type linked list.
2091 * @param resource - resource where resource type is to be inserted
2092 * @param resourceType - resource type to be inserted
2094 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
2095 OCResourceType *pointer;
2097 if (resource && !resource->rsrcType) {
2098 resource->rsrcType = resourceType;
2102 pointer = resource->rsrcType;
2106 pointer = resourceType;
2108 while (pointer->next) {
2109 pointer = pointer->next;
2111 pointer->next = resourceType;
2113 resourceType->next = NULL;
2117 * Get a resource type at the specified index within a resource.
2119 * @param handle - handle of resource
2120 * @param index - index of resource type
2123 * resourcetype - if found
2126 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
2127 OCResource *resource;
2128 OCResourceType *pointer;
2131 // Find the specified resource
2132 resource = findResource((OCResource *) handle);
2137 // Make sure a resource has a resourcetype
2138 if (!resource->rsrcType) {
2142 // Iterate through the list
2143 pointer = resource->rsrcType;
2145 while ((i < index) && pointer) {
2147 pointer = pointer->next;
2153 * Insert a resource interface into a resource's resource interface linked list.
2155 * @param resource - resource where resource interface is to be inserted
2156 * @param resourceInterface - resource interface to be inserted
2158 void insertResourceInterface(OCResource *resource,
2159 OCResourceInterface *resourceInterface) {
2160 OCResourceInterface *pointer;
2162 if (!resource->rsrcInterface) {
2163 resource->rsrcInterface = resourceInterface;
2165 pointer = resource->rsrcInterface;
2166 while (pointer->next) {
2167 pointer = pointer->next;
2169 pointer->next = resourceInterface;
2171 resourceInterface->next = NULL;
2175 * Get a resource interface at the specified index within a resource.
2177 * @param handle - handle of resource
2178 * @param index - index of resource interface
2181 * resourceinterface - if found
2184 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
2186 OCResource *resource;
2187 OCResourceInterface *pointer;
2190 // Find the specified resource
2191 resource = findResource((OCResource *) handle);
2196 // Make sure a resource has a resourceinterface
2197 if (!resource->rsrcInterface) {
2201 // Iterate through the list
2202 pointer = resource->rsrcInterface;
2204 while ((i < index) && pointer) {
2206 pointer = pointer->next;
2212 * Determine if a request/response must be sent in a block transfer because it is too large to be
2213 * sent in a single PDU. This function can be used for either a request or a response
2215 * @param request - NULL or pointer to request
2216 * @param response - NULL or pointer to response
2217 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
2218 * the length of the request/response
2221 * 0 - packet transfer NOT required (i.e. normal request/response)
2222 * 1 - packet transfer required (i.e. block transfer needed)
2224 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
2228 // Determine if we are checking a request or a response
2231 // If size is greater than 0, use it for the request size value, otherwise
2232 // assume request is null terminated and use strlen for size value
2233 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
2240 // If size is greater than 0, use it for the response size value, otherwise
2241 // assume response is null terminated and use strlen for size value
2242 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
2251 * Retrieves a resource type based upon a uri string if the uri string contains only just one
2252 * resource attribute (and that has to be of type "rt").
2254 * @remark This API malloc's memory for the resource type and newURI. Do not malloc resourceType
2255 * or newURI before passing in.
2257 * @param uri - Valid URI for "requiredUri" parameter to OCDoResource API.
2258 * @param resourceType - The resource type to be populated; pass by reference.
2259 * @param newURI - Return URI without resourceType appended to the end of it. This is used to
2260 * ensure that the uri parameter is not modified; pass by reference.
2263 * OC_STACK_INVALID_URI - Returns this if the URI is invalid/NULL.
2264 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
2265 * OC_STACK_OK - Success
2267 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI)
2271 return OC_STACK_INVALID_URI;
2273 if(!resourceType || !newURI)
2275 return OC_STACK_INVALID_PARAM;
2278 char * leftToken = NULL;
2279 char * tempURI = (char *) OCMalloc(strlen(uri));
2285 strcpy(tempURI, uri);
2286 leftToken = strtok((char *)tempURI, "?");
2288 while(leftToken != NULL)
2290 if(strncmp(leftToken, "rt=", 3) == 0)
2292 *resourceType = (unsigned char *) OCMalloc(strlen(leftToken)-3);
2297 strcpy((char *)*resourceType, ((const char *)&leftToken[3]));
2300 leftToken = strtok(NULL, "?");
2308 return OC_STACK_NO_MEMORY;