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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
23 #include "ocstackconfig.h"
24 #include "ocstackinternal.h"
25 #include "ocobserve.h"
26 #include "ocresourcehandler.h"
28 #include "oic_malloc.h"
29 #include "oic_string.h"
30 #include "ocpayload.h"
31 #include "ocserverrequest.h"
34 #include <coap/utlist.h>
36 #include <coap/coap.h>
39 #define MOD_NAME "ocobserve"
41 #define TAG "OIC_RI_OBSERVE"
43 #define VERIFY_NON_NULL(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL"); goto exit;} }
45 static struct ResourceObserver * g_serverObsList = NULL;
47 * Determine observe QOS based on the QOS of the request.
48 * The qos passed as a parameter overrides what the client requested.
49 * If we want the client preference taking high priority make:
50 * qos = resourceObserver->qos;
52 * @param method RESTful method.
53 * @param resourceObserver Observer.
54 * @param appQoS Quality of service.
55 * @return The quality of service of the observer.
57 static OCQualityOfService DetermineObserverQoS(OCMethod method,
58 ResourceObserver * resourceObserver, OCQualityOfService appQoS)
60 if (!resourceObserver)
62 OIC_LOG(ERROR, TAG, "DetermineObserverQoS called with invalid resourceObserver");
66 OCQualityOfService decidedQoS = appQoS;
67 if (appQoS == OC_NA_QOS)
69 decidedQoS = resourceObserver->qos;
72 if (appQoS != OC_HIGH_QOS)
74 OIC_LOG_V(INFO, TAG, "Current NON count for this observer is %d",
75 resourceObserver->lowQosCount);
77 if ((resourceObserver->forceHighQos \
78 || resourceObserver->lowQosCount >= MAX_OBSERVER_NON_COUNT) \
79 && method != OC_REST_PRESENCE)
81 if (resourceObserver->forceHighQos \
82 || resourceObserver->lowQosCount >= MAX_OBSERVER_NON_COUNT)
85 resourceObserver->lowQosCount = 0;
86 // at some point we have to to send CON to check on the
87 // availability of observer
88 OIC_LOG(INFO, TAG, "This time we are sending the notification as High qos");
89 decidedQoS = OC_HIGH_QOS;
93 (resourceObserver->lowQosCount)++;
100 * Create a get request and pass to entityhandler to notify specific observer.
102 * @param observer Observer that need to be notified.
103 * @param qos Quality of service of resource.
105 * @return ::OC_STACK_OK on success, some other value upon failure.
107 static OCStackResult SendObserveNotification(ResourceObserver *observer,
108 OCQualityOfService qos)
110 OCStackResult result = OC_STACK_ERROR;
111 OCServerRequest * request = NULL;
112 OCEntityHandlerRequest ehRequest = {0};
113 OCEntityHandlerResult ehResult = OC_EH_ERROR;
115 result = AddServerRequest(&request, 0, 0, 1, OC_REST_GET,
116 0, observer->resource->sequenceNum, qos,
117 observer->query, NULL, NULL,
118 observer->token, observer->tokenLength,
119 observer->resUri, 0, observer->acceptFormat,
124 request->observeResult = OC_STACK_OK;
125 if (result == OC_STACK_OK)
127 result = FormOCEntityHandlerRequest(
129 (OCRequestHandle) request->requestId,
132 (OCResourceHandle) observer->resource,
134 PAYLOAD_TYPE_REPRESENTATION,
136 request->payloadSize,
137 request->numRcvdVendorSpecificHeaderOptions,
138 request->rcvdVendorSpecificHeaderOptions,
139 OC_OBSERVE_NO_OPTION,
142 if (result == OC_STACK_OK)
144 ehResult = observer->resource->entityHandler(OC_REQUEST_FLAG, &ehRequest,
145 observer->resource->entityHandlerCallbackParam);
146 if (ehResult == OC_EH_ERROR)
148 FindAndDeleteServerRequest(request);
150 // Reset Observer TTL.
151 observer->TTL = GetTicks(MAX_OBSERVER_TTL_SECONDS * MILLISECONDS_PER_SECOND);
153 OCPayloadDestroy(ehRequest.payload);
161 OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr, uint32_t maxAge,
162 OCPresenceTrigger trigger, OCResourceType *resourceType, OCQualityOfService qos)
164 OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr, uint32_t maxAge,
165 OCQualityOfService qos)
168 OIC_LOG(INFO, TAG, "Entering SendObserverNotification");
171 return OC_STACK_INVALID_PARAM;
174 OCStackResult result = OC_STACK_ERROR;
175 ResourceObserver * resourceObserver = g_serverObsList;
177 OCServerRequest * request = NULL;
178 OCEntityHandlerRequest ehRequest = {0};
179 OCEntityHandlerResult ehResult = OC_EH_ERROR;
180 bool observeErrorFlag = false;
182 // Find clients that are observing this resource
183 while (resourceObserver)
185 if (resourceObserver->resource == resPtr)
189 if (method != OC_REST_PRESENCE)
192 qos = DetermineObserverQoS(method, resourceObserver, qos);
193 result = SendObserveNotification(resourceObserver, qos);
198 OCEntityHandlerResponse ehResponse = {0};
200 //This is effectively the implementation for the presence entity handler.
201 OIC_LOG(DEBUG, TAG, "This notification is for Presence");
202 result = AddServerRequest(&request, 0, 0, 1, OC_REST_GET,
203 0, resPtr->sequenceNum, qos, resourceObserver->query,
205 resourceObserver->token, resourceObserver->tokenLength,
206 resourceObserver->resUri, 0, resourceObserver->acceptFormat,
207 &resourceObserver->devAddr);
209 if (result == OC_STACK_OK)
211 OCPresencePayload* presenceResBuf = OCPresencePayloadCreate(
212 resPtr->sequenceNum, maxAge, trigger,
213 resourceType ? resourceType->resourcetypename : NULL);
217 return OC_STACK_NO_MEMORY;
220 if (result == OC_STACK_OK)
222 ehResponse.ehResult = OC_EH_OK;
223 ehResponse.payload = (OCPayload*)presenceResBuf;
224 ehResponse.persistentBufferFlag = 0;
225 ehResponse.requestHandle = (OCRequestHandle) request->requestId;
226 ehResponse.resourceHandle = (OCResourceHandle) resPtr;
227 OICStrcpy(ehResponse.resourceUri, sizeof(ehResponse.resourceUri),
228 resourceObserver->resUri);
229 result = OCDoResponse(&ehResponse);
232 OCPresencePayloadDestroy(presenceResBuf);
237 // Since we are in a loop, set an error flag to indicate at least one error occurred.
238 if (result != OC_STACK_OK)
240 observeErrorFlag = true;
243 resourceObserver = resourceObserver->next;
248 OIC_LOG(INFO, TAG, "Resource has no observers");
249 result = OC_STACK_NO_OBSERVERS;
251 else if (observeErrorFlag)
253 OIC_LOG(ERROR, TAG, "Observer notification error");
254 result = OC_STACK_ERROR;
259 OCStackResult SendListObserverNotification (OCResource * resource,
260 OCObservationId *obsIdList, uint8_t numberOfIds,
261 const OCRepPayload *payload,
263 OCQualityOfService qos)
266 if (!resource || !obsIdList || !payload)
268 return OC_STACK_INVALID_PARAM;
271 uint8_t numIds = numberOfIds;
272 ResourceObserver *observer = NULL;
273 uint8_t numSentNotification = 0;
274 OCServerRequest * request = NULL;
275 OCStackResult result = OC_STACK_ERROR;
276 bool observeErrorFlag = false;
278 OIC_LOG(INFO, TAG, "Entering SendListObserverNotification");
281 observer = GetObserverUsingId (*obsIdList);
284 // Found observer - verify if it matches the resource handle
285 if (observer->resource == resource)
287 qos = DetermineObserverQoS(OC_REST_GET, observer, qos);
290 result = AddServerRequest(&request, 0, 0, 1, OC_REST_GET,
291 0, resource->sequenceNum, qos, observer->query,
292 NULL, NULL, observer->token, observer->tokenLength,
293 observer->resUri, 0, observer->acceptFormat,
298 request->observeResult = OC_STACK_OK;
299 if (result == OC_STACK_OK)
301 OCEntityHandlerResponse ehResponse = {0};
302 ehResponse.ehResult = OC_EH_OK;
303 ehResponse.payload = (OCPayload*)OCRepPayloadCreate();
304 if (!ehResponse.payload)
306 FindAndDeleteServerRequest(request);
309 memcpy(ehResponse.payload, payload, sizeof(*payload));
310 ehResponse.persistentBufferFlag = 0;
311 ehResponse.requestHandle = (OCRequestHandle) request->requestId;
312 ehResponse.resourceHandle = (OCResourceHandle) resource;
313 result = OCDoResponse(&ehResponse);
314 if (result == OC_STACK_OK)
316 OIC_LOG_V(INFO, TAG, "Observer id %d notified.", *obsIdList);
318 // Increment only if OCDoResponse is successful
319 numSentNotification++;
321 OICFree(ehResponse.payload);
322 FindAndDeleteServerRequest(request);
326 OIC_LOG_V(INFO, TAG, "Error notifying observer id %d.", *obsIdList);
328 // Reset Observer TTL.
330 GetTicks(MAX_OBSERVER_TTL_SECONDS * MILLISECONDS_PER_SECOND);
334 FindAndDeleteServerRequest(request);
337 // Since we are in a loop, set an error flag to indicate
338 // at least one error occurred.
339 if (result != OC_STACK_OK)
341 observeErrorFlag = true;
349 if (numSentNotification == numberOfIds && !observeErrorFlag)
353 else if (numSentNotification == 0)
355 return OC_STACK_NO_OBSERVERS;
359 OIC_LOG(ERROR, TAG, "Observer notification error");
360 return OC_STACK_ERROR;
364 OCStackResult GenerateObserverId (OCObservationId *observationId)
366 ResourceObserver *resObs = NULL;
368 OIC_LOG(INFO, TAG, "Entering GenerateObserverId");
369 VERIFY_NON_NULL (observationId);
373 *observationId = OCGetRandomByte();
374 // Check if observation Id already exists
375 resObs = GetObserverUsingId (*observationId);
376 } while (NULL != resObs);
378 OIC_LOG_V(INFO, TAG, "GeneratedObservation ID is %u", *observationId);
382 return OC_STACK_ERROR;
385 OCStackResult AddObserver (const char *resUri,
387 OCObservationId obsId,
390 OCResource *resHandle,
391 OCQualityOfService qos,
392 OCPayloadFormat acceptFormat,
393 const OCDevAddr *devAddr)
395 // Check if resource exists and is observable.
398 return OC_STACK_INVALID_PARAM;
400 if (!(resHandle->resourceProperties & OC_OBSERVABLE))
402 return OC_STACK_RESOURCE_ERROR;
405 if (!resUri || !token)
407 return OC_STACK_INVALID_PARAM;
410 ResourceObserver *obsNode = (ResourceObserver *) OICCalloc(1, sizeof(ResourceObserver));
413 obsNode->observeId = obsId;
415 obsNode->resUri = OICStrdup(resUri);
416 VERIFY_NON_NULL (obsNode->resUri);
419 obsNode->acceptFormat = acceptFormat;
422 obsNode->query = OICStrdup(query);
423 VERIFY_NON_NULL (obsNode->query);
425 // If tokenLength is zero, the return value depends on the
426 // particular library implementation (it may or may not be a null pointer).
429 obsNode->token = (CAToken_t)OICMalloc(tokenLength);
430 VERIFY_NON_NULL (obsNode->token);
431 memcpy(obsNode->token, token, tokenLength);
433 obsNode->tokenLength = tokenLength;
435 obsNode->devAddr = *devAddr;
436 obsNode->resource = resHandle;
438 if ((strcmp(resUri, OC_RSRVD_PRESENCE_URI) == 0))
444 obsNode->TTL = GetTicks(MAX_OBSERVER_TTL_SECONDS * MILLISECONDS_PER_SECOND);
447 LL_APPEND (g_serverObsList, obsNode);
455 OICFree(obsNode->resUri);
456 OICFree(obsNode->query);
459 return OC_STACK_NO_MEMORY;
463 * This function checks if the node is past its time to live and
464 * deletes it if timed-out. Calling this function with a presence callback
465 * with ttl set to 0 will not delete anything as presence nodes have
466 * their own mechanisms for timeouts. A null argument will cause the function to
469 static void CheckTimedOutObserver(ResourceObserver* observer)
471 if (!observer || observer->TTL == 0)
479 if (observer->TTL < now)
481 // Send confirmable notification message to observer.
482 OIC_LOG(INFO, TAG, "Sending High-QoS notification to observer");
483 SendObserveNotification(observer, OC_HIGH_QOS);
487 ResourceObserver* GetObserverUsingId (const OCObservationId observeId)
489 ResourceObserver *out = NULL;
493 LL_FOREACH (g_serverObsList, out)
495 if (out->observeId == observeId)
499 CheckTimedOutObserver(out);
502 OIC_LOG(INFO, TAG, "Observer node not found!!");
506 ResourceObserver* GetObserverUsingToken (const CAToken_t token, uint8_t tokenLength)
510 OIC_LOG(INFO, TAG, "Looking for token");
511 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
513 ResourceObserver *out = NULL;
514 LL_FOREACH (g_serverObsList, out)
516 /* de-annotate below line if want to see all token in cbList */
517 //OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->token, tokenLength);
518 if ((memcmp(out->token, token, tokenLength) == 0))
520 OIC_LOG(INFO, TAG, "Found in observer list");
523 CheckTimedOutObserver(out);
528 OIC_LOG(ERROR, TAG, "Passed in NULL token");
531 OIC_LOG(INFO, TAG, "Observer node not found!!");
535 OCStackResult DeleteObserverUsingToken (CAToken_t token, uint8_t tokenLength)
539 return OC_STACK_INVALID_PARAM;
542 ResourceObserver *obsNode = GetObserverUsingToken (token, tokenLength);
545 OIC_LOG_V(INFO, TAG, "deleting observer id %u with token", obsNode->observeId);
546 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)obsNode->token, tokenLength);
547 LL_DELETE (g_serverObsList, obsNode);
548 OICFree(obsNode->resUri);
549 OICFree(obsNode->query);
550 OICFree(obsNode->token);
553 // it is ok if we did not find the observer...
557 OCStackResult DeleteObserverUsingDevAddr(const OCDevAddr *devAddr)
561 return OC_STACK_INVALID_PARAM;
564 ResourceObserver *out = NULL;
565 ResourceObserver *tmp = NULL;
566 LL_FOREACH_SAFE(g_serverObsList, out, tmp)
570 if ((strcmp(out->devAddr.addr, devAddr->addr) == 0)
571 && out->devAddr.port == devAddr->port)
573 OIC_LOG_V(INFO, TAG, "deleting observer id %u with %s:%u",
574 out->observeId, out->devAddr.addr, out->devAddr.port);
575 OCStackFeedBack(out->token, out->tokenLength, OC_OBSERVER_NOT_INTERESTED);
583 void DeleteObserverList()
585 ResourceObserver *out = NULL;
586 ResourceObserver *tmp = NULL;
587 LL_FOREACH_SAFE (g_serverObsList, out, tmp)
591 DeleteObserverUsingToken ((out->token), out->tokenLength);
594 g_serverObsList = NULL;
598 * CA layer expects observe registration/de-reg/notiifcations to be passed as a header
599 * option, which breaks the protocol abstraction requirement between RI & CA, and
600 * has to be fixed in the future. The function below adds the header option for observe.
601 * It should be noted that the observe header option is assumed to be the first option
602 * in the list of user defined header options and hence it is inserted at the front
603 * of the header options list and number of options adjusted accordingly.
606 CreateObserveHeaderOption (CAHeaderOption_t **caHdrOpt,
607 OCHeaderOption *ocHdrOpt,
613 return OC_STACK_INVALID_PARAM;
616 if (numOptions > 0 && !ocHdrOpt)
618 OIC_LOG (INFO, TAG, "options are NULL though number is non zero");
619 return OC_STACK_INVALID_PARAM;
622 CAHeaderOption_t *tmpHdrOpt = NULL;
624 tmpHdrOpt = (CAHeaderOption_t *) OICCalloc ((numOptions+1), sizeof(CAHeaderOption_t));
625 if (NULL == tmpHdrOpt)
627 return OC_STACK_NO_MEMORY;
629 tmpHdrOpt[0].protocolID = CA_COAP_ID;
630 tmpHdrOpt[0].optionID = COAP_OPTION_OBSERVE;
631 tmpHdrOpt[0].optionLength = sizeof(uint8_t);
632 tmpHdrOpt[0].optionData[0] = observeFlag;
633 for (uint8_t i = 0; i < numOptions; i++)
635 memcpy (&(tmpHdrOpt[i+1]), &(ocHdrOpt[i]), sizeof(CAHeaderOption_t));
638 *caHdrOpt = tmpHdrOpt;
643 * CA layer passes observe information to the RI layer as a header option, which
644 * breaks the protocol abstraction requirement between RI & CA, and has to be fixed
645 * in the future. The function below removes the observe header option and processes it.
646 * It should be noted that the observe header option is always assumed to be the first
647 * option in the list of user defined header options and hence it is deleted from the
648 * front of the header options list and the number of options is adjusted accordingly.
651 GetObserveHeaderOption (uint32_t * observationOption,
652 CAHeaderOption_t *options,
653 uint8_t * numOptions)
655 if (!observationOption)
657 return OC_STACK_INVALID_PARAM;
660 if (!options || !numOptions)
662 OIC_LOG (INFO, TAG, "No options present");
666 for(uint8_t i = 0; i < *numOptions; i++)
668 if (options[i].protocolID == CA_COAP_ID &&
669 options[i].optionID == COAP_OPTION_OBSERVE)
671 *observationOption = options[i].optionData[0];
672 for(uint8_t c = i; c < *numOptions-1; c++)
674 options[i] = options[i+1];