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 PCF("ocobserve")
40 #define TAG PCF("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, PCF("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, PCF("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 = {};
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,
137 &resourceObserver->devAddr);
141 request->observeResult = OC_STACK_OK;
142 if(result == OC_STACK_OK)
144 result = FormOCEntityHandlerRequest(
146 (OCRequestHandle) request,
149 (OCResourceHandle) resPtr,
152 request->payloadSize,
153 request->numRcvdVendorSpecificHeaderOptions,
154 request->rcvdVendorSpecificHeaderOptions,
155 OC_OBSERVE_NO_OPTION,
157 if(result == OC_STACK_OK)
159 ehResult = resPtr->entityHandler(OC_REQUEST_FLAG, &ehRequest,
160 resPtr->entityHandlerCallbackParam);
161 if(ehResult == OC_EH_ERROR)
163 FindAndDeleteServerRequest(request);
166 OCPayloadDestroy(ehRequest.payload);
173 OCEntityHandlerResponse ehResponse = {};
175 //This is effectively the implementation for the presence entity handler.
176 OC_LOG(DEBUG, TAG, PCF("This notification is for Presence"));
177 result = AddServerRequest(&request, 0, 0, 1, OC_REST_GET,
178 0, resPtr->sequenceNum, qos, resourceObserver->query,
180 resourceObserver->token, resourceObserver->tokenLength,
181 resourceObserver->resUri, 0,
182 &resourceObserver->devAddr);
184 if(result == OC_STACK_OK)
186 OCPresencePayload* presenceResBuf = OCPresencePayloadCreate(
187 resPtr->sequenceNum, maxAge, trigger,
188 resourceType ? resourceType->resourcetypename : NULL);
192 return OC_STACK_NO_MEMORY;
195 if(result == OC_STACK_OK)
197 ehResponse.ehResult = OC_EH_OK;
198 ehResponse.payload = (OCPayload*)presenceResBuf;
199 ehResponse.persistentBufferFlag = 0;
200 ehResponse.requestHandle = (OCRequestHandle) request;
201 ehResponse.resourceHandle = (OCResourceHandle) resPtr;
202 OICStrcpy(ehResponse.resourceUri, sizeof(ehResponse.resourceUri),
203 resourceObserver->resUri);
204 result = OCDoResponse(&ehResponse);
207 OCPresencePayloadDestroy(presenceResBuf);
212 // Since we are in a loop, set an error flag to indicate at least one error occurred.
213 if (result != OC_STACK_OK)
215 observeErrorFlag = true;
218 resourceObserver = resourceObserver->next;
223 OC_LOG(INFO, TAG, PCF("Resource has no observers"));
224 result = OC_STACK_NO_OBSERVERS;
226 else if (observeErrorFlag)
228 OC_LOG(ERROR, TAG, PCF("Observer notification error"));
229 result = OC_STACK_ERROR;
234 OCStackResult SendListObserverNotification (OCResource * resource,
235 OCObservationId *obsIdList, uint8_t numberOfIds,
236 const OCRepPayload *payload,
238 OCQualityOfService qos)
240 if(!resource || !obsIdList || !payload)
242 return OC_STACK_INVALID_PARAM;
245 uint8_t numIds = numberOfIds;
246 ResourceObserver *observer = NULL;
247 uint8_t numSentNotification = 0;
248 OCServerRequest * request = NULL;
249 OCStackResult result = OC_STACK_ERROR;
250 bool observeErrorFlag = false;
252 OC_LOG(INFO, TAG, PCF("Entering SendListObserverNotification"));
255 observer = GetObserverUsingId (*obsIdList);
258 // Found observer - verify if it matches the resource handle
259 if (observer->resource == resource)
261 qos = DetermineObserverQoS(OC_REST_GET, observer, qos);
264 result = AddServerRequest(&request, 0, 0, 1, OC_REST_GET,
265 0, resource->sequenceNum, qos, observer->query,
266 NULL, NULL, observer->token, observer->tokenLength,
272 request->observeResult = OC_STACK_OK;
273 if(result == OC_STACK_OK)
275 OCEntityHandlerResponse ehResponse = {};
276 ehResponse.ehResult = OC_EH_OK;
277 ehResponse.payload = (OCPayload*)OCRepPayloadCreate();
278 if(!ehResponse.payload)
280 FindAndDeleteServerRequest(request);
283 memcpy(ehResponse.payload, payload, sizeof(*payload));
284 ehResponse.persistentBufferFlag = 0;
285 ehResponse.requestHandle = (OCRequestHandle) request;
286 ehResponse.resourceHandle = (OCResourceHandle) resource;
287 result = OCDoResponse(&ehResponse);
288 if(result == OC_STACK_OK)
290 OC_LOG_V(INFO, TAG, "Observer id %d notified.", *obsIdList);
292 // Increment only if OCDoResponse is successful
293 numSentNotification++;
295 OICFree(ehResponse.payload);
296 FindAndDeleteServerRequest(request);
300 OC_LOG_V(INFO, TAG, "Error notifying observer id %d.", *obsIdList);
305 FindAndDeleteServerRequest(request);
308 // Since we are in a loop, set an error flag to indicate
309 // at least one error occurred.
310 if (result != OC_STACK_OK)
312 observeErrorFlag = true;
320 if(numSentNotification == numberOfIds && !observeErrorFlag)
324 else if(numSentNotification == 0)
326 return OC_STACK_NO_OBSERVERS;
330 OC_LOG(ERROR, TAG, PCF("Observer notification error"));
331 return OC_STACK_ERROR;
335 OCStackResult GenerateObserverId (OCObservationId *observationId)
337 ResourceObserver *resObs = NULL;
339 OC_LOG(INFO, TAG, PCF("Entering GenerateObserverId"));
340 VERIFY_NON_NULL (observationId);
344 *observationId = OCGetRandomByte();
345 // Check if observation Id already exists
346 resObs = GetObserverUsingId (*observationId);
347 } while (NULL != resObs);
349 OC_LOG_V(INFO, TAG, "Generated bservation ID is %u", *observationId);
353 return OC_STACK_ERROR;
356 OCStackResult AddObserver (const char *resUri,
358 OCObservationId obsId,
361 OCResource *resHandle,
362 OCQualityOfService qos,
363 const OCDevAddr *devAddr)
365 // Check if resource exists and is observable.
368 return OC_STACK_INVALID_PARAM;
370 if (!(resHandle->resourceProperties & OC_OBSERVABLE))
372 return OC_STACK_RESOURCE_ERROR;
374 ResourceObserver *obsNode = NULL;
376 if(!resUri || !token || !*token)
378 return OC_STACK_INVALID_PARAM;
381 obsNode = (ResourceObserver *) OICCalloc(1, sizeof(ResourceObserver));
384 obsNode->observeId = obsId;
386 obsNode->resUri = OICStrdup(resUri);
387 VERIFY_NON_NULL (obsNode->resUri);
392 obsNode->query = OICStrdup(query);
393 VERIFY_NON_NULL (obsNode->query);
395 // If tokenLength is zero, the return value depends on the
396 // particular library implementation (it may or may not be a null pointer).
399 obsNode->token = (CAToken_t)OICMalloc(tokenLength);
400 VERIFY_NON_NULL (obsNode->token);
401 memcpy(obsNode->token, token, tokenLength);
403 obsNode->tokenLength = tokenLength;
405 obsNode->devAddr = *devAddr;
406 obsNode->resource = resHandle;
408 LL_APPEND (serverObsList, obsNode);
416 OICFree(obsNode->resUri);
417 OICFree(obsNode->query);
420 return OC_STACK_NO_MEMORY;
423 ResourceObserver* GetObserverUsingId (const OCObservationId observeId)
425 ResourceObserver *out = NULL;
429 LL_FOREACH (serverObsList, out)
431 if (out->observeId == observeId)
437 OC_LOG(INFO, TAG, PCF("Observer node not found!!"));
441 ResourceObserver* GetObserverUsingToken (const CAToken_t token, uint8_t tokenLength)
443 ResourceObserver *out = NULL;
447 OC_LOG(INFO, TAG,PCF("Looking for token"));
448 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
449 OC_LOG(INFO, TAG,PCF("\tFound token:"));
451 LL_FOREACH (serverObsList, out)
453 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->token, tokenLength);
454 if((memcmp(out->token, token, tokenLength) == 0))
462 OC_LOG(ERROR, TAG,PCF("Passed in NULL token"));
465 OC_LOG(INFO, TAG, PCF("Observer node not found!!"));
469 OCStackResult DeleteObserverUsingToken (CAToken_t token, uint8_t tokenLength)
471 if(!token || !*token)
473 return OC_STACK_INVALID_PARAM;
476 ResourceObserver *obsNode = NULL;
478 obsNode = GetObserverUsingToken (token, tokenLength);
481 OC_LOG_V(INFO, TAG, "deleting observer id %u with token", obsNode->observeId);
482 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)obsNode->token, tokenLength);
483 LL_DELETE (serverObsList, obsNode);
484 OICFree(obsNode->resUri);
485 OICFree(obsNode->query);
486 OICFree(obsNode->token);
489 // it is ok if we did not find the observer...
493 void DeleteObserverList()
495 ResourceObserver *out = NULL;
496 ResourceObserver *tmp = NULL;
497 LL_FOREACH_SAFE (serverObsList, out, tmp)
501 DeleteObserverUsingToken ((out->token), out->tokenLength);
504 serverObsList = NULL;
508 * CA layer expects observe registration/de-reg/notiifcations to be passed as a header
509 * option, which breaks the protocol abstraction requirement between RI & CA, and
510 * has to be fixed in the future. The function below adds the header option for observe.
511 * It should be noted that the observe header option is assumed to be the first option
512 * in the list of user defined header options and hence it is inserted at the front
513 * of the header options list and number of options adjusted accordingly.
516 CreateObserveHeaderOption (CAHeaderOption_t **caHdrOpt,
517 OCHeaderOption *ocHdrOpt,
523 return OC_STACK_INVALID_PARAM;
526 CAHeaderOption_t *tmpHdrOpt = NULL;
528 tmpHdrOpt = (CAHeaderOption_t *) OICCalloc ((numOptions+1), sizeof(CAHeaderOption_t));
529 if (NULL == tmpHdrOpt)
531 return OC_STACK_NO_MEMORY;
533 tmpHdrOpt[0].protocolID = CA_COAP_ID;
534 tmpHdrOpt[0].optionID = COAP_OPTION_OBSERVE;
535 tmpHdrOpt[0].optionLength = sizeof(uint32_t);
536 tmpHdrOpt[0].optionData[0] = observeFlag;
537 for (uint8_t i = 0; i < numOptions; i++)
539 memcpy (&(tmpHdrOpt[i+1]), &(ocHdrOpt[i]), sizeof(CAHeaderOption_t));
542 *caHdrOpt = tmpHdrOpt;
547 * CA layer passes observe information to the RI layer as a header option, which
548 * breaks the protocol abstraction requirement between RI & CA, and has to be fixed
549 * in the future. The function below removes the observe header option and processes it.
550 * It should be noted that the observe header option is always assumed to be the first
551 * option in the list of user defined header options and hence it is deleted from the
552 * front of the header options list and the number of options is adjusted accordingly.
555 GetObserveHeaderOption (uint32_t * observationOption,
556 CAHeaderOption_t *options,
557 uint8_t * numOptions)
559 if(!observationOption)
561 return OC_STACK_INVALID_PARAM;
563 *observationOption = OC_OBSERVE_NO_OPTION;
565 if(!options || !numOptions)
567 return OC_STACK_INVALID_PARAM;
570 for(uint8_t i = 0; i < *numOptions; i++)
572 if(options[i].protocolID == CA_COAP_ID &&
573 options[i].optionID == COAP_OPTION_OBSERVE)
575 *observationOption = options[i].optionData[0];
576 for(uint8_t c = i; c < *numOptions-1; c++)
578 options[i] = options[i+1];