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"
38 #define MOD_NAME "ocobserve"
40 #define TAG "OCStackObserve"
42 #define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG(FATAL, TAG, #arg " is NULL"); goto exit;} }
44 static struct ResourceObserver * serverObsList = NULL;
46 * Determine observe QOS based on the QOS of the request.
47 * The qos passed as a parameter overrides what the client requested.
48 * If we want the client preference taking high priority make:
49 * qos = resourceObserver->qos;
51 * @param method RESTful method.
52 * @param resourceObserver Observer.
53 * @param appQoS Quality of service.
54 * @return The quality of service of the observer.
56 static OCQualityOfService DetermineObserverQoS(OCMethod method,
57 ResourceObserver * resourceObserver, OCQualityOfService appQoS)
61 OC_LOG(ERROR, TAG, "DetermineObserverQoS called with invalid resourceObserver");
65 OCQualityOfService decidedQoS = appQoS;
66 if(appQoS == OC_NA_QOS)
68 decidedQoS = resourceObserver->qos;
71 if(appQoS != OC_HIGH_QOS)
73 OC_LOG_V(INFO, TAG, "Current NON count for this observer is %d",
74 resourceObserver->lowQosCount);
76 if((resourceObserver->forceHighQos \
77 || resourceObserver->lowQosCount >= MAX_OBSERVER_NON_COUNT) \
78 && method != OC_REST_PRESENCE)
80 if(resourceObserver->forceHighQos \
81 || resourceObserver->lowQosCount >= MAX_OBSERVER_NON_COUNT)
84 resourceObserver->lowQosCount = 0;
85 // at some point we have to to send CON to check on the
86 // availability of observer
87 OC_LOG(INFO, TAG, "This time we are sending the notification as High qos");
88 decidedQoS = OC_HIGH_QOS;
92 (resourceObserver->lowQosCount)++;
99 OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr, uint32_t maxAge,
100 OCPresenceTrigger trigger, OCResourceType *resourceType, OCQualityOfService qos)
102 OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr, uint32_t maxAge,
103 OCQualityOfService qos)
106 OC_LOG(INFO, TAG, "Entering SendObserverNotification");
109 return OC_STACK_INVALID_PARAM;
112 OCStackResult result = OC_STACK_ERROR;
113 ResourceObserver * resourceObserver = serverObsList;
115 OCServerRequest * request = NULL;
116 OCEntityHandlerRequest ehRequest = {0};
117 OCEntityHandlerResult ehResult = OC_EH_ERROR;
118 bool observeErrorFlag = false;
120 // Find clients that are observing this resource
121 while (resourceObserver)
123 if (resourceObserver->resource == resPtr)
127 if(method != OC_REST_PRESENCE)
130 qos = DetermineObserverQoS(method, resourceObserver, qos);
132 result = AddServerRequest(&request, 0, 0, 1, OC_REST_GET,
133 0, resPtr->sequenceNum, qos, resourceObserver->query,
135 resourceObserver->token, resourceObserver->tokenLength,
136 resourceObserver->resUri, 0, resourceObserver->acceptFormat,
137 &resourceObserver->devAddr);
141 request->observeResult = OC_STACK_OK;
142 if(result == OC_STACK_OK)
144 result = FormOCEntityHandlerRequest(
146 (OCRequestHandle) request,
149 (OCResourceHandle) resPtr,
151 PAYLOAD_TYPE_REPRESENTATION,
153 request->payloadSize,
154 request->numRcvdVendorSpecificHeaderOptions,
155 request->rcvdVendorSpecificHeaderOptions,
156 OC_OBSERVE_NO_OPTION,
158 if(result == OC_STACK_OK)
160 ehResult = resPtr->entityHandler(OC_REQUEST_FLAG, &ehRequest,
161 resPtr->entityHandlerCallbackParam);
162 if(ehResult == OC_EH_ERROR)
164 FindAndDeleteServerRequest(request);
167 OCPayloadDestroy(ehRequest.payload);
174 OCEntityHandlerResponse ehResponse = {0};
176 //This is effectively the implementation for the presence entity handler.
177 OC_LOG(DEBUG, TAG, "This notification is for Presence");
178 result = AddServerRequest(&request, 0, 0, 1, OC_REST_GET,
179 0, resPtr->sequenceNum, qos, resourceObserver->query,
181 resourceObserver->token, resourceObserver->tokenLength,
182 resourceObserver->resUri, 0, resourceObserver->acceptFormat,
183 &resourceObserver->devAddr);
185 if(result == OC_STACK_OK)
187 OCPresencePayload* presenceResBuf = OCPresencePayloadCreate(
188 resPtr->sequenceNum, maxAge, trigger,
189 resourceType ? resourceType->resourcetypename : NULL);
193 return OC_STACK_NO_MEMORY;
196 if(result == OC_STACK_OK)
198 ehResponse.ehResult = OC_EH_OK;
199 ehResponse.payload = (OCPayload*)presenceResBuf;
200 ehResponse.persistentBufferFlag = 0;
201 ehResponse.requestHandle = (OCRequestHandle) request;
202 ehResponse.resourceHandle = (OCResourceHandle) resPtr;
203 OICStrcpy(ehResponse.resourceUri, sizeof(ehResponse.resourceUri),
204 resourceObserver->resUri);
205 result = OCDoResponse(&ehResponse);
208 OCPresencePayloadDestroy(presenceResBuf);
213 // Since we are in a loop, set an error flag to indicate at least one error occurred.
214 if (result != OC_STACK_OK)
216 observeErrorFlag = true;
219 resourceObserver = resourceObserver->next;
224 OC_LOG(INFO, TAG, "Resource has no observers");
225 result = OC_STACK_NO_OBSERVERS;
227 else if (observeErrorFlag)
229 OC_LOG(ERROR, TAG, "Observer notification error");
230 result = OC_STACK_ERROR;
235 OCStackResult SendListObserverNotification (OCResource * resource,
236 OCObservationId *obsIdList, uint8_t numberOfIds,
237 const OCRepPayload *payload,
239 OCQualityOfService qos)
242 if(!resource || !obsIdList || !payload)
244 return OC_STACK_INVALID_PARAM;
247 uint8_t numIds = numberOfIds;
248 ResourceObserver *observer = NULL;
249 uint8_t numSentNotification = 0;
250 OCServerRequest * request = NULL;
251 OCStackResult result = OC_STACK_ERROR;
252 bool observeErrorFlag = false;
254 OC_LOG(INFO, TAG, "Entering SendListObserverNotification");
257 observer = GetObserverUsingId (*obsIdList);
260 // Found observer - verify if it matches the resource handle
261 if (observer->resource == resource)
263 qos = DetermineObserverQoS(OC_REST_GET, observer, qos);
266 result = AddServerRequest(&request, 0, 0, 1, OC_REST_GET,
267 0, resource->sequenceNum, qos, observer->query,
268 NULL, NULL, observer->token, observer->tokenLength,
269 observer->resUri, 0, observer->acceptFormat,
274 request->observeResult = OC_STACK_OK;
275 if(result == OC_STACK_OK)
277 OCEntityHandlerResponse ehResponse = {0};
278 ehResponse.ehResult = OC_EH_OK;
279 ehResponse.payload = (OCPayload*)OCRepPayloadCreate();
280 if(!ehResponse.payload)
282 FindAndDeleteServerRequest(request);
285 memcpy(ehResponse.payload, payload, sizeof(*payload));
286 ehResponse.persistentBufferFlag = 0;
287 ehResponse.requestHandle = (OCRequestHandle) request;
288 ehResponse.resourceHandle = (OCResourceHandle) resource;
289 result = OCDoResponse(&ehResponse);
290 if(result == OC_STACK_OK)
292 OC_LOG_V(INFO, TAG, "Observer id %d notified.", *obsIdList);
294 // Increment only if OCDoResponse is successful
295 numSentNotification++;
297 OICFree(ehResponse.payload);
298 FindAndDeleteServerRequest(request);
302 OC_LOG_V(INFO, TAG, "Error notifying observer id %d.", *obsIdList);
307 FindAndDeleteServerRequest(request);
310 // Since we are in a loop, set an error flag to indicate
311 // at least one error occurred.
312 if (result != OC_STACK_OK)
314 observeErrorFlag = true;
322 if(numSentNotification == numberOfIds && !observeErrorFlag)
326 else if(numSentNotification == 0)
328 return OC_STACK_NO_OBSERVERS;
332 OC_LOG(ERROR, TAG, "Observer notification error");
333 return OC_STACK_ERROR;
337 OCStackResult GenerateObserverId (OCObservationId *observationId)
339 ResourceObserver *resObs = NULL;
341 OC_LOG(INFO, TAG, "Entering GenerateObserverId");
342 VERIFY_NON_NULL (observationId);
346 *observationId = OCGetRandomByte();
347 // Check if observation Id already exists
348 resObs = GetObserverUsingId (*observationId);
349 } while (NULL != resObs);
351 OC_LOG_V(INFO, TAG, "GeneratedObservation ID is %u", *observationId);
355 return OC_STACK_ERROR;
358 OCStackResult AddObserver (const char *resUri,
360 OCObservationId obsId,
363 OCResource *resHandle,
364 OCQualityOfService qos,
365 OCPayloadFormat acceptFormat,
366 const OCDevAddr *devAddr)
368 // Check if resource exists and is observable.
371 return OC_STACK_INVALID_PARAM;
373 if (!(resHandle->resourceProperties & OC_OBSERVABLE))
375 return OC_STACK_RESOURCE_ERROR;
377 ResourceObserver *obsNode = NULL;
379 if(!resUri || !token || !*token)
381 return OC_STACK_INVALID_PARAM;
384 obsNode = (ResourceObserver *) OICCalloc(1, sizeof(ResourceObserver));
387 obsNode->observeId = obsId;
389 obsNode->resUri = OICStrdup(resUri);
390 VERIFY_NON_NULL (obsNode->resUri);
393 obsNode->acceptFormat = acceptFormat;
396 obsNode->query = OICStrdup(query);
397 VERIFY_NON_NULL (obsNode->query);
399 // If tokenLength is zero, the return value depends on the
400 // particular library implementation (it may or may not be a null pointer).
403 obsNode->token = (CAToken_t)OICMalloc(tokenLength);
404 VERIFY_NON_NULL (obsNode->token);
405 memcpy(obsNode->token, token, tokenLength);
407 obsNode->tokenLength = tokenLength;
409 obsNode->devAddr = *devAddr;
410 obsNode->resource = resHandle;
412 LL_APPEND (serverObsList, obsNode);
420 OICFree(obsNode->resUri);
421 OICFree(obsNode->query);
424 return OC_STACK_NO_MEMORY;
427 ResourceObserver* GetObserverUsingId (const OCObservationId observeId)
429 ResourceObserver *out = NULL;
433 LL_FOREACH (serverObsList, out)
435 if (out->observeId == observeId)
441 OC_LOG(INFO, TAG, "Observer node not found!!");
445 ResourceObserver* GetObserverUsingToken (const CAToken_t token, uint8_t tokenLength)
447 ResourceObserver *out = NULL;
451 OC_LOG(INFO, TAG, "Looking for token");
452 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
453 OC_LOG(INFO, TAG, "\tFound token:");
455 LL_FOREACH (serverObsList, out)
457 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->token, tokenLength);
458 if((memcmp(out->token, token, tokenLength) == 0))
466 OC_LOG(ERROR, TAG, "Passed in NULL token");
469 OC_LOG(INFO, TAG, "Observer node not found!!");
473 OCStackResult DeleteObserverUsingToken (CAToken_t token, uint8_t tokenLength)
475 if(!token || !*token)
477 return OC_STACK_INVALID_PARAM;
480 ResourceObserver *obsNode = NULL;
482 obsNode = GetObserverUsingToken (token, tokenLength);
485 OC_LOG_V(INFO, TAG, "deleting observer id %u with token", obsNode->observeId);
486 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)obsNode->token, tokenLength);
487 LL_DELETE (serverObsList, obsNode);
488 OICFree(obsNode->resUri);
489 OICFree(obsNode->query);
490 OICFree(obsNode->token);
493 // it is ok if we did not find the observer...
497 void DeleteObserverList()
499 ResourceObserver *out = NULL;
500 ResourceObserver *tmp = NULL;
501 LL_FOREACH_SAFE (serverObsList, out, tmp)
505 DeleteObserverUsingToken ((out->token), out->tokenLength);
508 serverObsList = NULL;
512 * CA layer expects observe registration/de-reg/notiifcations to be passed as a header
513 * option, which breaks the protocol abstraction requirement between RI & CA, and
514 * has to be fixed in the future. The function below adds the header option for observe.
515 * It should be noted that the observe header option is assumed to be the first option
516 * in the list of user defined header options and hence it is inserted at the front
517 * of the header options list and number of options adjusted accordingly.
520 CreateObserveHeaderOption (CAHeaderOption_t **caHdrOpt,
521 OCHeaderOption *ocHdrOpt,
525 if(!caHdrOpt || !ocHdrOpt)
527 return OC_STACK_INVALID_PARAM;
530 CAHeaderOption_t *tmpHdrOpt = NULL;
532 tmpHdrOpt = (CAHeaderOption_t *) OICCalloc ((numOptions+1), sizeof(CAHeaderOption_t));
533 if (NULL == tmpHdrOpt)
535 return OC_STACK_NO_MEMORY;
537 tmpHdrOpt[0].protocolID = CA_COAP_ID;
538 tmpHdrOpt[0].optionID = COAP_OPTION_OBSERVE;
539 tmpHdrOpt[0].optionLength = sizeof(uint8_t);
540 tmpHdrOpt[0].optionData[0] = observeFlag;
541 for (uint8_t i = 0; i < numOptions; i++)
543 memcpy (&(tmpHdrOpt[i+1]), &(ocHdrOpt[i]), sizeof(CAHeaderOption_t));
546 *caHdrOpt = tmpHdrOpt;
551 * CA layer passes observe information to the RI layer as a header option, which
552 * breaks the protocol abstraction requirement between RI & CA, and has to be fixed
553 * in the future. The function below removes the observe header option and processes it.
554 * It should be noted that the observe header option is always assumed to be the first
555 * option in the list of user defined header options and hence it is deleted from the
556 * front of the header options list and the number of options is adjusted accordingly.
559 GetObserveHeaderOption (uint32_t * observationOption,
560 CAHeaderOption_t *options,
561 uint8_t * numOptions)
563 if(!observationOption)
565 return OC_STACK_INVALID_PARAM;
568 if(!options || !numOptions)
570 return OC_STACK_INVALID_PARAM;
573 *observationOption = OC_OBSERVE_NO_OPTION;
575 for(uint8_t i = 0; i < *numOptions; i++)
577 if(options[i].protocolID == CA_COAP_ID &&
578 options[i].optionID == COAP_OPTION_OBSERVE)
580 *observationOption = options[i].optionData[0];
581 for(uint8_t c = i; c < *numOptions-1; c++)
583 options[i] = options[i+1];