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"
29 #include "ocserverrequest.h"
35 #define MOD_NAME PCF("ocobserve")
37 #define TAG PCF("OCStackObserve")
39 #define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG(FATAL, TAG, #arg " is NULL"); goto exit;} }
41 static struct ResourceObserver * serverObsList = NULL;
44 * Determine observe QOS based on the QOS of the request.
45 * The qos passed as a parameter overrides what the client requested.
46 * If we want the client preference taking high priority make:
47 * qos = resourceObserver->qos;
49 * @param method RESTful method.
50 * @param resourceObserver Observer.
51 * @param appQoS Quality of service.
52 * @return The quality of service of the observer.
54 static OCQualityOfService DetermineObserverQoS(OCMethod method,
55 ResourceObserver * resourceObserver, OCQualityOfService appQoS)
59 OC_LOG(ERROR, TAG, "DetermineObserverQoS called with invalid resourceObserver");
63 OCQualityOfService decidedQoS = appQoS;
64 if(appQoS == OC_NA_QOS)
66 decidedQoS = resourceObserver->qos;
69 if(appQoS != OC_HIGH_QOS)
71 OC_LOG_V(INFO, TAG, "Current NON count for this observer is %d",
72 resourceObserver->lowQosCount);
74 if((resourceObserver->forceHighQos \
75 || resourceObserver->lowQosCount >= MAX_OBSERVER_NON_COUNT) \
76 && method != OC_REST_PRESENCE)
78 if(resourceObserver->forceHighQos \
79 || resourceObserver->lowQosCount >= MAX_OBSERVER_NON_COUNT)
82 resourceObserver->lowQosCount = 0;
83 // at some point we have to to send CON to check on the
84 // availability of observer
85 OC_LOG(INFO, TAG, PCF("This time we are sending the notification as High qos"));
86 decidedQoS = OC_HIGH_QOS;
90 (resourceObserver->lowQosCount)++;
97 OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr, uint32_t maxAge,
98 OCResourceType *resourceType, OCQualityOfService qos)
100 OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr, uint32_t maxAge,
101 OCQualityOfService qos)
104 OC_LOG(INFO, TAG, PCF("Entering SendObserverNotification"));
107 return OC_STACK_INVALID_PARAM;
110 OCStackResult result = OC_STACK_ERROR;
111 ResourceObserver * resourceObserver = serverObsList;
113 OCServerRequest * request = NULL;
114 OCEntityHandlerRequest ehRequest = {};
115 OCEntityHandlerResult ehResult = OC_EH_ERROR;
116 bool observeErrorFlag = false;
118 // Find clients that are observing this resource
119 while (resourceObserver)
121 if (resourceObserver->resource == resPtr)
125 if(method != OC_REST_PRESENCE)
128 qos = DetermineObserverQoS(method, resourceObserver, qos);
130 result = AddServerRequest(&request, 0, 0, 0, 1, OC_REST_GET,
131 0, resPtr->sequenceNum, qos, resourceObserver->query,
133 &resourceObserver->token, resourceObserver->tokenLength,
134 resourceObserver->resUri, 0,
135 &(resourceObserver->addressInfo), resourceObserver->connectivityType);
139 request->observeResult = OC_STACK_OK;
140 if(result == OC_STACK_OK)
142 result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request,
143 request->method, (OCResourceHandle) resPtr, request->query,
144 request->reqJSONPayload,
145 request->numRcvdVendorSpecificHeaderOptions,
146 request->rcvdVendorSpecificHeaderOptions,
147 OC_OBSERVE_NO_OPTION, 0);
148 if(result == OC_STACK_OK)
150 ehResult = resPtr->entityHandler(OC_REQUEST_FLAG, &ehRequest);
151 if(ehResult == OC_EH_ERROR)
153 FindAndDeleteServerRequest(request);
162 OCEntityHandlerResponse ehResponse = {};
163 char presenceResBuf[MAX_RESPONSE_LENGTH] = {};
164 //This is effectively the implementation for the presence entity handler.
165 OC_LOG(DEBUG, TAG, PCF("This notification is for Presence"));
166 result = AddServerRequest(&request, 0, 0, 0, 1, OC_REST_GET,
167 0, resPtr->sequenceNum, qos, resourceObserver->query,
169 &resourceObserver->token, resourceObserver->tokenLength,
170 resourceObserver->resUri, 0,
171 &(resourceObserver->addressInfo), resourceObserver->connectivityType);
173 if(result == OC_STACK_OK)
175 // we create the payload here
176 if(resourceType && resourceType->resourcetypename)
178 snprintf((char *)presenceResBuf, sizeof(presenceResBuf), "%u:%u:%s",
179 resPtr->sequenceNum, maxAge, resourceType->resourcetypename);
183 snprintf((char *)presenceResBuf, sizeof(presenceResBuf), "%u:%u",
184 resPtr->sequenceNum, maxAge);
186 ehResponse.ehResult = OC_EH_OK;
187 ehResponse.payload = presenceResBuf;
188 ehResponse.payloadSize = strlen((const char *)presenceResBuf) + 1;
189 ehResponse.persistentBufferFlag = 0;
190 ehResponse.requestHandle = (OCRequestHandle) request;
191 ehResponse.resourceHandle = (OCResourceHandle) resPtr;
192 strcpy((char *)ehResponse.resourceUri, (const char *)resourceObserver->resUri);
193 result = OCDoResponse(&ehResponse);
198 // Since we are in a loop, set an error flag to indicate at least one error occurred.
199 if (result != OC_STACK_OK)
201 observeErrorFlag = true;
204 resourceObserver = resourceObserver->next;
209 OC_LOG(INFO, TAG, PCF("Resource has no observers"));
210 result = OC_STACK_NO_OBSERVERS;
212 else if (observeErrorFlag)
214 OC_LOG(ERROR, TAG, PCF("Observer notification error"));
215 result = OC_STACK_ERROR;
220 OCStackResult SendListObserverNotification (OCResource * resource,
221 OCObservationId *obsIdList, uint8_t numberOfIds,
222 const char *notificationJSONPayload, uint32_t maxAge,
223 OCQualityOfService qos)
225 if(!resource || !obsIdList || !notificationJSONPayload)
227 return OC_STACK_INVALID_PARAM;
230 uint8_t numIds = numberOfIds;
231 ResourceObserver *observation = NULL;
232 uint8_t numSentNotification = 0;
233 OCServerRequest * request = NULL;
234 OCStackResult result = OC_STACK_ERROR;
235 bool observeErrorFlag = false;
237 OC_LOG(INFO, TAG, PCF("Entering SendListObserverNotification"));
240 OC_LOG_V(INFO, TAG, "Need to notify observation id %d", *obsIdList);
241 observation = GetObserverUsingId (*obsIdList);
244 // Found observation - verify if it matches the resource handle
245 if (observation->resource == resource)
247 qos = DetermineObserverQoS(OC_REST_GET, observation, qos);
250 result = AddServerRequest(&request, 0, 0, 0, 1, OC_REST_GET,
251 0, resource->sequenceNum, qos, observation->query,
252 NULL, NULL, &observation->token, observation->tokenLength,
253 observation->resUri, 0,
254 &(observation->addressInfo), observation->connectivityType);
258 request->observeResult = OC_STACK_OK;
259 if(result == OC_STACK_OK)
261 OCEntityHandlerResponse ehResponse = {};
262 ehResponse.ehResult = OC_EH_OK;
263 ehResponse.payload = (char *) OCMalloc(MAX_RESPONSE_LENGTH);
264 if(!ehResponse.payload)
266 FindAndDeleteServerRequest(request);
269 strncpy(ehResponse.payload, notificationJSONPayload, MAX_RESPONSE_LENGTH-1);
270 ehResponse.payloadSize = strlen(ehResponse.payload) + 1;
271 ehResponse.persistentBufferFlag = 0;
272 ehResponse.requestHandle = (OCRequestHandle) request;
273 ehResponse.resourceHandle = (OCResourceHandle) resource;
274 result = OCDoResponse(&ehResponse);
275 if(result == OC_STACK_OK)
277 // Increment sent notifications only if OCDoResponse is successful
278 numSentNotification++;
280 OCFree(ehResponse.payload);
281 FindAndDeleteServerRequest(request);
286 FindAndDeleteServerRequest(request);
289 // Since we are in a loop, set an error flag to indicate
290 // at least one error occurred.
291 if (result != OC_STACK_OK)
293 observeErrorFlag = true;
301 if(numSentNotification == numberOfIds && !observeErrorFlag)
305 else if(numSentNotification == 0)
307 return OC_STACK_NO_OBSERVERS;
311 OC_LOG(ERROR, TAG, PCF("Observer notification error"));
312 return OC_STACK_ERROR;
316 OCStackResult GenerateObserverId (OCObservationId *observationId)
318 ResourceObserver *resObs = NULL;
320 OC_LOG(INFO, TAG, PCF("Entering GenerateObserverId"));
321 VERIFY_NON_NULL (observationId);
325 *observationId = OCGetRandomByte();
326 // Check if observation Id already exists
327 resObs = GetObserverUsingId (*observationId);
328 } while (NULL != resObs);
330 OC_LOG_V(INFO, TAG, "Observation ID is %u", *observationId);
334 return OC_STACK_ERROR;
337 OCStackResult AddObserver (const char *resUri,
339 OCObservationId obsId,
342 OCResource *resHandle,
343 OCQualityOfService qos,
344 const CAAddress_t *addressInfo,
345 CAConnectivityType_t connectivityType)
347 // Check if resource exists and is observable.
350 return OC_STACK_INVALID_PARAM;
352 if (!(resHandle->resourceProperties & OC_OBSERVABLE))
354 return OC_STACK_RESOURCE_ERROR;
356 ResourceObserver *obsNode = NULL;
358 if(!resUri || !token || !*token)
360 return OC_STACK_INVALID_PARAM;
363 obsNode = (ResourceObserver *) OCCalloc(1, sizeof(ResourceObserver));
366 obsNode->observeId = obsId;
368 obsNode->resUri = (char *)OCMalloc(strlen(resUri)+1);
369 VERIFY_NON_NULL (obsNode->resUri);
370 memcpy (obsNode->resUri, resUri, strlen(resUri)+1);
375 obsNode->query = (char *)OCMalloc(strlen(query)+1);
376 VERIFY_NON_NULL (obsNode->query);
377 memcpy (obsNode->query, query, strlen(query)+1);
379 // If tokenLength is zero, the return value depends on the
380 // particular library implementation (it may or may not be a null pointer).
383 obsNode->token = (CAToken_t)OCMalloc(tokenLength);
384 VERIFY_NON_NULL (obsNode->token);
385 memcpy(obsNode->token, *token, tokenLength);
387 obsNode->tokenLength = tokenLength;
388 obsNode->addressInfo = *addressInfo;
389 obsNode->connectivityType = connectivityType;
390 obsNode->resource = resHandle;
391 LL_APPEND (serverObsList, obsNode);
398 OCFree(obsNode->resUri);
399 OCFree(obsNode->query);
402 return OC_STACK_NO_MEMORY;
405 ResourceObserver* GetObserverUsingId (const OCObservationId observeId)
407 ResourceObserver *out = NULL;
411 LL_FOREACH (serverObsList, out)
413 if (out->observeId == observeId)
419 OC_LOG(INFO, TAG, PCF("Observer node not found!!"));
423 ResourceObserver* GetObserverUsingToken (const CAToken_t * token, uint8_t tokenLength)
425 ResourceObserver *out = NULL;
429 LL_FOREACH (serverObsList, out)
431 OC_LOG(INFO, TAG,PCF("comparing tokens"));
432 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
433 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->token, tokenLength);
434 if((memcmp(out->token, *token, tokenLength) == 0))
440 OC_LOG(INFO, TAG, PCF("Observer node not found!!"));
444 OCStackResult DeleteObserverUsingToken (CAToken_t * token, uint8_t tokenLength)
446 if(!token || !*token)
448 return OC_STACK_INVALID_PARAM;
451 ResourceObserver *obsNode = NULL;
453 obsNode = GetObserverUsingToken (token, tokenLength);
456 OC_LOG_V(INFO, TAG, PCF("deleting tokens"));
457 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)obsNode->token, tokenLength);
458 LL_DELETE (serverObsList, obsNode);
459 OCFree(obsNode->resUri);
460 OCFree(obsNode->query);
461 OCFree(obsNode->token);
464 // it is ok if we did not find the observer...
468 void DeleteObserverList()
470 ResourceObserver *out = NULL;
471 ResourceObserver *tmp = NULL;
472 LL_FOREACH_SAFE (serverObsList, out, tmp)
476 DeleteObserverUsingToken (&(out->token), out->tokenLength);
479 serverObsList = NULL;
483 * CA layer expects observe registration/de-reg/notiifcations to be passed as a header
484 * option, which breaks the protocol abstraction requirement between RI & CA, and
485 * has to be fixed in the future. The function below adds the header option for observe.
486 * It should be noted that the observe header option is assumed to be the first option
487 * in the list of user defined header options and hence it is inserted at the front
488 * of the header options list and number of options adjusted accordingly.
491 CreateObserveHeaderOption (CAHeaderOption_t **caHdrOpt,
492 OCHeaderOption *ocHdrOpt,
498 return OC_STACK_INVALID_PARAM;
501 CAHeaderOption_t *tmpHdrOpt = NULL;
503 tmpHdrOpt = (CAHeaderOption_t *) OCMalloc ((numOptions+1)*sizeof(CAHeaderOption_t));
504 if (NULL == tmpHdrOpt)
506 return OC_STACK_NO_MEMORY;
508 tmpHdrOpt[0].protocolID = CA_COAP_ID;
509 tmpHdrOpt[0].optionID = COAP_OPTION_OBSERVE;
510 tmpHdrOpt[0].optionLength = sizeof(uint32_t);
511 tmpHdrOpt[0].optionData[0] = observeFlag;
512 for (uint8_t i = 0; i < numOptions; i++)
514 memcpy (&(tmpHdrOpt[i+1]), &(ocHdrOpt[i]), sizeof(CAHeaderOption_t));
517 *caHdrOpt = tmpHdrOpt;
522 * CA layer passes observe information to the RI layer as a header option, which
523 * breaks the protocol abstraction requirement between RI & CA, and has to be fixed
524 * in the future. The function below removes the observe header option and processes it.
525 * It should be noted that the observe header option is always assumed to be the first
526 * option in the list of user defined header options and hence it is deleted from the
527 * front of the header options list and the number of options is adjusted accordingly.
530 GetObserveHeaderOption (uint32_t * observationOption,
531 CAHeaderOption_t *options,
532 uint8_t * numOptions)
534 if(!observationOption)
536 return OC_STACK_INVALID_PARAM;
538 *observationOption = OC_OBSERVE_NO_OPTION;
540 if(!options || !numOptions)
542 return OC_STACK_INVALID_PARAM;
545 for(uint8_t i = 0; i < *numOptions; i++)
547 if(options[i].protocolID == CA_COAP_ID &&
548 options[i].optionID == COAP_OPTION_OBSERVE)
550 *observationOption = options[i].optionData[0];
551 for(uint8_t c = i; c < *numOptions-1; c++)
553 options[i].protocolID = options[i+1].protocolID;
554 options[i].optionID = options[i+1].optionID;
555 options[i].optionLength = options[i+1].optionLength;
556 memcpy(options[i].optionData, options[i+1].optionData, options[i+1].optionLength);