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"
39 #define MOD_NAME "ocobserve"
41 #define TAG "OCStackObserve"
43 #define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG(FATAL, TAG, #arg " is NULL"); goto exit;} }
45 static struct ResourceObserver * 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)
62 OC_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 OC_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 OC_LOG(INFO, TAG, "This time we are sending the notification as High qos");
89 decidedQoS = OC_HIGH_QOS;
93 (resourceObserver->lowQosCount)++;
100 OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr, uint32_t maxAge,
101 OCPresenceTrigger trigger, OCResourceType *resourceType, OCQualityOfService qos)
103 OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr, uint32_t maxAge,
104 OCQualityOfService qos)
107 OC_LOG(INFO, TAG, "Entering SendObserverNotification");
110 return OC_STACK_INVALID_PARAM;
113 OCStackResult result = OC_STACK_ERROR;
114 ResourceObserver * resourceObserver = serverObsList;
116 OCServerRequest * request = NULL;
117 OCEntityHandlerRequest ehRequest = {0};
118 OCEntityHandlerResult ehResult = OC_EH_ERROR;
119 bool observeErrorFlag = false;
121 // Find clients that are observing this resource
122 while (resourceObserver)
124 if (resourceObserver->resource == resPtr)
128 if(method != OC_REST_PRESENCE)
131 qos = DetermineObserverQoS(method, resourceObserver, qos);
133 result = AddServerRequest(&request, 0, 0, 1, OC_REST_GET,
134 0, resPtr->sequenceNum, qos, resourceObserver->query,
136 resourceObserver->token, resourceObserver->tokenLength,
137 resourceObserver->resUri, 0, resourceObserver->acceptFormat,
138 &resourceObserver->devAddr);
142 request->observeResult = OC_STACK_OK;
143 if(result == OC_STACK_OK)
145 result = FormOCEntityHandlerRequest(
147 (OCRequestHandle) request,
150 (OCResourceHandle) resPtr,
152 PAYLOAD_TYPE_REPRESENTATION,
154 request->payloadSize,
155 request->numRcvdVendorSpecificHeaderOptions,
156 request->rcvdVendorSpecificHeaderOptions,
157 OC_OBSERVE_NO_OPTION,
159 if(result == OC_STACK_OK)
161 ehResult = resPtr->entityHandler(OC_REQUEST_FLAG, &ehRequest,
162 resPtr->entityHandlerCallbackParam);
163 if(ehResult == OC_EH_ERROR)
165 FindAndDeleteServerRequest(request);
168 OCPayloadDestroy(ehRequest.payload);
175 OCEntityHandlerResponse ehResponse = {0};
177 //This is effectively the implementation for the presence entity handler.
178 OC_LOG(DEBUG, TAG, "This notification is for Presence");
179 result = AddServerRequest(&request, 0, 0, 1, OC_REST_GET,
180 0, resPtr->sequenceNum, qos, resourceObserver->query,
182 resourceObserver->token, resourceObserver->tokenLength,
183 resourceObserver->resUri, 0, resourceObserver->acceptFormat,
184 &resourceObserver->devAddr);
186 if(result == OC_STACK_OK)
188 OCPresencePayload* presenceResBuf = OCPresencePayloadCreate(
189 resPtr->sequenceNum, maxAge, trigger,
190 resourceType ? resourceType->resourcetypename : NULL);
194 return OC_STACK_NO_MEMORY;
197 if(result == OC_STACK_OK)
199 ehResponse.ehResult = OC_EH_OK;
200 ehResponse.payload = (OCPayload*)presenceResBuf;
201 ehResponse.persistentBufferFlag = 0;
202 ehResponse.requestHandle = (OCRequestHandle) request;
203 ehResponse.resourceHandle = (OCResourceHandle) resPtr;
204 OICStrcpy(ehResponse.resourceUri, sizeof(ehResponse.resourceUri),
205 resourceObserver->resUri);
206 result = OCDoResponse(&ehResponse);
209 OCPresencePayloadDestroy(presenceResBuf);
214 // Since we are in a loop, set an error flag to indicate at least one error occurred.
215 if (result != OC_STACK_OK)
217 observeErrorFlag = true;
220 resourceObserver = resourceObserver->next;
225 OC_LOG(INFO, TAG, "Resource has no observers");
226 result = OC_STACK_NO_OBSERVERS;
228 else if (observeErrorFlag)
230 OC_LOG(ERROR, TAG, "Observer notification error");
231 result = OC_STACK_ERROR;
236 OCStackResult SendListObserverNotification (OCResource * resource,
237 OCObservationId *obsIdList, uint8_t numberOfIds,
238 const OCRepPayload *payload,
240 OCQualityOfService qos)
243 if(!resource || !obsIdList || !payload)
245 return OC_STACK_INVALID_PARAM;
248 uint8_t numIds = numberOfIds;
249 ResourceObserver *observer = NULL;
250 uint8_t numSentNotification = 0;
251 OCServerRequest * request = NULL;
252 OCStackResult result = OC_STACK_ERROR;
253 bool observeErrorFlag = false;
255 OC_LOG(INFO, TAG, "Entering SendListObserverNotification");
258 observer = GetObserverUsingId (*obsIdList);
261 // Found observer - verify if it matches the resource handle
262 if (observer->resource == resource)
264 qos = DetermineObserverQoS(OC_REST_GET, observer, qos);
267 result = AddServerRequest(&request, 0, 0, 1, OC_REST_GET,
268 0, resource->sequenceNum, qos, observer->query,
269 NULL, NULL, observer->token, observer->tokenLength,
270 observer->resUri, 0, observer->acceptFormat,
275 request->observeResult = OC_STACK_OK;
276 if(result == OC_STACK_OK)
278 OCEntityHandlerResponse ehResponse = {0};
279 ehResponse.ehResult = OC_EH_OK;
280 ehResponse.payload = (OCPayload*)OCRepPayloadCreate();
281 if(!ehResponse.payload)
283 FindAndDeleteServerRequest(request);
286 memcpy(ehResponse.payload, payload, sizeof(*payload));
287 ehResponse.persistentBufferFlag = 0;
288 ehResponse.requestHandle = (OCRequestHandle) request;
289 ehResponse.resourceHandle = (OCResourceHandle) resource;
290 result = OCDoResponse(&ehResponse);
291 if(result == OC_STACK_OK)
293 OC_LOG_V(INFO, TAG, "Observer id %d notified.", *obsIdList);
295 // Increment only if OCDoResponse is successful
296 numSentNotification++;
298 OICFree(ehResponse.payload);
299 FindAndDeleteServerRequest(request);
303 OC_LOG_V(INFO, TAG, "Error notifying observer id %d.", *obsIdList);
308 FindAndDeleteServerRequest(request);
311 // Since we are in a loop, set an error flag to indicate
312 // at least one error occurred.
313 if (result != OC_STACK_OK)
315 observeErrorFlag = true;
323 if(numSentNotification == numberOfIds && !observeErrorFlag)
327 else if(numSentNotification == 0)
329 return OC_STACK_NO_OBSERVERS;
333 OC_LOG(ERROR, TAG, "Observer notification error");
334 return OC_STACK_ERROR;
338 OCStackResult GenerateObserverId (OCObservationId *observationId)
340 ResourceObserver *resObs = NULL;
342 OC_LOG(INFO, TAG, "Entering GenerateObserverId");
343 VERIFY_NON_NULL (observationId);
347 *observationId = OCGetRandomByte();
348 // Check if observation Id already exists
349 resObs = GetObserverUsingId (*observationId);
350 } while (NULL != resObs);
352 OC_LOG_V(INFO, TAG, "GeneratedObservation ID is %u", *observationId);
356 return OC_STACK_ERROR;
359 OCStackResult AddObserver (const char *resUri,
361 OCObservationId obsId,
364 OCResource *resHandle,
365 OCQualityOfService qos,
366 OCPayloadFormat acceptFormat,
367 const OCDevAddr *devAddr)
369 // Check if resource exists and is observable.
372 return OC_STACK_INVALID_PARAM;
374 if (!(resHandle->resourceProperties & OC_OBSERVABLE))
376 return OC_STACK_RESOURCE_ERROR;
378 ResourceObserver *obsNode = NULL;
380 if(!resUri || !token || !*token)
382 return OC_STACK_INVALID_PARAM;
385 obsNode = (ResourceObserver *) OICCalloc(1, sizeof(ResourceObserver));
388 obsNode->observeId = obsId;
390 obsNode->resUri = OICStrdup(resUri);
391 VERIFY_NON_NULL (obsNode->resUri);
394 obsNode->acceptFormat = acceptFormat;
397 obsNode->query = OICStrdup(query);
398 VERIFY_NON_NULL (obsNode->query);
400 // If tokenLength is zero, the return value depends on the
401 // particular library implementation (it may or may not be a null pointer).
404 obsNode->token = (CAToken_t)OICMalloc(tokenLength);
405 VERIFY_NON_NULL (obsNode->token);
406 memcpy(obsNode->token, token, tokenLength);
408 obsNode->tokenLength = tokenLength;
410 obsNode->devAddr = *devAddr;
411 obsNode->resource = resHandle;
413 LL_APPEND (serverObsList, obsNode);
421 OICFree(obsNode->resUri);
422 OICFree(obsNode->query);
425 return OC_STACK_NO_MEMORY;
428 ResourceObserver* GetObserverUsingId (const OCObservationId observeId)
430 ResourceObserver *out = NULL;
434 LL_FOREACH (serverObsList, out)
436 if (out->observeId == observeId)
442 OC_LOG(INFO, TAG, "Observer node not found!!");
446 ResourceObserver* GetObserverUsingToken (const CAToken_t token, uint8_t tokenLength)
448 ResourceObserver *out = NULL;
452 OC_LOG(INFO, TAG, "Looking for token");
453 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
454 OC_LOG(INFO, TAG, "\tFound token:");
456 LL_FOREACH (serverObsList, out)
458 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->token, tokenLength);
459 if((memcmp(out->token, token, tokenLength) == 0))
467 OC_LOG(ERROR, TAG, "Passed in NULL token");
470 OC_LOG(INFO, TAG, "Observer node not found!!");
474 OCStackResult DeleteObserverUsingToken (CAToken_t token, uint8_t tokenLength)
476 if(!token || !*token)
478 return OC_STACK_INVALID_PARAM;
481 ResourceObserver *obsNode = NULL;
483 obsNode = GetObserverUsingToken (token, tokenLength);
486 OC_LOG_V(INFO, TAG, "deleting observer id %u with token", obsNode->observeId);
487 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)obsNode->token, tokenLength);
488 LL_DELETE (serverObsList, obsNode);
489 OICFree(obsNode->resUri);
490 OICFree(obsNode->query);
491 OICFree(obsNode->token);
494 // it is ok if we did not find the observer...
498 void DeleteObserverList()
500 ResourceObserver *out = NULL;
501 ResourceObserver *tmp = NULL;
502 LL_FOREACH_SAFE (serverObsList, out, tmp)
506 DeleteObserverUsingToken ((out->token), out->tokenLength);
509 serverObsList = NULL;
513 * CA layer expects observe registration/de-reg/notiifcations to be passed as a header
514 * option, which breaks the protocol abstraction requirement between RI & CA, and
515 * has to be fixed in the future. The function below adds the header option for observe.
516 * It should be noted that the observe header option is assumed to be the first option
517 * in the list of user defined header options and hence it is inserted at the front
518 * of the header options list and number of options adjusted accordingly.
521 CreateObserveHeaderOption (CAHeaderOption_t **caHdrOpt,
522 OCHeaderOption *ocHdrOpt,
526 if(!caHdrOpt || !ocHdrOpt)
528 return OC_STACK_INVALID_PARAM;
531 CAHeaderOption_t *tmpHdrOpt = NULL;
533 tmpHdrOpt = (CAHeaderOption_t *) OICCalloc ((numOptions+1), sizeof(CAHeaderOption_t));
534 if (NULL == tmpHdrOpt)
536 return OC_STACK_NO_MEMORY;
538 tmpHdrOpt[0].protocolID = CA_COAP_ID;
539 tmpHdrOpt[0].optionID = COAP_OPTION_OBSERVE;
540 tmpHdrOpt[0].optionLength = sizeof(uint8_t);
541 tmpHdrOpt[0].optionData[0] = observeFlag;
542 for (uint8_t i = 0; i < numOptions; i++)
544 memcpy (&(tmpHdrOpt[i+1]), &(ocHdrOpt[i]), sizeof(CAHeaderOption_t));
547 *caHdrOpt = tmpHdrOpt;
552 * CA layer passes observe information to the RI layer as a header option, which
553 * breaks the protocol abstraction requirement between RI & CA, and has to be fixed
554 * in the future. The function below removes the observe header option and processes it.
555 * It should be noted that the observe header option is always assumed to be the first
556 * option in the list of user defined header options and hence it is deleted from the
557 * front of the header options list and the number of options is adjusted accordingly.
560 GetObserveHeaderOption (uint32_t * observationOption,
561 CAHeaderOption_t *options,
562 uint8_t * numOptions)
564 if(!observationOption)
566 return OC_STACK_INVALID_PARAM;
569 if(!options || !numOptions)
571 return OC_STACK_INVALID_PARAM;
574 *observationOption = OC_OBSERVE_NO_OPTION;
576 for(uint8_t i = 0; i < *numOptions; i++)
578 if(options[i].protocolID == CA_COAP_ID &&
579 options[i].optionID == COAP_OPTION_OBSERVE)
581 *observationOption = options[i].optionData[0];
582 for(uint8_t c = i; c < *numOptions-1; c++)
584 options[i] = options[i+1];