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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
25 #include "ocstackconfig.h"
31 //-----------------------------------------------------------------------------
33 //-----------------------------------------------------------------------------
35 //TODO: May want to refactor this in upcoming sprints.
36 //Don't want to expose to application layer that lower level stack is using CoAP.
37 #define OC_WELL_KNOWN_QUERY "coap://224.0.1.187:5683/oc/core"
38 #define OC_EXPLICIT_DEVICE_DISCOVERY_URI "coap://224.0.1.187:5683/oc/core?rt=core.led"
39 #define OC_MULTICAST_PREFIX "coap://224.0.1.187:5683"
40 #define OC_MULTICAST_IP "coap://224.0.1.187"
42 #define USE_RANDOM_PORT (0)
44 #define OC_DEFAULT_PRESENCE_TTL (60)
45 #define OC_PRESENCE_URI "/oc/presence"
46 extern uint8_t PresenceTimeOutSize; // length of PresenceTimeOut - 1
47 extern uint32_t PresenceTimeOut[];
49 //-----------------------------------------------------------------------------
51 //-----------------------------------------------------------------------------
54 * OC Virtual resources supported by every OC device
57 OC_WELL_KNOWN_URI= 0, // "/oc/core"
58 OC_DEVICE_URI, // "/oc/core/d"
59 OC_RESOURCE_TYPES_URI, // "/oc/core/d/type"
61 OC_PRESENCE, // "/oc/presence"
63 OC_MAX_VIRTUAL_RESOURCES // Max items in the list
67 * Standard RESTful HTTP Methods
71 OC_REST_GET = (1 << 0), // Read
72 OC_REST_PUT = (1 << 1), // Write
73 OC_REST_POST = (1 << 2), // Update
74 OC_REST_DELETE = (1 << 3), // Delete
75 // Register observe request for most up date notifications ONLY.
76 OC_REST_OBSERVE = (1 << 4),
77 // Register observe request for all notifications, including stale notifications.
78 OC_REST_OBSERVE_ALL = (1 << 5),
79 // Deregister observation, intended for internal use
80 OC_REST_CANCEL_OBSERVE = (1 << 6),
82 // Subscribe for all presence notifications of a particular resource.
83 OC_REST_PRESENCE = (1 << 7)
88 * Host Mode of Operation
96 extern OCMode myStackMode;
104 OC_NA_QOS // No Quality is defined, let the stack decide
105 } OCQualityOfService;
108 * Resource Properties
110 * OC_ACTIVE - When this bit is set, the resource is initialized, otherwise the resource
111 * is 'inactive'. 'inactive' signifies that the resource has been marked for
112 * deletion or is already deleted.
113 * OC_DISCOVERABLE - When this bit is set, the resource is allowed to be discovered by clients.
114 * OC_OBSERVABLE - When this bit is set, the resource is allowed to be observed by clients.
115 * OC_SLOW - When this bit is set, the resource has been marked as 'slow'. 'slow' signifies
116 * that responses from this resource can expect delays in processing its
117 * requests from clients.
118 * OC_SECURE - When this bit is set, the resource is a secure resource.
121 OC_ACTIVE = (1 << 0),
122 OC_DISCOVERABLE = (1 << 1),
123 OC_OBSERVABLE = (1 << 2),
126 } OCResourceProperty;
129 * Transport Protocol IDs
132 OC_INVALID_ID = (1 << 0),
133 OC_COAP_ID = (1 << 1)
134 } OCTransportProtocolID;
137 * Declares Stack Results & Errors
140 /* Success status code - START HERE */
142 OC_STACK_RESOURCE_CREATED,
143 OC_STACK_RESOURCE_DELETED,
144 /* Success status code - END HERE */
145 /* Error status code - START HERE */
146 OC_STACK_INVALID_URI,
147 OC_STACK_INVALID_QUERY,
149 OC_STACK_INVALID_PORT,
150 OC_STACK_INVALID_CALLBACK,
151 OC_STACK_INVALID_METHOD,
152 OC_STACK_INVALID_PARAM,
153 OC_STACK_INVALID_OBSERVE_PARAM,
157 OC_STACK_NO_RESOURCE, /* resource not found */
158 OC_STACK_RESOURCE_ERROR, /* ex: not supported method or interface */
159 OC_STACK_SLOW_RESOURCE,
160 OC_STACK_NO_OBSERVERS, /* resource has no registered observers */
161 OC_STACK_OBSERVER_NOT_FOUND,
162 OC_STACK_OBSERVER_NOT_ADDED,
163 OC_STACK_OBSERVER_NOT_REMOVED,
165 OC_STACK_PRESENCE_STOPPED,
166 OC_STACK_PRESENCE_DO_NOT_HANDLE,
168 OC_STACK_INVALID_OPTION,
169 OC_STACK_MALFORMED_RESPONSE, /* the remote reply contained malformed data */
171 /* Error status code - END HERE */
175 * Handle to an @ref OCDoResource invocation.
177 typedef void * OCDoHandle;
180 * Handle to an OCResource object owned by the OCStack.
182 typedef void * OCResourceHandle;
185 * Unique identifier for each observation request. Used when observations are
186 * registered or deregistering. Used by entity handler to signal specific
187 * observers to be notified of resource changes.
188 * There can be maximum of 256 observations per server.
190 typedef uint8_t OCObservationId;
193 * Action associated with observation
196 OC_OBSERVE_REGISTER = 0,
197 OC_OBSERVE_DEREGISTER = 1,
198 OC_OBSERVE_NO_OPTION = 2
202 // Action associated with observation request
203 OCObserveAction action;
204 // Identifier for observation being registered/deregistered
205 OCObservationId obsId;
208 // following structure will be used to define the vendor specific header options to be included
209 // in communication packets
211 typedef struct OCHeaderOption {
212 // The protocol ID this option applies to
213 OCTransportProtocolID protocolID;
214 // The header option ID which will be added to communication packets
217 uint16_t optionLength;
218 // pointer to its data
219 uint8_t optionData[MAX_HEADER_OPTION_DATA_LENGTH];
223 * Incoming requests handled by the server. Requests are passed in as a parameter to the @ref OCEntityHandler callback API.
224 * @brief The @ref OCEntityHandler callback API must be implemented in the application in order to receive these requests.
227 // Associated resource
228 OCResourceHandle resource;
229 // resource query send by client
230 unsigned char * query;
231 // the REST method retrieved from received request PDU
233 // reqJSON is retrieved from the payload of the received request PDU
234 unsigned const char * reqJSONPayload;
235 // resJSON is allocated in the stack and will be used by entity handler to fill in its response
236 unsigned char * resJSONPayload;
237 // Length of maximum allowed response
238 uint16_t resJSONPayloadLen;
239 // Information associated with observation - valid only when OCEntityHandler
240 // flag includes OC_OBSERVE_FLAG
241 OCObservationInfo *obsInfo;
242 // An array of the received vendor specific header options
243 uint8_t numRcvdVendorSpecificHeaderOptions;
244 OCHeaderOption rcvdVendorSpecificHeaderOptions[MAX_HEADER_OPTIONS];
245 // An array of the vendor specific header options the entity handler wishes to use in response
246 uint8_t numSendVendorSpecificHeaderOptions;
247 OCHeaderOption sendVendorSpecificHeaderOptions[MAX_HEADER_OPTIONS];
248 // URI of new resource that entity handler might create
249 unsigned char *newResourceUri;
251 }OCEntityHandlerRequest;
254 * Response from queries to remote servers. Queries are made by calling the @ref OCDoResource API.
257 // the is the result of our stack, OCStackResult should contain coap/other error codes;
258 OCStackResult result;
259 // Address of remote server
261 // If associated with observe, this will represent the sequence of notifications from server.
262 uint32_t sequenceNumber;
263 // resJSONPayload is retrieved from the payload of the received request PDU
264 unsigned const char * resJSONPayload;
265 // An array of the received vendor specific header options
266 uint8_t numRcvdVendorSpecificHeaderOptions;
267 OCHeaderOption rcvdVendorSpecificHeaderOptions[MAX_HEADER_OPTIONS];
271 OC_INIT_FLAG = (1 << 0),
272 OC_REQUEST_FLAG = (1 << 1),
273 OC_OBSERVE_FLAG = (1 << 2)
274 } OCEntityHandlerFlag; //entity_handler_flag_t ;
276 // possible returned values from client application
278 OC_STACK_DELETE_TRANSACTION = 0,
279 OC_STACK_KEEP_TRANSACTION
280 } OCStackApplicationResult;
282 //-----------------------------------------------------------------------------
283 // Callback function definitions
284 //-----------------------------------------------------------------------------
287 * Client applications implement this callback to consume responses received from Servers.
289 typedef OCStackApplicationResult (* OCClientResponseHandler)(void *context, OCDoHandle handle,
290 OCClientResponse * clientResponse);
293 * Client applications using a context pointer implement this callback to delete the
294 * context upon removal of the callback/context pointer from the internal callback-list
296 typedef void (* OCClientContextDeleter)(void *context);
299 * This info is passed from application to OC Stack when initiating a request to Server
303 OCClientResponseHandler cb;
304 OCClientContextDeleter cd;
308 * Possible returned values from entity handler
313 OC_EH_RESOURCE_CREATED,
314 OC_EH_RESOURCE_DELETED,
316 } OCEntityHandlerResult;
319 * Application server implementations must implement this callback to consume requests OTA.
320 * Entity handler callback needs to fill the resPayload of the entityHandlerRequest.
322 typedef OCEntityHandlerResult (*OCEntityHandler)
323 (OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest);
326 * Device Entity handler need to use this call back instead of OCEntityHandler
328 typedef OCEntityHandlerResult (*OCDeviceEntityHandler)
329 (OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest, char* uri);
331 //-----------------------------------------------------------------------------
332 // Function prototypes
333 //-----------------------------------------------------------------------------
336 * Initialize the OC Stack. Must be called prior to starting the stack.
339 * IP Address of host device
341 * Port of host device
343 * Host device is client, server, or client-server
346 * OC_STACK_OK - no errors
347 * OC_STACK_ERROR - stack init error
349 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode);
352 * Stop the OC stack. Use for a controlled shutdown.
354 * Note: OCStop() performs operations similar to OCStopPresence(), as well as OCDeleteResource() on
355 * all resources this server is hosting. OCDeleteResource() performs operations similar to
356 * OCNotifyAllObservers() to notify all client observers that the respective resource is being
360 * OC_STACK_OK - no errors
361 * OC_STACK_ERROR - stack not initialized
363 OCStackResult OCStop();
366 * Called in main loop of OC client or server. Allows low-level processing of
370 * OC_STACK_OK - no errors
371 * OC_STACK_ERROR - stack process error
373 OCStackResult OCProcess();
376 * Discover or Perform requests on a specified resource (specified by that Resource's respective URI).
378 * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of calling this API.
379 * @param method - @ref OCMethod to perform on the resource
380 * @param requiredUri - URI of the resource to interact with
381 * @param referenceUri - URI of the reference resource
382 * @param request - JSON encoded request
383 * @param qos - quality of service
384 * @param clientApplicationCB- asynchronous callback function that is invoked
385 * by the stack when discovery or resource interaction is complete
386 * @param options - The address of an array containing the vendor specific
387 * header options to be sent with the request
388 * @param numOptions - Number of header options to be included
391 * OC_STACK_OK - no errors
392 * OC_STACK_INVALID_CALLBACK - invalid callback function pointer
393 * OC_STACK_INVALID_METHOD - invalid resource method
394 * OC_STACK_INVALID_URI - invalid required or reference URI
396 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri, const char *referenceUri,
397 const char *request, OCQualityOfService qos, OCCallbackData *cbData, OCHeaderOption * options,
401 * Cancel a request associated with a specific @ref OCDoResource invocation.
403 * @param handle - Used to identify a specific OCDoResource invocation.
404 * @param qos - used to specify Quality of Service (read below for more info)
405 * @param options- used to specify vendor specific header options when sending
406 * explicit observe cancellation
407 * @param numOptions- Number of header options to be included
410 * OC_STACK_OK - No errors; Success
411 * OC_STACK_INVALID_PARAM - The handle provided is invalid.
413 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
418 * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
419 * presence notifications to clients via multicast. Once this API has been called with a success,
420 * clients may query for this server's presence and this server's stack will respond via multicast.
422 * Server can call this function when it comes online for the first time, or when it comes back
423 * online from offline mode, or when it re enters network.
425 * @param ttl - Time To Live in seconds
426 * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
429 * OC_STACK_OK - No errors; Success
431 OCStackResult OCStartPresence(const uint32_t ttl);
434 * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
435 * presence notifications to clients via multicast. Once this API has been called with a success,
436 * this server's stack will not respond to clients querying for this server's presence.
438 * Server can call this function when it is terminating, going offline, or when going
442 * OC_STACK_OK - No errors; Success
445 OCStackResult OCStopPresence();
450 * Set default device entity handler
452 * @param entityHandler - entity handler function that is called by ocstack to handle requests for
453 * any undefined resources or default actions.
454 * if NULL is passed it removes the device default entity handler.
457 * OC_STACK_OK - no errors
458 * OC_STACK_ERROR - stack process error
460 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler);
465 * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource
466 * @param resourceTypeName - name of resource type. Example: "core.led"
467 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
468 * @param uri - URI of the resource. Example: "/a/led"
469 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
470 * NULL for default entity handler
471 * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE
474 * OC_STACK_OK - no errors
475 * OC_STACK_ERROR - stack process error
477 OCStackResult OCCreateResource(OCResourceHandle *handle,
478 const char *resourceTypeName,
479 const char *resourceInterfaceName,
481 OCEntityHandler entityHandler,
482 uint8_t resourceProperties);
485 * Create a resource. with host ip address for remote resource
487 * @param handle - pointer to handle to newly created resource. Set by ocstack.
488 * Used to refer to resource
489 * @param resourceTypeName - name of resource type. Example: "core.led"
490 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
491 * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx"
492 * @param uri - URI of the resource. Example: "/a/led"
493 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
494 * NULL for default entity handler
495 * @param resourceProperties - properties supported by resource.
496 * Example: OC_DISCOVERABLE|OC_OBSERVABLE
499 * OC_STACK_OK - no errors
500 * OC_STACK_ERROR - stack process error
502 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
503 const char *resourceTypeName,
504 const char *resourceInterfaceName,
507 OCEntityHandler entityHandler,
508 uint8_t resourceProperties);
511 * Add a resource to a collection resource.
513 * @param collectionHandle - handle to the collection resource
514 * @param resourceHandle - handle to resource to be added to the collection resource
517 * OC_STACK_OK - no errors
518 * OC_STACK_ERROR - stack process error
519 * OC_STACK_INVALID_PARAM - invalid collectionhandle
521 OCStackResult OCBindResource(OCResourceHandle collectionHandle, OCResourceHandle resourceHandle);
524 * Remove a resource from a collection resource.
526 * @param collectionHandle - handle to the collection resource
527 * @param resourceHandle - handle to resource to be removed from the collection resource
530 * OC_STACK_OK - no errors
531 * OC_STACK_ERROR - stack process error
532 * OC_STACK_INVALID_PARAM - invalid collectionhandle
534 OCStackResult OCUnBindResource(OCResourceHandle collectionHandle, OCResourceHandle resourceHandle);
537 * Bind a resourcetype to a resource.
539 * @param handle - handle to the resource
540 * @param resourceTypeName - name of resource type. Example: "core.led"
543 * OC_STACK_OK - no errors
544 * OC_STACK_ERROR - stack process error
546 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
547 const char *resourceTypeName);
549 * Bind a resource interface to a resource.
551 * @param handle - handle to the resource
552 * @param resourceInterfaceName - name of resource interface. Example: "core.rw"
555 * OC_STACK_OK - no errors
556 * OC_STACK_ERROR - stack process error
558 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
559 const char *resourceInterfaceName);
562 * Bind an entity handler to the resource.
564 * @param handle - handle to the resource that the contained resource is to be bound
565 * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
567 * OC_STACK_OK - no errors
568 * OC_STACK_ERROR - stack process error
570 OCStackResult OCBindResourceHandler(OCResourceHandle handle, OCEntityHandler entityHandler);
573 * Get the number of resources that have been created in the stack.
575 * @param numResources - pointer to count variable
578 * OC_STACK_OK - no errors
579 * OC_STACK_ERROR - stack process error
582 OCStackResult OCGetNumberOfResources(uint8_t *numResources);
585 * Get a resource handle by index.
587 * @param index - index of resource, 0 to Count - 1
590 * Resource handle - if found
591 * NULL - if not found
593 OCResourceHandle OCGetResourceHandle(uint8_t index);
596 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
599 * Note: OCDeleteResource() performs operations similar to OCNotifyAllObservers() to notify all
600 * client observers that "this" resource is being deleted.
602 * @param handle - handle of resource to be deleted
605 * OC_STACK_OK - no errors
606 * OC_STACK_ERROR - stack process error
608 OCStackResult OCDeleteResource(OCResourceHandle handle);
611 * Get the URI of the resource specified by handle.
613 * @param handle - handle of resource
615 * URI string - if resource found
616 * NULL - resource not found
618 const char *OCGetResourceUri(OCResourceHandle handle);
621 * Get the properties of the resource specified by handle.
622 * NOTE: that after a resource is created, the OC_ACTIVE property is set
623 * for the resource by the stack.
625 * @param handle - handle of resource
627 * property bitmap - if resource found
628 * NULL - resource not found
630 uint8_t OCGetResourceProperties(OCResourceHandle handle);
633 * Get the number of resource types of the resource.
635 * @param handle - handle of resource
636 * @param numResourceTypes - pointer to count variable
639 * OC_STACK_OK - no errors
640 * OC_STACK_ERROR - stack process error
642 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle, uint8_t *numResourceTypes);
645 * Get name of resource type of the resource.
647 * @param handle - handle of resource
648 * @param index - index of resource, 0 to Count - 1
651 * resource type name - if resource found
652 * NULL - resource not found
654 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index);
657 * Get the number of resource interfaces of the resource.
659 * @param handle - handle of resource
660 * @param numResources - pointer to count variable
663 * OC_STACK_OK - no errors
664 * OC_STACK_ERROR - stack process error
667 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle, uint8_t *numResourceInterfaces);
670 * Get name of resource interface of the resource.
672 * @param handle - handle of resource
673 * @param index - index of resource, 0 to Count - 1
676 * resource interface name - if resource found
677 * NULL - resource not found
679 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index);
682 * Get methods of resource interface of the resource.
684 * @param handle - handle of resource
685 * @param index - index of resource, 0 to Count - 1
688 * allowed methods - if resource found
689 * NULL - resource not found
691 uint8_t OCGetResourceInterfaceAllowedMethods(OCResourceHandle handle, uint8_t index);
694 * Get resource handle from the collection resource by index.
696 * @param collectionHandle - handle of collection resource
697 * @param index - index of contained resource, 0 to Count - 1
700 * handle to contained resource - if resource found
701 * NULL - resource not found
703 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle, uint8_t index);
706 * Get the entity handler for a resource.
708 * @param handle - handle of resource
711 * entity handler - if resource found
712 * NULL - resource not found
714 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle);
717 * Notify all registered observers that the resource representation has
718 * changed. If observation includes a query the client is notified only
719 * if the query is valid after the resource representation has changed.
721 * @param handle - handle of resource
724 * OC_STACK_OK - no errors
725 * OC_STACK_NO_RESOURCE - invalid resource handle
726 * OC_STACK_NO_OBSERVERS - no more observers intrested in resource
728 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos);
731 * Notify specific observers with updated value of representation.
732 * Before this API is invoked by entity handler it has finished processing
733 * queries for the associated observers.
735 * @param handle - handle of resource
736 * @param obsIdList - list of observation ids that need to be notified
737 * @param numberOfIds - number of observation ids included in obsIdList
738 * @param notificationJSONPayload - JSON encoded payload to send in notification
739 * NOTE: The memory for obsIdList and notificationJSONPayload is managed by the
740 * entity invoking the API. The maximum size of the notification is 1015 bytes
741 * for non-Arduino platforms. For Arduino the maximum size is 247 bytes.
744 * OC_STACK_OK - no errors
745 * OC_STACK_NO_RESOURCE - invalid resource handle
748 OCNotifyListOfObservers (OCResourceHandle handle,
749 OCObservationId *obsIdList,
751 unsigned char *notificationJSONPayload,
752 OCQualityOfService qos);
756 #endif // __cplusplus
758 #endif /* OCSTACK_H_ */