blob: ef5b49dd8e3c367a3f0f0c38dc612e4c0feea809 [file] [log] [blame]
Qiufang Dai35c31332020-05-13 15:29:06 +08001/*
2 * Amazon FreeRTOS
3 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 * this software and associated documentation files (the "Software"), to deal in
7 * the Software without restriction, including without limitation the rights to
8 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 * the Software, and to permit persons to whom the Software is furnished to do so,
10 * subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 *
22 * http://aws.amazon.com/freertos
23 * http://www.FreeRTOS.org
24 */
25
26/**
27 * @file aws_shadow.h
28 * @brief Shadow API configuration, functions, and parameter structs.
29 */
30
31#ifndef _AWS_SHADOW_H_
32#define _AWS_SHADOW_H_
33
34#include "FreeRTOS.h"
35
36#include "aws_mqtt_agent.h"
37
38
39/**
40 * @brief The handle of a Shadow Client.
41 */
42typedef void * ShadowClientHandle_t;
43
44/**
45 * @brief Return values of Shadow API functions.
46 *
47 * Negative values indicate jsmn (JSON parser) errors, and @c 0 indicates
48 * success. Positive values indicate other errors. Values in the range of @c 400
49 * to @c 500 correspond to Shadow service rejection reasons.
50 *
51 * Refer to jsmn.h for jsmn errors.
52 *
53 * Refer to
54 * http://docs.aws.amazon.com/iot/latest/developerguide/thing-shadow-error-messages.html
55 * for Shadow service rejection reasons.
56 */
57#define eShadowJSMNPart ( -3 )
58#define eShadowJSMNInval ( -2 )
59#define eShadowJSMNNoMem ( -1 )
60
61/** An operation was accepted by the Shadow service, and all subroutines
62 * completed successfully. */
63#define eShadowSuccess ( 0 )
64
65/** Timeout signifies that at least one of the API call's subroutines failed to
66 * complete within the given time. This error can usually be fixed by increasing
67 * the timeout parameter.
68 * @note
69 * - Timeout doesn't always imply rejection. An operation may still be accepted
70 * after a timeout. However, the Shadow Client will not notify of acceptance or
71 * rejection after a timeout.
72 * - If an update fails because of incorrect JSON syntax in the update document,
73 * the update API call will return this code instead of @c eShadowRejectedBadRequest
74 * and print an error message if #shadowENABLE_DEBUG_LOGS is @c 1. */
75#define eShadowTimeout ( 1 )
76
77/** Failure code; signifies that at least one subroutine failed to complete
78 * and did not time out. */
79#define eShadowFailure ( 2 )
80
81/** Indicates neither failure nor success. This value should never be returned
82 * by a Shadow API function, but is used internally. */
83#define eShadowUnknown ( 3 )
84
85/**
86 * @brief Shadow service rejection reasons. */
87/** @{ */
88#define eShadowRejectedBadRequest ( 400 )
89#define eShadowRejectedUnauthorized ( 401 )
90#define eShadowRejectedForbidden ( 403 )
91#define eShadowRejectedNotFound ( 404 )
92#define eShadowRejectedConflict ( 409 )
93#define eShadowRejectedPayloadTooLarge ( 413 )
94#define eShadowRejectedUnsupportedMediaType ( 415 )
95#define eShadowRejectedTooManyRequests ( 429 )
96#define eShadowRejectedInternalServerError ( 500 )
97typedef int16_t ShadowReturnCode_t;
98/** @} */
99
100/**
101 * @brief Type of MQTT client in a new Shadow Client.
102 *
103 * The possible values of #ShadowCreateParams_t.xMQTTClientType; determines
104 * whether to initialize a shared or dedicated MQTT client.
105 * @note Only #eDedicatedMQTTClient is supported at this time.
106 */
107typedef enum ShadowMQTTClientType
108{
109 /** A shared MQTT client that may be used for purposes other than Shadow
110 * Client. Currently unsupported. */
111 eSharedMQTTClient,
112 /** A dedicated MQTT client to be used only by Shadow Client. */
113 eDedicatedMQTTClient
114} ShadowMQTTClientType_t;
115
116/**
117 * @brief Parameters to pass into #SHADOW_ClientCreate.
118 */
119typedef struct ShadowCreateParams
120{
121 /**
122 * @brief MQTT Client type.
123 *
124 * Whether the new Shadow Client will use a shared or dedicated MQTT Client.
125 * Currently, only #eDedicatedMQTTClient is supported.
126 * @see ShadowMQTTClientType. */
127 ShadowMQTTClientType_t xMQTTClientType;
128
129 /**
130 * @brief Handle of a shared MQTT client.
131 *
132 * If #ShadowCreateParams_t.xMQTTClientType is #eSharedMQTTClient, set this to
133 * the handle of the shared client. This member is ignored if
134 #ShadowCreateParams_t.xMQTTClientType is #eDedicatedMQTTClient. */
135 MQTTAgentHandle_t xMQTTClientHandle;
136} ShadowCreateParams_t;
137
138/**
139 * @brief Parameters for a Shadow API operation.
140 *
141 * Pass this struct as one of the arguments for #SHADOW_Update, #SHADOW_Get, or
142 * #SHADOW_Delete.
143 */
144typedef struct ShadowOperationParams
145{
146 /** @brief Thing name of Shadow. */
147 const char * pcThingName;
148
149 /**
150 * @brief Input parameter for #SHADOW_Update; output parameter of #SHADOW_Get.
151 * - For #SHADOW_Update, set this to point to the Shadow update document.
152 * - For #SHADOW_Get, this is the output parameter pointing to a buffer which
153 * holds the Shadow document. If #SHADOW_Get fails, this will be set to NULL.
154 * - This member is ignored by #SHADOW_Delete. */
155 const char * pcData;
156
157 /**
158 * @brief Input parameter for #SHADOW_Update; output parameter of #SHADOW_Get.
159 * - For #SHADOW_Update, set this to length of the Shadow update document.
160 * - For #SHADOW_Get, this is the output parameter specifying the length of
161 #ShadowOperationParams_t.pcData. If #SHADOW_Get fails, this will be set
162 * to @c 0.
163 * @note If the received Shadow document is longer than this value, the
164 * document will be truncated. A warning message will be printed if
165 #shadowENABLE_DEBUG_LOGS is @c 1.
166 * - This member is ignored by #SHADOW_Delete. */
167 uint32_t ulDataLength;
168
169 /**
170 * @brief Output parameter of #SHADOW_Get.
171 * - This member is ignored by #SHADOW_Update.
172 * - For #SHADOW_Get, this is the output parameter for the MQTT Buffer Handle.
173 * This buffer must be returned to the MQTT Client after the user is done
174 * with the received document by calling #SHADOW_ReturnMQTTBuffer.
175 * - This member is ignored by #SHADOW_Delete. */
176 MQTTBufferHandle_t xBuffer;
177
178 /**
179 * @brief Controls whether topic subscriptions remain active after a Shadow
180 * operation completes.
181 *
182 * Allows the MQTT subscriptions of the operation to remain active if set
183 * to @c 1, saving time if the same operation is performed again. Set this
184 * value to @c 0 to deactivate the operation's MQTT subscriptions after the
185 * operation completes.
186 * @warning Users may be billed for extraneous messages received on an
187 * operation's MQTT topics. If other clients are publishing to the same topics,
188 * it is best to deactivate the subscriptions. */
189 uint8_t ucKeepSubscriptions;
190
191 /**
192 * @brief MQTT QoS when publishing from the Shadow Client @b to the Shadow Service.
193 * @note The Shadow services always publishes to the Shadow Client with QoS 1. */
194 MQTTQoS_t xQoS;
195} ShadowOperationParams_t;
196
197/**
198 * @brief Function signature of a callback function registered for /update/documents.
199 *
200 * @param in: Custom user data.
201 * @param pcThingName The Thing Name of the updated Shadow.
202 * @param pcUpdateDocument The update document, a JSON string.
203 * @param ulDocumentLength The length of the update document.
204 * @param xBuffer The MQTT buffer containing @p pcUpdateDocument. This buffer
205 * must eventually be returned by calling #SHADOW_ReturnMQTTBuffer if taken.
206 *
207 * @return
208 * - pdTRUE to take ownership of the MQTT buffer containing pcUpdateDocument
209 * - pdFALSE to leave pcUpdateDocument with the MQTT client. The MQTT client
210 * may overwrite pcUpdateDocument.
211 *
212 * @note Callback functions are called from the MQTT task.
213 * @warning
214 * - <b> Do not make any blocking calls (including #SHADOW_Update, #SHADOW_Get, or
215 * #SHADOW_Delete) in a callback function! </b>
216 * - The MQTT client does not guarantee that messages on /update/documents
217 * will be received in the order they were published. If updates are being
218 * performed frequently, it is possible to receive newer update documents
219 * before older ones.
220 */
221typedef BaseType_t ( * ShadowUpdatedCallback_t )( void * pvUserData,
222 const char * const pcThingName,
223 const char * const pcUpdateDocument,
224 uint32_t ulDocumentLength,
225 MQTTBufferHandle_t xBuffer );
226
227/**
228 * @brief Function header of a callback function registered for /delete/accepted.
229 *
230 * @param in: Custom user data.
231 * @param pcThingName The Name of the Thing whose Shadow was deleted.
232 *
233 * @note Callback functions are called from the MQTT task.
234 * @warning <b> Do not make any blocking calls (including #SHADOW_Update, #SHADOW_Get, or
235 * #SHADOW_Delete) in a callback function! </b>
236 */
237typedef void ( * ShadowDeletedCallback_t )( void * pvUserData,
238 const char * const pcThingName );
239
240/**
241 * @brief Function header of a callback function registered for /update/delta.
242 *
243 * @param in: Custom user data.
244 * @param pcThingName The Thing Name of the delta document.
245 * @param pcDeltaDocument The delta document, a JSON string.
246 * @param ulDocumentLength The length of the delta document.
247 * @param xBuffer The MQTT buffer containing @p pcDeltaDocument. This buffer
248 * must eventually be returned by calling #SHADOW_ReturnMQTTBuffer if taken.
249 *
250 * @return
251 * - pdTRUE to take ownership of the MQTT buffer containing pcDeltaDocument
252 * - pdFALSE to leave pcDeltaDocument with the MQTT client. The MQTT client
253 * may overwrite pcDeltaDocument.
254 *
255 * @note Callback functions are called from the MQTT task.
256 * @warning
257 * - <b> Do not make any blocking calls (including #SHADOW_Update, #SHADOW_Get, or
258 * #SHADOW_Delete) in a callback function! </b>
259 * - The MQTT client does not guarantee that messages on /update/delta
260 * will be received in the order they were published. If updates are being
261 * performed frequently, it is possible to receive newer delta documents
262 * before older ones.
263 */
264typedef BaseType_t ( * ShadowDeltaCallback_t )( void * pvUserData,
265 const char * const pcThingName,
266 const char * const pcDeltaDocument,
267 uint32_t ulDocumentLength,
268 MQTTBufferHandle_t xBuffer );
269
270/**
271 * @brief Parameters to #SHADOW_RegisterCallbacks.
272 */
273typedef struct ShadowCallbackParams
274{
275 /** @brief Thing Name for which callbacks are registered. */
276 const char * pcThingName;
277
278 /**
279 * @brief Called to notify users that a Thing Shadow has been updated.
280 *
281 * Callback for a message on /update/documents. Set to NULL for no callback.
282 * @note This function @b will be called if the same Shadow Client that registered
283 * the callback function updated the Thing Shadow. */
284 ShadowUpdatedCallback_t xShadowUpdatedCallback;
285
286 /**
287 * @brief Called to notify users that @b another client has deleted the Thing Shadow.
288 *
289 * Callback for a message on /delete/accepted. Set to NULL for no callback.
290 * @note This function <b>will not</b> be called if the same Shadow Client that
291 * registered the callback function deleted the Thing Shadow. */
292 ShadowDeletedCallback_t xShadowDeletedCallback;
293
294 /**
295 * @brief Called to notify users that a delta document has been generated.
296 *
297 * Callback for a message on /delete/accepted. Set to NULL for no callback.
298 * @note This function @b will be called whenever a delta document is generated,
299 * regardless of which client performed an update. */
300 ShadowDeltaCallback_t xShadowDeltaCallback;
301} ShadowCallbackParams_t;
302
303/**
304 * @brief Create a new Shadow Client.
305 *
306 * @param[out] pxShadowClientHandle Output parameter for the handle of the
307 * newly-created Shadow Client. Only valid if the return code is #eShadowSuccess.
308 * @param[in] pxShadowCreateParams Pointer to a #ShadowCreateParams struct.
309 * @param[in] xTimeoutTicks Number of ticks this function may block before
310 * timeout.
311 *
312 * @return #ShadowReturnCode. The value of output parameter pxShadowClientHandle
313 * is valid only if the return code is #eShadowSuccess.
314 *
315 * @note
316 * - If xTimeoutTicks is insufficient time for initialization, this function
317 * will timeout and stop Shadow Client initialization. However, this function
318 * may block for up to (xTimeoutTicks + #shadowCLEANUP_TIME_MS) time as it
319 * cleans up a partially-initialized Shadow Client.
320 */
321ShadowReturnCode_t SHADOW_ClientCreate( ShadowClientHandle_t * pxShadowClientHandle,
322 const ShadowCreateParams_t * const pxShadowCreateParams );
323
324/**
325 * @brief Connect to the Shadow service.
326 *
327 * For a Shadow Client with a dedicated MQTT Client (#eDedicatedMQTTClient), calling
328 * this function is the only way to connect to the Shadow service. For a Shadow
329 * Client with a shared MQTT Client (#eSharedMQTTClient), calling this function is
330 * equivalent to calling @c MQTT_AGENT_Connect with the corresponding shared
331 * MQTT Client handle.
332 *
333 * @param[in] xShadowClientHandle Handle of Shadow Client to connect.
334 * @param[in] pxConnectParams Pointer to a @c TradstoneMQTTConnectParams_t struct.
335 * Note: ClientHandle should be at the top of user data passed in pxConnectParams
336 * @param[in] xTimeoutTicks Number of ticks this function may block before timeout.
337 *
338 * @return #ShadowReturnCode.
339 */
340ShadowReturnCode_t SHADOW_ClientConnect( ShadowClientHandle_t xShadowClientHandle,
341 MQTTAgentConnectParams_t * const pxConnectParams,
342 TickType_t xTimeoutTicks );
343
344/**
345 * @brief Disconnect from the Shadow service.
346 *
347 * For a Shadow Client with a dedicated MQTT Client (#eDedicatedMQTTClient), calling
348 * this function is the only way to disconnect from the Shadow service. For a Shadow
349 * Client with a shared MQTT Client (#eSharedMQTTClient), calling this function is
350 * equivalent to calling @c MQTT_AGENT_Disconnect with the corresponding shared
351 * MQTT Client handle.
352 *
353 * @param[in] xShadowClientHandle Handle of Shadow Client to disconnect.
354 *
355 * @return Unless #shadowCLEANUP_TIME_MS is insufficient to disconnect a Shadow
356 * Client, this function always returns #eShadowSuccess.
357 */
358ShadowReturnCode_t SHADOW_ClientDisconnect( ShadowClientHandle_t xShadowClientHandle );
359
360/**
361 * @brief Free resources used by a Shadow Client.
362 *
363 * @param[in] xShadowClientHandle Handle of Shadow Client to be deleted.
364 *
365 * @return #ShadowReturnCode.
366 *
367 * @warning Do not call while another operation is in progress on the Shadow Client.
368 * A Shadow Client must be re-initialized after this function completes if it is
369 * to be used again.
370 */
371ShadowReturnCode_t SHADOW_ClientDelete( ShadowClientHandle_t xShadowClientHandle );
372
373/**
374 * @brief Update a Thing Shadow.
375 *
376 * @param[in] xShadowClientHandle Handle of Shadow Client to use for update.
377 * @param[in] pxUpdateParams A pointer to a #ShadowOperationParams struct.
378 * @param[in] xTimeoutTicks Number of ticks this function may block before timeout.
379 *
380 * @return #ShadowReturnCode.
381 *
382 * @note
383 * - If xTimeoutTicks is insufficient time for the update, this function will
384 * timeout and stop the update. However, this function may block for up to
385 * (xTimeoutTicks + #shadowCLEANUP_TIME_MS) time as it cleans up subscriptions.
386 * - A timeout does not always mean that the update failed. The Shadow Service
387 * may still accept an update after this function times out. However, the user
388 * will not be notified if acceptance occurs after a timeout. The user may
389 * intentionally set a short timeout if the result of the update isn't relevant,
390 * but the timeout must still be long enough for the update to be published.
391 */
392ShadowReturnCode_t SHADOW_Update( ShadowClientHandle_t xShadowClientHandle,
393 ShadowOperationParams_t * const pxUpdateParams,
394 TickType_t xTimeoutTicks );
395
396/**
397 * @brief Get a Thing Shadow from the cloud.
398 *
399 * @param[in] xShadowClientHandle Handle of Shadow Client to use for get.
400 * @param pxGetParams A pointer to a #ShadowOperationParams struct. This is used
401 * as both an input and output parameter.
402 * @param[in] xTimeoutTicks Number of ticks this function may block before timeout.
403 *
404 * @return #ShadowReturnCode.
405 *
406 * @note
407 * - If xTimeoutTicks is insufficient time for the get, this function will
408 * timeout and stop the get. However, this function may block for up to
409 * (xTimeoutTicks + #shadowCLEANUP_TIME_MS) time as it cleans up subscriptions.
410 * - Documents received from the cloud after a timeout are ignored.
411 * - A call to #SHADOW_ReturnMQTTBuffer should follow a call to #SHADOW_Get to
412 * return the MQTT Buffer taken by #SHADOW_Get. #ShadowOperationParams_t.xBuffer
413 * should be passed as @p xBufferHandle.
414 */
415ShadowReturnCode_t SHADOW_Get( ShadowClientHandle_t xShadowClientHandle,
416 ShadowOperationParams_t * const pxGetParams,
417 TickType_t xTimeoutTicks );
418
419/**
420 * @brief Delete a Thing Shadow in the cloud.
421 *
422 * @param[in] xShadowClientHandle Handle of Shadow Client to use for delete.
423 * @param[in] pxDeleteParams A pointer to a #ShadowOperationParams struct.
424 * @param[in] xTimeoutTicks Number of ticks this function may block before timeout.
425 *
426 * @return #ShadowReturnCode.
427 *
428 * @note
429 * - If xTimeoutTicks is insufficient time for the delete, this function will
430 * timeout and stop the delete. However, this function may block for up to
431 * (xTimeoutTicks + #shadowCLEANUP_TIME_MS) time as it cleans up subscriptions.
432 * - A timeout does not always mean that the delete failed. The Shadow Service
433 * may still accept the delete after this function times out. However, the user
434 * will not be notified if acceptance occurs after a timeout. The user may
435 * intentionally set a short timeout if the result of the delete isn't relevant,
436 * but the timeout must still be long enough for the delete to be published.
437 */
438ShadowReturnCode_t SHADOW_Delete( ShadowClientHandle_t xShadowClientHandle,
439 ShadowOperationParams_t * const pxDeleteParams,
440 TickType_t xTimeoutTicks );
441
442/**
443 * @brief Register callback functions.
444 *
445 * @param[in] xShadowClientHandle Handle of Shadow Client to use for registering callbacks.
446 * @param[in] pxCallbackParams A pointer to a #ShadowCallbackParams struct.
447 * @param[in] xTimeoutTicks Number of ticks this function may block before timeout.
448 *
449 * @return
450 * - #eShadowSuccess if all callbacks registered successfully.
451 * - #eShadowFailure if the Shadow Client failed to subscribe to at least one
452 * callback topic and did not time out.
453 * - #eShadowTimeout if the Shadow Client timed out when subscribing to at least
454 * one callback topic.
455 *
456 * @note
457 * - This function will register as many callbacks as it can before xTimeoutTicks
458 * elapses.
459 * - Callbacks are registered in the order Updated, Deleted, Delta.
460 * - If a callback fails to register, this function will print a debug message if
461 * #shadowENABLE_DEBUG_LOGS is @c 1 and attempt to register the next callback.
462 */
463ShadowReturnCode_t SHADOW_RegisterCallbacks( ShadowClientHandle_t xShadowClientHandle,
464 ShadowCallbackParams_t * const pxCallbackParams,
465 TickType_t xTimeoutTicks );
466
467/**
468 * @brief Return an MQTT Buffer to the MQTT client.
469 *
470 * For a Shadow Client with a dedicated MQTT Client (#eDedicatedMQTTClient), calling
471 * this function is the only way to return an MQTT Buffer. For a Shadow Client with
472 * a shared MQTT Client (#eSharedMQTTClient), calling this function is equivalent
473 * to calling @c MQTT_AGENT_ReturnBuffer with the corresponding shared MQTT
474 * Client handle.
475 *
476 * @param[in] xShadowClientHandle Handle of Shadow Client for MQTT Buffer return.
477 * @param[in] xBufferHandle Handle of MQTT Buffer to return.
478 *
479 * @return #ShadowReturnCode.
480 *
481 * @note
482 * - This function should be called after every #SHADOW_Get call to return the
483 * MQTT buffer taken by #SHADOW_Get. Otherwise, the MQTT client will run out
484 * of buffers after repeated calls to #SHADOW_Get.
485 * - This function should also be called to return buffers taken in callback
486 * functions #ShadowUpdatedCallback_t and #ShadowDeltaCallback_t.
487 */
488ShadowReturnCode_t SHADOW_ReturnMQTTBuffer( ShadowClientHandle_t xShadowClientHandle,
489 MQTTBufferHandle_t xBufferHandle );
490
491#endif /* _AWS_SHADOW_H_ */