add websocket
author@CHENG <2393524978@qq.com>
Wed, 29 May 2024 03:02:32 +0000 (11:02 +0800)
committer@CHENG <2393524978@qq.com>
Wed, 29 May 2024 03:02:32 +0000 (11:02 +0800)
36 files changed:
2.sdk/sdk/product/craneg_modem/pcac/mbedTLS/alios/alios_mbedtls_config.h
2.sdk/sdk/product/craneg_modem/pcac/pca_components/build/pca_components.mak
2.sdk/sdk/product/craneg_modem/pcac/wsclient/build/wsclient.mak [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/build/wsclient_dep.mak [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/esp_err.h [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/esp_log.h [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/esp_timer.h [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/limits.h [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/list.h [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/private_include/queue.h [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/private_include/web_esp_transport_ssl_internal.h [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/private_include/web_esp_transport_utils.h [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/queue.h [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/semphr.h [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/sim_esp_tls.h [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/task.h [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_esp_tls_error_capture_internal.h [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_esp_tls_mbedtls.h [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_esp_transport.h [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_esp_transport_ssl.h [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_esp_transport_ssl_internal.h [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_esp_transport_tcp.h [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_esp_transport_ws.h [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_http_parser.h [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/sim_esp_websocket_client.h [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/sim_esp_tls.c [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/web_esp_tls_mbedtls.c [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/web_http_parser.c [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/web_random.c [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/web_transport.c [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/web_transport_ssl.c [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/web_transport_tcp.c [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/web_transport_ws.c [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/sim_esp_websocket_client.c [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/sim_websocket_example.c [new file with mode: 0644]
2.sdk/sdk/product/craneg_modem/tavor/Arbel/build/Arbel.mak

index 8cc2786..6604512 100644 (file)
 #if defined(MBEDTLS_CONFIG_CRYPTO_MD5)
 #define MBEDTLS_MD5_C
 #endif
+
+#define MBEDTLS_NET_C
+
 #if defined(MBEDTLS_CONFIG_CRYPTO_RIPEMD160)
 #define MBEDTLS_RIPEMD160_C
 #endif
index 137a9d7..799e96d 100644 (file)
@@ -113,7 +113,8 @@ ifneq (,$(findstring LWIP,${VARIANT_LIST}))
 GROUP_PACKAGE_LIST += \
                       pcac/lwipv4v6 \
                       pcac/duster \
-                      pcac/httpclient
+                      pcac/httpclient \
+                      pcac/wsclient
 
 ifeq (,$(findstring NOTLS,${VARIANT_LIST}))
 GROUP_PACKAGE_LIST += \
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/build/wsclient.mak b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/build/wsclient.mak
new file mode 100644 (file)
index 0000000..e0489c5
--- /dev/null
@@ -0,0 +1,102 @@
+#------------------------------------------------------------
+# (C) Copyright [2006-2008] Marvell International Ltd.
+# All Rights Reserved
+#------------------------------------------------------------
+
+#--------------------------------------------------------------------------------------------------------------------
+# INTEL CONFIDENTIAL
+# Copyright 2006 Intel Corporation All Rights Reserved.
+# The source code contained or described herein and all documents related to the source code ("Material") are owned
+# by Intel Corporation or its suppliers or licensors. Title to the Material remains with Intel Corporation or
+# its suppliers and licensors. The Material contains trade secrets and proprietary and confidential information of
+# Intel or its suppliers and licensors. The Material is protected by worldwide copyright and trade secret laws and
+# treaty provisions. No part of the Material may be used, copied, reproduced, modified, published, uploaded, posted,
+# transmitted, distributed, or disclosed in any way without Intel's prior express written permission.
+#
+# No license under any patent, copyright, trade secret or other intellectual property right is granted to or
+# conferred upon you by disclosure or delivery of the Materials, either expressly, by implication, inducement,
+# estoppel or otherwise. Any license under such intellectual property rights must be express and approved by
+# Intel in writing.
+# -------------------------------------------------------------------------------------------------------------------
+
+#=========================================================================
+# File Name      : libwebsockets.mak
+# Description    : Main make file for the lwip package.
+#
+# Usage          : make [-s] -f lwip.mak OPT_FILE=<path>/<opt_file>
+#
+# Notes          : The options file defines macro values defined
+#                  by the environment, target, and groups. It
+#                  must be included for proper package building.
+#
+#
+#
+#=========================================================================
+
+# Package build options
+include ${OPT_FILE}
+
+# Package Makefile information
+GEN_PACK_MAKEFILE = ${BUILD_ROOT}/env/${HOST}/build/package.mak
+
+# Define Package ---------------------------------------
+
+PACKAGE_NAME     = wsclient
+PACKAGE_BASE     = pcac
+PACKAGE_DEP_FILE = wsclient_dep.mak
+PACKAGE_PATH     = ${BUILD_ROOT}/${PACKAGE_BASE}/${PACKAGE_NAME}
+
+# The relative path locations of source and include file directories.
+PACKAGE_SRC_PATH    = ${PACKAGE_PATH}/libwebsockets/src        \
+                                         ${PACKAGE_PATH}/libwebsockets/src/common
+
+PACKAGE_INC_PATHS   = ${BUILD_ROOT}/pcac/lwipv4v6/src/include/lwip     \
+                                         ${PACKAGE_PATH}/libwebsockets/inc             \
+                                         ${PACKAGE_PATH}/libwebsockets/inc/common
+
+
+# Package source files, paths not required
+PACKAGE_SRC_FILES =                            \
+                    sim_esp_websocket_client.c \
+                                       web_transport_ws.c                      \
+                                       web_random.c                            \
+                                       web_transport_tcp.c                     \
+                                       web_transport.c                         \
+                                       web_http_parser.c                       \
+                                       sim_websocket_example.c         \
+                                       web_esp_tls_mbedtls.c           \
+                                       sim_esp_tls.c                           \
+                                       web_transport_ssl.c
+
+# These are the tool flags specific to the ci_stub package only.
+# The environment, target, and group also set flags.
+PACKAGE_CFLAGS  =
+ifneq (,$(findstring mbedTLS_2_1_8,${VARIANT_LIST}))
+PACKAGE_CFLAGS  += -I$(BUILD_ROOT)/pcac/mbedTLS/mbedTLS_2_1_8 \
+                   -I$(BUILD_ROOT)/pcac/mbedTLS/mbedTLS_2_1_8/include \
+                   -I$(BUILD_ROOT)/pcac/mbedTLS/mbedTLS_2_1_8/include/mbedtls
+endif
+
+ifneq (,$(findstring mbedTLS_3_2_1,${VARIANT_LIST}))
+PACKAGE_CFLAGS  += -I$(BUILD_ROOT)/pcac/mbedTLS/mbedTLS_3_2_1 \
+                   -I$(BUILD_ROOT)/pcac/mbedTLS/mbedTLS_3_2_1/include \
+                   -I$(BUILD_ROOT)/pcac/mbedTLS/mbedTLS_3_2_1/include/mbedtls \
+                   -I$(BUILD_ROOT)/pcac/mbedTLS/mbedTLS_3_2_1/tests/include \
+                   -I$(BUILD_ROOT)/pcac/mbedTLS/mbedTLS_3_2_1/tests/include/test
+endif
+
+# Include the Standard Package Make File ---------------
+include ${GEN_PACK_MAKEFILE}
+
+# Include the Make Dependency File ---------------------
+# This must be the last line in the file
+include ${PACKAGE_DEP_FILE}
+
+
+
+
+
+
+
+
+
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/build/wsclient_dep.mak b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/build/wsclient_dep.mak
new file mode 100644 (file)
index 0000000..078e4f3
--- /dev/null
@@ -0,0 +1,38 @@
+#------------------------------------------------------------
+# (C) Copyright [2006-2008] Marvell International Ltd.
+# All Rights Reserved
+#------------------------------------------------------------
+
+#--------------------------------------------------------------------------------------------------------------------
+# INTEL CONFIDENTIAL
+# Copyright 2006 Intel Corporation All Rights Reserved.
+# The source code contained or described herein and all documents related to the source code ("Material") are owned
+# by Intel Corporation or its suppliers or licensors. Title to the Material remains with Intel Corporation or
+# its suppliers and licensors. The Material contains trade secrets and proprietary and confidential information of
+# Intel or its suppliers and licensors. The Material is protected by worldwide copyright and trade secret laws and
+# treaty provisions. No part of the Material may be used, copied, reproduced, modified, published, uploaded, posted,
+# transmitted, distributed, or disclosed in any way without Intel's prior express written permission.
+#
+# No license under any patent, copyright, trade secret or other intellectual property right is granted to or
+# conferred upon you by disclosure or delivery of the Materials, either expressly, by implication, inducement,
+# estoppel or otherwise. Any license under such intellectual property rights must be express and approved by
+# Intel in writing.
+# -------------------------------------------------------------------------------------------------------------------
+
+# =======================================================================
+# File        : lwip_dep.mak
+# Description :        Make dependency file for the lwip   
+#               package.
+#
+# Notes       : This file contains the header file dependencies
+#               for the building of the diag package.
+#               This file is automatically generated by the build
+#               and should not be changed.
+#
+#
+# =======================================================================
+
+# DO NOT DELETE BELOW THIS LINE -------------------------------------
+
+
+
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/esp_err.h b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/esp_err.h
new file mode 100644 (file)
index 0000000..c14a95b
--- /dev/null
@@ -0,0 +1,161 @@
+// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+#pragma once
+
+#include <stdint.h>
+#include <stdio.h>
+#include <assert.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef int32_t esp_err_t;
+
+/* Definitions for error constants. */
+#define ESP_OK          0       /*!< esp_err_t value indicating success (no error) */
+#define ESP_FAIL        -1      /*!< Generic esp_err_t code indicating failure */
+
+#define ESP_ERR_NO_MEM              0x101   /*!< Out of memory */
+#define ESP_ERR_INVALID_ARG         0x102   /*!< Invalid argument */
+#define ESP_ERR_INVALID_STATE       0x103   /*!< Invalid state */
+#define ESP_ERR_INVALID_SIZE        0x104   /*!< Invalid size */
+#define ESP_ERR_NOT_FOUND           0x105   /*!< Requested resource not found */
+#define ESP_ERR_NOT_SUPPORTED       0x106   /*!< Operation or feature not supported */
+#define ESP_ERR_TIMEOUT             0x107   /*!< Operation timed out */
+#define ESP_ERR_INVALID_RESPONSE    0x108   /*!< Received response was invalid */
+#define ESP_ERR_INVALID_CRC         0x109   /*!< CRC or checksum was invalid */
+#define ESP_ERR_INVALID_VERSION     0x10A   /*!< Version was invalid */
+#define ESP_ERR_INVALID_MAC         0x10B   /*!< MAC address was invalid */
+
+#define ESP_ERR_WIFI_BASE           0x3000  /*!< Starting number of WiFi error codes */
+#define ESP_ERR_MESH_BASE           0x4000  /*!< Starting number of MESH error codes */
+#define ESP_ERR_FLASH_BASE          0x6000  /*!< Starting number of flash error codes */
+
+#define portMAX_DELAY               0xFFFFFFFF
+
+typedef int32_t esp_err_t;
+
+typedef void * xSemaphoreHandle;
+typedef void * SemaphoreHandle_t;
+typedef void * xQueueHandle;
+typedef void * QueueHandle_t;
+typedef void * TaskHandle_t;
+typedef void * esp_timer_handle_t;
+typedef uint32_t TickType_t;
+typedef uint32_t portTickType;
+/**
+  * @brief Returns string for esp_err_t error codes
+  *
+  * This function finds the error code in a pre-generated lookup-table and
+  * returns its string representation.
+  *
+  * The function is generated by the Python script
+  * tools/gen_esp_err_to_name.py which should be run each time an esp_err_t
+  * error is modified, created or removed from the IDF project.
+  *
+  * @param code esp_err_t error code
+  * @return string error message
+  */
+const char *esp_err_to_name(esp_err_t code);
+
+/**
+  * @brief Returns string for esp_err_t and system error codes
+  *
+  * This function finds the error code in a pre-generated lookup-table of
+  * esp_err_t errors and returns its string representation. If the error code
+  * is not found then it is attempted to be found among system errors.
+  *
+  * The function is generated by the Python script
+  * tools/gen_esp_err_to_name.py which should be run each time an esp_err_t
+  * error is modified, created or removed from the IDF project.
+  *
+  * @param code esp_err_t error code
+  * @param[out] buf buffer where the error message should be written
+  * @param buflen Size of buffer buf. At most buflen bytes are written into the buf buffer (including the terminating null byte).
+  * @return buf containing the string error message
+  */
+const char *esp_err_to_name_r(esp_err_t code, char *buf, size_t buflen);
+
+/** @cond */
+void _esp_error_check_failed(esp_err_t rc, const char *file, int line, const char *function, const char *expression) __attribute__((noreturn));
+
+/** @cond */
+void _esp_error_check_failed_without_abort(esp_err_t rc, const char *file, int line, const char *function, const char *expression);
+
+#ifndef __ASSERT_FUNC
+/* This won't happen on IDF, which defines __ASSERT_FUNC in assert.h, but it does happen when building on the host which
+   uses /usr/include/assert.h or equivalent.
+*/
+#ifdef __ASSERT_FUNCTION
+#define __ASSERT_FUNC __ASSERT_FUNCTION /* used in glibc assert.h */
+#else
+#define __ASSERT_FUNC "??"
+#endif
+#endif
+/** @endcond */
+
+/**
+ * Macro which can be used to check the error code,
+ * and terminate the program in case the code is not ESP_OK.
+ * Prints the error code, error location, and the failed statement to serial output.
+ *
+ * Disabled if assertions are disabled.
+ */
+#ifdef NDEBUG
+#define ESP_ERROR_CHECK(x) do {                                         \
+        esp_err_t __err_rc = (x);                                       \
+        (void) sizeof(__err_rc);                                        \
+    } while(0)
+#elif defined(CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT)
+#define ESP_ERROR_CHECK(x) do {                                         \
+        esp_err_t __err_rc = (x);                                       \
+        if (__err_rc != ESP_OK) {                                       \
+            abort();                                                    \
+        }                                                               \
+    } while(0)
+#else
+#define ESP_ERROR_CHECK(x) do {                                         \
+        esp_err_t __err_rc = (x);                                       \
+        if (__err_rc != ESP_OK) {                                       \
+            _esp_error_check_failed(__err_rc, __FILE__, __LINE__,       \
+                                    __ASSERT_FUNC, #x);                 \
+        }                                                               \
+    } while(0)
+#endif
+
+/**
+ * Macro which can be used to check the error code. Prints the error code, error location, and the failed statement to
+ * serial output.
+ * In comparison with ESP_ERROR_CHECK(), this prints the same error message but isn't terminating the program.
+ */
+#ifdef NDEBUG
+#define ESP_ERROR_CHECK_WITHOUT_ABORT(x) ({                                         \
+        esp_err_t __err_rc = (x);                                                   \
+        __err_rc;                                                                   \
+    })
+#else
+#define ESP_ERROR_CHECK_WITHOUT_ABORT(x) ({                                         \
+        esp_err_t __err_rc = (x);                                                   \
+        if (__err_rc != ESP_OK) {                                                   \
+            _esp_error_check_failed_without_abort(__err_rc, __FILE__, __LINE__,     \
+                                    __ASSERT_FUNC, #x);                             \
+        }                                                                           \
+        __err_rc;                                                                   \
+    })
+#endif //NDEBUG
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/esp_log.h b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/esp_log.h
new file mode 100644 (file)
index 0000000..6275b80
--- /dev/null
@@ -0,0 +1,15 @@
+#include <stdint.h>
+#include <stdio.h>
+#include "uart.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+#define ESP_LOGE( format, args... )   do{ CPUartLogPrintf( "[ws]"format, ##args ); }while(0)
+#define ESP_LOGW( format, args... )   do{ CPUartLogPrintf( "[ws]"format, ##args ); }while(0)
+#define ESP_LOGI( format, args... )   do{ CPUartLogPrintf( "[ws]"format, ##args ); }while(0)
+#define ESP_LOGD( format, args... )   do{ CPUartLogPrintf( "[ws]"format, ##args ); }while(0)
+#define ESP_LOGV( format, args... )   do{ CPUartLogPrintf( "[ws]"format, ##args ); }while(0)
+#ifdef __cplusplus
+}
+#endif
\ No newline at end of file
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/esp_timer.h b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/esp_timer.h
new file mode 100644 (file)
index 0000000..ff5c13a
--- /dev/null
@@ -0,0 +1,233 @@
+// Copyright 2017 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#pragma once
+
+/**
+ * @file esp_timer.h
+ * @brief microsecond-precision 64-bit timer API, replacement for ets_timer
+ *
+ * esp_timer APIs allow components to receive callbacks when a hardware timer
+ * reaches certain value. The timer provides microsecond accuracy and
+ * up to 64 bit range. Note that while the timer itself provides microsecond
+ * accuracy, callbacks are dispatched from an auxiliary task. Some time is
+ * needed to notify this task from timer ISR, and then to invoke the callback.
+ * If more than one callback needs to be dispatched at any particular time,
+ * each subsequent callback will be dispatched only when the previous callback
+ * returns. Therefore, callbacks should not do much work; instead, they should
+ * use RTOS notification mechanisms (queues, semaphores, event groups, etc.) to
+ * pass information to other tasks.
+ *
+ * To be implemented: it should be possible to request the callback to be called
+ * directly from the ISR. This reduces the latency, but has potential impact on
+ * all other callbacks which need to be dispatched. This option should only be
+ * used for simple callback functions, which do not take longer than a few
+ * microseconds to run.
+ *
+ * Implementation note: on the ESP32, esp_timer APIs use the "legacy" FRC2
+ * timer. Timer callbacks are called from a task running on the PRO CPU.
+ */
+
+#include <stdint.h>
+#include <stdio.h>
+#include "esp_err.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @brief Opaque type representing a single esp_timer
+ */
+typedef struct esp_timer* esp_timer_handle_t;
+
+/**
+ * @brief Timer callback function type
+ * @param arg pointer to opaque user-specific data
+ */
+typedef void (*esp_timer_cb_t)(void* arg);
+
+
+/**
+ * @brief Method for dispatching timer callback
+ */
+typedef enum {
+    ESP_TIMER_TASK,     //!< Callback is called from timer task
+
+    /* Not supported for now, provision to allow callbacks to run directly
+     * from an ISR:
+
+        ESP_TIMER_ISR,      //!< Callback is called from timer ISR
+
+     */
+} esp_timer_dispatch_t;
+
+/**
+ * @brief Timer configuration passed to esp_timer_create
+ */
+typedef struct {
+    esp_timer_cb_t callback;        //!< Function to call when timer expires
+    void* arg;                      //!< Argument to pass to the callback
+    esp_timer_dispatch_t dispatch_method;   //!< Call the callback from task or from ISR
+    const char* name;               //!< Timer name, used in esp_timer_dump function
+} esp_timer_create_args_t;
+
+/**
+ * @brief Initialize esp_timer library
+ *
+ * @note This function is called from startup code. Applications do not need
+ * to call this function before using other esp_timer APIs.
+ *
+ * @return
+ *      - ESP_OK on success
+ *      - ESP_ERR_NO_MEM if allocation has failed
+ *      - ESP_ERR_INVALID_STATE if already initialized
+ *      - other errors from interrupt allocator
+ */
+esp_err_t esp_timer_init();
+
+/**
+ * @brief De-initialize esp_timer library
+ *
+ * @note Normally this function should not be called from applications
+ *
+ * @return
+ *      - ESP_OK on success
+ *      - ESP_ERR_INVALID_STATE if not yet initialized
+ */
+esp_err_t esp_timer_deinit();
+
+/**
+ * @brief Create an esp_timer instance
+ *
+ * @note When done using the timer, delete it with esp_timer_delete function.
+ *
+ * @param create_args   Pointer to a structure with timer creation arguments.
+ *                      Not saved by the library, can be allocated on the stack.
+ * @param[out] out_handle  Output, pointer to esp_timer_handle_t variable which
+ *                         will hold the created timer handle.
+ *
+ * @return
+ *      - ESP_OK on success
+ *      - ESP_ERR_INVALID_ARG if some of the create_args are not valid
+ *      - ESP_ERR_INVALID_STATE if esp_timer library is not initialized yet
+ *      - ESP_ERR_NO_MEM if memory allocation fails
+ */
+esp_err_t esp_timer_create(const esp_timer_create_args_t* create_args,
+                           esp_timer_handle_t* out_handle);
+
+/**
+ * @brief Start one-shot timer
+ *
+ * Timer should not be running when this function is called.
+ *
+ * @param timer timer handle created using esp_timer_create
+ * @param timeout_us timer timeout, in microseconds relative to the current moment
+ * @return
+ *      - ESP_OK on success
+ *      - ESP_ERR_INVALID_ARG if the handle is invalid
+ *      - ESP_ERR_INVALID_STATE if the timer is already running
+ */
+esp_err_t esp_timer_start_once(esp_timer_handle_t timer, uint64_t timeout_us);
+
+/**
+ * @brief Start a periodic timer
+ *
+ * Timer should not be running when this function is called. This function will
+ * start the timer which will trigger every 'period' microseconds.
+ *
+ * @param timer timer handle created using esp_timer_create
+ * @param period timer period, in microseconds
+ * @return
+ *      - ESP_OK on success
+ *      - ESP_ERR_INVALID_ARG if the handle is invalid
+ *      - ESP_ERR_INVALID_STATE if the timer is already running
+ */
+esp_err_t esp_timer_start_periodic(esp_timer_handle_t timer, uint64_t period);
+
+/**
+ * @brief Stop the timer
+ *
+ * This function stops the timer previously started using esp_timer_start_once
+ * or esp_timer_start_periodic.
+ *
+ * @param timer timer handle created using esp_timer_create
+ * @return
+ *      - ESP_OK on success
+ *      - ESP_ERR_INVALID_STATE if the timer is not running
+ */
+esp_err_t esp_timer_stop(esp_timer_handle_t timer);
+
+/**
+ * @brief Delete an esp_timer instance
+ *
+ * The timer must be stopped before deleting. A one-shot timer which has expired
+ * does not need to be stopped.
+ *
+ * @param timer timer handle allocated using esp_timer_create
+ * @return
+ *      - ESP_OK on success
+ *      - ESP_ERR_INVALID_STATE if the timer is not running
+ */
+esp_err_t esp_timer_delete(esp_timer_handle_t timer);
+
+/**
+ * @brief Get time in microseconds since boot
+ * @return number of microseconds since esp_timer_init was called (this normally
+ *          happens early during application startup).
+ */
+int64_t esp_timer_get_time();
+
+/**
+ * @brief Get the timestamp when the next timeout is expected to occur
+ * @return Timestamp of the nearest timer event, in microseconds.
+ *         The timebase is the same as for the values returned by esp_timer_get_time.
+ */
+int64_t esp_timer_get_next_alarm();
+
+/**
+ * @brief Dump the list of timers to a stream
+ *
+ * If CONFIG_ESP_TIMER_PROFILING option is enabled, this prints the list of all
+ * the existing timers. Otherwise, only the list active timers is printed.
+ *
+ * The format is:
+ *
+ *   name  period  alarm  times_armed  times_triggered  total_callback_run_time
+ *
+ * where:
+ *
+ * name â€” timer name (if CONFIG_ESP_TIMER_PROFILING is defined), or timer pointer
+ * period â€” period of timer, in microseconds, or 0 for one-shot timer
+ * alarm - time of the next alarm, in microseconds since boot, or 0 if the timer
+ *         is not started
+ *
+ * The following fields are printed if CONFIG_ESP_TIMER_PROFILING is defined:
+ *
+ * times_armed â€” number of times the timer was armed via esp_timer_start_X
+ * times_triggered - number of times the callback was called
+ * total_callback_run_time - total time taken by callback to execute, across all calls
+ *
+ * @param stream stream (such as stdout) to dump the information to
+ * @return
+ *      - ESP_OK on success
+ *      - ESP_ERR_NO_MEM if can not allocate temporary buffer for the output
+ */
+esp_err_t esp_timer_dump(FILE* stream);
+
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/limits.h b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/limits.h
new file mode 100644 (file)
index 0000000..633b445
--- /dev/null
@@ -0,0 +1,146 @@
+#ifndef _LIBC_LIMITS_H_
+# define _LIBC_LIMITS_H_       1
+
+#include <newlib.h>
+
+# ifdef _MB_LEN_MAX
+#  define MB_LEN_MAX   _MB_LEN_MAX
+# else
+#  define MB_LEN_MAX    1
+# endif
+
+/* Maximum number of positional arguments, if _WANT_IO_POS_ARGS.  */
+# ifndef NL_ARGMAX
+#  define NL_ARGMAX 32
+# endif
+
+/* if do not have #include_next support, then we
+   have to define the limits here. */
+# if !defined __GNUC__ || __GNUC__ < 2
+
+#  ifndef _LIMITS_H
+#   define _LIMITS_H   1
+
+#   include <sys/config.h>
+
+/* Number of bits in a `char'.  */
+#   undef CHAR_BIT
+#   define CHAR_BIT 8
+
+/* Minimum and maximum values a `signed char' can hold.  */
+#   undef SCHAR_MIN
+#   define SCHAR_MIN (-128)
+#   undef SCHAR_MAX
+#   define SCHAR_MAX 127
+
+/* Maximum value an `unsigned char' can hold.  (Minimum is 0).  */
+#   undef UCHAR_MAX
+#   define UCHAR_MAX 255
+
+/* Minimum and maximum values a `char' can hold.  */
+#   ifdef __CHAR_UNSIGNED__
+#    undef CHAR_MIN
+#    define CHAR_MIN 0
+#    undef CHAR_MAX
+#    define CHAR_MAX 255
+#   else
+#    undef CHAR_MIN
+#    define CHAR_MIN (-128)
+#    undef CHAR_MAX
+#    define CHAR_MAX 127
+#   endif
+
+/* Minimum and maximum values a `signed short int' can hold.  */
+#   undef SHRT_MIN
+/* For the sake of 16 bit hosts, we may not use -32768 */
+#   define SHRT_MIN (-32767-1)
+#   undef SHRT_MAX
+#   define SHRT_MAX 32767
+
+/* Maximum value an `unsigned short int' can hold.  (Minimum is 0).  */
+#   undef USHRT_MAX
+#   define USHRT_MAX 65535
+
+/* Minimum and maximum values a `signed int' can hold.  */
+#   ifndef __INT_MAX__
+#    define __INT_MAX__ 2147483647
+#   endif
+#   undef INT_MIN
+#   define INT_MIN (-INT_MAX-1)
+#   undef INT_MAX
+#   define INT_MAX __INT_MAX__
+
+/* Maximum value an `unsigned int' can hold.  (Minimum is 0).  */
+#   undef UINT_MAX
+#   define UINT_MAX (INT_MAX * 2U + 1)
+
+/* Minimum and maximum values a `signed long int' can hold.
+   (Same as `int').  */
+#   ifndef __LONG_MAX__
+#    if defined (__alpha__) || (defined (__sparc__) && defined(__arch64__)) || defined (__sparcv9)
+#     define __LONG_MAX__ 9223372036854775807L
+#    else
+#     define __LONG_MAX__ 2147483647L
+#    endif /* __alpha__ || sparc64 */
+#   endif
+#   undef LONG_MIN
+#   define LONG_MIN (-LONG_MAX-1)
+#   undef LONG_MAX
+#   define LONG_MAX __LONG_MAX__
+
+/* Maximum value an `unsigned long int' can hold.  (Minimum is 0).  */
+#   undef ULONG_MAX
+#   define ULONG_MAX (LONG_MAX * 2UL + 1)
+
+#   ifndef __LONG_LONG_MAX__
+#    define __LONG_LONG_MAX__ 9223372036854775807LL
+#   endif
+
+#   if (defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) ||   \
+  (defined(__cplusplus) && __cplusplus >= 201103L)
+/* Minimum and maximum values a `signed long long int' can hold.  */
+#    undef LLONG_MIN
+#    define LLONG_MIN (-LLONG_MAX-1)
+#    undef LLONG_MAX
+#    define LLONG_MAX __LONG_LONG_MAX__
+
+/* Maximum value an `unsigned long long int' can hold.  (Minimum is 0).  */
+#    undef ULLONG_MAX
+#    define ULLONG_MAX (LLONG_MAX * 2ULL + 1)
+#   endif
+
+#  if defined (__GNU_LIBRARY__) ? defined (__USE_GNU) : !defined (__STRICT_ANSI__)
+/* Minimum and maximum values a `signed long long int' can hold.  */
+#    undef LONG_LONG_MIN
+#    define LONG_LONG_MIN (-LONG_LONG_MAX-1)
+#    undef LONG_LONG_MAX
+#    define LONG_LONG_MAX __LONG_LONG_MAX__
+
+/* Maximum value an `unsigned long long int' can hold.  (Minimum is 0).  */
+#    undef ULONG_LONG_MAX
+#    define ULONG_LONG_MAX (LONG_LONG_MAX * 2ULL + 1)
+#   endif
+
+#  endif /* _LIMITS_H  */
+# endif         /* GCC 2.  */
+
+#endif  /* !_LIBC_LIMITS_H_ */
+
+#if defined __GNUC__ && !defined _GCC_LIMITS_H_
+/* `_GCC_LIMITS_H_' is what GCC's file defines.  */
+# include_next <limits.h>
+#endif /* __GNUC__ && !_GCC_LIMITS_H_ */
+
+#ifndef _POSIX2_RE_DUP_MAX
+/* The maximum number of repeated occurrences of a regular expression
+ *    permitted when using the interval notation `\{M,N\}'.  */
+#define _POSIX2_RE_DUP_MAX              255
+#endif /* _POSIX2_RE_DUP_MAX  */
+
+#ifndef ARG_MAX
+#define ARG_MAX                4096
+#endif
+
+#ifndef PATH_MAX
+#define PATH_MAX       1024
+#endif
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/list.h b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/list.h
new file mode 100644 (file)
index 0000000..ed81eab
--- /dev/null
@@ -0,0 +1,466 @@
+/*
+    FreeRTOS V8.2.0 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+       ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+       ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+       the FAQ page "My application does not run, what could be wrong?".  Have you
+       defined configASSERT()?
+
+       http://www.FreeRTOS.org/support - In return for receiving this top quality
+       embedded software for free we request you assist our global community by
+       participating in the support forum.
+
+       http://www.FreeRTOS.org/training - Investing in training allows your team to
+       be as productive as possible as early as possible.  Now you can receive
+       FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+       Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+/*
+ * This is the list implementation used by the scheduler.  While it is tailored
+ * heavily for the schedulers needs, it is also available for use by
+ * application code.
+ *
+ * list_ts can only store pointers to list_item_ts.  Each ListItem_t contains a
+ * numeric value (xItemValue).  Most of the time the lists are sorted in
+ * descending item value order.
+ *
+ * Lists are created already containing one list item.  The value of this
+ * item is the maximum possible that can be stored, it is therefore always at
+ * the end of the list and acts as a marker.  The list member pxHead always
+ * points to this marker - even though it is at the tail of the list.  This
+ * is because the tail contains a wrap back pointer to the true head of
+ * the list.
+ *
+ * In addition to it's value, each list item contains a pointer to the next
+ * item in the list (pxNext), a pointer to the list it is in (pxContainer)
+ * and a pointer to back to the object that contains it.  These later two
+ * pointers are included for efficiency of list manipulation.  There is
+ * effectively a two way link between the object containing the list item and
+ * the list item itself.
+ *
+ *
+ * \page ListIntroduction List Implementation
+ * \ingroup FreeRTOSIntro
+ */
+
+//#ifndef INC_FREERTOS_H
+//     #error FreeRTOS.h must be included before list.h
+//#endif
+
+#ifndef LIST_H
+#define LIST_H
+
+/*
+ * The list structure members are modified from within interrupts, and therefore
+ * by rights should be declared volatile.  However, they are only modified in a
+ * functionally atomic way (within critical sections of with the scheduler
+ * suspended) and are either passed by reference into a function or indexed via
+ * a volatile variable.  Therefore, in all use cases tested so far, the volatile
+ * qualifier can be omitted in order to provide a moderate performance
+ * improvement without adversely affecting functional behaviour.  The assembly
+ * instructions generated by the IAR, ARM and GCC compilers when the respective
+ * compiler's options were set for maximum optimisation has been inspected and
+ * deemed to be as intended.  That said, as compiler technology advances, and
+ * especially if aggressive cross module optimisation is used (a use case that
+ * has not been exercised to any great extend) then it is feasible that the
+ * volatile qualifier will be needed for correct optimisation.  It is expected
+ * that a compiler removing essential code because, without the volatile
+ * qualifier on the list structure members and with aggressive cross module
+ * optimisation, the compiler deemed the code unnecessary will result in
+ * complete and obvious failure of the scheduler.  If this is ever experienced
+ * then the volatile qualifier can be inserted in the relevant places within the
+ * list structures by simply defining configLIST_VOLATILE to volatile in
+ * FreeRTOSConfig.h (as per the example at the bottom of this comment block).
+ * If configLIST_VOLATILE is not defined then the preprocessor directives below
+ * will simply #define configLIST_VOLATILE away completely.
+ *
+ * To use volatile list structure members then add the following line to
+ * FreeRTOSConfig.h (without the quotes):
+ * "#define configLIST_VOLATILE volatile"
+ */
+#ifndef configLIST_VOLATILE
+       #define configLIST_VOLATILE
+#endif /* configSUPPORT_CROSS_MODULE_OPTIMISATION */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Macros that can be used to place known values within the list structures,
+then check that the known values do not get corrupted during the execution of
+the application.   These may catch the list data structures being overwritten in
+memory.  They will not catch data errors caused by incorrect configuration or
+use of FreeRTOS.*/
+#if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 0 )
+       /* Define the macros to do nothing. */
+       #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE
+       #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE
+       #define listFIRST_LIST_INTEGRITY_CHECK_VALUE
+       #define listSECOND_LIST_INTEGRITY_CHECK_VALUE
+       #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem )
+       #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem )
+       #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList )
+       #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList )
+       #define listTEST_LIST_ITEM_INTEGRITY( pxItem )
+       #define listTEST_LIST_INTEGRITY( pxList )
+#else
+       /* Define macros that add new members into the list structures. */
+       #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE                               TickType_t xListItemIntegrityValue1;
+       #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE                              TickType_t xListItemIntegrityValue2;
+       #define listFIRST_LIST_INTEGRITY_CHECK_VALUE                                    TickType_t xListIntegrityValue1;
+       #define listSECOND_LIST_INTEGRITY_CHECK_VALUE                                   TickType_t xListIntegrityValue2;
+
+       /* Define macros that set the new structure members to known values. */
+       #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem )         ( pxItem )->xListItemIntegrityValue1 = pdINTEGRITY_CHECK_VALUE
+       #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem )        ( pxItem )->xListItemIntegrityValue2 = pdINTEGRITY_CHECK_VALUE
+       #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList )          ( pxList )->xListIntegrityValue1 = pdINTEGRITY_CHECK_VALUE
+       #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList )          ( pxList )->xListIntegrityValue2 = pdINTEGRITY_CHECK_VALUE
+
+       /* Define macros that will assert if one of the structure members does not
+       contain its expected value. */
+       #define listTEST_LIST_ITEM_INTEGRITY( pxItem )          configASSERT( ( ( pxItem )->xListItemIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxItem )->xListItemIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) )
+       #define listTEST_LIST_INTEGRITY( pxList )                       configASSERT( ( ( pxList )->xListIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxList )->xListIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) )
+#endif /* configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES */
+
+
+/*
+ * Definition of the only type of object that a list can contain.
+ */
+struct xLIST_ITEM
+{
+       listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE                               /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
+       configLIST_VOLATILE TickType_t xItemValue;                      /*< The value being listed.  In most cases this is used to sort the list in descending order. */
+       struct xLIST_ITEM * configLIST_VOLATILE pxNext;         /*< Pointer to the next ListItem_t in the list. */
+       struct xLIST_ITEM * configLIST_VOLATILE pxPrevious;     /*< Pointer to the previous ListItem_t in the list. */
+       void * pvOwner;                                                                         /*< Pointer to the object (normally a TCB) that contains the list item.  There is therefore a two way link between the object containing the list item and the list item itself. */
+       void * configLIST_VOLATILE pvContainer;                         /*< Pointer to the list in which this list item is placed (if any). */
+       listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE                              /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
+};
+typedef struct xLIST_ITEM ListItem_t;                                  /* For some reason lint wants this as two separate definitions. */
+
+#if __GNUC_PREREQ(4, 6)
+_Static_assert(sizeof(StaticListItem_t) == sizeof(ListItem_t), "StaticListItem_t != ListItem_t");
+#endif
+
+struct xMINI_LIST_ITEM
+{
+       listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE                               /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
+       configLIST_VOLATILE TickType_t xItemValue;
+       struct xLIST_ITEM * configLIST_VOLATILE pxNext;
+       struct xLIST_ITEM * configLIST_VOLATILE pxPrevious;
+};
+typedef struct xMINI_LIST_ITEM MiniListItem_t;
+
+#if __GNUC_PREREQ(4, 6)
+_Static_assert(sizeof(StaticMiniListItem_t) == sizeof(MiniListItem_t), "StaticMiniListItem_t != MiniListItem_t");
+#endif
+
+
+/*
+ * Definition of the type of queue used by the scheduler.
+ */
+typedef struct xLIST
+{
+       listFIRST_LIST_INTEGRITY_CHECK_VALUE                            /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
+       configLIST_VOLATILE UBaseType_t uxNumberOfItems;
+       ListItem_t * configLIST_VOLATILE pxIndex;               /*< Used to walk through the list.  Points to the last item returned by a call to listGET_OWNER_OF_NEXT_ENTRY (). */
+       MiniListItem_t xListEnd;                                                /*< List item that contains the maximum possible item value meaning it is always at the end of the list and is therefore used as a marker. */
+       listSECOND_LIST_INTEGRITY_CHECK_VALUE                           /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
+} List_t;
+
+#if __GNUC_PREREQ(4, 6)
+_Static_assert(sizeof(StaticList_t) == sizeof(List_t), "StaticList_t != List_t");
+#endif
+
+/*
+ * Access macro to set the owner of a list item.  The owner of a list item
+ * is the object (usually a TCB) that contains the list item.
+ *
+ * \page listSET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER
+ * \ingroup LinkedList
+ */
+#define listSET_LIST_ITEM_OWNER( pxListItem, pxOwner )         ( ( pxListItem )->pvOwner = ( void * ) ( pxOwner ) )
+
+/*
+ * Access macro to get the owner of a list item.  The owner of a list item
+ * is the object (usually a TCB) that contains the list item.
+ *
+ * \page listSET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER
+ * \ingroup LinkedList
+ */
+#define listGET_LIST_ITEM_OWNER( pxListItem )  ( ( pxListItem )->pvOwner )
+
+/*
+ * Access macro to set the value of the list item.  In most cases the value is
+ * used to sort the list in descending order.
+ *
+ * \page listSET_LIST_ITEM_VALUE listSET_LIST_ITEM_VALUE
+ * \ingroup LinkedList
+ */
+#define listSET_LIST_ITEM_VALUE( pxListItem, xValue )  ( ( pxListItem )->xItemValue = ( xValue ) )
+
+/*
+ * Access macro to retrieve the value of the list item.  The value can
+ * represent anything - for example the priority of a task, or the time at
+ * which a task should be unblocked.
+ *
+ * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE
+ * \ingroup LinkedList
+ */
+#define listGET_LIST_ITEM_VALUE( pxListItem )  ( ( pxListItem )->xItemValue )
+
+/*
+ * Access macro to retrieve the value of the list item at the head of a given
+ * list.
+ *
+ * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE
+ * \ingroup LinkedList
+ */
+#define listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxList )     ( ( ( pxList )->xListEnd ).pxNext->xItemValue )
+
+/*
+ * Return the list item at the head of the list.
+ *
+ * \page listGET_HEAD_ENTRY listGET_HEAD_ENTRY
+ * \ingroup LinkedList
+ */
+#define listGET_HEAD_ENTRY( pxList )   ( ( ( pxList )->xListEnd ).pxNext )
+
+/*
+ * Return the list item at the head of the list.
+ *
+ * \page listGET_NEXT listGET_NEXT
+ * \ingroup LinkedList
+ */
+#define listGET_NEXT( pxListItem )     ( ( pxListItem )->pxNext )
+
+/*
+ * Return the list item that marks the end of the list
+ *
+ * \page listGET_END_MARKER listGET_END_MARKER
+ * \ingroup LinkedList
+ */
+#define listGET_END_MARKER( pxList )   ( ( ListItem_t const * ) ( &( ( pxList )->xListEnd ) ) )
+
+/*
+ * Access macro to determine if a list contains any items.  The macro will
+ * only have the value true if the list is empty.
+ *
+ * \page listLIST_IS_EMPTY listLIST_IS_EMPTY
+ * \ingroup LinkedList
+ */
+#define listLIST_IS_EMPTY( pxList )    ( ( BaseType_t ) ( ( pxList )->uxNumberOfItems == ( UBaseType_t ) 0 ) )
+
+/*
+ * Access macro to return the number of items in the list.
+ */
+#define listCURRENT_LIST_LENGTH( pxList )      ( ( pxList )->uxNumberOfItems )
+
+/*
+ * Access function to obtain the owner of the next entry in a list.
+ *
+ * The list member pxIndex is used to walk through a list.  Calling
+ * listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list
+ * and returns that entry's pxOwner parameter.  Using multiple calls to this
+ * function it is therefore possible to move through every item contained in
+ * a list.
+ *
+ * The pxOwner parameter of a list item is a pointer to the object that owns
+ * the list item.  In the scheduler this is normally a task control block.
+ * The pxOwner parameter effectively creates a two way link between the list
+ * item and its owner.
+ *
+ * @param pxTCB pxTCB is set to the address of the owner of the next list item.
+ * @param pxList The list from which the next item owner is to be returned.
+ *
+ * \page listGET_OWNER_OF_NEXT_ENTRY listGET_OWNER_OF_NEXT_ENTRY
+ * \ingroup LinkedList
+ */
+#define listGET_OWNER_OF_NEXT_ENTRY( pxTCB, pxList )                                                                           \
+{                                                                                                                                                                                      \
+List_t * const pxConstList = ( pxList );                                                                                                       \
+       /* Increment the index to the next item and return the item, ensuring */                                \
+       /* we don't return the marker used at the end of the list.  */                                                  \
+       ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext;                                                    \
+       if( ( void * ) ( pxConstList )->pxIndex == ( void * ) &( ( pxConstList )->xListEnd ) )  \
+       {                                                                                                                                                                               \
+               ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext;                                            \
+       }                                                                                                                                                                               \
+       ( pxTCB ) = ( pxConstList )->pxIndex->pvOwner;                                                                                  \
+}
+
+
+/*
+ * Access function to obtain the owner of the first entry in a list.  Lists
+ * are normally sorted in ascending item value order.
+ *
+ * This function returns the pxOwner member of the first item in the list.
+ * The pxOwner parameter of a list item is a pointer to the object that owns
+ * the list item.  In the scheduler this is normally a task control block.
+ * The pxOwner parameter effectively creates a two way link between the list
+ * item and its owner.
+ *
+ * @param pxList The list from which the owner of the head item is to be
+ * returned.
+ *
+ * \page listGET_OWNER_OF_HEAD_ENTRY listGET_OWNER_OF_HEAD_ENTRY
+ * \ingroup LinkedList
+ */
+#define listGET_OWNER_OF_HEAD_ENTRY( pxList )  ( (&( ( pxList )->xListEnd ))->pxNext->pvOwner )
+
+/*
+ * Check to see if a list item is within a list.  The list item maintains a
+ * "container" pointer that points to the list it is in.  All this macro does
+ * is check to see if the container and the list match.
+ *
+ * @param pxList The list we want to know if the list item is within.
+ * @param pxListItem The list item we want to know if is in the list.
+ * @return pdTRUE if the list item is in the list, otherwise pdFALSE.
+ */
+#define listIS_CONTAINED_WITHIN( pxList, pxListItem ) ( ( BaseType_t ) ( ( pxListItem )->pvContainer == ( void * ) ( pxList ) ) )
+
+/*
+ * Return the list a list item is contained within (referenced from).
+ *
+ * @param pxListItem The list item being queried.
+ * @return A pointer to the List_t object that references the pxListItem
+ */
+#define listLIST_ITEM_CONTAINER( pxListItem ) ( ( pxListItem )->pvContainer )
+
+/*
+ * This provides a crude means of knowing if a list has been initialised, as
+ * pxList->xListEnd.xItemValue is set to portMAX_DELAY by the vListInitialise()
+ * function.
+ */
+#define listLIST_IS_INITIALISED( pxList ) ( ( pxList )->xListEnd.xItemValue == portMAX_DELAY )
+
+/*
+ * Must be called before a list is used!  This initialises all the members
+ * of the list structure and inserts the xListEnd item into the list as a
+ * marker to the back of the list.
+ *
+ * @param pxList Pointer to the list being initialised.
+ *
+ * \page vListInitialise vListInitialise
+ * \ingroup LinkedList
+ */
+void vListInitialise( List_t * const pxList );
+
+/*
+ * Must be called before a list item is used.  This sets the list container to
+ * null so the item does not think that it is already contained in a list.
+ *
+ * @param pxItem Pointer to the list item being initialised.
+ *
+ * \page vListInitialiseItem vListInitialiseItem
+ * \ingroup LinkedList
+ */
+void vListInitialiseItem( ListItem_t * const pxItem );
+
+/*
+ * Insert a list item into a list.  The item will be inserted into the list in
+ * a position determined by its item value (descending item value order).
+ *
+ * @param pxList The list into which the item is to be inserted.
+ *
+ * @param pxNewListItem The item that is to be placed in the list.
+ *
+ * \page vListInsert vListInsert
+ * \ingroup LinkedList
+ */
+void vListInsert( List_t * const pxList, ListItem_t * const pxNewListItem );
+
+/*
+ * Insert a list item into a list.  The item will be inserted in a position
+ * such that it will be the last item within the list returned by multiple
+ * calls to listGET_OWNER_OF_NEXT_ENTRY.
+ *
+ * The list member pvIndex is used to walk through a list.  Calling
+ * listGET_OWNER_OF_NEXT_ENTRY increments pvIndex to the next item in the list.
+ * Placing an item in a list using vListInsertEnd effectively places the item
+ * in the list position pointed to by pvIndex.  This means that every other
+ * item within the list will be returned by listGET_OWNER_OF_NEXT_ENTRY before
+ * the pvIndex parameter again points to the item being inserted.
+ *
+ * @param pxList The list into which the item is to be inserted.
+ *
+ * @param pxNewListItem The list item to be inserted into the list.
+ *
+ * \page vListInsertEnd vListInsertEnd
+ * \ingroup LinkedList
+ */
+void vListInsertEnd( List_t * const pxList, ListItem_t * const pxNewListItem );
+
+/*
+ * Remove an item from a list.  The list item has a pointer to the list that
+ * it is in, so only the list item need be passed into the function.
+ *
+ * @param uxListRemove The item to be removed.  The item will remove itself from
+ * the list pointed to by it's pxContainer parameter.
+ *
+ * @return The number of items that remain in the list after the list item has
+ * been removed.
+ *
+ * \page uxListRemove uxListRemove
+ * \ingroup LinkedList
+ */
+UBaseType_t uxListRemove( ListItem_t * const pxItemToRemove );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/private_include/queue.h b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/private_include/queue.h
new file mode 100644 (file)
index 0000000..e15152e
--- /dev/null
@@ -0,0 +1,1648 @@
+/*
+    FreeRTOS V8.2.0 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+       ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+       ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+       the FAQ page "My application does not run, what could be wrong?".  Have you
+       defined configASSERT()?
+
+       http://www.FreeRTOS.org/support - In return for receiving this top quality
+       embedded software for free we request you assist our global community by
+       participating in the support forum.
+
+       http://www.FreeRTOS.org/training - Investing in training allows your team to
+       be as productive as possible as early as possible.  Now you can receive
+       FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+       Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+
+#ifndef QUEUE_H
+#define QUEUE_H
+
+#ifndef INC_FREERTOS_H
+       #error "include FreeRTOS.h" must appear in source files before "include queue.h"
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/**
+ * Type by which queues are referenced.  For example, a call to xQueueCreate()
+ * returns an QueueHandle_t variable that can then be used as a parameter to
+ * xQueueSend(), xQueueReceive(), etc.
+ */
+typedef void * QueueHandle_t;
+
+/**
+ * Type by which queue sets are referenced.  For example, a call to
+ * xQueueCreateSet() returns an xQueueSet variable that can then be used as a
+ * parameter to xQueueSelectFromSet(), xQueueAddToSet(), etc.
+ */
+typedef void * QueueSetHandle_t;
+
+/**
+ * Queue sets can contain both queues and semaphores, so the
+ * QueueSetMemberHandle_t is defined as a type to be used where a parameter or
+ * return value can be either an QueueHandle_t or an SemaphoreHandle_t.
+ */
+typedef void * QueueSetMemberHandle_t;
+
+/** @cond */
+/* For internal use only. */
+#define        queueSEND_TO_BACK               ( ( BaseType_t ) 0 )
+#define        queueSEND_TO_FRONT              ( ( BaseType_t ) 1 )
+#define queueOVERWRITE                 ( ( BaseType_t ) 2 )
+
+/* For internal use only.  These definitions *must* match those in queue.c. */
+#define queueQUEUE_TYPE_BASE                           ( ( uint8_t ) 0U )
+#define queueQUEUE_TYPE_SET                                    ( ( uint8_t ) 0U )
+#define queueQUEUE_TYPE_MUTEX                          ( ( uint8_t ) 1U )
+#define queueQUEUE_TYPE_COUNTING_SEMAPHORE     ( ( uint8_t ) 2U )
+#define queueQUEUE_TYPE_BINARY_SEMAPHORE       ( ( uint8_t ) 3U )
+#define queueQUEUE_TYPE_RECURSIVE_MUTEX                ( ( uint8_t ) 4U )
+
+/** @endcond */
+
+/**
+ * Creates a new queue instance.  This allocates the storage required by the
+ * new queue and returns a handle for the queue.
+ *
+ * @param uxQueueLength The maximum number of items that the queue can contain.
+ *
+ * @param uxItemSize The number of bytes each item in the queue will require.
+ * Items are queued by copy, not by reference, so this is the number of bytes
+ * that will be copied for each posted item.  Each item on the queue must be
+ * the same size.
+ *
+ * @return If the queue is successfully create then a handle to the newly
+ * created queue is returned.  If the queue cannot be created then 0 is
+ * returned.
+ *
+ * Example usage:
+ * @code{c}
+ *  struct AMessage
+ *  {
+ *  char ucMessageID;
+ *  char ucData[ 20 ];
+ *  };
+ *
+ *  void vATask( void *pvParameters )
+ *  {
+ *  QueueHandle_t xQueue1, xQueue2;
+ *
+ *  // Create a queue capable of containing 10 uint32_t values.
+ *  xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
+ *  if( xQueue1 == 0 )
+ *  {
+ *      // Queue was not created and must not be used.
+ *  }
+ *
+ *  // Create a queue capable of containing 10 pointers to AMessage structures.
+ *  // These should be passed by pointer as they contain a lot of data.
+ *  xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
+ *  if( xQueue2 == 0 )
+ *  {
+ *      // Queue was not created and must not be used.
+ *  }
+ *
+ *  // ... Rest of task code.
+ *  }
+ * @endcode
+ * \ingroup QueueManagement
+ */
+#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
+       #define xQueueCreate( uxQueueLength, uxItemSize ) xQueueGenericCreate( ( uxQueueLength ), ( uxItemSize ), ( queueQUEUE_TYPE_BASE ) )
+#endif
+
+/**
+ * Creates a new queue instance, and returns a handle by which the new queue
+ * can be referenced.
+ *
+ * Internally, within the FreeRTOS implementation, queues use two blocks of
+ * memory.  The first block is used to hold the queue's data structures.  The
+ * second block is used to hold items placed into the queue.  If a queue is
+ * created using xQueueCreate() then both blocks of memory are automatically
+ * dynamically allocated inside the xQueueCreate() function.  (see
+ * http://www.freertos.org/a00111.html).  If a queue is created using
+ * xQueueCreateStatic() then the application writer must provide the memory that
+ * will get used by the queue.  xQueueCreateStatic() therefore allows a queue to
+ * be created without using any dynamic memory allocation.
+ *
+ * http://www.FreeRTOS.org/Embedded-RTOS-Queues.html
+ *
+ * @param uxQueueLength The maximum number of items that the queue can contain.
+ *
+ * @param uxItemSize The number of bytes each item in the queue will require.
+ * Items are queued by copy, not by reference, so this is the number of bytes
+ * that will be copied for each posted item.  Each item on the queue must be
+ * the same size.
+ *
+ * @param pucQueueStorage If uxItemSize is not zero then
+ * pucQueueStorageBuffer must point to a uint8_t array that is at least large
+ * enough to hold the maximum number of items that can be in the queue at any
+ * one time - which is ( uxQueueLength * uxItemsSize ) bytes.  If uxItemSize is
+ * zero then pucQueueStorageBuffer can be NULL.
+ *
+ * @param pxQueueBuffer Must point to a variable of type StaticQueue_t, which
+ * will be used to hold the queue's data structure.
+ *
+ * @return If the queue is created then a handle to the created queue is
+ * returned.  If pxQueueBuffer is NULL then NULL is returned.
+ *
+ * Example usage:
+ * @code{c}
+ * struct AMessage
+ * {
+ *  char ucMessageID;
+ *  char ucData[ 20 ];
+ * };
+ *
+ * #define QUEUE_LENGTH 10
+ * #define ITEM_SIZE sizeof( uint32_t )
+ *
+ * // xQueueBuffer will hold the queue structure.
+ * StaticQueue_t xQueueBuffer;
+ *
+ * // ucQueueStorage will hold the items posted to the queue.  Must be at least
+ * // [(queue length) * ( queue item size)] bytes long.
+ * uint8_t ucQueueStorage[ QUEUE_LENGTH * ITEM_SIZE ];
+ *
+ * void vATask( void *pvParameters )
+ * {
+ *  QueueHandle_t xQueue1;
+ *
+ *  // Create a queue capable of containing 10 uint32_t values.
+ *  xQueue1 = xQueueCreate( QUEUE_LENGTH, // The number of items the queue can hold.
+ *                          ITEM_SIZE     // The size of each item in the queue
+ *                          &( ucQueueStorage[ 0 ] ), // The buffer that will hold the items in the queue.
+ *                          &xQueueBuffer ); // The buffer that will hold the queue structure.
+ *
+ *  // The queue is guaranteed to be created successfully as no dynamic memory
+ *  // allocation is used.  Therefore xQueue1 is now a handle to a valid queue.
+ *
+ *  // ... Rest of task code.
+ * }
+ * @endcode
+ * \ingroup QueueManagement
+ */
+#if( configSUPPORT_STATIC_ALLOCATION == 1 )
+       #define xQueueCreateStatic( uxQueueLength, uxItemSize, pucQueueStorage, pxQueueBuffer ) xQueueGenericCreateStatic( ( uxQueueLength ), ( uxItemSize ), ( pucQueueStorage ), ( pxQueueBuffer ), ( queueQUEUE_TYPE_BASE ) )
+#endif /* configSUPPORT_STATIC_ALLOCATION */
+
+/**
+ * This is a macro that calls xQueueGenericSend().
+ *
+ * Post an item to the front of a queue.  The item is queued by copy, not by
+ * reference.  This function must not be called from an interrupt service
+ * routine.  See xQueueSendFromISR () for an alternative which may be used
+ * in an ISR.
+ *
+ * @param xQueue The handle to the queue on which the item is to be posted.
+ *
+ * @param pvItemToQueue A pointer to the item that is to be placed on the
+ * queue.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from pvItemToQueue
+ * into the queue storage area.
+ *
+ * @param xTicksToWait The maximum amount of time the task should block
+ * waiting for space to become available on the queue, should it already
+ * be full.  The call will return immediately if this is set to 0 and the
+ * queue is full.  The time is defined in tick periods so the constant
+ * portTICK_PERIOD_MS should be used to convert to real time if this is required.
+ *
+ * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL.
+ *
+ * Example usage:
+ * @code{c}
+ *  struct AMessage
+ *  {
+ *  char ucMessageID;
+ *  char ucData[ 20 ];
+ *  } xMessage;
+ *
+ *  uint32_t ulVar = 10UL;
+ *
+ *  void vATask( void *pvParameters )
+ *  {
+ *  QueueHandle_t xQueue1, xQueue2;
+ *  struct AMessage *pxMessage;
+ *
+ *  // Create a queue capable of containing 10 uint32_t values.
+ *  xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
+ *
+ *  // Create a queue capable of containing 10 pointers to AMessage structures.
+ *  // These should be passed by pointer as they contain a lot of data.
+ *  xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
+ *
+ *  // ...
+ *
+ *  if( xQueue1 != 0 )
+ *  {
+ *      // Send an uint32_t.  Wait for 10 ticks for space to become
+ *      // available if necessary.
+ *      if( xQueueSendToFront( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS )
+ *      {
+ *          // Failed to post the message, even after 10 ticks.
+ *      }
+ *  }
+ *
+ *  if( xQueue2 != 0 )
+ *  {
+ *      // Send a pointer to a struct AMessage object.  Don't block if the
+ *      // queue is already full.
+ *      pxMessage = & xMessage;
+ *      xQueueSendToFront( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
+ *  }
+ *
+ *  // ... Rest of task code.
+ *  }
+ * @endcode
+ * \ingroup QueueManagement
+ */
+#define xQueueSendToFront( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_FRONT )
+
+/**
+ * This is a macro that calls xQueueGenericSend().
+ *
+ * Post an item to the back of a queue.  The item is queued by copy, not by
+ * reference.  This function must not be called from an interrupt service
+ * routine.  See xQueueSendFromISR () for an alternative which may be used
+ * in an ISR.
+ *
+ * @param xQueue The handle to the queue on which the item is to be posted.
+ *
+ * @param pvItemToQueue A pointer to the item that is to be placed on the
+ * queue.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from pvItemToQueue
+ * into the queue storage area.
+ *
+ * @param xTicksToWait The maximum amount of time the task should block
+ * waiting for space to become available on the queue, should it already
+ * be full.  The call will return immediately if this is set to 0 and the queue
+ * is full.  The  time is defined in tick periods so the constant
+ * portTICK_PERIOD_MS should be used to convert to real time if this is required.
+ *
+ * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL.
+ *
+ * Example usage:
+ * @code{c}
+ *  struct AMessage
+ *  {
+ *  char ucMessageID;
+ *  char ucData[ 20 ];
+ *  } xMessage;
+ *
+ *  uint32_t ulVar = 10UL;
+ *
+ *  void vATask( void *pvParameters )
+ *  {
+ *  QueueHandle_t xQueue1, xQueue2;
+ *  struct AMessage *pxMessage;
+ *
+ *  // Create a queue capable of containing 10 uint32_t values.
+ *  xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
+ *
+ *  // Create a queue capable of containing 10 pointers to AMessage structures.
+ *  // These should be passed by pointer as they contain a lot of data.
+ *  xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
+ *
+ *  // ...
+ *
+ *  if( xQueue1 != 0 )
+ *  {
+ *      // Send an uint32_t.  Wait for 10 ticks for space to become
+ *      // available if necessary.
+ *      if( xQueueSendToBack( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS )
+ *      {
+ *          // Failed to post the message, even after 10 ticks.
+ *      }
+ *  }
+ *
+ *  if( xQueue2 != 0 )
+ *  {
+ *      // Send a pointer to a struct AMessage object.  Don't block if the
+ *      // queue is already full.
+ *      pxMessage = & xMessage;
+ *      xQueueSendToBack( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
+ *  }
+ *
+ *  // ... Rest of task code.
+ *  }
+ * @endcode
+ * \ingroup QueueManagement
+ */
+#define xQueueSendToBack( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_BACK )
+
+/**
+ * This is a macro that calls xQueueGenericSend().  It is included for
+ * backward compatibility with versions of FreeRTOS.org that did not
+ * include the xQueueSendToFront() and xQueueSendToBack() macros.  It is
+ * equivalent to xQueueSendToBack().
+ *
+ * Post an item on a queue.  The item is queued by copy, not by reference.
+ * This function must not be called from an interrupt service routine.
+ * See xQueueSendFromISR () for an alternative which may be used in an ISR.
+ *
+ * @param xQueue The handle to the queue on which the item is to be posted.
+ *
+ * @param pvItemToQueue A pointer to the item that is to be placed on the
+ * queue.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from pvItemToQueue
+ * into the queue storage area.
+ *
+ * @param xTicksToWait The maximum amount of time the task should block
+ * waiting for space to become available on the queue, should it already
+ * be full.  The call will return immediately if this is set to 0 and the
+ * queue is full.  The time is defined in tick periods so the constant
+ * portTICK_PERIOD_MS should be used to convert to real time if this is required.
+ *
+ * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL.
+ *
+ * Example usage:
+ * @code{c}
+ *  struct AMessage
+ *  {
+ *  char ucMessageID;
+ *  char ucData[ 20 ];
+ *  } xMessage;
+ *
+ *  uint32_t ulVar = 10UL;
+ *
+ *  void vATask( void *pvParameters )
+ *  {
+ *  QueueHandle_t xQueue1, xQueue2;
+ *  struct AMessage *pxMessage;
+ *
+ *  // Create a queue capable of containing 10 uint32_t values.
+ *  xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
+ *
+ *  // Create a queue capable of containing 10 pointers to AMessage structures.
+ *  // These should be passed by pointer as they contain a lot of data.
+ *  xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
+ *
+ *  // ...
+ *
+ *  if( xQueue1 != 0 )
+ *  {
+ *      // Send an uint32_t.  Wait for 10 ticks for space to become
+ *      // available if necessary.
+ *      if( xQueueSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS )
+ *      {
+ *          // Failed to post the message, even after 10 ticks.
+ *      }
+ *  }
+ *
+ *  if( xQueue2 != 0 )
+ *  {
+ *      // Send a pointer to a struct AMessage object.  Don't block if the
+ *      // queue is already full.
+ *      pxMessage = & xMessage;
+ *      xQueueSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
+ *  }
+ *
+ *  // ... Rest of task code.
+ *  }
+ * @endcode
+ * \ingroup QueueManagement
+ */
+#define xQueueSend( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_BACK )
+
+/**
+ * Only for use with queues that have a length of one - so the queue is either
+ * empty or full.
+ *
+ * Post an item on a queue.  If the queue is already full then overwrite the
+ * value held in the queue.  The item is queued by copy, not by reference.
+ *
+ * This function must not be called from an interrupt service routine.
+ * See xQueueOverwriteFromISR () for an alternative which may be used in an ISR.
+ *
+ * @param xQueue The handle of the queue to which the data is being sent.
+ *
+ * @param pvItemToQueue A pointer to the item that is to be placed on the
+ * queue.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from pvItemToQueue
+ * into the queue storage area.
+ *
+ * @return xQueueOverwrite() is a macro that calls xQueueGenericSend(), and
+ * therefore has the same return values as xQueueSendToFront().  However, pdPASS
+ * is the only value that can be returned because xQueueOverwrite() will write
+ * to the queue even when the queue is already full.
+ *
+ * Example usage:
+ * @code{c}
+ *
+ *  void vFunction( void *pvParameters )
+ *  {
+ *  QueueHandle_t xQueue;
+ *  uint32_t ulVarToSend, ulValReceived;
+ *
+ *  // Create a queue to hold one uint32_t value.  It is strongly
+ *  // recommended *not* to use xQueueOverwrite() on queues that can
+ *  // contain more than one value, and doing so will trigger an assertion
+ *  // if configASSERT() is defined.
+ *  xQueue = xQueueCreate( 1, sizeof( uint32_t ) );
+ *
+ *  // Write the value 10 to the queue using xQueueOverwrite().
+ *  ulVarToSend = 10;
+ *  xQueueOverwrite( xQueue, &ulVarToSend );
+ *
+ *  // Peeking the queue should now return 10, but leave the value 10 in
+ *  // the queue.  A block time of zero is used as it is known that the
+ *  // queue holds a value.
+ *  ulValReceived = 0;
+ *  xQueuePeek( xQueue, &ulValReceived, 0 );
+ *
+ *  if( ulValReceived != 10 )
+ *  {
+ *      // Error unless the item was removed by a different task.
+ *  }
+ *
+ *  // The queue is still full.  Use xQueueOverwrite() to overwrite the
+ *  // value held in the queue with 100.
+ *  ulVarToSend = 100;
+ *  xQueueOverwrite( xQueue, &ulVarToSend );
+ *
+ *  // This time read from the queue, leaving the queue empty once more.
+ *  // A block time of 0 is used again.
+ *  xQueueReceive( xQueue, &ulValReceived, 0 );
+ *
+ *  // The value read should be the last value written, even though the
+ *  // queue was already full when the value was written.
+ *  if( ulValReceived != 100 )
+ *  {
+ *      // Error!
+ *  }
+ *
+ *  // ...
+ * }
+ * @endcode
+ * \ingroup QueueManagement
+ */
+#define xQueueOverwrite( xQueue, pvItemToQueue ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), 0, queueOVERWRITE )
+
+
+/**
+ * It is preferred that the macros xQueueSend(), xQueueSendToFront() and
+ * xQueueSendToBack() are used in place of calling this function directly.
+ *
+ * Post an item on a queue.  The item is queued by copy, not by reference.
+ * This function must not be called from an interrupt service routine.
+ * See xQueueSendFromISR () for an alternative which may be used in an ISR.
+ *
+ * @param xQueue The handle to the queue on which the item is to be posted.
+ *
+ * @param pvItemToQueue A pointer to the item that is to be placed on the
+ * queue.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from pvItemToQueue
+ * into the queue storage area.
+ *
+ * @param xTicksToWait The maximum amount of time the task should block
+ * waiting for space to become available on the queue, should it already
+ * be full.  The call will return immediately if this is set to 0 and the
+ * queue is full.  The time is defined in tick periods so the constant
+ * portTICK_PERIOD_MS should be used to convert to real time if this is required.
+ *
+ * @param xCopyPosition Can take the value queueSEND_TO_BACK to place the
+ * item at the back of the queue, or queueSEND_TO_FRONT to place the item
+ * at the front of the queue (for high priority messages).
+ *
+ * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL.
+ *
+ * Example usage:
+ * @code{c}
+ *  struct AMessage
+ *  {
+ *  char ucMessageID;
+ *  char ucData[ 20 ];
+ *  } xMessage;
+ *
+ *  uint32_t ulVar = 10UL;
+ *
+ *  void vATask( void *pvParameters )
+ *  {
+ *  QueueHandle_t xQueue1, xQueue2;
+ *  struct AMessage *pxMessage;
+ *
+ *  // Create a queue capable of containing 10 uint32_t values.
+ *  xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
+ *
+ *  // Create a queue capable of containing 10 pointers to AMessage structures.
+ *  // These should be passed by pointer as they contain a lot of data.
+ *  xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
+ *
+ *  // ...
+ *
+ *  if( xQueue1 != 0 )
+ *  {
+ *      // Send an uint32_t.  Wait for 10 ticks for space to become
+ *      // available if necessary.
+ *      if( xQueueGenericSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10, queueSEND_TO_BACK ) != pdPASS )
+ *      {
+ *          // Failed to post the message, even after 10 ticks.
+ *      }
+ *  }
+ *
+ *  if( xQueue2 != 0 )
+ *  {
+ *      // Send a pointer to a struct AMessage object.  Don't block if the
+ *      // queue is already full.
+ *      pxMessage = & xMessage;
+ *      xQueueGenericSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0, queueSEND_TO_BACK );
+ *  }
+ *
+ *  // ... Rest of task code.
+ *  }
+ * @endcode
+ * \ingroup QueueManagement
+ */
+BaseType_t xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQueue, TickType_t xTicksToWait, const BaseType_t xCopyPosition ) PRIVILEGED_FUNCTION;
+
+/**
+ * This is a macro that calls the xQueueGenericReceive() function.
+ *
+ * Receive an item from a queue without removing the item from the queue.
+ * The item is received by copy so a buffer of adequate size must be
+ * provided.  The number of bytes copied into the buffer was defined when
+ * the queue was created.
+ *
+ * Successfully received items remain on the queue so will be returned again
+ * by the next call, or a call to xQueueReceive().
+ *
+ * This macro must not be used in an interrupt service routine.  See
+ * xQueuePeekFromISR() for an alternative that can be called from an interrupt
+ * service routine.
+ *
+ * @param xQueue The handle to the queue from which the item is to be
+ * received.
+ *
+ * @param pvBuffer Pointer to the buffer into which the received item will
+ * be copied.
+ *
+ * @param xTicksToWait The maximum amount of time the task should block
+ * waiting for an item to receive should the queue be empty at the time
+ * of the call.         The time is defined in tick periods so the constant
+ * portTICK_PERIOD_MS should be used to convert to real time if this is required.
+ * xQueuePeek() will return immediately if xTicksToWait is 0 and the queue
+ * is empty.
+ *
+ * @return pdTRUE if an item was successfully received from the queue,
+ * otherwise pdFALSE.
+ *
+ * Example usage:
+ * @code{c}
+ *  struct AMessage
+ *  {
+ *  char ucMessageID;
+ *  char ucData[ 20 ];
+ *  } xMessage;
+ *
+ *  QueueHandle_t xQueue;
+ *
+ *  // Task to create a queue and post a value.
+ *  void vATask( void *pvParameters )
+ *  {
+ *  struct AMessage *pxMessage;
+ *
+ *  // Create a queue capable of containing 10 pointers to AMessage structures.
+ *  // These should be passed by pointer as they contain a lot of data.
+ *  xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) );
+ *  if( xQueue == 0 )
+ *  {
+ *      // Failed to create the queue.
+ *  }
+ *
+ *  // ...
+ *
+ *  // Send a pointer to a struct AMessage object.  Don't block if the
+ *  // queue is already full.
+ *  pxMessage = & xMessage;
+ *  xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 );
+ *
+ *  // ... Rest of task code.
+ *  }
+ *
+ *  // Task to peek the data from the queue.
+ *  void vADifferentTask( void *pvParameters )
+ *  {
+ *  struct AMessage *pxRxedMessage;
+ *
+ *  if( xQueue != 0 )
+ *  {
+ *      // Peek a message on the created queue.  Block for 10 ticks if a
+ *      // message is not immediately available.
+ *      if( xQueuePeek( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) )
+ *      {
+ *          // pcRxedMessage now points to the struct AMessage variable posted
+ *          // by vATask, but the item still remains on the queue.
+ *      }
+ *  }
+ *
+ *  // ... Rest of task code.
+ *  }
+ * @endcode
+ * \ingroup QueueManagement
+ */
+#define xQueuePeek( xQueue, pvBuffer, xTicksToWait ) xQueueGenericReceive( ( xQueue ), ( pvBuffer ), ( xTicksToWait ), pdTRUE )
+
+/**
+ * A version of xQueuePeek() that can be called from an interrupt service
+ * routine (ISR).
+ *
+ * Receive an item from a queue without removing the item from the queue.
+ * The item is received by copy so a buffer of adequate size must be
+ * provided.  The number of bytes copied into the buffer was defined when
+ * the queue was created.
+ *
+ * Successfully received items remain on the queue so will be returned again
+ * by the next call, or a call to xQueueReceive().
+ *
+ * @param xQueue The handle to the queue from which the item is to be
+ * received.
+ *
+ * @param pvBuffer Pointer to the buffer into which the received item will
+ * be copied.
+ *
+ * @return pdTRUE if an item was successfully received from the queue,
+ * otherwise pdFALSE.
+ *
+ * \ingroup QueueManagement
+ */
+BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, void * const pvBuffer ) PRIVILEGED_FUNCTION;
+
+/**
+ * queue. h
+ * <pre>
+ BaseType_t xQueueReceive(
+                                                                QueueHandle_t xQueue,
+                                                                void *pvBuffer,
+                                                                TickType_t xTicksToWait
+                                                       );</pre>
+ *
+ * This is a macro that calls the xQueueGenericReceive() function.
+ *
+ * Receive an item from a queue.  The item is received by copy so a buffer of
+ * adequate size must be provided.  The number of bytes copied into the buffer
+ * was defined when the queue was created.
+ *
+ * Successfully received items are removed from the queue.
+ *
+ * This function must not be used in an interrupt service routine.  See
+ * xQueueReceiveFromISR for an alternative that can.
+ *
+ * @param xQueue The handle to the queue from which the item is to be
+ * received.
+ *
+ * @param pvBuffer Pointer to the buffer into which the received item will
+ * be copied.
+ *
+ * @param xTicksToWait The maximum amount of time the task should block
+ * waiting for an item to receive should the queue be empty at the time
+ * of the call.         xQueueReceive() will return immediately if xTicksToWait
+ * is zero and the queue is empty.  The time is defined in tick periods so the
+ * constant portTICK_PERIOD_MS should be used to convert to real time if this is
+ * required.
+ *
+ * @return pdTRUE if an item was successfully received from the queue,
+ * otherwise pdFALSE.
+ *
+ * Example usage:
+ * @code{c}
+ *  struct AMessage
+ *  {
+ *     char ucMessageID;
+ *     char ucData[ 20 ];
+ *  } xMessage;
+ *
+ *  QueueHandle_t xQueue;
+ *
+ *  // Task to create a queue and post a value.
+ *  void vATask( void *pvParameters )
+ *  {
+ *  struct AMessage *pxMessage;
+ *
+ *     // Create a queue capable of containing 10 pointers to AMessage structures.
+ *     // These should be passed by pointer as they contain a lot of data.
+ *     xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) );
+ *     if( xQueue == 0 )
+ *     {
+ *             // Failed to create the queue.
+ *     }
+ *
+ *     // ...
+ *
+ *     // Send a pointer to a struct AMessage object.  Don't block if the
+ *     // queue is already full.
+ *     pxMessage = & xMessage;
+ *     xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 );
+ *
+ *     // ... Rest of task code.
+ *  }
+ *
+ *  // Task to receive from the queue.
+ *  void vADifferentTask( void *pvParameters )
+ *  {
+ *  struct AMessage *pxRxedMessage;
+ *
+ *     if( xQueue != 0 )
+ *     {
+ *             // Receive a message on the created queue.  Block for 10 ticks if a
+ *             // message is not immediately available.
+ *             if( xQueueReceive( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) )
+ *             {
+ *                     // pcRxedMessage now points to the struct AMessage variable posted
+ *                     // by vATask.
+ *             }
+ *     }
+ *
+ *     // ... Rest of task code.
+ *  }
+ * @endcode
+ * \ingroup QueueManagement
+ */
+#define xQueueReceive( xQueue, pvBuffer, xTicksToWait ) xQueueGenericReceive( ( xQueue ), ( pvBuffer ), ( xTicksToWait ), pdFALSE )
+
+
+/**
+ * It is preferred that the macro xQueueReceive() be used rather than calling
+ * this function directly.
+ *
+ * Receive an item from a queue.  The item is received by copy so a buffer of
+ * adequate size must be provided.  The number of bytes copied into the buffer
+ * was defined when the queue was created.
+ *
+ * This function must not be used in an interrupt service routine.  See
+ * xQueueReceiveFromISR for an alternative that can.
+ *
+ * @param xQueue The handle to the queue from which the item is to be
+ * received.
+ *
+ * @param pvBuffer Pointer to the buffer into which the received item will
+ * be copied.
+ *
+ * @param xTicksToWait The maximum amount of time the task should block
+ * waiting for an item to receive should the queue be empty at the time
+ * of the call.         The time is defined in tick periods so the constant
+ * portTICK_PERIOD_MS should be used to convert to real time if this is required.
+ * xQueueGenericReceive() will return immediately if the queue is empty and
+ * xTicksToWait is 0.
+ *
+ * @param xJustPeek When set to true, the item received from the queue is not
+ * actually removed from the queue - meaning a subsequent call to
+ * xQueueReceive() will return the same item.  When set to false, the item
+ * being received from the queue is also removed from the queue.
+ *
+ * @return pdTRUE if an item was successfully received from the queue,
+ * otherwise pdFALSE.
+ *
+ * Example usage:
+ * @code{c}
+ *  struct AMessage
+ *  {
+ *     char ucMessageID;
+ *     char ucData[ 20 ];
+ *  } xMessage;
+ *
+ *  QueueHandle_t xQueue;
+ *
+ *  // Task to create a queue and post a value.
+ *  void vATask( void *pvParameters )
+ *  {
+ *  struct AMessage *pxMessage;
+ *
+ *     // Create a queue capable of containing 10 pointers to AMessage structures.
+ *     // These should be passed by pointer as they contain a lot of data.
+ *     xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) );
+ *     if( xQueue == 0 )
+ *     {
+ *             // Failed to create the queue.
+ *     }
+ *
+ *     // ...
+ *
+ *     // Send a pointer to a struct AMessage object.  Don't block if the
+ *     // queue is already full.
+ *     pxMessage = & xMessage;
+ *     xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 );
+ *
+ *     // ... Rest of task code.
+ *  }
+ *
+ *  // Task to receive from the queue.
+ *  void vADifferentTask( void *pvParameters )
+ *  {
+ *  struct AMessage *pxRxedMessage;
+ *
+ *     if( xQueue != 0 )
+ *     {
+ *             // Receive a message on the created queue.  Block for 10 ticks if a
+ *             // message is not immediately available.
+ *             if( xQueueGenericReceive( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) )
+ *             {
+ *                     // pcRxedMessage now points to the struct AMessage variable posted
+ *                     // by vATask.
+ *             }
+ *     }
+ *
+ *     // ... Rest of task code.
+ *  }
+ * @endcode
+ * \ingroup QueueManagement
+ */
+BaseType_t xQueueGenericReceive( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait, const BaseType_t xJustPeek ) PRIVILEGED_FUNCTION;
+
+/**
+ * Return the number of messages stored in a queue.
+ *
+ * @param xQueue A handle to the queue being queried.
+ *
+ * @return The number of messages available in the queue.
+ *
+ * \ingroup QueueManagement
+ */
+UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
+
+/**
+ * Return the number of free spaces available in a queue.  This is equal to the
+ * number of items that can be sent to the queue before the queue becomes full
+ * if no items are removed.
+ *
+ * @param xQueue A handle to the queue being queried.
+ *
+ * @return The number of spaces available in the queue.
+ *
+ * \ingroup QueueManagement
+ */
+UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
+
+/**
+ * Delete a queue - freeing all the memory allocated for storing of items
+ * placed on the queue.
+ *
+ * @param xQueue A handle to the queue to be deleted.
+ *
+ * \ingroup QueueManagement
+ */
+void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
+
+/**
+ * This is a macro that calls xQueueGenericSendFromISR().
+ *
+ * Post an item to the front of a queue.  It is safe to use this macro from
+ * within an interrupt service routine.
+ *
+ * Items are queued by copy not reference so it is preferable to only
+ * queue small items, especially when called from an ISR.  In most cases
+ * it would be preferable to store a pointer to the item being queued.
+ *
+ * @param xQueue The handle to the queue on which the item is to be posted.
+ *
+ * @param pvItemToQueue A pointer to the item that is to be placed on the
+ * queue.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from pvItemToQueue
+ * into the queue storage area.
+ *
+ * @param[out] pxHigherPriorityTaskWoken xQueueSendToFrontFromISR() will set
+ * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task
+ * to unblock, and the unblocked task has a priority higher than the currently
+ * running task.  If xQueueSendToFromFromISR() sets this value to pdTRUE then
+ * a context switch should be requested before the interrupt is exited.
+ *
+ * @return pdTRUE if the data was successfully sent to the queue, otherwise
+ * errQUEUE_FULL.
+ *
+ * Example usage for buffered IO (where the ISR can obtain more than one value
+ * per call):
+ * @code{c}
+ *  void vBufferISR( void )
+ *  {
+ *  char cIn;
+ *  BaseType_t xHigherPrioritTaskWoken;
+ *
+ *     // We have not woken a task at the start of the ISR.
+ *     xHigherPriorityTaskWoken = pdFALSE;
+ *
+ *     // Loop until the buffer is empty.
+ *     do
+ *     {
+ *             // Obtain a byte from the buffer.
+ *             cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS );
+ *
+ *             // Post the byte.
+ *             xQueueSendToFrontFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken );
+ *
+ *     } while( portINPUT_BYTE( BUFFER_COUNT ) );
+ *
+ *     // Now the buffer is empty we can switch context if necessary.
+ *     if( xHigherPriorityTaskWoken )
+ *     {
+ *             portYIELD_FROM_ISR ();
+ *     }
+ *  }
+ * @endcode
+ * \ingroup QueueManagement
+ */
+#define xQueueSendToFrontFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_FRONT )
+
+
+/**
+ * This is a macro that calls xQueueGenericSendFromISR().
+ *
+ * Post an item to the back of a queue.  It is safe to use this macro from
+ * within an interrupt service routine.
+ *
+ * Items are queued by copy not reference so it is preferable to only
+ * queue small items, especially when called from an ISR.  In most cases
+ * it would be preferable to store a pointer to the item being queued.
+ *
+ * @param xQueue The handle to the queue on which the item is to be posted.
+ *
+ * @param pvItemToQueue A pointer to the item that is to be placed on the
+ * queue.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from pvItemToQueue
+ * into the queue storage area.
+ *
+ * @param[out] pxHigherPriorityTaskWoken xQueueSendToBackFromISR() will set
+ * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task
+ * to unblock, and the unblocked task has a priority higher than the currently
+ * running task.  If xQueueSendToBackFromISR() sets this value to pdTRUE then
+ * a context switch should be requested before the interrupt is exited.
+ *
+ * @return pdTRUE if the data was successfully sent to the queue, otherwise
+ * errQUEUE_FULL.
+ *
+ * Example usage for buffered IO (where the ISR can obtain more than one value
+ * per call):
+ * @code{c}
+ *  void vBufferISR( void )
+ *  {
+ *  char cIn;
+ *  BaseType_t xHigherPriorityTaskWoken;
+ *
+ *     // We have not woken a task at the start of the ISR.
+ *     xHigherPriorityTaskWoken = pdFALSE;
+ *
+ *     // Loop until the buffer is empty.
+ *     do
+ *     {
+ *             // Obtain a byte from the buffer.
+ *             cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS );
+ *
+ *             // Post the byte.
+ *             xQueueSendToBackFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken );
+ *
+ *     } while( portINPUT_BYTE( BUFFER_COUNT ) );
+ *
+ *     // Now the buffer is empty we can switch context if necessary.
+ *     if( xHigherPriorityTaskWoken )
+ *     {
+ *             portYIELD_FROM_ISR ();
+ *     }
+ *  }
+ * @endcode
+ * \ingroup QueueManagement
+ */
+#define xQueueSendToBackFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_BACK )
+
+/**
+ * A version of xQueueOverwrite() that can be used in an interrupt service
+ * routine (ISR).
+ *
+ * Only for use with queues that can hold a single item - so the queue is either
+ * empty or full.
+ *
+ * Post an item on a queue.  If the queue is already full then overwrite the
+ * value held in the queue.  The item is queued by copy, not by reference.
+ *
+ * @param xQueue The handle to the queue on which the item is to be posted.
+ *
+ * @param pvItemToQueue A pointer to the item that is to be placed on the
+ * queue.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from pvItemToQueue
+ * into the queue storage area.
+ *
+ * @param[out] pxHigherPriorityTaskWoken xQueueOverwriteFromISR() will set
+ * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task
+ * to unblock, and the unblocked task has a priority higher than the currently
+ * running task.  If xQueueOverwriteFromISR() sets this value to pdTRUE then
+ * a context switch should be requested before the interrupt is exited.
+ *
+ * @return xQueueOverwriteFromISR() is a macro that calls
+ * xQueueGenericSendFromISR(), and therefore has the same return values as
+ * xQueueSendToFrontFromISR().  However, pdPASS is the only value that can be
+ * returned because xQueueOverwriteFromISR() will write to the queue even when
+ * the queue is already full.
+ *
+ * Example usage:
+ * @code{c}
+ *  QueueHandle_t xQueue;
+ *
+ *  void vFunction( void *pvParameters )
+ *  {
+ *     // Create a queue to hold one uint32_t value.  It is strongly
+ *     // recommended *not* to use xQueueOverwriteFromISR() on queues that can
+ *     // contain more than one value, and doing so will trigger an assertion
+ *     // if configASSERT() is defined.
+ *     xQueue = xQueueCreate( 1, sizeof( uint32_t ) );
+ * }
+ *
+ * void vAnInterruptHandler( void )
+ * {
+ * // xHigherPriorityTaskWoken must be set to pdFALSE before it is used.
+ * BaseType_t xHigherPriorityTaskWoken = pdFALSE;
+ * uint32_t ulVarToSend, ulValReceived;
+ *
+ *     // Write the value 10 to the queue using xQueueOverwriteFromISR().
+ *     ulVarToSend = 10;
+ *     xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken );
+ *
+ *     // The queue is full, but calling xQueueOverwriteFromISR() again will still
+ *     // pass because the value held in the queue will be overwritten with the
+ *     // new value.
+ *     ulVarToSend = 100;
+ *     xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken );
+ *
+ *     // Reading from the queue will now return 100.
+ *
+ *     // ...
+ *
+ *     if( xHigherPrioritytaskWoken == pdTRUE )
+ *     {
+ *             // Writing to the queue caused a task to unblock and the unblocked task
+ *             // has a priority higher than or equal to the priority of the currently
+ *             // executing task (the task this interrupt interrupted).  Perform a context
+ *             // switch so this interrupt returns directly to the unblocked task.
+ *             portYIELD_FROM_ISR(); // or portEND_SWITCHING_ISR() depending on the port.
+ *     }
+ * }
+ * @endcode
+ * \ingroup QueueManagement
+ */
+#define xQueueOverwriteFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueOVERWRITE )
+
+/**
+ * This is a macro that calls xQueueGenericSendFromISR().  It is included
+ * for backward compatibility with versions of FreeRTOS.org that did not
+ * include the xQueueSendToBackFromISR() and xQueueSendToFrontFromISR()
+ * macros.
+ *
+ * Post an item to the back of a queue.  It is safe to use this function from
+ * within an interrupt service routine.
+ *
+ * Items are queued by copy not reference so it is preferable to only
+ * queue small items, especially when called from an ISR.  In most cases
+ * it would be preferable to store a pointer to the item being queued.
+ *
+ * @param xQueue The handle to the queue on which the item is to be posted.
+ *
+ * @param pvItemToQueue A pointer to the item that is to be placed on the
+ * queue.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from pvItemToQueue
+ * into the queue storage area.
+ *
+ * @param[out] pxHigherPriorityTaskWoken xQueueSendFromISR() will set
+ * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task
+ * to unblock, and the unblocked task has a priority higher than the currently
+ * running task.  If xQueueSendFromISR() sets this value to pdTRUE then
+ * a context switch should be requested before the interrupt is exited.
+ *
+ * @return pdTRUE if the data was successfully sent to the queue, otherwise
+ * errQUEUE_FULL.
+ *
+ * Example usage for buffered IO (where the ISR can obtain more than one value
+ * per call):
+ * @code{c}
+ *  void vBufferISR( void )
+ *  {
+ *  char cIn;
+ *  BaseType_t xHigherPriorityTaskWoken;
+ *
+ *     // We have not woken a task at the start of the ISR.
+ *     xHigherPriorityTaskWoken = pdFALSE;
+ *
+ *     // Loop until the buffer is empty.
+ *     do
+ *     {
+ *             // Obtain a byte from the buffer.
+ *             cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS );
+ *
+ *             // Post the byte.
+ *             xQueueSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken );
+ *
+ *     } while( portINPUT_BYTE( BUFFER_COUNT ) );
+ *
+ *     // Now the buffer is empty we can switch context if necessary.
+ *     if( xHigherPriorityTaskWoken )
+ *     {
+ *             // Actual macro used here is port specific.
+ *             portYIELD_FROM_ISR ();
+ *     }
+ *  }
+ * @endcode
+ *
+ * \ingroup QueueManagement
+ */
+#define xQueueSendFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_BACK )
+
+/**@{*/
+/**
+ * It is preferred that the macros xQueueSendFromISR(),
+ * xQueueSendToFrontFromISR() and xQueueSendToBackFromISR() be used in place
+ * of calling this function directly.  xQueueGiveFromISR() is an
+ * equivalent for use by semaphores that don't actually copy any data.
+ *
+ * Post an item on a queue.  It is safe to use this function from within an
+ * interrupt service routine.
+ *
+ * Items are queued by copy not reference so it is preferable to only
+ * queue small items, especially when called from an ISR.  In most cases
+ * it would be preferable to store a pointer to the item being queued.
+ *
+ * @param xQueue The handle to the queue on which the item is to be posted.
+ *
+ * @param pvItemToQueue A pointer to the item that is to be placed on the
+ * queue.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from pvItemToQueue
+ * into the queue storage area.
+ *
+ * @param[out] pxHigherPriorityTaskWoken xQueueGenericSendFromISR() will set
+ * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task
+ * to unblock, and the unblocked task has a priority higher than the currently
+ * running task.  If xQueueGenericSendFromISR() sets this value to pdTRUE then
+ * a context switch should be requested before the interrupt is exited.
+ *
+ * @param xCopyPosition Can take the value queueSEND_TO_BACK to place the
+ * item at the back of the queue, or queueSEND_TO_FRONT to place the item
+ * at the front of the queue (for high priority messages).
+ *
+ * @return pdTRUE if the data was successfully sent to the queue, otherwise
+ * errQUEUE_FULL.
+ *
+ * Example usage for buffered IO (where the ISR can obtain more than one value
+ * per call):
+ * @code{c}
+ *  void vBufferISR( void )
+ *  {
+ *  char cIn;
+ *  BaseType_t xHigherPriorityTaskWokenByPost;
+ *
+ *     // We have not woken a task at the start of the ISR.
+ *     xHigherPriorityTaskWokenByPost = pdFALSE;
+ *
+ *     // Loop until the buffer is empty.
+ *     do
+ *     {
+ *             // Obtain a byte from the buffer.
+ *             cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS );
+ *
+ *             // Post each byte.
+ *             xQueueGenericSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWokenByPost, queueSEND_TO_BACK );
+ *
+ *     } while( portINPUT_BYTE( BUFFER_COUNT ) );
+ *
+ *     // Now the buffer is empty we can switch context if necessary.  Note that the
+ *     // name of the yield function required is port specific.
+ *     if( xHigherPriorityTaskWokenByPost )
+ *     {
+ *             taskYIELD_YIELD_FROM_ISR();
+ *     }
+ *  }
+ * @endcode
+ * \ingroup QueueManagement
+ */
+BaseType_t xQueueGenericSendFromISR( QueueHandle_t xQueue, const void * const pvItemToQueue, BaseType_t * const pxHigherPriorityTaskWoken, const BaseType_t xCopyPosition ) PRIVILEGED_FUNCTION;
+BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;
+/**@}*/
+
+/**
+ * Receive an item from a queue.  It is safe to use this function from within an
+ * interrupt service routine.
+ *
+ * @param xQueue The handle to the queue from which the item is to be
+ * received.
+ *
+ * @param pvBuffer Pointer to the buffer into which the received item will
+ * be copied.
+ *
+ * @param[out] pxHigherPriorityTaskWoken A task may be blocked waiting for space to become
+ * available on the queue.  If xQueueReceiveFromISR causes such a task to
+ * unblock *pxTaskWoken will get set to pdTRUE, otherwise *pxTaskWoken will
+ * remain unchanged.
+ *
+ * @return pdTRUE if an item was successfully received from the queue,
+ * otherwise pdFALSE.
+ *
+ * Example usage:
+ * @code{c}
+ *  QueueHandle_t xQueue;
+ *
+ *  // Function to create a queue and post some values.
+ *  void vAFunction( void *pvParameters )
+ *  {
+ *  char cValueToPost;
+ *  const TickType_t xTicksToWait = ( TickType_t )0xff;
+ *
+ *     // Create a queue capable of containing 10 characters.
+ *     xQueue = xQueueCreate( 10, sizeof( char ) );
+ *     if( xQueue == 0 )
+ *     {
+ *             // Failed to create the queue.
+ *     }
+ *
+ *     // ...
+ *
+ *     // Post some characters that will be used within an ISR.  If the queue
+ *     // is full then this task will block for xTicksToWait ticks.
+ *     cValueToPost = 'a';
+ *     xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait );
+ *     cValueToPost = 'b';
+ *     xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait );
+ *
+ *     // ... keep posting characters ... this task may block when the queue
+ *     // becomes full.
+ *
+ *     cValueToPost = 'c';
+ *     xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait );
+ *  }
+ *
+ *  // ISR that outputs all the characters received on the queue.
+ *  void vISR_Routine( void )
+ *  {
+ *  BaseType_t xTaskWokenByReceive = pdFALSE;
+ *  char cRxedChar;
+ *
+ *     while( xQueueReceiveFromISR( xQueue, ( void * ) &cRxedChar, &xTaskWokenByReceive) )
+ *     {
+ *             // A character was received.  Output the character now.
+ *             vOutputCharacter( cRxedChar );
+ *
+ *             // If removing the character from the queue woke the task that was
+ *             // posting onto the queue cTaskWokenByReceive will have been set to
+ *             // pdTRUE.  No matter how many times this loop iterates only one
+ *             // task will be woken.
+ *     }
+ *
+ *     if( cTaskWokenByPost != ( char ) pdFALSE;
+ *     {
+ *             taskYIELD ();
+ *     }
+ *  }
+ * @endcode
+ * \ingroup QueueManagement
+ */
+BaseType_t xQueueReceiveFromISR( QueueHandle_t xQueue, void * const pvBuffer, BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;
+
+/**@{*/
+/**
+ * Utilities to query queues that are safe to use from an ISR.  These utilities
+ * should be used only from witin an ISR, or within a critical section.
+ */
+BaseType_t xQueueIsQueueEmptyFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
+BaseType_t xQueueIsQueueFullFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
+UBaseType_t uxQueueMessagesWaitingFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
+/**@}*/
+
+/** @cond */
+/**
+ * xQueueAltGenericSend() is an alternative version of xQueueGenericSend().
+ * Likewise xQueueAltGenericReceive() is an alternative version of
+ * xQueueGenericReceive().
+ *
+ * The source code that implements the alternative (Alt) API is much
+ * simpler     because it executes everything from within a critical section.
+ * This is     the approach taken by many other RTOSes, but FreeRTOS.org has the
+ * preferred fully featured API too.  The fully featured API has more
+ * complex     code that takes longer to execute, but makes much less use of
+ * critical sections.  Therefore the alternative API sacrifices interrupt
+ * responsiveness to gain execution speed, whereas the fully featured API
+ * sacrifices execution speed to ensure better interrupt responsiveness.
+ */
+BaseType_t xQueueAltGenericSend( QueueHandle_t xQueue, const void * const pvItemToQueue, TickType_t xTicksToWait, BaseType_t xCopyPosition );
+BaseType_t xQueueAltGenericReceive( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait, BaseType_t xJustPeeking );
+#define xQueueAltSendToFront( xQueue, pvItemToQueue, xTicksToWait ) xQueueAltGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_FRONT )
+#define xQueueAltSendToBack( xQueue, pvItemToQueue, xTicksToWait ) xQueueAltGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_BACK )
+#define xQueueAltReceive( xQueue, pvBuffer, xTicksToWait ) xQueueAltGenericReceive( ( xQueue ), ( pvBuffer ), ( xTicksToWait ), pdFALSE )
+#define xQueueAltPeek( xQueue, pvBuffer, xTicksToWait ) xQueueAltGenericReceive( ( xQueue ), ( pvBuffer ), ( xTicksToWait ), pdTRUE )
+
+/*
+ * The functions defined above are for passing data to and from tasks.  The
+ * functions below are the equivalents for passing data to and from
+ * co-routines.
+ *
+ * These functions are called from the co-routine macro implementation and
+ * should not be called directly from application code.  Instead use the macro
+ * wrappers defined within croutine.h.
+ */
+BaseType_t xQueueCRSendFromISR( QueueHandle_t xQueue, const void *pvItemToQueue, BaseType_t xCoRoutinePreviouslyWoken );
+BaseType_t xQueueCRReceiveFromISR( QueueHandle_t xQueue, void *pvBuffer, BaseType_t *pxTaskWoken );
+BaseType_t xQueueCRSend( QueueHandle_t xQueue, const void *pvItemToQueue, TickType_t xTicksToWait );
+BaseType_t xQueueCRReceive( QueueHandle_t xQueue, void *pvBuffer, TickType_t xTicksToWait );
+
+/*
+ * For internal use only.  Use xSemaphoreCreateMutex(),
+ * xSemaphoreCreateCounting() or xSemaphoreGetMutexHolder() instead of calling
+ * these functions directly.
+ */
+QueueHandle_t xQueueCreateMutex( const uint8_t ucQueueType ) PRIVILEGED_FUNCTION;
+QueueHandle_t xQueueCreateMutexStatic( const uint8_t ucQueueType, StaticQueue_t *pxStaticQueue ) PRIVILEGED_FUNCTION;
+QueueHandle_t xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount ) PRIVILEGED_FUNCTION;
+QueueHandle_t xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount, StaticQueue_t *pxStaticQueue ) PRIVILEGED_FUNCTION;
+void* xQueueGetMutexHolder( QueueHandle_t xSemaphore ) PRIVILEGED_FUNCTION;
+
+/*
+ * For internal use only.  Use xSemaphoreTakeMutexRecursive() or
+ * xSemaphoreGiveMutexRecursive() instead of calling these functions directly.
+ */
+BaseType_t xQueueTakeMutexRecursive( QueueHandle_t xMutex, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+BaseType_t xQueueGiveMutexRecursive( QueueHandle_t pxMutex ) PRIVILEGED_FUNCTION;
+/** @endcond */
+
+/**
+ * Reset a queue back to its original empty state.  pdPASS is returned if the
+ * queue is successfully reset.  pdFAIL is returned if the queue could not be
+ * reset because there are tasks blocked on the queue waiting to either
+ * receive from the queue or send to the queue.
+ *
+ * @param xQueue The queue to reset
+ * @return always returns pdPASS
+ */
+#define xQueueReset( xQueue ) xQueueGenericReset( xQueue, pdFALSE )
+
+/**
+ * The registry is provided as a means for kernel aware debuggers to
+ * locate queues, semaphores and mutexes.  Call vQueueAddToRegistry() add
+ * a queue, semaphore or mutex handle to the registry if you want the handle
+ * to be available to a kernel aware debugger.  If you are not using a kernel
+ * aware debugger then this function can be ignored.
+ *
+ * configQUEUE_REGISTRY_SIZE defines the maximum number of handles the
+ * registry can hold.  configQUEUE_REGISTRY_SIZE must be greater than 0
+ * within FreeRTOSConfig.h for the registry to be available.  Its value
+ * does not effect the number of queues, semaphores and mutexes that can be
+ * created - just the number that the registry can hold.
+ *
+ * @param xQueue The handle of the queue being added to the registry.  This
+ * is the handle returned by a call to xQueueCreate().  Semaphore and mutex
+ * handles can also be passed in here.
+ *
+ * @param pcName The name to be associated with the handle.  This is the
+ * name that the kernel aware debugger will display.  The queue registry only
+ * stores a pointer to the string - so the string must be persistent (global or
+ * preferably in ROM/Flash), not on the stack.
+ */
+#if configQUEUE_REGISTRY_SIZE > 0
+       void vQueueAddToRegistry( QueueHandle_t xQueue, const char *pcName ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+#endif
+
+/**
+ * The registry is provided as a means for kernel aware debuggers to
+ * locate queues, semaphores and mutexes.  Call vQueueAddToRegistry() add
+ * a queue, semaphore or mutex handle to the registry if you want the handle
+ * to be available to a kernel aware debugger, and vQueueUnregisterQueue() to
+ * remove the queue, semaphore or mutex from the register.  If you are not using
+ * a kernel aware debugger then this function can be ignored.
+ *
+ * @param xQueue The handle of the queue being removed from the registry.
+ */
+#if configQUEUE_REGISTRY_SIZE > 0
+       void vQueueUnregisterQueue( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
+#endif
+
+/**
+ * @note This function has been back ported from FreeRTOS v9.0.0
+ *
+ * The queue registry is provided as a means for kernel aware debuggers to
+ * locate queues, semaphores and mutexes.  Call pcQueueGetName() to look
+ * up and return the name of a queue in the queue registry from the queue's
+ * handle.
+ *
+ * @param xQueue The handle of the queue the name of which will be returned.
+ * @return If the queue is in the registry then a pointer to the name of the
+ * queue is returned.  If the queue is not in the registry then NULL is
+ * returned.
+ */
+#if( configQUEUE_REGISTRY_SIZE > 0 )
+       const char *pcQueueGetName( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+#endif
+
+/**
+ * Generic version of the function used to creaet a queue using dynamic memory
+ * allocation.  This is called by other functions and macros that create other
+ * RTOS objects that use the queue structure as their base.
+ */
+#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
+       QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, const uint8_t ucQueueType ) PRIVILEGED_FUNCTION;
+#endif
+
+/**
+ * Generic version of the function used to creaet a queue using dynamic memory
+ * allocation.  This is called by other functions and macros that create other
+ * RTOS objects that use the queue structure as their base.
+ */
+#if( configSUPPORT_STATIC_ALLOCATION == 1 )
+       QueueHandle_t xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, StaticQueue_t *pxStaticQueue, const uint8_t ucQueueType ) PRIVILEGED_FUNCTION;
+#endif
+
+/**
+ * Queue sets provide a mechanism to allow a task to block (pend) on a read
+ * operation from multiple queues or semaphores simultaneously.
+ *
+ * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this
+ * function.
+ *
+ * A queue set must be explicitly created using a call to xQueueCreateSet()
+ * before it can be used.  Once created, standard FreeRTOS queues and semaphores
+ * can be added to the set using calls to xQueueAddToSet().
+ * xQueueSelectFromSet() is then used to determine which, if any, of the queues
+ * or semaphores contained in the set is in a state where a queue read or
+ * semaphore take operation would be successful.
+ *
+ * Note 1:  See the documentation on http://wwwFreeRTOS.org/RTOS-queue-sets.html
+ * for reasons why queue sets are very rarely needed in practice as there are
+ * simpler methods of blocking on multiple objects.
+ *
+ * Note 2:  Blocking on a queue set that contains a mutex will not cause the
+ * mutex holder to inherit the priority of the blocked task.
+ *
+ * Note 3:  An additional 4 bytes of RAM is required for each space in a every
+ * queue added to a queue set.  Therefore counting semaphores that have a high
+ * maximum count value should not be added to a queue set.
+ *
+ * Note 4:  A receive (in the case of a queue) or take (in the case of a
+ * semaphore) operation must not be performed on a member of a queue set unless
+ * a call to xQueueSelectFromSet() has first returned a handle to that set member.
+ *
+ * @param uxEventQueueLength Queue sets store events that occur on
+ * the queues and semaphores contained in the set.  uxEventQueueLength specifies
+ * the maximum number of events that can be queued at once.  To be absolutely
+ * certain that events are not lost uxEventQueueLength should be set to the
+ * total sum of the length of the queues added to the set, where binary
+ * semaphores and mutexes have a length of 1, and counting semaphores have a
+ * length set by their maximum count value.  Examples:
+ *  + If a queue set is to hold a queue of length 5, another queue of length 12,
+ *    and a binary semaphore, then uxEventQueueLength should be set to
+ *    (5 + 12 + 1), or 18.
+ *  + If a queue set is to hold three binary semaphores then uxEventQueueLength
+ *    should be set to (1 + 1 + 1 ), or 3.
+ *  + If a queue set is to hold a counting semaphore that has a maximum count of
+ *    5, and a counting semaphore that has a maximum count of 3, then
+ *    uxEventQueueLength should be set to (5 + 3), or 8.
+ *
+ * @return If the queue set is created successfully then a handle to the created
+ * queue set is returned.  Otherwise NULL is returned.
+ */
+QueueSetHandle_t xQueueCreateSet( const UBaseType_t uxEventQueueLength ) PRIVILEGED_FUNCTION;
+
+/**
+ * Adds a queue or semaphore to a queue set that was previously created by a
+ * call to xQueueCreateSet().
+ *
+ * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this
+ * function.
+ *
+ * Note 1:  A receive (in the case of a queue) or take (in the case of a
+ * semaphore) operation must not be performed on a member of a queue set unless
+ * a call to xQueueSelectFromSet() has first returned a handle to that set member.
+ *
+ * @param xQueueOrSemaphore The handle of the queue or semaphore being added to
+ * the queue set (cast to an QueueSetMemberHandle_t type).
+ *
+ * @param xQueueSet The handle of the queue set to which the queue or semaphore
+ * is being added.
+ *
+ * @return If the queue or semaphore was successfully added to the queue set
+ * then pdPASS is returned.  If the queue could not be successfully added to the
+ * queue set because it is already a member of a different queue set then pdFAIL
+ * is returned.
+ */
+BaseType_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION;
+
+/**
+ * Removes a queue or semaphore from a queue set.  A queue or semaphore can only
+ * be removed from a set if the queue or semaphore is empty.
+ *
+ * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this
+ * function.
+ *
+ * @param xQueueOrSemaphore The handle of the queue or semaphore being removed
+ * from the queue set (cast to an QueueSetMemberHandle_t type).
+ *
+ * @param xQueueSet The handle of the queue set in which the queue or semaphore
+ * is included.
+ *
+ * @return If the queue or semaphore was successfully removed from the queue set
+ * then pdPASS is returned.  If the queue was not in the queue set, or the
+ * queue (or semaphore) was not empty, then pdFAIL is returned.
+ */
+BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION;
+
+/**
+ * xQueueSelectFromSet() selects from the members of a queue set a queue or
+ * semaphore that either contains data (in the case of a queue) or is available
+ * to take (in the case of a semaphore).  xQueueSelectFromSet() effectively
+ * allows a task to block (pend) on a read operation on all the queues and
+ * semaphores in a queue set simultaneously.
+ *
+ * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this
+ * function.
+ *
+ * Note 1:  See the documentation on http://wwwFreeRTOS.org/RTOS-queue-sets.html
+ * for reasons why queue sets are very rarely needed in practice as there are
+ * simpler methods of blocking on multiple objects.
+ *
+ * Note 2:  Blocking on a queue set that contains a mutex will not cause the
+ * mutex holder to inherit the priority of the blocked task.
+ *
+ * Note 3:  A receive (in the case of a queue) or take (in the case of a
+ * semaphore) operation must not be performed on a member of a queue set unless
+ * a call to xQueueSelectFromSet() has first returned a handle to that set member.
+ *
+ * @param xQueueSet The queue set on which the task will (potentially) block.
+ *
+ * @param xTicksToWait The maximum time, in ticks, that the calling task will
+ * remain in the Blocked state (with other tasks executing) to wait for a member
+ * of the queue set to be ready for a successful queue read or semaphore take
+ * operation.
+ *
+ * @return xQueueSelectFromSet() will return the handle of a queue (cast to
+ * a QueueSetMemberHandle_t type) contained in the queue set that contains data,
+ * or the handle of a semaphore (cast to a QueueSetMemberHandle_t type) contained
+ * in the queue set that is available, or NULL if no such queue or semaphore
+ * exists before before the specified block time expires.
+ */
+QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+
+/**
+ * A version of xQueueSelectFromSet() that can be used from an ISR.
+ */
+QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION;
+
+/** @cond */
+/* Not public API functions. */
+void vQueueWaitForMessageRestricted( QueueHandle_t xQueue, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+BaseType_t xQueueGenericReset( QueueHandle_t xQueue, BaseType_t xNewQueue ) PRIVILEGED_FUNCTION;
+void vQueueSetQueueNumber( QueueHandle_t xQueue, UBaseType_t uxQueueNumber ) PRIVILEGED_FUNCTION;
+UBaseType_t uxQueueGetQueueNumber( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
+uint8_t ucQueueGetQueueType( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
+/** @endcond */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* QUEUE_H */
+
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/private_include/web_esp_transport_ssl_internal.h b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/private_include/web_esp_transport_ssl_internal.h
new file mode 100644 (file)
index 0000000..5fd818a
--- /dev/null
@@ -0,0 +1,30 @@
+// Copyright 2015-2019 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef _WEB_ESP_TRANSPORT_INTERNAL_H_
+#define _WEB_ESP_TRANSPORT_INTERNAL_H_
+
+/**
+ * @brief      Sets error to common transport handle
+ *
+ *             Note: This function copies the supplied error handle object to tcp_transport's internal
+ *             error handle object
+ *
+ * @param[in]  A transport handle
+ *
+ */
+void wb_esp_transport_set_errors(wb_esp_transport_handle_t t, const wb_esp_tls_error_handle_t error_handle);
+
+
+#endif /* _ESP_TRANSPORT_INTERNAL_H_ */
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/private_include/web_esp_transport_utils.h b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/private_include/web_esp_transport_utils.h
new file mode 100644 (file)
index 0000000..814ca97
--- /dev/null
@@ -0,0 +1,44 @@
+// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef _ESP_TRANSPORT_UTILS_H_
+#define _ESP_TRANSPORT_UTILS_H_
+#include <sys/time.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @brief      Utility macro to be used for NULL ptr check after malloc
+ *
+ */
+#define ESP_TRANSPORT_MEM_CHECK(a, action) if (!(a)) {                                         \
+        ESP_LOGE("%s:%d (%s): %s", __FILE__, __LINE__, __FUNCTION__, "Memory exhausted");       \
+        action;                                                                                     \
+        }
+
+/**
+ * @brief      Convert milliseconds to timeval struct
+ *
+ * @param[in]  timeout_ms  The timeout milliseconds
+ * @param[out] tv          Timeval struct
+ */
+void wb_esp_transport_utils_ms_to_timeval(int timeout_ms, struct timeval *tv);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* _ESP_TRANSPORT_UTILS_H_ */
\ No newline at end of file
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/queue.h b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/queue.h
new file mode 100644 (file)
index 0000000..925094f
--- /dev/null
@@ -0,0 +1,691 @@
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 4. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ *     @(#)queue.h     8.5 (Berkeley) 8/20/94
+ * $FreeBSD$
+ */
+
+#ifndef _SYS_QUEUE_H_
+#define        _SYS_QUEUE_H_
+
+//#include <sys/cdefs.h>
+
+/*
+ * This file defines four types of data structures: singly-linked lists,
+ * singly-linked tail queues, lists and tail queues.
+ *
+ * A singly-linked list is headed by a single forward pointer. The elements
+ * are singly linked for minimum space and pointer manipulation overhead at
+ * the expense of O(n) removal for arbitrary elements. New elements can be
+ * added to the list after an existing element or at the head of the list.
+ * Elements being removed from the head of the list should use the explicit
+ * macro for this purpose for optimum efficiency. A singly-linked list may
+ * only be traversed in the forward direction.  Singly-linked lists are ideal
+ * for applications with large datasets and few or no removals or for
+ * implementing a LIFO queue.
+ *
+ * A singly-linked tail queue is headed by a pair of pointers, one to the
+ * head of the list and the other to the tail of the list. The elements are
+ * singly linked for minimum space and pointer manipulation overhead at the
+ * expense of O(n) removal for arbitrary elements. New elements can be added
+ * to the list after an existing element, at the head of the list, or at the
+ * end of the list. Elements being removed from the head of the tail queue
+ * should use the explicit macro for this purpose for optimum efficiency.
+ * A singly-linked tail queue may only be traversed in the forward direction.
+ * Singly-linked tail queues are ideal for applications with large datasets
+ * and few or no removals or for implementing a FIFO queue.
+ *
+ * A list is headed by a single forward pointer (or an array of forward
+ * pointers for a hash table header). The elements are doubly linked
+ * so that an arbitrary element can be removed without a need to
+ * traverse the list. New elements can be added to the list before
+ * or after an existing element or at the head of the list. A list
+ * may be traversed in either direction.
+ *
+ * A tail queue is headed by a pair of pointers, one to the head of the
+ * list and the other to the tail of the list. The elements are doubly
+ * linked so that an arbitrary element can be removed without a need to
+ * traverse the list. New elements can be added to the list before or
+ * after an existing element, at the head of the list, or at the end of
+ * the list. A tail queue may be traversed in either direction.
+ *
+ * For details on the use of these macros, see the queue(3) manual page.
+ *
+ *
+ *                             SLIST   LIST    STAILQ  TAILQ
+ * _HEAD                       +       +       +       +
+ * _HEAD_INITIALIZER           +       +       +       +
+ * _ENTRY                      +       +       +       +
+ * _INIT                       +       +       +       +
+ * _EMPTY                      +       +       +       +
+ * _FIRST                      +       +       +       +
+ * _NEXT                       +       +       +       +
+ * _PREV                       -       +       -       +
+ * _LAST                       -       -       +       +
+ * _FOREACH                    +       +       +       +
+ * _FOREACH_SAFE               +       +       +       +
+ * _FOREACH_REVERSE            -       -       -       +
+ * _FOREACH_REVERSE_SAFE       -       -       -       +
+ * _INSERT_HEAD                        +       +       +       +
+ * _INSERT_BEFORE              -       +       -       +
+ * _INSERT_AFTER               +       +       +       +
+ * _INSERT_TAIL                        -       -       +       +
+ * _CONCAT                     -       -       +       +
+ * _REMOVE_AFTER               +       -       +       -
+ * _REMOVE_HEAD                        +       -       +       -
+ * _REMOVE                     +       +       +       +
+ * _SWAP                       +       +       +       +
+ *
+ */
+#ifdef QUEUE_MACRO_DEBUG
+/* Store the last 2 places the queue element or head was altered */
+struct qm_trace {
+       unsigned long    lastline;
+       unsigned long    prevline;
+       const char      *lastfile;
+       const char      *prevfile;
+};
+
+#define        TRACEBUF        struct qm_trace trace;
+#define        TRACEBUF_INITIALIZER    { __FILE__, __LINE__, NULL, 0 } ,
+#define        TRASHIT(x)      do {(x) = (void *)-1;} while (0)
+#define        QMD_SAVELINK(name, link)        void **name = (void *)&(link)
+
+#define        QMD_TRACE_HEAD(head) do {                                       \
+       (head)->trace.prevline = (head)->trace.lastline;                \
+       (head)->trace.prevfile = (head)->trace.lastfile;                \
+       (head)->trace.lastline = __LINE__;                              \
+       (head)->trace.lastfile = __FILE__;                              \
+} while (0)
+
+#define        QMD_TRACE_ELEM(elem) do {                                       \
+       (elem)->trace.prevline = (elem)->trace.lastline;                \
+       (elem)->trace.prevfile = (elem)->trace.lastfile;                \
+       (elem)->trace.lastline = __LINE__;                              \
+       (elem)->trace.lastfile = __FILE__;                              \
+} while (0)
+
+#else
+#define        QMD_TRACE_ELEM(elem)
+#define        QMD_TRACE_HEAD(head)
+#define        QMD_SAVELINK(name, link)
+#define        TRACEBUF
+#define        TRACEBUF_INITIALIZER
+#define        TRASHIT(x)
+#endif /* QUEUE_MACRO_DEBUG */
+
+/*
+ * Singly-linked List declarations.
+ */
+#define        SLIST_HEAD(name, type)                                          \
+struct name {                                                          \
+       struct type *slh_first; /* first element */                     \
+}
+
+#define        SLIST_HEAD_INITIALIZER(head)                                    \
+       { NULL }
+
+#define        SLIST_ENTRY(type)                                               \
+struct {                                                               \
+       struct type *sle_next;  /* next element */                      \
+}
+
+/*
+ * Singly-linked List functions.
+ */
+#define        SLIST_EMPTY(head)       ((head)->slh_first == NULL)
+
+#define        SLIST_FIRST(head)       ((head)->slh_first)
+
+#define        SLIST_FOREACH(var, head, field)                                 \
+       for ((var) = SLIST_FIRST((head));                               \
+           (var);                                                      \
+           (var) = SLIST_NEXT((var), field))
+
+#define        SLIST_FOREACH_SAFE(var, head, field, tvar)                      \
+       for ((var) = SLIST_FIRST((head));                               \
+           (var) && ((tvar) = SLIST_NEXT((var), field), 1);            \
+           (var) = (tvar))
+
+#define        SLIST_FOREACH_PREVPTR(var, varp, head, field)                   \
+       for ((varp) = &SLIST_FIRST((head));                             \
+           ((var) = *(varp)) != NULL;                                  \
+           (varp) = &SLIST_NEXT((var), field))
+
+#define        SLIST_INIT(head) do {                                           \
+       SLIST_FIRST((head)) = NULL;                                     \
+} while (0)
+
+#define        SLIST_INSERT_AFTER(slistelm, elm, field) do {                   \
+       SLIST_NEXT((elm), field) = SLIST_NEXT((slistelm), field);       \
+       SLIST_NEXT((slistelm), field) = (elm);                          \
+} while (0)
+
+#define        SLIST_INSERT_HEAD(head, elm, field) do {                        \
+       SLIST_NEXT((elm), field) = SLIST_FIRST((head));                 \
+       SLIST_FIRST((head)) = (elm);                                    \
+} while (0)
+
+#define        SLIST_NEXT(elm, field)  ((elm)->field.sle_next)
+
+#define        SLIST_REMOVE(head, elm, type, field) do {                       \
+       QMD_SAVELINK(oldnext, (elm)->field.sle_next);                   \
+       if (SLIST_FIRST((head)) == (elm)) {                             \
+               SLIST_REMOVE_HEAD((head), field);                       \
+       }                                                               \
+       else {                                                          \
+               struct type *curelm = SLIST_FIRST((head));              \
+               while (SLIST_NEXT(curelm, field) != (elm))              \
+                       curelm = SLIST_NEXT(curelm, field);             \
+               SLIST_REMOVE_AFTER(curelm, field);                      \
+       }                                                               \
+       TRASHIT(*oldnext);                                              \
+} while (0)
+
+#define SLIST_REMOVE_AFTER(elm, field) do {                            \
+       SLIST_NEXT(elm, field) =                                        \
+           SLIST_NEXT(SLIST_NEXT(elm, field), field);                  \
+} while (0)
+
+#define        SLIST_REMOVE_HEAD(head, field) do {                             \
+       SLIST_FIRST((head)) = SLIST_NEXT(SLIST_FIRST((head)), field);   \
+} while (0)
+
+#define SLIST_SWAP(head1, head2, type) do {                            \
+       struct type *swap_first = SLIST_FIRST(head1);                   \
+       SLIST_FIRST(head1) = SLIST_FIRST(head2);                        \
+       SLIST_FIRST(head2) = swap_first;                                \
+} while (0)
+
+/*
+ * Singly-linked Tail queue declarations.
+ */
+#define        STAILQ_HEAD(name, type)                                         \
+struct name {                                                          \
+       struct type *stqh_first;/* first element */                     \
+       struct type **stqh_last;/* addr of last next element */         \
+}
+
+#define        STAILQ_HEAD_INITIALIZER(head)                                   \
+       { NULL, &(head).stqh_first }
+
+#define        STAILQ_ENTRY(type)                                              \
+struct {                                                               \
+       struct type *stqe_next; /* next element */                      \
+}
+
+/*
+ * Singly-linked Tail queue functions.
+ */
+#define        STAILQ_CONCAT(head1, head2) do {                                \
+       if (!STAILQ_EMPTY((head2))) {                                   \
+               *(head1)->stqh_last = (head2)->stqh_first;              \
+               (head1)->stqh_last = (head2)->stqh_last;                \
+               STAILQ_INIT((head2));                                   \
+       }                                                               \
+} while (0)
+
+#define        STAILQ_EMPTY(head)      ((head)->stqh_first == NULL)
+
+#define        STAILQ_FIRST(head)      ((head)->stqh_first)
+
+#define        STAILQ_FOREACH(var, head, field)                                \
+       for((var) = STAILQ_FIRST((head));                               \
+          (var);                                                       \
+          (var) = STAILQ_NEXT((var), field))
+
+
+#define        STAILQ_FOREACH_SAFE(var, head, field, tvar)                     \
+       for ((var) = STAILQ_FIRST((head));                              \
+           (var) && ((tvar) = STAILQ_NEXT((var), field), 1);           \
+           (var) = (tvar))
+
+#define        STAILQ_INIT(head) do {                                          \
+       STAILQ_FIRST((head)) = NULL;                                    \
+       (head)->stqh_last = &STAILQ_FIRST((head));                      \
+} while (0)
+
+#define        STAILQ_INSERT_AFTER(head, tqelm, elm, field) do {               \
+       if ((STAILQ_NEXT((elm), field) = STAILQ_NEXT((tqelm), field)) == NULL)\
+               (head)->stqh_last = &STAILQ_NEXT((elm), field);         \
+       STAILQ_NEXT((tqelm), field) = (elm);                            \
+} while (0)
+
+#define        STAILQ_INSERT_HEAD(head, elm, field) do {                       \
+       if ((STAILQ_NEXT((elm), field) = STAILQ_FIRST((head))) == NULL) \
+               (head)->stqh_last = &STAILQ_NEXT((elm), field);         \
+       STAILQ_FIRST((head)) = (elm);                                   \
+} while (0)
+
+#define        STAILQ_INSERT_TAIL(head, elm, field) do {                       \
+       STAILQ_NEXT((elm), field) = NULL;                               \
+       *(head)->stqh_last = (elm);                                     \
+       (head)->stqh_last = &STAILQ_NEXT((elm), field);                 \
+} while (0)
+
+#define        STAILQ_LAST(head, type, field)                                  \
+       (STAILQ_EMPTY((head)) ? NULL :                                  \
+           __containerof((head)->stqh_last, struct type, field.stqe_next))
+
+#define        STAILQ_NEXT(elm, field) ((elm)->field.stqe_next)
+
+#define        STAILQ_REMOVE(head, elm, type, field) do {                      \
+       QMD_SAVELINK(oldnext, (elm)->field.stqe_next);                  \
+       if (STAILQ_FIRST((head)) == (elm)) {                            \
+               STAILQ_REMOVE_HEAD((head), field);                      \
+       }                                                               \
+       else {                                                          \
+               struct type *curelm = STAILQ_FIRST((head));             \
+               while (STAILQ_NEXT(curelm, field) != (elm))             \
+                       curelm = STAILQ_NEXT(curelm, field);            \
+               STAILQ_REMOVE_AFTER(head, curelm, field);               \
+       }                                                               \
+       TRASHIT(*oldnext);                                              \
+} while (0)
+
+#define STAILQ_REMOVE_AFTER(head, elm, field) do {                     \
+       if ((STAILQ_NEXT(elm, field) =                                  \
+            STAILQ_NEXT(STAILQ_NEXT(elm, field), field)) == NULL)      \
+               (head)->stqh_last = &STAILQ_NEXT((elm), field);         \
+} while (0)
+
+#define        STAILQ_REMOVE_HEAD(head, field) do {                            \
+       if ((STAILQ_FIRST((head)) =                                     \
+            STAILQ_NEXT(STAILQ_FIRST((head)), field)) == NULL)         \
+               (head)->stqh_last = &STAILQ_FIRST((head));              \
+} while (0)
+
+#define        STAILQ_REMOVE_HEAD_UNTIL(head, elm, field) do {                 \
+       if ((STAILQ_FIRST((head)) = STAILQ_NEXT((elm), field)) == NULL) \
+               (head)->stqh_last = &STAILQ_FIRST((head));              \
+} while (0)
+
+#define STAILQ_SWAP(head1, head2, type) do {                           \
+       struct type *swap_first = STAILQ_FIRST(head1);                  \
+       struct type **swap_last = (head1)->stqh_last;                   \
+       STAILQ_FIRST(head1) = STAILQ_FIRST(head2);                      \
+       (head1)->stqh_last = (head2)->stqh_last;                        \
+       STAILQ_FIRST(head2) = swap_first;                               \
+       (head2)->stqh_last = swap_last;                                 \
+       if (STAILQ_EMPTY(head1))                                        \
+               (head1)->stqh_last = &STAILQ_FIRST(head1);              \
+       if (STAILQ_EMPTY(head2))                                        \
+               (head2)->stqh_last = &STAILQ_FIRST(head2);              \
+} while (0)
+
+
+/*
+ * List declarations.
+ */
+#define        LIST_HEAD(name, type)                                           \
+struct name {                                                          \
+       struct type *lh_first;  /* first element */                     \
+}
+
+#define        LIST_HEAD_INITIALIZER(head)                                     \
+       { NULL }
+
+#define        LIST_ENTRY(type)                                                \
+struct {                                                               \
+       struct type *le_next;   /* next element */                      \
+       struct type **le_prev;  /* address of previous next element */  \
+}
+
+/*
+ * List functions.
+ */
+
+#if (defined(_KERNEL) && defined(INVARIANTS))
+#define        QMD_LIST_CHECK_HEAD(head, field) do {                           \
+       if (LIST_FIRST((head)) != NULL &&                               \
+           LIST_FIRST((head))->field.le_prev !=                        \
+            &LIST_FIRST((head)))                                       \
+               panic("Bad list head %p first->prev != head", (head));  \
+} while (0)
+
+#define        QMD_LIST_CHECK_NEXT(elm, field) do {                            \
+       if (LIST_NEXT((elm), field) != NULL &&                          \
+           LIST_NEXT((elm), field)->field.le_prev !=                   \
+            &((elm)->field.le_next))                                   \
+               panic("Bad link elm %p next->prev != elm", (elm));      \
+} while (0)
+
+#define        QMD_LIST_CHECK_PREV(elm, field) do {                            \
+       if (*(elm)->field.le_prev != (elm))                             \
+               panic("Bad link elm %p prev->next != elm", (elm));      \
+} while (0)
+#else
+#define        QMD_LIST_CHECK_HEAD(head, field)
+#define        QMD_LIST_CHECK_NEXT(elm, field)
+#define        QMD_LIST_CHECK_PREV(elm, field)
+#endif /* (_KERNEL && INVARIANTS) */
+
+#define        LIST_EMPTY(head)        ((head)->lh_first == NULL)
+
+#define        LIST_FIRST(head)        ((head)->lh_first)
+
+#define        LIST_FOREACH(var, head, field)                                  \
+       for ((var) = LIST_FIRST((head));                                \
+           (var);                                                      \
+           (var) = LIST_NEXT((var), field))
+
+#define        LIST_FOREACH_SAFE(var, head, field, tvar)                       \
+       for ((var) = LIST_FIRST((head));                                \
+           (var) && ((tvar) = LIST_NEXT((var), field), 1);             \
+           (var) = (tvar))
+
+#define        LIST_INIT(head) do {                                            \
+       LIST_FIRST((head)) = NULL;                                      \
+} while (0)
+
+#define        LIST_INSERT_AFTER(listelm, elm, field) do {                     \
+       QMD_LIST_CHECK_NEXT(listelm, field);                            \
+       if ((LIST_NEXT((elm), field) = LIST_NEXT((listelm), field)) != NULL)\
+               LIST_NEXT((listelm), field)->field.le_prev =            \
+                   &LIST_NEXT((elm), field);                           \
+       LIST_NEXT((listelm), field) = (elm);                            \
+       (elm)->field.le_prev = &LIST_NEXT((listelm), field);            \
+} while (0)
+
+#define        LIST_INSERT_BEFORE(listelm, elm, field) do {                    \
+       QMD_LIST_CHECK_PREV(listelm, field);                            \
+       (elm)->field.le_prev = (listelm)->field.le_prev;                \
+       LIST_NEXT((elm), field) = (listelm);                            \
+       *(listelm)->field.le_prev = (elm);                              \
+       (listelm)->field.le_prev = &LIST_NEXT((elm), field);            \
+} while (0)
+
+#define        LIST_INSERT_HEAD(head, elm, field) do {                         \
+       QMD_LIST_CHECK_HEAD((head), field);                             \
+       if ((LIST_NEXT((elm), field) = LIST_FIRST((head))) != NULL)     \
+               LIST_FIRST((head))->field.le_prev = &LIST_NEXT((elm), field);\
+       LIST_FIRST((head)) = (elm);                                     \
+       (elm)->field.le_prev = &LIST_FIRST((head));                     \
+} while (0)
+
+#define        LIST_NEXT(elm, field)   ((elm)->field.le_next)
+
+#define        LIST_PREV(elm, head, type, field)                               \
+       ((elm)->field.le_prev == &LIST_FIRST((head)) ? NULL :           \
+           __containerof((elm)->field.le_prev, struct type, field.le_next))
+
+#define        LIST_REMOVE(elm, field) do {                                    \
+       QMD_SAVELINK(oldnext, (elm)->field.le_next);                    \
+       QMD_SAVELINK(oldprev, (elm)->field.le_prev);                    \
+       QMD_LIST_CHECK_NEXT(elm, field);                                \
+       QMD_LIST_CHECK_PREV(elm, field);                                \
+       if (LIST_NEXT((elm), field) != NULL)                            \
+               LIST_NEXT((elm), field)->field.le_prev =                \
+                   (elm)->field.le_prev;                               \
+       *(elm)->field.le_prev = LIST_NEXT((elm), field);                \
+       TRASHIT(*oldnext);                                              \
+       TRASHIT(*oldprev);                                              \
+} while (0)
+
+#define LIST_SWAP(head1, head2, type, field) do {                      \
+       struct type *swap_tmp = LIST_FIRST((head1));                    \
+       LIST_FIRST((head1)) = LIST_FIRST((head2));                      \
+       LIST_FIRST((head2)) = swap_tmp;                                 \
+       if ((swap_tmp = LIST_FIRST((head1))) != NULL)                   \
+               swap_tmp->field.le_prev = &LIST_FIRST((head1));         \
+       if ((swap_tmp = LIST_FIRST((head2))) != NULL)                   \
+               swap_tmp->field.le_prev = &LIST_FIRST((head2));         \
+} while (0)
+
+/*
+ * Tail queue declarations.
+ */
+#define        TAILQ_HEAD(name, type)                                          \
+struct name {                                                          \
+       struct type *tqh_first; /* first element */                     \
+       struct type **tqh_last; /* addr of last next element */         \
+       TRACEBUF                                                        \
+}
+
+#define        TAILQ_HEAD_INITIALIZER(head)                                    \
+       { NULL, &(head).tqh_first, TRACEBUF_INITIALIZER }
+
+#define        TAILQ_ENTRY(type)                                               \
+struct {                                                               \
+       struct type *tqe_next;  /* next element */                      \
+       struct type **tqe_prev; /* address of previous next element */  \
+       TRACEBUF                                                        \
+}
+
+/*
+ * Tail queue functions.
+ */
+#if (defined(_KERNEL) && defined(INVARIANTS))
+#define        QMD_TAILQ_CHECK_HEAD(head, field) do {                          \
+       if (!TAILQ_EMPTY(head) &&                                       \
+           TAILQ_FIRST((head))->field.tqe_prev !=                      \
+            &TAILQ_FIRST((head)))                                      \
+               panic("Bad tailq head %p first->prev != head", (head)); \
+} while (0)
+
+#define        QMD_TAILQ_CHECK_TAIL(head, field) do {                          \
+       if (*(head)->tqh_last != NULL)                                  \
+               panic("Bad tailq NEXT(%p->tqh_last) != NULL", (head));  \
+} while (0)
+
+#define        QMD_TAILQ_CHECK_NEXT(elm, field) do {                           \
+       if (TAILQ_NEXT((elm), field) != NULL &&                         \
+           TAILQ_NEXT((elm), field)->field.tqe_prev !=                 \
+            &((elm)->field.tqe_next))                                  \
+               panic("Bad link elm %p next->prev != elm", (elm));      \
+} while (0)
+
+#define        QMD_TAILQ_CHECK_PREV(elm, field) do {                           \
+       if (*(elm)->field.tqe_prev != (elm))                            \
+               panic("Bad link elm %p prev->next != elm", (elm));      \
+} while (0)
+#else
+#define        QMD_TAILQ_CHECK_HEAD(head, field)
+#define        QMD_TAILQ_CHECK_TAIL(head, headname)
+#define        QMD_TAILQ_CHECK_NEXT(elm, field)
+#define        QMD_TAILQ_CHECK_PREV(elm, field)
+#endif /* (_KERNEL && INVARIANTS) */
+
+#define        TAILQ_CONCAT(head1, head2, field) do {                          \
+       if (!TAILQ_EMPTY(head2)) {                                      \
+               *(head1)->tqh_last = (head2)->tqh_first;                \
+               (head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \
+               (head1)->tqh_last = (head2)->tqh_last;                  \
+               TAILQ_INIT((head2));                                    \
+               QMD_TRACE_HEAD(head1);                                  \
+               QMD_TRACE_HEAD(head2);                                  \
+       }                                                               \
+} while (0)
+
+#define        TAILQ_EMPTY(head)       ((head)->tqh_first == NULL)
+
+#define        TAILQ_FIRST(head)       ((head)->tqh_first)
+
+#define        TAILQ_FOREACH(var, head, field)                                 \
+       for ((var) = TAILQ_FIRST((head));                               \
+           (var);                                                      \
+           (var) = TAILQ_NEXT((var), field))
+
+#define        TAILQ_FOREACH_SAFE(var, head, field, tvar)                      \
+       for ((var) = TAILQ_FIRST((head));                               \
+           (var) && ((tvar) = TAILQ_NEXT((var), field), 1);            \
+           (var) = (tvar))
+
+#define        TAILQ_FOREACH_REVERSE(var, head, headname, field)               \
+       for ((var) = TAILQ_LAST((head), headname);                      \
+           (var);                                                      \
+           (var) = TAILQ_PREV((var), headname, field))
+
+#define        TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, tvar)    \
+       for ((var) = TAILQ_LAST((head), headname);                      \
+           (var) && ((tvar) = TAILQ_PREV((var), headname, field), 1);  \
+           (var) = (tvar))
+
+#define        TAILQ_INIT(head) do {                                           \
+       TAILQ_FIRST((head)) = NULL;                                     \
+       (head)->tqh_last = &TAILQ_FIRST((head));                        \
+       QMD_TRACE_HEAD(head);                                           \
+} while (0)
+
+#define        TAILQ_INSERT_AFTER(head, listelm, elm, field) do {              \
+       QMD_TAILQ_CHECK_NEXT(listelm, field);                           \
+       if ((TAILQ_NEXT((elm), field) = TAILQ_NEXT((listelm), field)) != NULL)\
+               TAILQ_NEXT((elm), field)->field.tqe_prev =              \
+                   &TAILQ_NEXT((elm), field);                          \
+       else {                                                          \
+               (head)->tqh_last = &TAILQ_NEXT((elm), field);           \
+               QMD_TRACE_HEAD(head);                                   \
+       }                                                               \
+       TAILQ_NEXT((listelm), field) = (elm);                           \
+       (elm)->field.tqe_prev = &TAILQ_NEXT((listelm), field);          \
+       QMD_TRACE_ELEM(&(elm)->field);                                  \
+       QMD_TRACE_ELEM(&listelm->field);                                \
+} while (0)
+
+#define        TAILQ_INSERT_BEFORE(listelm, elm, field) do {                   \
+       QMD_TAILQ_CHECK_PREV(listelm, field);                           \
+       (elm)->field.tqe_prev = (listelm)->field.tqe_prev;              \
+       TAILQ_NEXT((elm), field) = (listelm);                           \
+       *(listelm)->field.tqe_prev = (elm);                             \
+       (listelm)->field.tqe_prev = &TAILQ_NEXT((elm), field);          \
+       QMD_TRACE_ELEM(&(elm)->field);                                  \
+       QMD_TRACE_ELEM(&listelm->field);                                \
+} while (0)
+
+#define        TAILQ_INSERT_HEAD(head, elm, field) do {                        \
+       QMD_TAILQ_CHECK_HEAD(head, field);                              \
+       if ((TAILQ_NEXT((elm), field) = TAILQ_FIRST((head))) != NULL)   \
+               TAILQ_FIRST((head))->field.tqe_prev =                   \
+                   &TAILQ_NEXT((elm), field);                          \
+       else                                                            \
+               (head)->tqh_last = &TAILQ_NEXT((elm), field);           \
+       TAILQ_FIRST((head)) = (elm);                                    \
+       (elm)->field.tqe_prev = &TAILQ_FIRST((head));                   \
+       QMD_TRACE_HEAD(head);                                           \
+       QMD_TRACE_ELEM(&(elm)->field);                                  \
+} while (0)
+
+#define        TAILQ_INSERT_TAIL(head, elm, field) do {                        \
+       QMD_TAILQ_CHECK_TAIL(head, field);                              \
+       TAILQ_NEXT((elm), field) = NULL;                                \
+       (elm)->field.tqe_prev = (head)->tqh_last;                       \
+       *(head)->tqh_last = (elm);                                      \
+       (head)->tqh_last = &TAILQ_NEXT((elm), field);                   \
+       QMD_TRACE_HEAD(head);                                           \
+       QMD_TRACE_ELEM(&(elm)->field);                                  \
+} while (0)
+
+#define        TAILQ_LAST(head, headname)                                      \
+       (*(((struct headname *)((head)->tqh_last))->tqh_last))
+
+#define        TAILQ_NEXT(elm, field) ((elm)->field.tqe_next)
+
+#define        TAILQ_PREV(elm, headname, field)                                \
+       (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last))
+
+#define        TAILQ_REMOVE(head, elm, field) do {                             \
+       QMD_SAVELINK(oldnext, (elm)->field.tqe_next);                   \
+       QMD_SAVELINK(oldprev, (elm)->field.tqe_prev);                   \
+       QMD_TAILQ_CHECK_NEXT(elm, field);                               \
+       QMD_TAILQ_CHECK_PREV(elm, field);                               \
+       if ((TAILQ_NEXT((elm), field)) != NULL)                         \
+               TAILQ_NEXT((elm), field)->field.tqe_prev =              \
+                   (elm)->field.tqe_prev;                              \
+       else {                                                          \
+               (head)->tqh_last = (elm)->field.tqe_prev;               \
+               QMD_TRACE_HEAD(head);                                   \
+       }                                                               \
+       *(elm)->field.tqe_prev = TAILQ_NEXT((elm), field);              \
+       TRASHIT(*oldnext);                                              \
+       TRASHIT(*oldprev);                                              \
+       QMD_TRACE_ELEM(&(elm)->field);                                  \
+} while (0)
+
+#define TAILQ_SWAP(head1, head2, type, field) do {                     \
+       struct type *swap_first = (head1)->tqh_first;                   \
+       struct type **swap_last = (head1)->tqh_last;                    \
+       (head1)->tqh_first = (head2)->tqh_first;                        \
+       (head1)->tqh_last = (head2)->tqh_last;                          \
+       (head2)->tqh_first = swap_first;                                \
+       (head2)->tqh_last = swap_last;                                  \
+       if ((swap_first = (head1)->tqh_first) != NULL)                  \
+               swap_first->field.tqe_prev = &(head1)->tqh_first;       \
+       else                                                            \
+               (head1)->tqh_last = &(head1)->tqh_first;                \
+       if ((swap_first = (head2)->tqh_first) != NULL)                  \
+               swap_first->field.tqe_prev = &(head2)->tqh_first;       \
+       else                                                            \
+               (head2)->tqh_last = &(head2)->tqh_first;                \
+} while (0)
+
+#ifdef _KERNEL
+
+/*
+ * XXX insque() and remque() are an old way of handling certain queues.
+ * They bogusly assumes that all queue heads look alike.
+ */
+
+struct quehead {
+       struct quehead *qh_link;
+       struct quehead *qh_rlink;
+};
+
+#ifdef __GNUC__
+
+static __inline void
+insque(void *a, void *b)
+{
+       struct quehead *element = (struct quehead *)a,
+                *head = (struct quehead *)b;
+
+       element->qh_link = head->qh_link;
+       element->qh_rlink = head;
+       head->qh_link = element;
+       element->qh_link->qh_rlink = element;
+}
+
+static __inline void
+remque(void *a)
+{
+       struct quehead *element = (struct quehead *)a;
+
+       element->qh_link->qh_rlink = element->qh_rlink;
+       element->qh_rlink->qh_link = element->qh_link;
+       element->qh_rlink = 0;
+}
+
+#else /* !__GNUC__ */
+
+void   insque(void *a, void *b);
+void   remque(void *a);
+
+#endif /* __GNUC__ */
+
+#endif /* _KERNEL */
+
+#endif /* !_SYS_QUEUE_H_ */
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/semphr.h b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/semphr.h
new file mode 100644 (file)
index 0000000..b7ef7f8
--- /dev/null
@@ -0,0 +1,1052 @@
+#ifndef SEMAPHORE_H
+#define SEMAPHORE_H
+
+///#ifndef INC_FREERTOS_H
+       //#error "include FreeRTOS.h" must appear in source files before "include semphr.h"
+//#endif
+
+#include "queue.h"
+
+typedef QueueHandle_t SemaphoreHandle_t;
+
+#define semBINARY_SEMAPHORE_QUEUE_LENGTH       ( ( uint8_t ) 1U )
+#define semSEMAPHORE_QUEUE_ITEM_LENGTH         ( ( uint8_t ) 0U )
+#define semGIVE_BLOCK_TIME                                     ( ( TickType_t ) 0U )
+
+#define xSemaphoreCreateRecursiveMutex()                xQueueCreateMutex( queueQUEUE_TYPE_RECURSIVE_MUTEX )
+#define xSemaphoreTakeRecursive( xMutex, xBlockTime )  xQueueTakeMutexRecursive( ( xMutex ), ( xBlockTime ) )
+
+/** @cond */
+/**
+ * This old vSemaphoreCreateBinary() macro is now deprecated in favour of the
+ * xSemaphoreCreateBinary() function.  Note that binary semaphores created using
+ * the vSemaphoreCreateBinary() macro are created in a state such that the
+ * first call to 'take' the semaphore would pass, whereas binary semaphores
+ * created using xSemaphoreCreateBinary() are created in a state such that the
+ * the semaphore must first be 'given' before it can be 'taken'.
+ *
+ * <i>Macro</i> that implements a semaphore by using the existing queue mechanism.
+ * The queue length is 1 as this is a binary semaphore.  The data size is 0
+ * as we don't want to actually store any data - we just want to know if the
+ * queue is empty or full.
+ *
+ * This type of semaphore can be used for pure synchronisation between tasks or
+ * between an interrupt and a task.  The semaphore need not be given back once
+ * obtained, so one task/interrupt can continuously 'give' the semaphore while
+ * another continuously 'takes' the semaphore.  For this reason this type of
+ * semaphore does not use a priority inheritance mechanism.  For an alternative
+ * that does use priority inheritance see xSemaphoreCreateMutex().
+ *
+ * @param xSemaphore Handle to the created semaphore.  Should be of type SemaphoreHandle_t.
+ *
+ * Example usage:
+ * @code{c}
+ *  SemaphoreHandle_t xSemaphore = NULL;
+ *
+ *  void vATask( void * pvParameters )
+ *  {
+ *     // Semaphore cannot be used before a call to vSemaphoreCreateBinary ().
+ *     // This is a macro so pass the variable in directly.
+ *     vSemaphoreCreateBinary( xSemaphore );
+ *
+ *     if( xSemaphore != NULL )
+ *     {
+ *         // The semaphore was created successfully.
+ *         // The semaphore can now be used.
+ *     }
+ *  }
+ * @endcode
+ * \ingroup Semaphores
+ */
+#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
+       #define vSemaphoreCreateBinary( xSemaphore )                                                                                                                                                                                    \
+               {                                                                                                                                                                                                                                                                       \
+                       ( xSemaphore ) = xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE );    \
+                       if( ( xSemaphore ) != NULL )                                                                                                                                                                                                    \
+                       {                                                                                                                                                                                                                                                               \
+                               ( void ) xSemaphoreGive( ( xSemaphore ) );                                                                                                                                                                      \
+                       }                                                                                                                                                                                                                                                               \
+               }
+#endif
+/** @endcond */
+
+/**
+ * Creates a new binary semaphore instance, and returns a handle by which the
+ * new semaphore can be referenced.
+ *
+ * In many usage scenarios it is faster and more memory efficient to use a
+ * direct to task notification in place of a binary semaphore!
+ * http://www.freertos.org/RTOS-task-notifications.html
+ *
+ * Internally, within the FreeRTOS implementation, binary semaphores use a block
+ * of memory, in which the semaphore structure is stored.  If a binary semaphore
+ * is created using xSemaphoreCreateBinary() then the required memory is
+ * automatically dynamically allocated inside the xSemaphoreCreateBinary()
+ * function.  (see http://www.freertos.org/a00111.html).  If a binary semaphore
+ * is created using xSemaphoreCreateBinaryStatic() then the application writer
+ * must provide the memory.  xSemaphoreCreateBinaryStatic() therefore allows a
+ * binary semaphore to be created without using any dynamic memory allocation.
+ *
+ * The old vSemaphoreCreateBinary() macro is now deprecated in favour of this
+ * xSemaphoreCreateBinary() function.  Note that binary semaphores created using
+ * the vSemaphoreCreateBinary() macro are created in a state such that the
+ * first call to 'take' the semaphore would pass, whereas binary semaphores
+ * created using xSemaphoreCreateBinary() are created in a state such that the
+ * the semaphore must first be 'given' before it can be 'taken'.
+ *
+ * Function that creates a semaphore by using the existing queue mechanism.
+ * The queue length is 1 as this is a binary semaphore.  The data size is 0
+ * as nothing is actually stored - all that is important is whether the queue is
+ * empty or full (the binary semaphore is available or not).
+ *
+ * This type of semaphore can be used for pure synchronisation between tasks or
+ * between an interrupt and a task.  The semaphore need not be given back once
+ * obtained, so one task/interrupt can continuously 'give' the semaphore while
+ * another continuously 'takes' the semaphore.  For this reason this type of
+ * semaphore does not use a priority inheritance mechanism.  For an alternative
+ * that does use priority inheritance see xSemaphoreCreateMutex().
+ *
+ * @return Handle to the created semaphore.
+ *
+ * Example usage:
+ * @code{c}
+ *  SemaphoreHandle_t xSemaphore = NULL;
+ *
+ *  void vATask( void * pvParameters )
+ *  {
+ *     // Semaphore cannot be used before a call to vSemaphoreCreateBinary ().
+ *     // This is a macro so pass the variable in directly.
+ *     xSemaphore = xSemaphoreCreateBinary();
+ *
+ *     if( xSemaphore != NULL )
+ *     {
+ *         // The semaphore was created successfully.
+ *         // The semaphore can now be used.
+ *     }
+ *  }
+ * @endcode
+ * \ingroup Semaphores
+ */
+#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
+       #define xSemaphoreCreateBinary() xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE )
+#endif
+
+/**
+ * Creates a new binary semaphore instance, and returns a handle by which the
+ * new semaphore can be referenced.
+ *
+ * NOTE: In many usage scenarios it is faster and more memory efficient to use a
+ * direct to task notification in place of a binary semaphore!
+ * http://www.freertos.org/RTOS-task-notifications.html
+ *
+ * Internally, within the FreeRTOS implementation, binary semaphores use a block
+ * of memory, in which the semaphore structure is stored.  If a binary semaphore
+ * is created using xSemaphoreCreateBinary() then the required memory is
+ * automatically dynamically allocated inside the xSemaphoreCreateBinary()
+ * function.  (see http://www.freertos.org/a00111.html).  If a binary semaphore
+ * is created using xSemaphoreCreateBinaryStatic() then the application writer
+ * must provide the memory.  xSemaphoreCreateBinaryStatic() therefore allows a
+ * binary semaphore to be created without using any dynamic memory allocation.
+ *
+ * This type of semaphore can be used for pure synchronisation between tasks or
+ * between an interrupt and a task.  The semaphore need not be given back once
+ * obtained, so one task/interrupt can continuously 'give' the semaphore while
+ * another continuously 'takes' the semaphore.  For this reason this type of
+ * semaphore does not use a priority inheritance mechanism.  For an alternative
+ * that does use priority inheritance see xSemaphoreCreateMutex().
+ *
+ * @param pxStaticSemaphore Must point to a variable of type StaticSemaphore_t,
+ * which will then be used to hold the semaphore's data structure, removing the
+ * need for the memory to be allocated dynamically.
+ *
+ * @return If the semaphore is created then a handle to the created semaphore is
+ * returned.  If pxSemaphoreBuffer is NULL then NULL is returned.
+ *
+ * Example usage:
+ * @code{c}
+ *  SemaphoreHandle_t xSemaphore = NULL;
+ *  StaticSemaphore_t xSemaphoreBuffer;
+ *
+ *  void vATask( void * pvParameters )
+ *  {
+ *     // Semaphore cannot be used before a call to xSemaphoreCreateBinary().
+ *     // The semaphore's data structures will be placed in the xSemaphoreBuffer
+ *     // variable, the address of which is passed into the function.  The
+ *     // function's parameter is not NULL, so the function will not attempt any
+ *     // dynamic memory allocation, and therefore the function will not return
+ *     // return NULL.
+ *     xSemaphore = xSemaphoreCreateBinary( &xSemaphoreBuffer );
+ *
+ *     // Rest of task code goes here.
+ *  }
+ * @endcode
+ * \ingroup Semaphores
+ */
+#if( configSUPPORT_STATIC_ALLOCATION == 1 )
+       #define xSemaphoreCreateBinaryStatic( pxStaticSemaphore ) xQueueGenericCreateStatic( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticSemaphore, queueQUEUE_TYPE_BINARY_SEMAPHORE )
+#endif /* configSUPPORT_STATIC_ALLOCATION */
+
+/**
+ * <i>Macro</i> to obtain a semaphore.  The semaphore must have previously been
+ * created with a call to vSemaphoreCreateBinary(), xSemaphoreCreateMutex() or
+ * xSemaphoreCreateCounting().
+ *
+ * @param xSemaphore A handle to the semaphore being taken - obtained when
+ * the semaphore was created.
+ *
+ * @param xBlockTime The time in ticks to wait for the semaphore to become
+ * available.  The macro portTICK_PERIOD_MS can be used to convert this to a
+ * real time.  A block time of zero can be used to poll the semaphore.  A block
+ * time of portMAX_DELAY can be used to block indefinitely (provided
+ * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h).
+ *
+ * @return pdTRUE if the semaphore was obtained.  pdFALSE
+ * if xBlockTime expired without the semaphore becoming available.
+ *
+ * Example usage:
+ * @code{c}
+ *  SemaphoreHandle_t xSemaphore = NULL;
+ *
+ *  // A task that creates a semaphore.
+ *  void vATask( void * pvParameters )
+ *  {
+ *     // Create the semaphore to guard a shared resource.
+ *     vSemaphoreCreateBinary( xSemaphore );
+ *  }
+ *
+ *  // A task that uses the semaphore.
+ *  void vAnotherTask( void * pvParameters )
+ *  {
+ *     // ... Do other things.
+ *
+ *     if( xSemaphore != NULL )
+ *     {
+ *         // See if we can obtain the semaphore.  If the semaphore is not available
+ *         // wait 10 ticks to see if it becomes free.
+ *         if( xSemaphoreTake( xSemaphore, ( TickType_t ) 10 ) == pdTRUE )
+ *         {
+ *             // We were able to obtain the semaphore and can now access the
+ *             // shared resource.
+ *
+ *             // ...
+ *
+ *             // We have finished accessing the shared resource.  Release the
+ *             // semaphore.
+ *             xSemaphoreGive( xSemaphore );
+ *         }
+ *         else
+ *         {
+ *             // We could not obtain the semaphore and can therefore not access
+ *             // the shared resource safely.
+ *         }
+ *     }
+ *  }
+ * @endcode
+ * \ingroup Semaphores
+ */
+#define xSemaphoreTake( xSemaphore, xBlockTime )               xQueueGenericReceive( ( QueueHandle_t ) ( xSemaphore ), NULL, ( xBlockTime ), pdFALSE )
+
+/**
+ * <i>Macro</i> to recursively obtain, or 'take', a mutex type semaphore.
+ * The mutex must have previously been created using a call to
+ * xSemaphoreCreateRecursiveMutex();
+ *
+ * configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this
+ * macro to be available.
+ *
+ * This macro must not be used on mutexes created using xSemaphoreCreateMutex().
+ *
+ * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex
+ * doesn't become available again until the owner has called
+ * xSemaphoreGiveRecursive() for each successful 'take' request.  For example,
+ * if a task successfully 'takes' the same mutex 5 times then the mutex will
+ * not be available to any other task until it has also  'given' the mutex back
+ * exactly five times.
+ *
+ * @param xMutex A handle to the mutex being obtained.  This is the
+ * handle returned by xSemaphoreCreateRecursiveMutex();
+ *
+ * @param xBlockTime The time in ticks to wait for the semaphore to become
+ * available.  The macro portTICK_PERIOD_MS can be used to convert this to a
+ * real time.  A block time of zero can be used to poll the semaphore.  If
+ * the task already owns the semaphore then xSemaphoreTakeRecursive() will
+ * return immediately no matter what the value of xBlockTime.
+ *
+ * @return pdTRUE if the semaphore was obtained.  pdFALSE if xBlockTime
+ * expired without the semaphore becoming available.
+ *
+ * Example usage:
+ * @code{c}
+ *  SemaphoreHandle_t xMutex = NULL;
+ *
+ *  // A task that creates a mutex.
+ *  void vATask( void * pvParameters )
+ *  {
+ *     // Create the mutex to guard a shared resource.
+ *     xMutex = xSemaphoreCreateRecursiveMutex();
+ *  }
+ *
+ *  // A task that uses the mutex.
+ *  void vAnotherTask( void * pvParameters )
+ *  {
+ *     // ... Do other things.
+ *
+ *     if( xMutex != NULL )
+ *     {
+ *         // See if we can obtain the mutex.  If the mutex is not available
+ *         // wait 10 ticks to see if it becomes free.
+ *         if( xSemaphoreTakeRecursive( xSemaphore, ( TickType_t ) 10 ) == pdTRUE )
+ *         {
+ *             // We were able to obtain the mutex and can now access the
+ *             // shared resource.
+ *
+ *             // ...
+ *             // For some reason due to the nature of the code further calls to
+ *                     // xSemaphoreTakeRecursive() are made on the same mutex.  In real
+ *                     // code these would not be just sequential calls as this would make
+ *                     // no sense.  Instead the calls are likely to be buried inside
+ *                     // a more complex call structure.
+ *             xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 );
+ *             xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 );
+ *
+ *             // The mutex has now been 'taken' three times, so will not be
+ *                     // available to another task until it has also been given back
+ *                     // three times.  Again it is unlikely that real code would have
+ *                     // these calls sequentially, but instead buried in a more complex
+ *                     // call structure.  This is just for illustrative purposes.
+ *             xSemaphoreGiveRecursive( xMutex );
+ *                     xSemaphoreGiveRecursive( xMutex );
+ *                     xSemaphoreGiveRecursive( xMutex );
+ *
+ *                     // Now the mutex can be taken by other tasks.
+ *         }
+ *         else
+ *         {
+ *             // We could not obtain the mutex and can therefore not access
+ *             // the shared resource safely.
+ *         }
+ *     }
+ *  }
+ * @endcode
+ * \ingroup Semaphores
+ */
+#define xSemaphoreTakeRecursive( xMutex, xBlockTime )  xQueueTakeMutexRecursive( ( xMutex ), ( xBlockTime ) )
+
+/** @cond */
+/*
+ * xSemaphoreAltTake() is an alternative version of xSemaphoreTake().
+ *
+ * The source code that implements the alternative (Alt) API is much
+ * simpler     because it executes everything from within a critical section.
+ * This is     the approach taken by many other RTOSes, but FreeRTOS.org has the
+ * preferred fully featured API too.  The fully featured API has more
+ * complex     code that takes longer to execute, but makes much less use of
+ * critical sections.  Therefore the alternative API sacrifices interrupt
+ * responsiveness to gain execution speed, whereas the fully featured API
+ * sacrifices execution speed to ensure better interrupt responsiveness.
+ */
+#define xSemaphoreAltTake( xSemaphore, xBlockTime )            xQueueAltGenericReceive( ( QueueHandle_t ) ( xSemaphore ), NULL, ( xBlockTime ), pdFALSE )
+/** @endcond */
+
+/**
+ * <i>Macro</i> to release a semaphore.  The semaphore must have previously been
+ * created with a call to vSemaphoreCreateBinary(), xSemaphoreCreateMutex() or
+ * xSemaphoreCreateCounting(). and obtained using sSemaphoreTake().
+ *
+ * This macro must not be used from an ISR.  See xSemaphoreGiveFromISR () for
+ * an alternative which can be used from an ISR.
+ *
+ * This macro must also not be used on semaphores created using
+ * xSemaphoreCreateRecursiveMutex().
+ *
+ * @param xSemaphore A handle to the semaphore being released.  This is the
+ * handle returned when the semaphore was created.
+ *
+ * @return pdTRUE if the semaphore was released.  pdFALSE if an error occurred.
+ * Semaphores are implemented using queues.  An error can occur if there is
+ * no space on the queue to post a message - indicating that the
+ * semaphore was not first obtained correctly.
+ *
+ * Example usage:
+ * @code{c}
+ *  SemaphoreHandle_t xSemaphore = NULL;
+ *
+ *  void vATask( void * pvParameters )
+ *  {
+ *     // Create the semaphore to guard a shared resource.
+ *     vSemaphoreCreateBinary( xSemaphore );
+ *
+ *     if( xSemaphore != NULL )
+ *     {
+ *         if( xSemaphoreGive( xSemaphore ) != pdTRUE )
+ *         {
+ *             // We would expect this call to fail because we cannot give
+ *             // a semaphore without first "taking" it!
+ *         }
+ *
+ *         // Obtain the semaphore - don't block if the semaphore is not
+ *         // immediately available.
+ *         if( xSemaphoreTake( xSemaphore, ( TickType_t ) 0 ) )
+ *         {
+ *             // We now have the semaphore and can access the shared resource.
+ *
+ *             // ...
+ *
+ *             // We have finished accessing the shared resource so can free the
+ *             // semaphore.
+ *             if( xSemaphoreGive( xSemaphore ) != pdTRUE )
+ *             {
+ *                 // We would not expect this call to fail because we must have
+ *                 // obtained the semaphore to get here.
+ *             }
+ *         }
+ *     }
+ *  }
+ * @endcode
+ * \ingroup Semaphores
+ */
+#define xSemaphoreGive( xSemaphore )           xQueueGenericSend( ( QueueHandle_t ) ( xSemaphore ), NULL, semGIVE_BLOCK_TIME, queueSEND_TO_BACK )
+
+/**
+ * <i>Macro</i> to recursively release, or 'give', a mutex type semaphore.
+ * The mutex must have previously been created using a call to
+ * xSemaphoreCreateRecursiveMutex();
+ *
+ * configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this
+ * macro to be available.
+ *
+ * This macro must not be used on mutexes created using xSemaphoreCreateMutex().
+ *
+ * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex
+ * doesn't become available again until the owner has called
+ * xSemaphoreGiveRecursive() for each successful 'take' request.  For example,
+ * if a task successfully 'takes' the same mutex 5 times then the mutex will
+ * not be available to any other task until it has also  'given' the mutex back
+ * exactly five times.
+ *
+ * @param xMutex A handle to the mutex being released, or 'given'.  This is the
+ * handle returned by xSemaphoreCreateMutex();
+ *
+ * @return pdTRUE if the semaphore was given.
+ *
+ * Example usage:
+ * @code{c}
+ *  SemaphoreHandle_t xMutex = NULL;
+ *
+ *  // A task that creates a mutex.
+ *  void vATask( void * pvParameters )
+ *  {
+ *     // Create the mutex to guard a shared resource.
+ *     xMutex = xSemaphoreCreateRecursiveMutex();
+ *  }
+ *
+ *  // A task that uses the mutex.
+ *  void vAnotherTask( void * pvParameters )
+ *  {
+ *     // ... Do other things.
+ *
+ *     if( xMutex != NULL )
+ *     {
+ *         // See if we can obtain the mutex.  If the mutex is not available
+ *         // wait 10 ticks to see if it becomes free.
+ *         if( xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ) == pdTRUE )
+ *         {
+ *             // We were able to obtain the mutex and can now access the
+ *             // shared resource.
+ *
+ *             // ...
+ *             // For some reason due to the nature of the code further calls to
+ *                     // xSemaphoreTakeRecursive() are made on the same mutex.  In real
+ *                     // code these would not be just sequential calls as this would make
+ *                     // no sense.  Instead the calls are likely to be buried inside
+ *                     // a more complex call structure.
+ *             xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 );
+ *             xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 );
+ *
+ *             // The mutex has now been 'taken' three times, so will not be
+ *                     // available to another task until it has also been given back
+ *                     // three times.  Again it is unlikely that real code would have
+ *                     // these calls sequentially, it would be more likely that the calls
+ *                     // to xSemaphoreGiveRecursive() would be called as a call stack
+ *                     // unwound.  This is just for demonstrative purposes.
+ *             xSemaphoreGiveRecursive( xMutex );
+ *                     xSemaphoreGiveRecursive( xMutex );
+ *                     xSemaphoreGiveRecursive( xMutex );
+ *
+ *                     // Now the mutex can be taken by other tasks.
+ *         }
+ *         else
+ *         {
+ *             // We could not obtain the mutex and can therefore not access
+ *             // the shared resource safely.
+ *         }
+ *     }
+ *  }
+ * @endcode
+ * \ingroup Semaphores
+ */
+#define xSemaphoreGiveRecursive( xMutex )      xQueueGiveMutexRecursive( ( xMutex ) )
+
+/** @cond */
+/*
+ * xSemaphoreAltGive() is an alternative version of xSemaphoreGive().
+ *
+ * The source code that implements the alternative (Alt) API is much
+ * simpler     because it executes everything from within a critical section.
+ * This is     the approach taken by many other RTOSes, but FreeRTOS.org has the
+ * preferred fully featured API too.  The fully featured API has more
+ * complex     code that takes longer to execute, but makes much less use of
+ * critical sections.  Therefore the alternative API sacrifices interrupt
+ * responsiveness to gain execution speed, whereas the fully featured API
+ * sacrifices execution speed to ensure better interrupt responsiveness.
+ */
+#define xSemaphoreAltGive( xSemaphore )                xQueueAltGenericSend( ( QueueHandle_t ) ( xSemaphore ), NULL, semGIVE_BLOCK_TIME, queueSEND_TO_BACK )
+
+/** @endcond */
+
+/**
+ * <i>Macro</i> to  release a semaphore.  The semaphore must have previously been
+ * created with a call to vSemaphoreCreateBinary() or xSemaphoreCreateCounting().
+ *
+ * Mutex type semaphores (those created using a call to xSemaphoreCreateMutex())
+ * must not be used with this macro.
+ *
+ * This macro can be used from an ISR.
+ *
+ * @param xSemaphore A handle to the semaphore being released.  This is the
+ * handle returned when the semaphore was created.
+ *
+ * @param[out] pxHigherPriorityTaskWoken xSemaphoreGiveFromISR() will set
+ * *pxHigherPriorityTaskWoken to pdTRUE if giving the semaphore caused a task
+ * to unblock, and the unblocked task has a priority higher than the currently
+ * running task.  If xSemaphoreGiveFromISR() sets this value to pdTRUE then
+ * a context switch should be requested before the interrupt is exited.
+ *
+ * @return pdTRUE if the semaphore was successfully given, otherwise errQUEUE_FULL.
+ *
+ * Example usage:
+ * @code{c}
+ *  \#define LONG_TIME 0xffff
+ *  \#define TICKS_TO_WAIT     10
+ *  SemaphoreHandle_t xSemaphore = NULL;
+ *
+ *  // Repetitive task.
+ *  void vATask( void * pvParameters )
+ *  {
+ *     for( ;; )
+ *     {
+ *         // We want this task to run every 10 ticks of a timer.  The semaphore
+ *         // was created before this task was started.
+ *
+ *         // Block waiting for the semaphore to become available.
+ *         if( xSemaphoreTake( xSemaphore, LONG_TIME ) == pdTRUE )
+ *         {
+ *             // It is time to execute.
+ *
+ *             // ...
+ *
+ *             // We have finished our task.  Return to the top of the loop where
+ *             // we will block on the semaphore until it is time to execute
+ *             // again.  Note when using the semaphore for synchronisation with an
+ *                     // ISR in this manner there is no need to 'give' the semaphore back.
+ *         }
+ *     }
+ *  }
+ *
+ *  // Timer ISR
+ *  void vTimerISR( void * pvParameters )
+ *  {
+ *  static uint8_t ucLocalTickCount = 0;
+ *  static BaseType_t xHigherPriorityTaskWoken;
+ *
+ *     // A timer tick has occurred.
+ *
+ *     // ... Do other time functions.
+ *
+ *     // Is it time for vATask () to run?
+ *     xHigherPriorityTaskWoken = pdFALSE;
+ *     ucLocalTickCount++;
+ *     if( ucLocalTickCount >= TICKS_TO_WAIT )
+ *     {
+ *         // Unblock the task by releasing the semaphore.
+ *         xSemaphoreGiveFromISR( xSemaphore, &xHigherPriorityTaskWoken );
+ *
+ *         // Reset the count so we release the semaphore again in 10 ticks time.
+ *         ucLocalTickCount = 0;
+ *     }
+ *
+ *     if( xHigherPriorityTaskWoken != pdFALSE )
+ *     {
+ *         // We can force a context switch here.  Context switching from an
+ *         // ISR uses port specific syntax.  Check the demo task for your port
+ *         // to find the syntax required.
+ *     }
+ *  }
+ * @endcode
+ * \ingroup Semaphores
+ */
+#define xSemaphoreGiveFromISR( xSemaphore, pxHigherPriorityTaskWoken ) xQueueGiveFromISR( ( QueueHandle_t ) ( xSemaphore ), ( pxHigherPriorityTaskWoken ) )
+
+/**
+ * <i>Macro</i> to  take a semaphore from an ISR.  The semaphore must have
+ * previously been created with a call to vSemaphoreCreateBinary() or
+ * xSemaphoreCreateCounting().
+ *
+ * Mutex type semaphores (those created using a call to xSemaphoreCreateMutex())
+ * must not be used with this macro.
+ *
+ * This macro can be used from an ISR, however taking a semaphore from an ISR
+ * is not a common operation.  It is likely to only be useful when taking a
+ * counting semaphore when an interrupt is obtaining an object from a resource
+ * pool (when the semaphore count indicates the number of resources available).
+ *
+ * @param xSemaphore A handle to the semaphore being taken.  This is the
+ * handle returned when the semaphore was created.
+ *
+ * @param[out] pxHigherPriorityTaskWoken xSemaphoreTakeFromISR() will set
+ * *pxHigherPriorityTaskWoken to pdTRUE if taking the semaphore caused a task
+ * to unblock, and the unblocked task has a priority higher than the currently
+ * running task.  If xSemaphoreTakeFromISR() sets this value to pdTRUE then
+ * a context switch should be requested before the interrupt is exited.
+ *
+ * @return pdTRUE if the semaphore was successfully taken, otherwise
+ * pdFALSE
+ */
+#define xSemaphoreTakeFromISR( xSemaphore, pxHigherPriorityTaskWoken ) xQueueReceiveFromISR( ( QueueHandle_t ) ( xSemaphore ), NULL, ( pxHigherPriorityTaskWoken ) )
+
+/**
+ * <i>Macro</i> that implements a mutex semaphore by using the existing queue
+ * mechanism.
+ *
+ * Internally, within the FreeRTOS implementation, mutex semaphores use a block
+ * of memory, in which the mutex structure is stored.  If a mutex is created
+ * using xSemaphoreCreateMutex() then the required memory is automatically
+ * dynamically allocated inside the xSemaphoreCreateMutex() function.  (see
+ * http://www.freertos.org/a00111.html).  If a mutex is created using
+ * xSemaphoreCreateMutexStatic() then the application writer must provided the
+ * memory.  xSemaphoreCreateMutexStatic() therefore allows a mutex to be created
+ * without using any dynamic memory allocation.
+ *
+ * Mutexes created using this function can be accessed using the xSemaphoreTake()
+ * and xSemaphoreGive() macros.  The xSemaphoreTakeRecursive() and
+ * xSemaphoreGiveRecursive() macros must not be used.
+ *
+ * This type of semaphore uses a priority inheritance mechanism so a task
+ * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the
+ * semaphore it is no longer required.
+ *
+ * Mutex type semaphores cannot be used from within interrupt service routines.
+ *
+ * See vSemaphoreCreateBinary() for an alternative implementation that can be
+ * used for pure synchronisation (where one task or interrupt always 'gives' the
+ * semaphore and another always 'takes' the semaphore) and from within interrupt
+ * service routines.
+ *
+ * @return If the mutex was successfully created then a handle to the created
+ * semaphore is returned.  If there was not enough heap to allocate the mutex
+ * data structures then NULL is returned.
+ *
+ * Example usage:
+ * @code{c}
+ *  SemaphoreHandle_t xSemaphore;
+ *
+ *  void vATask( void * pvParameters )
+ *  {
+ *     // Semaphore cannot be used before a call to xSemaphoreCreateMutex().
+ *     // This is a macro so pass the variable in directly.
+ *     xSemaphore = xSemaphoreCreateMutex();
+ *
+ *     if( xSemaphore != NULL )
+ *     {
+ *         // The semaphore was created successfully.
+ *         // The semaphore can now be used.
+ *     }
+ *  }
+ * @endcode
+ * \ingroup Semaphores
+ */
+#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
+       #define xSemaphoreCreateMutex() xQueueCreateMutex( queueQUEUE_TYPE_MUTEX )
+#endif
+
+/**
+ * Creates a new mutex type semaphore instance, and returns a handle by which
+ * the new mutex can be referenced.
+ *
+ * Internally, within the FreeRTOS implementation, mutex semaphores use a block
+ * of memory, in which the mutex structure is stored.  If a mutex is created
+ * using xSemaphoreCreateMutex() then the required memory is automatically
+ * dynamically allocated inside the xSemaphoreCreateMutex() function.  (see
+ * http://www.freertos.org/a00111.html).  If a mutex is created using
+ * xSemaphoreCreateMutexStatic() then the application writer must provided the
+ * memory.  xSemaphoreCreateMutexStatic() therefore allows a mutex to be created
+ * without using any dynamic memory allocation.
+ *
+ * Mutexes created using this function can be accessed using the xSemaphoreTake()
+ * and xSemaphoreGive() macros.  The xSemaphoreTakeRecursive() and
+ * xSemaphoreGiveRecursive() macros must not be used.
+ *
+ * This type of semaphore uses a priority inheritance mechanism so a task
+ * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the
+ * semaphore it is no longer required.
+ *
+ * Mutex type semaphores cannot be used from within interrupt service routines.
+ *
+ * See xSemaphoreCreateBinary() for an alternative implementation that can be
+ * used for pure synchronisation (where one task or interrupt always 'gives' the
+ * semaphore and another always 'takes' the semaphore) and from within interrupt
+ * service routines.
+ *
+ * @param pxMutexBuffer Must point to a variable of type StaticSemaphore_t,
+ * which will be used to hold the mutex's data structure, removing the need for
+ * the memory to be allocated dynamically.
+ *
+ * @return If the mutex was successfully created then a handle to the created
+ * mutex is returned.  If pxMutexBuffer was NULL then NULL is returned.
+ *
+ * Example usage:
+ * @code
+ *  SemaphoreHandle_t xSemaphore;
+ *  StaticSemaphore_t xMutexBuffer;
+ *
+ *  void vATask( void * pvParameters )
+ *  {
+ *     // A mutex cannot be used before it has been created.  xMutexBuffer is
+ *     // into xSemaphoreCreateMutexStatic() so no dynamic memory allocation is
+ *     // attempted.
+ *     xSemaphore = xSemaphoreCreateMutexStatic( &xMutexBuffer );
+ *
+ *     // As no dynamic memory allocation was performed, xSemaphore cannot be NULL,
+ *     // so there is no need to check it.
+ *  }
+ * @endcode
+ * \ingroup Semaphores
+ */
+ #if( configSUPPORT_STATIC_ALLOCATION == 1 )
+       #define xSemaphoreCreateMutexStatic( pxMutexBuffer ) xQueueCreateMutexStatic( queueQUEUE_TYPE_MUTEX, ( pxMutexBuffer ) )
+#endif /* configSUPPORT_STATIC_ALLOCATION */
+
+
+/**
+ * Creates a new recursive mutex type semaphore instance, and returns a handle
+ * by which the new recursive mutex can be referenced.
+ *
+ * Internally, within the FreeRTOS implementation, recursive mutexs use a block
+ * of memory, in which the mutex structure is stored.  If a recursive mutex is
+ * created using xSemaphoreCreateRecursiveMutex() then the required memory is
+ * automatically dynamically allocated inside the
+ * xSemaphoreCreateRecursiveMutex() function.  (see
+ * http://www.freertos.org/a00111.html).  If a recursive mutex is created using
+ * xSemaphoreCreateRecursiveMutexStatic() then the application writer must
+ * provide the memory that will get used by the mutex.
+ * xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to
+ * be created without using any dynamic memory allocation.
+ *
+ * Mutexes created using this macro can be accessed using the
+ * xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros.  The
+ * xSemaphoreTake() and xSemaphoreGive() macros must not be used.
+ *
+ * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex
+ * doesn't become available again until the owner has called
+ * xSemaphoreGiveRecursive() for each successful 'take' request.  For example,
+ * if a task successfully 'takes' the same mutex 5 times then the mutex will
+ * not be available to any other task until it has also  'given' the mutex back
+ * exactly five times.
+ *
+ * This type of semaphore uses a priority inheritance mechanism so a task
+ * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the
+ * semaphore it is no longer required.
+ *
+ * Mutex type semaphores cannot be used from within interrupt service routines.
+ *
+ * See vSemaphoreCreateBinary() for an alternative implementation that can be
+ * used for pure synchronisation (where one task or interrupt always 'gives' the
+ * semaphore and another always 'takes' the semaphore) and from within interrupt
+ * service routines.
+ *
+ * @return xSemaphore Handle to the created mutex semaphore.  Should be of type
+ *             SemaphoreHandle_t.
+ *
+ * Example usage:
+ * @code{c}
+ *  SemaphoreHandle_t xSemaphore;
+ *
+ *  void vATask( void * pvParameters )
+ *  {
+ *     // Semaphore cannot be used before a call to xSemaphoreCreateMutex().
+ *     // This is a macro so pass the variable in directly.
+ *     xSemaphore = xSemaphoreCreateRecursiveMutex();
+ *
+ *     if( xSemaphore != NULL )
+ *     {
+ *         // The semaphore was created successfully.
+ *         // The semaphore can now be used.
+ *     }
+ *  }
+ * @endcode
+ * \ingroup Semaphores
+ */
+#if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configUSE_RECURSIVE_MUTEXES == 1 ) )
+       #define xSemaphoreCreateRecursiveMutex() xQueueCreateMutex( queueQUEUE_TYPE_RECURSIVE_MUTEX )
+#endif
+
+/**
+ * Creates a new recursive mutex type semaphore instance, and returns a handle
+ * by which the new recursive mutex can be referenced.
+ *
+ * Internally, within the FreeRTOS implementation, recursive mutexs use a block
+ * of memory, in which the mutex structure is stored.  If a recursive mutex is
+ * created using xSemaphoreCreateRecursiveMutex() then the required memory is
+ * automatically dynamically allocated inside the
+ * xSemaphoreCreateRecursiveMutex() function.  (see
+ * http://www.freertos.org/a00111.html).  If a recursive mutex is created using
+ * xSemaphoreCreateRecursiveMutexStatic() then the application writer must
+ * provide the memory that will get used by the mutex.
+ * xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to
+ * be created without using any dynamic memory allocation.
+ *
+ * Mutexes created using this macro can be accessed using the
+ * xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros.  The
+ * xSemaphoreTake() and xSemaphoreGive() macros must not be used.
+ *
+ * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex
+ * doesn't become available again until the owner has called
+ * xSemaphoreGiveRecursive() for each successful 'take' request.  For example,
+ * if a task successfully 'takes' the same mutex 5 times then the mutex will
+ * not be available to any other task until it has also  'given' the mutex back
+ * exactly five times.
+ *
+ * This type of semaphore uses a priority inheritance mechanism so a task
+ * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the
+ * semaphore it is no longer required.
+ *
+ * Mutex type semaphores cannot be used from within interrupt service routines.
+ *
+ * See xSemaphoreCreateBinary() for an alternative implementation that can be
+ * used for pure synchronisation (where one task or interrupt always 'gives' the
+ * semaphore and another always 'takes' the semaphore) and from within interrupt
+ * service routines.
+ *
+ * @param pxStaticSemaphore Must point to a variable of type StaticSemaphore_t,
+ * which will then be used to hold the recursive mutex's data structure,
+ * removing the need for the memory to be allocated dynamically.
+ *
+ * @return If the recursive mutex was successfully created then a handle to the
+ * created recursive mutex is returned.  If pxMutexBuffer was NULL then NULL is
+ * returned.
+ *
+ * Example usage:
+ * @code
+ *  SemaphoreHandle_t xSemaphore;
+ *  StaticSemaphore_t xMutexBuffer;
+ *
+ *  void vATask( void * pvParameters )
+ *  {
+ *     // A recursive semaphore cannot be used before it is created.  Here a
+ *     // recursive mutex is created using xSemaphoreCreateRecursiveMutexStatic().
+ *     // The address of xMutexBuffer is passed into the function, and will hold
+ *     // the mutexes data structures - so no dynamic memory allocation will be
+ *     // attempted.
+ *     xSemaphore = xSemaphoreCreateRecursiveMutexStatic( &xMutexBuffer );
+ *
+ *     // As no dynamic memory allocation was performed, xSemaphore cannot be NULL,
+ *     // so there is no need to check it.
+ *  }
+ * @endcode
+ * \ingroup Semaphores
+ */
+#if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configUSE_RECURSIVE_MUTEXES == 1 ) )
+       #define xSemaphoreCreateRecursiveMutexStatic( pxStaticSemaphore ) xQueueCreateMutexStatic( queueQUEUE_TYPE_RECURSIVE_MUTEX, pxStaticSemaphore )
+#endif /* configSUPPORT_STATIC_ALLOCATION */
+
+/**
+ * Creates a new counting semaphore instance, and returns a handle by which the
+ * new counting semaphore can be referenced.
+ *
+ * In many usage scenarios it is faster and more memory efficient to use a
+ * direct to task notification in place of a counting semaphore!
+ * http://www.freertos.org/RTOS-task-notifications.html
+ *
+ * Internally, within the FreeRTOS implementation, counting semaphores use a
+ * block of memory, in which the counting semaphore structure is stored.  If a
+ * counting semaphore is created using xSemaphoreCreateCounting() then the
+ * required memory is automatically dynamically allocated inside the
+ * xSemaphoreCreateCounting() function.  (see
+ * http://www.freertos.org/a00111.html).  If a counting semaphore is created
+ * using xSemaphoreCreateCountingStatic() then the application writer can
+ * instead optionally provide the memory that will get used by the counting
+ * semaphore.  xSemaphoreCreateCountingStatic() therefore allows a counting
+ * semaphore to be created without using any dynamic memory allocation.
+ *
+ * Counting semaphores are typically used for two things:
+ *
+ * 1) Counting events.
+ *
+ *    In this usage scenario an event handler will 'give' a semaphore each time
+ *    an event occurs (incrementing the semaphore count value), and a handler
+ *    task will 'take' a semaphore each time it processes an event
+ *    (decrementing the semaphore count value).  The count value is therefore
+ *    the difference between the number of events that have occurred and the
+ *    number that have been processed.  In this case it is desirable for the
+ *    initial count value to be zero.
+ *
+ * 2) Resource management.
+ *
+ *    In this usage scenario the count value indicates the number of resources
+ *    available.  To obtain control of a resource a task must first obtain a
+ *    semaphore - decrementing the semaphore count value.  When the count value
+ *    reaches zero there are no free resources.  When a task finishes with the
+ *    resource it 'gives' the semaphore back - incrementing the semaphore count
+ *    value.  In this case it is desirable for the initial count value to be
+ *    equal to the maximum count value, indicating that all resources are free.
+ *
+ * @param uxMaxCount The maximum count value that can be reached.  When the
+ *        semaphore reaches this value it can no longer be 'given'.
+ *
+ * @param uxInitialCount The count value assigned to the semaphore when it is
+ *        created.
+ *
+ * @return Handle to the created semaphore.  Null if the semaphore could not be
+ *         created.
+ *
+ * Example usage:
+ * @code{c}
+ *  SemaphoreHandle_t xSemaphore;
+ *
+ *  void vATask( void * pvParameters )
+ *  {
+ *  SemaphoreHandle_t xSemaphore = NULL;
+ *
+ *     // Semaphore cannot be used before a call to xSemaphoreCreateCounting().
+ *     // The max value to which the semaphore can count should be 10, and the
+ *     // initial value assigned to the count should be 0.
+ *     xSemaphore = xSemaphoreCreateCounting( 10, 0 );
+ *
+ *     if( xSemaphore != NULL )
+ *     {
+ *         // The semaphore was created successfully.
+ *         // The semaphore can now be used.
+ *     }
+ *  }
+ * @endcode
+ * \ingroup Semaphores
+ */
+#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
+       #define xSemaphoreCreateCounting( uxMaxCount, uxInitialCount ) xQueueCreateCountingSemaphore( ( uxMaxCount ), ( uxInitialCount ) )
+#endif
+
+/**
+ * Creates a new counting semaphore instance, and returns a handle by which the
+ * new counting semaphore can be referenced.
+ *
+ * In many usage scenarios it is faster and more memory efficient to use a
+ * direct to task notification in place of a counting semaphore!
+ * http://www.freertos.org/RTOS-task-notifications.html
+ *
+ * Internally, within the FreeRTOS implementation, counting semaphores use a
+ * block of memory, in which the counting semaphore structure is stored.  If a
+ * counting semaphore is created using xSemaphoreCreateCounting() then the
+ * required memory is automatically dynamically allocated inside the
+ * xSemaphoreCreateCounting() function.  (see
+ * http://www.freertos.org/a00111.html).  If a counting semaphore is created
+ * using xSemaphoreCreateCountingStatic() then the application writer must
+ * provide the memory.  xSemaphoreCreateCountingStatic() therefore allows a
+ * counting semaphore to be created without using any dynamic memory allocation.
+ *
+ * Counting semaphores are typically used for two things:
+ *
+ * 1) Counting events.
+ *
+ *    In this usage scenario an event handler will 'give' a semaphore each time
+ *    an event occurs (incrementing the semaphore count value), and a handler
+ *    task will 'take' a semaphore each time it processes an event
+ *    (decrementing the semaphore count value).  The count value is therefore
+ *    the difference between the number of events that have occurred and the
+ *    number that have been processed.  In this case it is desirable for the
+ *    initial count value to be zero.
+ *
+ * 2) Resource management.
+ *
+ *    In this usage scenario the count value indicates the number of resources
+ *    available.  To obtain control of a resource a task must first obtain a
+ *    semaphore - decrementing the semaphore count value.  When the count value
+ *    reaches zero there are no free resources.  When a task finishes with the
+ *    resource it 'gives' the semaphore back - incrementing the semaphore count
+ *    value.  In this case it is desirable for the initial count value to be
+ *    equal to the maximum count value, indicating that all resources are free.
+ *
+ * @param uxMaxCount The maximum count value that can be reached.  When the
+ *        semaphore reaches this value it can no longer be 'given'.
+ *
+ * @param uxInitialCount The count value assigned to the semaphore when it is
+ *        created.
+ *
+ * @param pxSemaphoreBuffer Must point to a variable of type StaticSemaphore_t,
+ * which will then be used to hold the semaphore's data structure, removing the
+ * need for the memory to be allocated dynamically.
+ *
+ * @return If the counting semaphore was successfully created then a handle to
+ * the created counting semaphore is returned.  If pxSemaphoreBuffer was NULL
+ * then NULL is returned.
+ *
+ * Example usage:
+ * @code{c}
+ *  SemaphoreHandle_t xSemaphore;
+ *  StaticSemaphore_t xSemaphoreBuffer;
+ *
+ *  void vATask( void * pvParameters )
+ *  {
+ *  SemaphoreHandle_t xSemaphore = NULL;
+ *
+ *     // Counting semaphore cannot be used before they have been created.  Create
+ *     // a counting semaphore using xSemaphoreCreateCountingStatic().  The max
+ *     // value to which the semaphore can count is 10, and the initial value
+ *     // assigned to the count will be 0.  The address of xSemaphoreBuffer is
+ *     // passed in and will be used to hold the semaphore structure, so no dynamic
+ *     // memory allocation will be used.
+ *     xSemaphore = xSemaphoreCreateCounting( 10, 0, &xSemaphoreBuffer );
+ *
+ *     // No memory allocation was attempted so xSemaphore cannot be NULL, so there
+ *     // is no need to check its value.
+ *  }
+ * @endcode
+ * \ingroup Semaphores
+ */
+#if( configSUPPORT_STATIC_ALLOCATION == 1 )
+       #define xSemaphoreCreateCountingStatic( uxMaxCount, uxInitialCount, pxSemaphoreBuffer ) xQueueCreateCountingSemaphoreStatic( ( uxMaxCount ), ( uxInitialCount ), ( pxSemaphoreBuffer ) )
+#endif /* configSUPPORT_STATIC_ALLOCATION */
+
+/**
+ * Delete a semaphore.  This function must be used with care.  For example,
+ * do not delete a mutex type semaphore if the mutex is held by a task.
+ *
+ * @param xSemaphore A handle to the semaphore to be deleted.
+ *
+ * \ingroup Semaphores
+ */
+#define vSemaphoreDelete( xSemaphore ) vQueueDelete( ( QueueHandle_t ) ( xSemaphore ) )
+
+/**
+ * If xMutex is indeed a mutex type semaphore, return the current mutex holder.
+ * If xMutex is not a mutex type semaphore, or the mutex is available (not held
+ * by a task), return NULL.
+ *
+ * Note: This is a good way of determining if the calling task is the mutex
+ * holder, but not a good way of determining the identity of the mutex holder as
+ * the holder may change between the function exiting and the returned value
+ * being tested.
+ */
+#define xSemaphoreGetMutexHolder( xSemaphore ) xQueueGetMutexHolder( ( xSemaphore ) )
+
+/**
+ * If the semaphore is a counting semaphore then uxSemaphoreGetCount() returns
+ * its current count value.  If the semaphore is a binary semaphore then
+ * uxSemaphoreGetCount() returns 1 if the semaphore is available, and 0 if the
+ * semaphore is not available.
+ *
+ */
+#define uxSemaphoreGetCount( xSemaphore ) uxQueueMessagesWaiting( ( QueueHandle_t ) ( xSemaphore ) )
+
+#endif /* SEMAPHORE_H */
+
+
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/sim_esp_tls.h b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/sim_esp_tls.h
new file mode 100644 (file)
index 0000000..e1ac8f8
--- /dev/null
@@ -0,0 +1,632 @@
+// Copyright 2017-2018 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+#ifndef _SIM_ESP_TLS_H_
+#define _SIM_ESP_TLS_H_
+
+#define CONFIG_ESP_TLS_USING_MBEDTLS
+
+#include <stdbool.h>
+#include <sockets.h>
+//#include <fcntl.h>
+#include "esp_err.h"
+#ifdef CONFIG_ESP_TLS_USING_MBEDTLS
+#include "platform.h"
+#include "net_sockets.h"
+#include "debug.h"
+#include "ssl.h"
+#include "entropy.h"
+#include "ctr_drbg.h"
+#include "error.h"
+#include "certs.h"
+#include "x509_crt.h"
+//#elif CONFIG_ESP_TLS_USING_WOLFSSL
+//#include "wolfssl/wolfcrypt/settings.h"
+//#include "wolfssl/ssl.h"
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//typedef int size_t;
+typedef unsigned int ssize_t;
+
+#define SIM_ESP_ERR_ESP_TLS_BASE           0x8000             /*!< Starting number of ESP-TLS error codes */
+#define SIM_ESP_ERR_ESP_TLS_CANNOT_RESOLVE_HOSTNAME           (SIM_ESP_ERR_ESP_TLS_BASE + 0x01)  /*!< Error if hostname couldn't be resolved upon tls connection */
+#define ESP_ERR_ESP_TLS_CANNOT_CREATE_SOCKET              (SIM_ESP_ERR_ESP_TLS_BASE + 0x02)  /*!< Failed to create socket */
+#define ESP_ERR_ESP_TLS_UNSUPPORTED_PROTOCOL_FAMILY       (SIM_ESP_ERR_ESP_TLS_BASE + 0x03)  /*!< Unsupported protocol family */
+#define ESP_ERR_ESP_TLS_FAILED_CONNECT_TO_HOST            (SIM_ESP_ERR_ESP_TLS_BASE + 0x04)  /*!< Failed to connect to host */
+#define ESP_ERR_ESP_TLS_SOCKET_SETOPT_FAILED              (SIM_ESP_ERR_ESP_TLS_BASE + 0x05)  /*!< failed to set socket option */
+#define ESP_ERR_MBEDTLS_CERT_PARTLY_OK                    (SIM_ESP_ERR_ESP_TLS_BASE + 0x06)  /*!< mbedtls parse certificates was partly successful */
+#define ESP_ERR_MBEDTLS_CTR_DRBG_SEED_FAILED              (SIM_ESP_ERR_ESP_TLS_BASE + 0x07)  /*!< mbedtls api returned error */
+#define ESP_ERR_MBEDTLS_SSL_SET_HOSTNAME_FAILED           (SIM_ESP_ERR_ESP_TLS_BASE + 0x08)  /*!< mbedtls api returned error */
+#define ESP_ERR_MBEDTLS_SSL_CONFIG_DEFAULTS_FAILED        (SIM_ESP_ERR_ESP_TLS_BASE + 0x09)  /*!< mbedtls api returned error */
+#define ESP_ERR_MBEDTLS_SSL_CONF_ALPN_PROTOCOLS_FAILED    (SIM_ESP_ERR_ESP_TLS_BASE + 0x0A)  /*!< mbedtls api returned error */
+#define ESP_ERR_MBEDTLS_X509_CRT_PARSE_FAILED             (SIM_ESP_ERR_ESP_TLS_BASE + 0x0B)  /*!< mbedtls api returned error */
+#define ESP_ERR_MBEDTLS_SSL_CONF_OWN_CERT_FAILED          (SIM_ESP_ERR_ESP_TLS_BASE + 0x0C)  /*!< mbedtls api returned error */
+#define ESP_ERR_MBEDTLS_SSL_SETUP_FAILED                  (SIM_ESP_ERR_ESP_TLS_BASE + 0x0D)  /*!< mbedtls api returned error */
+#define ESP_ERR_MBEDTLS_SSL_WRITE_FAILED                  (SIM_ESP_ERR_ESP_TLS_BASE + 0x0E)  /*!< mbedtls api returned error */
+#define ESP_ERR_MBEDTLS_PK_PARSE_KEY_FAILED               (SIM_ESP_ERR_ESP_TLS_BASE + 0x0F)  /*!< mbedtls api returned failed  */
+#define ESP_ERR_MBEDTLS_SSL_HANDSHAKE_FAILED              (SIM_ESP_ERR_ESP_TLS_BASE + 0x10)  /*!< mbedtls api returned failed  */
+#define ESP_ERR_MBEDTLS_SSL_CONF_PSK_FAILED               (SIM_ESP_ERR_ESP_TLS_BASE + 0x11)  /*!< mbedtls api returned failed  */
+#define ESP_ERR_ESP_TLS_CONNECTION_TIMEOUT                (SIM_ESP_ERR_ESP_TLS_BASE + 0x12)  /*!< new connection in esp_tls_low_level_conn connection timeouted */
+#define ESP_ERR_WOLFSSL_SSL_SET_HOSTNAME_FAILED           (SIM_ESP_ERR_ESP_TLS_BASE + 0x13)  /*!< wolfSSL api returned error */
+#define ESP_ERR_WOLFSSL_SSL_CONF_ALPN_PROTOCOLS_FAILED    (SIM_ESP_ERR_ESP_TLS_BASE + 0x14)  /*!< wolfSSL api returned error */
+#define ESP_ERR_WOLFSSL_CERT_VERIFY_SETUP_FAILED          (SIM_ESP_ERR_ESP_TLS_BASE + 0x15)  /*!< wolfSSL api returned error */
+#define ESP_ERR_WOLFSSL_KEY_VERIFY_SETUP_FAILED           (SIM_ESP_ERR_ESP_TLS_BASE + 0x16)  /*!< wolfSSL api returned error */
+#define ESP_ERR_WOLFSSL_SSL_HANDSHAKE_FAILED              (SIM_ESP_ERR_ESP_TLS_BASE + 0x17)  /*!< wolfSSL api returned failed  */
+#define ESP_ERR_WOLFSSL_CTX_SETUP_FAILED                  (SIM_ESP_ERR_ESP_TLS_BASE + 0x18)  /*!< wolfSSL api returned failed */
+#define ESP_ERR_WOLFSSL_SSL_SETUP_FAILED                  (SIM_ESP_ERR_ESP_TLS_BASE + 0x19)  /*!< wolfSSL api returned failed */
+#define ESP_ERR_WOLFSSL_SSL_WRITE_FAILED                  (SIM_ESP_ERR_ESP_TLS_BASE + 0x1A)  /*!< wolfSSL api returned failed */
+
+#define ESP_ERR_ESP_TLS_SE_FAILED                         (SIM_ESP_ERR_ESP_TLS_BASE + 0x1B)  /*< esp-tls use Secure Element returned failed */
+#ifdef CONFIG_ESP_TLS_USING_MBEDTLS
+#define ESP_TLS_ERR_SSL_WANT_READ                          MBEDTLS_ERR_SSL_WANT_READ
+#define ESP_TLS_ERR_SSL_WANT_WRITE                         MBEDTLS_ERR_SSL_WANT_WRITE
+#define ESP_TLS_ERR_SSL_TIMEOUT                            MBEDTLS_ERR_SSL_TIMEOUT
+#elif CONFIG_ESP_TLS_USING_WOLFSSL /* CONFIG_ESP_TLS_USING_MBEDTLS */
+#define ESP_TLS_ERR_SSL_WANT_READ                          WOLFSSL_ERROR_WANT_READ
+#define ESP_TLS_ERR_SSL_WANT_WRITE                         WOLFSSL_ERROR_WANT_WRITE
+#define ESP_TLS_ERR_SSL_TIMEOUT                            WOLFSSL_CBIO_ERR_TIMEOUT
+#endif /*CONFIG_ESP_TLS_USING_WOLFSSL */
+typedef struct wb_esp_tls_last_error* wb_esp_tls_error_handle_t;
+
+/**
+*  @brief Error structure containing relevant errors in case tls error occurred
+*/
+typedef struct wb_esp_tls_last_error {
+    esp_err_t last_error;               /*!< error code (based on SIM_ESP_ERR_ESP_TLS_BASE) of the last occurred error */
+    int       esp_tls_error_code;       /*!< esp_tls error code from last esp_tls failed api */
+    int       esp_tls_flags;            /*!< last certification verification flags */
+} esp_tls_last_error_t;
+
+/**
+ *  @brief ESP-TLS Connection State
+ */
+typedef enum esp_tls_conn_state {
+    ESP_TLS_INIT = 0,
+    ESP_TLS_CONNECTING,
+    ESP_TLS_HANDSHAKE,
+    ESP_TLS_FAIL,
+    ESP_TLS_DONE,
+} esp_tls_conn_state_t;
+
+typedef enum esp_tls_role {
+    ESP_TLS_CLIENT = 0,
+    ESP_TLS_SERVER,
+} esp_tls_role_t;
+
+/**
+ *  @brief ESP-TLS preshared key and hint structure
+ */
+typedef struct psk_key_hint {
+    const uint8_t* key;                     /*!< key in PSK authentication mode in binary format */
+    const size_t   key_size;                /*!< length of the key */
+    const char* hint;                       /*!< hint in PSK authentication mode in string format */
+} psk_hint_key_t;
+
+/**
+ * @brief      ESP-TLS configuration parameters
+ *
+ * @note       Note about format of certificates:
+ *             - This structure includes certificates of a Certificate Authority, of client or server as well
+ *             as private keys, which may be of PEM or DER format. In case of PEM format, the buffer must be
+ *             NULL terminated (with NULL character included in certificate size).
+ *             - Certificate Authority's certificate may be a chain of certificates in case of PEM format,
+ *             but could be only one certificate in case of DER format
+ *             - Variables names of certificates and private key buffers and sizes are defined as unions providing
+ *             backward compatibility for legacy *_pem_buf and *_pem_bytes names which suggested only PEM format
+ *             was supported. It is encouraged to use generic names such as cacert_buf and cacert_bytes.
+ */
+typedef struct esp_tls_cfg {
+    const char **alpn_protos;               /*!< Application protocols required for HTTP2.
+                                                 If HTTP2/ALPN support is required, a list
+                                                 of protocols that should be negotiated.
+                                                 The format is length followed by protocol
+                                                 name.
+                                                 For the most common cases the following is ok:
+                                                 const char **alpn_protos = { "h2", NULL };
+                                                 - where 'h2' is the protocol name */
+
+    union {
+    const unsigned char *cacert_buf;        /*!< Certificate Authority's certificate in a buffer.
+                                                 Format may be PEM or DER, depending on mbedtls-support
+                                                 This buffer should be NULL terminated in case of PEM */
+    const unsigned char *cacert_pem_buf;    /*!< CA certificate buffer legacy name */
+    };
+
+    union {
+    unsigned int cacert_bytes;              /*!< Size of Certificate Authority certificate
+                                                 pointed to by cacert_buf
+                                                 (including NULL-terminator in case of PEM format) */
+    unsigned int cacert_pem_bytes;          /*!< Size of Certificate Authority certificate legacy name */
+    };
+
+    union {
+    const unsigned char *clientcert_buf;    /*!< Client certificate in a buffer
+                                                 Format may be PEM or DER, depending on mbedtls-support
+                                                 This buffer should be NULL terminated in case of PEM */
+    const unsigned char *clientcert_pem_buf;     /*!< Client certificate legacy name */
+    };
+
+    union {
+    unsigned int clientcert_bytes;          /*!< Size of client certificate pointed to by
+                                                 clientcert_pem_buf
+                                                 (including NULL-terminator in case of PEM format) */
+    unsigned int clientcert_pem_bytes;      /*!< Size of client certificate legacy name */
+    };
+
+    union {
+    const unsigned char *clientkey_buf;     /*!< Client key in a buffer
+                                                 Format may be PEM or DER, depending on mbedtls-support
+                                                 This buffer should be NULL terminated in case of PEM */
+    const unsigned char *clientkey_pem_buf; /*!< Client key legacy name */
+    };
+
+    union {
+    unsigned int clientkey_bytes;           /*!< Size of client key pointed to by
+                                                 clientkey_pem_buf
+                                                 (including NULL-terminator in case of PEM format) */
+    unsigned int clientkey_pem_bytes;       /*!< Size of client key legacy name */
+    };
+
+    const unsigned char *clientkey_password;/*!< Client key decryption password string */
+
+    unsigned int clientkey_password_len;    /*!< String length of the password pointed to by
+                                                 clientkey_password */
+
+    bool non_block;                         /*!< Configure non-blocking mode. If set to true the
+                                                 underneath socket will be configured in non
+                                                 blocking mode after tls session is established */
+
+    bool use_secure_element;                /*!< Enable this option to use secure element or
+                                                 atecc608a chip ( Integrated with ESP32-WROOM-32SE ) */
+
+    int timeout_ms;                         /*!< Network timeout in milliseconds */
+
+    bool use_global_ca_store;               /*!< Use a global ca_store for all the connections in which
+                                                 this bool is set. */
+
+    const char *common_name;                /*!< If non-NULL, server certificate CN must match this name.
+                                                 If NULL, server certificate CN must match hostname. */
+
+    bool skip_common_name;                  /*!< Skip any validation of server certificate CN field */
+
+    const psk_hint_key_t* psk_hint_key;     /*!< Pointer to PSK hint and key. if not NULL (and certificates are NULL)
+                                                 then PSK authentication is enabled with configured setup.
+                                                 Important note: the pointer must be valid for connection */
+
+    esp_err_t (*crt_bundle_attach)(void *conf);
+                                            /*!< Function pointer to esp_crt_bundle_attach. Enables the use of certification
+                                                 bundle for server verification, must be enabled in menuconfig */
+
+} esp_tls_cfg_t;
+
+#ifdef CONFIG_ESP_TLS_SERVER
+typedef struct esp_tls_cfg_server {
+    const char **alpn_protos;                   /*!< Application protocols required for HTTP2.
+                                                     If HTTP2/ALPN support is required, a list
+                                                     of protocols that should be negotiated.
+                                                     The format is length followed by protocol
+                                                     name.
+                                                     For the most common cases the following is ok:
+                                                     const char **alpn_protos = { "h2", NULL };
+                                                     - where 'h2' is the protocol name */
+
+    union {
+    const unsigned char *cacert_buf;        /*!< Client CA certificate in a buffer.
+                                                     This buffer should be NULL terminated */
+    const unsigned char *cacert_pem_buf;    /*!< Client CA certificate legacy name */
+    };
+
+    union {
+    unsigned int cacert_bytes;              /*!< Size of client CA certificate
+                                                     pointed to by cacert_pem_buf */
+    unsigned int cacert_pem_bytes;          /*!< Size of client CA certificate legacy name */
+    };
+
+    union {
+    const unsigned char *servercert_buf;        /*!< Server certificate in a buffer
+                                                     This buffer should be NULL terminated */
+    const unsigned char *servercert_pem_buf;    /*!< Server certificate legacy name */
+    };
+
+    union {
+    unsigned int servercert_bytes;             /*!< Size of server certificate pointed to by
+                                                     servercert_pem_buf */
+    unsigned int servercert_pem_bytes;          /*!< Size of server certificate legacy name */
+    };
+
+    union {
+    const unsigned char *serverkey_buf;         /*!< Server key in a buffer
+                                                     This buffer should be NULL terminated */
+    const unsigned char *serverkey_pem_buf;     /*!< Server key legacy name */
+    };
+
+    union {
+    unsigned int serverkey_bytes;               /*!< Size of server key pointed to by
+                                                     serverkey_pem_buf */
+    unsigned int serverkey_pem_bytes;           /*!< Size of server key legacy name */
+    };
+
+    const unsigned char *serverkey_password;    /*!< Server key decryption password string */
+
+    unsigned int serverkey_password_len;        /*!< String length of the password pointed to by
+                                                     serverkey_password */
+
+} esp_tls_cfg_server_t;
+#endif /* ! CONFIG_ESP_TLS_SERVER */
+
+/**
+ * @brief      ESP-TLS Connection Handle
+ */
+typedef struct esp_tls {
+#ifdef CONFIG_ESP_TLS_USING_MBEDTLS
+    mbedtls_ssl_context ssl;                                                    /*!< TLS/SSL context */
+
+    mbedtls_entropy_context entropy;                                            /*!< mbedTLS entropy context structure */
+
+    mbedtls_ctr_drbg_context ctr_drbg;                                          /*!< mbedTLS ctr drbg context structure.
+                                                                                     CTR_DRBG is deterministic random
+                                                                                     bit generation based on AES-256 */
+
+    mbedtls_ssl_config conf;                                                    /*!< TLS/SSL configuration to be shared
+                                                                                     between mbedtls_ssl_context
+                                                                                     structures */
+
+    mbedtls_net_context server_fd;                                              /*!< mbedTLS wrapper type for sockets */
+
+    mbedtls_x509_crt cacert;                                                    /*!< Container for the X.509 CA certificate */
+
+    mbedtls_x509_crt *cacert_ptr;                                               /*!< Pointer to the cacert being used. */
+
+    mbedtls_x509_crt clientcert;                                                /*!< Container for the X.509 client certificate */
+
+    mbedtls_pk_context clientkey;                                               /*!< Container for the private key of the client
+                                                                                     certificate */
+#ifdef CONFIG_ESP_TLS_SERVER
+    mbedtls_x509_crt servercert;                                                /*!< Container for the X.509 server certificate */
+
+    mbedtls_pk_context serverkey;                                               /*!< Container for the private key of the server
+                                                                                   certificate */
+#endif
+#elif CONFIG_ESP_TLS_USING_WOLFSSL
+    void *priv_ctx;
+    void *priv_ssl;
+#endif
+    int sockfd;                                                                 /*!< Underlying socket file descriptor. */
+
+    ssize_t (*s_read)(struct esp_tls  *tls, char *data, size_t datalen);          /*!< Callback function for reading data from TLS/SSL
+                                                                                     connection. */
+//     read_function read;
+
+    ssize_t (*s_write)(struct esp_tls *tls, const char *data, size_t datalen);    /*!< Callback function for writing data to TLS/SSL
+                                                                                     connection. */
+
+    esp_tls_conn_state_t  conn_state;                                           /*!< ESP-TLS Connection state */
+
+    fd_set rset;                                                                /*!< read file descriptors */
+
+    fd_set wset;                                                                /*!< write file descriptors */
+
+    bool is_tls;                                                                /*!< indicates connection type (TLS or NON-TLS) */
+
+    esp_tls_role_t role;                                                        /*!< esp-tls role
+                                                                                     - ESP_TLS_CLIENT
+                                                                                     - ESP_TLS_SERVER */
+
+    wb_esp_tls_error_handle_t error_handle;                                        /*!< handle to error descriptor */
+
+} esp_tls_t;
+//typedef ssize_t (*read_function)(struct esp_tls      *tls, char *data, size_t datalen);
+
+
+/**
+ * @brief      Create TLS connection
+ *
+ * This function allocates and initializes esp-tls structure handle.
+ *
+ * @return      tls     Pointer to esp-tls as esp-tls handle if successfully initialized,
+ *                      NULL if allocation error
+ */
+esp_tls_t *sim_esp_tls_init(void);
+
+
+
+
+/**
+ * @brief      Create a new blocking TLS/SSL connection
+ *
+ * This function establishes a TLS/SSL connection with the specified host in blocking manner.
+ *
+ * Note: This API is present for backward compatibility reasons. Alternative function
+ * with the same functionality is `sim_esp_tls_conn_new_sync` (and its asynchronous version
+ * `sim_esp_tls_conn_new_async`)
+ *
+ * @param[in]  hostname  Hostname of the host.
+ * @param[in]  hostlen   Length of hostname.
+ * @param[in]  port      Port number of the host.
+ * @param[in]  cfg       TLS configuration as esp_tls_cfg_t. If you wish to open
+ *                       non-TLS connection, keep this NULL. For TLS connection,
+ *                       a pass pointer to esp_tls_cfg_t. At a minimum, this
+ *                       structure should be zero-initialized.
+ *
+ * @return pointer to esp_tls_t, or NULL if connection couldn't be opened.
+ */
+esp_tls_t *sim_esp_tls_conn_new(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg)  __attribute__ ((deprecated));
+
+/**
+ * @brief      Create a new blocking TLS/SSL connection
+ *
+ * This function establishes a TLS/SSL connection with the specified host in blocking manner.
+ *
+ * @param[in]  hostname  Hostname of the host.
+ * @param[in]  hostlen   Length of hostname.
+ * @param[in]  port      Port number of the host.
+ * @param[in]  cfg       TLS configuration as esp_tls_cfg_t. If you wish to open
+ *                       non-TLS connection, keep this NULL. For TLS connection,
+ *                       a pass pointer to esp_tls_cfg_t. At a minimum, this
+ *                       structure should be zero-initialized.
+ * @param[in]  tls       Pointer to esp-tls as esp-tls handle.
+ *
+ * @return
+ *             - -1      If connection establishment fails.
+ *             -  1      If connection establishment is successful.
+ *             -  0      If connection state is in progress.
+ */
+int sim_esp_tls_conn_new_sync(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_t *tls);
+
+/**
+ * @brief      Create a new blocking TLS/SSL connection with a given "HTTP" url
+ *
+ * The behaviour is same as sim_esp_tls_conn_new() API. However this API accepts host's url.
+ *
+ * @param[in]  url  url of host.
+ * @param[in]  cfg  TLS configuration as esp_tls_cfg_t. If you wish to open
+ *                  non-TLS connection, keep this NULL. For TLS connection,
+ *                  a pass pointer to 'esp_tls_cfg_t'. At a minimum, this
+ *                  structure should be zero-initialized.
+ * @return pointer to esp_tls_t, or NULL if connection couldn't be opened.
+ */
+esp_tls_t *sim_esp_tls_conn_http_new(const char *url, const esp_tls_cfg_t *cfg);
+
+/**
+ * @brief      Create a new non-blocking TLS/SSL connection
+ *
+ * This function initiates a non-blocking TLS/SSL connection with the specified host, but due to
+ * its non-blocking nature, it doesn't wait for the connection to get established.
+ *
+ * @param[in]  hostname  Hostname of the host.
+ * @param[in]  hostlen   Length of hostname.
+ * @param[in]  port      Port number of the host.
+ * @param[in]  cfg       TLS configuration as esp_tls_cfg_t. `non_block` member of
+ *                       this structure should be set to be true.
+ * @param[in]  tls       pointer to esp-tls as esp-tls handle.
+ *
+ * @return
+ *             - -1      If connection establishment fails.
+ *             -  0      If connection establishment is in progress.
+ *             -  1      If connection establishment is successful.
+ */
+int sim_esp_tls_conn_new_async(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_t *tls);
+
+/**
+ * @brief      Create a new non-blocking TLS/SSL connection with a given "HTTP" url
+ *
+ * The behaviour is same as sim_esp_tls_conn_new() API. However this API accepts host's url.
+ *
+ * @param[in]  url     url of host.
+ * @param[in]  cfg     TLS configuration as esp_tls_cfg_t.
+ * @param[in]  tls     pointer to esp-tls as esp-tls handle.
+ *
+ * @return
+ *             - -1     If connection establishment fails.
+ *             -  0     If connection establishment is in progress.
+ *             -  1     If connection establishment is successful.
+ */
+int sim_esp_tls_conn_http_new_async(const char *url, const esp_tls_cfg_t *cfg, esp_tls_t *tls);
+
+/**
+ * @brief      Write from buffer 'data' into specified tls connection.
+ *
+ * @param[in]  tls      pointer to esp-tls as esp-tls handle.
+ * @param[in]  data     Buffer from which data will be written.
+ * @param[in]  datalen  Length of data buffer.
+ *
+ * @return
+ *             - >=0  if write operation was successful, the return value is the number
+ *                   of bytes actually written to the TLS/SSL connection.
+ *             - <0  if write operation was not successful, because either an
+ *                   error occured or an action must be taken by the calling process.
+ */
+ssize_t sim_esp_tls_conn_write(esp_tls_t *tls, const void *data, size_t datalen);
+//{
+  //  return tls->write(tls, (char *)data, datalen);
+//}
+
+/**
+ * @brief      Read from specified tls connection into the buffer 'data'.
+ *
+ * @param[in]  tls      pointer to esp-tls as esp-tls handle.
+ * @param[in]  data     Buffer to hold read data.
+ * @param[in]  datalen  Length of data buffer.
+ *
+ * @return
+ *             - >0  if read operation was successful, the return value is the number
+ *                   of bytes actually read from the TLS/SSL connection.
+ *             -  0  if read operation was not successful. The underlying
+ *                   connection was closed.
+ *             - <0  if read operation was not successful, because either an
+ *                   error occured or an action must be taken by the calling process.
+ */
+ssize_t sim_esp_tls_conn_read(esp_tls_t *tls, void  *data, size_t datalen);
+//{
+//    return tls->read(tls, (char *)data, datalen);
+//}
+
+/**
+ * @brief      Compatible version of sim_esp_tls_conn_destroy() to close the TLS/SSL connection
+ *
+ * @note This API will be removed in IDFv5.0
+ *
+ * @param[in]  tls  pointer to esp-tls as esp-tls handle.
+ */
+void sim_esp_tls_conn_delete(esp_tls_t *tls);
+
+/**
+ * @brief      Close the TLS/SSL connection and free any allocated resources.
+ *
+ * This function should be called to close each tls connection opened with sim_esp_tls_conn_new() or
+ * sim_esp_tls_conn_http_new() APIs.
+ *
+ * @param[in]  tls  pointer to esp-tls as esp-tls handle.
+ *
+ * @return    - 0 on success
+ *            - -1 if socket error or an invalid argument
+ */
+int sim_esp_tls_conn_destroy(esp_tls_t *tls);
+
+/**
+ * @brief      Return the number of application data bytes remaining to be
+ *             read from the current record
+ *
+ * This API is a wrapper over mbedtls's mbedtls_ssl_get_bytes_avail() API.
+ *
+ * @param[in]  tls  pointer to esp-tls as esp-tls handle.
+ *
+ * @return
+ *            - -1  in case of invalid arg
+ *            - bytes available in the application data
+ *              record read buffer
+ */
+ssize_t sim_esp_tls_get_bytes_avail(esp_tls_t *tls);
+
+/**
+ * @brief       Returns the connection socket file descriptor from esp_tls session
+ *
+ * @param[in]   tls          handle to esp_tls context
+ *
+ * @param[out]  sockfd       int pointer to sockfd value.
+ *
+ * @return     - ESP_OK on success and value of sockfd will be updated with socket file descriptor for connection
+ *             - ESP_ERR_INVALID_ARG if (tls == NULL || sockfd == NULL)
+ */
+esp_err_t sim_esp_tls_get_conn_sockfd(esp_tls_t *tls, int *sockfd);
+
+/**
+ * @brief      Create a global CA store, initially empty.
+ *
+ * This function should be called if the application wants to use the same CA store for multiple connections.
+ * This function initialises the global CA store which can be then set by calling sim_esp_tls_set_global_ca_store().
+ * To be effective, this function must be called before any call to sim_esp_tls_set_global_ca_store().
+ *
+ * @return
+ *             - ESP_OK             if creating global CA store was successful.
+ *             - ESP_ERR_NO_MEM     if an error occured when allocating the mbedTLS resources.
+ */
+esp_err_t sim_esp_tls_init_global_ca_store(void);
+
+/**
+ * @brief      Set the global CA store with the buffer provided in pem format.
+ *
+ * This function should be called if the application wants to set the global CA store for
+ * multiple connections i.e. to add the certificates in the provided buffer to the certificate chain.
+ * This function implicitly calls sim_esp_tls_init_global_ca_store() if it has not already been called.
+ * The application must call this function before calling sim_esp_tls_conn_new().
+ *
+ * @param[in]  cacert_pem_buf    Buffer which has certificates in pem format. This buffer
+ *                               is used for creating a global CA store, which can be used
+ *                               by other tls connections.
+ * @param[in]  cacert_pem_bytes  Length of the buffer.
+ *
+ * @return
+ *             - ESP_OK  if adding certificates was successful.
+ *             - Other   if an error occured or an action must be taken by the calling process.
+ */
+esp_err_t sim_esp_tls_set_global_ca_store(const unsigned char *cacert_pem_buf, const unsigned int cacert_pem_bytes);
+
+/**
+ * @brief      Free the global CA store currently being used.
+ *
+ * The memory being used by the global CA store to store all the parsed certificates is
+ * freed up. The application can call this API if it no longer needs the global CA store.
+ */
+void sim_esp_tls_free_global_ca_store(void);
+
+/**
+ * @brief      Returns last error in esp_tls with detailed mbedtls related error codes.
+ *             The error information is cleared internally upon return
+ *
+ * @param[in]  h              esp-tls error handle.
+ * @param[out] esp_tls_code   last error code returned from mbedtls api (set to zero if none)
+ *                            This pointer could be NULL if caller does not care about esp_tls_code
+ * @param[out] esp_tls_flags  last certification verification flags (set to zero if none)
+ *                            This pointer could be NULL if caller does not care about esp_tls_code
+ *
+ * @return
+ *            - ESP_ERR_INVALID_STATE if invalid parameters
+ *            - ESP_OK (0) if no error occurred
+ *            - specific error code (based on SIM_ESP_ERR_ESP_TLS_BASE) otherwise
+ */
+esp_err_t sim_esp_tls_get_and_clear_last_error(wb_esp_tls_error_handle_t h, int *esp_tls_code, int *esp_tls_flags);
+
+//#if CONFIG_ESP_TLS_USING_MBEDTLS
+/**
+ * @brief      Get the pointer to the global CA store currently being used.
+ *
+ * The application must first call sim_esp_tls_set_global_ca_store(). Then the same
+ * CA store could be used by the application for APIs other than esp_tls.
+ *
+ * @note       Modifying the pointer might cause a failure in verifying the certificates.
+ *
+ * @return
+ *             - Pointer to the global CA store currently being used    if successful.
+ *             - NULL                                                   if there is no global CA store set.
+ */
+mbedtls_x509_crt *sim_esp_tls_get_global_ca_store(void);
+
+//#endif /* CONFIG_ESP_TLS_USING_MBEDTLS */
+#ifdef CONFIG_ESP_TLS_SERVER
+/**
+ * @brief      Create TLS/SSL server session
+ *
+ * This function creates a TLS/SSL server context for already accepted client connection
+ * and performs TLS/SSL handshake with the client
+ *
+ * @param[in]  cfg      Pointer to esp_tls_cfg_server_t
+ * @param[in]  sockfd   FD of accepted connection
+ * @param[out] tls      Pointer to allocated esp_tls_t
+ *
+ * @return
+ *          - 0  if successful
+ *          - <0 in case of error
+ *
+ */
+int sim_esp_tls_server_session_create(esp_tls_cfg_server_t *cfg, int sockfd, esp_tls_t *tls);
+
+/**
+ * @brief      Close the server side TLS/SSL connection and free any allocated resources.
+ *
+ * This function should be called to close each tls connection opened with sim_esp_tls_server_session_create()
+ *
+ * @param[in]  tls  pointer to esp_tls_t
+ */
+void sim_esp_tls_server_session_delete(esp_tls_t *tls);
+#endif /* ! CONFIG_ESP_TLS_SERVER */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ! _ESP_TLS_H_ */
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/task.h b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/task.h
new file mode 100644 (file)
index 0000000..2448342
--- /dev/null
@@ -0,0 +1,2249 @@
+#ifndef INC_TASK_H
+#define INC_TASK_H
+
+//#ifndef INC_FREERTOS_H
+//     #error "include FreeRTOS.h must appear in source files before include task.h"
+//#endif
+
+#include <limits.h>
+#include "osa_old_api.h"
+
+//#include "list.h"
+//#include "portmacro.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define vTaskDelay(a)   OSATaskSleep(a)
+/*-----------------------------------------------------------
+ * MACROS AND DEFINITIONS
+ *----------------------------------------------------------*/
+
+#define tskKERNEL_VERSION_NUMBER "V8.2.0"
+#define tskKERNEL_VERSION_MAJOR 8
+#define tskKERNEL_VERSION_MINOR 2
+#define tskKERNEL_VERSION_BUILD 0
+
+/**
+ * @brief Argument of xTaskCreatePinnedToCore indicating that task has no affinity
+ */
+#define tskNO_AFFINITY INT_MAX
+
+/**
+ * task. h
+ *
+ * Type by which tasks are referenced.  For example, a call to xTaskCreate
+ * returns (via a pointer parameter) an TaskHandle_t variable that can then
+ * be used as a parameter to vTaskDelete to delete the task.
+ *
+ * \ingroup Tasks
+ */
+typedef void * TaskHandle_t;
+
+/**
+ * Defines the prototype to which the application task hook function must
+ * conform.
+ */
+typedef BaseType_t (*TaskHookFunction_t)( void * );
+
+/** Task states returned by eTaskGetState. */
+typedef enum
+{
+       eRunning = 0,   /*!< A task is querying the state of itself, so must be running. */
+       eReady,                 /*!< The task being queried is in a read or pending ready list. */
+       eBlocked,               /*!< The task being queried is in the Blocked state. */
+       eSuspended,             /*!< The task being queried is in the Suspended state, or is in the Blocked state with an infinite time out. */
+       eDeleted                /*!< The task being queried has been deleted, but its TCB has not yet been freed. */
+} eTaskState;
+
+/** Actions that can be performed when vTaskNotify() is called. */
+typedef enum
+{
+       eNoAction = 0,                          /*!< Notify the task without updating its notify value. */
+       eSetBits,                                       /*!< Set bits in the task's notification value. */
+       eIncrement,                                     /*!< Increment the task's notification value. */
+       eSetValueWithOverwrite,         /*!< Set the task's notification value to a specific value even if the previous value has not yet been read by the task. */
+       eSetValueWithoutOverwrite       /*!< Set the task's notification value if the previous value has been read by the task. */
+} eNotifyAction;
+
+/** @cond */
+/**
+ * Used internally only.
+ */
+typedef struct xTIME_OUT
+{
+       BaseType_t xOverflowCount;
+       TickType_t xTimeOnEntering;
+} TimeOut_t;
+
+/**
+ * Defines the memory ranges allocated to the task when an MPU is used.
+ */
+typedef struct xMEMORY_REGION
+{
+       void *pvBaseAddress;
+       uint32_t ulLengthInBytes;
+       uint32_t ulParameters;
+} MemoryRegion_t;
+
+/**
+ * Parameters required to create an MPU protected task.
+ */
+typedef struct xTASK_PARAMETERS
+{
+       TaskFunction_t pvTaskCode;
+       const char * const pcName;      /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+       uint32_t usStackDepth;
+       void *pvParameters;
+       UBaseType_t uxPriority;
+       StackType_t *puxStackBuffer;
+       MemoryRegion_t xRegions[ portNUM_CONFIGURABLE_REGIONS ];
+} TaskParameters_t;
+/** @endcond */
+
+/**
+ *  Used with the uxTaskGetSystemState() function to return the state of each task in the system.
+*/
+typedef struct xTASK_STATUS
+{
+       TaskHandle_t xHandle;                   /*!< The handle of the task to which the rest of the information in the structure relates. */
+       const char *pcTaskName;                 /*!< A pointer to the task's name.  This value will be invalid if the task was deleted since the structure was populated! */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+       UBaseType_t xTaskNumber;                /*!< A number unique to the task. */
+       eTaskState eCurrentState;               /*!< The state in which the task existed when the structure was populated. */
+       UBaseType_t uxCurrentPriority;  /*!< The priority at which the task was running (may be inherited) when the structure was populated. */
+       UBaseType_t uxBasePriority;             /*!< The priority to which the task will return if the task's current priority has been inherited to avoid unbounded priority inversion when obtaining a mutex.  Only valid if configUSE_MUTEXES is defined as 1 in FreeRTOSConfig.h. */
+       uint32_t ulRunTimeCounter;              /*!< The total run time allocated to the task so far, as defined by the run time stats clock.  See http://www.freertos.org/rtos-run-time-stats.html.  Only valid when configGENERATE_RUN_TIME_STATS is defined as 1 in FreeRTOSConfig.h. */
+       StackType_t *pxStackBase;               /*!< Points to the lowest address of the task's stack area. */
+       uint32_t usStackHighWaterMark;  /*!< The minimum amount of stack space that has remained for the task since the task was created.  The closer this value is to zero the closer the task has come to overflowing its stack. */
+#if configTASKLIST_INCLUDE_COREID
+       BaseType_t xCoreID;                             /*!< Core this task is pinned to. This field is present if CONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID is set. */
+#endif
+} TaskStatus_t;
+
+/**
+ * Used with the uxTaskGetSnapshotAll() function to save memory snapshot of each task in the system.
+ * We need this struct because TCB_t is defined (hidden) in tasks.c.
+ */
+typedef struct xTASK_SNAPSHOT
+{
+       void        *pxTCB;         /*!< Address of task control block. */
+       StackType_t *pxTopOfStack;  /*!< Points to the location of the last item placed on the tasks stack. */
+       StackType_t *pxEndOfStack;  /*!< Points to the end of the stack. pxTopOfStack < pxEndOfStack, stack grows hi2lo
+                                                                       pxTopOfStack > pxEndOfStack, stack grows lo2hi*/
+} TaskSnapshot_t;
+
+/**
+ * Possible return values for eTaskConfirmSleepModeStatus().
+ */
+typedef enum
+{
+       eAbortSleep = 0,                /*!< A task has been made ready or a context switch pended since portSUPPORESS_TICKS_AND_SLEEP() was called - abort entering a sleep mode. */
+       eStandardSleep,                 /*!< Enter a sleep mode that will not last any longer than the expected idle time. */
+       eNoTasksWaitingTimeout  /*!< No tasks are waiting for a timeout so it is safe to enter a sleep mode that can only be exited by an external interrupt. */
+} eSleepModeStatus;
+
+
+/**
+ * Defines the priority used by the idle task.  This must not be modified.
+ *
+ * \ingroup TaskUtils
+ */
+#define tskIDLE_PRIORITY                       ( ( UBaseType_t ) 0U )
+
+/**
+ * task. h
+ *
+ * Macro for forcing a context switch.
+ *
+ * \ingroup SchedulerControl
+ */
+#define taskYIELD()                                    portYIELD()
+
+/**
+ * task. h
+ *
+ * Macro to mark the start of a critical code region.  Preemptive context
+ * switches cannot occur when in a critical region.
+ *
+ * @note This may alter the stack (depending on the portable implementation)
+ * so must be used with care!
+ *
+ * \ingroup SchedulerControl
+ */
+#ifdef _ESP_FREERTOS_INTERNAL
+#define taskENTER_CRITICAL(mux)                portENTER_CRITICAL(mux)
+#else
+#define taskENTER_CRITICAL(mux) _Pragma("GCC warning \"'taskENTER_CRITICAL(mux)' is deprecated in ESP-IDF, consider using 'portENTER_CRITICAL(mux)'\"") portENTER_CRITICAL(mux)
+#endif
+#define taskENTER_CRITICAL_ISR(mux)            portENTER_CRITICAL_ISR(mux)
+
+/**
+ * task. h
+ *
+ * Macro to mark the end of a critical code region.  Preemptive context
+ * switches cannot occur when in a critical region.
+ *
+ * @note This may alter the stack (depending on the portable implementation)
+ * so must be used with care!
+ *
+ * \ingroup SchedulerControl
+ */
+#ifdef _ESP_FREERTOS_INTERNAL
+#define taskEXIT_CRITICAL(mux)                 portEXIT_CRITICAL(mux)
+#else
+#define taskEXIT_CRITICAL(mux) _Pragma("GCC warning \"'taskEXIT_CRITICAL(mux)' is deprecated in ESP-IDF, consider using 'portEXIT_CRITICAL(mux)'\"") portEXIT_CRITICAL(mux)
+#endif
+#define taskEXIT_CRITICAL_ISR(mux)             portEXIT_CRITICAL_ISR(mux)
+
+/**
+ * task. h
+ *
+ * Macro to disable all maskable interrupts.
+ *
+ * \ingroup SchedulerControl
+ */
+#define taskDISABLE_INTERRUPTS()       portDISABLE_INTERRUPTS()
+
+/**
+ * task. h
+ *
+ * Macro to enable microcontroller interrupts.
+ *
+ * \ingroup SchedulerControl
+ */
+#define taskENABLE_INTERRUPTS()                portENABLE_INTERRUPTS()
+
+/* Definitions returned by xTaskGetSchedulerState().  taskSCHEDULER_SUSPENDED is
+0 to generate more optimal code when configASSERT() is defined as the constant
+is used in assert() statements. */
+#define taskSCHEDULER_SUSPENDED                ( ( BaseType_t ) 0 )
+#define taskSCHEDULER_NOT_STARTED      ( ( BaseType_t ) 1 )
+#define taskSCHEDULER_RUNNING          ( ( BaseType_t ) 2 )
+
+
+/*-----------------------------------------------------------
+ * TASK CREATION API
+ *----------------------------------------------------------*/
+
+/**
+ * Create a new task with a specified affinity.
+ *
+ * This function is similar to xTaskCreate, but allows setting task affinity
+ * in SMP system.
+ *
+ * @param pvTaskCode Pointer to the task entry function.  Tasks
+ * must be implemented to never return (i.e. continuous loop).
+ *
+ * @param pcName A descriptive name for the task.  This is mainly used to
+ * facilitate debugging.  Max length defined by configMAX_TASK_NAME_LEN - default
+ * is 16.
+ *
+ * @param usStackDepth The size of the task stack specified as the number of
+ * bytes. Note that this differs from vanilla FreeRTOS.
+ *
+ * @param pvParameters Pointer that will be used as the parameter for the task
+ * being created.
+ *
+ * @param uxPriority The priority at which the task should run.  Systems that
+ * include MPU support can optionally create tasks in a privileged (system)
+ * mode by setting bit portPRIVILEGE_BIT of the priority parameter.  For
+ * example, to create a privileged task at priority 2 the uxPriority parameter
+ * should be set to ( 2 | portPRIVILEGE_BIT ).
+ *
+ * @param pvCreatedTask Used to pass back a handle by which the created task
+ * can be referenced.
+ *
+ * @param xCoreID If the value is tskNO_AFFINITY, the created task is not
+ * pinned to any CPU, and the scheduler can run it on any core available.
+ * Other values indicate the index number of the CPU which the task should
+ * be pinned to. Specifying values larger than (portNUM_PROCESSORS - 1) will
+ * cause the function to fail.
+ *
+ * @return pdPASS if the task was successfully created and added to a ready
+ * list, otherwise an error code defined in the file projdefs.h
+ *
+ * \ingroup Tasks
+ */
+#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
+       BaseType_t xTaskCreatePinnedToCore(     TaskFunction_t pvTaskCode,
+                                                                               const char * const pcName,
+                                                                               const uint32_t usStackDepth,
+                                                                               void * const pvParameters,
+                                                                               UBaseType_t uxPriority,
+                                                                               TaskHandle_t * const pvCreatedTask,
+                                                                               const BaseType_t xCoreID);
+
+#endif
+
+/**
+ * Create a new task and add it to the list of tasks that are ready to run.
+ *
+ * Internally, within the FreeRTOS implementation, tasks use two blocks of
+ * memory.  The first block is used to hold the task's data structures.  The
+ * second block is used by the task as its stack.  If a task is created using
+ * xTaskCreate() then both blocks of memory are automatically dynamically
+ * allocated inside the xTaskCreate() function.  (see
+ * http://www.freertos.org/a00111.html).  If a task is created using
+ * xTaskCreateStatic() then the application writer must provide the required
+ * memory.  xTaskCreateStatic() therefore allows a task to be created without
+ * using any dynamic memory allocation.
+ *
+ * See xTaskCreateStatic() for a version that does not use any dynamic memory
+ * allocation.
+ *
+ * xTaskCreate() can only be used to create a task that has unrestricted
+ * access to the entire microcontroller memory map.  Systems that include MPU
+ * support can alternatively create an MPU constrained task using
+ * xTaskCreateRestricted().
+ *
+ * @param pvTaskCode Pointer to the task entry function.  Tasks
+ * must be implemented to never return (i.e. continuous loop).
+ *
+ * @param pcName A descriptive name for the task.  This is mainly used to
+ * facilitate debugging.  Max length defined by configMAX_TASK_NAME_LEN - default
+ * is 16.
+ *
+ * @param usStackDepth The size of the task stack specified as the number of
+ * bytes. Note that this differs from vanilla FreeRTOS.
+ *
+ * @param pvParameters Pointer that will be used as the parameter for the task
+ * being created.
+ *
+ * @param uxPriority The priority at which the task should run.  Systems that
+ * include MPU support can optionally create tasks in a privileged (system)
+ * mode by setting bit portPRIVILEGE_BIT of the priority parameter.  For
+ * example, to create a privileged task at priority 2 the uxPriority parameter
+ * should be set to ( 2 | portPRIVILEGE_BIT ).
+ *
+ * @param pvCreatedTask Used to pass back a handle by which the created task
+ * can be referenced.
+ *
+ * @return pdPASS if the task was successfully created and added to a ready
+ * list, otherwise an error code defined in the file projdefs.h
+ *
+ * @note If program uses thread local variables (ones specified with "__thread" keyword)
+ * then storage for them will be allocated on the task's stack.
+ *
+ * Example usage:
+ * @code{c}
+ *  // Task to be created.
+ *  void vTaskCode( void * pvParameters )
+ *  {
+ *   for( ;; )
+ *   {
+ *       // Task code goes here.
+ *   }
+ *  }
+ *
+ *  // Function that creates a task.
+ *  void vOtherFunction( void )
+ *  {
+ *  static uint8_t ucParameterToPass;
+ *  TaskHandle_t xHandle = NULL;
+ *
+ *   // Create the task, storing the handle.  Note that the passed parameter ucParameterToPass
+ *   // must exist for the lifetime of the task, so in this case is declared static.  If it was just an
+ *   // an automatic stack variable it might no longer exist, or at least have been corrupted, by the time
+ *   // the new task attempts to access it.
+ *   xTaskCreate( vTaskCode, "NAME", STACK_SIZE, &ucParameterToPass, tskIDLE_PRIORITY, &xHandle );
+ *      configASSERT( xHandle );
+ *
+ *   // Use the handle to delete the task.
+ *      if( xHandle != NULL )
+ *      {
+ *       vTaskDelete( xHandle );
+ *      }
+ *  }
+ * @endcode
+ * \ingroup Tasks
+ */
+
+#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
+
+       static inline IRAM_ATTR BaseType_t xTaskCreate(
+                       TaskFunction_t pvTaskCode,
+                       const char * const pcName,
+                       const uint32_t usStackDepth,
+                       void * const pvParameters,
+                       UBaseType_t uxPriority,
+                       TaskHandle_t * const pvCreatedTask)
+       {
+               return xTaskCreatePinnedToCore( pvTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pvCreatedTask, tskNO_AFFINITY );
+       }
+
+#endif
+
+
+
+
+/**
+ * Create a new task with a specified affinity.
+ *
+ * This function is similar to xTaskCreateStatic, but allows specifying
+ * task affinity in an SMP system.
+ *
+ * @param pvTaskCode Pointer to the task entry function.  Tasks
+ * must be implemented to never return (i.e. continuous loop).
+ *
+ * @param pcName A descriptive name for the task.  This is mainly used to
+ * facilitate debugging.  The maximum length of the string is defined by
+ * configMAX_TASK_NAME_LEN in FreeRTOSConfig.h.
+ *
+ * @param ulStackDepth The size of the task stack specified as the number of
+ * bytes. Note that this differs from vanilla FreeRTOS.
+ *
+ * @param pvParameters Pointer that will be used as the parameter for the task
+ * being created.
+ *
+ * @param uxPriority The priority at which the task will run.
+ *
+ * @param pxStackBuffer Must point to a StackType_t array that has at least
+ * ulStackDepth indexes - the array will then be used as the task's stack,
+ * removing the need for the stack to be allocated dynamically.
+ *
+ * @param pxTaskBuffer Must point to a variable of type StaticTask_t, which will
+ * then be used to hold the task's data structures, removing the need for the
+ * memory to be allocated dynamically.
+ *
+ * @param xCoreID If the value is tskNO_AFFINITY, the created task is not
+ * pinned to any CPU, and the scheduler can run it on any core available.
+ * Other values indicate the index number of the CPU which the task should
+ * be pinned to. Specifying values larger than (portNUM_PROCESSORS - 1) will
+ * cause the function to fail.
+ *
+ * @return If neither pxStackBuffer or pxTaskBuffer are NULL, then the task will
+ * be created and pdPASS is returned.  If either pxStackBuffer or pxTaskBuffer
+ * are NULL then the task will not be created and
+ * errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY is returned.
+ *
+ * \ingroup Tasks
+ */
+#if( configSUPPORT_STATIC_ALLOCATION == 1 )
+       TaskHandle_t xTaskCreateStaticPinnedToCore(     TaskFunction_t pvTaskCode,
+                                                                                               const char * const pcName,
+                                                                                               const uint32_t ulStackDepth,
+                                                                                               void * const pvParameters,
+                                                                                               UBaseType_t uxPriority,
+                                                                                               StackType_t * const pxStackBuffer,
+                                                                                               StaticTask_t * const pxTaskBuffer,
+                                                                                               const BaseType_t xCoreID );
+#endif /* configSUPPORT_STATIC_ALLOCATION */
+
+/**
+ * Create a new task and add it to the list of tasks that are ready to run.
+ *
+ * Internally, within the FreeRTOS implementation, tasks use two blocks of
+ * memory.  The first block is used to hold the task's data structures.  The
+ * second block is used by the task as its stack.  If a task is created using
+ * xTaskCreate() then both blocks of memory are automatically dynamically
+ * allocated inside the xTaskCreate() function.  (see
+ * http://www.freertos.org/a00111.html).  If a task is created using
+ * xTaskCreateStatic() then the application writer must provide the required
+ * memory.  xTaskCreateStatic() therefore allows a task to be created without
+ * using any dynamic memory allocation.
+ *
+ * @param pvTaskCode Pointer to the task entry function.  Tasks
+ * must be implemented to never return (i.e. continuous loop).
+ *
+ * @param pcName A descriptive name for the task.  This is mainly used to
+ * facilitate debugging.  The maximum length of the string is defined by
+ * configMAX_TASK_NAME_LEN in FreeRTOSConfig.h.
+ *
+ * @param ulStackDepth The size of the task stack specified as the number of
+ * bytes. Note that this differs from vanilla FreeRTOS.
+ *
+ * @param pvParameters Pointer that will be used as the parameter for the task
+ * being created.
+ *
+ * @param uxPriority The priority at which the task will run.
+ *
+ * @param pxStackBuffer Must point to a StackType_t array that has at least
+ * ulStackDepth indexes - the array will then be used as the task's stack,
+ * removing the need for the stack to be allocated dynamically.
+ *
+ * @param pxTaskBuffer Must point to a variable of type StaticTask_t, which will
+ * then be used to hold the task's data structures, removing the need for the
+ * memory to be allocated dynamically.
+ *
+ * @return If neither pxStackBuffer or pxTaskBuffer are NULL, then the task will
+ * be created and pdPASS is returned.  If either pxStackBuffer or pxTaskBuffer
+ * are NULL then the task will not be created and
+ * errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY is returned.
+ *
+ * @note If program uses thread local variables (ones specified with "__thread" keyword)
+ * then storage for them will be allocated on the task's stack.
+ *
+ * Example usage:
+ * @code{c}
+ *
+ *     // Dimensions the buffer that the task being created will use as its stack.
+ *     // NOTE:  This is the number of bytes the stack will hold, not the number of
+ *     // words as found in vanilla FreeRTOS.
+ *     #define STACK_SIZE 200
+ *
+ *     // Structure that will hold the TCB of the task being created.
+ *     StaticTask_t xTaskBuffer;
+ *
+ *     // Buffer that the task being created will use as its stack.  Note this is
+ *     // an array of StackType_t variables.  The size of StackType_t is dependent on
+ *     // the RTOS port.
+ *     StackType_t xStack[ STACK_SIZE ];
+ *
+ *     // Function that implements the task being created.
+ *     void vTaskCode( void * pvParameters )
+ *     {
+ *         // The parameter value is expected to be 1 as 1 is passed in the
+ *         // pvParameters value in the call to xTaskCreateStatic().
+ *         configASSERT( ( uint32_t ) pvParameters == 1UL );
+ *
+ *         for( ;; )
+ *         {
+ *             // Task code goes here.
+ *         }
+ *     }
+ *
+ *     // Function that creates a task.
+ *     void vOtherFunction( void )
+ *     {
+ *         TaskHandle_t xHandle = NULL;
+ *
+ *         // Create the task without using any dynamic memory allocation.
+ *         xHandle = xTaskCreateStatic(
+ *                       vTaskCode,       // Function that implements the task.
+ *                       "NAME",          // Text name for the task.
+ *                       STACK_SIZE,      // Stack size in bytes, not words.
+ *                       ( void * ) 1,    // Parameter passed into the task.
+ *                       tskIDLE_PRIORITY,// Priority at which the task is created.
+ *                       xStack,          // Array to use as the task's stack.
+ *                       &xTaskBuffer );  // Variable to hold the task's data structure.
+ *
+ *         // puxStackBuffer and pxTaskBuffer were not NULL, so the task will have
+ *         // been created, and xHandle will be the task's handle.  Use the handle
+ *         // to suspend the task.
+ *         vTaskSuspend( xHandle );
+ *     }
+ * @endcode
+ * \ingroup Tasks
+ */
+
+#if( configSUPPORT_STATIC_ALLOCATION == 1 )
+       static inline IRAM_ATTR TaskHandle_t xTaskCreateStatic(
+                       TaskFunction_t pvTaskCode,
+                       const char * const pcName,
+                       const uint32_t ulStackDepth,
+                       void * const pvParameters,
+                       UBaseType_t uxPriority,
+                       StackType_t * const pxStackBuffer,
+                       StaticTask_t * const pxTaskBuffer)
+       {
+               return xTaskCreateStaticPinnedToCore( pvTaskCode, pcName, ulStackDepth, pvParameters, uxPriority, pxStackBuffer, pxTaskBuffer, tskNO_AFFINITY );
+       }
+#endif /* configSUPPORT_STATIC_ALLOCATION */
+
+/** @cond */
+/**
+ * xTaskCreateRestricted() should only be used in systems that include an MPU
+ * implementation.
+ *
+ * Create a new task and add it to the list of tasks that are ready to run.
+ * The function parameters define the memory regions and associated access
+ * permissions allocated to the task.
+ *
+ * @param pxTaskDefinition Pointer to a structure that contains a member
+ * for each of the normal xTaskCreate() parameters (see the xTaskCreate() API
+ * documentation) plus an optional stack buffer and the memory region
+ * definitions.
+ *
+ * @param pxCreatedTask Used to pass back a handle by which the created task
+ * can be referenced.
+ *
+ * @return pdPASS if the task was successfully created and added to a ready
+ * list, otherwise an error code defined in the file projdefs.h
+ *
+ * Example usage:
+ * @code{c}
+ * // Create an TaskParameters_t structure that defines the task to be created.
+ * static const TaskParameters_t xCheckTaskParameters =
+ * {
+ *     vATask,         // pvTaskCode - the function that implements the task.
+ *     "ATask",        // pcName - just a text name for the task to assist debugging.
+ *     100,            // usStackDepth - the stack size DEFINED IN BYTES.
+ *     NULL,           // pvParameters - passed into the task function as the function parameters.
+ *     ( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state.
+ *     cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack.
+ *
+ *     // xRegions - Allocate up to three separate memory regions for access by
+ *     // the task, with appropriate access permissions.  Different processors have
+ *     // different memory alignment requirements - refer to the FreeRTOS documentation
+ *     // for full information.
+ *     {
+ *             // Base address                                 Length  Parameters
+ *         { cReadWriteArray,                          32,             portMPU_REGION_READ_WRITE },
+ *         { cReadOnlyArray,                           32,             portMPU_REGION_READ_ONLY },
+ *         { cPrivilegedOnlyAccessArray,       128,    portMPU_REGION_PRIVILEGED_READ_WRITE }
+ *     }
+ * };
+ *
+ * int main( void )
+ * {
+ * TaskHandle_t xHandle;
+ *
+ *     // Create a task from the const structure defined above.  The task handle
+ *     // is requested (the second parameter is not NULL) but in this case just for
+ *     // demonstration purposes as its not actually used.
+ *     xTaskCreateRestricted( &xRegTest1Parameters, &xHandle );
+ *
+ *     // Start the scheduler.
+ *     vTaskStartScheduler();
+ *
+ *     // Will only get here if there was insufficient memory to create the idle
+ *     // and/or timer task.
+ *     for( ;; );
+ * }
+ * @endcode
+ * \ingroup Tasks
+ */
+#if( portUSING_MPU_WRAPPERS == 1 )
+       BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) PRIVILEGED_FUNCTION;
+#endif
+
+
+/**
+ * Memory regions are assigned to a restricted task when the task is created by
+ * a call to xTaskCreateRestricted().  These regions can be redefined using
+ * vTaskAllocateMPURegions().
+ *
+ * @param xTask The handle of the task being updated.
+ *
+ * @param xRegions A pointer to an MemoryRegion_t structure that contains the
+ * new memory region definitions.
+ *
+ * Example usage:
+ *
+ * @code{c}
+ * // Define an array of MemoryRegion_t structures that configures an MPU region
+ * // allowing read/write access for 1024 bytes starting at the beginning of the
+ * // ucOneKByte array.  The other two of the maximum 3 definable regions are
+ * // unused so set to zero.
+ * static const MemoryRegion_t xAltRegions[ portNUM_CONFIGURABLE_REGIONS ] =
+ * {
+ *     // Base address         Length          Parameters
+ *     { ucOneKByte,           1024,           portMPU_REGION_READ_WRITE },
+ *     { 0,                            0,                      0 },
+ *     { 0,                            0,                      0 }
+ * };
+ *
+ * void vATask( void *pvParameters )
+ * {
+ *     // This task was created such that it has access to certain regions of
+ *     // memory as defined by the MPU configuration.  At some point it is
+ *     // desired that these MPU regions are replaced with that defined in the
+ *     // xAltRegions const struct above.  Use a call to vTaskAllocateMPURegions()
+ *     // for this purpose.  NULL is used as the task handle to indicate that this
+ *     // function should modify the MPU regions of the calling task.
+ *     vTaskAllocateMPURegions( NULL, xAltRegions );
+ *
+ *     // Now the task can continue its function, but from this point on can only
+ *     // access its stack and the ucOneKByte array (unless any other statically
+ *     // defined or shared regions have been declared elsewhere).
+ * }
+ * @endcode
+ * \ingroup Tasks
+ */
+void vTaskAllocateMPURegions( TaskHandle_t xTask, const MemoryRegion_t * const pxRegions ) PRIVILEGED_FUNCTION;
+
+/** @endcond */
+
+/**
+ * Remove a task from the RTOS real time kernel's management.
+ *
+ * The task being deleted will be removed from all ready, blocked, suspended
+ * and event lists.
+ *
+ * INCLUDE_vTaskDelete must be defined as 1 for this function to be available.
+ * See the configuration section for more information.
+ *
+ * @note The idle task is responsible for freeing the kernel allocated
+ * memory from tasks that have been deleted.  It is therefore important that
+ * the idle task is not starved of microcontroller processing time if your
+ * application makes any calls to vTaskDelete ().  Memory allocated by the
+ * task code is not automatically freed, and should be freed before the task
+ * is deleted.
+ *
+ * See the demo application file death.c for sample code that utilises
+ * vTaskDelete ().
+ *
+ * @param xTaskToDelete The handle of the task to be deleted.  Passing NULL will
+ * cause the calling task to be deleted.
+ *
+ * Example usage:
+ * @code{c}
+ *  void vOtherFunction( void )
+ *  {
+ *  TaskHandle_t xHandle;
+ *
+ *      // Create the task, storing the handle.
+ *      xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );
+ *
+ *      // Use the handle to delete the task.
+ *      vTaskDelete( xHandle );
+ *  }
+ * @endcode
+ * \ingroup Tasks
+ */
+void vTaskDelete( TaskHandle_t xTaskToDelete ) PRIVILEGED_FUNCTION;
+
+/*-----------------------------------------------------------
+ * TASK CONTROL API
+ *----------------------------------------------------------*/
+
+/**
+ * Delay a task for a given number of ticks.
+ *
+ * The actual time that the task remains blocked depends on the tick rate.
+ * The constant portTICK_PERIOD_MS can be used to calculate real time from
+ * the tick rate - with the resolution of one tick period.
+ *
+ * INCLUDE_vTaskDelay must be defined as 1 for this function to be available.
+ * See the configuration section for more information.
+ *
+ * vTaskDelay() specifies a time at which the task wishes to unblock relative to
+ * the time at which vTaskDelay() is called.  For example, specifying a block
+ * period of 100 ticks will cause the task to unblock 100 ticks after
+ * vTaskDelay() is called.  vTaskDelay() does not therefore provide a good method
+ * of controlling the frequency of a periodic task as the path taken through the
+ * code, as well as other task and interrupt activity, will effect the frequency
+ * at which vTaskDelay() gets called and therefore the time at which the task
+ * next executes.  See vTaskDelayUntil() for an alternative API function designed
+ * to facilitate fixed frequency execution.  It does this by specifying an
+ * absolute time (rather than a relative time) at which the calling task should
+ * unblock.
+ *
+ * @param xTicksToDelay The amount of time, in tick periods, that
+ * the calling task should block.
+ *
+ * Example usage:
+ * @code{c}
+ *  void vTaskFunction( void * pvParameters )
+ *  {
+ *  // Block for 500ms.
+ *  const TickType_t xDelay = 500 / portTICK_PERIOD_MS;
+ *
+ *      for( ;; )
+ *      {
+ *              // Simply toggle the LED every 500ms, blocking between each toggle.
+ *              vToggleLED();
+ *              vTaskDelay( xDelay );
+ *      }
+ *  }
+ * @endcode
+ * \ingroup TaskCtrl
+ */
+void vTaskDelay( const TickType_t xTicksToDelay ) PRIVILEGED_FUNCTION;
+
+/**
+ * Delay a task until a specified time.
+ *
+ * INCLUDE_vTaskDelayUntil must be defined as 1 for this function to be available.
+ * See the configuration section for more information.
+ *
+ * This function can be used by periodic tasks to ensure a constant execution frequency.
+ *
+ * This function differs from vTaskDelay () in one important aspect:  vTaskDelay () will
+ * cause a task to block for the specified number of ticks from the time vTaskDelay () is
+ * called.  It is therefore difficult to use vTaskDelay () by itself to generate a fixed
+ * execution frequency as the time between a task starting to execute and that task
+ * calling vTaskDelay () may not be fixed [the task may take a different path though the
+ * code between calls, or may get interrupted or preempted a different number of times
+ * each time it executes].
+ *
+ * Whereas vTaskDelay () specifies a wake time relative to the time at which the function
+ * is called, vTaskDelayUntil () specifies the absolute (exact) time at which it wishes to
+ * unblock.
+ *
+ * The constant portTICK_PERIOD_MS can be used to calculate real time from the tick
+ * rate - with the resolution of one tick period.
+ *
+ * @param pxPreviousWakeTime Pointer to a variable that holds the time at which the
+ * task was last unblocked.  The variable must be initialised with the current time
+ * prior to its first use (see the example below).  Following this the variable is
+ * automatically updated within vTaskDelayUntil ().
+ *
+ * @param xTimeIncrement The cycle time period.  The task will be unblocked at
+ * time *pxPreviousWakeTime + xTimeIncrement.  Calling vTaskDelayUntil with the
+ * same xTimeIncrement parameter value will cause the task to execute with
+ * a fixed interface period.
+ *
+ * Example usage:
+ * @code{c}
+ *  // Perform an action every 10 ticks.
+ *  void vTaskFunction( void * pvParameters )
+ *  {
+ *  TickType_t xLastWakeTime;
+ *  const TickType_t xFrequency = 10;
+ *
+ *      // Initialise the xLastWakeTime variable with the current time.
+ *      xLastWakeTime = xTaskGetTickCount ();
+ *      for( ;; )
+ *      {
+ *              // Wait for the next cycle.
+ *              vTaskDelayUntil( &xLastWakeTime, xFrequency );
+ *
+ *              // Perform action here.
+ *      }
+ *  }
+ * @endcode
+ * \ingroup TaskCtrl
+ */
+void vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, const TickType_t xTimeIncrement ) PRIVILEGED_FUNCTION;
+
+/**
+ * Obtain the priority of any task.
+ *
+ * INCLUDE_uxTaskPriorityGet must be defined as 1 for this function to be available.
+ * See the configuration section for more information.
+ *
+ * @param xTask Handle of the task to be queried.  Passing a NULL
+ * handle results in the priority of the calling task being returned.
+ *
+ * @return The priority of xTask.
+ *
+ * Example usage:
+ * @code{c}
+ *  void vAFunction( void )
+ *  {
+ *  TaskHandle_t xHandle;
+ *
+ *   // Create a task, storing the handle.
+ *   xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );
+ *
+ *   // ...
+ *
+ *   // Use the handle to obtain the priority of the created task.
+ *   // It was created with tskIDLE_PRIORITY, but may have changed
+ *   // it itself.
+ *   if( uxTaskPriorityGet( xHandle ) != tskIDLE_PRIORITY )
+ *   {
+ *       // The task has changed it's priority.
+ *   }
+ *
+ *   // ...
+ *
+ *   // Is our priority higher than the created task?
+ *   if( uxTaskPriorityGet( xHandle ) < uxTaskPriorityGet( NULL ) )
+ *   {
+ *       // Our priority (obtained using NULL handle) is higher.
+ *   }
+ * }
+ * @endcode
+ * \ingroup TaskCtrl
+ */
+UBaseType_t uxTaskPriorityGet( TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
+
+/**
+ * A version of uxTaskPriorityGet() that can be used from an ISR.
+ *
+ * @param xTask Handle of the task to be queried.  Passing a NULL
+ * handle results in the priority of the calling task being returned.
+ *
+ * @return The priority of xTask.
+ *
+ */
+UBaseType_t uxTaskPriorityGetFromISR( TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
+
+/**
+ * Obtain the state of any task.
+ *
+ * States are encoded by the eTaskState enumerated type.
+ *
+ * INCLUDE_eTaskGetState must be defined as 1 for this function to be available.
+ * See the configuration section for more information.
+ *
+ * @param xTask Handle of the task to be queried.
+ *
+ * @return The state of xTask at the time the function was called.  Note the
+ * state of the task might change between the function being called, and the
+ * functions return value being tested by the calling task.
+ */
+eTaskState eTaskGetState( TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
+
+/**
+ * Set the priority of any task.
+ *
+ * INCLUDE_vTaskPrioritySet must be defined as 1 for this function to be available.
+ * See the configuration section for more information.
+ *
+ * A context switch will occur before the function returns if the priority
+ * being set is higher than the currently executing task.
+ *
+ * @param xTask Handle to the task for which the priority is being set.
+ * Passing a NULL handle results in the priority of the calling task being set.
+ *
+ * @param uxNewPriority The priority to which the task will be set.
+ *
+ * Example usage:
+ * @code{c}
+ *  void vAFunction( void )
+ *  {
+ *  TaskHandle_t xHandle;
+ *
+ *   // Create a task, storing the handle.
+ *   xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );
+ *
+ *   // ...
+ *
+ *   // Use the handle to raise the priority of the created task.
+ *   vTaskPrioritySet( xHandle, tskIDLE_PRIORITY + 1 );
+ *
+ *   // ...
+ *
+ *   // Use a NULL handle to raise our priority to the same value.
+ *   vTaskPrioritySet( NULL, tskIDLE_PRIORITY + 1 );
+ *  }
+ * @endcode
+ * \ingroup TaskCtrl
+ */
+void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority ) PRIVILEGED_FUNCTION;
+
+/**
+ * Suspend a task.
+ *
+ * INCLUDE_vTaskSuspend must be defined as 1 for this function to be available.
+ * See the configuration section for more information.
+ *
+ * When suspended, a task will never get any microcontroller processing time,
+ * no matter what its priority.
+ *
+ * Calls to vTaskSuspend are not accumulative -
+ * i.e. calling vTaskSuspend () twice on the same task still only requires one
+ * call to vTaskResume () to ready the suspended task.
+ *
+ * @param xTaskToSuspend Handle to the task being suspended.  Passing a NULL
+ * handle will cause the calling task to be suspended.
+ *
+ * Example usage:
+ * @code{c}
+ *  void vAFunction( void )
+ *  {
+ *  TaskHandle_t xHandle;
+ *
+ *   // Create a task, storing the handle.
+ *   xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );
+ *
+ *   // ...
+ *
+ *   // Use the handle to suspend the created task.
+ *   vTaskSuspend( xHandle );
+ *
+ *   // ...
+ *
+ *   // The created task will not run during this period, unless
+ *   // another task calls vTaskResume( xHandle ).
+ *
+ *   //...
+ *
+ *
+ *   // Suspend ourselves.
+ *   vTaskSuspend( NULL );
+ *
+ *   // We cannot get here unless another task calls vTaskResume
+ *   // with our handle as the parameter.
+ *  }
+ * @endcode
+ * \ingroup TaskCtrl
+ */
+void vTaskSuspend( TaskHandle_t xTaskToSuspend ) PRIVILEGED_FUNCTION;
+
+/**
+ * Resumes a suspended task.
+ *
+ * INCLUDE_vTaskSuspend must be defined as 1 for this function to be available.
+ * See the configuration section for more information.
+ *
+ * A task that has been suspended by one or more calls to vTaskSuspend ()
+ * will be made available for running again by a single call to
+ * vTaskResume ().
+ *
+ * @param xTaskToResume Handle to the task being readied.
+ *
+ * Example usage:
+ * @code{c}
+ *  void vAFunction( void )
+ *  {
+ *  TaskHandle_t xHandle;
+ *
+ *   // Create a task, storing the handle.
+ *   xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );
+ *
+ *   // ...
+ *
+ *   // Use the handle to suspend the created task.
+ *   vTaskSuspend( xHandle );
+ *
+ *   // ...
+ *
+ *   // The created task will not run during this period, unless
+ *   // another task calls vTaskResume( xHandle ).
+ *
+ *   //...
+ *
+ *
+ *   // Resume the suspended task ourselves.
+ *   vTaskResume( xHandle );
+ *
+ *   // The created task will once again get microcontroller processing
+ *   // time in accordance with its priority within the system.
+ *  }
+ * @endcode
+ * \ingroup TaskCtrl
+ */
+void vTaskResume( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION;
+
+/**
+ * An implementation of vTaskResume() that can be called from within an ISR.
+ *
+ * INCLUDE_xTaskResumeFromISR must be defined as 1 for this function to be
+ * available.  See the configuration section for more information.
+ *
+ * A task that has been suspended by one or more calls to vTaskSuspend ()
+ * will be made available for running again by a single call to
+ * xTaskResumeFromISR ().
+ *
+ * xTaskResumeFromISR() should not be used to synchronise a task with an
+ * interrupt if there is a chance that the interrupt could arrive prior to the
+ * task being suspended - as this can lead to interrupts being missed. Use of a
+ * semaphore as a synchronisation mechanism would avoid this eventuality.
+ *
+ * @param xTaskToResume Handle to the task being readied.
+ *
+ * @return pdTRUE if resuming the task should result in a context switch,
+ * otherwise pdFALSE. This is used by the ISR to determine if a context switch
+ * may be required following the ISR.
+ *
+ * \ingroup TaskCtrl
+ */
+BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION;
+
+/*-----------------------------------------------------------
+ * SCHEDULER CONTROL
+ *----------------------------------------------------------*/
+/** @cond */
+/**
+ * Starts the real time kernel tick processing.
+ *
+ * After calling the kernel has control over which tasks are executed and when.
+ *
+ * See the demo application file main.c for an example of creating
+ * tasks and starting the kernel.
+ *
+ * Example usage:
+ * @code{c}
+ *  void vAFunction( void )
+ *  {
+ *   // Create at least one task before starting the kernel.
+ *   xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
+ *
+ *   // Start the real time kernel with preemption.
+ *   vTaskStartScheduler ();
+ *
+ *   // Will not get here unless a task calls vTaskEndScheduler ()
+ *  }
+ * @endcode
+ *
+ * \ingroup SchedulerControl
+ */
+void vTaskStartScheduler( void ) PRIVILEGED_FUNCTION;
+
+/**
+ * Stops the real time kernel tick.
+ *
+ * @note At the time of writing only the x86 real mode port, which runs on a PC
+ * in place of DOS, implements this function.
+ *
+ * All created tasks will be automatically deleted and multitasking
+ * (either preemptive or cooperative) will stop.
+ * Execution then resumes from the point where vTaskStartScheduler ()
+ * was called, as if vTaskStartScheduler () had just returned.
+ *
+ * See the demo application file main. c in the demo/PC directory for an
+ * example that uses vTaskEndScheduler ().
+ *
+ * vTaskEndScheduler () requires an exit function to be defined within the
+ * portable layer (see vPortEndScheduler () in port. c for the PC port).  This
+ * performs hardware specific operations such as stopping the kernel tick.
+ *
+ * vTaskEndScheduler () will cause all of the resources allocated by the
+ * kernel to be freed - but will not free resources allocated by application
+ * tasks.
+ *
+ * Example usage:
+ * @code{c}
+ *  void vTaskCode( void * pvParameters )
+ *  {
+ *   for( ;; )
+ *   {
+ *       // Task code goes here.
+ *
+ *       // At some point we want to end the real time kernel processing
+ *       // so call ...
+ *       vTaskEndScheduler ();
+ *   }
+ *  }
+ *
+ *  void vAFunction( void )
+ *  {
+ *   // Create at least one task before starting the kernel.
+ *   xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
+ *
+ *   // Start the real time kernel with preemption.
+ *   vTaskStartScheduler ();
+ *
+ *   // Will only get here when the vTaskCode () task has called
+ *   // vTaskEndScheduler ().  When we get here we are back to single task
+ *   // execution.
+ *  }
+ * @endcode
+ * \ingroup SchedulerControl
+ */
+void vTaskEndScheduler( void ) PRIVILEGED_FUNCTION;
+
+/** @endcond */
+
+/**
+ * Suspends the scheduler without disabling interrupts.
+ *
+ * Context switches will not occur while the scheduler is suspended.
+ *
+ * After calling vTaskSuspendAll () the calling task will continue to execute
+ * without risk of being swapped out until a call to xTaskResumeAll () has been
+ * made.
+ *
+ * API functions that have the potential to cause a context switch (for example,
+ * vTaskDelayUntil(), xQueueSend(), etc.) must not be called while the scheduler
+ * is suspended.
+ *
+ * Example usage:
+ * @code{c}
+ *  void vTask1( void * pvParameters )
+ *  {
+ *   for( ;; )
+ *   {
+ *       // Task code goes here.
+ *
+ *       // ...
+ *
+ *       // At some point the task wants to perform a long operation during
+ *       // which it does not want to get swapped out.  It cannot use
+ *       // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the
+ *       // operation may cause interrupts to be missed - including the
+ *       // ticks.
+ *
+ *       // Prevent the real time kernel swapping out the task.
+ *       vTaskSuspendAll ();
+ *
+ *       // Perform the operation here.  There is no need to use critical
+ *       // sections as we have all the microcontroller processing time.
+ *       // During this time interrupts will still operate and the kernel
+ *       // tick count will be maintained.
+ *
+ *       // ...
+ *
+ *       // The operation is complete.  Restart the kernel.
+ *       xTaskResumeAll ();
+ *   }
+ *  }
+ * @endcode
+ * \ingroup SchedulerControl
+ */
+void vTaskSuspendAll( void ) PRIVILEGED_FUNCTION;
+
+/**
+ * Resumes scheduler activity after it was suspended by a call to
+ * vTaskSuspendAll().
+ *
+ * xTaskResumeAll() only resumes the scheduler.  It does not unsuspend tasks
+ * that were previously suspended by a call to vTaskSuspend().
+ *
+ * @return If resuming the scheduler caused a context switch then pdTRUE is
+ *               returned, otherwise pdFALSE is returned.
+ *
+ * Example usage:
+ * @code{c}
+ *  void vTask1( void * pvParameters )
+ *  {
+ *   for( ;; )
+ *   {
+ *       // Task code goes here.
+ *
+ *       // ...
+ *
+ *       // At some point the task wants to perform a long operation during
+ *       // which it does not want to get swapped out.  It cannot use
+ *       // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the
+ *       // operation may cause interrupts to be missed - including the
+ *       // ticks.
+ *
+ *       // Prevent the real time kernel swapping out the task.
+ *       vTaskSuspendAll ();
+ *
+ *       // Perform the operation here.  There is no need to use critical
+ *       // sections as we have all the microcontroller processing time.
+ *       // During this time interrupts will still operate and the real
+ *       // time kernel tick count will be maintained.
+ *
+ *       // ...
+ *
+ *       // The operation is complete.  Restart the kernel.  We want to force
+ *       // a context switch - but there is no point if resuming the scheduler
+ *       // caused a context switch already.
+ *       if( !xTaskResumeAll () )
+ *       {
+ *            taskYIELD ();
+ *       }
+ *   }
+ *  }
+ * @endcode
+ * \ingroup SchedulerControl
+ */
+BaseType_t xTaskResumeAll( void ) PRIVILEGED_FUNCTION;
+
+/*-----------------------------------------------------------
+ * TASK UTILITIES
+ *----------------------------------------------------------*/
+
+/**
+ * Get tick count
+ *
+ * @return The count of ticks since vTaskStartScheduler was called.
+ *
+ * \ingroup TaskUtils
+ */
+TickType_t xTaskGetTickCount( void ) PRIVILEGED_FUNCTION;
+
+/**
+ * Get tick count from ISR
+ *
+ * @return The count of ticks since vTaskStartScheduler was called.
+ *
+ * This is a version of xTaskGetTickCount() that is safe to be called from an
+ * ISR - provided that TickType_t is the natural word size of the
+ * microcontroller being used or interrupt nesting is either not supported or
+ * not being used.
+ *
+ * \ingroup TaskUtils
+ */
+TickType_t xTaskGetTickCountFromISR( void ) PRIVILEGED_FUNCTION;
+
+/**
+ * Get current number of tasks
+ *
+ * @return The number of tasks that the real time kernel is currently managing.
+ * This includes all ready, blocked and suspended tasks.  A task that
+ * has been deleted but not yet freed by the idle task will also be
+ * included in the count.
+ *
+ * \ingroup TaskUtils
+ */
+UBaseType_t uxTaskGetNumberOfTasks( void ) PRIVILEGED_FUNCTION;
+
+/**
+ * Get task name
+ *
+ * @return The text (human readable) name of the task referenced by the handle
+ * xTaskToQuery.  A task can query its own name by either passing in its own
+ * handle, or by setting xTaskToQuery to NULL.  INCLUDE_pcTaskGetTaskName must be
+ * set to 1 in FreeRTOSConfig.h for pcTaskGetTaskName() to be available.
+ *
+ * \ingroup TaskUtils
+ */
+char *pcTaskGetTaskName( TaskHandle_t xTaskToQuery ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+
+/**
+ * Returns the high water mark of the stack associated with xTask.
+ *
+ * INCLUDE_uxTaskGetStackHighWaterMark must be set to 1 in FreeRTOSConfig.h for
+ * this function to be available.
+ *
+ * High water mark is the minimum free stack space there has been (in bytes
+ * rather than words as found in vanilla FreeRTOS) since the task started.
+ * The smaller the returned number the closer the task has come to overflowing its stack.
+ *
+ * @param xTask Handle of the task associated with the stack to be checked.
+ * Set xTask to NULL to check the stack of the calling task.
+ *
+ * @return The smallest amount of free stack space there has been (in bytes
+ * rather than words as found in vanilla FreeRTOS) since the task referenced by
+ * xTask was created.
+ */
+UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
+
+/**
+ * Returns the start of the stack associated with xTask.
+ *
+ * INCLUDE_pxTaskGetStackStart must be set to 1 in FreeRTOSConfig.h for
+ * this function to be available.
+ *
+ * Returns the highest stack memory address on architectures where the stack grows down
+ * from high memory, and the lowest memory address on architectures where the
+ * stack grows up from low memory.
+ *
+ * @param xTask Handle of the task associated with the stack returned.
+ * Set xTask to NULL to return the stack of the calling task.
+ *
+ * @return A pointer to the start of the stack.
+ */
+uint8_t* pxTaskGetStackStart( TaskHandle_t xTask) PRIVILEGED_FUNCTION;
+
+/* When using trace macros it is sometimes necessary to include task.h before
+FreeRTOS.h.  When this is done TaskHookFunction_t will not yet have been defined,
+so the following two prototypes will cause a compilation error.  This can be
+fixed by simply guarding against the inclusion of these two prototypes unless
+they are explicitly required by the configUSE_APPLICATION_TASK_TAG configuration
+constant. */
+#ifdef configUSE_APPLICATION_TASK_TAG
+       #if configUSE_APPLICATION_TASK_TAG == 1
+               /**
+                * Sets pxHookFunction to be the task hook function used by the task xTask.
+                * @param xTask Handle of the task to set the hook function for
+                *              Passing xTask as NULL has the effect of setting the calling
+                *              tasks hook function.
+                * @param pxHookFunction  Pointer to the hook function.
+                */
+               void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction ) PRIVILEGED_FUNCTION;
+
+               /**
+                * Get the hook function assigned to given task.
+                * @param xTask Handle of the task to get the hook function for
+                *              Passing xTask as NULL has the effect of getting the calling
+                *              tasks hook function.
+                * @return The pxHookFunction value assigned to the task xTask.
+                */
+               TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
+       #endif /* configUSE_APPLICATION_TASK_TAG ==1 */
+#endif /* ifdef configUSE_APPLICATION_TASK_TAG */
+#if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 )
+
+       /**
+        * Set local storage pointer specific to the given task.
+        *
+        * Each task contains an array of pointers that is dimensioned by the
+        * configNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h.
+        * The kernel does not use the pointers itself, so the application writer
+        * can use the pointers for any purpose they wish.
+        *
+        * @param xTaskToSet  Task to set thread local storage pointer for
+        * @param xIndex The index of the pointer to set, from 0 to
+        *               configNUM_THREAD_LOCAL_STORAGE_POINTERS - 1.
+        * @param pvValue  Pointer value to set.
+        */
+       void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue ) PRIVILEGED_FUNCTION;
+
+
+       /**
+        * Get local storage pointer specific to the given task.
+        *
+        * Each task contains an array of pointers that is dimensioned by the
+        * configNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h.
+        * The kernel does not use the pointers itself, so the application writer
+        * can use the pointers for any purpose they wish.
+        *
+        * @param xTaskToQuery  Task to get thread local storage pointer for
+        * @param xIndex The index of the pointer to get, from 0 to
+        *               configNUM_THREAD_LOCAL_STORAGE_POINTERS - 1.
+        * @return  Pointer value
+        */
+       void *pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, BaseType_t xIndex ) PRIVILEGED_FUNCTION;
+
+       #if ( configTHREAD_LOCAL_STORAGE_DELETE_CALLBACKS )
+
+               /**
+                * Prototype of local storage pointer deletion callback.
+                */
+               typedef void (*TlsDeleteCallbackFunction_t)( int, void * );
+
+               /**
+                * Set local storage pointer and deletion callback.
+                *
+                * Each task contains an array of pointers that is dimensioned by the
+                * configNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h.
+                * The kernel does not use the pointers itself, so the application writer
+                * can use the pointers for any purpose they wish.
+                *
+                * Local storage pointers set for a task can reference dynamically
+                * allocated resources. This function is similar to
+                * vTaskSetThreadLocalStoragePointer, but provides a way to release
+                * these resources when the task gets deleted. For each pointer,
+                * a callback function can be set. This function will be called
+                * when task is deleted, with the local storage pointer index
+                * and value as arguments.
+                *
+                * @param xTaskToSet  Task to set thread local storage pointer for
+                * @param xIndex The index of the pointer to set, from 0 to
+                *               configNUM_THREAD_LOCAL_STORAGE_POINTERS - 1.
+                * @param pvValue  Pointer value to set.
+                * @param pvDelCallback  Function to call to dispose of the local
+                *                       storage pointer when the task is deleted.
+                */
+               void vTaskSetThreadLocalStoragePointerAndDelCallback( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue, TlsDeleteCallbackFunction_t pvDelCallback);
+       #endif
+
+#endif
+
+/**
+ * Calls the hook function associated with xTask. Passing xTask as NULL has
+ * the effect of calling the Running tasks (the calling task) hook function.
+ *
+ * @param xTask  Handle of the task to call the hook for.
+ * @param pvParameter  Parameter passed to the hook function for the task to interpret as it
+ * wants.  The return value is the value returned by the task hook function
+ * registered by the user.
+ */
+BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter ) PRIVILEGED_FUNCTION;
+
+/**
+ * Get the handle of idle task for the current CPU.
+ *
+ * xTaskGetIdleTaskHandle() is only available if
+ * INCLUDE_xTaskGetIdleTaskHandle is set to 1 in FreeRTOSConfig.h.
+ *
+ * @return The handle of the idle task.  It is not valid to call
+ * xTaskGetIdleTaskHandle() before the scheduler has been started.
+ */
+TaskHandle_t xTaskGetIdleTaskHandle( void );
+
+/**
+ * Get the handle of idle task for the given CPU.
+ *
+ * xTaskGetIdleTaskHandleForCPU() is only available if
+ * INCLUDE_xTaskGetIdleTaskHandle is set to 1 in FreeRTOSConfig.h.
+ *
+ * @param cpuid The CPU to get the handle for
+ *
+ * @return Idle task handle of a given cpu. It is not valid to call
+ * xTaskGetIdleTaskHandleForCPU() before the scheduler has been started.
+ */
+TaskHandle_t xTaskGetIdleTaskHandleForCPU( UBaseType_t cpuid );
+
+/**
+ * Get the state of tasks in the system.
+ *
+ * configUSE_TRACE_FACILITY must be defined as 1 in FreeRTOSConfig.h for
+ * uxTaskGetSystemState() to be available.
+ *
+ * uxTaskGetSystemState() populates an TaskStatus_t structure for each task in
+ * the system.  TaskStatus_t structures contain, among other things, members
+ * for the task handle, task name, task priority, task state, and total amount
+ * of run time consumed by the task.  See the TaskStatus_t structure
+ * definition in this file for the full member list.
+ *
+ * @note  This function is intended for debugging use only as its use results in
+ * the scheduler remaining suspended for an extended period.
+ *
+ * @param pxTaskStatusArray A pointer to an array of TaskStatus_t structures.
+ * The array must contain at least one TaskStatus_t structure for each task
+ * that is under the control of the RTOS.  The number of tasks under the control
+ * of the RTOS can be determined using the uxTaskGetNumberOfTasks() API function.
+ *
+ * @param uxArraySize The size of the array pointed to by the pxTaskStatusArray
+ * parameter.  The size is specified as the number of indexes in the array, or
+ * the number of TaskStatus_t structures contained in the array, not by the
+ * number of bytes in the array.
+ *
+ * @param pulTotalRunTime If configGENERATE_RUN_TIME_STATS is set to 1 in
+ * FreeRTOSConfig.h then *pulTotalRunTime is set by uxTaskGetSystemState() to the
+ * total run time (as defined by the run time stats clock, see
+ * http://www.freertos.org/rtos-run-time-stats.html) since the target booted.
+ * pulTotalRunTime can be set to NULL to omit the total run time information.
+ *
+ * @return The number of TaskStatus_t structures that were populated by
+ * uxTaskGetSystemState().  This should equal the number returned by the
+ * uxTaskGetNumberOfTasks() API function, but will be zero if the value passed
+ * in the uxArraySize parameter was too small.
+ *
+ * Example usage:
+ * @code{c}
+ * // This example demonstrates how a human readable table of run time stats
+ * // information is generated from raw data provided by uxTaskGetSystemState().
+ * // The human readable table is written to pcWriteBuffer
+ * void vTaskGetRunTimeStats( char *pcWriteBuffer )
+ * {
+ * TaskStatus_t *pxTaskStatusArray;
+ * volatile UBaseType_t uxArraySize, x;
+ * uint32_t ulTotalRunTime, ulStatsAsPercentage;
+ *
+ *  // Make sure the write buffer does not contain a string.
+ *  *pcWriteBuffer = 0x00;
+ *
+ *  // Take a snapshot of the number of tasks in case it changes while this
+ *  // function is executing.
+ *  uxArraySize = uxTaskGetNumberOfTasks();
+ *
+ *  // Allocate a TaskStatus_t structure for each task.  An array could be
+ *  // allocated statically at compile time.
+ *  pxTaskStatusArray = pvPortMalloc( uxArraySize * sizeof( TaskStatus_t ) );
+ *
+ *  if( pxTaskStatusArray != NULL )
+ *  {
+ *      // Generate raw status information about each task.
+ *      uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalRunTime );
+ *
+ *      // For percentage calculations.
+ *      ulTotalRunTime /= 100UL;
+ *
+ *      // Avoid divide by zero errors.
+ *      if( ulTotalRunTime > 0 )
+ *      {
+ *          // For each populated position in the pxTaskStatusArray array,
+ *          // format the raw data as human readable ASCII data
+ *          for( x = 0; x < uxArraySize; x++ )
+ *          {
+ *              // What percentage of the total run time has the task used?
+ *              // This will always be rounded down to the nearest integer.
+ *              // ulTotalRunTimeDiv100 has already been divided by 100.
+ *              ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalRunTime;
+ *
+ *              if( ulStatsAsPercentage > 0UL )
+ *              {
+ *                  sprintf( pcWriteBuffer, "%s\t\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage );
+ *              }
+ *              else
+ *              {
+ *                  // If the percentage is zero here then the task has
+ *                  // consumed less than 1% of the total run time.
+ *                  sprintf( pcWriteBuffer, "%s\t\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter );
+ *              }
+ *
+ *              pcWriteBuffer += strlen( ( char * ) pcWriteBuffer );
+ *          }
+ *      }
+ *
+ *      // The array is no longer needed, free the memory it consumes.
+ *      vPortFree( pxTaskStatusArray );
+ *  }
+ * }
+ * @endcode
+ */
+UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, const UBaseType_t uxArraySize, uint32_t * const pulTotalRunTime );
+
+/**
+ * List all the current tasks.
+ *
+ * configUSE_TRACE_FACILITY and configUSE_STATS_FORMATTING_FUNCTIONS must
+ * both be defined as 1 for this function to be available.  See the
+ * configuration section of the FreeRTOS.org website for more information.
+ *
+ * @note This function will disable interrupts for its duration.  It is
+ * not intended for normal application runtime use but as a debug aid.
+ *
+ * Lists all the current tasks, along with their current state and stack
+ * usage high water mark.
+ *
+ * Tasks are reported as blocked ('B'), ready ('R'), deleted ('D') or
+ * suspended ('S').
+ *
+ * @note This function is provided for convenience only, and is used by many of the
+ * demo applications.  Do not consider it to be part of the scheduler.
+ *
+ * vTaskList() calls uxTaskGetSystemState(), then formats part of the
+ * uxTaskGetSystemState() output into a human readable table that displays task
+ * names, states and stack usage.
+ *
+ * vTaskList() has a dependency on the sprintf() C library function that might
+ * bloat the code size, use a lot of stack, and provide different results on
+ * different platforms.  An alternative, tiny, third party, and limited
+ * functionality implementation of sprintf() is provided in many of the
+ * FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note
+ * printf-stdarg.c does not provide a full snprintf() implementation!).
+ *
+ * It is recommended that production systems call uxTaskGetSystemState()
+ * directly to get access to raw stats data, rather than indirectly through a
+ * call to vTaskList().
+ *
+ * @param pcWriteBuffer A buffer into which the above mentioned details
+ * will be written, in ASCII form.  This buffer is assumed to be large
+ * enough to contain the generated report.  Approximately 40 bytes per
+ * task should be sufficient.
+ *
+ * \ingroup TaskUtils
+ */
+void vTaskList( char * pcWriteBuffer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+
+/**
+ * Get the state of running tasks as a string
+ *
+ * configGENERATE_RUN_TIME_STATS and configUSE_STATS_FORMATTING_FUNCTIONS
+ * must both be defined as 1 for this function to be available.  The application
+ * must also then provide definitions for
+ * portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE()
+ * to configure a peripheral timer/counter and return the timers current count
+ * value respectively.  The counter should be at least 10 times the frequency of
+ * the tick count.
+ *
+ * @note This function will disable interrupts for its duration.  It is
+ * not intended for normal application runtime use but as a debug aid.
+ *
+ * Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total
+ * accumulated execution time being stored for each task.  The resolution
+ * of the accumulated time value depends on the frequency of the timer
+ * configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro.
+ * Calling vTaskGetRunTimeStats() writes the total execution time of each
+ * task into a buffer, both as an absolute count value and as a percentage
+ * of the total system execution time.
+ *
+ * @note This function is provided for convenience only, and is used by many of the
+ * demo applications.  Do not consider it to be part of the scheduler.
+ *
+ * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part of the
+ * uxTaskGetSystemState() output into a human readable table that displays the
+ * amount of time each task has spent in the Running state in both absolute and
+ * percentage terms.
+ *
+ * vTaskGetRunTimeStats() has a dependency on the sprintf() C library function
+ * that might bloat the code size, use a lot of stack, and provide different
+ * results on different platforms.  An alternative, tiny, third party, and
+ * limited functionality implementation of sprintf() is provided in many of the
+ * FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note
+ * printf-stdarg.c does not provide a full snprintf() implementation!).
+ *
+ * It is recommended that production systems call uxTaskGetSystemState() directly
+ * to get access to raw stats data, rather than indirectly through a call to
+ * vTaskGetRunTimeStats().
+ *
+ * @param pcWriteBuffer A buffer into which the execution times will be
+ * written, in ASCII form.  This buffer is assumed to be large enough to
+ * contain the generated report.  Approximately 40 bytes per task should
+ * be sufficient.
+ *
+ * \ingroup TaskUtils
+ */
+void vTaskGetRunTimeStats( char *pcWriteBuffer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+
+/**
+ * Send task notification.
+ *
+ * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this
+ * function to be available.
+ *
+ * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
+ * "notification value", which is a 32-bit unsigned integer (uint32_t).
+ *
+ * Events can be sent to a task using an intermediary object.  Examples of such
+ * objects are queues, semaphores, mutexes and event groups.  Task notifications
+ * are a method of sending an event directly to a task without the need for such
+ * an intermediary object.
+ *
+ * A notification sent to a task can optionally perform an action, such as
+ * update, overwrite or increment the task's notification value.  In that way
+ * task notifications can be used to send data to a task, or be used as light
+ * weight and fast binary or counting semaphores.
+ *
+ * A notification sent to a task will remain pending until it is cleared by the
+ * task calling xTaskNotifyWait() or ulTaskNotifyTake().  If the task was
+ * already in the Blocked state to wait for a notification when the notification
+ * arrives then the task will automatically be removed from the Blocked state
+ * (unblocked) and the notification cleared.
+ *
+ * A task can use xTaskNotifyWait() to [optionally] block to wait for a
+ * notification to be pending, or ulTaskNotifyTake() to [optionally] block
+ * to wait for its notification value to have a non-zero value.  The task does
+ * not consume any CPU time while it is in the Blocked state.
+ *
+ * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details.
+ *
+ * @param xTaskToNotify The handle of the task being notified.  The handle to a
+ * task can be returned from the xTaskCreate() API function used to create the
+ * task, and the handle of the currently running task can be obtained by calling
+ * xTaskGetCurrentTaskHandle().
+ *
+ * @param ulValue Data that can be sent with the notification.  How the data is
+ * used depends on the value of the eAction parameter.
+ *
+ * @param eAction Specifies how the notification updates the task's notification
+ * value, if at all.  Valid values for eAction are as follows:
+ *     - eSetBits:
+ *       The task's notification value is bitwise ORed with ulValue.  xTaskNofify()
+ *       always returns pdPASS in this case.
+ *
+ *     - eIncrement:
+ *       The task's notification value is incremented.  ulValue is not used and
+ *       xTaskNotify() always returns pdPASS in this case.
+ *
+ *     - eSetValueWithOverwrite:
+ *       The task's notification value is set to the value of ulValue, even if the
+ *       task being notified had not yet processed the previous notification (the
+ *       task already had a notification pending).  xTaskNotify() always returns
+ *       pdPASS in this case.
+ *
+ *     - eSetValueWithoutOverwrite:
+ *       If the task being notified did not already have a notification pending then
+ *       the task's notification value is set to ulValue and xTaskNotify() will
+ *       return pdPASS.  If the task being notified already had a notification
+ *       pending then no action is performed and pdFAIL is returned.
+ *
+ *     - eNoAction:
+ *       The task receives a notification without its notification value being
+ *     Â Â updated.  ulValue is not used and xTaskNotify() always returns pdPASS in
+ *       this case.
+ *
+ * @return Dependent on the value of eAction.  See the description of the
+ * eAction parameter.
+ *
+ * \ingroup TaskNotifications
+ */
+BaseType_t xTaskNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction );
+
+/**
+ * Send task notification from an ISR.
+ *
+ * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this
+ * function to be available.
+ *
+ * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
+ * "notification value", which is a 32-bit unsigned integer (uint32_t).
+ *
+ * A version of xTaskNotify() that can be used from an interrupt service routine
+ * (ISR).
+ *
+ * Events can be sent to a task using an intermediary object.  Examples of such
+ * objects are queues, semaphores, mutexes and event groups.  Task notifications
+ * are a method of sending an event directly to a task without the need for such
+ * an intermediary object.
+ *
+ * A notification sent to a task can optionally perform an action, such as
+ * update, overwrite or increment the task's notification value.  In that way
+ * task notifications can be used to send data to a task, or be used as light
+ * weight and fast binary or counting semaphores.
+ *
+ * A notification sent to a task will remain pending until it is cleared by the
+ * task calling xTaskNotifyWait() or ulTaskNotifyTake().  If the task was
+ * already in the Blocked state to wait for a notification when the notification
+ * arrives then the task will automatically be removed from the Blocked state
+ * (unblocked) and the notification cleared.
+ *
+ * A task can use xTaskNotifyWait() to [optionally] block to wait for a
+ * notification to be pending, or ulTaskNotifyTake() to [optionally] block
+ * to wait for its notification value to have a non-zero value.  The task does
+ * not consume any CPU time while it is in the Blocked state.
+ *
+ * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details.
+ *
+ * @param xTaskToNotify The handle of the task being notified.  The handle to a
+ * task can be returned from the xTaskCreate() API function used to create the
+ * task, and the handle of the currently running task can be obtained by calling
+ * xTaskGetCurrentTaskHandle().
+ *
+ * @param ulValue Data that can be sent with the notification.  How the data is
+ * used depends on the value of the eAction parameter.
+ *
+ * @param eAction Specifies how the notification updates the task's notification
+ * value, if at all.  Valid values for eAction are as follows:
+ *     - eSetBits:
+ *       The task's notification value is bitwise ORed with ulValue.  xTaskNofify()
+ *       always returns pdPASS in this case.
+ *
+ *     - eIncrement:
+ *       The task's notification value is incremented.  ulValue is not used and
+ *       xTaskNotify() always returns pdPASS in this case.
+ *
+ *     - eSetValueWithOverwrite:
+ *       The task's notification value is set to the value of ulValue, even if the
+ *       task being notified had not yet processed the previous notification (the
+ *       task already had a notification pending).  xTaskNotify() always returns
+ *       pdPASS in this case.
+ *
+ *     - eSetValueWithoutOverwrite:
+ *       If the task being notified did not already have a notification pending then
+ *       the task's notification value is set to ulValue and xTaskNotify() will
+ *       return pdPASS.  If the task being notified already had a notification
+ *       pending then no action is performed and pdFAIL is returned.
+ *
+ *     - eNoAction:
+ *       The task receives a notification without its notification value being
+ *       updated.  ulValue is not used and xTaskNotify() always returns pdPASS in
+ *       this case.
+ *
+ * @param pxHigherPriorityTaskWoken  xTaskNotifyFromISR() will set
+ * *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the
+ * task to which the notification was sent to leave the Blocked state, and the
+ * unblocked task has a priority higher than the currently running task.  If
+ * xTaskNotifyFromISR() sets this value to pdTRUE then a context switch should
+ * be requested before the interrupt is exited.  How a context switch is
+ * requested from an ISR is dependent on the port - see the documentation page
+ * for the port in use.
+ *
+ * @return Dependent on the value of eAction.  See the description of the
+ * eAction parameter.
+ *
+ * \ingroup TaskNotifications
+ */
+BaseType_t xTaskNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, BaseType_t *pxHigherPriorityTaskWoken );
+
+/**
+ * Wait for task notification
+ *
+ * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this
+ * function to be available.
+ *
+ * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
+ * "notification value", which is a 32-bit unsigned integer (uint32_t).
+ *
+ * Events can be sent to a task using an intermediary object.  Examples of such
+ * objects are queues, semaphores, mutexes and event groups.  Task notifications
+ * are a method of sending an event directly to a task without the need for such
+ * an intermediary object.
+ *
+ * A notification sent to a task can optionally perform an action, such as
+ * update, overwrite or increment the task's notification value.  In that way
+ * task notifications can be used to send data to a task, or be used as light
+ * weight and fast binary or counting semaphores.
+ *
+ * A notification sent to a task will remain pending until it is cleared by the
+ * task calling xTaskNotifyWait() or ulTaskNotifyTake().  If the task was
+ * already in the Blocked state to wait for a notification when the notification
+ * arrives then the task will automatically be removed from the Blocked state
+ * (unblocked) and the notification cleared.
+ *
+ * A task can use xTaskNotifyWait() to [optionally] block to wait for a
+ * notification to be pending, or ulTaskNotifyTake() to [optionally] block
+ * to wait for its notification value to have a non-zero value.  The task does
+ * not consume any CPU time while it is in the Blocked state.
+ *
+ * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details.
+ *
+ * @param ulBitsToClearOnEntry Bits that are set in ulBitsToClearOnEntry value
+ * will be cleared in the calling task's notification value before the task
+ * checks to see if any notifications are pending, and optionally blocks if no
+ * notifications are pending.  Setting ulBitsToClearOnEntry to ULONG_MAX (if
+ * limits.h is included) or 0xffffffffUL (if limits.h is not included) will have
+ * the effect of resetting the task's notification value to 0.  Setting
+ * ulBitsToClearOnEntry to 0 will leave the task's notification value unchanged.
+ *
+ * @param ulBitsToClearOnExit If a notification is pending or received before
+ * the calling task exits the xTaskNotifyWait() function then the task's
+ * notification value (see the xTaskNotify() API function) is passed out using
+ * the pulNotificationValue parameter.  Then any bits that are set in
+ * ulBitsToClearOnExit will be cleared in the task's notification value (note
+ * *pulNotificationValue is set before any bits are cleared).  Setting
+ * ulBitsToClearOnExit to ULONG_MAX (if limits.h is included) or 0xffffffffUL
+ * (if limits.h is not included) will have the effect of resetting the task's
+ * notification value to 0 before the function exits.  Setting
+ * ulBitsToClearOnExit to 0 will leave the task's notification value unchanged
+ * when the function exits (in which case the value passed out in
+ * pulNotificationValue will match the task's notification value).
+ *
+ * @param pulNotificationValue Used to pass the task's notification value out
+ * of the function.  Note the value passed out will not be effected by the
+ * clearing of any bits caused by ulBitsToClearOnExit being non-zero.
+ *
+ * @param xTicksToWait The maximum amount of time that the task should wait in
+ * the Blocked state for a notification to be received, should a notification
+ * not already be pending when xTaskNotifyWait() was called.  The task
+ * will not consume any processing time while it is in the Blocked state.  This
+ * is specified in kernel ticks, the macro pdMS_TO_TICSK( value_in_ms ) can be
+ * used to convert a time specified in milliseconds to a time specified in
+ * ticks.
+ *
+ * @return If a notification was received (including notifications that were
+ * already pending when xTaskNotifyWait was called) then pdPASS is
+ * returned.  Otherwise pdFAIL is returned.
+ *
+ * \ingroup TaskNotifications
+ */
+BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait );
+
+/**
+ * Simplified macro for sending task notification.
+ *
+ * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro
+ * to be available.
+ *
+ * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
+ * "notification value", which is a 32-bit unsigned integer (uint32_t).
+ *
+ * Events can be sent to a task using an intermediary object.  Examples of such
+ * objects are queues, semaphores, mutexes and event groups.  Task notifications
+ * are a method of sending an event directly to a task without the need for such
+ * an intermediary object.
+ *
+ * A notification sent to a task can optionally perform an action, such as
+ * update, overwrite or increment the task's notification value.  In that way
+ * task notifications can be used to send data to a task, or be used as light
+ * weight and fast binary or counting semaphores.
+ *
+ * xTaskNotifyGive() is a helper macro intended for use when task notifications
+ * are used as light weight and faster binary or counting semaphore equivalents.
+ * Actual FreeRTOS semaphores are given using the xSemaphoreGive() API function,
+ * the equivalent action that instead uses a task notification is
+ * xTaskNotifyGive().
+ *
+ * When task notifications are being used as a binary or counting semaphore
+ * equivalent then the task being notified should wait for the notification
+ * using the ulTaskNotificationTake() API function rather than the
+ * xTaskNotifyWait() API function.
+ *
+ * See http://www.FreeRTOS.org/RTOS-task-notifications.html for more details.
+ *
+ * @param xTaskToNotify The handle of the task being notified.  The handle to a
+ * task can be returned from the xTaskCreate() API function used to create the
+ * task, and the handle of the currently running task can be obtained by calling
+ * xTaskGetCurrentTaskHandle().
+ *
+ * @return xTaskNotifyGive() is a macro that calls xTaskNotify() with the
+ * eAction parameter set to eIncrement - so pdPASS is always returned.
+ *
+ * \ingroup TaskNotifications
+ */
+#define xTaskNotifyGive( xTaskToNotify ) xTaskNotify( ( xTaskToNotify ), 0, eIncrement )
+
+/**
+ * Simplified macro for sending task notification from ISR.
+ *
+ * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro
+ * to be available.
+ *
+ * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
+ * "notification value", which is a 32-bit unsigned integer (uint32_t).
+ *
+ * A version of xTaskNotifyGive() that can be called from an interrupt service
+ * routine (ISR).
+ *
+ * Events can be sent to a task using an intermediary object.  Examples of such
+ * objects are queues, semaphores, mutexes and event groups.  Task notifications
+ * are a method of sending an event directly to a task without the need for such
+ * an intermediary object.
+ *
+ * A notification sent to a task can optionally perform an action, such as
+ * update, overwrite or increment the task's notification value.  In that way
+ * task notifications can be used to send data to a task, or be used as light
+ * weight and fast binary or counting semaphores.
+ *
+ * vTaskNotifyGiveFromISR() is intended for use when task notifications are
+ * used as light weight and faster binary or counting semaphore equivalents.
+ * Actual FreeRTOS semaphores are given from an ISR using the
+ * xSemaphoreGiveFromISR() API function, the equivalent action that instead uses
+ * a task notification is vTaskNotifyGiveFromISR().
+ *
+ * When task notifications are being used as a binary or counting semaphore
+ * equivalent then the task being notified should wait for the notification
+ * using the ulTaskNotificationTake() API function rather than the
+ * xTaskNotifyWait() API function.
+ *
+ * See http://www.FreeRTOS.org/RTOS-task-notifications.html for more details.
+ *
+ * @param xTaskToNotify The handle of the task being notified.  The handle to a
+ * task can be returned from the xTaskCreate() API function used to create the
+ * task, and the handle of the currently running task can be obtained by calling
+ * xTaskGetCurrentTaskHandle().
+ *
+ * @param pxHigherPriorityTaskWoken  vTaskNotifyGiveFromISR() will set
+ * *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the
+ * task to which the notification was sent to leave the Blocked state, and the
+ * unblocked task has a priority higher than the currently running task.  If
+ * vTaskNotifyGiveFromISR() sets this value to pdTRUE then a context switch
+ * should be requested before the interrupt is exited.  How a context switch is
+ * requested from an ISR is dependent on the port - see the documentation page
+ * for the port in use.
+ *
+ * \ingroup TaskNotifications
+ */
+void vTaskNotifyGiveFromISR( TaskHandle_t xTaskToNotify, BaseType_t *pxHigherPriorityTaskWoken );
+
+/**
+ * Simplified macro for receiving task notification.
+ *
+ * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this
+ * function to be available.
+ *
+ * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
+ * "notification value", which is a 32-bit unsigned integer (uint32_t).
+ *
+ * Events can be sent to a task using an intermediary object.  Examples of such
+ * objects are queues, semaphores, mutexes and event groups.  Task notifications
+ * are a method of sending an event directly to a task without the need for such
+ * an intermediary object.
+ *
+ * A notification sent to a task can optionally perform an action, such as
+ * update, overwrite or increment the task's notification value.  In that way
+ * task notifications can be used to send data to a task, or be used as light
+ * weight and fast binary or counting semaphores.
+ *
+ * ulTaskNotifyTake() is intended for use when a task notification is used as a
+ * faster and lighter weight binary or counting semaphore alternative.  Actual
+ * FreeRTOS semaphores are taken using the xSemaphoreTake() API function, the
+ * equivalent action that instead uses a task notification is
+ * ulTaskNotifyTake().
+ *
+ * When a task is using its notification value as a binary or counting semaphore
+ * other tasks should send notifications to it using the xTaskNotifyGive()
+ * macro, or xTaskNotify() function with the eAction parameter set to
+ * eIncrement.
+ *
+ * ulTaskNotifyTake() can either clear the task's notification value to
+ * zero on exit, in which case the notification value acts like a binary
+ * semaphore, or decrement the task's notification value on exit, in which case
+ * the notification value acts like a counting semaphore.
+ *
+ * A task can use ulTaskNotifyTake() to [optionally] block to wait for a
+ * the task's notification value to be non-zero.  The task does not consume any
+ * CPU time while it is in the Blocked state.
+ *
+ * Where as xTaskNotifyWait() will return when a notification is pending,
+ * ulTaskNotifyTake() will return when the task's notification value is
+ * not zero.
+ *
+ * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details.
+ *
+ * @param xClearCountOnExit if xClearCountOnExit is pdFALSE then the task's
+ * notification value is decremented when the function exits.  In this way the
+ * notification value acts like a counting semaphore.  If xClearCountOnExit is
+ * not pdFALSE then the task's notification value is cleared to zero when the
+ * function exits.  In this way the notification value acts like a binary
+ * semaphore.
+ *
+ * @param xTicksToWait The maximum amount of time that the task should wait in
+ * the Blocked state for the task's notification value to be greater than zero,
+ * should the count not already be greater than zero when
+ * ulTaskNotifyTake() was called.  The task will not consume any processing
+ * time while it is in the Blocked state.  This is specified in kernel ticks,
+ * the macro pdMS_TO_TICSK( value_in_ms ) can be used to convert a time
+ * specified in milliseconds to a time specified in ticks.
+ *
+ * @return The task's notification count before it is either cleared to zero or
+ * decremented (see the xClearCountOnExit parameter).
+ *
+ * \ingroup TaskNotifications
+ */
+uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait );
+
+/*-----------------------------------------------------------
+ * SCHEDULER INTERNALS AVAILABLE FOR PORTING PURPOSES
+ *----------------------------------------------------------*/
+/** @cond */
+/*
+ * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE.  IT IS ONLY
+ * INTENDED FOR USE WHEN IMPLEMENTING A PORT OF THE SCHEDULER AND IS
+ * AN INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER.
+ *
+ * Called from the real time kernel tick (either preemptive or cooperative),
+ * this increments the tick count and checks if any tasks that are blocked
+ * for a finite period required removing from a blocked list and placing on
+ * a ready list.  If a non-zero value is returned then a context switch is
+ * required because either:
+ *   + A task was removed from a blocked list because its timeout had expired,
+ *     or
+ *   + Time slicing is in use and there is a task of equal priority to the
+ *     currently running task.
+ */
+BaseType_t xTaskIncrementTick( void ) PRIVILEGED_FUNCTION;
+
+/*
+ * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE.  IT IS AN
+ * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER.
+ *
+ * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED.
+ *
+ * Removes the calling task from the ready list and places it both
+ * on the list of tasks waiting for a particular event, and the
+ * list of delayed tasks.  The task will be removed from both lists
+ * and replaced on the ready list should either the event occur (and
+ * there be no higher priority tasks waiting on the same event) or
+ * the delay period expires.
+ *
+ * The 'unordered' version replaces the event list item value with the
+ * xItemValue value, and inserts the list item at the end of the list.
+ *
+ * The 'ordered' version uses the existing event list item value (which is the
+ * owning tasks priority) to insert the list item into the event list is task
+ * priority order.
+ *
+ * @param pxEventList The list containing tasks that are blocked waiting
+ * for the event to occur.
+ *
+ * @param xItemValue The item value to use for the event list item when the
+ * event list is not ordered by task priority.
+ *
+ * @param xTicksToWait The maximum amount of time that the task should wait
+ * for the event to occur.  This is specified in kernel ticks,the constant
+ * portTICK_PERIOD_MS can be used to convert kernel ticks into a real time
+ * period.
+ */
+void vTaskPlaceOnEventList( List_t * const pxEventList, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+void vTaskPlaceOnUnorderedEventList( List_t * pxEventList, const TickType_t xItemValue, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+
+/*
+ * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE.  IT IS AN
+ * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER.
+ *
+ * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED.
+ *
+ * This function performs nearly the same function as vTaskPlaceOnEventList().
+ * The difference being that this function does not permit tasks to block
+ * indefinitely, whereas vTaskPlaceOnEventList() does.
+ *
+ */
+void vTaskPlaceOnEventListRestricted( List_t * const pxEventList, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+
+/*
+ * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE.  IT IS AN
+ * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER.
+ *
+ * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED.
+ *
+ * Removes a task from both the specified event list and the list of blocked
+ * tasks, and places it on a ready queue.
+ *
+ * xTaskRemoveFromEventList()/xTaskRemoveFromUnorderedEventList() will be called
+ * if either an event occurs to unblock a task, or the block timeout period
+ * expires.
+ *
+ * xTaskRemoveFromEventList() is used when the event list is in task priority
+ * order.  It removes the list item from the head of the event list as that will
+ * have the highest priority owning task of all the tasks on the event list.
+ * xTaskRemoveFromUnorderedEventList() is used when the event list is not
+ * ordered and the event list items hold something other than the owning tasks
+ * priority.  In this case the event list item value is updated to the value
+ * passed in the xItemValue parameter.
+ *
+ * @return pdTRUE if the task being removed has a higher priority than the task
+ * making the call, otherwise pdFALSE.
+ */
+BaseType_t xTaskRemoveFromEventList( const List_t * const pxEventList ) PRIVILEGED_FUNCTION;
+BaseType_t xTaskRemoveFromUnorderedEventList( ListItem_t * pxEventListItem, const TickType_t xItemValue ) PRIVILEGED_FUNCTION;
+
+/*
+ * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE.  IT IS ONLY
+ * INTENDED FOR USE WHEN IMPLEMENTING A PORT OF THE SCHEDULER AND IS
+ * AN INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER.
+ *
+ * Sets the pointer to the current TCB to the TCB of the highest priority task
+ * that is ready to run.
+ */
+void vTaskSwitchContext( void ) PRIVILEGED_FUNCTION;
+
+/*
+ * THESE FUNCTIONS MUST NOT BE USED FROM APPLICATION CODE.  THEY ARE USED BY
+ * THE EVENT BITS MODULE.
+ */
+TickType_t uxTaskResetEventItemValue( void ) PRIVILEGED_FUNCTION;
+
+/*
+ * Return the handle of the calling task.
+ */
+TaskHandle_t xTaskGetCurrentTaskHandle( void ) PRIVILEGED_FUNCTION;
+
+
+
+/*
+ * Return the handle of the task running on a certain CPU. Because of
+ * the nature of SMP processing, there is no guarantee that this
+ * value will still be valid on return and should only be used for
+ * debugging purposes.
+ */
+TaskHandle_t xTaskGetCurrentTaskHandleForCPU( BaseType_t cpuid );
+
+
+/*
+ * Capture the current time status for future reference.
+ */
+void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) PRIVILEGED_FUNCTION;
+
+/*
+ * Compare the time status now with that previously captured to see if the
+ * timeout has expired.
+ */
+BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, TickType_t * const pxTicksToWait ) PRIVILEGED_FUNCTION;
+
+/*
+ * Shortcut used by the queue implementation to prevent unnecessary call to
+ * taskYIELD();
+ */
+void vTaskMissedYield( void ) PRIVILEGED_FUNCTION;
+
+/*
+ * Returns the scheduler state as taskSCHEDULER_RUNNING,
+ * taskSCHEDULER_NOT_STARTED or taskSCHEDULER_SUSPENDED.
+ */
+BaseType_t xTaskGetSchedulerState( void ) PRIVILEGED_FUNCTION;
+
+/*
+ * Raises the priority of the mutex holder to that of the calling task should
+ * the mutex holder have a priority less than the calling task.
+ */
+void vTaskPriorityInherit( TaskHandle_t const pxMutexHolder ) PRIVILEGED_FUNCTION;
+
+/*
+ * Set the priority of a task back to its proper priority in the case that it
+ * inherited a higher priority while it was holding a semaphore.
+ */
+BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder ) PRIVILEGED_FUNCTION;
+
+/*
+ * Get the uxTCBNumber assigned to the task referenced by the xTask parameter.
+ */
+UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
+
+
+/*
+ * Get the current core affinity of a task
+ */
+BaseType_t xTaskGetAffinity( TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
+
+/*
+ * Set the uxTaskNumber of the task referenced by the xTask parameter to
+ * uxHandle.
+ */
+void vTaskSetTaskNumber( TaskHandle_t xTask, const UBaseType_t uxHandle ) PRIVILEGED_FUNCTION;
+
+/*
+ * Only available when configUSE_TICKLESS_IDLE is set to 1.
+ * If tickless mode is being used, or a low power mode is implemented, then
+ * the tick interrupt will not execute during idle periods.  When this is the
+ * case, the tick count value maintained by the scheduler needs to be kept up
+ * to date with the actual execution time by being skipped forward by a time
+ * equal to the idle period.
+ */
+void vTaskStepTick( const TickType_t xTicksToJump ) PRIVILEGED_FUNCTION;
+
+/*
+ * Only avilable when configUSE_TICKLESS_IDLE is set to 1.
+ * Provided for use within portSUPPRESS_TICKS_AND_SLEEP() to allow the port
+ * specific sleep function to determine if it is ok to proceed with the sleep,
+ * and if it is ok to proceed, if it is ok to sleep indefinitely.
+ *
+ * This function is necessary because portSUPPRESS_TICKS_AND_SLEEP() is only
+ * called with the scheduler suspended, not from within a critical section.  It
+ * is therefore possible for an interrupt to request a context switch between
+ * portSUPPRESS_TICKS_AND_SLEEP() and the low power mode actually being
+ * entered.  eTaskConfirmSleepModeStatus() should be called from a short
+ * critical section between the timer being stopped and the sleep mode being
+ * entered to ensure it is ok to proceed into the sleep mode.
+ */
+eSleepModeStatus eTaskConfirmSleepModeStatus( void ) PRIVILEGED_FUNCTION;
+
+/*
+ * For internal use only.  Increment the mutex held count when a mutex is
+ * taken and return the handle of the task that has taken the mutex.
+ */
+void *pvTaskIncrementMutexHeldCount( void );
+
+/*
+ * This function fills array with TaskSnapshot_t structures for every task in the system.
+ * Used by core dump facility to get snapshots of all tasks in the system.
+ * Only available when configENABLE_TASK_SNAPSHOT is set to 1.
+ * @param pxTaskSnapshotArray Pointer to array of TaskSnapshot_t structures to store tasks snapshot data.
+ * @param uxArraySize Size of tasks snapshots array.
+ * @param pxTcbSz Pointer to store size of TCB.
+ * @return Number of elements stored in array.
+ */
+UBaseType_t uxTaskGetSnapshotAll( TaskSnapshot_t * const pxTaskSnapshotArray, const UBaseType_t uxArraySize, UBaseType_t * const pxTcbSz );
+
+/** @endcond */
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* INC_TASK_H */
+
+
+
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_esp_tls_error_capture_internal.h b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_esp_tls_error_capture_internal.h
new file mode 100644 (file)
index 0000000..f9367c3
--- /dev/null
@@ -0,0 +1,69 @@
+// Copyright 2017-2019 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef __ESP_TLS_ERROR_CAPTURE_INTERNAL_H__
+#define __ESP_TLS_ERROR_CAPTURE_INTERNAL_H__
+/**
+* Note: this is an implementation placeholder for error logger.
+* This version is internal to esp-tls component and only saves single esp_err of last occurred error
+*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+* Definition of different types/sources of error codes reported
+* from different components
+*/
+typedef enum {
+    ERR_TYPE_UNKNOWN = 0,
+    ERR_TYPE_SYSTEM,
+    ERR_TYPE_MBEDTLS,
+    ERR_TYPE_MBEDTLS_CERT_FLAGS,
+    ERR_TYPE_ESP,
+    ERR_TYPE_WOLFSSL,
+    ERR_TYPE_WOLFSSL_CERT_FLAGS,
+} err_type_t;
+
+/**
+ * Error tracker logging macro, this implementation saves latest errors of
+ *  ERR_TYPE_ESP, ERR_TYPE_ESP_TLS and ERR_TYPE_ESP_TLS_CERT_FLAGS types
+ */
+#define ESP_INT_EVENT_TRACKER_CAPTURE(h, type, code)    esp_int_event_tracker_capture(h, type, code)
+
+static inline void esp_int_event_tracker_capture(wb_esp_tls_error_handle_t h, uint32_t type, int code)
+{
+    if (h) {
+        if (type == ERR_TYPE_ESP) {
+            h->last_error = code;
+        } else if (type == ERR_TYPE_MBEDTLS) {
+            h->esp_tls_error_code = code;
+        } else if (type == ERR_TYPE_MBEDTLS_CERT_FLAGS) {
+            h->esp_tls_flags = code;
+        } else if (type == ERR_TYPE_WOLFSSL) {
+            h->esp_tls_error_code = code;
+        } else if (type == ERR_TYPE_WOLFSSL_CERT_FLAGS) {
+            h->esp_tls_flags = code;
+        }
+    }
+}
+
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //__ESP_TLS_ERROR_CAPTURE_INTERNAL_H__
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_esp_tls_mbedtls.h b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_esp_tls_mbedtls.h
new file mode 100644 (file)
index 0000000..3c380d1
--- /dev/null
@@ -0,0 +1,104 @@
+// Copyright 2019 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#pragma once
+#include "sim_esp_tls.h"
+
+/**
+ * Internal Callback API for mbedtls_ssl_read
+ */
+ssize_t wb_esp_mbedtls_read(esp_tls_t *tls, char *data, size_t datalen);
+
+/**
+ * Internal callback API for mbedtls_ssl_write
+ */
+ssize_t wb_esp_mbedtls_write(esp_tls_t *tls, const char *data, size_t datalen);
+
+/**
+ * Internal Callback for mbedtls_handshake
+ */
+int wb_esp_mbedtls_handshake(esp_tls_t *tls, const esp_tls_cfg_t *cfg);
+
+/**
+ * Internal Callback for mbedtls_cleanup , frees up all the memory used by mbedtls
+ */
+void wb_esp_mbedtls_cleanup(esp_tls_t *tls);
+
+/**
+ * Internal Callback for Certificate verification for mbedtls
+ */
+void wb_esp_mbedtls_verify_certificate(esp_tls_t *tls);
+
+/**
+ * Internal Callback for deleting the mbedtls connection
+ */
+void wb_esp_mbedtls_conn_delete(esp_tls_t *tls);
+
+/**
+ * Internal Callback for mbedtls_get_bytes_avail
+ */
+ssize_t wb_esp_mbedtls_get_bytes_avail(esp_tls_t *tls);
+
+/**
+ * Internal Callback for creating ssl handle for mbedtls
+ */
+esp_err_t wb_esp_create_mbedtls_handle(const char *hostname, size_t hostlen, const void *cfg, esp_tls_t *tls);
+
+#ifdef CONFIG_ESP_TLS_SERVER
+/**
+ * Internal Callback for wb_set_server_config
+ *
+ * /note :- can only be used with mbedtls ssl library
+ */
+esp_err_t wb_set_server_config(esp_tls_cfg_server_t *cfg, esp_tls_t *tls);
+
+/**
+ * Internal Callback for mbedtls_server_session_create
+ *
+ * /note :- The function can only be used with mbedtls ssl library
+ */
+int wb_esp_mbedtls_server_session_create(esp_tls_cfg_server_t *cfg, int sockfd, esp_tls_t *tls);
+
+/**
+ * Internal Callback for mbedtls_server_session_delete
+ *
+ * /note :- The function can only be used with mbedtls ssl library
+ */
+void wb_esp_mbedtls_server_session_delete(esp_tls_t *tls);
+#endif
+
+/**
+ * Internal Callback for set_client_config_function
+ */
+esp_err_t wb_set_client_config(const char *hostname, size_t hostlen, esp_tls_cfg_t *cfg, esp_tls_t *tls);
+
+/**
+ * Internal Callback for mbedtls_init_global_ca_store
+ */
+esp_err_t wb_esp_mbedtls_init_global_ca_store(void);
+
+/**
+ * Callback function for setting global CA store data for TLS/SSL using mbedtls
+ */
+esp_err_t wb_esp_mbedtls_set_global_ca_store(const unsigned char *cacert_pem_buf, const unsigned int cacert_pem_bytes);
+
+/**
+ * Internal Callback for esp_tls_global_ca_store
+ */
+mbedtls_x509_crt *wb_esp_mbedtls_get_global_ca_store(void);
+
+/**
+ * Callback function for freeing global ca store for TLS/SSL using mbedtls
+ */
+void wb_esp_mbedtls_free_global_ca_store(void);
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_esp_transport.h b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_esp_transport.h
new file mode 100644 (file)
index 0000000..3564a25
--- /dev/null
@@ -0,0 +1,344 @@
+// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef _WEB_ESP_TRANSPORT_H_
+#define _WEB_ESP_TRANSPORT_H_
+
+#include "esp_err.h"
+#include "queue.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define ESP_TRANSPORT_MEM_CHECK(a, action) if (!(a)) {                                         \
+        ESP_LOGE("%s:%d (%s): %s", __FILE__, __LINE__, __FUNCTION__, "Memory exhausted");       \
+        action;                                                                                     \
+        }
+typedef struct wb_esp_transport_internal* wb_esp_transport_list_handle_t;
+typedef struct wb_esp_tls_last_error* wb_esp_tls_error_handle_t;
+typedef struct wb_esp_transport_item_t* wb_esp_transport_handle_t;
+typedef int (*wb_connect_func)(wb_esp_transport_handle_t t, const char *host, int port, int timeout_ms);
+typedef int (*wb_io_func)(wb_esp_transport_handle_t t, const char *buffer, int len, int timeout_ms);
+typedef int (*wb_io_read_func)(wb_esp_transport_handle_t t, char *buffer, int len, int timeout_ms);
+typedef int (*wb_trans_func)(wb_esp_transport_handle_t t);
+typedef int (*wb_poll_func)(wb_esp_transport_handle_t t, int timeout_ms);
+typedef int (*wb_connect_async_func)(wb_esp_transport_handle_t t, const char *host, int port, int timeout_ms);
+typedef wb_esp_transport_handle_t (*wb_payload_transfer_func)(wb_esp_transport_handle_t);
+typedef int (*wb_get_socket_func)(wb_esp_transport_handle_t t);
+struct wb_esp_transport_item_t {
+    int             port;
+    int             socket;         /*!< Socket to use in this transport */
+    char            *scheme;        /*!< Tag name */
+    void            *context;       /*!< Context data */
+    void            *data;          /*!< Additional transport data */
+    wb_connect_func    _connect;       /*!< Connect function of this transport */
+    wb_io_read_func    _read;          /*!< Read */
+    wb_io_func         _write;         /*!< Write */
+    wb_trans_func      _close;         /*!< Close */
+    wb_poll_func       _poll_read;     /*!< Poll and read */
+    wb_poll_func       _poll_write;    /*!< Poll and write */
+    wb_trans_func      _destroy;       /*!< Destroy and free transport */
+    wb_connect_async_func _connect_async;      /*!< non-blocking connect function of this transport */
+    wb_payload_transfer_func  _parent_transfer;        /*!< Function returning underlying transport layer */
+    wb_esp_tls_error_handle_t     error_handle;            /*!< Pointer to esp-tls error handle */
+    wb_get_socket_func        _get_socket;
+
+    STAILQ_ENTRY(wb_esp_transport_item_t) next;
+};
+
+/**
+ * @brief      Create transport list
+ *
+ * @return     A handle can hold all transports
+ */
+wb_esp_transport_list_handle_t wb_esp_transport_list_init(void);
+
+/**
+ * @brief      Cleanup and free all transports, include itself,
+ *             this function will invoke esp_transport_destroy of every transport have added this the list
+ *
+ * @param[in]  list  The list
+ *
+ * @return
+ *     - ESP_OK
+ *     - ESP_FAIL
+ */
+esp_err_t wb_esp_transport_list_destroy(wb_esp_transport_list_handle_t list);
+
+/**
+ * @brief      Add a transport to the list, and define a scheme to indentify this transport in the list
+ *
+ * @param[in]  list    The list
+ * @param[in]  t       The Transport
+ * @param[in]  scheme  The scheme
+ *
+ * @return
+ *     - ESP_OK
+ */
+esp_err_t wb_esp_transport_list_add(wb_esp_transport_list_handle_t list, wb_esp_transport_handle_t t, const char *scheme);
+
+/**
+ * @brief      This function will remove all transport from the list,
+ *             invoke esp_transport_destroy of every transport have added this the list
+ *
+ * @param[in]  list  The list
+ *
+ * @return
+ *     - ESP_OK
+ *     - ESP_ERR_INVALID_ARG
+ */
+esp_err_t wb_esp_transport_list_clean(wb_esp_transport_list_handle_t list);
+
+/**
+ * @brief      Get the transport by scheme, which has been defined when calling function `esp_transport_list_add`
+ *
+ * @param[in]  list  The list
+ * @param[in]  tag   The tag
+ *
+ * @return     The transport handle
+ */
+wb_esp_transport_handle_t wb_esp_transport_list_get_transport(wb_esp_transport_list_handle_t list, const char *scheme);
+
+/**
+ * @brief      Initialize a transport handle object
+ *
+ * @return     The transport handle
+ */
+wb_esp_transport_handle_t wb_esp_transport_init(void);
+
+/**
+ * @brief      Cleanup and free memory the transport
+ *
+ * @param[in]  t     The transport handle
+ *
+ * @return
+ *     - ESP_OK
+ *     - ESP_FAIL
+ */
+esp_err_t wb_esp_transport_destroy(wb_esp_transport_handle_t t);
+
+/**
+ * @brief      Get default port number used by this transport
+ *
+ * @param[in]  t     The transport handle
+ *
+ * @return     the port number
+ */
+int wb_esp_transport_get_default_port(wb_esp_transport_handle_t t);
+
+/**
+ * @brief      Set default port number that can be used by this transport
+ *
+ * @param[in]  t     The transport handle
+ * @param[in]  port  The port number
+ *
+ * @return
+ *     - ESP_OK
+ *     - ESP_FAIL
+ */
+esp_err_t wb_esp_transport_set_default_port(wb_esp_transport_handle_t t, int port);
+
+/**
+ * @brief      Transport connection function, to make a connection to server
+ *
+ * @param      t           The transport handle
+ * @param[in]  host        Hostname
+ * @param[in]  port        Port
+ * @param[in]  timeout_ms  The timeout milliseconds
+ *
+ * @return
+ * - socket for will use by this transport
+ * - (-1) if there are any errors, should check errno
+ */
+int wb_esp_transport_connect(wb_esp_transport_handle_t t, const char *host, int port, int timeout_ms);
+
+/**
+ * @brief      Non-blocking transport connection function, to make a connection to server
+ *
+ * @param      t           The transport handle
+ * @param[in]  host        Hostname
+ * @param[in]  port        Port
+ * @param[in]  timeout_ms  The timeout milliseconds
+ *
+ * @return
+ * - socket for will use by this transport
+ * - (-1) if there are any errors, should check errno
+ */
+int wb_esp_transport_connect_async(wb_esp_transport_handle_t t, const char *host, int port, int timeout_ms);
+
+/**
+ * @brief      Transport read function
+ *
+ * @param      t           The transport handle
+ * @param      buffer      The buffer
+ * @param[in]  len         The length
+ * @param[in]  timeout_ms  The timeout milliseconds
+ *
+ * @return
+ *  - Number of bytes was read
+ *  - (-1) if there are any errors, should check errno
+ */
+int wb_esp_transport_read(wb_esp_transport_handle_t t, char *buffer, int len, int timeout_ms);
+
+/**
+ * @brief      Poll the transport until readable or timeout
+ *
+ * @param[in]  t           The transport handle
+ * @param[in]  timeout_ms  The timeout milliseconds
+ *
+ * @return
+ *     - 0      Timeout
+ *     - (-1)   If there are any errors, should check errno
+ *     - other  The transport can read
+ */
+int wb_esp_transport_poll_read(wb_esp_transport_handle_t t, int timeout_ms);
+
+/**
+ * @brief      Transport write function
+ *
+ * @param      t           The transport handle
+ * @param      buffer      The buffer
+ * @param[in]  len         The length
+ * @param[in]  timeout_ms  The timeout milliseconds
+ *
+ * @return
+ *  - Number of bytes was written
+ *  - (-1) if there are any errors, should check errno
+ */
+int wb_esp_transport_write(wb_esp_transport_handle_t t, const char *buffer, int len, int timeout_ms);
+
+/**
+ * @brief      Poll the transport until writeable or timeout
+ *
+ * @param[in]  t           The transport handle
+ * @param[in]  timeout_ms  The timeout milliseconds
+ *
+ * @return
+ *     - 0      Timeout
+ *     - (-1)   If there are any errors, should check errno
+ *     - other  The transport can write
+ */
+int wb_esp_transport_poll_write(wb_esp_transport_handle_t t, int timeout_ms);
+
+/**
+ * @brief      Transport close
+ *
+ * @param      t     The transport handle
+ *
+ * @return
+ * - 0 if ok
+ * - (-1) if there are any errors, should check errno
+ */
+int wb_esp_transport_close(wb_esp_transport_handle_t t);
+
+/**
+ * @brief      Get user data context of this transport
+ *
+ * @param[in]  t        The transport handle
+ *
+ * @return     The user data context
+ */
+void *wb_esp_transport_get_context_data(wb_esp_transport_handle_t t);
+
+/**
+ * @brief      Get transport handle of underlying protocol
+ *             which can access this protocol payload directly
+ *             (used for receiving longer msg multiple times)
+ *
+ * @param[in]  t        The transport handle
+ *
+ * @return     Payload transport handle
+ */
+wb_esp_transport_handle_t wb_esp_transport_get_payload_transport_handle(wb_esp_transport_handle_t t);
+
+/**
+ * @brief      Set the user context data for this transport
+ *
+ * @param[in]  t        The transport handle
+ * @param      data     The user data context
+ *
+ * @return
+ *     - ESP_OK
+ */
+esp_err_t wb_esp_transport_set_context_data(wb_esp_transport_handle_t t, void *data);
+
+/**
+ * @brief      Set transport functions for the transport handle
+ *
+ * @param[in]  t            The transport handle
+ * @param[in]  _connect     The connect function pointer
+ * @param[in]  _read        The read function pointer
+ * @param[in]  _write       The write function pointer
+ * @param[in]  _close       The close function pointer
+ * @param[in]  _poll_read   The poll read function pointer
+ * @param[in]  _poll_write  The poll write function pointer
+ * @param[in]  _destroy     The destroy function pointer
+ *
+ * @return
+ *     - ESP_OK
+ */
+esp_err_t wb_esp_transport_set_func(wb_esp_transport_handle_t t,
+                             wb_connect_func _connect,
+                             wb_io_read_func _read,
+                             wb_io_func _write,
+                             wb_trans_func _close,
+                             wb_poll_func _poll_read,
+                             wb_poll_func _poll_write,
+                             wb_trans_func _destroy);
+
+
+/**
+ * @brief      Set transport functions for the transport handle
+ *
+ * @param[in]  t                    The transport handle
+ * @param[in]  _connect_async_func  The connect_async function pointer
+ *
+ * @return
+ *     - ESP_OK
+ *     - ESP_FAIL
+ */
+esp_err_t wb_esp_transport_set_async_connect_func(wb_esp_transport_handle_t t, wb_connect_async_func _connect_async_func);
+
+/**
+ * @brief      Set parent transport function to the handle
+ *
+ * @param[in]  t                    The transport handle
+ * @param[in]  _parent_transport    The underlying transport getter pointer
+ *
+ * @return
+ *     - ESP_OK
+ *     - ESP_FAIL
+ */
+esp_err_t wb_esp_transport_set_parent_transport_func(wb_esp_transport_handle_t t, wb_payload_transfer_func _parent_transport);
+
+/**
+ * @brief      Returns esp_tls error handle.
+ *             Warning: The returned pointer is valid only as long as wb_esp_transport_handle_t exists. Once transport
+ *             handle gets destroyed, this value (wb_esp_tls_error_handle_t) is freed automatically.
+ *
+ * @param[in]  A transport handle
+ *
+ * @return
+ *            - valid pointer of esp_error_handle_t
+ *            - NULL if invalid transport handle
+  */
+wb_esp_tls_error_handle_t wb_esp_transport_get_error_handle(wb_esp_transport_handle_t t);
+
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* _ESP_TRANSPORT_ */
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_esp_transport_ssl.h b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_esp_transport_ssl.h
new file mode 100644 (file)
index 0000000..31e930b
--- /dev/null
@@ -0,0 +1,86 @@
+// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef _WEB_ESP_TRANSPORT_SSL_H_
+#define _WEB_ESP_TRANSPORT_SSL_H_
+
+#include "web_esp_transport.h"
+//#include "sim_esp_tls.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/**
+ * @brief       Create new SSL transport, the transport handle must be release esp_transport_destroy callback
+ *
+ * @return      the allocated wb_esp_transport_handle_t, or NULL if the handle can not be allocated
+ */
+wb_esp_transport_handle_t wb_esp_transport_ssl_init(void);
+
+/**
+ * @brief      Set SSL certificate data (as PEM format).
+ *             Note that, this function stores the pointer to data, rather than making a copy.
+ *             So this data must remain valid until after the connection is cleaned up
+ *
+ * @param      t     ssl transport
+ * @param[in]  data  The pem data
+ * @param[in]  len   The length
+ */
+void wb_esp_transport_ssl_set_cert_data(wb_esp_transport_handle_t t, const char *data, int len);
+
+/**
+ * @brief      Enable global CA store for SSL connection
+ *
+ * @param      t    ssl transport
+ */
+void wb_esp_transport_ssl_enable_global_ca_store(wb_esp_transport_handle_t t);
+
+/**
+ * @brief      Set SSL client certificate data for mutual authentication (as PEM format).
+ *             Note that, this function stores the pointer to data, rather than making a copy.
+ *             So this data must remain valid until after the connection is cleaned up
+ *
+ * @param      t     ssl transport
+ * @param[in]  data  The pem data
+ * @param[in]  len   The length
+ */
+void wb_esp_transport_ssl_set_client_cert_data(wb_esp_transport_handle_t t, const char *data, int len);
+
+/**
+ * @brief      Set SSL client key data for mutual authentication (as PEM format).
+ *             Note that, this function stores the pointer to data, rather than making a copy.
+ *             So this data must remain valid until after the connection is cleaned up
+ *
+ * @param      t     ssl transport
+ * @param[in]  data  The pem data
+ * @param[in]  len   The length
+ */
+void wb_esp_transport_ssl_set_client_key_data(wb_esp_transport_handle_t t, const char *data, int len);
+
+/**
+ * @brief      Skip validation of certificate's common name field
+ *
+ * @note       Skipping CN validation is not recommended
+ *
+ * @param      t     ssl transport
+ */
+void wb_esp_transport_ssl_skip_common_name_check(wb_esp_transport_handle_t t);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* _ESP_TRANSPORT_SSL_H_ */
+
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_esp_transport_ssl_internal.h b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_esp_transport_ssl_internal.h
new file mode 100644 (file)
index 0000000..5fd818a
--- /dev/null
@@ -0,0 +1,30 @@
+// Copyright 2015-2019 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef _WEB_ESP_TRANSPORT_INTERNAL_H_
+#define _WEB_ESP_TRANSPORT_INTERNAL_H_
+
+/**
+ * @brief      Sets error to common transport handle
+ *
+ *             Note: This function copies the supplied error handle object to tcp_transport's internal
+ *             error handle object
+ *
+ * @param[in]  A transport handle
+ *
+ */
+void wb_esp_transport_set_errors(wb_esp_transport_handle_t t, const wb_esp_tls_error_handle_t error_handle);
+
+
+#endif /* _ESP_TRANSPORT_INTERNAL_H_ */
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_esp_transport_tcp.h b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_esp_transport_tcp.h
new file mode 100644 (file)
index 0000000..a3dccff
--- /dev/null
@@ -0,0 +1,36 @@
+// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef _WEB_ESP_TRANSPORT_TCP_H_
+#define _WEB_ESP_TRANSPORT_TCP_H_
+
+#include "web_esp_transport.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @brief      Create TCP transport, the transport handle must be release esp_transport_destroy callback
+ *
+ * @return  the allocated wb_esp_transport_handle_t, or NULL if the handle can not be allocated
+ */
+wb_esp_transport_handle_t wb_esp_transport_tcp_init(void);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _ESP_TRANSPORT_TCP_H_ */
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_esp_transport_ws.h b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_esp_transport_ws.h
new file mode 100644 (file)
index 0000000..afea816
--- /dev/null
@@ -0,0 +1,101 @@
+/*
+ * This file is subject to the terms and conditions defined in
+ * file 'LICENSE', which is part of this source code package.
+ * Tuan PM <tuanpm at live dot com>
+ */
+
+#ifndef _WEB_ESP_TRANSPORT_WS_H_
+#define _WEB_ESP_TRANSPORT_WS_H_
+
+#include "web_esp_transport.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum ws_transport_opcodes {
+    WS_TRANSPORT_OPCODES_CONT =  0x00,
+    WS_TRANSPORT_OPCODES_TEXT =  0x01,
+    WS_TRANSPORT_OPCODES_BINARY = 0x02,
+    WS_TRANSPORT_OPCODES_CLOSE = 0x08,
+    WS_TRANSPORT_OPCODES_PING = 0x09,
+    WS_TRANSPORT_OPCODES_PONG = 0x0a,    
+    WS_TRANSPORT_OPCODES_FIN = 0x80,
+} ws_transport_opcodes_t;
+
+/**
+ * @brief      Create web socket transport
+ *
+ * @return
+ *  - transport
+ *  - NULL
+ */
+wb_esp_transport_handle_t wb_esp_transport_ws_init(wb_esp_transport_handle_t parent_handle);
+
+/**
+ * @brief       Set HTTP path to update protocol to websocket
+ *
+ * @param t     websocket transport handle
+ * @param path  The HTTP Path
+ */
+void wb_esp_transport_ws_set_path(wb_esp_transport_handle_t t, const char *path);
+
+/**
+ * @brief               Set websocket sub protocol header
+ *
+ * @param t             websocket transport handle
+ * @param sub_protocol  Sub protocol string
+ *
+ * @return
+ *      - ESP_OK on success
+ *      - One of the error codes
+ */
+esp_err_t wb_esp_transport_ws_set_subprotocol(wb_esp_transport_handle_t t, const char *sub_protocol);
+
+/**
+ * @brief               Sends websocket raw message with custom opcode and payload
+ *
+ * Note that generic esp_transport_write for ws handle sends
+ * binary massages by default if size is > 0 and
+ * ping message if message size is set to 0.
+ * This API is provided to support explicit messages with arbitrary opcode,
+ * should it be PING, PONG or TEXT message with arbitrary data.
+ *
+ * @param[in]  t           Websocket transport handle
+ * @param[in]  opcode      ws operation code
+ * @param[in]  buffer      The buffer
+ * @param[in]  len         The length
+ * @param[in]  timeout_ms  The timeout milliseconds
+ *
+ * @return
+ *  - Number of bytes was written
+ *  - (-1) if there are any errors, should check errno
+ */
+int wb_esp_transport_ws_send_raw(wb_esp_transport_handle_t t, ws_transport_opcodes_t opcode, const char *b, int len, int timeout_ms);
+
+/**
+ * @brief               Returns websocket op-code for last received data
+ *
+ * @param t             websocket transport handle
+ *
+ * @return
+ *      - Received op-code as enum
+ */
+ws_transport_opcodes_t wb_esp_transport_ws_get_read_opcode(wb_esp_transport_handle_t t);
+
+/**
+ * @brief               Returns payload length of the last received data
+ *
+ * @param t             websocket transport handle
+ *
+ * @return
+ *      - Number of bytes in the payload
+ */
+int wb_esp_transport_ws_get_read_payload_len(wb_esp_transport_handle_t t);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _ESP_TRANSPORT_WS_H_ */
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_http_parser.h b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/common/web_http_parser.h
new file mode 100644 (file)
index 0000000..78b202d
--- /dev/null
@@ -0,0 +1,364 @@
+/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+#ifndef http_parser_h
+#define http_parser_h
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Also update SONAME in the Makefile whenever you change these. */
+#define HTTP_PARSER_VERSION_MAJOR 2
+#define HTTP_PARSER_VERSION_MINOR 7
+#define HTTP_PARSER_VERSION_PATCH 0
+
+typedef  unsigned int           size_t;
+
+//#include <sys/types.h>
+#if defined(_WIN32) && !defined(__MINGW32__) && \
+  (!defined(_MSC_VER) || _MSC_VER<1600) && !defined(__WINE__)
+//#include <BaseTsd.h>
+//#include <stddef.h>
+typedef __int8 int8_t;
+typedef unsigned __int8 uint8_t;
+typedef __int16 int16_t;
+typedef unsigned __int16 uint16_t;
+typedef __int32 int32_t;
+typedef unsigned __int32 uint32_t;
+typedef __int64 int64_t;
+typedef unsigned __int64 uint64_t;
+#else
+#include <stdint.h>
+#endif
+
+/* Compile with -DHTTP_PARSER_STRICT=0 to make less checks, but run
+ * faster
+ */
+#ifndef HTTP_PARSER_STRICT
+# define HTTP_PARSER_STRICT 1
+#endif
+
+/* Maximium header size allowed. If the macro is not defined
+ * before including this header then the default is used. To
+ * change the maximum header size, define the macro in the build
+ * environment (e.g. -DHTTP_MAX_HEADER_SIZE=<value>). To remove
+ * the effective limit on the size of the header, define the macro
+ * to a very large number (e.g. -DHTTP_MAX_HEADER_SIZE=0x7fffffff)
+ */
+#ifndef HTTP_MAX_HEADER_SIZE
+# define HTTP_MAX_HEADER_SIZE (80*1024)
+#endif
+
+typedef struct http_parser http_parser;
+typedef struct http_parser_settings http_parser_settings;
+
+
+/* Callbacks should return non-zero to indicate an error. The parser will
+ * then halt execution.
+ *
+ * The one exception is on_headers_complete. In a HTTP_RESPONSE parser
+ * returning '1' from on_headers_complete will tell the parser that it
+ * should not expect a body. This is used when receiving a response to a
+ * HEAD request which may contain 'Content-Length' or 'Transfer-Encoding:
+ * chunked' headers that indicate the presence of a body.
+ *
+ * Returning `2` from on_headers_complete will tell parser that it should not
+ * expect neither a body nor any futher responses on this connection. This is
+ * useful for handling responses to a CONNECT request which may not contain
+ * `Upgrade` or `Connection: upgrade` headers.
+ *
+ * http_data_cb does not return data chunks. It will be called arbitrarily
+ * many times for each string. E.G. you might get 10 callbacks for "on_url"
+ * each providing just a few characters more data.
+ */
+typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);
+typedef int (*http_cb) (http_parser*);
+
+
+/* Request Methods */
+#define HTTP_METHOD_MAP(XX)         \
+  XX(0,  DELETE,      DELETE)       \
+  XX(1,  GET,         GET)          \
+  XX(2,  HEAD,        HEAD)         \
+  XX(3,  POST,        POST)         \
+  XX(4,  PUT,         PUT)          \
+  /* pathological */                \
+  XX(5,  CONNECT,     CONNECT)      \
+  XX(6,  OPTIONS,     OPTIONS)      \
+  XX(7,  TRACE,       TRACE)        \
+  /* WebDAV */                      \
+  XX(8,  COPY,        COPY)         \
+  XX(9,  LOCK,        LOCK)         \
+  XX(10, MKCOL,       MKCOL)        \
+  XX(11, MOVE,        MOVE)         \
+  XX(12, PROPFIND,    PROPFIND)     \
+  XX(13, PROPPATCH,   PROPPATCH)    \
+  XX(14, SEARCH,      SEARCH)       \
+  XX(15, UNLOCK,      UNLOCK)       \
+  XX(16, BIND,        BIND)         \
+  XX(17, REBIND,      REBIND)       \
+  XX(18, UNBIND,      UNBIND)       \
+  XX(19, ACL,         ACL)          \
+  /* subversion */                  \
+  XX(20, REPORT,      REPORT)       \
+  XX(21, MKACTIVITY,  MKACTIVITY)   \
+  XX(22, CHECKOUT,    CHECKOUT)     \
+  XX(23, MERGE,       MERGE)        \
+  /* upnp */                        \
+  XX(24, MSEARCH,     M-SEARCH)     \
+  XX(25, NOTIFY,      NOTIFY)       \
+  XX(26, SUBSCRIBE,   SUBSCRIBE)    \
+  XX(27, UNSUBSCRIBE, UNSUBSCRIBE)  \
+  /* RFC-5789 */                    \
+  XX(28, PATCH,       PATCH)        \
+  XX(29, PURGE,       PURGE)        \
+  /* CalDAV */                      \
+  XX(30, MKCALENDAR,  MKCALENDAR)   \
+  /* RFC-2068, section 19.6.1.2 */  \
+  XX(31, LINK,        LINK)         \
+  XX(32, UNLINK,      UNLINK)       \
+
+enum http_method
+  {
+#define XX(num, name, string) HTTP_##name = num,
+  HTTP_METHOD_MAP(XX)
+#undef XX
+  };
+
+
+enum http_parser_type { HTTP_REQUEST, HTTP_RESPONSE, HTTP_BOTH };
+
+
+/* Flag values for http_parser.flags field */
+enum flags
+  { F_CHUNKED               = 1 << 0
+  , F_CONNECTION_KEEP_ALIVE = 1 << 1
+  , F_CONNECTION_CLOSE      = 1 << 2
+  , F_CONNECTION_UPGRADE    = 1 << 3
+  , F_TRAILING              = 1 << 4
+  , F_UPGRADE               = 1 << 5
+  , F_SKIPBODY              = 1 << 6
+  , F_CONTENTLENGTH         = 1 << 7
+  };
+
+
+/* Map for errno-related constants
+ *
+ * The provided argument should be a macro that takes 2 arguments.
+ */
+#define HTTP_ERRNO_MAP(XX)                                           \
+  /* No error */                                                     \
+  XX(OK, "success")                                                  \
+                                                                     \
+  /* Callback-related errors */                                      \
+  XX(CB_message_begin, "the on_message_begin callback failed")       \
+  XX(CB_url, "the on_url callback failed")                           \
+  XX(CB_header_field, "the on_header_field callback failed")         \
+  XX(CB_header_value, "the on_header_value callback failed")         \
+  XX(CB_headers_complete, "the on_headers_complete callback failed") \
+  XX(CB_body, "the on_body callback failed")                         \
+  XX(CB_message_complete, "the on_message_complete callback failed") \
+  XX(CB_status, "the on_status callback failed")                     \
+  XX(CB_chunk_header, "the on_chunk_header callback failed")         \
+  XX(CB_chunk_complete, "the on_chunk_complete callback failed")     \
+                                                                     \
+  /* Parsing-related errors */                                       \
+  XX(INVALID_EOF_STATE, "stream ended at an unexpected time")        \
+  XX(HEADER_OVERFLOW,                                                \
+     "too many header bytes seen; overflow detected")                \
+  XX(CLOSED_CONNECTION,                                              \
+     "data received after completed connection: close message")      \
+  XX(INVALID_VERSION, "invalid HTTP version")                        \
+  XX(INVALID_STATUS, "invalid HTTP status code")                     \
+  XX(INVALID_METHOD, "invalid HTTP method")                          \
+  XX(INVALID_URL, "invalid URL")                                     \
+  XX(INVALID_HOST, "invalid host")                                   \
+  XX(INVALID_PORT, "invalid port")                                   \
+  XX(INVALID_PATH, "invalid path")                                   \
+  XX(INVALID_QUERY_STRING, "invalid query string")                   \
+  XX(INVALID_FRAGMENT, "invalid fragment")                           \
+  XX(LF_EXPECTED, "LF character expected")                           \
+  XX(INVALID_HEADER_TOKEN, "invalid character in header")            \
+  XX(INVALID_CONTENT_LENGTH,                                         \
+     "invalid character in content-length header")                   \
+  XX(UNEXPECTED_CONTENT_LENGTH,                                      \
+     "unexpected content-length header")                             \
+  XX(INVALID_CHUNK_SIZE,                                             \
+     "invalid character in chunk size header")                       \
+  XX(INVALID_CONSTANT, "invalid constant string")                    \
+  XX(INVALID_INTERNAL_STATE, "encountered unexpected internal state")\
+  XX(STRICT, "strict mode assertion failed")                         \
+  XX(PAUSED, "parser is paused")                                     \
+  XX(UNKNOWN, "an unknown error occurred")
+
+
+/* Define HPE_* values for each errno value above */
+#define HTTP_ERRNO_GEN(n, s) HPE_##n,
+enum http_errno {
+  HTTP_ERRNO_MAP(HTTP_ERRNO_GEN)
+};
+#undef HTTP_ERRNO_GEN
+
+
+/* Get an http_errno value from an http_parser */
+#define HTTP_PARSER_ERRNO(p)            ((enum http_errno) (p)->http_errno)
+
+
+struct http_parser {
+  /** PRIVATE **/
+  unsigned int type : 2;         /* enum http_parser_type */
+  unsigned int flags : 8;        /* F_* values from 'flags' enum; semi-public */
+  unsigned int state : 7;        /* enum state from http_parser.c */
+  unsigned int header_state : 7; /* enum header_state from http_parser.c */
+  unsigned int index : 7;        /* index into current matcher */
+  unsigned int lenient_http_headers : 1;
+
+  uint32_t nread;          /* # bytes read in various scenarios */
+  uint64_t content_length; /* # bytes in body (0 if no Content-Length header) */
+
+  /** READ-ONLY **/
+  unsigned short http_major;
+  unsigned short http_minor;
+  unsigned int status_code : 16; /* responses only */
+  unsigned int method : 8;       /* requests only */
+  unsigned int http_errno : 7;
+
+  /* 1 = Upgrade header was present and the parser has exited because of that.
+   * 0 = No upgrade header present.
+   * Should be checked when wb_http_parser_execute() returns in addition to
+   * error checking.
+   */
+  unsigned int upgrade : 1;
+
+  /** PUBLIC **/
+  void *data; /* A pointer to get hook to the "connection" or "socket" object */
+};
+
+
+struct http_parser_settings {
+  http_cb      on_message_begin;
+  http_data_cb on_url;
+  http_data_cb on_status;
+  http_data_cb on_header_field;
+  http_data_cb on_header_value;
+  http_cb      on_headers_complete;
+  http_data_cb on_body;
+  http_cb      on_message_complete;
+  /* When on_chunk_header is called, the current chunk length is stored
+   * in parser->content_length.
+   */
+  http_cb      on_chunk_header;
+  http_cb      on_chunk_complete;
+};
+
+
+enum http_parser_url_fields
+  { UF_SCHEMA           = 0
+  , UF_HOST             = 1
+  , UF_PORT             = 2
+  , UF_PATH             = 3
+  , UF_QUERY            = 4
+  , UF_FRAGMENT         = 5
+  , UF_USERINFO         = 6
+  , UF_MAX              = 7
+  };
+
+
+/* Result structure for wb_http_parser_parse_url().
+ *
+ * Callers should index into field_data[] with UF_* values iff field_set
+ * has the relevant (1 << UF_*) bit set. As a courtesy to clients (and
+ * because we probably have padding left over), we convert any port to
+ * a uint16_t.
+ */
+struct http_parser_url {
+  uint16_t field_set;           /* Bitmask of (1 << UF_*) values */
+  uint16_t port;                /* Converted UF_PORT string */
+
+  struct {
+    uint16_t off;               /* Offset into buffer in which field starts */
+    uint16_t len;               /* Length of run in buffer */
+  } field_data[UF_MAX];
+};
+
+
+/* Returns the library version. Bits 16-23 contain the major version number,
+ * bits 8-15 the minor version number and bits 0-7 the patch level.
+ * Usage example:
+ *
+ *   unsigned long version = wb_http_parser_version();
+ *   unsigned major = (version >> 16) & 255;
+ *   unsigned minor = (version >> 8) & 255;
+ *   unsigned patch = version & 255;
+ *   printf("http_parser v%u.%u.%u\n", major, minor, patch);
+ */
+unsigned long wb_http_parser_version(void);
+
+void wb_http_parser_init(http_parser *parser, enum http_parser_type type);
+
+
+/* Initialize http_parser_settings members to 0
+ */
+void wb_http_parser_settings_init(http_parser_settings *settings);
+
+
+/* Executes the parser. Returns number of parsed bytes. Sets
+ * `parser->http_errno` on error. */
+size_t wb_http_parser_execute(http_parser *parser,
+                           const http_parser_settings *settings,
+                           const char *data,
+                           size_t len);
+
+
+/* If wb_http_should_keep_alive() in the on_headers_complete or
+ * on_message_complete callback returns 0, then this should be
+ * the last message on the connection.
+ * If you are the server, respond with the "Connection: close" header.
+ * If you are the client, close the connection.
+ */
+int wb_http_should_keep_alive(const http_parser *parser);
+
+/* Returns a string version of the HTTP method. */
+const char *wb_http_method_str(enum http_method m);
+
+/* Return a string name of the given error */
+const char *wb_http_errno_name(enum http_errno err);
+
+/* Return a string description of the given error */
+const char *wb_http_errno_description(enum http_errno err);
+
+/* Initialize all http_parser_url members to 0 */
+void wb_http_parser_url_init(struct http_parser_url *u);
+
+/* Parse a URL; return nonzero on failure */
+int wb_http_parser_parse_url(const char *buf, size_t buflen,
+                          int is_connect,
+                          struct http_parser_url *u);
+
+/* Pause or un-pause the parser; a nonzero value pauses */
+void wb_http_parser_pause(http_parser *parser, int paused);
+
+/* Checks if this is the final chunk of the body. */
+int wb_http_body_is_final(const http_parser *parser);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/sim_esp_websocket_client.h b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/inc/sim_esp_websocket_client.h
new file mode 100644 (file)
index 0000000..d9f8698
--- /dev/null
@@ -0,0 +1,285 @@
+// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef _SIM_ESP_WEBSOCKET_CLIENT_H_
+#define _SIM_ESP_WEBSOCKET_CLIENT_H_
+
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <string.h>
+#include "web_esp_transport_ws.h"
+#include "esp_err.h"
+#include "web_esp_transport.h"
+#include "osa_old_api.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+typedef unsigned long UINT32;
+
+#define sim_portTICK_RATE_MS   1000
+#define sim_portTICK_PERIOD_MS 1000
+
+//ESP_EVENT_DECLARE_BASE(WEBSOCKET_EVENTS);         // declaration of the task events family
+
+/******************************************
+ function declared in here
+ *****************************************/
+extern char* strdup(const char* str);
+extern void free( void *p );
+extern void *malloc( size_t Size );
+extern void *calloc( size_t nItems, size_t itemSize );
+//extern int strtol(const char *p1, char **p2, int base);
+
+typedef struct sim_esp_websocket_client *sim_esp_websocket_client_handle_t;
+typedef void   (*sim_esp_event_handler_t)(int32_t event_id, void* event_data); /**< function called when an event is posted to the queue */
+
+/**
+ * @brief Websocket Client events id
+ */
+typedef enum {
+    WEBSOCKET_EVENT_ANY = -1,
+    WEBSOCKET_EVENT_ERROR = 0,      /*!< This event occurs when there are any errors during execution */
+    WEBSOCKET_EVENT_CONNECTED,      /*!< Once the Websocket has been connected to the server, no data exchange has been performed */
+    WEBSOCKET_EVENT_DISCONNECTED,   /*!< The connection has been disconnected */
+    WEBSOCKET_EVENT_DATA,           /*!< When receiving data from the server, possibly multiple portions of the packet */
+       WEBSOCKET_EVENT_CLOSED,
+       WEBSOCKET_EVENT_MAX
+} sim_esp_websocket_event_id_t;
+
+/**
+ * @brief Websocket event data
+ */
+typedef struct {
+    char *data_ptr;                   /*!< Data pointer */
+    int data_len;                           /*!< Data length */
+    uint8_t op_code;                        /*!< Received opcode */
+    sim_esp_websocket_client_handle_t client;   /*!< sim_esp_websocket_client_handle_t context */
+    void *user_context;                     /*!< user_data context, from sim_esp_websocket_client_config_t user_data */
+    int payload_len;                        /*!< Total payload length, payloads exceeding buffer will be posted through multiple events */
+    int payload_offset;                     /*!< Actual offset for the data associated with this event */
+       sim_esp_websocket_event_id_t event;
+} sim_esp_websocket_event_data_t;
+
+typedef struct {
+    UINT32                      task_stack;
+    int                         task_prio;
+    char                        *uri;
+    char                        *p_host;
+    char                        host[64];
+    char                        *p_path;
+    char                        path[1024];
+    char                        scheme[16];
+    char                        *username;
+    char                        *password;
+    int                         port;
+    bool                        auto_reconnect;
+    void                        *user_context;
+    int                         network_timeout_ms;
+    char                        *subprotocol;
+} sim_websocket_config_storage_t;
+
+typedef enum {
+    WEBSOCKET_STATE_ERROR = -1,
+    WEBSOCKET_STATE_UNKNOW = 0,
+    WEBSOCKET_STATE_INIT,
+    WEBSOCKET_STATE_CONNECTED,
+    WEBSOCKET_STATE_WAIT_TIMEOUT,
+    WEBSOCKET_STATE_CLOSING,
+} sim_websocket_client_state_t;
+
+struct sim_esp_websocket_client {
+       sim_esp_event_handler_t         handler;
+    wb_esp_transport_list_handle_t transport_list;
+    wb_esp_transport_handle_t      transport;
+    sim_websocket_config_storage_t  *config;
+    sim_websocket_client_state_t    state;
+       OSAMutexRef                 lock;
+    UINT32                      keepalive_tick_ms;
+    UINT32                      reconnect_tick_ms;
+    UINT32                      ping_tick_ms;
+    int                         wait_timeout_ms;
+    int                         auto_reconnect;
+    char                        *rx_buffer;
+    char                        *tx_buffer;
+    int                         buffer_size;
+    ws_transport_opcodes_t      last_opcode;
+    int                         payload_len;
+    int                         payload_offset;
+};
+
+/**
+ * @brief Websocket Client transport
+ */
+typedef enum {
+    WEBSOCKET_TRANSPORT_UNKNOWN = 0x0,  /*!< Transport unknown */
+    WEBSOCKET_TRANSPORT_OVER_TCP,       /*!< Transport over tcp */
+    WEBSOCKET_TRANSPORT_OVER_SSL,       /*!< Transport over ssl */
+} sim_esp_websocket_transport_t;
+
+/**
+ * @brief Websocket client setup configuration
+ */
+typedef struct {
+    const char                  *uri;                       /*!< Websocket URI, the information on the URI can be overrides the other fields below, if any */
+    const char                  *host;                      /*!< Domain or IP as string */
+    int                         port;                       /*!< Port to connect, default depend on sim_esp_websocket_transport_t (80 or 443) */
+    const char                  *username;                  /*!< Using for Http authentication - Not supported for now */
+    const char                  *password;                  /*!< Using for Http authentication - Not supported for now */
+    const char                  *path;                      /*!< HTTP Path, if not set, default is `/` */
+    bool                        disable_auto_reconnect;     /*!< Disable the automatic reconnect function when disconnected */
+    void                        *user_context;              /*!< HTTP user data context */
+    int                         task_prio;                  /*!< Websocket task priority */
+    int                         task_stack;                 /*!< Websocket task stack */
+    int                         buffer_size;                /*!< Websocket buffer size */
+    const char                  *cert_pem;                  /*!< SSL Certification, PEM format as string, if the client requires to verify server */
+    sim_esp_websocket_transport_t   transport;                  /*!< Websocket transport type, see `sim_esp_websocket_transport_t */
+    char                        *subprotocol;               /*!< Websocket subprotocol */
+} sim_esp_websocket_client_config_t;
+
+/**
+ * @brief      Start a Websocket session
+ *             This function must be the first function to call,
+ *             and it returns a sim_esp_websocket_client_handle_t that you must use as input to other functions in the interface.
+ *             This call MUST have a corresponding call to sim_esp_websocket_client_destroy when the operation is complete.
+ *
+ * @param[in]  config  The configuration
+ *
+ * @return
+ *     - `sim_esp_websocket_client_handle_t`
+ *     - NULL if any errors
+ */
+sim_esp_websocket_client_handle_t sim_esp_websocket_client_init(const sim_esp_websocket_client_config_t *config);
+
+/**
+ * @brief      Set URL for client, when performing this behavior, the options in the URL will replace the old ones
+ *             Must stop the WebSocket client before set URI if the client has been connected
+ *
+ * @param[in]  client  The client
+ * @param[in]  uri     The uri
+ *
+ * @return     esp_err_t
+ */
+esp_err_t sim_esp_websocket_client_set_uri(sim_esp_websocket_client_handle_t client, const char *uri);
+
+/**
+ * @brief      Open the WebSocket connection
+ *
+ * @param[in]  client  The client
+ *
+ * @return     esp_err_t
+ */
+esp_err_t sim_esp_websocket_client_start(sim_esp_websocket_client_handle_t client);
+
+/**
+ * @brief      Close the WebSocket connection
+ *
+ * @param[in]  client  The client
+ *
+ * @return     esp_err_t
+ */
+esp_err_t sim_esp_websocket_client_stop(sim_esp_websocket_client_handle_t client);
+
+/**
+ * @brief      Destroy the WebSocket connection and free all resources.
+ *             This function must be the last function to call for an session.
+ *             It is the opposite of the sim_esp_websocket_client_init function and must be called with the same handle as input that a esp_websocket_client_init call returned.
+ *             This might close all connections this handle has used.
+ *
+ * @param[in]  client  The client
+ *
+ * @return     esp_err_t
+ */
+esp_err_t sim_esp_websocket_client_destroy(sim_esp_websocket_client_handle_t client);
+
+/**
+ * @brief      Generic write data to the WebSocket connection; defaults to binary send
+ *
+ * @param[in]  client  The client
+ * @param[in]  data    The data
+ * @param[in]  len     The length
+ * @param[in]  timeout Write data timeout
+ *
+ * @return
+ *     - Number of data was sent
+ *     - (-1) if any errors
+ */
+int sim_esp_websocket_client_send(sim_esp_websocket_client_handle_t client, const char *data, int len, TickType_t timeout);
+
+/**
+ * @brief      Write binary data to the WebSocket connection (data send with WS OPCODE=02, i.e. binary)
+ *
+ * @param[in]  client  The client
+ * @param[in]  data    The data
+ * @param[in]  len     The length
+ * @param[in]  timeout Write data timeout
+ *
+ * @return
+ *     - Number of data was sent
+ *     - (-1) if any errors
+ */
+int sim_esp_websocket_client_send_bin(sim_esp_websocket_client_handle_t client, const char *data, int len, TickType_t timeout);
+
+static int sim_esp_websocket_client_send_close(sim_esp_websocket_client_handle_t client, int code, const char *additional_data, int total_len, TickType_t timeout);
+
+static int sim_esp_websocket_client_close_with_optional_body(sim_esp_websocket_client_handle_t client, bool send_body, int code, const char *data, int len, TickType_t timeout);
+
+int sim_esp_websocket_client_close_with_code(sim_esp_websocket_client_handle_t client, int code, const char *data, int len, TickType_t timeout);
+
+int sim_esp_websocket_client_close(sim_esp_websocket_client_handle_t client, TickType_t timeout);
+
+/**
+ * @brief      Write textual data to the WebSocket connection (data send with WS OPCODE=01, i.e. text)
+ *
+ * @param[in]  client  The client
+ * @param[in]  data    The data
+ * @param[in]  len     The length
+ * @param[in]  timeout Write data timeout
+ *
+ * @return
+ *     - Number of data was sent
+ *     - (-1) if any errors
+ */
+int sim_esp_websocket_client_send_text(sim_esp_websocket_client_handle_t client, const char *data, int len, TickType_t timeout);
+
+/**
+ * @brief      Check the WebSocket connection status
+ *
+ * @param[in]  client  The client handle
+ *
+ * @return
+ *     - true
+ *     - false
+ */
+bool sim_esp_websocket_client_is_connected(sim_esp_websocket_client_handle_t client);
+
+/**
+ * @brief Register the Websocket Events
+ *
+ * @param client            The client handle
+ * @param event             The event id
+ * @param event_handler     The callback function
+ * @param event_handler_arg User context
+ * @return esp_err_t
+ */
+esp_err_t sim_esp_websocket_register_events(sim_esp_websocket_client_handle_t client,
+                                                                                       sim_esp_event_handler_t event_handler);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/sim_esp_tls.c b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/sim_esp_tls.c
new file mode 100644 (file)
index 0000000..9b58bec
--- /dev/null
@@ -0,0 +1,532 @@
+// Copyright 2019 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+//#include <unistd.h>
+
+//#include <sys/types.h>
+#include <sockets.h>
+#include <netdb.h>
+
+#include <web_http_parser.h>
+#include "sim_esp_tls.h"
+#include "web_esp_tls_error_capture_internal.h"
+#include <errno.h>
+//static const char *TAG = "esp-tls";
+
+#ifdef CONFIG_ESP_TLS_USING_MBEDTLS
+#include "web_esp_tls_mbedtls.h"
+#elif CONFIG_ESP_TLS_USING_WOLFSSL
+#include "esp_tls_wolfssl.h"
+#endif
+
+//#ifdef ESP_PLATFORM
+#include <esp_log.h>
+//#else
+//#define ESP_LOGD(TAG, ...) //printf(__VA_ARGS__);
+//#define ESP_LOGE(TAG, ...) printf(__VA_ARGS__);
+//#endif
+
+#ifdef CONFIG_ESP_TLS_USING_MBEDTLS
+#define _esp_create_ssl_handle              wb_esp_create_mbedtls_handle
+#define _esp_tls_handshake                  wb_esp_mbedtls_handshake
+#define _esp_tls_read                       wb_esp_mbedtls_read
+#define _esp_tls_write                      wb_esp_mbedtls_write
+#define _esp_tls_conn_delete                wb_esp_mbedtls_conn_delete
+#ifdef CONFIG_ESP_TLS_SERVER
+#define _esp_tls_server_session_create      wb_esp_mbedtls_server_session_create
+#define _esp_tls_server_session_delete      wb_esp_mbedtls_server_session_delete
+#endif  /* CONFIG_ESP_TLS_SERVER */
+#define _esp_tls_get_bytes_avail            wb_esp_mbedtls_get_bytes_avail
+#define _esp_tls_init_global_ca_store       wb_esp_mbedtls_init_global_ca_store
+#define _esp_tls_set_global_ca_store        wb_esp_mbedtls_set_global_ca_store                 /*!< Callback function for setting global CA store data for TLS/SSL */
+#define _esp_tls_get_global_ca_store        wb_esp_mbedtls_get_global_ca_store
+#define _esp_tls_free_global_ca_store       wb_esp_mbedtls_free_global_ca_store                /*!< Callback function for freeing global ca store for TLS/SSL */
+#elif CONFIG_ESP_TLS_USING_WOLFSSL /* CONFIG_ESP_TLS_USING_MBEDTLS */
+#define _esp_create_ssl_handle              esp_create_wolfssl_handle
+#define _esp_tls_handshake                  esp_wolfssl_handshake
+#define _esp_tls_read                       esp_wolfssl_read
+#define _esp_tls_write                      esp_wolfssl_write
+#define _esp_tls_conn_delete                esp_wolfssl_conn_delete
+#ifdef CONFIG_ESP_TLS_SERVER
+#define _esp_tls_server_session_create      esp_wolfssl_server_session_create
+#define _esp_tls_server_session_delete      esp_wolfssl_server_session_delete
+#endif  /* CONFIG_ESP_TLS_SERVER */
+#define _esp_tls_get_bytes_avail            esp_wolfssl_get_bytes_avail
+#define _esp_tls_init_global_ca_store       esp_wolfssl_init_global_ca_store
+#define _esp_tls_set_global_ca_store        esp_wolfssl_set_global_ca_store                 /*!< Callback function for setting global CA store data for TLS/SSL */
+#define _esp_tls_free_global_ca_store       esp_wolfssl_free_global_ca_store                /*!< Callback function for freeing global ca store for TLS/SSL */
+#else   /* ESP_TLS_USING_WOLFSSL */
+//#error "No TLS stack configured"
+#endif
+#define configTICK_RATE_HZ 1000
+#define pdMS_TO_TICKS( xTimeInMs ) ( ( ( ( TickType_t ) ( xTimeInMs ) * configTICK_RATE_HZ ) / ( TickType_t ) 1000 ) / 5 )
+
+extern int      gettimeofday(struct timeval *tv, void* dummy);
+
+size_t xTaskGetTickCount(void)
+{
+    struct timeval tv;
+//    struct timezone tz;
+    if (gettimeofday(&tv, NULL) == 0) {
+        return ((tv.tv_sec * 1000) + (tv.tv_usec / 1000))/5;   //get ticks, 1 tick is 5ms
+    }
+    return 0;
+}
+
+ssize_t sim_esp_tls_conn_write(esp_tls_t *tls, const void *data, size_t datalen)
+{
+    return tls->s_write(tls, (char *)data, datalen);
+}
+
+ssize_t sim_esp_tls_conn_read(esp_tls_t *tls, void  *data, size_t datalen)
+{
+    return tls->s_read(tls, (char *)data, datalen);
+}
+
+static esp_err_t create_ssl_handle(const char *hostname, size_t hostlen, const void *cfg, esp_tls_t *tls)
+{
+    return _esp_create_ssl_handle(hostname, hostlen, cfg, tls);
+}
+
+static esp_err_t esp_tls_handshake(esp_tls_t *tls, const esp_tls_cfg_t *cfg)
+{
+    return _esp_tls_handshake(tls, cfg);
+}
+
+static ssize_t tcp_read(esp_tls_t *tls, char *data, size_t datalen)
+{
+    return recv(tls->sockfd, data, datalen, 0);
+}
+
+static ssize_t tcp_write(esp_tls_t *tls, const char *data, size_t datalen)
+{
+    return send(tls->sockfd, data, datalen, 0);
+}
+
+/**
+ * @brief      Close the TLS connection and free any allocated resources.
+ */
+void sim_esp_tls_conn_delete(esp_tls_t *tls)
+{
+    sim_esp_tls_conn_destroy(tls);
+}
+
+int sim_esp_tls_conn_destroy(esp_tls_t *tls)
+{
+    if (tls != NULL) {
+        int ret = 0;
+        _esp_tls_conn_delete(tls);
+        if (tls->sockfd >= 0) {
+            ret = close(tls->sockfd);
+        }
+        free(tls->error_handle);
+        free(tls);
+        return ret;
+    }
+    return -1; // invalid argument
+}
+
+esp_tls_t *sim_esp_tls_init(void)
+{
+    esp_tls_t *tls = (esp_tls_t *)calloc(1, sizeof(esp_tls_t));
+    if (!tls) {
+        return NULL;
+    }
+    tls->error_handle = calloc(1, sizeof(esp_tls_last_error_t));
+    if (!tls->error_handle) {
+        free(tls);
+        return NULL;
+    }
+#ifdef CONFIG_ESP_TLS_USING_MBEDTLS
+    tls->server_fd.fd = -1;
+#endif
+    tls->sockfd = -1;
+    return tls;
+}
+
+extern char* strdup(const char* str);
+
+static esp_err_t resolve_host_name(const char *host, size_t hostlen, struct addrinfo **address_info)
+{
+    struct addrinfo hints;
+    memset(&hints, 0, sizeof(hints));
+    hints.ai_family = AF_UNSPEC;
+    hints.ai_socktype = SOCK_STREAM;
+
+    char *use_host = strdup(host);
+    if (!use_host) {
+        return ESP_ERR_NO_MEM;
+    }
+
+    ESP_LOGD("host:%s: strlen %lu", use_host, (unsigned long)hostlen);
+    if (getaddrinfo(use_host, NULL, &hints, address_info)) {
+        ESP_LOGE("couldn't get hostname for :%s:", use_host);
+        free(use_host);
+        return SIM_ESP_ERR_ESP_TLS_CANNOT_RESOLVE_HOSTNAME;
+    }
+    free(use_host);
+    return ESP_OK;
+}
+
+static void ms_to_timeval(int timeout_ms, struct timeval *tv)
+{
+    tv->tv_sec = timeout_ms / 1000;
+    tv->tv_usec = (timeout_ms % 1000) * 1000;
+}
+
+static esp_err_t esp_tcp_connect(const char *host, int hostlen, int port, int *sockfd, const esp_tls_t *tls, const esp_tls_cfg_t *cfg)
+{
+    esp_err_t ret;
+    struct addrinfo *addrinfo;
+    if ((ret = resolve_host_name(host, hostlen, &addrinfo)) != ESP_OK) {
+        return ret;
+    }
+
+    int fd = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
+    if (fd < 0) {
+        ESP_LOGE("Failed to create socket (family %d socktype %d protocol %d)", addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
+        //ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_SYSTEM, errno);
+        ret = ESP_ERR_ESP_TLS_CANNOT_CREATE_SOCKET;
+        goto err_freeaddr;
+    }
+
+    void *addr_ptr;
+    if (addrinfo->ai_family == AF_INET) {
+        struct sockaddr_in *p = (struct sockaddr_in *)addrinfo->ai_addr;
+        p->sin_port = htons(port);
+        addr_ptr = p;
+    } else if (addrinfo->ai_family == AF_INET6) {
+        struct sockaddr_in6 *p = (struct sockaddr_in6 *)addrinfo->ai_addr;
+        p->sin6_port = htons(port);
+        p->sin6_family = AF_INET6;
+        addr_ptr = p;
+    } else {
+        ESP_LOGE("Unsupported protocol family %d", addrinfo->ai_family);
+        ret = ESP_ERR_ESP_TLS_UNSUPPORTED_PROTOCOL_FAMILY;
+        goto err_freesocket;
+    }
+
+    if (cfg) {
+        if (cfg->timeout_ms >= 0) {
+            struct timeval tv;
+            ms_to_timeval(cfg->timeout_ms, &tv);
+            setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
+            setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
+        }
+        if (cfg->non_block) {
+            int flags = fcntl(fd, F_GETFL, 0);
+            ret = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
+            if (ret < 0) {
+                ESP_LOGE("Failed to configure the socket as non-blocking (errno %d)", errno);
+                goto err_freesocket;
+            }
+        }
+    }
+
+    ret = connect(fd, addr_ptr, addrinfo->ai_addrlen);
+    if (ret < 0 && !(errno == EINPROGRESS && cfg && cfg->non_block)) {
+
+        ESP_LOGE("Failed to connnect to host (errno %d)", errno);
+        //ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_SYSTEM, errno);
+        ret = ESP_ERR_ESP_TLS_FAILED_CONNECT_TO_HOST;
+        goto err_freesocket;
+    }
+
+    *sockfd = fd;
+    freeaddrinfo(addrinfo);
+    return ESP_OK;
+
+err_freesocket:
+    close(fd);
+err_freeaddr:
+    freeaddrinfo(addrinfo);
+    return ret;
+}
+
+int esp_tls_low_level_conn(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_t *tls)
+{
+    if (!tls) {
+        ESP_LOGE("empty esp_tls parameter");
+        return -1;
+    }
+    esp_err_t esp_ret;
+    /* These states are used to keep a tab on connection progress in case of non-blocking connect,
+    and in case of blocking connect these cases will get executed one after the other */
+    switch (tls->conn_state) {
+    case ESP_TLS_INIT:
+        tls->sockfd = -1;
+        if (cfg != NULL) {
+#ifdef CONFIG_ESP_TLS_USING_MBEDTLS
+            mbedtls_net_init(&tls->server_fd);
+#endif
+            tls->is_tls = true;
+        }
+        if ((esp_ret = esp_tcp_connect(hostname, hostlen, port, &tls->sockfd, tls, cfg)) != ESP_OK) {
+            //ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_ESP, esp_ret);
+            return -1;
+        }
+        if (!cfg) {
+            tls->s_read = tcp_read;
+            tls->s_write = tcp_write;
+            ESP_LOGD("non-tls connection established");
+            return 1;
+        }
+        if (cfg->non_block) {
+            FD_ZERO(&tls->rset);
+            FD_SET(tls->sockfd, &tls->rset);
+            tls->wset = tls->rset;
+        }
+        tls->conn_state = ESP_TLS_CONNECTING;
+    /* falls through */
+    case ESP_TLS_CONNECTING:
+        if (cfg->non_block) {
+            ESP_LOGD("connecting...");
+            struct timeval tv;
+            ms_to_timeval(cfg->timeout_ms, &tv);
+
+            /* In case of non-blocking I/O, we use the select() API to check whether
+               connection has been established or not*/
+            if (select(tls->sockfd + 1, &tls->rset, &tls->wset, NULL,
+                       cfg->timeout_ms>0 ? &tv : NULL) == 0) {
+                ESP_LOGD("select() timed out");
+                return 0;
+            }
+            if (FD_ISSET(tls->sockfd, &tls->rset) || FD_ISSET(tls->sockfd, &tls->wset)) {
+                int error;
+                unsigned int len = sizeof(error);
+                /* pending error check */
+                if (getsockopt(tls->sockfd, SOL_SOCKET, SO_ERROR, &error, (socklen_t *)&len) < 0) {
+                    ESP_LOGD("Non blocking connect failed");
+                    //ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_SYSTEM, errno);
+                    //ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_ESP, ESP_ERR_ESP_TLS_SOCKET_SETOPT_FAILED);
+                    tls->conn_state = ESP_TLS_FAIL;
+                    return -1;
+                }
+            }
+        }
+        /* By now, the connection has been established */
+        esp_ret = create_ssl_handle(hostname, hostlen, cfg, tls);
+        if (esp_ret != ESP_OK) {
+            ESP_LOGE("create_ssl_handle failed");
+            //ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_ESP, esp_ret);
+            tls->conn_state = ESP_TLS_FAIL;
+            return -1;
+        }
+        tls->s_read = _esp_tls_read;
+        tls->s_write = _esp_tls_write;
+        tls->conn_state = ESP_TLS_HANDSHAKE;
+    /* falls through */
+    case ESP_TLS_HANDSHAKE:
+        ESP_LOGD("handshake in progress...");
+        return esp_tls_handshake(tls, cfg);
+        //break;
+    case ESP_TLS_FAIL:
+        ESP_LOGE("failed to open a new connection");;
+        break;
+    default:
+        ESP_LOGE("invalid esp-tls state");
+        break;
+    }
+    return -1;
+}
+
+/**
+ * @brief      Create a new TLS/SSL connection
+ */
+esp_tls_t *sim_esp_tls_conn_new(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg)
+{
+    esp_tls_t *tls = sim_esp_tls_init();
+    if (!tls) {
+        return NULL;
+    }
+    /* sim_esp_tls_conn_new() API establishes connection in a blocking manner thus this loop ensures that sim_esp_tls_conn_new()
+       API returns only after connection is established unless there is an error*/
+    size_t start = xTaskGetTickCount();
+    while (1) {
+        int ret = esp_tls_low_level_conn(hostname, hostlen, port, cfg, tls);
+        if (ret == 1) {
+            return tls;
+        } else if (ret == -1) {
+            sim_esp_tls_conn_delete(tls);
+            ESP_LOGE("Failed to open new connection");
+            return NULL;
+        } else if (ret == 0 && cfg->timeout_ms >= 0) {
+            size_t timeout_ticks = pdMS_TO_TICKS(cfg->timeout_ms);
+            uint32_t expired = xTaskGetTickCount() - start;
+            if (expired >= timeout_ticks) {
+                sim_esp_tls_conn_delete(tls);
+                ESP_LOGE("Failed to open new connection in specified timeout");
+                return NULL;
+            }
+        }
+    }
+//    return NULL;
+}
+
+int sim_esp_tls_conn_new_sync(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_t *tls)
+{
+    /* sim_esp_tls_conn_new_sync() is a sync alternative to sim_esp_tls_conn_new_async() with symmetric function prototype
+    it is an alternative to sim_esp_tls_conn_new() which is left for compatibility reasons */
+    size_t start = xTaskGetTickCount();
+    while (1) {
+        int ret = esp_tls_low_level_conn(hostname, hostlen, port, cfg, tls);
+        if (ret == 1) {
+            return ret;
+        } else if (ret == -1) {
+            ESP_LOGE("Failed to open new connection");
+            return -1;
+        } else if (ret == 0 && cfg->timeout_ms >= 0) {
+            size_t timeout_ticks = pdMS_TO_TICKS(cfg->timeout_ms);
+            uint32_t expired = xTaskGetTickCount() - start;
+            if (expired >= timeout_ticks) {
+                ESP_LOGW("Failed to open new connection in specified timeout");
+                ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_ESP, ESP_ERR_ESP_TLS_CONNECTION_TIMEOUT);
+                return 0;
+            }
+        }
+    }
+//    return 0;
+}
+
+/*
+ * @brief      Create a new TLS/SSL non-blocking connection
+ */
+int sim_esp_tls_conn_new_async(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_t *tls)
+{
+    return esp_tls_low_level_conn(hostname, hostlen, port, cfg, tls);
+}
+
+static int get_port(const char *url, struct http_parser_url *u)
+{
+    if (u->field_data[UF_PORT].len) {
+        return strtol(&url[u->field_data[UF_PORT].off], NULL, 10);
+    } else {
+        if (strncasecmp(&url[u->field_data[UF_SCHEMA].off], "http", u->field_data[UF_SCHEMA].len) == 0) {
+            return 80;
+        } else if (strncasecmp(&url[u->field_data[UF_SCHEMA].off], "https", u->field_data[UF_SCHEMA].len) == 0) {
+            return 443;
+        }
+    }
+    return 0;
+}
+
+/**
+ * @brief      Create a new TLS/SSL connection with a given "HTTP" url
+ */
+esp_tls_t *sim_esp_tls_conn_http_new(const char *url, const esp_tls_cfg_t *cfg)
+{
+    /* Parse URI */
+    struct http_parser_url u;
+    wb_http_parser_url_init(&u);
+    wb_http_parser_parse_url(url, strlen(url), 0, &u);
+    esp_tls_t *tls = sim_esp_tls_init();
+    if (!tls) {
+        return NULL;
+    }
+    /* Connect to host */
+    if (sim_esp_tls_conn_new_sync(&url[u.field_data[UF_HOST].off], u.field_data[UF_HOST].len,
+                              get_port(url, &u), cfg, tls) == 1) {
+        return tls;
+    }
+    sim_esp_tls_conn_delete(tls);
+    return NULL;
+}
+
+/**
+ * @brief      Create a new non-blocking TLS/SSL connection with a given "HTTP" url
+ */
+int sim_esp_tls_conn_http_new_async(const char *url, const esp_tls_cfg_t *cfg, esp_tls_t *tls)
+{
+    /* Parse URI */
+    struct http_parser_url u;
+    wb_http_parser_url_init(&u);
+    wb_http_parser_parse_url(url, strlen(url), 0, &u);
+
+    /* Connect to host */
+    return sim_esp_tls_conn_new_async(&url[u.field_data[UF_HOST].off], u.field_data[UF_HOST].len,
+                                  get_port(url, &u), cfg, tls);
+}
+
+#ifdef CONFIG_ESP_TLS_USING_MBEDTLS
+
+mbedtls_x509_crt *sim_esp_tls_get_global_ca_store(void)
+{
+    return _esp_tls_get_global_ca_store();
+}
+
+#endif /* CONFIG_ESP_TLS_USING_MBEDTLS */
+#ifdef CONFIG_ESP_TLS_SERVER
+/**
+ * @brief      Create a server side TLS/SSL connection
+ */
+int sim_esp_tls_server_session_create(esp_tls_cfg_server_t *cfg, int sockfd, esp_tls_t *tls)
+{
+    return _esp_tls_server_session_create(cfg, sockfd, tls);
+}
+/**
+ * @brief      Close the server side TLS/SSL connection and free any allocated resources.
+ */
+void sim_esp_tls_server_session_delete(esp_tls_t *tls)
+{
+    return _esp_tls_server_session_delete(tls);
+}
+#endif /* CONFIG_ESP_TLS_SERVER */
+
+ssize_t sim_esp_tls_get_bytes_avail(esp_tls_t *tls)
+{
+    return _esp_tls_get_bytes_avail(tls);
+}
+
+esp_err_t sim_esp_tls_get_conn_sockfd(esp_tls_t *tls, int *sockfd)
+{
+    if (!tls || !sockfd) {
+        ESP_LOGE("Invalid arguments passed");
+        return ESP_ERR_INVALID_ARG;
+    }
+    *sockfd = tls->sockfd;
+    return ESP_OK;
+}
+
+esp_err_t sim_esp_tls_get_and_clear_last_error(wb_esp_tls_error_handle_t h, int *esp_tls_code, int *esp_tls_flags)
+{
+    if (!h) {
+        return ESP_ERR_INVALID_STATE;
+    }
+    esp_err_t last_err = h->last_error;
+    if (esp_tls_code) {
+        *esp_tls_code = h->esp_tls_error_code;
+    }
+    if (esp_tls_flags) {
+        *esp_tls_flags = h->esp_tls_flags;
+    }
+    memset(h, 0, sizeof(esp_tls_last_error_t));
+    return last_err;
+}
+
+esp_err_t sim_esp_tls_init_global_ca_store(void)
+{
+    return _esp_tls_init_global_ca_store();
+}
+
+esp_err_t sim_esp_tls_set_global_ca_store(const unsigned char *cacert_pem_buf, const unsigned int cacert_pem_bytes)
+{
+    return _esp_tls_set_global_ca_store(cacert_pem_buf, cacert_pem_bytes);
+}
+
+void sim_esp_tls_free_global_ca_store(void)
+{
+    return _esp_tls_free_global_ca_store();
+}
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/web_esp_tls_mbedtls.c b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/web_esp_tls_mbedtls.c
new file mode 100644 (file)
index 0000000..00abff3
--- /dev/null
@@ -0,0 +1,680 @@
+// Copyright 2019 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+//#include <unistd.h>
+
+//#include <sys/types.h>
+#include <sockets.h>
+#include <netdb.h>
+
+#include <web_http_parser.h>
+#include "web_esp_tls_mbedtls.h"
+#include "web_esp_tls_error_capture_internal.h"
+#include <errno.h>
+#include "esp_log.h"
+
+#ifdef CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
+#include "esp_crt_bundle.h"
+#endif
+
+#ifdef CONFIG_ESP_TLS_USE_SECURE_ELEMENT
+
+#define ATECC608A_TNG_SLAVE_ADDR        0x6A
+#define ATECC608A_TFLEX_SLAVE_ADDR      0x6C
+#define ATECC608A_TCUSTOM_SLAVE_ADDR    0xC0
+/* cryptoauthlib includes */
+#include "mbedtls/atca_mbedtls_wrap.h"
+#include "tng_atca.h"
+#include "cryptoauthlib.h"
+static const atcacert_def_t* cert_def = NULL;
+/* Prototypes for functions */
+static esp_err_t esp_set_atecc608a_pki_context(esp_tls_t *tls, esp_tls_cfg_t *cfg);
+#endif /* CONFIG_ESP_TLS_USE_SECURE_ELEMENT */
+
+#define bzero(a,b)          memset(a, 0, b)
+
+static const char *TAG = "esp-tls-mbedtls";
+static mbedtls_x509_crt *global_cacert = NULL;
+extern char* strdup(const char* str);
+
+typedef struct esp_tls_pki_t {
+    mbedtls_x509_crt *public_cert;
+    mbedtls_pk_context *pk_key;
+    const unsigned char *publiccert_pem_buf;
+    unsigned int publiccert_pem_bytes;
+    const unsigned char *privkey_pem_buf;
+    unsigned int privkey_pem_bytes;
+    const unsigned char *privkey_password;
+    unsigned int privkey_password_len;
+} esp_tls_pki_t;
+
+esp_err_t wb_esp_create_mbedtls_handle(const char *hostname, size_t hostlen, const void *cfg, esp_tls_t *tls)
+{
+    assert(cfg != NULL);
+    assert(tls != NULL);
+    int ret;
+    esp_err_t esp_ret = ESP_FAIL;
+    tls->server_fd.fd = tls->sockfd;
+    mbedtls_ssl_init(&tls->ssl);
+    mbedtls_ctr_drbg_init(&tls->ctr_drbg);
+    mbedtls_ssl_config_init(&tls->conf);
+    mbedtls_entropy_init(&tls->entropy);
+
+    if (tls->role == ESP_TLS_CLIENT) {
+        esp_ret = wb_set_client_config(hostname, hostlen, (esp_tls_cfg_t *)cfg, tls);
+        if (esp_ret != ESP_OK) {
+            ESP_LOGE("Failed to set client configurations");
+            goto exit;
+        }
+    } else if (tls->role == ESP_TLS_SERVER) {
+#ifdef CONFIG_ESP_TLS_SERVER
+        esp_ret = wb_set_server_config((esp_tls_cfg_server_t *) cfg, tls);
+        if (esp_ret != 0) {
+            ESP_LOGE("Failed to set server configurations");
+            goto exit;
+        }
+#else
+            ESP_LOGE("ESP_TLS_SERVER Not enabled in Kconfig");
+            goto exit;
+#endif
+    }
+
+    if ((ret = mbedtls_ctr_drbg_seed(&tls->ctr_drbg,
+                                     mbedtls_entropy_func, &tls->entropy, NULL, 0)) != 0) {
+        ESP_LOGE("mbedtls_ctr_drbg_seed returned -0x%x", -ret);
+        ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_MBEDTLS, -ret);
+        esp_ret = ESP_ERR_MBEDTLS_CTR_DRBG_SEED_FAILED;
+        goto exit;
+    }
+
+    mbedtls_ssl_conf_rng(&tls->conf, mbedtls_ctr_drbg_random, &tls->ctr_drbg);
+
+#ifdef CONFIG_MBEDTLS_DEBUG
+    mbedtls_esp_enable_debug_log(&tls->conf, CONFIG_MBEDTLS_DEBUG_LEVEL);
+#endif
+
+    if ((ret = mbedtls_ssl_setup(&tls->ssl, &tls->conf)) != 0) {
+        ESP_LOGE("mbedtls_ssl_setup returned -0x%x", -ret);
+        ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_MBEDTLS, -ret);
+        esp_ret = ESP_ERR_MBEDTLS_SSL_SETUP_FAILED;
+        goto exit;
+    }
+    mbedtls_ssl_set_bio(&tls->ssl, &tls->server_fd, mbedtls_net_send, mbedtls_net_recv, NULL);
+
+    return ESP_OK;
+
+exit:
+    wb_esp_mbedtls_cleanup(tls);
+    return esp_ret;
+
+}
+
+int wb_esp_mbedtls_handshake(esp_tls_t *tls, const esp_tls_cfg_t *cfg)
+{
+    int ret;
+    ret = mbedtls_ssl_handshake(&tls->ssl);
+    if (ret == 0) {
+        tls->conn_state = ESP_TLS_DONE;
+        return 1;
+    } else {
+        if (ret != ESP_TLS_ERR_SSL_WANT_READ && ret != ESP_TLS_ERR_SSL_WANT_WRITE) {
+            ESP_LOGE("mbedtls_ssl_handshake returned -0x%x", -ret);
+            ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_MBEDTLS, -ret);
+            ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_ESP, ESP_ERR_MBEDTLS_SSL_HANDSHAKE_FAILED);
+            if (cfg->cacert_buf != NULL || cfg->use_global_ca_store == true) {
+                /* This is to check whether handshake failed due to invalid certificate*/
+                wb_esp_mbedtls_verify_certificate(tls);
+            }
+            tls->conn_state = ESP_TLS_FAIL;
+            return -1;
+        }
+        /* Irrespective of blocking or non-blocking I/O, we return on getting ESP_TLS_ERR_SSL_WANT_READ
+        or ESP_TLS_ERR_SSL_WANT_WRITE during handshake */
+        return 0;
+    }
+}
+
+ssize_t wb_esp_mbedtls_read(esp_tls_t *tls, char *data, size_t datalen)
+{
+
+    int ret = mbedtls_ssl_read(&tls->ssl, (unsigned char *)data, datalen);
+    if (ret < 0) {
+        if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
+            return 0;
+        }
+        if (ret != ESP_TLS_ERR_SSL_WANT_READ  && ret != ESP_TLS_ERR_SSL_WANT_WRITE) {
+            ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_MBEDTLS, -ret);
+            ESP_LOGE("read error :%d:", ret);
+        }
+    }
+    return ret;
+}
+
+ssize_t wb_esp_mbedtls_write(esp_tls_t *tls, const char *data, size_t datalen)
+{
+    size_t written = 0;
+    size_t write_len = datalen;
+    while (written < datalen) {
+        if (write_len > MBEDTLS_SSL_OUT_CONTENT_LEN) {
+            write_len = MBEDTLS_SSL_OUT_CONTENT_LEN;
+        }
+        if (datalen > MBEDTLS_SSL_OUT_CONTENT_LEN) {
+            ESP_LOGD("Fragmenting data of excessive size :%d, offset: %d, size %d", datalen, written, write_len);
+        }
+        ssize_t ret = mbedtls_ssl_write(&tls->ssl, (unsigned char*) data + written, write_len);
+        if (ret <= 0) {
+            if (ret != ESP_TLS_ERR_SSL_WANT_READ  && ret != ESP_TLS_ERR_SSL_WANT_WRITE && ret != 0) {
+                ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_MBEDTLS, -ret);
+                ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_ESP, ESP_ERR_MBEDTLS_SSL_WRITE_FAILED);
+                ESP_LOGE("write error :%d:", ret);
+                return ret;
+            } else {
+                // Exitting the tls-write process as less than desired datalen are writable
+                ESP_LOGD("mbedtls_ssl_write() returned %d, already written %d, exitting...", ret, written);
+                return written;
+            }
+        }
+        written += ret;
+        write_len = datalen - written;
+    }
+    return written;
+}
+
+void wb_esp_mbedtls_conn_delete(esp_tls_t *tls)
+{
+    if (tls != NULL) {
+        wb_esp_mbedtls_cleanup(tls);
+        if (tls->is_tls) {
+            mbedtls_net_free(&tls->server_fd);
+        }
+    }
+}
+
+void wb_esp_mbedtls_verify_certificate(esp_tls_t *tls)
+{
+    int flags;
+    char buf[100];
+    if ((flags = mbedtls_ssl_get_verify_result(&tls->ssl)) != 0) {
+        ESP_LOGI("Failed to verify peer certificate!");
+        ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_MBEDTLS_CERT_FLAGS, flags);
+        bzero(buf, sizeof(buf));
+        mbedtls_x509_crt_verify_info(buf, sizeof(buf), "  ! ", flags);
+        ESP_LOGI("verification info: %s", buf);
+    } else {
+        ESP_LOGI("Certificate verified.");
+    }
+}
+
+ssize_t wb_esp_mbedtls_get_bytes_avail(esp_tls_t *tls)
+{
+    if (!tls) {
+        ESP_LOGE("empty arg passed to sim_esp_tls_get_bytes_avail()");
+        return ESP_FAIL;
+    }
+    return mbedtls_ssl_get_bytes_avail(&tls->ssl);
+}
+
+void wb_esp_mbedtls_cleanup(esp_tls_t *tls)
+{
+    if (!tls) {
+        return;
+    }
+    if (tls->cacert_ptr != global_cacert) {
+        mbedtls_x509_crt_free(tls->cacert_ptr);
+    }
+    tls->cacert_ptr = NULL;
+#ifdef CONFIG_ESP_TLS_SERVER
+    mbedtls_x509_crt_free(&tls->servercert);
+    mbedtls_pk_free(&tls->serverkey);
+#endif
+    mbedtls_x509_crt_free(&tls->cacert);
+    mbedtls_x509_crt_free(&tls->clientcert);
+    mbedtls_pk_free(&tls->clientkey);
+    mbedtls_entropy_free(&tls->entropy);
+    mbedtls_ssl_config_free(&tls->conf);
+    mbedtls_ctr_drbg_free(&tls->ctr_drbg);
+    mbedtls_ssl_free(&tls->ssl);
+#ifdef CONFIG_ESP_TLS_USE_SECURE_ELEMENT
+    atcab_release();
+#endif
+}
+
+static esp_err_t set_ca_cert(esp_tls_t *tls, const unsigned char *cacert, size_t cacert_len)
+{
+    assert(tls);
+    tls->cacert_ptr = &tls->cacert;
+    mbedtls_x509_crt_init(tls->cacert_ptr);
+    int ret = mbedtls_x509_crt_parse(tls->cacert_ptr, cacert, cacert_len);
+    if (ret < 0) {
+        ESP_LOGE("mbedtls_x509_crt_parse returned -0x%x", -ret);
+        ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_MBEDTLS, -ret);
+        return ESP_ERR_MBEDTLS_X509_CRT_PARSE_FAILED;
+    }
+    mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
+    mbedtls_ssl_conf_ca_chain(&tls->conf, tls->cacert_ptr, NULL);
+    return ESP_OK;
+}
+
+static esp_err_t set_pki_context(esp_tls_t *tls, const esp_tls_pki_t *pki)
+{
+    assert(tls);
+    assert(pki);
+    int ret;
+
+    if (pki->publiccert_pem_buf != NULL &&
+        pki->privkey_pem_buf != NULL &&
+        pki->public_cert != NULL &&
+        pki->pk_key != NULL) {
+
+        mbedtls_x509_crt_init(pki->public_cert);
+        mbedtls_pk_init(pki->pk_key);
+
+        ret = mbedtls_x509_crt_parse(pki->public_cert, pki->publiccert_pem_buf, pki->publiccert_pem_bytes);
+        if (ret < 0) {
+            ESP_LOGE("mbedtls_x509_crt_parse returned -0x%x", -ret);
+            ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_MBEDTLS, -ret);
+            return ESP_ERR_MBEDTLS_X509_CRT_PARSE_FAILED;
+        }
+#if 0 //mbedTLS_3_2_1
+        ret = mbedtls_pk_parse_key(pki->pk_key, pki->privkey_pem_buf, pki->privkey_pem_bytes,
+                                   pki->privkey_password, pki->privkey_password_len, NULL, NULL);
+#else //mbedTLS_2_1_8
+        ret = mbedtls_pk_parse_key(pki->pk_key, pki->privkey_pem_buf, pki->privkey_pem_bytes,
+                                   pki->privkey_password, pki->privkey_password_len);
+#endif
+        if (ret < 0) {
+            ESP_LOGE("mbedtls_pk_parse_keyfile returned -0x%x", -ret);
+            ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_MBEDTLS, -ret);
+            return ESP_ERR_MBEDTLS_PK_PARSE_KEY_FAILED;
+        }
+
+        ret = mbedtls_ssl_conf_own_cert(&tls->conf, pki->public_cert, pki->pk_key);
+        if (ret < 0) {
+            ESP_LOGE("mbedtls_ssl_conf_own_cert returned -0x%x", -ret);
+            ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_MBEDTLS, -ret);
+            return ESP_ERR_MBEDTLS_SSL_CONF_OWN_CERT_FAILED;
+        }
+    } else {
+        return ESP_ERR_INVALID_ARG;
+    }
+    return ESP_OK;
+}
+
+static esp_err_t set_global_ca_store(esp_tls_t *tls)
+{
+    assert(tls);
+    if (global_cacert == NULL) {
+        ESP_LOGE("global_cacert is NULL");
+        return ESP_ERR_INVALID_STATE;
+    }
+    tls->cacert_ptr = global_cacert;
+    mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
+    mbedtls_ssl_conf_ca_chain(&tls->conf, tls->cacert_ptr, NULL);
+    return ESP_OK;
+}
+
+
+#ifdef CONFIG_ESP_TLS_SERVER
+esp_err_t wb_set_server_config(esp_tls_cfg_server_t *cfg, esp_tls_t *tls)
+{
+    assert(cfg != NULL);
+    assert(tls != NULL);
+    int ret;
+    esp_err_t esp_ret;
+    if ((ret = mbedtls_ssl_config_defaults(&tls->conf,
+                    MBEDTLS_SSL_IS_SERVER,
+                    MBEDTLS_SSL_TRANSPORT_STREAM,
+                    MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
+        ESP_LOGE("mbedtls_ssl_config_defaults returned %d", ret);
+        ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_MBEDTLS, -ret);
+        return ESP_ERR_MBEDTLS_SSL_CONFIG_DEFAULTS_FAILED;
+    }
+
+#ifdef CONFIG_MBEDTLS_SSL_ALPN
+    if (cfg->alpn_protos) {
+        mbedtls_ssl_conf_alpn_protocols(&tls->conf, cfg->alpn_protos);
+    }
+#endif
+
+    if (cfg->cacert_buf != NULL) {
+        esp_ret = set_ca_cert(tls, cfg->cacert_buf, cfg->cacert_bytes);
+        if (esp_ret != ESP_OK) {
+            return esp_ret;
+        }
+    } else {
+        mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_NONE);
+    }
+
+    if (cfg->servercert_buf != NULL && cfg->serverkey_buf != NULL) {
+        esp_tls_pki_t pki = {
+            .public_cert = &tls->servercert,
+            .pk_key = &tls->serverkey,
+            .publiccert_pem_buf = cfg->servercert_buf,
+            .publiccert_pem_bytes = cfg->servercert_bytes,
+            .privkey_pem_buf = cfg->serverkey_buf,
+            .privkey_pem_bytes = cfg->serverkey_bytes,
+            .privkey_password = cfg->serverkey_password,
+            .privkey_password_len = cfg->serverkey_password_len,
+        };
+        esp_ret = set_pki_context(tls, &pki);
+        if (esp_ret != ESP_OK) {
+            ESP_LOGE("Failed to set server pki context");
+            return esp_ret;
+        }
+    } else {
+        ESP_LOGE("Missing server certificate and/or key");
+        return ESP_ERR_INVALID_STATE;
+    }
+    return ESP_OK;
+}
+#endif /* ! CONFIG_ESP_TLS_SERVER */
+
+esp_err_t wb_set_client_config(const char *hostname, size_t hostlen, esp_tls_cfg_t *cfg, esp_tls_t *tls)
+{
+    assert(cfg != NULL);
+    assert(tls != NULL);
+    int ret;
+    if (!cfg->skip_common_name) {
+        char *use_host = NULL;
+        if (cfg->common_name != NULL) {
+            use_host = strdup(cfg->common_name);
+        } else {
+            use_host = strdup(hostname);
+        }
+
+        if (use_host == NULL) {
+            return ESP_ERR_NO_MEM;
+        }
+        /* Hostname set here should match CN in server certificate */
+        if ((ret = mbedtls_ssl_set_hostname(&tls->ssl, use_host)) != 0) {
+            ESP_LOGE("mbedtls_ssl_set_hostname returned -0x%x", -ret);
+            ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_MBEDTLS, -ret);
+            free(use_host);
+            return ESP_ERR_MBEDTLS_SSL_SET_HOSTNAME_FAILED;
+        }
+        free(use_host);
+    }
+
+    if ((ret = mbedtls_ssl_config_defaults(&tls->conf,
+                                           MBEDTLS_SSL_IS_CLIENT,
+                                           MBEDTLS_SSL_TRANSPORT_STREAM,
+                                           MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
+        ESP_LOGE("mbedtls_ssl_config_defaults returned -0x%x", -ret);
+        ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_MBEDTLS, -ret);
+        return ESP_ERR_MBEDTLS_SSL_CONFIG_DEFAULTS_FAILED;
+    }
+
+#ifdef CONFIG_MBEDTLS_SSL_RENEGOTIATION
+    mbedtls_ssl_conf_renegotiation(&tls->conf, MBEDTLS_SSL_RENEGOTIATION_ENABLED);
+#endif
+
+    if (cfg->alpn_protos) {
+#ifdef CONFIG_MBEDTLS_SSL_ALPN
+        if ((ret = mbedtls_ssl_conf_alpn_protocols(&tls->conf, cfg->alpn_protos) != 0)) {
+            ESP_LOGE("mbedtls_ssl_conf_alpn_protocols returned -0x%x", -ret);
+            ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_MBEDTLS, -ret);
+            return ESP_ERR_MBEDTLS_SSL_CONF_ALPN_PROTOCOLS_FAILED;
+        }
+#else
+        ESP_LOGE("alpn_protos configured but not enabled in menuconfig: Please enable MBEDTLS_SSL_ALPN option");
+        return ESP_ERR_INVALID_STATE;
+#endif
+    }
+
+    if (cfg->crt_bundle_attach != NULL) {
+#ifdef CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
+        ESP_LOGD("Use certificate bundle");
+        mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
+        cfg->crt_bundle_attach(&tls->conf);
+#else //CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
+        ESP_LOGE("use_crt_bundle configured but not enabled in menuconfig: Please enable MBEDTLS_CERTIFICATE_BUNDLE option");
+        return ESP_ERR_INVALID_STATE;
+#endif
+    } else if (cfg->use_global_ca_store == true) {
+        esp_err_t esp_ret = set_global_ca_store(tls);
+        if (esp_ret != ESP_OK) {
+            return esp_ret;
+        }
+    } else if (cfg->cacert_buf != NULL) {
+        esp_err_t esp_ret = set_ca_cert(tls, cfg->cacert_buf, cfg->cacert_bytes);
+        if (esp_ret != ESP_OK) {
+            return esp_ret;
+        }
+        mbedtls_ssl_conf_ca_chain(&tls->conf, tls->cacert_ptr, NULL);
+    } else if (cfg->psk_hint_key) {
+#if defined(CONFIG_ESP_TLS_PSK_VERIFICATION)
+        //
+        // PSK encryption mode is configured only if no certificate supplied and psk pointer not null
+        ESP_LOGD("ssl psk authentication");
+        ret = mbedtls_ssl_conf_psk(&tls->conf, cfg->psk_hint_key->key, cfg->psk_hint_key->key_size,
+                                   (const unsigned char *)cfg->psk_hint_key->hint, strlen(cfg->psk_hint_key->hint));
+        if (ret != 0) {
+            ESP_LOGE("mbedtls_ssl_conf_psk returned -0x%x", -ret);
+            ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_MBEDTLS, -ret);
+            return ESP_ERR_MBEDTLS_SSL_CONF_PSK_FAILED;
+        }
+#else
+        ESP_LOGE("psk_hint_key configured but not enabled in menuconfig: Please enable ESP_TLS_PSK_VERIFICATION option");
+        return ESP_ERR_INVALID_STATE;
+#endif
+    } else {
+        mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_NONE);
+    }
+
+    if (cfg->use_secure_element) {
+#ifdef CONFIG_ESP_TLS_USE_SECURE_ELEMENT
+        ret = esp_set_atecc608a_pki_context(tls, (esp_tls_cfg_t *)cfg);
+        if (ret != ESP_OK) {
+            return ret;
+        }
+#else
+        ESP_LOGE("Please enable secure element support for ESP-TLS in menuconfig");
+        return ESP_FAIL;
+#endif /* CONFIG_ESP_TLS_USE_SECURE_ELEMENT */
+    } else if (cfg->clientcert_pem_buf != NULL && cfg->clientkey_pem_buf != NULL) {
+        esp_tls_pki_t pki = {
+            .public_cert = &tls->clientcert,
+            .pk_key = &tls->clientkey,
+            .publiccert_pem_buf = cfg->clientcert_buf,
+            .publiccert_pem_bytes = cfg->clientcert_bytes,
+            .privkey_pem_buf = cfg->clientkey_buf,
+            .privkey_pem_bytes = cfg->clientkey_bytes,
+            .privkey_password = cfg->clientkey_password,
+            .privkey_password_len = cfg->clientkey_password_len,
+        };
+        esp_err_t esp_ret = set_pki_context(tls, &pki);
+        if (esp_ret != ESP_OK) {
+            ESP_LOGE("Failed to set client pki context");
+            return esp_ret;
+        }
+    } else if (cfg->clientcert_buf != NULL || cfg->clientkey_buf != NULL) {
+        ESP_LOGE("You have to provide both clientcert_buf and clientkey_buf for mutual authentication");
+        return ESP_ERR_INVALID_STATE;
+    }
+    return ESP_OK;
+}
+
+#ifdef CONFIG_ESP_TLS_SERVER
+/**
+ * @brief      Create TLS/SSL server session
+ */
+int wb_esp_mbedtls_server_session_create(esp_tls_cfg_server_t *cfg, int sockfd, esp_tls_t *tls)
+{
+    if (tls == NULL || cfg == NULL) {
+        return -1;
+    }
+    tls->role = ESP_TLS_SERVER;
+    tls->sockfd = sockfd;
+    esp_err_t esp_ret = wb_esp_create_mbedtls_handle(NULL, 0, cfg, tls);
+    if (esp_ret != ESP_OK) {
+        ESP_LOGE("create_ssl_handle failed");
+        ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_ESP, esp_ret);
+        tls->conn_state = ESP_TLS_FAIL;
+        return -1;
+    }
+    tls->read = wb_esp_mbedtls_read;
+    tls->write = wb_esp_mbedtls_write;
+    int ret;
+    while ((ret = mbedtls_ssl_handshake(&tls->ssl)) != 0) {
+        if (ret != ESP_TLS_ERR_SSL_WANT_READ && ret != ESP_TLS_ERR_SSL_WANT_WRITE) {
+            ESP_LOGE("mbedtls_ssl_handshake returned %d", ret);
+            tls->conn_state = ESP_TLS_FAIL;
+            return ret;
+        }
+    }
+    return 0;
+}
+/**
+ * @brief      Close the server side TLS/SSL connection and free any allocated resources.
+ */
+void wb_esp_mbedtls_server_session_delete(esp_tls_t *tls)
+{
+    if (tls != NULL) {
+        wb_esp_mbedtls_cleanup(tls);
+        free(tls);
+    }
+};
+#endif /* ! CONFIG_ESP_TLS_SERVER */
+
+esp_err_t wb_esp_mbedtls_init_global_ca_store(void)
+{
+    if (global_cacert == NULL) {
+        global_cacert = (mbedtls_x509_crt *)calloc(1, sizeof(mbedtls_x509_crt));
+        if (global_cacert == NULL) {
+            ESP_LOGE("global_cacert not allocated");
+            return ESP_ERR_NO_MEM;
+        }
+        mbedtls_x509_crt_init(global_cacert);
+    }
+    return ESP_OK;
+}
+
+esp_err_t wb_esp_mbedtls_set_global_ca_store(const unsigned char *cacert_pem_buf, const unsigned int cacert_pem_bytes)
+{
+    if (cacert_pem_buf == NULL) {
+        ESP_LOGE("cacert_pem_buf is null");
+        return ESP_ERR_INVALID_ARG;
+    }
+    int ret;
+    if (global_cacert == NULL) {
+        ret = wb_esp_mbedtls_init_global_ca_store();
+        if (ret != ESP_OK) {
+            return ret;
+        }
+    }
+    ret = mbedtls_x509_crt_parse(global_cacert, cacert_pem_buf, cacert_pem_bytes);
+    if (ret < 0) {
+        ESP_LOGE("mbedtls_x509_crt_parse returned -0x%x", -ret);
+        mbedtls_x509_crt_free(global_cacert);
+        global_cacert = NULL;
+        return ESP_FAIL;
+    } else if (ret > 0) {
+        ESP_LOGE("mbedtls_x509_crt_parse was partly successful. No. of failed certificates: %d", ret);
+        return ESP_ERR_MBEDTLS_CERT_PARTLY_OK;
+    }
+    return ESP_OK;
+}
+
+mbedtls_x509_crt *wb_esp_mbedtls_get_global_ca_store(void)
+{
+    return global_cacert;
+}
+
+void wb_esp_mbedtls_free_global_ca_store(void)
+{
+    if (global_cacert) {
+        mbedtls_x509_crt_free(global_cacert);
+        global_cacert = NULL;
+    }
+}
+
+#ifdef CONFIG_ESP_TLS_USE_SECURE_ELEMENT
+static esp_err_t esp_init_atecc608a(uint8_t slave_addr)
+{
+    cfg_ateccx08a_i2c_default.atcai2c.slave_address = slave_addr;
+    int ret = atcab_init(&cfg_ateccx08a_i2c_default);
+    if(ret != 0) {
+        ESP_LOGE("Failed\n !atcab_init returned %02x", ret);
+        return ESP_FAIL;
+    }
+    return ESP_OK;
+}
+
+static esp_err_t esp_set_atecc608a_pki_context(esp_tls_t *tls, esp_tls_cfg_t *cfg)
+{
+    int ret = 0;
+    int esp_ret = ESP_FAIL;
+    ESP_LOGI("Initialize the ATECC interface...");
+#if defined(CONFIG_ATECC608A_TNG) || defined(CONFIG_ATECC608A_TFLEX)
+#ifdef CONFIG_ATECC608A_TNG
+    esp_ret = esp_init_atecc608a(ATECC608A_TNG_SLAVE_ADDR);
+    if (ret != ESP_OK) {
+        return ESP_ERR_ESP_TLS_SE_FAILED;
+    }
+#elif CONFIG_ATECC608A_TFLEX /* CONFIG_ATECC608A_TNG */
+    esp_ret = esp_init_atecc608a(ATECC608A_TFLEX_SLAVE_ADDR);
+    if (ret != ESP_OK) {
+        return ESP_ERR_ESP_TLS_SE_FAILED;
+    }
+#endif /* CONFIG_ATECC608A_TFLEX */
+    mbedtls_x509_crt_init(&tls->clientcert);
+    ret = tng_get_device_cert_def(&cert_def);
+    if (ret != 0) {
+        ESP_LOGE("Failed to get device cert def");
+        return ESP_ERR_ESP_TLS_SE_FAILED;
+    }
+
+    /* Extract the device certificate and convert to mbedtls cert */
+    ret = atca_mbedtls_cert_add(&tls->clientcert, cert_def);
+    if (ret != 0) {
+        ESP_LOGE("Failed to parse cert from device, return %02x", ret);
+        return ESP_ERR_ESP_TLS_SE_FAILED;
+    }
+#elif CONFIG_ATECC608A_TCUSTOM
+    esp_ret = esp_init_atecc608a(ATECC608A_TCUSTOM_SLAVE_ADDR);
+    if (ret != ESP_OK) {
+        return ESP_ERR_ESP_TLS_SE_FAILED;
+    }
+    mbedtls_x509_crt_init(&tls->clientcert);
+
+    if(cfg->clientcert_buf != NULL) {
+        ret = mbedtls_x509_crt_parse(&tls->clientcert, (const unsigned char*)cfg->clientcert_buf, cfg->clientcert_bytes);
+        if (ret < 0) {
+            ESP_LOGE("mbedtls_x509_crt_parse returned -0x%x", -ret);
+            ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_MBEDTLS, -ret);
+            return ESP_ERR_MBEDTLS_X509_CRT_PARSE_FAILED;
+        }
+    } else {
+        ESP_LOGE("Device certificate must be provided for TrustCustom Certs");
+        return ESP_FAIL;
+    }
+#endif /* CONFIG_ATECC608A_TCUSTOM */
+    ret = atca_mbedtls_pk_init(&tls->clientkey, 0);
+    if (ret != 0) {
+        ESP_LOGE("Failed to parse key from device");
+        ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_MBEDTLS, -ret);
+        return ESP_ERR_ESP_TLS_SE_FAILED;
+    }
+
+    ret = mbedtls_ssl_conf_own_cert(&tls->conf, &tls->clientcert, &tls->clientkey);
+    if (ret != 0) {
+        ESP_LOGE("Failed\n ! mbedtls_ssl_conf_own_cert returned -0x%x", ret);
+        ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ERR_TYPE_MBEDTLS, -ret);
+        return ESP_ERR_ESP_TLS_SE_FAILED;
+    }
+    return ESP_OK;
+}
+#endif /* CONFIG_ESP_TLS_USE_SECURE_ELEMENT */
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/web_http_parser.c b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/web_http_parser.c
new file mode 100644 (file)
index 0000000..a72ddf8
--- /dev/null
@@ -0,0 +1,2469 @@
+/* Based on src/http/ngx_http_parse.c from NGINX copyright Igor Sysoev
+ *
+ * Additional changes are licensed under the same terms as NGINX and
+ * copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+#include "web_http_parser.h"
+#include <assert.h>
+#include <stddef.h>
+#include <ctype.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+
+#ifndef ULLONG_MAX
+# define ULLONG_MAX ((uint64_t) -1) /* 2^64-1 */
+#endif
+
+#ifndef MIN
+# define MIN(a,b) ((a) < (b) ? (a) : (b))
+#endif
+
+#ifndef ARRAY_SIZE
+# define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
+#endif
+
+#ifndef BIT_AT
+# define BIT_AT(a, i)                                                \
+  (!!((unsigned int) (a)[(unsigned int) (i) >> 3] &                  \
+   (1 << ((unsigned int) (i) & 7))))
+#endif
+
+#ifndef ELEM_AT
+# define ELEM_AT(a, i, v) ((unsigned int) (i) < ARRAY_SIZE(a) ? (a)[(i)] : (v))
+#endif
+
+#define SET_ERRNO(e)                                                 \
+do {                                                                 \
+  parser->http_errno = (e);                                          \
+} while(0)
+
+#define CURRENT_STATE() p_state
+#define UPDATE_STATE(V) p_state = (enum state) (V);
+#define RETURN(V)                                                    \
+do {                                                                 \
+  parser->state = CURRENT_STATE();                                   \
+  return (V);                                                        \
+} while (0);
+#define REEXECUTE()                                                  \
+  goto reexecute;                                                    \
+
+
+#ifdef __GNUC__
+# define LIKELY(X) __builtin_expect(!!(X), 1)
+# define UNLIKELY(X) __builtin_expect(!!(X), 0)
+#else
+# define LIKELY(X) (X)
+# define UNLIKELY(X) (X)
+#endif
+
+
+/* Run the notify callback FOR, returning ER if it fails */
+#define CALLBACK_NOTIFY_(FOR, ER)                                    \
+do {                                                                 \
+  assert(HTTP_PARSER_ERRNO(parser) == HPE_OK);                       \
+                                                                     \
+  if (LIKELY(settings->on_##FOR)) {                                  \
+    parser->state = CURRENT_STATE();                                 \
+    if (UNLIKELY(0 != settings->on_##FOR(parser))) {                 \
+      SET_ERRNO(HPE_CB_##FOR);                                       \
+    }                                                                \
+    UPDATE_STATE(parser->state);                                     \
+                                                                     \
+    /* We either errored above or got paused; get out */             \
+    if (UNLIKELY(HTTP_PARSER_ERRNO(parser) != HPE_OK)) {             \
+      return (ER);                                                   \
+    }                                                                \
+  }                                                                  \
+} while (0)
+
+/* Run the notify callback FOR and consume the current byte */
+#define CALLBACK_NOTIFY(FOR)            CALLBACK_NOTIFY_(FOR, p - data + 1)
+
+/* Run the notify callback FOR and don't consume the current byte */
+#define CALLBACK_NOTIFY_NOADVANCE(FOR)  CALLBACK_NOTIFY_(FOR, p - data)
+
+/* Run data callback FOR with LEN bytes, returning ER if it fails */
+#define CALLBACK_DATA_(FOR, LEN, ER)                                 \
+do {                                                                 \
+  assert(HTTP_PARSER_ERRNO(parser) == HPE_OK);                       \
+                                                                     \
+  if (FOR##_mark) {                                                  \
+    if (LIKELY(settings->on_##FOR)) {                                \
+      parser->state = CURRENT_STATE();                               \
+      if (UNLIKELY(0 !=                                              \
+                   settings->on_##FOR(parser, FOR##_mark, (LEN)))) { \
+        SET_ERRNO(HPE_CB_##FOR);                                     \
+      }                                                              \
+      UPDATE_STATE(parser->state);                                   \
+                                                                     \
+      /* We either errored above or got paused; get out */           \
+      if (UNLIKELY(HTTP_PARSER_ERRNO(parser) != HPE_OK)) {           \
+        return (ER);                                                 \
+      }                                                              \
+    }                                                                \
+    FOR##_mark = NULL;                                               \
+  }                                                                  \
+} while (0)
+
+/* Run the data callback FOR and consume the current byte */
+#define CALLBACK_DATA(FOR)                                           \
+    CALLBACK_DATA_(FOR, p - FOR##_mark, p - data + 1)
+
+/* Run the data callback FOR and don't consume the current byte */
+#define CALLBACK_DATA_NOADVANCE(FOR)                                 \
+    CALLBACK_DATA_(FOR, p - FOR##_mark, p - data)
+
+/* Set the mark FOR; non-destructive if mark is already set */
+#define MARK(FOR)                                                    \
+do {                                                                 \
+  if (!FOR##_mark) {                                                 \
+    FOR##_mark = p;                                                  \
+  }                                                                  \
+} while (0)
+
+/* Don't allow the total size of the HTTP headers (including the status
+ * line) to exceed HTTP_MAX_HEADER_SIZE.  This check is here to protect
+ * embedders against denial-of-service attacks where the attacker feeds
+ * us a never-ending header that the embedder keeps buffering.
+ *
+ * This check is arguably the responsibility of embedders but we're doing
+ * it on the embedder's behalf because most won't bother and this way we
+ * make the web a little safer.  HTTP_MAX_HEADER_SIZE is still far bigger
+ * than any reasonable request or response so this should never affect
+ * day-to-day operation.
+ */
+#define COUNT_HEADER_SIZE(V)                                         \
+do {                                                                 \
+  parser->nread += (V);                                              \
+  if (UNLIKELY(parser->nread > (HTTP_MAX_HEADER_SIZE))) {            \
+    SET_ERRNO(HPE_HEADER_OVERFLOW);                                  \
+    goto error;                                                      \
+  }                                                                  \
+} while (0)
+
+
+#define PROXY_CONNECTION "proxy-connection"
+#define CONNECTION "connection"
+#define CONTENT_LENGTH "content-length"
+#define TRANSFER_ENCODING "transfer-encoding"
+#define UPGRADE "upgrade"
+#define CHUNKED "chunked"
+#define KEEP_ALIVE "keep-alive"
+#define CLOSE "close"
+
+
+static const char *method_strings[] =
+  {
+#define XX(num, name, string) #string,
+  HTTP_METHOD_MAP(XX)
+#undef XX
+  };
+
+
+/* Tokens as defined by rfc 2616. Also lowercases them.
+ *        token       = 1*<any CHAR except CTLs or separators>
+ *     separators     = "(" | ")" | "<" | ">" | "@"
+ *                    | "," | ";" | ":" | "\" | <">
+ *                    | "/" | "[" | "]" | "?" | "="
+ *                    | "{" | "}" | SP | HT
+ */
+static const char tokens[256] = {
+/*   0 nul    1 soh    2 stx    3 etx    4 eot    5 enq    6 ack    7 bel  */
+        0,       0,       0,       0,       0,       0,       0,       0,
+/*   8 bs     9 ht    10 nl    11 vt    12 np    13 cr    14 so    15 si   */
+        0,       0,       0,       0,       0,       0,       0,       0,
+/*  16 dle   17 dc1   18 dc2   19 dc3   20 dc4   21 nak   22 syn   23 etb */
+        0,       0,       0,       0,       0,       0,       0,       0,
+/*  24 can   25 em    26 sub   27 esc   28 fs    29 gs    30 rs    31 us  */
+        0,       0,       0,       0,       0,       0,       0,       0,
+/*  32 sp    33  !    34  "    35  #    36  $    37  %    38  &    39  '  */
+        0,      '!',      0,      '#',     '$',     '%',     '&',    '\'',
+/*  40  (    41  )    42  *    43  +    44  ,    45  -    46  .    47  /  */
+        0,       0,      '*',     '+',      0,      '-',     '.',      0,
+/*  48  0    49  1    50  2    51  3    52  4    53  5    54  6    55  7  */
+       '0',     '1',     '2',     '3',     '4',     '5',     '6',     '7',
+/*  56  8    57  9    58  :    59  ;    60  <    61  =    62  >    63  ?  */
+       '8',     '9',      0,       0,       0,       0,       0,       0,
+/*  64  @    65  A    66  B    67  C    68  D    69  E    70  F    71  G  */
+        0,      'a',     'b',     'c',     'd',     'e',     'f',     'g',
+/*  72  H    73  I    74  J    75  K    76  L    77  M    78  N    79  O  */
+       'h',     'i',     'j',     'k',     'l',     'm',     'n',     'o',
+/*  80  P    81  Q    82  R    83  S    84  T    85  U    86  V    87  W  */
+       'p',     'q',     'r',     's',     't',     'u',     'v',     'w',
+/*  88  X    89  Y    90  Z    91  [    92  \    93  ]    94  ^    95  _  */
+       'x',     'y',     'z',      0,       0,       0,      '^',     '_',
+/*  96  `    97  a    98  b    99  c   100  d   101  e   102  f   103  g  */
+       '`',     'a',     'b',     'c',     'd',     'e',     'f',     'g',
+/* 104  h   105  i   106  j   107  k   108  l   109  m   110  n   111  o  */
+       'h',     'i',     'j',     'k',     'l',     'm',     'n',     'o',
+/* 112  p   113  q   114  r   115  s   116  t   117  u   118  v   119  w  */
+       'p',     'q',     'r',     's',     't',     'u',     'v',     'w',
+/* 120  x   121  y   122  z   123  {   124  |   125  }   126  ~   127 del */
+       'x',     'y',     'z',      0,      '|',      0,      '~',       0 };
+
+
+static const int8_t unhex[256] =
+  {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1
+  ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  };
+
+
+#if HTTP_PARSER_STRICT
+# define T(v) 0
+#else
+# define T(v) v
+#endif
+
+
+static const uint8_t normal_url_char[32] = {
+/*   0 nul    1 soh    2 stx    3 etx    4 eot    5 enq    6 ack    7 bel  */
+        0    |   0    |   0    |   0    |   0    |   0    |   0    |   0,
+/*   8 bs     9 ht    10 nl    11 vt    12 np    13 cr    14 so    15 si   */
+        0    | T(2)   |   0    |   0    | T(16)  |   0    |   0    |   0,
+/*  16 dle   17 dc1   18 dc2   19 dc3   20 dc4   21 nak   22 syn   23 etb */
+        0    |   0    |   0    |   0    |   0    |   0    |   0    |   0,
+/*  24 can   25 em    26 sub   27 esc   28 fs    29 gs    30 rs    31 us  */
+        0    |   0    |   0    |   0    |   0    |   0    |   0    |   0,
+/*  32 sp    33  !    34  "    35  #    36  $    37  %    38  &    39  '  */
+        0    |   2    |   4    |   0    |   16   |   32   |   64   |  128,
+/*  40  (    41  )    42  *    43  +    44  ,    45  -    46  .    47  /  */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
+/*  48  0    49  1    50  2    51  3    52  4    53  5    54  6    55  7  */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
+/*  56  8    57  9    58  :    59  ;    60  <    61  =    62  >    63  ?  */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |   0,
+/*  64  @    65  A    66  B    67  C    68  D    69  E    70  F    71  G  */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
+/*  72  H    73  I    74  J    75  K    76  L    77  M    78  N    79  O  */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
+/*  80  P    81  Q    82  R    83  S    84  T    85  U    86  V    87  W  */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
+/*  88  X    89  Y    90  Z    91  [    92  \    93  ]    94  ^    95  _  */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
+/*  96  `    97  a    98  b    99  c   100  d   101  e   102  f   103  g  */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
+/* 104  h   105  i   106  j   107  k   108  l   109  m   110  n   111  o  */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
+/* 112  p   113  q   114  r   115  s   116  t   117  u   118  v   119  w  */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
+/* 120  x   121  y   122  z   123  {   124  |   125  }   126  ~   127 del */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |   0, };
+
+#undef T
+
+enum state
+  { s_dead = 1 /* important that this is > 0 */
+
+  , s_start_req_or_res
+  , s_res_or_resp_H
+  , s_start_res
+  , s_res_H
+  , s_res_HT
+  , s_res_HTT
+  , s_res_HTTP
+  , s_res_first_http_major
+  , s_res_http_major
+  , s_res_first_http_minor
+  , s_res_http_minor
+  , s_res_first_status_code
+  , s_res_status_code
+  , s_res_status_start
+  , s_res_status
+  , s_res_line_almost_done
+
+  , s_start_req
+
+  , s_req_method
+  , s_req_spaces_before_url
+  , s_req_schema
+  , s_req_schema_slash
+  , s_req_schema_slash_slash
+  , s_req_server_start
+  , s_req_server
+  , s_req_server_with_at
+  , s_req_path
+  , s_req_query_string_start
+  , s_req_query_string
+  , s_req_fragment_start
+  , s_req_fragment
+  , s_req_http_start
+  , s_req_http_H
+  , s_req_http_HT
+  , s_req_http_HTT
+  , s_req_http_HTTP
+  , s_req_first_http_major
+  , s_req_http_major
+  , s_req_first_http_minor
+  , s_req_http_minor
+  , s_req_line_almost_done
+
+  , s_header_field_start
+  , s_header_field
+  , s_header_value_discard_ws
+  , s_header_value_discard_ws_almost_done
+  , s_header_value_discard_lws
+  , s_header_value_start
+  , s_header_value
+  , s_header_value_lws
+
+  , s_header_almost_done
+
+  , s_chunk_size_start
+  , s_chunk_size
+  , s_chunk_parameters
+  , s_chunk_size_almost_done
+
+  , s_headers_almost_done
+  , s_headers_done
+
+  /* Important: 's_headers_done' must be the last 'header' state. All
+   * states beyond this must be 'body' states. It is used for overflow
+   * checking. See the PARSING_HEADER() macro.
+   */
+
+  , s_chunk_data
+  , s_chunk_data_almost_done
+  , s_chunk_data_done
+
+  , s_body_identity
+  , s_body_identity_eof
+
+  , s_message_done
+  };
+
+
+#define PARSING_HEADER(state) (state <= s_headers_done)
+
+
+enum header_states
+  { h_general = 0
+  , h_C
+  , h_CO
+  , h_CON
+
+  , h_matching_connection
+  , h_matching_proxy_connection
+  , h_matching_content_length
+  , h_matching_transfer_encoding
+  , h_matching_upgrade
+
+  , h_connection
+  , h_content_length
+  , h_transfer_encoding
+  , h_upgrade
+
+  , h_matching_transfer_encoding_chunked
+  , h_matching_connection_token_start
+  , h_matching_connection_keep_alive
+  , h_matching_connection_close
+  , h_matching_connection_upgrade
+  , h_matching_connection_token
+
+  , h_transfer_encoding_chunked
+  , h_connection_keep_alive
+  , h_connection_close
+  , h_connection_upgrade
+  };
+
+enum http_host_state
+  {
+    s_http_host_dead = 1
+  , s_http_userinfo_start
+  , s_http_userinfo
+  , s_http_host_start
+  , s_http_host_v6_start
+  , s_http_host
+  , s_http_host_v6
+  , s_http_host_v6_end
+  , s_http_host_v6_zone_start
+  , s_http_host_v6_zone
+  , s_http_host_port_start
+  , s_http_host_port
+};
+
+/* Macros for character classes; depends on strict-mode  */
+#define CR                  '\r'
+#define LF                  '\n'
+#define LOWER(c)            (unsigned char)(c | 0x20)
+#define IS_ALPHA(c)         (LOWER(c) >= 'a' && LOWER(c) <= 'z')
+#define IS_NUM(c)           ((c) >= '0' && (c) <= '9')
+#define IS_ALPHANUM(c)      (IS_ALPHA(c) || IS_NUM(c))
+#define IS_HEX(c)           (IS_NUM(c) || (LOWER(c) >= 'a' && LOWER(c) <= 'f'))
+#define IS_MARK(c)          ((c) == '-' || (c) == '_' || (c) == '.' || \
+  (c) == '!' || (c) == '~' || (c) == '*' || (c) == '\'' || (c) == '(' || \
+  (c) == ')')
+#define IS_USERINFO_CHAR(c) (IS_ALPHANUM(c) || IS_MARK(c) || (c) == '%' || \
+  (c) == ';' || (c) == ':' || (c) == '&' || (c) == '=' || (c) == '+' || \
+  (c) == '$' || (c) == ',')
+
+#define STRICT_TOKEN(c)     (tokens[(unsigned char)c])
+
+#if HTTP_PARSER_STRICT
+#define TOKEN(c)            (tokens[(unsigned char)c])
+#define IS_URL_CHAR(c)      (BIT_AT(normal_url_char, (unsigned char)c))
+#define IS_HOST_CHAR(c)     (IS_ALPHANUM(c) || (c) == '.' || (c) == '-')
+#else
+#define TOKEN(c)            ((c == ' ') ? ' ' : tokens[(unsigned char)c])
+#define IS_URL_CHAR(c)                                                         \
+  (BIT_AT(normal_url_char, (unsigned char)c) || ((c) & 0x80))
+#define IS_HOST_CHAR(c)                                                        \
+  (IS_ALPHANUM(c) || (c) == '.' || (c) == '-' || (c) == '_')
+#endif
+
+/**
+ * Verify that a char is a valid visible (printable) US-ASCII
+ * character or %x80-FF
+ **/
+#define IS_HEADER_CHAR(ch)                                                     \
+  (ch == CR || ch == LF || ch == 9 || ((unsigned char)ch > 31 && ch != 127))
+
+#define start_state (parser->type == HTTP_REQUEST ? s_start_req : s_start_res)
+
+
+#if HTTP_PARSER_STRICT
+# define STRICT_CHECK(cond)                                          \
+do {                                                                 \
+  if (cond) {                                                        \
+    SET_ERRNO(HPE_STRICT);                                           \
+    goto error;                                                      \
+  }                                                                  \
+} while (0)
+# define NEW_MESSAGE() (wb_http_should_keep_alive(parser) ? start_state : s_dead)
+#else
+# define STRICT_CHECK(cond)
+# define NEW_MESSAGE() start_state
+#endif
+
+
+/* Map errno values to strings for human-readable output */
+#define HTTP_STRERROR_GEN(n, s) { "HPE_" #n, s },
+static struct {
+  const char *name;
+  const char *description;
+} http_strerror_tab[] = {
+  HTTP_ERRNO_MAP(HTTP_STRERROR_GEN)
+};
+#undef HTTP_STRERROR_GEN
+
+int wb_http_message_needs_eof(const http_parser *parser);
+
+/* Our URL parser.
+ *
+ * This is designed to be shared by wb_http_parser_execute() for URL validation,
+ * hence it has a state transition + byte-for-byte interface. In addition, it
+ * is meant to be embedded in wb_http_parser_parse_url(), which does the dirty
+ * work of turning state transitions URL components for its API.
+ *
+ * This function should only be invoked with non-space characters. It is
+ * assumed that the caller cares about (and can detect) the transition between
+ * URL and non-URL states by looking for these.
+ */
+static enum state
+parse_url_char(enum state s, const char ch)
+{
+  if (ch == ' ' || ch == '\r' || ch == '\n') {
+    return s_dead;
+  }
+
+#if HTTP_PARSER_STRICT
+  if (ch == '\t' || ch == '\f') {
+    return s_dead;
+  }
+#endif
+
+  switch (s) {
+    case s_req_spaces_before_url:
+      /* Proxied requests are followed by scheme of an absolute URI (alpha).
+       * All methods except CONNECT are followed by '/' or '*'.
+       */
+
+      if (ch == '/' || ch == '*') {
+        return s_req_path;
+      }
+
+      if (IS_ALPHA(ch)) {
+        return s_req_schema;
+      }
+
+      break;
+
+    case s_req_schema:
+      if (IS_ALPHA(ch)) {
+        return s;
+      }
+
+      if (ch == ':') {
+        return s_req_schema_slash;
+      }
+
+      break;
+
+    case s_req_schema_slash:
+      if (ch == '/') {
+        return s_req_schema_slash_slash;
+      }
+
+      break;
+
+    case s_req_schema_slash_slash:
+      if (ch == '/') {
+        return s_req_server_start;
+      }
+
+      break;
+
+    case s_req_server_with_at:
+      if (ch == '@') {
+        return s_dead;
+      }
+
+    /* FALLTHROUGH */
+    case s_req_server_start:
+    case s_req_server:
+      if (ch == '/') {
+        return s_req_path;
+      }
+
+      if (ch == '?') {
+        return s_req_query_string_start;
+      }
+
+      if (ch == '@') {
+        return s_req_server_with_at;
+      }
+
+      if (IS_USERINFO_CHAR(ch) || ch == '[' || ch == ']') {
+        return s_req_server;
+      }
+
+      break;
+
+    case s_req_path:
+      if (IS_URL_CHAR(ch)) {
+        return s;
+      }
+
+      switch (ch) {
+        case '?':
+          return s_req_query_string_start;
+
+        case '#':
+          return s_req_fragment_start;
+      }
+
+      break;
+
+    case s_req_query_string_start:
+    case s_req_query_string:
+      if (IS_URL_CHAR(ch)) {
+        return s_req_query_string;
+      }
+
+      switch (ch) {
+        case '?':
+          /* allow extra '?' in query string */
+          return s_req_query_string;
+
+        case '#':
+          return s_req_fragment_start;
+      }
+
+      break;
+
+    case s_req_fragment_start:
+      if (IS_URL_CHAR(ch)) {
+        return s_req_fragment;
+      }
+
+      switch (ch) {
+        case '?':
+          return s_req_fragment;
+
+        case '#':
+          return s;
+      }
+
+      break;
+
+    case s_req_fragment:
+      if (IS_URL_CHAR(ch)) {
+        return s;
+      }
+
+      switch (ch) {
+        case '?':
+        case '#':
+          return s;
+      }
+
+      break;
+
+    default:
+      break;
+  }
+
+  /* We should never fall out of the switch above unless there's an error */
+  return s_dead;
+}
+
+size_t wb_http_parser_execute (http_parser *parser,
+                            const http_parser_settings *settings,
+                            const char *data,
+                            size_t len)
+{
+  char c, ch;
+  int8_t unhex_val;
+  const char *p = data;
+  const char *header_field_mark = 0;
+  const char *header_value_mark = 0;
+  const char *url_mark = 0;
+  const char *body_mark = 0;
+  const char *status_mark = 0;
+  enum state p_state = (enum state) parser->state;
+  const unsigned int lenient = parser->lenient_http_headers;
+
+  /* We're in an error state. Don't bother doing anything. */
+  if (HTTP_PARSER_ERRNO(parser) != HPE_OK) {
+    return 0;
+  }
+
+  if (len == 0) {
+    switch (CURRENT_STATE()) {
+      case s_body_identity_eof:
+        /* Use of CALLBACK_NOTIFY() here would erroneously return 1 byte read if
+         * we got paused.
+         */
+        CALLBACK_NOTIFY_NOADVANCE(message_complete);
+        return 0;
+
+      case s_dead:
+      case s_start_req_or_res:
+      case s_start_res:
+      case s_start_req:
+        return 0;
+
+      default:
+        SET_ERRNO(HPE_INVALID_EOF_STATE);
+        return 1;
+    }
+  }
+
+
+  if (CURRENT_STATE() == s_header_field)
+    header_field_mark = data;
+  if (CURRENT_STATE() == s_header_value)
+    header_value_mark = data;
+  switch (CURRENT_STATE()) {
+  case s_req_path:
+  case s_req_schema:
+  case s_req_schema_slash:
+  case s_req_schema_slash_slash:
+  case s_req_server_start:
+  case s_req_server:
+  case s_req_server_with_at:
+  case s_req_query_string_start:
+  case s_req_query_string:
+  case s_req_fragment_start:
+  case s_req_fragment:
+    url_mark = data;
+    break;
+  case s_res_status:
+    status_mark = data;
+    break;
+  default:
+    break;
+  }
+
+  for (p=data; p != data + len; p++) {
+    ch = *p;
+
+    if (PARSING_HEADER(CURRENT_STATE()))
+      COUNT_HEADER_SIZE(1);
+
+reexecute:
+    switch (CURRENT_STATE()) {
+
+      case s_dead:
+        /* this state is used after a 'Connection: close' message
+         * the parser will error out if it reads another message
+         */
+        if (LIKELY(ch == CR || ch == LF))
+          break;
+
+        SET_ERRNO(HPE_CLOSED_CONNECTION);
+        goto error;
+
+      case s_start_req_or_res:
+      {
+        if (ch == CR || ch == LF)
+          break;
+        parser->flags = 0;
+        parser->content_length = ULLONG_MAX;
+
+        if (ch == 'H') {
+          UPDATE_STATE(s_res_or_resp_H);
+
+          CALLBACK_NOTIFY(message_begin);
+        } else {
+          parser->type = HTTP_REQUEST;
+          UPDATE_STATE(s_start_req);
+          REEXECUTE();
+        }
+
+        break;
+      }
+
+      case s_res_or_resp_H:
+        if (ch == 'T') {
+          parser->type = HTTP_RESPONSE;
+          UPDATE_STATE(s_res_HT);
+        } else {
+          if (UNLIKELY(ch != 'E')) {
+            SET_ERRNO(HPE_INVALID_CONSTANT);
+            goto error;
+          }
+
+          parser->type = HTTP_REQUEST;
+          parser->method = HTTP_HEAD;
+          parser->index = 2;
+          UPDATE_STATE(s_req_method);
+        }
+        break;
+
+      case s_start_res:
+      {
+        parser->flags = 0;
+        parser->content_length = ULLONG_MAX;
+
+        switch (ch) {
+          case 'H':
+            UPDATE_STATE(s_res_H);
+            break;
+
+          case CR:
+          case LF:
+            break;
+
+          default:
+            SET_ERRNO(HPE_INVALID_CONSTANT);
+            goto error;
+        }
+
+        CALLBACK_NOTIFY(message_begin);
+        break;
+      }
+
+      case s_res_H:
+        STRICT_CHECK(ch != 'T');
+        UPDATE_STATE(s_res_HT);
+        break;
+
+      case s_res_HT:
+        STRICT_CHECK(ch != 'T');
+        UPDATE_STATE(s_res_HTT);
+        break;
+
+      case s_res_HTT:
+        STRICT_CHECK(ch != 'P');
+        UPDATE_STATE(s_res_HTTP);
+        break;
+
+      case s_res_HTTP:
+        STRICT_CHECK(ch != '/');
+        UPDATE_STATE(s_res_first_http_major);
+        break;
+
+      case s_res_first_http_major:
+        if (UNLIKELY(ch < '0' || ch > '9')) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_major = ch - '0';
+        UPDATE_STATE(s_res_http_major);
+        break;
+
+      /* major HTTP version or dot */
+      case s_res_http_major:
+      {
+        if (ch == '.') {
+          UPDATE_STATE(s_res_first_http_minor);
+          break;
+        }
+
+        if (!IS_NUM(ch)) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_major *= 10;
+        parser->http_major += ch - '0';
+
+        if (UNLIKELY(parser->http_major > 999)) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        break;
+      }
+
+      /* first digit of minor HTTP version */
+      case s_res_first_http_minor:
+        if (UNLIKELY(!IS_NUM(ch))) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_minor = ch - '0';
+        UPDATE_STATE(s_res_http_minor);
+        break;
+
+      /* minor HTTP version or end of request line */
+      case s_res_http_minor:
+      {
+        if (ch == ' ') {
+          UPDATE_STATE(s_res_first_status_code);
+          break;
+        }
+
+        if (UNLIKELY(!IS_NUM(ch))) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_minor *= 10;
+        parser->http_minor += ch - '0';
+
+        if (UNLIKELY(parser->http_minor > 999)) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        break;
+      }
+
+      case s_res_first_status_code:
+      {
+        if (!IS_NUM(ch)) {
+          if (ch == ' ') {
+            break;
+          }
+
+          SET_ERRNO(HPE_INVALID_STATUS);
+          goto error;
+        }
+        parser->status_code = ch - '0';
+        UPDATE_STATE(s_res_status_code);
+        break;
+      }
+
+      case s_res_status_code:
+      {
+        if (!IS_NUM(ch)) {
+          switch (ch) {
+            case ' ':
+              UPDATE_STATE(s_res_status_start);
+              break;
+            case CR:
+              UPDATE_STATE(s_res_line_almost_done);
+              break;
+            case LF:
+              UPDATE_STATE(s_header_field_start);
+              break;
+            default:
+              SET_ERRNO(HPE_INVALID_STATUS);
+              goto error;
+          }
+          break;
+        }
+
+        parser->status_code *= 10;
+        parser->status_code += ch - '0';
+
+        if (UNLIKELY(parser->status_code > 999)) {
+          SET_ERRNO(HPE_INVALID_STATUS);
+          goto error;
+        }
+
+        break;
+      }
+
+      case s_res_status_start:
+      {
+        if (ch == CR) {
+          UPDATE_STATE(s_res_line_almost_done);
+          break;
+        }
+
+        if (ch == LF) {
+          UPDATE_STATE(s_header_field_start);
+          break;
+        }
+
+        MARK(status);
+        UPDATE_STATE(s_res_status);
+        parser->index = 0;
+        break;
+      }
+
+      case s_res_status:
+        if (ch == CR) {
+          UPDATE_STATE(s_res_line_almost_done);
+          CALLBACK_DATA(status);
+          break;
+        }
+
+        if (ch == LF) {
+          UPDATE_STATE(s_header_field_start);
+          CALLBACK_DATA(status);
+          break;
+        }
+
+        break;
+
+      case s_res_line_almost_done:
+        STRICT_CHECK(ch != LF);
+        UPDATE_STATE(s_header_field_start);
+        break;
+
+      case s_start_req:
+      {
+        if (ch == CR || ch == LF)
+          break;
+        parser->flags = 0;
+        parser->content_length = ULLONG_MAX;
+
+        if (UNLIKELY(!IS_ALPHA(ch))) {
+          SET_ERRNO(HPE_INVALID_METHOD);
+          goto error;
+        }
+
+        parser->method = (enum http_method) 0;
+        parser->index = 1;
+        switch (ch) {
+          case 'A': parser->method = HTTP_ACL; break;
+          case 'B': parser->method = HTTP_BIND; break;
+          case 'C': parser->method = HTTP_CONNECT; /* or COPY, CHECKOUT */ break;
+          case 'D': parser->method = HTTP_DELETE; break;
+          case 'G': parser->method = HTTP_GET; break;
+          case 'H': parser->method = HTTP_HEAD; break;
+          case 'L': parser->method = HTTP_LOCK; /* or LINK */ break;
+          case 'M': parser->method = HTTP_MKCOL; /* or MOVE, MKACTIVITY, MERGE, M-SEARCH, MKCALENDAR */ break;
+          case 'N': parser->method = HTTP_NOTIFY; break;
+          case 'O': parser->method = HTTP_OPTIONS; break;
+          case 'P': parser->method = HTTP_POST;
+            /* or PROPFIND|PROPPATCH|PUT|PATCH|PURGE */
+            break;
+          case 'R': parser->method = HTTP_REPORT; /* or REBIND */ break;
+          case 'S': parser->method = HTTP_SUBSCRIBE; /* or SEARCH */ break;
+          case 'T': parser->method = HTTP_TRACE; break;
+          case 'U': parser->method = HTTP_UNLOCK; /* or UNSUBSCRIBE, UNBIND, UNLINK */ break;
+          default:
+            SET_ERRNO(HPE_INVALID_METHOD);
+            goto error;
+        }
+        UPDATE_STATE(s_req_method);
+
+        CALLBACK_NOTIFY(message_begin);
+
+        break;
+      }
+
+      case s_req_method:
+      {
+        const char *matcher;
+        if (UNLIKELY(ch == '\0')) {
+          SET_ERRNO(HPE_INVALID_METHOD);
+          goto error;
+        }
+
+        matcher = method_strings[parser->method];
+        if (ch == ' ' && matcher[parser->index] == '\0') {
+          UPDATE_STATE(s_req_spaces_before_url);
+        } else if (ch == matcher[parser->index]) {
+          ; /* nada */
+        } else if (IS_ALPHA(ch)) {
+
+          switch (parser->method << 16 | parser->index << 8 | ch) {
+#define XX(meth, pos, ch, new_meth) \
+            case (HTTP_##meth << 16 | pos << 8 | ch): \
+              parser->method = HTTP_##new_meth; break;
+
+            XX(POST,      1, 'U', PUT)
+            XX(POST,      1, 'A', PATCH)
+            XX(CONNECT,   1, 'H', CHECKOUT)
+            XX(CONNECT,   2, 'P', COPY)
+            XX(MKCOL,     1, 'O', MOVE)
+            XX(MKCOL,     1, 'E', MERGE)
+            XX(MKCOL,     2, 'A', MKACTIVITY)
+            XX(MKCOL,     3, 'A', MKCALENDAR)
+            XX(SUBSCRIBE, 1, 'E', SEARCH)
+            XX(REPORT,    2, 'B', REBIND)
+            XX(POST,      1, 'R', PROPFIND)
+            XX(PROPFIND,  4, 'P', PROPPATCH)
+            XX(PUT,       2, 'R', PURGE)
+            XX(LOCK,      1, 'I', LINK)
+            XX(UNLOCK,    2, 'S', UNSUBSCRIBE)
+            XX(UNLOCK,    2, 'B', UNBIND)
+            XX(UNLOCK,    3, 'I', UNLINK)
+#undef XX
+
+            default:
+              SET_ERRNO(HPE_INVALID_METHOD);
+              goto error;
+          }
+        } else if (ch == '-' &&
+                   parser->index == 1 &&
+                   parser->method == HTTP_MKCOL) {
+          parser->method = HTTP_MSEARCH;
+        } else {
+          SET_ERRNO(HPE_INVALID_METHOD);
+          goto error;
+        }
+
+        ++parser->index;
+        break;
+      }
+
+      case s_req_spaces_before_url:
+      {
+        if (ch == ' ') break;
+
+        MARK(url);
+        if (parser->method == HTTP_CONNECT) {
+          UPDATE_STATE(s_req_server_start);
+        }
+
+        UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch));
+        if (UNLIKELY(CURRENT_STATE() == s_dead)) {
+          SET_ERRNO(HPE_INVALID_URL);
+          goto error;
+        }
+
+        break;
+      }
+
+      case s_req_schema:
+      case s_req_schema_slash:
+      case s_req_schema_slash_slash:
+      case s_req_server_start:
+      {
+        switch (ch) {
+          /* No whitespace allowed here */
+          case ' ':
+          case CR:
+          case LF:
+            SET_ERRNO(HPE_INVALID_URL);
+            goto error;
+          default:
+            UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch));
+            if (UNLIKELY(CURRENT_STATE() == s_dead)) {
+              SET_ERRNO(HPE_INVALID_URL);
+              goto error;
+            }
+        }
+
+        break;
+      }
+
+      case s_req_server:
+      case s_req_server_with_at:
+      case s_req_path:
+      case s_req_query_string_start:
+      case s_req_query_string:
+      case s_req_fragment_start:
+      case s_req_fragment:
+      {
+        switch (ch) {
+          case ' ':
+            UPDATE_STATE(s_req_http_start);
+            CALLBACK_DATA(url);
+            break;
+          case CR:
+          case LF:
+            parser->http_major = 0;
+            parser->http_minor = 9;
+            UPDATE_STATE((ch == CR) ?
+              s_req_line_almost_done :
+              s_header_field_start);
+            CALLBACK_DATA(url);
+            break;
+          default:
+            UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch));
+            if (UNLIKELY(CURRENT_STATE() == s_dead)) {
+              SET_ERRNO(HPE_INVALID_URL);
+              goto error;
+            }
+        }
+        break;
+      }
+
+      case s_req_http_start:
+        switch (ch) {
+          case 'H':
+            UPDATE_STATE(s_req_http_H);
+            break;
+          case ' ':
+            break;
+          default:
+            SET_ERRNO(HPE_INVALID_CONSTANT);
+            goto error;
+        }
+        break;
+
+      case s_req_http_H:
+        STRICT_CHECK(ch != 'T');
+        UPDATE_STATE(s_req_http_HT);
+        break;
+
+      case s_req_http_HT:
+        STRICT_CHECK(ch != 'T');
+        UPDATE_STATE(s_req_http_HTT);
+        break;
+
+      case s_req_http_HTT:
+        STRICT_CHECK(ch != 'P');
+        UPDATE_STATE(s_req_http_HTTP);
+        break;
+
+      case s_req_http_HTTP:
+        STRICT_CHECK(ch != '/');
+        UPDATE_STATE(s_req_first_http_major);
+        break;
+
+      /* first digit of major HTTP version */
+      case s_req_first_http_major:
+        if (UNLIKELY(ch < '1' || ch > '9')) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_major = ch - '0';
+        UPDATE_STATE(s_req_http_major);
+        break;
+
+      /* major HTTP version or dot */
+      case s_req_http_major:
+      {
+        if (ch == '.') {
+          UPDATE_STATE(s_req_first_http_minor);
+          break;
+        }
+
+        if (UNLIKELY(!IS_NUM(ch))) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_major *= 10;
+        parser->http_major += ch - '0';
+
+        if (UNLIKELY(parser->http_major > 999)) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        break;
+      }
+
+      /* first digit of minor HTTP version */
+      case s_req_first_http_minor:
+        if (UNLIKELY(!IS_NUM(ch))) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_minor = ch - '0';
+        UPDATE_STATE(s_req_http_minor);
+        break;
+
+      /* minor HTTP version or end of request line */
+      case s_req_http_minor:
+      {
+        if (ch == CR) {
+          UPDATE_STATE(s_req_line_almost_done);
+          break;
+        }
+
+        if (ch == LF) {
+          UPDATE_STATE(s_header_field_start);
+          break;
+        }
+
+        /* XXX allow spaces after digit? */
+
+        if (UNLIKELY(!IS_NUM(ch))) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_minor *= 10;
+        parser->http_minor += ch - '0';
+
+        if (UNLIKELY(parser->http_minor > 999)) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        break;
+      }
+
+      /* end of request line */
+      case s_req_line_almost_done:
+      {
+        if (UNLIKELY(ch != LF)) {
+          SET_ERRNO(HPE_LF_EXPECTED);
+          goto error;
+        }
+
+        UPDATE_STATE(s_header_field_start);
+        break;
+      }
+
+      case s_header_field_start:
+      {
+        if (ch == CR) {
+          UPDATE_STATE(s_headers_almost_done);
+          break;
+        }
+
+        if (ch == LF) {
+          /* they might be just sending \n instead of \r\n so this would be
+           * the second \n to denote the end of headers*/
+          UPDATE_STATE(s_headers_almost_done);
+          REEXECUTE();
+        }
+
+        c = TOKEN(ch);
+
+        if (UNLIKELY(!c)) {
+          SET_ERRNO(HPE_INVALID_HEADER_TOKEN);
+          goto error;
+        }
+
+        MARK(header_field);
+
+        parser->index = 0;
+        UPDATE_STATE(s_header_field);
+
+        switch (c) {
+          case 'c':
+            parser->header_state = h_C;
+            break;
+
+          case 'p':
+            parser->header_state = h_matching_proxy_connection;
+            break;
+
+          case 't':
+            parser->header_state = h_matching_transfer_encoding;
+            break;
+
+          case 'u':
+            parser->header_state = h_matching_upgrade;
+            break;
+
+          default:
+            parser->header_state = h_general;
+            break;
+        }
+        break;
+      }
+
+      case s_header_field:
+      {
+        const char* start = p;
+        for (; p != data + len; p++) {
+          ch = *p;
+          c = TOKEN(ch);
+
+          if (!c)
+            break;
+
+          switch (parser->header_state) {
+            case h_general:
+              break;
+
+            case h_C:
+              parser->index++;
+              parser->header_state = (c == 'o' ? h_CO : h_general);
+              break;
+
+            case h_CO:
+              parser->index++;
+              parser->header_state = (c == 'n' ? h_CON : h_general);
+              break;
+
+            case h_CON:
+              parser->index++;
+              switch (c) {
+                case 'n':
+                  parser->header_state = h_matching_connection;
+                  break;
+                case 't':
+                  parser->header_state = h_matching_content_length;
+                  break;
+                default:
+                  parser->header_state = h_general;
+                  break;
+              }
+              break;
+
+            /* connection */
+
+            case h_matching_connection:
+              parser->index++;
+              if (parser->index > sizeof(CONNECTION)-1
+                  || c != CONNECTION[parser->index]) {
+                parser->header_state = h_general;
+              } else if (parser->index == sizeof(CONNECTION)-2) {
+                parser->header_state = h_connection;
+              }
+              break;
+
+            /* proxy-connection */
+
+            case h_matching_proxy_connection:
+              parser->index++;
+              if (parser->index > sizeof(PROXY_CONNECTION)-1
+                  || c != PROXY_CONNECTION[parser->index]) {
+                parser->header_state = h_general;
+              } else if (parser->index == sizeof(PROXY_CONNECTION)-2) {
+                parser->header_state = h_connection;
+              }
+              break;
+
+            /* content-length */
+
+            case h_matching_content_length:
+              parser->index++;
+              if (parser->index > sizeof(CONTENT_LENGTH)-1
+                  || c != CONTENT_LENGTH[parser->index]) {
+                parser->header_state = h_general;
+              } else if (parser->index == sizeof(CONTENT_LENGTH)-2) {
+                if (parser->flags & F_CONTENTLENGTH) {
+                  SET_ERRNO(HPE_UNEXPECTED_CONTENT_LENGTH);
+                  goto error;
+                }
+                parser->header_state = h_content_length;
+                parser->flags |= F_CONTENTLENGTH;
+              }
+              break;
+
+            /* transfer-encoding */
+
+            case h_matching_transfer_encoding:
+              parser->index++;
+              if (parser->index > sizeof(TRANSFER_ENCODING)-1
+                  || c != TRANSFER_ENCODING[parser->index]) {
+                parser->header_state = h_general;
+              } else if (parser->index == sizeof(TRANSFER_ENCODING)-2) {
+                parser->header_state = h_transfer_encoding;
+              }
+              break;
+
+            /* upgrade */
+
+            case h_matching_upgrade:
+              parser->index++;
+              if (parser->index > sizeof(UPGRADE)-1
+                  || c != UPGRADE[parser->index]) {
+                parser->header_state = h_general;
+              } else if (parser->index == sizeof(UPGRADE)-2) {
+                parser->header_state = h_upgrade;
+              }
+              break;
+
+            case h_connection:
+            case h_content_length:
+            case h_transfer_encoding:
+            case h_upgrade:
+              if (ch != ' ') parser->header_state = h_general;
+              break;
+
+            default:
+              assert(0 && "Unknown header_state");
+              break;
+          }
+        }
+
+        COUNT_HEADER_SIZE(p - start);
+
+        if (p == data + len) {
+          --p;
+          break;
+        }
+
+        if (ch == ':') {
+          UPDATE_STATE(s_header_value_discard_ws);
+          CALLBACK_DATA(header_field);
+          break;
+        }
+
+        SET_ERRNO(HPE_INVALID_HEADER_TOKEN);
+        goto error;
+      }
+
+      case s_header_value_discard_ws:
+        if (ch == ' ' || ch == '\t') break;
+
+        if (ch == CR) {
+          UPDATE_STATE(s_header_value_discard_ws_almost_done);
+          break;
+        }
+
+        if (ch == LF) {
+          UPDATE_STATE(s_header_value_discard_lws);
+          break;
+        }
+
+        /* FALLTHROUGH */
+
+      case s_header_value_start:
+      {
+        MARK(header_value);
+
+        UPDATE_STATE(s_header_value);
+        parser->index = 0;
+
+        c = LOWER(ch);
+
+        switch (parser->header_state) {
+          case h_upgrade:
+            parser->flags |= F_UPGRADE;
+            parser->header_state = h_general;
+            break;
+
+          case h_transfer_encoding:
+            /* looking for 'Transfer-Encoding: chunked' */
+            if ('c' == c) {
+              parser->header_state = h_matching_transfer_encoding_chunked;
+            } else {
+              parser->header_state = h_general;
+            }
+            break;
+
+          case h_content_length:
+            if (UNLIKELY(!IS_NUM(ch))) {
+              SET_ERRNO(HPE_INVALID_CONTENT_LENGTH);
+              goto error;
+            }
+
+            parser->content_length = ch - '0';
+            break;
+
+          case h_connection:
+            /* looking for 'Connection: keep-alive' */
+            if (c == 'k') {
+              parser->header_state = h_matching_connection_keep_alive;
+            /* looking for 'Connection: close' */
+            } else if (c == 'c') {
+              parser->header_state = h_matching_connection_close;
+            } else if (c == 'u') {
+              parser->header_state = h_matching_connection_upgrade;
+            } else {
+              parser->header_state = h_matching_connection_token;
+            }
+            break;
+
+          /* Multi-value `Connection` header */
+          case h_matching_connection_token_start:
+            break;
+
+          default:
+            parser->header_state = h_general;
+            break;
+        }
+        break;
+      }
+
+      case s_header_value:
+      {
+        const char* start = p;
+        enum header_states h_state = (enum header_states) parser->header_state;
+        for (; p != data + len; p++) {
+          ch = *p;
+          if (ch == CR) {
+            UPDATE_STATE(s_header_almost_done);
+            parser->header_state = h_state;
+            CALLBACK_DATA(header_value);
+            break;
+          }
+
+          if (ch == LF) {
+            UPDATE_STATE(s_header_almost_done);
+            COUNT_HEADER_SIZE(p - start);
+            parser->header_state = h_state;
+            CALLBACK_DATA_NOADVANCE(header_value);
+            REEXECUTE();
+          }
+
+          if (!lenient && !IS_HEADER_CHAR(ch)) {
+            SET_ERRNO(HPE_INVALID_HEADER_TOKEN);
+            goto error;
+          }
+
+          c = LOWER(ch);
+
+          switch (h_state) {
+            case h_general:
+            {
+              const char* p_cr;
+              const char* p_lf;
+              size_t limit = data + len - p;
+
+              limit = MIN(limit, HTTP_MAX_HEADER_SIZE);
+
+              p_cr = (const char*) memchr(p, CR, limit);
+              p_lf = (const char*) memchr(p, LF, limit);
+              if (p_cr != NULL) {
+                if (p_lf != NULL && p_cr >= p_lf)
+                  p = p_lf;
+                else
+                  p = p_cr;
+              } else if (UNLIKELY(p_lf != NULL)) {
+                p = p_lf;
+              } else {
+                p = data + len;
+              }
+              --p;
+
+              break;
+            }
+
+            case h_connection:
+            case h_transfer_encoding:
+              assert(0 && "Shouldn't get here.");
+              break;
+
+            case h_content_length:
+            {
+              uint64_t t;
+
+              if (ch == ' ') break;
+
+              if (UNLIKELY(!IS_NUM(ch))) {
+                SET_ERRNO(HPE_INVALID_CONTENT_LENGTH);
+                parser->header_state = h_state;
+                goto error;
+              }
+
+              t = parser->content_length;
+              t *= 10;
+              t += ch - '0';
+
+              /* Overflow? Test against a conservative limit for simplicity. */
+              if (UNLIKELY((ULLONG_MAX - 10) / 10 < parser->content_length)) {
+                SET_ERRNO(HPE_INVALID_CONTENT_LENGTH);
+                parser->header_state = h_state;
+                goto error;
+              }
+
+              parser->content_length = t;
+              break;
+            }
+
+            /* Transfer-Encoding: chunked */
+            case h_matching_transfer_encoding_chunked:
+              parser->index++;
+              if (parser->index > sizeof(CHUNKED)-1
+                  || c != CHUNKED[parser->index]) {
+                h_state = h_general;
+              } else if (parser->index == sizeof(CHUNKED)-2) {
+                h_state = h_transfer_encoding_chunked;
+              }
+              break;
+
+            case h_matching_connection_token_start:
+              /* looking for 'Connection: keep-alive' */
+              if (c == 'k') {
+                h_state = h_matching_connection_keep_alive;
+              /* looking for 'Connection: close' */
+              } else if (c == 'c') {
+                h_state = h_matching_connection_close;
+              } else if (c == 'u') {
+                h_state = h_matching_connection_upgrade;
+              } else if (STRICT_TOKEN(c)) {
+                h_state = h_matching_connection_token;
+              } else if (c == ' ' || c == '\t') {
+                /* Skip lws */
+              } else {
+                h_state = h_general;
+              }
+              break;
+
+            /* looking for 'Connection: keep-alive' */
+            case h_matching_connection_keep_alive:
+              parser->index++;
+              if (parser->index > sizeof(KEEP_ALIVE)-1
+                  || c != KEEP_ALIVE[parser->index]) {
+                h_state = h_matching_connection_token;
+              } else if (parser->index == sizeof(KEEP_ALIVE)-2) {
+                h_state = h_connection_keep_alive;
+              }
+              break;
+
+            /* looking for 'Connection: close' */
+            case h_matching_connection_close:
+              parser->index++;
+              if (parser->index > sizeof(CLOSE)-1 || c != CLOSE[parser->index]) {
+                h_state = h_matching_connection_token;
+              } else if (parser->index == sizeof(CLOSE)-2) {
+                h_state = h_connection_close;
+              }
+              break;
+
+            /* looking for 'Connection: upgrade' */
+            case h_matching_connection_upgrade:
+              parser->index++;
+              if (parser->index > sizeof(UPGRADE) - 1 ||
+                  c != UPGRADE[parser->index]) {
+                h_state = h_matching_connection_token;
+              } else if (parser->index == sizeof(UPGRADE)-2) {
+                h_state = h_connection_upgrade;
+              }
+              break;
+
+            case h_matching_connection_token:
+              if (ch == ',') {
+                h_state = h_matching_connection_token_start;
+                parser->index = 0;
+              }
+              break;
+
+            case h_transfer_encoding_chunked:
+              if (ch != ' ') h_state = h_general;
+              break;
+
+            case h_connection_keep_alive:
+            case h_connection_close:
+            case h_connection_upgrade:
+              if (ch == ',') {
+                if (h_state == h_connection_keep_alive) {
+                  parser->flags |= F_CONNECTION_KEEP_ALIVE;
+                } else if (h_state == h_connection_close) {
+                  parser->flags |= F_CONNECTION_CLOSE;
+                } else if (h_state == h_connection_upgrade) {
+                  parser->flags |= F_CONNECTION_UPGRADE;
+                }
+                h_state = h_matching_connection_token_start;
+                parser->index = 0;
+              } else if (ch != ' ') {
+                h_state = h_matching_connection_token;
+              }
+              break;
+
+            default:
+              UPDATE_STATE(s_header_value);
+              h_state = h_general;
+              break;
+          }
+        }
+        parser->header_state = h_state;
+
+        COUNT_HEADER_SIZE(p - start);
+
+        if (p == data + len)
+          --p;
+        break;
+      }
+
+      case s_header_almost_done:
+      {
+        if (UNLIKELY(ch != LF)) {
+          SET_ERRNO(HPE_LF_EXPECTED);
+          goto error;
+        }
+
+        UPDATE_STATE(s_header_value_lws);
+        break;
+      }
+
+      case s_header_value_lws:
+      {
+        if (ch == ' ' || ch == '\t') {
+          UPDATE_STATE(s_header_value_start);
+          REEXECUTE();
+        }
+
+        /* finished the header */
+        switch (parser->header_state) {
+          case h_connection_keep_alive:
+            parser->flags |= F_CONNECTION_KEEP_ALIVE;
+            break;
+          case h_connection_close:
+            parser->flags |= F_CONNECTION_CLOSE;
+            break;
+          case h_transfer_encoding_chunked:
+            parser->flags |= F_CHUNKED;
+            break;
+          case h_connection_upgrade:
+            parser->flags |= F_CONNECTION_UPGRADE;
+            break;
+          default:
+            break;
+        }
+
+        UPDATE_STATE(s_header_field_start);
+        REEXECUTE();
+      }
+
+      case s_header_value_discard_ws_almost_done:
+      {
+        STRICT_CHECK(ch != LF);
+        UPDATE_STATE(s_header_value_discard_lws);
+        break;
+      }
+
+      case s_header_value_discard_lws:
+      {
+        if (ch == ' ' || ch == '\t') {
+          UPDATE_STATE(s_header_value_discard_ws);
+          break;
+        } else {
+          switch (parser->header_state) {
+            case h_connection_keep_alive:
+              parser->flags |= F_CONNECTION_KEEP_ALIVE;
+              break;
+            case h_connection_close:
+              parser->flags |= F_CONNECTION_CLOSE;
+              break;
+            case h_connection_upgrade:
+              parser->flags |= F_CONNECTION_UPGRADE;
+              break;
+            case h_transfer_encoding_chunked:
+              parser->flags |= F_CHUNKED;
+              break;
+            default:
+              break;
+          }
+
+          /* header value was empty */
+          MARK(header_value);
+          UPDATE_STATE(s_header_field_start);
+          CALLBACK_DATA_NOADVANCE(header_value);
+          REEXECUTE();
+        }
+      }
+
+      case s_headers_almost_done:
+      {
+        STRICT_CHECK(ch != LF);
+
+        if (parser->flags & F_TRAILING) {
+          /* End of a chunked request */
+          UPDATE_STATE(s_message_done);
+          CALLBACK_NOTIFY_NOADVANCE(chunk_complete);
+          REEXECUTE();
+        }
+
+        /* Cannot use chunked encoding and a content-length header together
+           per the HTTP specification. */
+        if ((parser->flags & F_CHUNKED) &&
+            (parser->flags & F_CONTENTLENGTH)) {
+          SET_ERRNO(HPE_UNEXPECTED_CONTENT_LENGTH);
+          goto error;
+        }
+
+        UPDATE_STATE(s_headers_done);
+
+        /* Set this here so that on_headers_complete() callbacks can see it */
+        parser->upgrade =
+          ((parser->flags & (F_UPGRADE | F_CONNECTION_UPGRADE)) ==
+           (F_UPGRADE | F_CONNECTION_UPGRADE) ||
+           parser->method == HTTP_CONNECT);
+
+        /* Here we call the headers_complete callback. This is somewhat
+         * different than other callbacks because if the user returns 1, we
+         * will interpret that as saying that this message has no body. This
+         * is needed for the annoying case of recieving a response to a HEAD
+         * request.
+         *
+         * We'd like to use CALLBACK_NOTIFY_NOADVANCE() here but we cannot, so
+         * we have to simulate it by handling a change in errno below.
+         */
+        if (settings->on_headers_complete) {
+          switch (settings->on_headers_complete(parser)) {
+            case 0:
+              break;
+
+            case 2:
+              parser->upgrade = 1;
+              /* falls through */
+            case 1:
+              parser->flags |= F_SKIPBODY;
+              break;
+
+            default:
+              SET_ERRNO(HPE_CB_headers_complete);
+              RETURN(p - data); /* Error */
+          }
+        }
+
+        if (HTTP_PARSER_ERRNO(parser) != HPE_OK) {
+          RETURN(p - data);
+        }
+
+        REEXECUTE();
+      }
+
+      case s_headers_done:
+      {
+        int hasBody;
+        STRICT_CHECK(ch != LF);
+
+        parser->nread = 0;
+
+        hasBody = parser->flags & F_CHUNKED ||
+          (parser->content_length > 0 && parser->content_length != ULLONG_MAX);
+        if (parser->upgrade && (parser->method == HTTP_CONNECT ||
+                                (parser->flags & F_SKIPBODY) || !hasBody)) {
+          /* Exit, the rest of the message is in a different protocol. */
+          UPDATE_STATE(NEW_MESSAGE());
+          CALLBACK_NOTIFY(message_complete);
+          RETURN((p - data) + 1);
+        }
+
+        if (parser->flags & F_SKIPBODY) {
+          UPDATE_STATE(NEW_MESSAGE());
+          CALLBACK_NOTIFY(message_complete);
+        } else if (parser->flags & F_CHUNKED) {
+          /* chunked encoding - ignore Content-Length header */
+          UPDATE_STATE(s_chunk_size_start);
+        } else {
+          if (parser->content_length == 0) {
+            /* Content-Length header given but zero: Content-Length: 0\r\n */
+            UPDATE_STATE(NEW_MESSAGE());
+            CALLBACK_NOTIFY(message_complete);
+          } else if (parser->content_length != ULLONG_MAX) {
+            /* Content-Length header given and non-zero */
+            UPDATE_STATE(s_body_identity);
+          } else {
+            if (!wb_http_message_needs_eof(parser)) {
+              /* Assume content-length 0 - read the next */
+              UPDATE_STATE(NEW_MESSAGE());
+              CALLBACK_NOTIFY(message_complete);
+            } else {
+              /* Read body until EOF */
+              UPDATE_STATE(s_body_identity_eof);
+            }
+          }
+        }
+
+        break;
+      }
+
+      case s_body_identity:
+      {
+        uint64_t to_read = MIN(parser->content_length,
+                               (uint64_t) ((data + len) - p));
+
+        assert(parser->content_length != 0
+            && parser->content_length != ULLONG_MAX);
+
+        /* The difference between advancing content_length and p is because
+         * the latter will automaticaly advance on the next loop iteration.
+         * Further, if content_length ends up at 0, we want to see the last
+         * byte again for our message complete callback.
+         */
+        MARK(body);
+        parser->content_length -= to_read;
+        p += to_read - 1;
+
+        if (parser->content_length == 0) {
+          UPDATE_STATE(s_message_done);
+
+          /* Mimic CALLBACK_DATA_NOADVANCE() but with one extra byte.
+           *
+           * The alternative to doing this is to wait for the next byte to
+           * trigger the data callback, just as in every other case. The
+           * problem with this is that this makes it difficult for the test
+           * harness to distinguish between complete-on-EOF and
+           * complete-on-length. It's not clear that this distinction is
+           * important for applications, but let's keep it for now.
+           */
+          CALLBACK_DATA_(body, p - body_mark + 1, p - data);
+          REEXECUTE();
+        }
+
+        break;
+      }
+
+      /* read until EOF */
+      case s_body_identity_eof:
+        MARK(body);
+        p = data + len - 1;
+
+        break;
+
+      case s_message_done:
+        UPDATE_STATE(NEW_MESSAGE());
+        CALLBACK_NOTIFY(message_complete);
+        if (parser->upgrade) {
+          /* Exit, the rest of the message is in a different protocol. */
+          RETURN((p - data) + 1);
+        }
+        break;
+
+      case s_chunk_size_start:
+      {
+        assert(parser->nread == 1);
+        assert(parser->flags & F_CHUNKED);
+
+        unhex_val = unhex[(unsigned char)ch];
+        if (UNLIKELY(unhex_val == -1)) {
+          SET_ERRNO(HPE_INVALID_CHUNK_SIZE);
+          goto error;
+        }
+
+        parser->content_length = unhex_val;
+        UPDATE_STATE(s_chunk_size);
+        break;
+      }
+
+      case s_chunk_size:
+      {
+        uint64_t t;
+
+        assert(parser->flags & F_CHUNKED);
+
+        if (ch == CR) {
+          UPDATE_STATE(s_chunk_size_almost_done);
+          break;
+        }
+
+        unhex_val = unhex[(unsigned char)ch];
+
+        if (unhex_val == -1) {
+          if (ch == ';' || ch == ' ') {
+            UPDATE_STATE(s_chunk_parameters);
+            break;
+          }
+
+          SET_ERRNO(HPE_INVALID_CHUNK_SIZE);
+          goto error;
+        }
+
+        t = parser->content_length;
+        t *= 16;
+        t += unhex_val;
+
+        /* Overflow? Test against a conservative limit for simplicity. */
+        if (UNLIKELY((ULLONG_MAX - 16) / 16 < parser->content_length)) {
+          SET_ERRNO(HPE_INVALID_CONTENT_LENGTH);
+          goto error;
+        }
+
+        parser->content_length = t;
+        break;
+      }
+
+      case s_chunk_parameters:
+      {
+        assert(parser->flags & F_CHUNKED);
+        /* just ignore this shit. TODO check for overflow */
+        if (ch == CR) {
+          UPDATE_STATE(s_chunk_size_almost_done);
+          break;
+        }
+        break;
+      }
+
+      case s_chunk_size_almost_done:
+      {
+        assert(parser->flags & F_CHUNKED);
+        STRICT_CHECK(ch != LF);
+
+        parser->nread = 0;
+
+        if (parser->content_length == 0) {
+          parser->flags |= F_TRAILING;
+          UPDATE_STATE(s_header_field_start);
+        } else {
+          UPDATE_STATE(s_chunk_data);
+        }
+        CALLBACK_NOTIFY(chunk_header);
+        break;
+      }
+
+      case s_chunk_data:
+      {
+        uint64_t to_read = MIN(parser->content_length,
+                               (uint64_t) ((data + len) - p));
+
+        assert(parser->flags & F_CHUNKED);
+        assert(parser->content_length != 0
+            && parser->content_length != ULLONG_MAX);
+
+        /* See the explanation in s_body_identity for why the content
+         * length and data pointers are managed this way.
+         */
+        MARK(body);
+        parser->content_length -= to_read;
+        p += to_read - 1;
+
+        if (parser->content_length == 0) {
+          UPDATE_STATE(s_chunk_data_almost_done);
+        }
+
+        break;
+      }
+
+      case s_chunk_data_almost_done:
+        assert(parser->flags & F_CHUNKED);
+        assert(parser->content_length == 0);
+        STRICT_CHECK(ch != CR);
+        UPDATE_STATE(s_chunk_data_done);
+        CALLBACK_DATA(body);
+        break;
+
+      case s_chunk_data_done:
+        assert(parser->flags & F_CHUNKED);
+        STRICT_CHECK(ch != LF);
+        parser->nread = 0;
+        UPDATE_STATE(s_chunk_size_start);
+        CALLBACK_NOTIFY(chunk_complete);
+        break;
+
+      default:
+        assert(0 && "unhandled state");
+        SET_ERRNO(HPE_INVALID_INTERNAL_STATE);
+        goto error;
+    }
+  }
+
+  /* Run callbacks for any marks that we have leftover after we ran our of
+   * bytes. There should be at most one of these set, so it's OK to invoke
+   * them in series (unset marks will not result in callbacks).
+   *
+   * We use the NOADVANCE() variety of callbacks here because 'p' has already
+   * overflowed 'data' and this allows us to correct for the off-by-one that
+   * we'd otherwise have (since CALLBACK_DATA() is meant to be run with a 'p'
+   * value that's in-bounds).
+   */
+
+  assert(((header_field_mark ? 1 : 0) +
+          (header_value_mark ? 1 : 0) +
+          (url_mark ? 1 : 0)  +
+          (body_mark ? 1 : 0) +
+          (status_mark ? 1 : 0)) <= 1);
+
+  CALLBACK_DATA_NOADVANCE(header_field);
+  CALLBACK_DATA_NOADVANCE(header_value);
+  CALLBACK_DATA_NOADVANCE(url);
+  CALLBACK_DATA_NOADVANCE(body);
+  CALLBACK_DATA_NOADVANCE(status);
+
+  RETURN(len);
+
+error:
+  if (HTTP_PARSER_ERRNO(parser) == HPE_OK) {
+    SET_ERRNO(HPE_UNKNOWN);
+  }
+
+  RETURN(p - data);
+}
+
+
+/* Does the parser need to see an EOF to find the end of the message? */
+int
+wb_http_message_needs_eof (const http_parser *parser)
+{
+  if (parser->type == HTTP_REQUEST) {
+    return 0;
+  }
+
+  /* See RFC 2616 section 4.4 */
+  if (parser->status_code / 100 == 1 || /* 1xx e.g. Continue */
+      parser->status_code == 204 ||     /* No Content */
+      parser->status_code == 304 ||     /* Not Modified */
+      parser->flags & F_SKIPBODY) {     /* response to a HEAD request */
+    return 0;
+  }
+
+  if ((parser->flags & F_CHUNKED) || parser->content_length != ULLONG_MAX) {
+    return 0;
+  }
+
+  return 1;
+}
+
+
+int
+wb_http_should_keep_alive (const http_parser *parser)
+{
+  if (parser->http_major > 0 && parser->http_minor > 0) {
+    /* HTTP/1.1 */
+    if (parser->flags & F_CONNECTION_CLOSE) {
+      return 0;
+    }
+  } else {
+    /* HTTP/1.0 or earlier */
+    if (!(parser->flags & F_CONNECTION_KEEP_ALIVE)) {
+      return 0;
+    }
+  }
+
+  return !wb_http_message_needs_eof(parser);
+}
+
+
+const char *
+wb_http_method_str (enum http_method m)
+{
+  return ELEM_AT(method_strings, m, "<unknown>");
+}
+
+
+void
+wb_http_parser_init (http_parser *parser, enum http_parser_type t)
+{
+  void *data = parser->data; /* preserve application data */
+  memset(parser, 0, sizeof(*parser));
+  parser->data = data;
+  parser->type = t;
+  parser->state = (t == HTTP_REQUEST ? s_start_req : (t == HTTP_RESPONSE ? s_start_res : s_start_req_or_res));
+  parser->http_errno = HPE_OK;
+}
+
+void
+wb_http_parser_settings_init(http_parser_settings *settings)
+{
+  memset(settings, 0, sizeof(*settings));
+}
+
+const char *
+wb_http_errno_name(enum http_errno err) {
+  assert(((size_t) err) < ARRAY_SIZE(http_strerror_tab));
+  return http_strerror_tab[err].name;
+}
+
+const char *
+wb_http_errno_description(enum http_errno err) {
+  assert(((size_t) err) < ARRAY_SIZE(http_strerror_tab));
+  return http_strerror_tab[err].description;
+}
+
+static enum http_host_state
+http_parse_host_char(enum http_host_state s, const char ch) {
+  switch(s) {
+    case s_http_userinfo:
+    case s_http_userinfo_start:
+      if (ch == '@') {
+        return s_http_host_start;
+      }
+
+      if (IS_USERINFO_CHAR(ch)) {
+        return s_http_userinfo;
+      }
+      break;
+
+    case s_http_host_start:
+      if (ch == '[') {
+        return s_http_host_v6_start;
+      }
+
+      if (IS_HOST_CHAR(ch)) {
+        return s_http_host;
+      }
+
+      break;
+
+    case s_http_host:
+      if (IS_HOST_CHAR(ch)) {
+        return s_http_host;
+      }
+
+    /* FALLTHROUGH */
+    case s_http_host_v6_end:
+      if (ch == ':') {
+        return s_http_host_port_start;
+      }
+
+      break;
+
+    case s_http_host_v6:
+      if (ch == ']') {
+        return s_http_host_v6_end;
+      }
+
+    /* FALLTHROUGH */
+    case s_http_host_v6_start:
+      if (IS_HEX(ch) || ch == ':' || ch == '.') {
+        return s_http_host_v6;
+      }
+
+      if (s == s_http_host_v6 && ch == '%') {
+        return s_http_host_v6_zone_start;
+      }
+      break;
+
+    case s_http_host_v6_zone:
+      if (ch == ']') {
+        return s_http_host_v6_end;
+      }
+
+    /* FALLTHROUGH */
+    case s_http_host_v6_zone_start:
+      /* RFC 6874 Zone ID consists of 1*( unreserved / pct-encoded) */
+      if (IS_ALPHANUM(ch) || ch == '%' || ch == '.' || ch == '-' || ch == '_' ||
+          ch == '~') {
+        return s_http_host_v6_zone;
+      }
+      break;
+
+    case s_http_host_port:
+    case s_http_host_port_start:
+      if (IS_NUM(ch)) {
+        return s_http_host_port;
+      }
+
+      break;
+
+    default:
+      break;
+  }
+  return s_http_host_dead;
+}
+
+static int
+http_parse_host(const char * buf, struct http_parser_url *u, int found_at) {
+  enum http_host_state s;
+
+  const char *p;
+  size_t buflen = u->field_data[UF_HOST].off + u->field_data[UF_HOST].len;
+
+  assert(u->field_set & (1 << UF_HOST));
+
+  u->field_data[UF_HOST].len = 0;
+
+  s = found_at ? s_http_userinfo_start : s_http_host_start;
+
+  for (p = buf + u->field_data[UF_HOST].off; p < buf + buflen; p++) {
+    enum http_host_state new_s = http_parse_host_char(s, *p);
+
+    if (new_s == s_http_host_dead) {
+      return 1;
+    }
+
+    switch(new_s) {
+      case s_http_host:
+        if (s != s_http_host) {
+          u->field_data[UF_HOST].off = p - buf;
+        }
+        u->field_data[UF_HOST].len++;
+        break;
+
+      case s_http_host_v6:
+        if (s != s_http_host_v6) {
+          u->field_data[UF_HOST].off = p - buf;
+        }
+        u->field_data[UF_HOST].len++;
+        break;
+
+      case s_http_host_v6_zone_start:
+      case s_http_host_v6_zone:
+        u->field_data[UF_HOST].len++;
+        break;
+
+      case s_http_host_port:
+        if (s != s_http_host_port) {
+          u->field_data[UF_PORT].off = p - buf;
+          u->field_data[UF_PORT].len = 0;
+          u->field_set |= (1 << UF_PORT);
+        }
+        u->field_data[UF_PORT].len++;
+        break;
+
+      case s_http_userinfo:
+        if (s != s_http_userinfo) {
+          u->field_data[UF_USERINFO].off = p - buf ;
+          u->field_data[UF_USERINFO].len = 0;
+          u->field_set |= (1 << UF_USERINFO);
+        }
+        u->field_data[UF_USERINFO].len++;
+        break;
+
+      default:
+        break;
+    }
+    s = new_s;
+  }
+
+  /* Make sure we don't end somewhere unexpected */
+  switch (s) {
+    case s_http_host_start:
+    case s_http_host_v6_start:
+    case s_http_host_v6:
+    case s_http_host_v6_zone_start:
+    case s_http_host_v6_zone:
+    case s_http_host_port_start:
+    case s_http_userinfo:
+    case s_http_userinfo_start:
+      return 1;
+    default:
+      break;
+  }
+
+  return 0;
+}
+
+void
+wb_http_parser_url_init(struct http_parser_url *u) {
+  memset(u, 0, sizeof(*u));
+}
+
+int
+wb_http_parser_parse_url(const char *buf, size_t buflen, int is_connect,
+                      struct http_parser_url *u)
+{
+  enum state s;
+  const char *p;
+  enum http_parser_url_fields uf, old_uf;
+  int found_at = 0;
+
+  u->port = u->field_set = 0;
+  s = is_connect ? s_req_server_start : s_req_spaces_before_url;
+  old_uf = UF_MAX;
+
+  for (p = buf; p < buf + buflen; p++) {
+    s = parse_url_char(s, *p);
+
+    /* Figure out the next field that we're operating on */
+    switch (s) {
+      case s_dead:
+        return 1;
+
+      /* Skip delimeters */
+      case s_req_schema_slash:
+      case s_req_schema_slash_slash:
+      case s_req_server_start:
+      case s_req_query_string_start:
+      case s_req_fragment_start:
+        continue;
+
+      case s_req_schema:
+        uf = UF_SCHEMA;
+        break;
+
+      case s_req_server_with_at:
+        found_at = 1;
+
+        /* falls through */
+      case s_req_server:
+        uf = UF_HOST;
+        break;
+
+      case s_req_path:
+        uf = UF_PATH;
+        break;
+
+      case s_req_query_string:
+        uf = UF_QUERY;
+        break;
+
+      case s_req_fragment:
+        uf = UF_FRAGMENT;
+        break;
+
+      default:
+        assert(!"Unexpected state");
+        return 1;
+    }
+
+    /* Nothing's changed; soldier on */
+    if (uf == old_uf) {
+      u->field_data[uf].len++;
+      continue;
+    }
+
+    u->field_data[uf].off = p - buf;
+    u->field_data[uf].len = 1;
+
+    u->field_set |= (1 << uf);
+    old_uf = uf;
+  }
+
+  /* host must be present if there is a schema */
+  /* parsing http:///toto will fail */
+  if ((u->field_set & (1 << UF_SCHEMA)) &&
+      (u->field_set & (1 << UF_HOST)) == 0) {
+    return 1;
+  }
+
+  if (u->field_set & (1 << UF_HOST)) {
+    if (http_parse_host(buf, u, found_at) != 0) {
+      return 1;
+    }
+  }
+
+  /* CONNECT requests can only contain "hostname:port" */
+  if (is_connect && u->field_set != ((1 << UF_HOST)|(1 << UF_PORT))) {
+    return 1;
+  }
+
+  if (u->field_set & (1 << UF_PORT)) {
+    /* Don't bother with endp; we've already validated the string */
+    unsigned long v = strtoul(buf + u->field_data[UF_PORT].off, NULL, 10);
+
+    /* Ports have a max value of 2^16 */
+    if (v > 0xffff) {
+      return 1;
+    }
+
+    u->port = (uint16_t) v;
+  }
+
+  return 0;
+}
+
+void
+wb_http_parser_pause(http_parser *parser, int paused) {
+  /* Users should only be pausing/unpausing a parser that is not in an error
+   * state. In non-debug builds, there's not much that we can do about this
+   * other than ignore it.
+   */
+  if (HTTP_PARSER_ERRNO(parser) == HPE_OK ||
+      HTTP_PARSER_ERRNO(parser) == HPE_PAUSED) {
+    SET_ERRNO((paused) ? HPE_PAUSED : HPE_OK);
+  } else {
+    assert(0 && "Attempting to pause parser in error state");
+  }
+}
+
+int
+wb_http_body_is_final(const struct http_parser *parser) {
+    return parser->state == s_message_done;
+}
+
+unsigned long
+wb_http_parser_version(void) {
+  return HTTP_PARSER_VERSION_MAJOR * 0x10000 |
+         HTTP_PARSER_VERSION_MINOR * 0x00100 |
+         HTTP_PARSER_VERSION_PATCH * 0x00001;
+}
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/web_random.c b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/web_random.c
new file mode 100644 (file)
index 0000000..c6dc940
--- /dev/null
@@ -0,0 +1,36 @@
+#include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+#include "esp_log.h"
+
+//static const char *TAG = "RANDOM";
+//#define MIN(a,b) ((a)<(b) ? (a):(b))
+
+void wb_esp_fill_random(void *buf, size_t len)
+{
+    ASSERT(buf != NULL);
+    uint8_t *buf_bytes = (uint8_t *)buf;
+    while (len > 0) {
+        int word = rand();
+               ESP_LOGD("wb_getrandom word=%d", word);
+        uint32_t to_copy = MIN(sizeof(word), len);
+        memcpy(buf_bytes, &word, to_copy);
+        buf_bytes += to_copy;
+        len -= to_copy;
+    }
+}
+
+int wb_getrandom(void *buf, size_t buflen, unsigned int flags)
+{
+    ESP_LOGD("wb_getrandom(buf=0x%x, buflen=%d, flags=%u)", (int) buf, buflen, flags);
+
+    if (buf == NULL) {
+        ESP_LOGD("wb_getrandom returns -1 (EFAULT)");
+        return -1;
+    }
+
+    wb_esp_fill_random(buf, buflen);
+
+    ESP_LOGD("wb_getrandom returns %d", buflen);
+    return buflen;
+}
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/web_transport.c b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/web_transport.c
new file mode 100644 (file)
index 0000000..794c2b3
--- /dev/null
@@ -0,0 +1,297 @@
+// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include <stdlib.h>
+#include <string.h>
+#include <sim_esp_tls.h>
+
+#include "queue.h"
+#include "esp_log.h"
+
+#include "web_esp_transport.h"
+//#include "web_esp_transport_utils.h"
+
+//static const char *TAG = "TRANSPORT";
+
+/**
+ * Transport layer structure, which will provide functions, basic properties for transport types
+ */
+
+/**
+ * This list will hold all transport available
+ */
+STAILQ_HEAD(esp_transport_list_t, wb_esp_transport_item_t);
+
+/**
+ * Internal transport structure holding list of transports and other data common to all transports
+ */
+typedef struct wb_esp_transport_internal {
+    struct esp_transport_list_t list;                      /*!< List of transports */
+    wb_esp_tls_error_handle_t  error_handle;                               /*!< Pointer to the error tracker if enabled  */
+} esp_transport_internal_t;
+
+static wb_esp_transport_handle_t wb_esp_transport_get_default_parent(wb_esp_transport_handle_t t)
+{
+    /*
+    * By default, the underlying transport layer handle is the handle itself
+    */
+    return t;
+}
+
+wb_esp_transport_list_handle_t wb_esp_transport_list_init()
+{
+    wb_esp_transport_list_handle_t transport = calloc(1, sizeof(esp_transport_internal_t));
+    ESP_TRANSPORT_MEM_CHECK(transport, return NULL);
+    STAILQ_INIT(&transport->list);
+    transport->error_handle = calloc(1, sizeof(esp_tls_last_error_t));
+    return transport;
+}
+
+esp_err_t wb_esp_transport_list_add(wb_esp_transport_list_handle_t h, wb_esp_transport_handle_t t, const char *scheme)
+{
+    if (h == NULL || t == NULL) {
+        return ESP_ERR_INVALID_ARG;
+    }
+    t->scheme = calloc(1, strlen(scheme) + 1);
+    ESP_TRANSPORT_MEM_CHECK(t->scheme, return ESP_ERR_NO_MEM);
+    strcpy(t->scheme, scheme);
+    STAILQ_INSERT_TAIL(&h->list, t, next);
+    // Each transport in a list to share the same error tracker
+    t->error_handle = h->error_handle;
+    return ESP_OK;
+}
+
+wb_esp_transport_handle_t wb_esp_transport_list_get_transport(wb_esp_transport_list_handle_t h, const char *scheme)
+{
+    if (!h) {
+        return NULL;
+    }
+    if (scheme == NULL) {
+        return STAILQ_FIRST(&h->list);
+    }
+    wb_esp_transport_handle_t item;
+    STAILQ_FOREACH(item, &h->list, next) {
+        if (strcasecmp(item->scheme, scheme) == 0) {
+            return item;
+        }
+    }
+    return NULL;
+}
+
+esp_err_t wb_esp_transport_list_destroy(wb_esp_transport_list_handle_t h)
+{
+     wb_esp_transport_list_clean(h);
+    free(h->error_handle);
+    free(h);
+    return ESP_OK;
+}
+
+esp_err_t wb_esp_transport_list_clean(wb_esp_transport_list_handle_t h)
+{
+    wb_esp_transport_handle_t item = STAILQ_FIRST(&h->list);
+    wb_esp_transport_handle_t tmp;
+    while (item != NULL) {
+        tmp = STAILQ_NEXT(item, next);
+         wb_esp_transport_destroy(item);
+        item = tmp;
+    }
+    STAILQ_INIT(&h->list);
+    return ESP_OK;
+}
+
+wb_esp_transport_handle_t wb_esp_transport_init()
+{
+    wb_esp_transport_handle_t t = calloc(1, sizeof(struct wb_esp_transport_item_t));
+    ESP_TRANSPORT_MEM_CHECK(t, return NULL);
+    return t;
+}
+
+wb_esp_transport_handle_t wb_esp_transport_get_payload_transport_handle(wb_esp_transport_handle_t t)
+{
+    if (t && t->_read) {
+        return t->_parent_transfer(t);
+    }
+    return NULL;
+}
+
+esp_err_t wb_esp_transport_destroy(wb_esp_transport_handle_t t)
+{
+    if (t->_destroy) {
+        t->_destroy(t);
+    }
+    if (t->scheme) {
+        free(t->scheme);
+    }
+    free(t);
+    return ESP_OK;
+}
+
+int wb_esp_transport_connect(wb_esp_transport_handle_t t, const char *host, int port, int timeout_ms)
+{
+    int ret = -1;
+    if (t && t->_connect) {
+        return t->_connect(t, host, port, timeout_ms);
+    }
+    return ret;
+}
+
+int wb_esp_transport_connect_async(wb_esp_transport_handle_t t, const char *host, int port, int timeout_ms)
+{
+    int ret = -1;
+    if (t && t->_connect_async) {
+        return t->_connect_async(t, host, port, timeout_ms);
+    }
+    return ret;
+}
+
+int wb_esp_transport_read(wb_esp_transport_handle_t t, char *buffer, int len, int timeout_ms)
+{
+    if (t && t->_read) {
+        return t->_read(t, buffer, len, timeout_ms);
+    }
+    return -1;
+}
+
+int wb_esp_transport_write(wb_esp_transport_handle_t t, const char *buffer, int len, int timeout_ms)
+{
+    if (t && t->_write) {
+        return t->_write(t, buffer, len, timeout_ms);
+    }
+    return -1;
+}
+
+int wb_esp_transport_poll_read(wb_esp_transport_handle_t t, int timeout_ms)
+{
+    if (t && t->_poll_read) {
+        return t->_poll_read(t, timeout_ms);
+    }
+    return -1;
+}
+
+int wb_esp_transport_poll_write(wb_esp_transport_handle_t t, int timeout_ms)
+{
+    if (t && t->_poll_write) {
+        return t->_poll_write(t, timeout_ms);
+    }
+    return -1;
+}
+
+int wb_esp_transport_close(wb_esp_transport_handle_t t)
+{
+    if (t && t->_close) {
+        return t->_close(t);
+    }
+    return 0;
+}
+
+void *wb_esp_transport_get_context_data(wb_esp_transport_handle_t t)
+{
+    if (t) {
+        return t->data;
+    }
+    return NULL;
+}
+
+esp_err_t wb_esp_transport_set_context_data(wb_esp_transport_handle_t t, void *data)
+{
+    if (t) {
+        t->data = data;
+        return ESP_OK;
+    }
+    return ESP_FAIL;
+}
+
+esp_err_t wb_esp_transport_set_func(wb_esp_transport_handle_t t,
+                             wb_connect_func _connect,
+                             wb_io_read_func _read,
+                             wb_io_func _write,
+                             wb_trans_func _close,
+                             wb_poll_func _poll_read,
+                             wb_poll_func _poll_write,
+                             wb_trans_func _destroy)
+{
+    if (t == NULL) {
+        return ESP_FAIL;
+    }
+    t->_connect = _connect;
+    t->_read = _read;
+    t->_write = _write;
+    t->_close = _close;
+    t->_poll_read = _poll_read;
+    t->_poll_write = _poll_write;
+    t->_destroy = _destroy;
+    t->_connect_async = NULL;
+    t->_parent_transfer = wb_esp_transport_get_default_parent;
+    return ESP_OK;
+}
+
+int wb_esp_transport_get_default_port(wb_esp_transport_handle_t t)
+{
+    if (t == NULL) {
+        return -1;
+    }
+    return t->port;
+}
+
+esp_err_t wb_esp_transport_set_default_port(wb_esp_transport_handle_t t, int port)
+{
+    if (t == NULL) {
+        return ESP_FAIL;
+    }
+    t->port = port;
+    return ESP_OK;
+}
+
+esp_err_t wb_esp_transport_set_async_connect_func(wb_esp_transport_handle_t t, wb_connect_async_func _connect_async_func)
+{
+    if (t == NULL) {
+        return ESP_FAIL;
+    }
+    t->_connect_async = _connect_async_func;
+    return ESP_OK;
+}
+
+esp_err_t wb_esp_transport_set_parent_transport_func(wb_esp_transport_handle_t t, wb_payload_transfer_func _parent_transport)
+{
+    if (t == NULL) {
+        return ESP_FAIL;
+    }
+    t->_parent_transfer = _parent_transport;
+    return ESP_OK;
+}
+
+wb_esp_tls_error_handle_t wb_esp_transport_get_error_handle(wb_esp_transport_handle_t t)
+{
+    if (t) {
+        return t->error_handle;
+    }
+    return NULL;
+}
+
+void wb_esp_transport_set_errors(wb_esp_transport_handle_t t, const wb_esp_tls_error_handle_t error_handle)
+{
+    if (t)  {
+        memcpy(t->error_handle, error_handle, sizeof(esp_tls_last_error_t));
+    }
+}
+
+int wb_esp_transport_get_socket(wb_esp_transport_handle_t t)
+{
+    if (t && t->_get_socket)  {
+        return  t->_get_socket(t);
+    }
+    return -1;
+}
+
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/web_transport_ssl.c b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/web_transport_ssl.c
new file mode 100644 (file)
index 0000000..9abdb4f
--- /dev/null
@@ -0,0 +1,236 @@
+#include <string.h>
+#include <stdlib.h>
+
+//#include "freertos/FreeRTOS.h"
+//#include "freertos/task.h"
+#include "sim_esp_tls.h"
+#include "esp_log.h"
+//#include "esp_system.h"
+
+#include "web_esp_transport.h"
+#include "web_esp_transport_ssl.h"
+//#include "web_esp_transport_utils.h"
+#include "web_esp_transport_ssl_internal.h"
+
+//static const char *TAG = "TRANS_SSL";
+
+extern int esp_tls_low_level_conn(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_t *tls);
+extern void wb_esp_transport_utils_ms_to_timeval(int timeout_ms, struct timeval *tv);
+
+#define ESP_TRANSPORT_MEM_CHECK(a, action) if (!(a)) {                                         \
+        ESP_LOGE("%s:%d (%s): %s", __FILE__, __LINE__, __FUNCTION__, "Memory exhausted");       \
+        action;                                                                                     \
+        }
+
+typedef enum {
+    TRANS_SSL_INIT = 0,
+    TRANS_SSL_CONNECTING,
+} transport_ssl_conn_state_t;
+
+/**
+ *  mbedtls specific transport data
+ */
+typedef struct {
+    esp_tls_t                *tls;
+    esp_tls_cfg_t            cfg;
+    bool                     ssl_initialized;
+    transport_ssl_conn_state_t conn_state;
+} transport_ssl_t;
+
+static int ssl_close(wb_esp_transport_handle_t t);
+
+static int ssl_connect_async(wb_esp_transport_handle_t t, const char *host, int port, int timeout_ms)
+{
+    transport_ssl_t *ssl = wb_esp_transport_get_context_data(t);
+    if (ssl->conn_state == TRANS_SSL_INIT) {
+        ssl->cfg.timeout_ms = timeout_ms;
+        ssl->cfg.non_block = true;
+        ssl->ssl_initialized = true;
+        ssl->tls = sim_esp_tls_init();
+        if (!ssl->tls) {
+            return -1;
+        }
+        ssl->conn_state = TRANS_SSL_CONNECTING;
+    }
+    if (ssl->conn_state == TRANS_SSL_CONNECTING) {
+        return sim_esp_tls_conn_new_async(host, strlen(host), port, &ssl->cfg, ssl->tls);
+    }
+    return 0;
+}
+
+static int ssl_connect(wb_esp_transport_handle_t t, const char *host, int port, int timeout_ms)
+{
+    transport_ssl_t *ssl = wb_esp_transport_get_context_data(t);
+
+    ssl->cfg.timeout_ms = timeout_ms;
+    ssl->ssl_initialized = true;
+    ssl->tls = sim_esp_tls_init();
+    if (esp_tls_low_level_conn(host, strlen(host), port, &ssl->cfg, ssl->tls) <= 0) {
+        ESP_LOGE("Failed to open a new connection");
+        wb_esp_transport_set_errors(t, ssl->tls->error_handle);
+        sim_esp_tls_conn_delete(ssl->tls);
+        ssl->tls = NULL;
+        return -1;
+    }
+
+    return 0;
+}
+
+static int ssl_poll_read(wb_esp_transport_handle_t t, int timeout_ms)
+{
+    transport_ssl_t *ssl = wb_esp_transport_get_context_data(t);
+    int ret = -1;
+    fd_set readset;
+    fd_set errset;
+    FD_ZERO(&readset);
+    FD_ZERO(&errset);
+    FD_SET(ssl->tls->sockfd, &readset);
+    FD_SET(ssl->tls->sockfd, &errset);
+    struct timeval timeout;
+    wb_esp_transport_utils_ms_to_timeval(timeout_ms, &timeout);
+
+    ret = select(ssl->tls->sockfd + 1, &readset, NULL, &errset, &timeout);
+    if (ret > 0 && FD_ISSET(ssl->tls->sockfd, &errset)) {
+        int sock_errno = 0;
+        socklen_t optlen = sizeof(sock_errno);
+        getsockopt(ssl->tls->sockfd, SOL_SOCKET, SO_ERROR, &sock_errno, &optlen);
+        ESP_LOGE("ssl_poll_read select error %d, errno = %s, fd = %d", sock_errno, strerror(sock_errno), ssl->tls->sockfd);
+        ret = -1;
+    }
+    return ret;
+}
+
+static int ssl_poll_write(wb_esp_transport_handle_t t, int timeout_ms)
+{
+    transport_ssl_t *ssl = wb_esp_transport_get_context_data(t);
+    int ret = -1;
+    fd_set writeset;
+    fd_set errset;
+    FD_ZERO(&writeset);
+    FD_ZERO(&errset);
+    FD_SET(ssl->tls->sockfd, &writeset);
+    FD_SET(ssl->tls->sockfd, &errset);
+    struct timeval timeout;
+    wb_esp_transport_utils_ms_to_timeval(timeout_ms, &timeout);
+    ret = select(ssl->tls->sockfd + 1, NULL, &writeset, &errset, &timeout);
+    if (ret > 0 && FD_ISSET(ssl->tls->sockfd, &errset)) {
+        int sock_errno = 0;
+        socklen_t optlen = sizeof(sock_errno);
+        getsockopt(ssl->tls->sockfd, SOL_SOCKET, SO_ERROR, &sock_errno, &optlen);
+        ESP_LOGE("ssl_poll_write select error %d, errno = %s, fd = %d", sock_errno, strerror(sock_errno), ssl->tls->sockfd);
+        ret = -1;
+    }
+    return ret;
+}
+
+static int ssl_write(wb_esp_transport_handle_t t, const char *buffer, int len, int timeout_ms)
+{
+    int poll, ret;
+    transport_ssl_t *ssl = wb_esp_transport_get_context_data(t);
+
+    if ((poll = wb_esp_transport_poll_write(t, timeout_ms)) <= 0) {
+        ESP_LOGW("Poll timeout or error, errno=%s, fd=%d, timeout_ms=%d", strerror(errno), ssl->tls->sockfd, timeout_ms);
+        return poll;
+    }
+    ret = sim_esp_tls_conn_write(ssl->tls, (const unsigned char *) buffer, len);
+    if (ret < 0) {
+        ESP_LOGE("sim_esp_tls_conn_write error, errno=%s", strerror(errno));
+        wb_esp_transport_set_errors(t, ssl->tls->error_handle);
+    }
+    return ret;
+}
+
+static int ssl_read(wb_esp_transport_handle_t t, char *buffer, int len, int timeout_ms)
+{
+    int poll, ret;
+    transport_ssl_t *ssl = wb_esp_transport_get_context_data(t);
+
+    if (sim_esp_tls_get_bytes_avail(ssl->tls) <= 0) {
+        if ((poll = wb_esp_transport_poll_read(t, timeout_ms)) <= 0) {
+            return poll;
+        }
+    }
+    ret = sim_esp_tls_conn_read(ssl->tls, (unsigned char *)buffer, len);
+    if (ret < 0) {
+        ESP_LOGE("sim_esp_tls_conn_read error, errno=%s", strerror(errno));
+        wb_esp_transport_set_errors(t, ssl->tls->error_handle);
+    }
+    if (ret == 0) {
+        ret = -1;
+    }
+    return ret;
+}
+
+static int ssl_close(wb_esp_transport_handle_t t)
+{
+    int ret = -1;
+    transport_ssl_t *ssl = wb_esp_transport_get_context_data(t);
+    if (ssl->ssl_initialized) {
+        sim_esp_tls_conn_delete(ssl->tls);
+        ssl->ssl_initialized = false;
+    }
+    return ret;
+}
+
+static int ssl_destroy(wb_esp_transport_handle_t t)
+{
+    transport_ssl_t *ssl = wb_esp_transport_get_context_data(t);
+    wb_esp_transport_close(t);
+    free(ssl);
+    return 0;
+}
+
+void wb_esp_transport_ssl_enable_global_ca_store(wb_esp_transport_handle_t t)
+{
+    transport_ssl_t *ssl = wb_esp_transport_get_context_data(t);
+    if (t && ssl) {
+        ssl->cfg.use_global_ca_store = true;
+    }
+}
+
+void wb_esp_transport_ssl_set_cert_data(wb_esp_transport_handle_t t, const char *data, int len)
+{
+    transport_ssl_t *ssl = wb_esp_transport_get_context_data(t);
+    if (t && ssl) {
+        ssl->cfg.cacert_pem_buf = (void *)data;
+        ssl->cfg.cacert_pem_bytes = len + 1;
+    }
+}
+
+void wb_esp_transport_ssl_set_client_cert_data(wb_esp_transport_handle_t t, const char *data, int len)
+{
+    transport_ssl_t *ssl = wb_esp_transport_get_context_data(t);
+    if (t && ssl) {
+        ssl->cfg.clientcert_pem_buf = (void *)data;
+        ssl->cfg.clientcert_pem_bytes = len + 1;
+    }
+}
+
+void wb_esp_transport_ssl_set_client_key_data(wb_esp_transport_handle_t t, const char *data, int len)
+{
+    transport_ssl_t *ssl = wb_esp_transport_get_context_data(t);
+    if (t && ssl) {
+        ssl->cfg.clientkey_pem_buf = (void *)data;
+        ssl->cfg.clientkey_pem_bytes = len + 1;
+    }
+}
+
+void wb_esp_transport_ssl_skip_common_name_check(wb_esp_transport_handle_t t)
+{
+    transport_ssl_t *ssl = wb_esp_transport_get_context_data(t);
+    if (t && ssl) {
+        ssl->cfg.skip_common_name = true;
+    }
+}
+
+wb_esp_transport_handle_t wb_esp_transport_ssl_init()
+{
+    wb_esp_transport_handle_t t = wb_esp_transport_init();
+    transport_ssl_t *ssl = calloc(1, sizeof(transport_ssl_t));
+    ESP_TRANSPORT_MEM_CHECK(ssl, return NULL);
+    wb_esp_transport_set_context_data(t, ssl);
+    wb_esp_transport_set_func(t, ssl_connect, ssl_read, ssl_write, ssl_close, ssl_poll_read, ssl_poll_write, ssl_destroy);
+    wb_esp_transport_set_async_connect_func(t, ssl_connect_async);
+    return t;
+}
+
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/web_transport_tcp.c b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/web_transport_tcp.c
new file mode 100644 (file)
index 0000000..2171e41
--- /dev/null
@@ -0,0 +1,219 @@
+// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "sockets.h"
+#include "dns.h"
+#include "netdb.h"
+
+#include "esp_log.h"
+//#include "esp_system.h"
+#include "esp_err.h"
+
+//#include "web_esp_transport_utils.h"
+#include "web_esp_transport.h"
+
+//static const char *TAG = "TRANS_TCP";
+#define bzero(a,b)          memset(a, 0, b)
+#define ESP_TRANSPORT_MEM_CHECK(a, action) if (!(a)) {                                         \
+        ESP_LOGE("%s:%d (%s): %s", __FILE__, __LINE__, __FUNCTION__, "Memory exhausted");       \
+        action;                                                                                     \
+        }
+
+typedef struct {
+    int sock;
+} transport_tcp_t;
+
+void wb_esp_transport_utils_ms_to_timeval(int timeout_ms, struct timeval *tv)
+{
+    tv->tv_sec = timeout_ms / 1000;
+    tv->tv_usec = (timeout_ms - (tv->tv_sec * 1000)) * 1000;
+}
+
+static int resolve_dns(const char *host, struct sockaddr_in *ip) {
+
+    struct hostent *he;
+    struct in_addr **addr_list;
+    he = gethostbyname(host);
+    if (he == NULL) {
+        return ESP_FAIL;
+    }
+    addr_list = (struct in_addr **)he->h_addr_list;
+    if (addr_list[0] == NULL) {
+        return ESP_FAIL;
+    }
+    ip->sin_family = AF_INET;
+    memcpy(&ip->sin_addr, addr_list[0], sizeof(ip->sin_addr));
+    return ESP_OK;
+}
+
+static int tcp_connect(wb_esp_transport_handle_t t, const char *host, int port, int timeout_ms)
+{
+    struct sockaddr_in remote_ip;
+    struct timeval tv;
+    transport_tcp_t *tcp = wb_esp_transport_get_context_data(t);
+
+    bzero(&remote_ip, sizeof(struct sockaddr_in));
+
+    //if stream_host is not ip address, resolve it AF_INET,servername,&serveraddr.sin_addr
+    if (inet_pton(AF_INET, host, &remote_ip.sin_addr) != 1) {
+        if (resolve_dns(host, &remote_ip) < 0) {
+            return -1;
+        }
+    }
+
+    tcp->sock = socket(PF_INET, SOCK_STREAM, 0);
+
+    if (tcp->sock < 0) {
+        ESP_LOGE("Error create socket");
+        return -1;
+    }
+
+    remote_ip.sin_family = AF_INET;
+    remote_ip.sin_port = htons(port);
+
+    wb_esp_transport_utils_ms_to_timeval(timeout_ms, &tv);
+
+    setsockopt(tcp->sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
+    setsockopt(tcp->sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
+
+    ESP_LOGD("[sock=%d],connecting to server IP:%s,Port:%d...",
+             tcp->sock, ipaddr_ntoa((const ip_addr_t*)&remote_ip.sin_addr.s_addr), port);
+    if (connect(tcp->sock, (struct sockaddr *)(&remote_ip), sizeof(struct sockaddr)) != 0) {
+        close(tcp->sock);
+        tcp->sock = -1;
+        return -1;
+    }
+    return tcp->sock;
+}
+
+static int tcp_write(wb_esp_transport_handle_t t, const char *buffer, int len, int timeout_ms)
+{
+    int poll;
+    transport_tcp_t *tcp = wb_esp_transport_get_context_data(t);
+    if ((poll = wb_esp_transport_poll_write(t, timeout_ms)) <= 0) {
+               //ESP_LOGD("%s, poll write success and poll is %d", __FUNCTION__, poll);
+        return poll;
+    }
+       //ESP_LOGD("%s, poll write failed and use write to send buffer", __FUNCTION__);
+    return write(tcp->sock, buffer, len);
+}
+
+static int tcp_read(wb_esp_transport_handle_t t, char *buffer, int len, int timeout_ms)
+{
+    transport_tcp_t *tcp = wb_esp_transport_get_context_data(t);
+    int poll = -1;
+    if ((poll = wb_esp_transport_poll_read(t, timeout_ms)) <= 0) {
+               //ESP_LOGD("%s, poll read success and poll is %d", __FUNCTION__, poll);
+        return poll;
+    }
+    int read_len = read(tcp->sock, buffer, len);
+    if (read_len == 0) {
+        return -1;
+    }
+       //ESP_LOGD("%s, poll read failed and use read to recv buffer", __FUNCTION__);
+    return read_len;
+}
+
+static int tcp_poll_read(wb_esp_transport_handle_t t, int timeout_ms)
+{
+    transport_tcp_t *tcp = wb_esp_transport_get_context_data(t);
+    int ret = -1;
+    fd_set readset;
+    fd_set errset;
+    FD_ZERO(&readset);
+    FD_ZERO(&errset);
+    FD_SET(tcp->sock, &readset);
+    FD_SET(tcp->sock, &errset);
+    struct timeval timeout;
+    wb_esp_transport_utils_ms_to_timeval(timeout_ms, &timeout);
+    ret = select(tcp->sock + 1, &readset, NULL, &errset, &timeout);
+    if (ret > 0 && FD_ISSET(tcp->sock, &errset)) {
+        int sock_errno = 0;
+        socklen_t optlen = sizeof(sock_errno);
+        getsockopt(tcp->sock, SOL_SOCKET, SO_ERROR, &sock_errno, &optlen);
+        ESP_LOGE("tcp_poll_read select error %d, errno = %s, fd = %d", sock_errno, strerror(sock_errno), tcp->sock);
+        ret = -1;
+    }
+    return ret;
+}
+
+static int tcp_poll_write(wb_esp_transport_handle_t t, int timeout_ms)
+{
+    transport_tcp_t *tcp = wb_esp_transport_get_context_data(t);
+    int ret = -1;
+    fd_set writeset;
+    fd_set errset;
+    FD_ZERO(&writeset);
+    FD_ZERO(&errset);
+    FD_SET(tcp->sock, &writeset);
+    FD_SET(tcp->sock, &errset);
+    struct timeval timeout;
+    wb_esp_transport_utils_ms_to_timeval(timeout_ms, &timeout);
+    ret = select(tcp->sock + 1, NULL, &writeset, &errset, &timeout);
+    if (ret > 0 && FD_ISSET(tcp->sock, &errset)) {
+        int sock_errno = 0;
+        socklen_t optlen = sizeof(sock_errno);
+        getsockopt(tcp->sock, SOL_SOCKET, SO_ERROR, &sock_errno, &optlen);
+        ESP_LOGE("tcp_poll_write select error %d, errno = %s, fd = %d", sock_errno, strerror(sock_errno), tcp->sock);
+        ret = -1;
+    }
+       ESP_LOGD("%s, ret is %d", __FUNCTION__, ret);
+    return ret;
+}
+
+static int tcp_close(wb_esp_transport_handle_t t)
+{
+    transport_tcp_t *tcp = wb_esp_transport_get_context_data(t);
+    int ret = -1;
+    if (tcp->sock >= 0) {
+        ret = close(tcp->sock);
+        tcp->sock = -1;
+    }
+    return ret;
+}
+
+static esp_err_t tcp_destroy(wb_esp_transport_handle_t t)
+{
+    transport_tcp_t *tcp = wb_esp_transport_get_context_data(t);
+    wb_esp_transport_close(t);
+    free(tcp);
+    return 0;
+}
+
+static int tcp_get_socket(wb_esp_transport_handle_t t)
+{
+    if (t) {
+        transport_tcp_t *tcp = t->data;
+        if (tcp) {
+            return tcp->sock;
+        }
+    }
+    return -1;
+}
+
+wb_esp_transport_handle_t wb_esp_transport_tcp_init()
+{
+    wb_esp_transport_handle_t t = wb_esp_transport_init();
+    transport_tcp_t *tcp = calloc(1, sizeof(transport_tcp_t));
+    ESP_TRANSPORT_MEM_CHECK(tcp, return NULL);
+    tcp->sock = -1;
+    wb_esp_transport_set_func(t, tcp_connect, tcp_read, tcp_write, tcp_close, tcp_poll_read, tcp_poll_write, tcp_destroy);
+    wb_esp_transport_set_context_data(t, tcp);
+    t->_get_socket = tcp_get_socket;
+
+    return t;
+}
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/web_transport_ws.c b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/common/web_transport_ws.c
new file mode 100644 (file)
index 0000000..7becf04
--- /dev/null
@@ -0,0 +1,580 @@
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include <random.h>
+
+#include "esp_log.h"
+#include "web_esp_transport.h"
+#include "web_esp_transport_tcp.h"
+#include "web_esp_transport_ws.h"
+//#include "web_esp_transport_utils.h"
+//#include "transport_strcasestr.h"
+//#ifndef MBEDTLS_CONFIG_FILE 
+//#define MBEDTLS_CONFIG_FILE
+//#endif
+#include "base64.h"
+#include "sha1.h"
+#include "sockets.h"
+#include "arch.h"
+//#include "compat-2.x.h"
+
+//static const char *TAG = "TRANSPORT_WS";
+
+#define DEFAULT_WS_BUFFER (2048)
+#define WS_FIN            0x80
+#define WS_OPCODE_TEXT    0x01
+#define WS_OPCODE_BINARY  0x02
+#define WS_OPCODE_CLOSE   0x08
+#define WS_OPCODE_PING    0x09
+#define WS_OPCODE_PONG    0x0a
+// Second byte
+#define WS_MASK           0x80
+#define WS_SIZE16         126
+#define WS_SIZE64         127
+#define MAX_WEBSOCKET_HEADER_SIZE 16
+#define WS_RESPONSE_OK    101
+#define ESP_TRANSPORT_MEM_CHECK(a, action) if (!(a)) {                                         \
+        ESP_LOGE("%s:%d (%s): %s", __FILE__, __LINE__, __FUNCTION__, "Memory exhausted");       \
+        action;                                                                                     \
+        }
+
+extern char* strdup(const char* str);
+extern char* strcasestr(const char* haystack,const char* needle);
+extern int   wb_getrandom(void *buf, size_t buflen, unsigned int flags);
+extern int wb_esp_transport_get_socket(wb_esp_transport_handle_t t);
+
+typedef struct {
+    uint8_t opcode;
+    char mask_key[4];                   /*!< Mask key for this payload */
+    int payload_len;                    /*!< Total length of the payload */
+    int bytes_remaining;                /*!< Bytes left to read of the payload  */
+} ws_transport_frame_state_t;
+
+typedef struct {
+    char *path;
+    char *buffer;
+    char *sub_protocol;
+    ws_transport_frame_state_t frame_state;
+    wb_esp_transport_handle_t parent;
+} transport_ws_t;
+
+static inline uint8_t ws_get_bin_opcode(ws_transport_opcodes_t opcode)
+{
+    return (uint8_t)opcode;
+}
+
+static wb_esp_transport_handle_t ws_get_payload_transport_handle(wb_esp_transport_handle_t t)
+{
+    transport_ws_t *ws = wb_esp_transport_get_context_data(t);
+
+    /* Reading parts of a frame directly will disrupt the WS internal frame state,
+        reset bytes_remaining to prepare for reading a new frame */
+    ws->frame_state.bytes_remaining = 0;
+
+    return ws->parent;
+}
+
+static char *trimwhitespace(const char *str)
+{
+    char *end;
+
+    // Trim leading space
+    while (isspace((unsigned char)*str)) str++;
+
+    if (*str == 0) {
+        return (char *)str;
+    }
+
+    // Trim trailing space
+    end = (char *)(str + strlen(str) - 1);
+    while (end > str && isspace((unsigned char)*end)) end--;
+
+    // Write new null terminator
+    *(end + 1) = 0;
+
+    return (char *)str;
+}
+
+static char *get_http_header(const char *buffer, const char *key)
+{
+    char *found = strcasestr(buffer, key);
+    if (found) {
+        found += strlen(key);
+        char *found_end = strstr(found, "\r\n");
+        if (found_end) {
+            found_end[0] = 0;//terminal string
+
+            return trimwhitespace(found);
+        }
+    }
+    return NULL;
+}
+
+static int ws_connect(wb_esp_transport_handle_t t, const char *host, int port, int timeout_ms)
+{
+    transport_ws_t *ws = wb_esp_transport_get_context_data(t);
+    if (wb_esp_transport_connect(ws->parent, host, port, timeout_ms) < 0) {
+        ESP_LOGE("Error connecting to host %s:%d", host, port);
+        return -1;
+    }
+
+    unsigned char random_key[16];
+    wb_getrandom(random_key, sizeof(random_key), 0);
+       //ESP_LOGE("random_key: %s", random_key);
+
+    // Size of base64 coded string is equal '((input_size * 4) / 3) + (input_size / 96) + 6' including Z-term
+    unsigned char client_key[28] = {0};
+
+    size_t outlen = 0;
+    mbedtls_base64_encode(client_key, sizeof(client_key), &outlen, random_key, sizeof(random_key));
+    int len = snprintf(ws->buffer, DEFAULT_WS_BUFFER,
+                         /*"GET /?encoding=text HTTP/1.1\r\n"*/
+                                                "GET %s HTTP/1.1\r\n"
+                                        "Host: %s:%d\r\n"
+                         "Connection: Upgrade\r\n"
+                         "Pragma: no-cache\r\n"
+                         "Cache-Control: no-cache\r\n"
+                                                "User-Agent: ASR Websocket Client\r\n"
+                         "Upgrade: websocket\r\n"
+                         "Origin: http://oktools.net\r\n"
+                         "Sec-WebSocket-Version: 13\r\n"
+                         "Accept-Encoding: gzip, deflate\r\n"
+                         "Accept-Language: zh-CN,zh;q=0.9\r\n"
+                         "Sec-WebSocket-Key: %s\r\n"
+                         "Sec-Websocket-Extensions: permessage-deflate; client_max_window_bits\r\n",
+                         //"\r\n",
+                         ws->path,
+                         host, 
+                         port,
+                         client_key);
+    if (len <= 0 || len >= DEFAULT_WS_BUFFER) {
+        ESP_LOGE("Error in request generation, %d", len);
+        return -1;
+    }
+    if (ws->sub_protocol) {
+        int r = snprintf(ws->buffer + len, DEFAULT_WS_BUFFER - len, "Sec-WebSocket-Protocol: %s\r\n", ws->sub_protocol);
+        len += r;
+        if (r <= 0 || len >= DEFAULT_WS_BUFFER) {
+            ESP_LOGE("Error in request generation"
+                          "(snprintf of subprotocol returned %d, desired request len: %d, buffer size: %d", r, len, DEFAULT_WS_BUFFER);
+            return -1;
+        }
+    }
+    int r = snprintf(ws->buffer + len, DEFAULT_WS_BUFFER - len, "\r\n");
+    len += r;
+    if (r <= 0 || len >= DEFAULT_WS_BUFFER) {
+        ESP_LOGE("Error in request generation"
+                       "(snprintf of header terminal returned %d, desired request len: %d, buffer size: %d", r, len, DEFAULT_WS_BUFFER);
+        return -1;
+    }
+    ESP_LOGD("%s, len is %d and Write upgrate request\r\n%s", __FUNCTION__, len, ws->buffer);
+    if (wb_esp_transport_write(ws->parent, ws->buffer, len, timeout_ms) <= 0) {
+        ESP_LOGE("Error write Upgrade header %s", ws->buffer);
+        return -1;
+    }
+    int header_len = 0;
+    do {
+        if ((len = wb_esp_transport_read(ws->parent, ws->buffer + header_len, DEFAULT_WS_BUFFER - header_len, timeout_ms)) <= 0) {
+            ESP_LOGE("Error read response for Upgrade header %s", ws->buffer);
+            return -1;
+        }
+        header_len += len;
+        ws->buffer[header_len] = '\0';
+        ESP_LOGD("Read header chunk %d, current header size: %d", len, header_len);
+    } while (NULL == strstr(ws->buffer, "\r\n\r\n") && header_len < DEFAULT_WS_BUFFER);
+
+    char *server_key = get_http_header(ws->buffer, "Sec-WebSocket-Accept:");
+    if (server_key == NULL) {
+        ESP_LOGE("Sec-WebSocket-Accept not found");
+        return -1;
+    }
+
+    // See mbedtls_sha1_ret() arg size
+    unsigned char expected_server_sha1[20];
+    // Size of base64 coded string see above
+    unsigned char expected_server_key[33] = {0};
+    // If you are interested, see https://tools.ietf.org/html/rfc6455
+    const char expected_server_magic[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
+    unsigned char expected_server_text[sizeof(client_key) + sizeof(expected_server_magic) + 1];
+    strcpy((char*)expected_server_text, (char*)client_key);
+    strcat((char*)expected_server_text, expected_server_magic);
+
+    size_t key_len = strlen((char*)expected_server_text);
+    mbedtls_sha1_ret(expected_server_text, key_len, expected_server_sha1);
+    mbedtls_base64_encode(expected_server_key, sizeof(expected_server_key),  &outlen, expected_server_sha1, sizeof(expected_server_sha1));
+    expected_server_key[ (outlen < sizeof(expected_server_key)) ? outlen : (sizeof(expected_server_key) - 1) ] = 0;
+    ESP_LOGD("server key=%s, send_key=%s, expected_server_key=%s", (char *)server_key, (char*)client_key, expected_server_key);
+    if (strcmp((char*)expected_server_key, (char*)server_key) != 0) {
+        ESP_LOGE("Invalid websocket key");
+        return -1;
+    }
+    return 0;
+}
+
+static int _ws_write(wb_esp_transport_handle_t t, int opcode, int mask_flag, const char *b, int len, int timeout_ms)
+{
+    transport_ws_t *ws = wb_esp_transport_get_context_data(t);
+    char *buffer = (char *)b;
+    char ws_header[MAX_WEBSOCKET_HEADER_SIZE];
+    char *mask;
+    int header_len = 0, i;
+
+    int poll_write;
+    if ((poll_write = wb_esp_transport_poll_write(ws->parent, timeout_ms)) <= 0) {
+        ESP_LOGE("Error transport_poll_write");
+        return poll_write;
+    }
+    ws_header[header_len++] = opcode;
+
+    if (len <= 125) {
+        ws_header[header_len++] = (uint8_t)(len | mask_flag);
+    } else if (len < 65536) {
+        ws_header[header_len++] = WS_SIZE16 | mask_flag;
+        ws_header[header_len++] = (uint8_t)(len >> 8);
+        ws_header[header_len++] = (uint8_t)(len & 0xFF);
+    } else {
+        ws_header[header_len++] = WS_SIZE64 | mask_flag;
+        /* Support maximum 4 bytes length */
+        ws_header[header_len++] = 0; //(uint8_t)((len >> 56) & 0xFF);
+        ws_header[header_len++] = 0; //(uint8_t)((len >> 48) & 0xFF);
+        ws_header[header_len++] = 0; //(uint8_t)((len >> 40) & 0xFF);
+        ws_header[header_len++] = 0; //(uint8_t)((len >> 32) & 0xFF);
+        ws_header[header_len++] = (uint8_t)((len >> 24) & 0xFF);
+        ws_header[header_len++] = (uint8_t)((len >> 16) & 0xFF);
+        ws_header[header_len++] = (uint8_t)((len >> 8) & 0xFF);
+        ws_header[header_len++] = (uint8_t)((len >> 0) & 0xFF);
+    }
+
+    if (mask_flag) {
+        mask = &ws_header[header_len];
+        wb_getrandom(ws_header + header_len, 4, 0);
+        header_len += 4;
+
+        for (i = 0; i < len; ++i) {
+            buffer[i] = (buffer[i] ^ mask[i % 4]);
+        }
+    }
+
+    if (wb_esp_transport_write(ws->parent, ws_header, header_len, timeout_ms) != header_len) {
+        ESP_LOGE("Error write header");
+        return -1;
+    }
+    if (len == 0) {
+        return 0;
+    }
+
+    int ret = wb_esp_transport_write(ws->parent, buffer, len, timeout_ms);
+    // in case of masked transport we have to revert back to the original data, as ws layer
+    // does not create its own copy of data to be sent
+    if (mask_flag) {
+        mask = &ws_header[header_len-4];
+        for (i = 0; i < len; ++i) {
+            buffer[i] = (buffer[i] ^ mask[i % 4]);
+        }
+    }
+    return ret;
+}
+
+int wb_esp_transport_ws_send_raw(wb_esp_transport_handle_t t, ws_transport_opcodes_t opcode, const char *b, int len, int timeout_ms)
+{
+    uint8_t op_code = ws_get_bin_opcode(opcode);
+    if (t == NULL) {
+        ESP_LOGE("Transport must be a valid ws handle");
+        return ESP_ERR_INVALID_ARG;
+    }
+    ESP_LOGD("Sending raw ws message with opcode %d", op_code);
+    return _ws_write(t, op_code | WS_FIN, WS_MASK, b, len, timeout_ms);
+}
+
+static int ws_write(wb_esp_transport_handle_t t, const char *b, int len, int timeout_ms)
+{
+    if (len == 0) {
+        // Default transport write of zero length in ws layer sends out a ping message.
+        // This behaviour could however be altered in IDF 5.0, since a separate API for sending
+        // messages with user defined opcodes has been introduced.
+        ESP_LOGD("Write PING message");
+        return _ws_write(t, WS_OPCODE_PING | WS_FIN, WS_MASK, NULL, 0, timeout_ms);
+    }
+    return _ws_write(t, WS_OPCODE_BINARY | WS_FIN, WS_MASK, b, len, timeout_ms);
+}
+
+
+static int ws_read_payload(wb_esp_transport_handle_t t, char *buffer, int len, int timeout_ms)
+{
+       int i;
+    transport_ws_t *ws = wb_esp_transport_get_context_data(t);
+
+    int bytes_to_read;
+    int rlen = 0;
+
+    if (ws->frame_state.bytes_remaining > len) {
+        ESP_LOGD("Actual data to receive (%d) are longer than ws buffer (%d)", ws->frame_state.bytes_remaining, len);
+        bytes_to_read = len;
+
+    } else {
+        bytes_to_read = ws->frame_state.bytes_remaining;
+    }
+
+    // Receive and process payload
+    if (bytes_to_read != 0 && (rlen = wb_esp_transport_read(ws->parent, buffer, bytes_to_read, timeout_ms)) <= 0) {
+        ESP_LOGE("Error read data");
+        return rlen;
+    }
+    ws->frame_state.bytes_remaining -= rlen;
+
+    if (ws->frame_state.mask_key) {
+        for (i = 0; i < bytes_to_read; i++) {
+            buffer[i] = (buffer[i] ^ ws->frame_state.mask_key[i % 4]);
+        }
+    }
+    return rlen;
+}
+
+
+/* Read and parse the WS header, determine length of payload */
+static int ws_read_header(wb_esp_transport_handle_t t, char *buffer, int len, int timeout_ms)
+{
+    transport_ws_t *ws = wb_esp_transport_get_context_data(t);
+    int payload_len;
+
+    char ws_header[MAX_WEBSOCKET_HEADER_SIZE];
+    char *data_ptr = ws_header, mask;
+    int rlen;
+    int poll_read;
+    if ((poll_read = wb_esp_transport_poll_read(ws->parent, timeout_ms)) <= 0) {
+        return poll_read;
+    }
+
+    // Receive and process header first (based on header size)
+    int header = 2;
+    int mask_len = 4;
+    if ((rlen = wb_esp_transport_read(ws->parent, data_ptr, header, timeout_ms)) <= 0) {
+        ESP_LOGE("Error read data");
+        return rlen;
+    }
+    ws->frame_state.opcode = (*data_ptr & 0x0F);
+    data_ptr ++;
+    mask = ((*data_ptr >> 7) & 0x01);
+    payload_len = (*data_ptr & 0x7F);
+    data_ptr++;
+    ESP_LOGD("Opcode: %d, mask: %d, len: %d\r\n", ws->frame_state.opcode, mask, payload_len);
+    if (payload_len == 126) {
+        // headerLen += 2;
+        if ((rlen = wb_esp_transport_read(ws->parent, data_ptr, header, timeout_ms)) <= 0) {
+            ESP_LOGE("Error read data");
+            return rlen;
+        }
+        payload_len = data_ptr[0] << 8 | data_ptr[1];
+    } else if (payload_len == 127) {
+        // headerLen += 8;
+        header = 8;
+        if ((rlen = wb_esp_transport_read(ws->parent, data_ptr, header, timeout_ms)) <= 0) {
+            ESP_LOGE("Error read data");
+            return rlen;
+        }
+
+        if (data_ptr[0] != 0 || data_ptr[1] != 0 || data_ptr[2] != 0 || data_ptr[3] != 0) {
+            // really too big!
+            payload_len = 0xFFFFFFFF;
+        } else {
+            payload_len = data_ptr[4] << 24 | data_ptr[5] << 16 | data_ptr[6] << 8 | data_ptr[7];
+        }
+    }
+
+    if (mask) {
+        // Read and store mask
+        if (payload_len != 0 && (rlen = wb_esp_transport_read(ws->parent, buffer, mask_len, timeout_ms)) <= 0) {
+            ESP_LOGE("Error read data");
+            return rlen;
+        }
+        memcpy(ws->frame_state.mask_key, buffer, mask_len);
+    } else {
+        memset(ws->frame_state.mask_key, 0, mask_len);
+    }
+
+    ws->frame_state.payload_len = payload_len;
+    ws->frame_state.bytes_remaining = payload_len;
+
+    return payload_len;
+}
+
+static int ws_read(wb_esp_transport_handle_t t, char *buffer, int len, int timeout_ms)
+{
+    int rlen = 0;
+    transport_ws_t *ws = wb_esp_transport_get_context_data(t);
+
+    // If message exceeds buffer len then subsequent reads will skip reading header and read whatever is left of the payload
+    if (ws->frame_state.bytes_remaining <= 0) {
+        if ( (rlen = ws_read_header(t, buffer, len, timeout_ms)) <= 0) {
+            // If something when wrong then we prepare for reading a new header
+            ws->frame_state.bytes_remaining = 0;
+            return rlen;
+        }
+    }
+    if (ws->frame_state.payload_len) {
+        if ( (rlen = ws_read_payload(t, buffer, len, timeout_ms)) <= 0) {
+            ESP_LOGE("Error reading payload data");
+            ws->frame_state.bytes_remaining = 0;
+            return rlen;
+        }
+    }
+
+    return rlen;
+}
+
+static int ws_poll_read(wb_esp_transport_handle_t t, int timeout_ms)
+{
+    transport_ws_t *ws = wb_esp_transport_get_context_data(t);
+    return wb_esp_transport_poll_read(ws->parent, timeout_ms);
+}
+
+static int ws_poll_write(wb_esp_transport_handle_t t, int timeout_ms)
+{
+    transport_ws_t *ws = wb_esp_transport_get_context_data(t);
+    return wb_esp_transport_poll_write(ws->parent, timeout_ms);;
+}
+
+static int ws_close(wb_esp_transport_handle_t t)
+{
+    transport_ws_t *ws = wb_esp_transport_get_context_data(t);
+    return wb_esp_transport_close(ws->parent);
+}
+
+static esp_err_t ws_destroy(wb_esp_transport_handle_t t)
+{
+    transport_ws_t *ws = wb_esp_transport_get_context_data(t);
+       if (NULL != ws->buffer) {
+               free(ws->buffer);
+               ws->buffer = NULL;
+       }
+       if (NULL != ws->path) {
+               free(ws->path);
+               ws->path = NULL;
+       }
+       if (NULL != ws->sub_protocol) {
+               free(ws->sub_protocol);
+               ws->sub_protocol = NULL;
+       }
+    //free(ws->buffer);
+    //free(ws->path);
+    //free(ws->sub_protocol);
+    free(ws);
+    return 0;
+}
+void wb_esp_transport_ws_set_path(wb_esp_transport_handle_t t, const char *path)
+{
+    transport_ws_t *ws = wb_esp_transport_get_context_data(t);
+    ws->path = realloc(ws->path, strlen(path) + 1);
+    strcpy(ws->path, path);
+}
+
+int ws_get_socket(wb_esp_transport_handle_t t)
+{
+       transport_ws_t *ws = wb_esp_transport_get_context_data(t);
+ //   if (ws && ws->parent && ws->parent->_get_socket) {
+ //       return ws->parent->_get_socket(ws->parent);
+ //   }
+    return -1;
+}
+
+wb_esp_transport_handle_t wb_esp_transport_ws_init(wb_esp_transport_handle_t parent_handle)
+{
+    wb_esp_transport_handle_t t = wb_esp_transport_init();
+    transport_ws_t *ws = calloc(1, sizeof(transport_ws_t));
+    ESP_TRANSPORT_MEM_CHECK(ws, return NULL);
+    ws->parent = parent_handle;
+
+    ws->path = strdup("/");
+    ESP_TRANSPORT_MEM_CHECK(ws->path, {
+        free(ws);
+        return NULL;
+    });
+    ws->buffer = malloc(DEFAULT_WS_BUFFER);
+    ESP_TRANSPORT_MEM_CHECK(ws->buffer, {
+        free(ws->path);
+        free(ws);
+        return NULL;
+    });
+
+    wb_esp_transport_set_func(t, ws_connect, ws_read, ws_write, ws_close, ws_poll_read, ws_poll_write, ws_destroy);
+    // webocket underlying transfer is the payload transfer handle
+    wb_esp_transport_set_parent_transport_func(t, ws_get_payload_transport_handle);
+
+    wb_esp_transport_set_context_data(t, ws);
+ //   t->_get_socket = ws_get_socket;
+    return t;
+}
+
+esp_err_t wb_esp_transport_ws_set_subprotocol(wb_esp_transport_handle_t t, const char *sub_protocol)
+{
+    if (t == NULL) {
+        return ESP_ERR_INVALID_ARG;
+    }
+    transport_ws_t *ws = wb_esp_transport_get_context_data(t);
+    if (ws->sub_protocol) {
+        free(ws->sub_protocol);
+    }
+    if (sub_protocol == NULL) {
+        ws->sub_protocol = NULL;
+        return ESP_OK;
+    }
+    ws->sub_protocol = strdup(sub_protocol);
+    if (ws->sub_protocol == NULL) {
+        return ESP_ERR_NO_MEM;
+    }
+    return ESP_OK;
+}
+
+ws_transport_opcodes_t wb_esp_transport_ws_get_read_opcode(wb_esp_transport_handle_t t)
+{
+    transport_ws_t *ws = wb_esp_transport_get_context_data(t);
+    return ws->frame_state.opcode;
+}
+
+int wb_esp_transport_ws_get_read_payload_len(wb_esp_transport_handle_t t)
+{
+    transport_ws_t *ws = wb_esp_transport_get_context_data(t);
+    return ws->frame_state.payload_len;
+}
+
+int esp_transport_ws_poll_connection_closed(wb_esp_transport_handle_t t, int timeout_ms)
+{
+    struct timeval tv;
+    int sock = wb_esp_transport_get_socket(t);
+    fd_set readset;
+    fd_set errset;
+    FD_ZERO(&readset);
+    FD_ZERO(&errset);
+    FD_SET(sock, &readset);
+    FD_SET(sock, &errset);
+
+    tv.tv_sec = timeout_ms / 1000;
+    tv.tv_usec = (timeout_ms - (tv.tv_sec * 1000)) * 1000;
+
+    int ret = select(sock + 1, &readset, NULL, &errset, &tv);
+    if (ret > 0) {
+        if (FD_ISSET(sock, &readset)) {
+            uint8_t buffer;
+            if (recv(sock, &buffer, 1, MSG_PEEK) <= 0) {
+                // socket is readable, but reads zero bytes -- connection cleanly closed by FIN flag
+                return 1;
+            }
+            ESP_LOGW("esp_transport_ws_poll_connection_closed: unexpected data readable on socket=%d", sock);
+        } else if (FD_ISSET(sock, &errset)) {
+            int sock_errno = 0;
+            socklen_t optlen = sizeof(sock_errno);
+            getsockopt(sock, SOL_SOCKET, SO_ERROR, &sock_errno, &optlen);
+            ESP_LOGD("esp_transport_ws_poll_connection_closed select error %d, errno = %s, fd = %d", sock_errno, strerror(sock_errno), sock);
+            if (sock_errno == ENOTCONN || sock_errno == ECONNRESET || sock_errno == ECONNABORTED) {
+                // the three err codes above might be caused by connection termination by RTS flag
+                // which we still assume as expected closing sequence of ws-transport connection
+                return 1;
+            }
+            ESP_LOGE("esp_transport_ws_poll_connection_closed: unexpected errno=%d on socket=%d", sock_errno, sock);
+        }
+        return -1; // indicates error: socket unexpectedly reads an actual data, or unexpected errno code
+    }
+    return ret;
+
+}
+
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/sim_esp_websocket_client.c b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/sim_esp_websocket_client.c
new file mode 100644 (file)
index 0000000..c27a774
--- /dev/null
@@ -0,0 +1,826 @@
+// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include <stdio.h>
+
+#include "sim_esp_websocket_client.h"
+#include "web_esp_transport.h"
+#include "web_esp_transport_tcp.h"
+#include "web_esp_transport_ssl.h"
+#include "web_esp_transport_ws.h"
+
+/* using uri parser */
+#include "web_http_parser.h"
+#include "queue.h"
+#include "esp_log.h"
+#include "sockets.h"
+#include "osa.h"
+
+static int       task_run = 0;
+static OSTaskRef websocket_client_ref = NULL;
+static void *    websocket_client_stack_ptr = NULL;
+
+#define websocket_version                              "asr_websocket_v1.10_20210926"
+#define WEBSOCKET_TCP_DEFAULT_PORT      (80)
+#define WEBSOCKET_SSL_DEFAULT_PORT      (443)
+#define WEBSOCKET_BUFFER_SIZE_BYTE      (8*1024)
+#define WEBSOCKET_RECONNECT_TIMEOUT_MS  (5*60*1000)
+#define WEBSOCKET_TASK_PRIORITY         (90)
+#define WEBSOCKET_TASK_STACK            (8*1024)
+#define WEBSOCKET_NETWORK_TIMEOUT_MS    (10*1000)
+#define WEBSOCKET_PING_TIMEOUT_MS       (15*60*1000)
+#define WEBSOCKET_EVENT_QUEUE_SIZE      (1)
+
+#define ESP_WS_CLIENT_MEM_CHECK(a, action) if (!(a)) {                                         \
+        ESP_LOGE("%s:%d (%s): %s", __FILE__, __LINE__, __FUNCTION__, "Memory exhausted");       \
+        action;                                                                                     \
+        }
+#define ESP_EVENT_DECLARE_BASE(id) extern esp_event_base_t id
+#define ESP_EVENT_DEFINE_BASE(id) esp_event_base_t id = #id
+
+static int sim_esp_websocket_client_send_with_opcode(sim_esp_websocket_client_handle_t client, ws_transport_opcodes_t opcode, const char *data, int len, TickType_t timeout);
+static void asr_ws_loop_run_task(void *pv);
+extern OSMsgQRef asr_ws_msgQ_ref;
+extern int esp_transport_ws_poll_connection_closed(wb_esp_transport_handle_t t, int timeout_ms);
+
+static UINT32 _tick_get_ms(void)
+{
+       return (5*OSAGetTicks());       //get ms
+    //return esp_timer_get_time()/1000;
+}
+
+static int esp_websocket_client_dispatch_event(sim_esp_websocket_client_handle_t client,
+                                                     sim_esp_websocket_event_id_t event,
+                                                     const char *data,
+                                                     int data_len)
+{
+       if (client->handler) {
+               if (NULL == data) {
+                       client->handler(event, NULL);
+               } else {
+                       sim_esp_websocket_event_data_t *event_data = NULL;
+                       event_data = malloc(sizeof(sim_esp_websocket_event_data_t));
+                       if (NULL == event_data) {
+                               ESP_LOGE("%s, event_data malloc failed", __FUNCTION__);
+                               return -1;
+                       } else {
+                               memset(event_data, '\0', sizeof(sim_esp_websocket_event_data_t));
+                               event_data->data_ptr = malloc(data_len);
+                               if (event_data->data_ptr) {
+                                       memset(event_data->data_ptr, 0, data_len);
+                                       memcpy(event_data->data_ptr, data, data_len);
+                               }
+                       }
+
+                       event_data->data_len = data_len;
+               event_data->op_code  = client->last_opcode;
+            //shenxj+++
+            event_data->payload_len = client->payload_len;
+            event_data->payload_offset = client->payload_offset;
+            //shenxj---
+
+                       client->handler(event, event_data);
+               }
+       }
+
+       return 0;
+}
+
+static int esp_websocket_client_abort_connection(sim_esp_websocket_client_handle_t client)
+{
+       int ret = 0;
+       
+    wb_esp_transport_close(client->transport);
+    client->wait_timeout_ms = WEBSOCKET_RECONNECT_TIMEOUT_MS;
+    client->reconnect_tick_ms = _tick_get_ms();
+    client->state = WEBSOCKET_STATE_WAIT_TIMEOUT;
+    ESP_LOGI("Reconnect after %d ms", client->wait_timeout_ms);
+    ret = esp_websocket_client_dispatch_event(client, WEBSOCKET_EVENT_DISCONNECTED, NULL, 0);
+       ESP_LOGD("%s, client abort connection ret is %d", __FUNCTION__, ret);
+    return ret;
+}
+
+static esp_err_t esp_websocket_client_set_config(sim_esp_websocket_client_handle_t client, const sim_esp_websocket_client_config_t *config)
+{
+    sim_websocket_config_storage_t *cfg = client->config;
+    cfg->task_prio = config->task_prio;
+    if (cfg->task_prio <= 0) {
+        cfg->task_prio = WEBSOCKET_TASK_PRIORITY;
+    }
+
+    cfg->task_stack = config->task_stack;
+    if (cfg->task_stack == 0) {
+        cfg->task_stack = WEBSOCKET_TASK_STACK;
+    }
+
+    if (config->host) {
+        cfg->p_host = strdup(config->host);
+               memcpy(cfg->host, cfg->p_host, strlen(config->host));
+        ESP_WS_CLIENT_MEM_CHECK(cfg->host, return ESP_ERR_NO_MEM);
+    }
+
+    if (config->port) {
+        cfg->port = config->port;
+    }
+
+    if (config->username) {
+        //free(cfg->username);
+        cfg->username = strdup(config->username);
+        ESP_WS_CLIENT_MEM_CHECK(cfg->username, return ESP_ERR_NO_MEM);
+    }
+
+    if (config->password) {
+        //free(cfg->password);
+        cfg->password = strdup(config->password);
+        ESP_WS_CLIENT_MEM_CHECK(cfg->password, return ESP_ERR_NO_MEM);
+    }
+
+    if (config->uri) {
+        //free(cfg->uri);
+        cfg->uri = strdup(config->uri);
+        ESP_WS_CLIENT_MEM_CHECK(cfg->uri, return ESP_ERR_NO_MEM);
+    }
+    if (config->path) {
+        //free(cfg->path);
+        cfg->p_path = strdup(config->path);
+               memcpy(cfg->path, cfg->p_path, strlen(config->path));
+        ESP_WS_CLIENT_MEM_CHECK(cfg->path, return ESP_ERR_NO_MEM);
+    }
+    if (config->subprotocol) {
+        //free(cfg->subprotocol);
+        cfg->subprotocol = strdup(config->subprotocol);
+        ESP_WS_CLIENT_MEM_CHECK(cfg->subprotocol, return ESP_ERR_NO_MEM);
+    }
+
+    cfg->network_timeout_ms = WEBSOCKET_NETWORK_TIMEOUT_MS;
+    cfg->user_context = config->user_context;
+    cfg->auto_reconnect = true;
+    if (config->disable_auto_reconnect) {
+        cfg->auto_reconnect = false;
+    }
+
+
+    return ESP_OK;
+}
+
+static esp_err_t esp_websocket_client_destroy_config(sim_esp_websocket_client_handle_t client)
+{
+    if (client == NULL) {
+        return ESP_ERR_INVALID_ARG;
+    }
+    sim_websocket_config_storage_t *cfg = client->config;
+    if (client->config == NULL) {
+        return ESP_ERR_INVALID_ARG;
+    }
+       
+       if (NULL != cfg->p_host) {
+               free(cfg->p_host);
+               cfg->p_host = NULL;
+       }
+       if (NULL != cfg->uri) {
+               free(cfg->uri);
+               cfg->uri = NULL;
+       }
+       if (NULL != cfg->p_path) {
+               free(cfg->p_path);
+               cfg->p_path = NULL;
+       }
+       if (NULL != cfg->username) {
+               free(cfg->username);
+               cfg->username = NULL;
+       }
+       if (NULL != cfg->password) {
+               free(cfg->password);
+               cfg->password = NULL;
+       }
+       if (NULL != cfg->subprotocol) {
+               free(cfg->subprotocol);
+               cfg->subprotocol = NULL;
+       }
+
+    memset(cfg, 0, sizeof(sim_websocket_config_storage_t));
+    free(client->config);
+    client->config = NULL;
+    return ESP_OK;
+}
+
+static void set_websocket_transport_optional_settings(sim_esp_websocket_client_handle_t client, wb_esp_transport_handle_t trans)
+{
+    if (trans && client->config->path) {
+        wb_esp_transport_ws_set_path(trans, client->config->path);
+    }
+    if (trans && client->config->subprotocol) {
+        wb_esp_transport_ws_set_subprotocol(trans, client->config->subprotocol);
+    }
+}
+
+sim_esp_websocket_client_handle_t sim_esp_websocket_client_init(const sim_esp_websocket_client_config_t *config)
+{
+    wb_esp_transport_handle_t tcp = NULL;
+    wb_esp_transport_handle_t ws  = NULL;
+    wb_esp_transport_handle_t ssl = NULL;
+    wb_esp_transport_handle_t wss = NULL;
+    int buffer_size = 0;    
+       OS_STATUS status;
+       
+    sim_esp_websocket_client_handle_t client = (sim_esp_websocket_client_handle_t)malloc(1*sizeof(struct sim_esp_websocket_client));
+    ESP_WS_CLIENT_MEM_CHECK(client, return NULL);
+       memset(client, '\0', sizeof(struct sim_esp_websocket_client));
+       client->state = WEBSOCKET_STATE_UNKNOW;
+       
+       status = OSAMutexCreate(&client->lock, OSA_FIFO);
+       if (OS_SUCCESS != status) {
+               ESP_LOGE("Failed to create client lock");
+       }
+       
+    client->config = calloc(1, sizeof(sim_websocket_config_storage_t));
+    ESP_WS_CLIENT_MEM_CHECK(client->config, goto _websocket_init_fail);
+
+    client->transport_list = wb_esp_transport_list_init();
+    ESP_WS_CLIENT_MEM_CHECK(client->transport_list, goto _websocket_init_fail);
+
+    tcp = wb_esp_transport_tcp_init();
+    ESP_WS_CLIENT_MEM_CHECK(tcp, goto _websocket_init_fail);
+
+    wb_esp_transport_set_default_port(tcp, WEBSOCKET_TCP_DEFAULT_PORT);
+    wb_esp_transport_list_add(client->transport_list, tcp, "_tcp"); // need to save to transport list, for cleanup
+
+
+    ws = wb_esp_transport_ws_init(tcp);
+    ESP_WS_CLIENT_MEM_CHECK(ws, goto _websocket_init_fail);
+
+    wb_esp_transport_set_default_port(ws, WEBSOCKET_TCP_DEFAULT_PORT);
+    wb_esp_transport_list_add(client->transport_list, ws, "ws");
+    if (config->transport == WEBSOCKET_TRANSPORT_OVER_TCP) {
+        sprintf(client->config->scheme, "%s", "ws");
+        ESP_WS_CLIENT_MEM_CHECK(client->config->scheme, goto _websocket_init_fail);
+    }
+
+    ssl = wb_esp_transport_ssl_init();
+    ESP_WS_CLIENT_MEM_CHECK(ssl, goto _websocket_init_fail);
+
+    wb_esp_transport_set_default_port(ssl, WEBSOCKET_SSL_DEFAULT_PORT);
+    if (config->cert_pem) {
+        wb_esp_transport_ssl_set_cert_data(ssl, config->cert_pem, strlen(config->cert_pem));
+    }
+    wb_esp_transport_list_add(client->transport_list, ssl, "_ssl"); // need to save to transport list, for cleanup
+
+    wss = wb_esp_transport_ws_init(ssl);
+    ESP_WS_CLIENT_MEM_CHECK(wss, goto _websocket_init_fail);
+
+    wb_esp_transport_set_default_port(wss, WEBSOCKET_SSL_DEFAULT_PORT);
+
+    wb_esp_transport_list_add(client->transport_list, wss, "wss");
+    if (config->transport == WEBSOCKET_TRANSPORT_OVER_SSL) {
+        sprintf(client->config->scheme, "%s", "wss");
+        ESP_WS_CLIENT_MEM_CHECK(client->config->scheme, goto _websocket_init_fail);
+    }
+
+    if (config->uri) {
+        if (sim_esp_websocket_client_set_uri(client, config->uri) != ESP_OK) {
+            ESP_LOGE("Invalid uri");
+            goto _websocket_init_fail;
+        }
+    }
+
+    if (esp_websocket_client_set_config(client, config) != ESP_OK) {
+        ESP_LOGE("Failed to set the configuration");
+        goto _websocket_init_fail;
+    }
+
+    if (client->config->scheme == NULL) {
+        sprintf(client->config->scheme, "%s", "ws");
+        ESP_WS_CLIENT_MEM_CHECK(client->config->scheme, goto _websocket_init_fail);
+    }
+
+    set_websocket_transport_optional_settings(client, wb_esp_transport_list_get_transport(client->transport_list, "ws"));
+    set_websocket_transport_optional_settings(client, wb_esp_transport_list_get_transport(client->transport_list, "wss"));
+
+    client->keepalive_tick_ms = _tick_get_ms();
+    client->reconnect_tick_ms = _tick_get_ms();
+    client->ping_tick_ms = _tick_get_ms();
+
+    buffer_size = config->buffer_size;
+    if (buffer_size <= 0) {
+        buffer_size = WEBSOCKET_BUFFER_SIZE_BYTE;
+    }
+    client->rx_buffer = malloc(buffer_size);
+    ESP_WS_CLIENT_MEM_CHECK(client->rx_buffer, {
+        goto _websocket_init_fail;
+    });
+    client->tx_buffer = malloc(buffer_size);
+    ESP_WS_CLIENT_MEM_CHECK(client->tx_buffer, {
+        goto _websocket_init_fail;
+    });
+
+    client->buffer_size = buffer_size;
+    return client;
+
+_websocket_init_fail:
+    sim_esp_websocket_client_destroy(client);
+    return NULL;
+}
+
+esp_err_t sim_esp_websocket_client_destroy(sim_esp_websocket_client_handle_t client)
+{
+    if (client == NULL) {
+        return ESP_ERR_INVALID_ARG;
+    }
+    if (1 == task_run) {
+        sim_esp_websocket_client_stop(client);
+    }
+       
+       OSAMutexDelete(client->lock);
+
+    esp_websocket_client_destroy_config(client);
+               
+    wb_esp_transport_list_destroy(client->transport_list);
+       
+       if (NULL != client->tx_buffer) {
+               free(client->tx_buffer);
+               client->tx_buffer = NULL;
+       }
+       if (NULL != client->rx_buffer) {
+               free(client->rx_buffer);
+               client->rx_buffer = NULL;
+       }
+       if (NULL != client) {
+               free(client);
+               client = NULL;
+       }
+       
+    return ESP_OK;
+}
+
+esp_err_t sim_esp_websocket_client_set_uri(sim_esp_websocket_client_handle_t client, const char *uri)
+{
+    if (client == NULL || uri == NULL) {
+        return ESP_ERR_INVALID_ARG;
+    }
+    struct http_parser_url puri;
+    wb_http_parser_url_init(&puri);
+    int parser_status = wb_http_parser_parse_url(uri, strlen(uri), 0, &puri);
+    if (parser_status != 0) {
+        ESP_LOGE("Error parse uri = %s", uri);
+        return ESP_FAIL;
+    }
+    if (puri.field_data[UF_SCHEMA].len) {
+        //free(client->config->scheme);
+        sprintf(client->config->scheme, "%.*s", puri.field_data[UF_SCHEMA].len, uri + puri.field_data[UF_SCHEMA].off);
+        ESP_WS_CLIENT_MEM_CHECK(client->config->scheme, return ESP_ERR_NO_MEM);
+    }
+
+    if (puri.field_data[UF_HOST].len) {
+        //free(client->config->host);
+        sprintf(client->config->host, "%.*s", puri.field_data[UF_HOST].len, uri + puri.field_data[UF_HOST].off);
+        ESP_WS_CLIENT_MEM_CHECK(client->config->host, return ESP_ERR_NO_MEM);
+    }
+
+
+    if (puri.field_data[UF_PATH].len || puri.field_data[UF_QUERY].len) {
+        //free(client->config->path);
+        if (puri.field_data[UF_QUERY].len == 0) {
+            sprintf(client->config->path, "%.*s", puri.field_data[UF_PATH].len, uri + puri.field_data[UF_PATH].off);
+        } else if (puri.field_data[UF_PATH].len == 0)  {
+            sprintf(client->config->path, "/?%.*s", puri.field_data[UF_QUERY].len, uri + puri.field_data[UF_QUERY].off);
+        } else {
+            sprintf(client->config->path, "%.*s?%.*s", puri.field_data[UF_PATH].len, uri + puri.field_data[UF_PATH].off,
+                    puri.field_data[UF_QUERY].len, uri + puri.field_data[UF_QUERY].off);
+        }
+        ESP_WS_CLIENT_MEM_CHECK(client->config->path, return ESP_ERR_NO_MEM);
+    }
+    if (puri.field_data[UF_PORT].off) {
+        client->config->port = strtol((const char*)(uri + puri.field_data[UF_PORT].off), NULL, 10);
+    }
+
+    if (puri.field_data[UF_USERINFO].len) {
+        char user_info[1024];
+        memset(user_info, '\0', 1024);
+        sprintf(user_info, "%.*s", puri.field_data[UF_USERINFO].len, uri + puri.field_data[UF_USERINFO].off);
+        if (user_info) {
+            char *pass = strchr(user_info, ':');
+            if (pass) {
+                pass[0] = 0; //terminal username
+                pass ++;
+                //free(client->config->password);
+                client->config->password = strdup(pass);
+                ESP_WS_CLIENT_MEM_CHECK(client->config->password, return ESP_ERR_NO_MEM);
+            }
+            //free(client->config->username);
+            client->config->username = strdup(user_info);
+            ESP_WS_CLIENT_MEM_CHECK(client->config->username, return ESP_ERR_NO_MEM);
+            //free(user_info);
+        } else {
+            return ESP_ERR_NO_MEM;
+        }
+    }
+    return ESP_OK;
+}
+
+static esp_err_t esp_websocket_client_recv(sim_esp_websocket_client_handle_t client)
+{
+    int rlen;
+    client->payload_offset = 0;
+       memset(client->rx_buffer, 0, client->buffer_size);
+    do {
+        rlen = wb_esp_transport_read(client->transport, client->rx_buffer, client->buffer_size, client->config->network_timeout_ms);
+        if (rlen <= 0) {
+            ESP_LOGE("Error read data");
+            esp_websocket_client_abort_connection(client);
+            return ESP_FAIL;
+        }
+        client->payload_len = wb_esp_transport_ws_get_read_payload_len(client->transport);
+        client->last_opcode = wb_esp_transport_ws_get_read_opcode(client->transport);
+
+        esp_websocket_client_dispatch_event(client, WEBSOCKET_EVENT_DATA, client->rx_buffer, rlen);
+
+        client->payload_offset += rlen;
+    } while (client->payload_offset < client->payload_len);
+
+    // if a PING message received -> send out the PONG, this will not work for PING messages with payload longer than buffer len
+    if (client->last_opcode == WS_TRANSPORT_OPCODES_PING) {
+        const char *data = (client->payload_len == 0) ? NULL : client->rx_buffer;
+        wb_esp_transport_ws_send_raw(client->transport, WS_TRANSPORT_OPCODES_PONG, data, client->payload_len,
+                                  client->config->network_timeout_ms);
+    } else if (client->last_opcode == WS_TRANSPORT_OPCODES_CLOSE) {
+        ESP_LOGD("Received close frame");
+        client->state = WEBSOCKET_STATE_CLOSING;
+    }
+
+    return ESP_OK;
+}
+
+static void esp_websocket_client_task(void *pv)
+{
+       OSA_STATUS status;
+       int ret = 0;
+    const int lock_timeout = portMAX_DELAY;
+    sim_esp_websocket_client_handle_t client = (sim_esp_websocket_client_handle_t) pv;
+    task_run = 1;
+
+    //get transport by scheme
+    client->transport = wb_esp_transport_list_get_transport(client->transport_list, client->config->scheme);
+
+    if (client->transport == NULL) {
+        ESP_LOGE("There are no transports valid, stop websocket client");
+        task_run = 0;
+    }
+    //default port
+    if (client->config->port == 0) {
+        client->config->port = wb_esp_transport_get_default_port(client->transport);
+    }
+
+    client->state = WEBSOCKET_STATE_INIT;
+    int read_select = 0;
+    while (1) {
+               if (0 == task_run) {
+                       ESP_LOGE("%s: task_run=0 and task exit", __FUNCTION__);
+                       break;
+               }
+       
+               //ESP_LOGD("%s, client state is %d, client->run is %d", 
+               //                      __FUNCTION__, (int)client->state, task_run);
+  
+               status = OSAMutexLock(client->lock, OSA_SUSPEND);
+               if (status != OS_SUCCESS) {
+                       ESP_LOGE("%s: get lock failed and task exit", __FUNCTION__);
+                       break;
+               }
+        switch ((int)client->state) {
+            case WEBSOCKET_STATE_INIT:
+                if (client->transport == NULL) {
+                    ESP_LOGE("There are no transport");
+                    task_run = 0;
+                    break;
+                }
+                               
+                if (wb_esp_transport_connect(client->transport,
+                                          client->config->host,
+                                          client->config->port,
+                                          client->config->network_timeout_ms) < 0) {
+                    ESP_LOGE("Error transport connect");
+                    ret  = esp_websocket_client_abort_connection(client);
+                                       ESP_LOGD("%s, client abort connection ret is %d", __FUNCTION__, ret);
+                    break;
+                }
+                ESP_LOGD("Transport connected to %s://%s:%d", client->config->scheme, client->config->host, client->config->port);
+
+                client->state = WEBSOCKET_STATE_CONNECTED;
+                esp_websocket_client_dispatch_event(client, WEBSOCKET_EVENT_CONNECTED, NULL, 0);
+
+                break;
+            case WEBSOCKET_STATE_CONNECTED:
+                if (_tick_get_ms() - client->ping_tick_ms > WEBSOCKET_PING_TIMEOUT_MS) {
+                    client->ping_tick_ms = _tick_get_ms();
+                    ESP_LOGD("Sending PING...");
+                    wb_esp_transport_ws_send_raw(client->transport, WS_TRANSPORT_OPCODES_PING, NULL, 0, client->config->network_timeout_ms);
+                }
+
+                if (read_select == 0) {
+                    //ESP_LOGV("Read poll timeout: skipping esp_transport_read()...");
+                    break;
+                }
+                client->ping_tick_ms = _tick_get_ms();
+
+                if (esp_websocket_client_recv(client) == ESP_FAIL) {
+                    ESP_LOGE("Error receive data");
+                    esp_websocket_client_abort_connection(client);
+                    break;
+                }
+                break;
+            case WEBSOCKET_STATE_WAIT_TIMEOUT:
+                if (!client->config->auto_reconnect) {
+                    task_run = 0;
+                    break;
+                }
+                if (_tick_get_ms() - client->reconnect_tick_ms > client->wait_timeout_ms) {
+                    client->state = WEBSOCKET_STATE_INIT;
+                    client->reconnect_tick_ms = _tick_get_ms();
+                    ESP_LOGD("Reconnecting...");
+                } else {
+                                       client->state = WEBSOCKET_STATE_WAIT_TIMEOUT;
+                                       ESP_LOGD("Waiting connect...");
+                               }
+                break;
+                       case WEBSOCKET_STATE_CLOSING:
+                               // if closing not initiated by the client echo the close message back
+                               ESP_LOGD("Closing initiated by the server, sending close frame");
+                               wb_esp_transport_ws_send_raw(client->transport, WS_TRANSPORT_OPCODES_CLOSE | WS_TRANSPORT_OPCODES_FIN, NULL, 0, client->config->network_timeout_ms);
+                               break;
+
+                       default:                                
+                               ESP_LOGD("Client run iteration in a default state: %d", client->state);
+                               break;
+        }
+               OSAMutexUnlock(client->lock); 
+
+               if (WEBSOCKET_STATE_CONNECTED == client->state) {
+            read_select = wb_esp_transport_poll_read(client->transport, 1000); //Poll every 1000ms
+            if (read_select < 0) {
+                ESP_LOGE("Network error: esp_transport_poll_read() returned %d, errno=%d", read_select, errno);
+                esp_websocket_client_abort_connection(client);
+            }
+        } else if (WEBSOCKET_STATE_WAIT_TIMEOUT == client->state) {
+            // waiting for reconnecting...
+            OSATaskSleep(client->wait_timeout_ms / 2 / sim_portTICK_RATE_MS);
+        } else if (WEBSOCKET_STATE_CLOSING == client->state) {
+            ESP_LOGD(" Waiting for TCP connection to be closed by the server");
+            ret = esp_transport_ws_poll_connection_closed(client->transport, 1000);
+            if (ret == 0) {
+                // still waiting
+                break;
+            }
+            if (ret < 0) {
+                ESP_LOGW("Connection terminated while waiting for clean TCP close");
+            }
+            task_run = 0;
+            client->state = WEBSOCKET_STATE_UNKNOW;
+            esp_websocket_client_dispatch_event(client, WEBSOCKET_EVENT_CLOSED, NULL, 0);
+            break;
+        }
+    }
+       
+    wb_esp_transport_close(client->transport);
+    client->state = WEBSOCKET_STATE_UNKNOW;
+    ESP_LOGD("%s task exit!task_run=%d, client state=%d",
+        __FUNCTION__, task_run, client->state);
+       return;
+}
+
+esp_err_t sim_esp_websocket_client_start(sim_esp_websocket_client_handle_t client)
+{
+       OS_STATUS status = OS_SUCCESS;
+
+    if (client == NULL) {
+        return ESP_ERR_INVALID_ARG;
+    }
+    if (client->state > WEBSOCKET_STATE_INIT) {
+        ESP_LOGE("The client has started and client state is %d", client->state);
+        return ESP_FAIL;
+    }
+
+       if (NULL == websocket_client_ref) {
+               if (NULL == websocket_client_stack_ptr) {
+                       websocket_client_stack_ptr = malloc(8*1024);
+                       if (NULL == websocket_client_stack_ptr) {
+                               ESP_LOGE("websocket task stack malloc failed.");
+                               return ESP_ERR_NO_MEM;
+                       }
+               }
+               status = OSATaskCreate(&websocket_client_ref, 
+                                                         websocket_client_stack_ptr,
+                                                         8*1024,
+                                                         90,
+                                                         "ws_task",
+                                                         esp_websocket_client_task,
+                                                         (void *)client);
+               if (OS_SUCCESS != status) {
+                       if (websocket_client_stack_ptr) {
+                               free(websocket_client_stack_ptr);
+                               websocket_client_stack_ptr = NULL;
+                       }
+                       ESP_LOGE("Error create websocket task");
+               }
+       } else {
+               ESP_LOGD("websocket task is exist!");
+       }
+       
+    ESP_LOGD("websocket_version: %s.", websocket_version);
+       ESP_LOGD("create ws task SUCCESS!");
+    return ESP_OK;
+}
+
+esp_err_t sim_esp_websocket_client_stop(sim_esp_websocket_client_handle_t client)
+{
+    if (client == NULL) {
+        return ESP_ERR_INVALID_ARG;
+    }
+    if (0 == task_run) {
+        ESP_LOGW("Client was not started");
+        return ESP_FAIL;
+    }
+    task_run = 0;      
+    client->state = WEBSOCKET_STATE_UNKNOW;
+    //delete task
+    if(websocket_client_ref == NULL) {
+        ESP_LOGD("websocket task is not exist!");
+        return ESP_FAIL;
+    }
+    ESP_LOGD("task deleting...");
+#if 1 //liangrf @ fixed Bug #50522 (release select_cb)
+    lwip_trigger_process("select", websocket_client_ref);
+#endif
+    OSA_STATUS delete_status = OSATaskDelete(websocket_client_ref);
+    ESP_LOGD("task deleted, deleteTaskRet is %d...", delete_status);
+    if(websocket_client_stack_ptr) {
+        free(websocket_client_stack_ptr);
+        websocket_client_stack_ptr = NULL;
+    }
+    websocket_client_ref = NULL;
+    //delete task
+    
+    ESP_LOGD("%s, client state is %d, task_run is %d", 
+               __FUNCTION__, (int)client->state, task_run);
+    return ESP_OK;
+}
+
+static int sim_esp_websocket_client_send_close(sim_esp_websocket_client_handle_t client, int code, const char *additional_data, int total_len, TickType_t timeout)
+{
+    char *close_status_data = NULL;
+    // RFC6455#section-5.5.1: The Close frame MAY contain a body (indicated by total_len >= 2)
+    if (total_len >= 2) {
+        close_status_data = calloc(1, total_len);
+        ESP_WS_CLIENT_MEM_CHECK(close_status_data, return -1);
+        // RFC6455#section-5.5.1: The first two bytes of the body MUST be a 2-byte representing a status
+        uint16_t *code_network_order = (uint16_t *) close_status_data;
+        *code_network_order = htons(code);
+        memcpy(close_status_data + 2, additional_data, total_len - 2);
+    }
+    int ret = sim_esp_websocket_client_send_with_opcode(client, WS_TRANSPORT_OPCODES_CLOSE, close_status_data, total_len, timeout);
+       if (NULL != close_status_data) {
+               free(close_status_data);
+               close_status_data = NULL;
+       }
+    return ret;
+}
+
+
+static int sim_esp_websocket_client_close_with_optional_body(sim_esp_websocket_client_handle_t client, bool send_body, int code, const char *data, int len, TickType_t timeout)
+{
+       int ret = 0;
+       
+    if (client == NULL) {
+        return ESP_ERR_INVALID_ARG;
+    }
+    if (0 == task_run) {
+        ESP_LOGW("Client was not started");
+        return ESP_FAIL;
+    }
+
+    if (send_body) {
+        ret = sim_esp_websocket_client_send_close(client, code, data, len + 2, portMAX_DELAY); // len + 2 -> always sending the code
+    } else {
+        ret = sim_esp_websocket_client_send_close(client, 0, NULL, 0, portMAX_DELAY); // only opcode frame
+    }
+
+    // If could not close gracefully within timeout, stop the client and disconnect
+    //task_run = 0;
+    //client->state = WEBSOCKET_STATE_UNKNOW;
+    if (ret >= 0) {
+               return ESP_OK;
+       } else {
+               ESP_LOGW("Client send close failed");
+               return ESP_FAIL;
+       }
+}
+
+int sim_esp_websocket_client_close_with_code(sim_esp_websocket_client_handle_t client, int code, const char *data, int len, TickType_t timeout)
+{
+    return sim_esp_websocket_client_close_with_optional_body(client, true, code, data, len, timeout);
+}
+
+int sim_esp_websocket_client_close(sim_esp_websocket_client_handle_t client, TickType_t timeout)
+{
+    return sim_esp_websocket_client_close_with_optional_body(client, false, 0, NULL, 0, timeout);
+}
+
+int sim_esp_websocket_client_send_text(sim_esp_websocket_client_handle_t client, const char *data, int len, TickType_t timeout)
+{
+    return sim_esp_websocket_client_send_with_opcode(client, WS_TRANSPORT_OPCODES_TEXT, data, len, timeout);
+}
+
+int sim_esp_websocket_client_send(sim_esp_websocket_client_handle_t client, const char *data, int len, TickType_t timeout)
+{
+    return sim_esp_websocket_client_send_with_opcode(client, WS_TRANSPORT_OPCODES_BINARY, data, len, timeout);
+}
+
+int sim_esp_websocket_client_send_bin(sim_esp_websocket_client_handle_t client, const char *data, int len, TickType_t timeout)
+{
+    return sim_esp_websocket_client_send_with_opcode(client, WS_TRANSPORT_OPCODES_BINARY, data, len, timeout);
+}
+
+static int sim_esp_websocket_client_send_with_opcode(sim_esp_websocket_client_handle_t client, ws_transport_opcodes_t opcode, const char *data, int len, TickType_t timeout)
+{
+    int need_write = len;
+    int wlen = 0, widx = 0;
+    int ret = ESP_FAIL;
+    UINT32 current_opcode = opcode;
+       OSA_STATUS status;
+
+    if (client == NULL || len < 0 ||
+        (opcode != WS_TRANSPORT_OPCODES_CLOSE && (data == NULL || len <= 0))) {
+        ESP_LOGE("Invalid arguments");
+        return ESP_FAIL;
+    }
+       
+       status = OSAMutexLock(client->lock, timeout);
+       if (status != OS_SUCCESS) {
+               ESP_LOGE("%s: get lock failed and return error", __FUNCTION__);
+               return ESP_FAIL;
+       }
+    if (!sim_esp_websocket_client_is_connected(client)) {
+        ESP_LOGE("Websocket client is not connected");
+        goto unlock_and_return;
+    }
+
+    if (client->transport == NULL) {
+        ESP_LOGE("Invalid transport");
+        goto unlock_and_return;
+    }
+
+    while (widx < len || current_opcode) {  // allow for sending "current_opcode" only message with len==0
+        if (need_write > client->buffer_size) {
+            need_write = client->buffer_size;
+        } else {
+            current_opcode |= WS_TRANSPORT_OPCODES_FIN;
+        }
+        memcpy(client->tx_buffer, data + widx, need_write);
+        // send with ws specific way and specific opcode
+        wlen = wb_esp_transport_ws_send_raw(client->transport, current_opcode, (char *)client->tx_buffer, need_write,
+                                        (timeout==portMAX_DELAY)? -1 : timeout * sim_portTICK_PERIOD_MS);
+        if (wlen < 0 || (wlen == 0 && need_write != 0)) {
+            ret = wlen;
+            ESP_LOGE("Network error: esp_transport_write() returned %d, errno=%d", ret, errno);
+            esp_websocket_client_abort_connection(client);
+            goto unlock_and_return;
+        }
+        current_opcode = 0;
+        widx += wlen;
+        need_write = len - widx;
+    }
+
+    ret = widx;
+unlock_and_return:
+       OSAMutexUnlock(client->lock);
+    return ret;
+}
+
+bool sim_esp_websocket_client_is_connected(sim_esp_websocket_client_handle_t client)
+{
+    if (client == NULL) {
+        return false;
+    }
+    return client->state == WEBSOCKET_STATE_CONNECTED;
+}
+
+esp_err_t sim_esp_websocket_register_events(sim_esp_websocket_client_handle_t client,
+                                        sim_esp_event_handler_t event_handler)
+{
+    if (client == NULL) {
+        return -1;
+    }
+       ESP_LOGD("client handler register success!!");
+       client->handler = event_handler;
+    return 0;
+}
diff --git a/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/sim_websocket_example.c b/2.sdk/sdk/product/craneg_modem/pcac/wsclient/libwebsockets/src/sim_websocket_example.c
new file mode 100644 (file)
index 0000000..286ea1b
--- /dev/null
@@ -0,0 +1,146 @@
+/* ESP HTTP Client Example
+
+   This example code is in the Public Domain (or CC0 licensed, at your option.)
+
+   Unless required by applicable law or agreed to in writing, this
+   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+   CONDITIONS OF ANY KIND, either express or implied.
+*/
+
+#include <stdio.h>
+#include <osa.h>
+#include "esp_log.h"
+#include "sim_esp_websocket_client.h"
+
+#define NO_DATA_TIMEOUT_SEC 10
+
+char config_websocket_uri[1024] = "ws://echo.websocket.org";
+//#define CONFIG_WEBSOCKET_URI "ws://echo.websocket.org"
+//#define CONFIG_WEBSOCKET_URI "ws://xvstc.xiaoyastar.com/ws03/ws/ws-voice?param=%7B%22osAccessToken%22%3A%22eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJvcy5jbGllbnQuMDAwMzY4IiwidWlkIjoxMjEyODYxNzMsInN2IjoiMiIsInByb2R1Y3RJZCI6IlNfUFJPRDFfMTU5NCIsImV4cCI6MTYzMjY0MzAyMywiZGV2aWNlSWQiOiIwMDEwNjgwMDAwMDAwMDYifQ.7Tm913uFPF_i9L6zQDGxSWRPAV11vxyj3O9UysZ6s9Y%22%2C%22dt%22%3A1632635825000%2C%22device%22%3A%7B%22sn%22%3A%22001068000000006%22%2C%22os%22%3A%22rtos%22%7D%2C%22product%22%3A%7B%22id%22%3A%22S_PROD1_1594%22%2C%22channel%22%3A%2240%22%7D%2C%22version%22%3A%7B%22os%22%3A%221.6.42%22%2C%22app%22%3A%221.6.42%22%7D%7D&sid=%7B%22sid%22%3A%22c6a0bc33-8ef02133-67a51168%22%7D&sig=03a9bb2b4e74302fa272795e68d65763"
+#define CONFIG_WEBSOCKET_URI   "ws://82.157.123.54:9010/ajaxchattest"
+
+#if CONFIG_WEBSOCKET_URI_FROM_STDIN
+static void get_string(char *line, size_t size)
+{
+    int count = 0;
+    while (count < size) {
+        int c = fgetc(stdin);
+        if (c == '\n') {
+            line[count] = '\0';
+            break;
+        } else if (c > 0 && c < 127) {
+            line[count] = c;
+            ++count;
+        }
+        vTaskDelay(10 / portTICK_PERIOD_MS);
+    }
+}
+
+#endif /* CONFIG_WEBSOCKET_URI_FROM_STDIN */
+
+static void websocket_event_handler(int32_t event_id, void *event_data)
+{
+       ESP_LOGD("%s, client handler is run and event_id is %d", __FUNCTION__, event_id);
+    sim_esp_websocket_event_data_t *data = (sim_esp_websocket_event_data_t *)event_data;
+    switch (event_id) {
+    case WEBSOCKET_EVENT_CONNECTED:
+        ESP_LOGI("WEBSOCKET_EVENT_CONNECTED");
+        break;
+    case WEBSOCKET_EVENT_DISCONNECTED:
+        ESP_LOGI("WEBSOCKET_EVENT_DISCONNECTED");
+        break;
+    case WEBSOCKET_EVENT_DATA:
+        ESP_LOGI("WEBSOCKET_EVENT_DATA");
+        ESP_LOGI("Received opcode=%d", data->op_code);
+        if (data->op_code == 0x08 && data->data_len == 2) {
+            ESP_LOGW("Received closed message with code=%d", 256*data->data_ptr[0] + data->data_ptr[1]);
+        } else {
+            ESP_LOGW("Received=%.*s", data->data_len, (char *)data->data_ptr);
+        }
+        ESP_LOGW("Total payload length=%d, data_len=%d, current payload offset=%d\r\n", data->payload_len, data->data_len, data->payload_offset);
+               //OSATimerStart(shutdown_signal_timer, portMAX_DELAY, 0, shutdown_signaler, 0);
+               break;
+    case WEBSOCKET_EVENT_ERROR:
+        ESP_LOGI("WEBSOCKET_EVENT_ERROR");
+        break;
+       case WEBSOCKET_EVENT_CLOSED:
+               ESP_LOGI("WEBSOCKET_EVENT_CLOSED");
+               break;
+       default:
+        ESP_LOGI("websocket event_id is NULL");
+               break;
+    }
+
+       if (NULL != data) {
+               if (NULL != data->data_ptr) {
+                       free(data->data_ptr);
+                       data->data_ptr = NULL;
+                       ESP_LOGI("%s: free data_ptr", __FUNCTION__);
+               }
+               ESP_LOGI("%s: free data", __FUNCTION__);
+               free(data);
+               data = NULL;
+       }
+       return;
+}
+
+static void sim_websocket_app_start(void)
+{
+       OS_STATUS       status;
+       int             ret = 0;
+    sim_esp_websocket_client_config_t websocket_cfg = {};
+
+#if CONFIG_WEBSOCKET_URI_FROM_STDIN
+    char line[128];
+
+    ESP_LOGI("Please enter uri of websocket endpoint");
+    get_string(line, sizeof(line));
+
+    websocket_cfg.uri = line;
+    ESP_LOGI("Endpoint uri: %s\n", line);
+
+#else
+    websocket_cfg.uri = CONFIG_WEBSOCKET_URI;
+    //websocket_cfg.uri = config_websocket_uri;
+
+#endif /* CONFIG_WEBSOCKET_URI_FROM_STDIN */
+    ESP_LOGI("Connecting to %s...", websocket_cfg.uri);
+
+    sim_esp_websocket_client_handle_t client = sim_esp_websocket_client_init(&websocket_cfg);
+    sim_esp_websocket_register_events(client, websocket_event_handler);
+
+    sim_esp_websocket_client_start(client);
+       
+       //status = OSATimerStart(shutdown_signal_timer, portMAX_DELAY, 0, shutdown_signaler, 0);
+    //ASSERT( status == OS_SUCCESS );
+#if 0
+    char data[32];
+    int i = 0;
+    while (i < 10) {
+        if (esp_websocket_client_is_connected(client)) {
+            int len = sprintf(data, "hello %d", i++);
+            ESP_LOGI("Sending %s", data);
+            ret = esp_websocket_client_send_text(client, data, len, portMAX_DELAY);
+                       if (0 > ret) {
+                               ESP_LOGI("Sending failed and ret=%d", ret);
+                               continue;
+                       }
+        }
+        OSATaskSleep(1000 / sim_portTICK_RATE_MS);
+    }
+
+       //status = OSASemaphoreAcquire(shutdown_sema, OS_SUSPEND);
+       OSATaskSleep(5000 / sim_portTICK_RATE_MS);
+       ESP_LOGI("Websocket Stopped");          
+       esp_websocket_client_destroy(client);   
+#endif
+       return;
+}
+
+int sim_app_main(void)
+{
+    ESP_LOGI("[APP] Startup..");
+
+    sim_websocket_app_start();
+       return 0;
+}
index 2a540ee..6b0abcd 100644 (file)
@@ -211,6 +211,10 @@ TARGET_DFLAGS       += -DLCD128X160
 endif
 
 
+# websocket
+VARIANT_LIST += WS_SUPPORT
+
+
 # L1 Software Wlan SSID Scan as WIFI location assisscent
 # enable by default for all CP build
 VARIANT_LIST += WLAN_SUPPORT