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 *) OCCalloc(1, sizeof(OCResource));
960 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
962 insertResource(pointer);
965 size = strlen(uri) + 1;
966 str = (char *) OCMalloc(size);
970 strncpy(str, uri, size);
973 // Set properties. Set OC_ACTIVE
974 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
977 // Add the resourcetype to the resource
978 result = BindResourceTypeToResource(pointer, resourceTypeName);
979 if (result != OC_STACK_OK) {
980 OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
984 // Add the resourceinterface to the resource
985 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
986 if (result != OC_STACK_OK) {
987 OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
991 // If an entity handler has been passed, attach it to the newly created
992 // resource. Otherwise, set the default entity handler.
995 pointer->entityHandler = entityHandler;
999 pointer->entityHandler = defaultResourceEHandler;
1003 result = OC_STACK_OK;
1005 #ifdef WITH_PRESENCE
1006 if(presenceResource.handle)
1008 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1009 SendPresenceNotification(pointer->rsrcType);
1013 if (result != OC_STACK_OK)
1015 // Deep delete of resource and other dynamic elements that it contains
1016 deleteResource(pointer);
1025 * Create a resource. with host ip address for remote resource
1027 * @param handle - pointer to handle to newly created resource. Set by ocstack.
1028 * Used to refer to resource
1029 * @param resourceTypeName - name of resource type. Example: "core.led"
1030 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
1031 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
1032 * @param uri - URI of the resource. Example: "/a/led"
1033 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1034 * NULL for default entity handler
1035 * @param resourceProperties - properties supported by resource.
1036 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
1039 * OC_STACK_OK - no errors
1040 * OC_STACK_ERROR - stack process error
1043 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
1044 const char *resourceTypeName,
1045 const char *resourceInterfaceName,
1048 OCEntityHandler entityHandler,
1049 uint8_t resourceProperties)
1053 OCStackResult result = OC_STACK_ERROR;
1055 result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
1056 uri, entityHandler, resourceProperties);
1058 if (result != OC_STACK_ERROR)
1061 size = strlen(host) + 1;
1062 str = (char *) OCMalloc(size);
1065 return OC_STACK_ERROR;
1067 strncpy(str, host, size);
1068 ((OCResource *) *handle)->host = str;
1075 * Add a resource to a collection resource.
1077 * @param collectionHandle - handle to the collection resource
1078 * @param resourceHandle - handle to resource to be added to the collection resource
1081 * OC_STACK_OK - no errors
1082 * OC_STACK_ERROR - stack process error
1083 * OC_STACK_INVALID_PARAM - invalid collectionhandle
1085 OCStackResult OCBindResource(
1086 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1087 OCResource *resource;
1090 OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
1092 // Validate parameters
1093 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1094 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1095 // Container cannot contain itself
1096 if (collectionHandle == resourceHandle) {
1097 OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
1098 return OC_STACK_INVALID_PARAM;
1101 // Use the handle to find the resource in the resource linked list
1102 resource = findResource((OCResource *) collectionHandle);
1104 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1105 return OC_STACK_INVALID_PARAM;
1108 // Look for an open slot to add add the child resource.
1109 // If found, add it and return success
1110 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1111 if (!resource->rsrcResources[i]) {
1112 resource->rsrcResources[i] = (OCResource *) resourceHandle;
1113 OC_LOG(INFO, TAG, PCF("resource bound"));
1118 #ifdef WITH_PRESENCE
1119 if(presenceResource.handle)
1121 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1122 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1126 // Unable to add resourceHandle, so return error
1127 return OC_STACK_ERROR;
1131 * Remove a resource from a collection resource.
1133 * @param collectionHandle - handle to the collection resource
1134 * @param resourceHandle - handle to resource to be added to the collection resource
1137 * OC_STACK_OK - no errors
1138 * OC_STACK_ERROR - stack process error
1139 * OC_STACK_INVALID_PARAM - invalid collectionHandle
1141 OCStackResult OCUnBindResource(
1142 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
1143 OCResource *resource;
1146 OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
1148 // Validate parameters
1149 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
1150 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
1151 // Container cannot contain itself
1152 if (collectionHandle == resourceHandle) {
1153 OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
1154 return OC_STACK_INVALID_PARAM;
1157 // Use the handle to find the resource in the resource linked list
1158 resource = findResource((OCResource *) collectionHandle);
1160 OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
1161 return OC_STACK_INVALID_PARAM;
1164 // Look for an open slot to add add the child resource.
1165 // If found, add it and return success
1166 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
1167 if (resourceHandle == resource->rsrcResources[i]) {
1168 resource->rsrcResources[i] = (OCResource *) NULL;
1169 OC_LOG(INFO, TAG, PCF("resource unbound"));
1174 OC_LOG(INFO, TAG, PCF("resource not found in collection"));
1176 #ifdef WITH_PRESENCE
1177 if(presenceResource.handle)
1179 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1180 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
1184 // Unable to add resourceHandle, so return error
1185 return OC_STACK_ERROR;
1188 OCStackResult BindResourceTypeToResource(OCResource* resource,
1189 const char *resourceTypeName)
1191 OCResourceType *pointer = NULL;
1194 OCStackResult result = OC_STACK_ERROR;
1196 OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
1198 // Validate parameters
1199 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
1200 // TODO: Does resource attribute resentation really have to be maintained in stack?
1201 // Is it presented during resource discovery?
1203 TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
1205 // Create the resourcetype and insert it into the resource list
1206 pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
1211 // Set the resourceTypeName
1212 size = strlen(resourceTypeName) + 1;
1213 str = (char *) OCMalloc(size);
1217 strncpy(str, resourceTypeName, size);
1218 pointer->resourcetypename = str;
1220 insertResourceType(resource, pointer);
1221 result = OC_STACK_OK;
1223 exit: if (result != OC_STACK_OK) {
1231 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
1232 const char *resourceInterfaceName)
1234 OCResourceInterface *pointer = NULL;
1237 OCStackResult result = OC_STACK_ERROR;
1239 OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
1241 // Validate parameters
1242 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
1244 TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
1246 // Create the resourceinterface and insert it into the resource list
1247 pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
1252 // Set the resourceinterface name
1253 size = strlen(resourceInterfaceName) + 1;
1254 str = (char *) OCMalloc(size);
1258 strncpy(str, resourceInterfaceName, size);
1259 pointer->name = str;
1261 // Bind the resourceinterface to the resource
1262 insertResourceInterface(resource, pointer);
1264 result = OC_STACK_OK;
1266 exit: if (result != OC_STACK_OK) {
1275 * Bind a resourcetype to a resource.
1277 * @param handle - handle to the resource
1278 * @param resourceTypeName - name of resource type. Example: "core.led"
1281 * OC_STACK_OK - no errors
1282 * OC_STACK_ERROR - stack process error
1284 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
1285 const char *resourceTypeName) {
1287 OCStackResult result = OC_STACK_ERROR;
1288 OCResource *resource;
1290 // Make sure resource exists
1291 resource = findResource((OCResource *) handle);
1293 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1294 return OC_STACK_ERROR;
1297 // call internal function
1298 result = BindResourceTypeToResource(resource, resourceTypeName);
1300 #ifdef WITH_PRESENCE
1301 if(presenceResource.handle)
1303 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1304 SendPresenceNotification(resource->rsrcType);
1312 * Bind a resourceinterface to a resource.
1314 * @param handle - handle to the resource
1315 * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b"
1318 * OC_STACK_OK - no errors
1319 * OC_STACK_ERROR - stack process error
1322 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
1323 const char *resourceInterfaceName) {
1325 OCStackResult result = OC_STACK_ERROR;
1326 OCResource *resource;
1328 // Make sure resource exists
1329 resource = findResource((OCResource *) handle);
1331 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1332 return OC_STACK_ERROR;
1335 // call internal function
1336 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
1338 #ifdef WITH_PRESENCE
1339 if(presenceResource.handle)
1341 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1342 SendPresenceNotification(resource->rsrcType);
1350 * Get the number of resources that have been created in the stack.
1352 * @param numResources - pointer to count variable
1355 * OC_STACK_OK - no errors
1356 * OC_STACK_ERROR - stack process error
1359 OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
1360 OCResource *pointer = headResource;
1362 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
1363 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
1366 *numResources = *numResources + 1;
1367 pointer = pointer->next;
1373 * Get a resource handle by index.
1375 * @param index - index of resource, 0 to Count - 1
1378 * Resource handle - if found
1379 * NULL - if not found
1381 OCResourceHandle OCGetResourceHandle(uint8_t index) {
1382 OCResource *pointer = headResource;
1385 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
1387 // Iterate through the list
1388 while ((i < index) && pointer) {
1390 pointer = pointer->next;
1392 return (OCResourceHandle) pointer;
1396 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
1399 * @param handle - handle of resource to be deleted
1402 * OC_STACK_OK - no errors
1403 * OC_STACK_ERROR - stack process error
1404 * OC_STACK_NO_RESOURCE - resource not found
1405 * OC_STACK_INVALID_PARAM - invalid param
1407 OCStackResult OCDeleteResource(OCResourceHandle handle) {
1408 OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
1411 OC_LOG(ERROR, TAG, PCF("Invalid param"));
1412 return OC_STACK_INVALID_PARAM;
1415 OCResource *resource = findResource((OCResource *) handle);
1416 if (resource == NULL) {
1417 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1418 return OC_STACK_NO_RESOURCE;
1421 if (deleteResource((OCResource *) handle) == 0) {
1422 OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
1423 return OC_STACK_ERROR;
1430 * Get the URI of the resource specified by handle.
1432 * @param handle - handle of resource
1434 * URI string - if resource found
1435 * NULL - resource not found
1437 const char *OCGetResourceUri(OCResourceHandle handle) {
1438 OCResource *resource;
1439 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
1441 resource = findResource((OCResource *) handle);
1443 return resource->uri;
1445 return (const char *) NULL;
1449 * Get the properties of the resource specified by handle.
1450 * NOTE: that after a resource is created, the OC_ACTIVE property is set
1451 * for the resource by the stack.
1453 * @param handle - handle of resource
1455 * property bitmap - if resource found
1456 * NULL - resource not found
1458 uint8_t OCGetResourceProperties(OCResourceHandle handle) {
1459 OCResource *resource;
1460 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
1462 resource = findResource((OCResource *) handle);
1464 return resource->resourceProperties;
1470 * Get the number of resource types of the resource.
1472 * @param handle - handle of resource
1473 * @param numResourceTypes - pointer to count variable
1476 * OC_STACK_OK - no errors
1477 * OC_STACK_ERROR - stack process error
1479 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
1480 uint8_t *numResourceTypes) {
1481 OCResource *resource;
1482 OCResourceType *pointer;
1484 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
1485 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
1486 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
1488 *numResourceTypes = 0;
1490 resource = findResource((OCResource *) handle);
1492 pointer = resource->rsrcType;
1494 *numResourceTypes = *numResourceTypes + 1;
1495 pointer = pointer->next;
1502 * Get name of resource type of the resource.
1504 * @param handle - handle of resource
1505 * @param index - index of resource, 0 to Count - 1
1508 * resource type name - if resource found
1509 * NULL - resource not found
1511 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
1512 OCResourceType *resourceType;
1514 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
1516 resourceType = findResourceTypeAtIndex(handle, index);
1518 return resourceType->resourcetypename;
1520 return (const char *) NULL;
1526 * Get the number of resource interfaces of the resource.
1528 * @param handle - handle of resource
1529 * @param numResources - pointer to count variable
1532 * OC_STACK_OK - no errors
1533 * OC_STACK_ERROR - stack process error
1535 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
1536 uint8_t *numResourceInterfaces) {
1537 OCResourceInterface *pointer;
1538 OCResource *resource;
1540 OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
1542 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
1543 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
1545 *numResourceInterfaces = 0;
1546 resource = findResource((OCResource *) handle);
1548 pointer = resource->rsrcInterface;
1550 *numResourceInterfaces = *numResourceInterfaces + 1;
1551 pointer = pointer->next;
1558 * Get name of resource interface of the resource.
1560 * @param handle - handle of resource
1561 * @param index - index of resource, 0 to Count - 1
1564 * resource interface name - if resource found
1565 * NULL - resource not found
1567 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
1568 OCResourceInterface *resourceInterface;
1570 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
1572 resourceInterface = findResourceInterfaceAtIndex(handle, index);
1573 if (resourceInterface) {
1574 return resourceInterface->name;
1576 return (const char *) NULL;
1580 * Get resource handle from the collection resource by index.
1582 * @param collectionHandle - handle of collection resource
1583 * @param index - index of contained resource, 0 to Count - 1
1586 * handle to resource - if resource found
1587 * NULL - resource not found
1589 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
1591 OCResource *resource;
1593 OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
1595 if (index >= MAX_CONTAINED_RESOURCES) {
1599 resource = findResource((OCResource *) collectionHandle);
1604 return resource->rsrcResources[index];
1608 * Bind an entity handler to the resource.
1610 * @param handle - handle to the resource that the contained resource is to be bound
1611 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
1613 * OC_STACK_OK - no errors
1614 * OC_STACK_ERROR - stack process error
1616 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
1617 OCEntityHandler entityHandler) {
1618 OCResource *resource;
1620 OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
1622 // Validate parameters
1623 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
1624 //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
1626 // Use the handle to find the resource in the resource linked list
1627 resource = findResource((OCResource *)handle);
1629 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1630 return OC_STACK_ERROR;
1634 resource->entityHandler = entityHandler;
1636 #ifdef WITH_PRESENCE
1637 if(presenceResource.handle)
1639 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
1640 SendPresenceNotification(resource->rsrcType);
1648 * Get the entity handler for a resource.
1650 * @param handle - handle of resource
1653 * entity handler - if resource found
1654 * NULL - resource not found
1656 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
1657 OCResource *resource;
1659 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
1661 // Use the handle to find the resource in the resource linked list
1662 resource = findResource((OCResource *)handle);
1664 OC_LOG(ERROR, TAG, PCF("Resource not found"));
1669 return resource->entityHandler;
1672 void incrementSequenceNumber(OCResource * resPtr)
1674 // Increment the sequence number
1675 resPtr->sequenceNum += 1;
1676 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
1678 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
1683 #ifdef WITH_PRESENCE
1685 * Notify Presence subscribers that a resource has been modified
1687 * @param resourceType - Handle to the resourceType linked list of resource
1688 * that was modified.
1689 * @param qos - Quality Of Service
1692 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
1694 OCResource *resPtr = NULL;
1695 OCStackResult result;
1696 OCMethod method = OC_REST_PRESENCE;
1697 uint32_t maxAge = 0;
1698 resPtr = findResource((OCResource *) presenceResource.handle);
1701 return OC_STACK_NO_RESOURCE;
1703 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
1705 maxAge = presenceResource.presenceTTL;
1712 result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
1718 * Notify observers that an observed value has changed.
1720 * @param handle - handle of resource
1723 * OC_STACK_OK - no errors
1724 * OC_STACK_NO_RESOURCE - invalid resource handle
1725 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
1727 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
1729 OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
1731 OCResource *resPtr = NULL;
1732 OCStackResult result;
1733 OCMethod method = OC_REST_NOMETHOD;
1734 uint32_t maxAge = 0;
1736 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
1737 // Verify that the resource exists
1738 resPtr = findResource ((OCResource *) handle);
1739 if (NULL == resPtr || myStackMode == OC_CLIENT)
1741 return OC_STACK_NO_RESOURCE;
1745 //only increment in the case of regular observing (not presence)
1746 incrementSequenceNumber(resPtr);
1747 method = OC_REST_OBSERVE;
1748 maxAge = MAX_OBSERVE_AGE;
1749 #ifdef WITH_PRESENCE
1750 result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos);
1752 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
1759 OCNotifyListOfObservers (OCResourceHandle handle,
1760 OCObservationId *obsIdList,
1761 uint8_t numberOfIds,
1762 unsigned char *notificationJSONPayload,
1763 OCQualityOfService qos)
1765 OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
1767 OCResource *resPtr = NULL;
1768 //TODO: we should allow the server to define this
1769 uint32_t maxAge = MAX_OBSERVE_AGE;
1771 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
1772 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
1773 VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR);
1775 // Verify that the resource exists
1776 resPtr = findResource ((OCResource *) handle);
1777 if (NULL == resPtr || myStackMode == OC_CLIENT)
1779 return OC_STACK_NO_RESOURCE;
1783 incrementSequenceNumber(resPtr);
1785 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
1786 notificationJSONPayload, maxAge, qos));
1790 * Send a response to a request.
1791 * The response can be a regular, slow, or block (i.e. a response that
1792 * is too large to be sent in a single PDU and must span multiple transmissions)
1794 * @param response - pointer to structure that contains response parameters
1797 * OC_STACK_OK - No errors; Success
1798 * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse
1799 * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found
1800 * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
1801 * persistent response buffer is necessary
1803 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
1805 OCStackResult result = OC_STACK_ERROR;
1806 OCServerRequest *serverRequest = NULL;
1808 OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
1810 // Validate input parameters
1811 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
1812 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
1814 // TODO: Placeholder for creating a response entry when implementing
1815 // block transfer feature
1817 // If a response payload is present, check if block transfer is required
1818 if (ehResponse->payload && OCIsPacketTransferRequired(NULL,
1819 (const char *)ehResponse->payload, ehResponse->payloadSize))
1821 OC_LOG(INFO, TAG, PCF("Block transfer required"));
1823 // Persistent response buffer is needed for block transfer
1824 if (!ehResponse->persistentBufferFlag)
1826 OC_LOG(WARNING, TAG, PCF("Persistent response buffer required"));
1827 return OC_STACK_PERSISTENT_BUFFER_REQUIRED;
1829 // TODO: Placeholder for block transfer handling
1830 // TODO: Placeholder for setting the the response handle in the OCServerResponse struct
1831 // when implementing the block transfer feature
1837 // Get pointer to request info
1838 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
1841 result = serverRequest->ehResponseHandler(ehResponse);
1848 * Cancel a response. Applies to a block response
1850 * @param responseHandle - response handle set by stack in OCServerResponse after
1851 * OCDoResponse is called
1854 * OC_STACK_OK - No errors; Success
1855 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
1857 OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
1859 OCStackResult result = OC_STACK_NOTIMPL;
1861 OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
1863 // TODO: validate response handle
1868 //-----------------------------------------------------------------------------
1869 // Private internal function definitions
1870 //-----------------------------------------------------------------------------
1872 * Generate handle of OCDoResource invocation for callback management.
1874 static OCDoHandle GenerateInvocationHandle()
1876 OCDoHandle handle = NULL;
1877 // Generate token here, it will be deleted when the transaction is deleted
1878 handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
1881 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
1886 #ifdef WITH_PRESENCE
1887 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
1888 OCResourceProperty resourceProperties, uint8_t enable)
1890 if (resourceProperties
1891 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
1892 OC_LOG(ERROR, TAG, PCF("Invalid property"));
1893 return OC_STACK_INVALID_PARAM;
1897 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
1901 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
1908 * Initialize resource data structures, variables, etc.
1910 OCStackResult initResources() {
1911 OCStackResult result = OC_STACK_OK;
1912 // Init application resource vars
1913 headResource = NULL;
1914 // Init Virtual Resources
1915 #ifdef WITH_PRESENCE
1916 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
1917 //presenceResource.token = OCGenerateCoAPToken();
1918 result = OCCreateResource(&presenceResource.handle,
1924 //make resource inactive
1925 result = OCChangeResourceProperty(
1926 &(((OCResource *) presenceResource.handle)->resourceProperties),
1933 * Add a resource to the end of the linked list of resources.
1935 * @param resource - resource to be added
1937 void insertResource(OCResource *resource) {
1938 OCResource *pointer;
1940 if (!headResource) {
1941 headResource = resource;
1943 pointer = headResource;
1945 while (pointer->next) {
1946 pointer = pointer->next;
1948 pointer->next = resource;
1950 resource->next = NULL;
1954 * Find a resource in the linked list of resources.
1956 * @param resource - resource to be found
1958 * NULL - resource not found
1959 * pointer to resource - pointer to resource that was found in the linked list
1961 OCResource *findResource(OCResource *resource) {
1962 OCResource *pointer = headResource;
1965 if (pointer == resource) {
1968 pointer = pointer->next;
1973 void deleteAllResources()
1975 OCResource *pointer = headResource;
1980 temp = pointer->next;
1981 deleteResource(pointer);
1987 * Delete the resource from the linked list.
1989 * @param resource - resource to be deleted
1994 int deleteResource(OCResource *resource) {
1995 OCResource *prev = NULL;
1998 temp = headResource;
2000 if (temp == resource) {
2001 // Invalidate all Resource Properties.
2002 resource->resourceProperties = (OCResourceProperty) 0;
2003 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
2005 #ifdef WITH_PRESENCE
2006 if(presenceResource.handle)
2008 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2009 SendPresenceNotification(resource->rsrcType);
2013 if (temp == headResource) {
2014 headResource = temp->next;
2016 prev->next = temp->next;
2019 deleteResourceElements(temp);
2032 * Delete all of the dynamically allocated elements that were created for the resource.
2034 * @param resource - specified resource
2036 void deleteResourceElements(OCResource *resource) {
2042 OCFree(resource->uri);
2044 // Delete resourcetype linked list
2045 deleteResourceType(resource->rsrcType);
2047 // Delete resourceinterface linked list
2048 deleteResourceInterface(resource->rsrcInterface);
2052 * Delete all of the dynamically allocated elements that were created for the resource type.
2054 * @param resourceType - specified resource type
2056 void deleteResourceType(OCResourceType *resourceType) {
2057 OCResourceType *pointer = resourceType;
2058 OCResourceType *next;
2061 next = pointer->next;
2062 OCFree(pointer->resourcetypename);
2069 * Delete all of the dynamically allocated elements that were created for the resource interface.
2071 * @param resourceInterface - specified resource interface
2073 void deleteResourceInterface(OCResourceInterface *resourceInterface) {
2074 OCResourceInterface *pointer = resourceInterface;
2075 OCResourceInterface *next;
2078 next = pointer->next;
2079 OCFree(pointer->name);
2086 * Insert a resource type into a resource's resource type linked list.
2088 * @param resource - resource where resource type is to be inserted
2089 * @param resourceType - resource type to be inserted
2091 void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
2092 OCResourceType *pointer;
2094 if (resource && !resource->rsrcType) {
2095 resource->rsrcType = resourceType;
2099 pointer = resource->rsrcType;
2103 pointer = resourceType;
2105 while (pointer->next) {
2106 pointer = pointer->next;
2108 pointer->next = resourceType;
2110 resourceType->next = NULL;
2114 * Get a resource type at the specified index within a resource.
2116 * @param handle - handle of resource
2117 * @param index - index of resource type
2120 * resourcetype - if found
2123 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
2124 OCResource *resource;
2125 OCResourceType *pointer;
2128 // Find the specified resource
2129 resource = findResource((OCResource *) handle);
2134 // Make sure a resource has a resourcetype
2135 if (!resource->rsrcType) {
2139 // Iterate through the list
2140 pointer = resource->rsrcType;
2142 while ((i < index) && pointer) {
2144 pointer = pointer->next;
2150 * Insert a resource interface into a resource's resource interface linked list.
2152 * @param resource - resource where resource interface is to be inserted
2153 * @param resourceInterface - resource interface to be inserted
2155 void insertResourceInterface(OCResource *resource,
2156 OCResourceInterface *resourceInterface) {
2157 OCResourceInterface *pointer;
2159 if (!resource->rsrcInterface) {
2160 resource->rsrcInterface = resourceInterface;
2162 pointer = resource->rsrcInterface;
2163 while (pointer->next) {
2164 pointer = pointer->next;
2166 pointer->next = resourceInterface;
2168 resourceInterface->next = NULL;
2172 * Get a resource interface at the specified index within a resource.
2174 * @param handle - handle of resource
2175 * @param index - index of resource interface
2178 * resourceinterface - if found
2181 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
2183 OCResource *resource;
2184 OCResourceInterface *pointer;
2187 // Find the specified resource
2188 resource = findResource((OCResource *) handle);
2193 // Make sure a resource has a resourceinterface
2194 if (!resource->rsrcInterface) {
2198 // Iterate through the list
2199 pointer = resource->rsrcInterface;
2201 while ((i < index) && pointer) {
2203 pointer = pointer->next;
2209 * Determine if a request/response must be sent in a block transfer because it is too large to be
2210 * sent in a single PDU. This function can be used for either a request or a response
2212 * @param request - NULL or pointer to request
2213 * @param response - NULL or pointer to response
2214 * @param size - 0 or size of the request/response. If 0, strlen is used for determining
2215 * the length of the request/response
2218 * 0 - packet transfer NOT required (i.e. normal request/response)
2219 * 1 - packet transfer required (i.e. block transfer needed)
2221 uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
2225 // Determine if we are checking a request or a response
2228 // If size is greater than 0, use it for the request size value, otherwise
2229 // assume request is null terminated and use strlen for size value
2230 if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
2237 // If size is greater than 0, use it for the response size value, otherwise
2238 // assume response is null terminated and use strlen for size value
2239 if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
2248 * Retrieves a resource type based upon a uri string if the uri string contains only just one
2249 * resource attribute (and that has to be of type "rt").
2251 * @remark This API malloc's memory for the resource type and newURI. Do not malloc resourceType
2252 * or newURI before passing in.
2254 * @param uri - Valid URI for "requiredUri" parameter to OCDoResource API.
2255 * @param resourceType - The resource type to be populated; pass by reference.
2256 * @param newURI - Return URI without resourceType appended to the end of it. This is used to
2257 * ensure that the uri parameter is not modified; pass by reference.
2260 * OC_STACK_INVALID_URI - Returns this if the URI is invalid/NULL.
2261 * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
2262 * OC_STACK_OK - Success
2264 OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI)
2268 return OC_STACK_INVALID_URI;
2270 if(!resourceType || !newURI)
2272 return OC_STACK_INVALID_PARAM;
2275 char * leftToken = NULL;
2276 char * tempURI = (char *) OCMalloc(strlen(uri));
2282 strcpy(tempURI, uri);
2283 leftToken = strtok((char *)tempURI, "?");
2285 while(leftToken != NULL)
2287 if(strncmp(leftToken, "rt=", 3) == 0)
2289 *resourceType = (unsigned char *) OCMalloc(strlen(leftToken)-3);
2294 strcpy((char *)*resourceType, ((const char *)&leftToken[3]));
2297 leftToken = strtok(NULL, "?");
2305 return OC_STACK_NO_MEMORY;