code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 _TCP_CLIENT_STREAM_H_
#define _TCP_CLIENT_STREAM_H_
#include "audio_error.h"
#include "audio_element.h"
#include "esp_transport.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
TCP_STREAM_STATE_NONE,
TCP_STREAM_STATE_CONNECTED,
} tcp_stream_status_t;
/**
* @brief TCP Stream massage configuration
*/
typedef struct tcp_stream_event_msg {
void *source; /*!< Element handle */
void *data; /*!< Data of input/output */
int data_len; /*!< Data length of input/output */
esp_transport_handle_t sock_fd; /*!< handle of socket*/
} tcp_stream_event_msg_t;
typedef esp_err_t (*tcp_stream_event_handle_cb)(tcp_stream_event_msg_t *msg, tcp_stream_status_t state, void *event_ctx);
/**
* @brief TCP Stream configuration, if any entry is zero then the configuration will be set to default values
*/
typedef struct {
audio_stream_type_t type; /*!< Type of stream */
int timeout_ms; /*!< time timeout for read/write*/
int port; /*!< TCP port> */
char *host; /*!< TCP host> */
int task_stack; /*!< Task stack size */
int task_core; /*!< Task running in core (0 or 1) */
int task_prio; /*!< Task priority (based on freeRTOS priority) */
bool ext_stack; /*!< Allocate stack on extern ram */
tcp_stream_event_handle_cb event_handler; /*!< TCP stream event callback*/
void *event_ctx; /*!< User context*/
} tcp_stream_cfg_t;
/**
* @brief TCP stream parameters
*/
#define TCP_STREAM_DEFAULT_PORT (8080)
#define TCP_STREAM_TASK_STACK (3072)
#define TCP_STREAM_BUF_SIZE (2048)
#define TCP_STREAM_TASK_PRIO (5)
#define TCP_STREAM_TASK_CORE (0)
#define TCP_SERVER_DEFAULT_RESPONSE_LENGTH (512)
#define TCP_STREAM_CFG_DEFAULT() { \
.type = AUDIO_STREAM_READER, \
.timeout_ms = 30 *1000, \
.port = TCP_STREAM_DEFAULT_PORT, \
.host = NULL, \
.task_stack = TCP_STREAM_TASK_STACK, \
.task_core = TCP_STREAM_TASK_CORE, \
.task_prio = TCP_STREAM_TASK_PRIO, \
.ext_stack = true, \
.event_handler = NULL, \
.event_ctx = NULL, \
}
/**
* @brief Initialize a TCP stream to/from an audio element
* This function creates a TCP stream to/from an audio element depending on the stream type configuration (e.g.,
* AUDIO_STREAM_READER or AUDIO_STREAM_WRITER). The handle of the audio element is the returned.
*
* @param config The configuration
*
* @return The audio element handle
*/
audio_element_handle_t tcp_stream_init(tcp_stream_cfg_t *config);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/audio_stream/include/tcp_client_stream.h
|
C
|
apache-2.0
| 4,447
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 _TONE_STREAM_H_
#define _TONE_STREAM_H_
#include "audio_element.h"
#include "esp_image_format.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief TONE Stream configurations, if any entry is zero then the configuration will be set to default values
*/
typedef struct
{
audio_stream_type_t type; /*!< Stream type */
int buf_sz; /*!< Audio Element Buffer size */
int out_rb_size; /*!< Size of output ringbuffer */
int task_stack; /*!< Task stack size */
int task_core; /*!< Task running in core (0 or 1) */
int task_prio; /*!< Task priority (based on freeRTOS priority) */
const char *label; /*!< Label of tone stored in flash. The default value is `flash_tone`*/
bool extern_stack; /*!< Task stack allocate on the extern ram */
bool use_delegate; /*!< Read tone partition with esp_delegate. If task stack is on extern ram, this MUST be TRUE */
} tone_stream_cfg_t;
#define TONE_STREAM_BUF_SIZE (2048)
#define TONE_STREAM_TASK_STACK (3072)
#define TONE_STREAM_TASK_CORE (0)
#define TONE_STREAM_TASK_PRIO (4)
#define TONE_STREAM_RINGBUFFER_SIZE (2 * 1024)
#define TONE_STREAM_EXT_STACK (false)
#define TONE_STREAM_USE_DELEGATE (false)
#define TONE_STREAM_CFG_DEFAULT() \
{ \
.type = AUDIO_STREAM_NONE, \
.buf_sz = TONE_STREAM_BUF_SIZE, \
.out_rb_size = TONE_STREAM_RINGBUFFER_SIZE,\
.task_stack = TONE_STREAM_TASK_STACK, \
.task_core = TONE_STREAM_TASK_CORE, \
.task_prio = TONE_STREAM_TASK_PRIO, \
.label = "flash_tone", \
.extern_stack = TONE_STREAM_EXT_STACK, \
.use_delegate = TONE_STREAM_USE_DELEGATE, \
}
/**
* @brief Create a handle to an Audio Element to stream data from flash to another Element
* or get data from other elements written to flash, depending on the configuration
* the stream type, either AUDIO_STREAM_READER or AUDIO_STREAM_WRITER.
*
* @param config The configuration
*
* @return The Audio Element handle
*/
audio_element_handle_t tone_stream_init(tone_stream_cfg_t *config);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/audio_stream/include/tone_stream.h
|
C
|
apache-2.0
| 3,559
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 _TTS_STREAM_H_
#define _TTS_STREAM_H_
#include "audio_error.h"
#include "audio_element.h"
#ifdef __cplusplus
extern "C" {
#endif
/* The speech speed speed of synthesized speech */
typedef enum {
TTS_VOICE_SPEED_0, /* the slowest speed */
TTS_VOICE_SPEED_1,
TTS_VOICE_SPEED_2,
TTS_VOICE_SPEED_3,
TTS_VOICE_SPEED_4,
TTS_VOICE_SPEED_5, /* the fastest speech */
TTS_VOICE_SPEED_MAX,
} tts_voice_speed_t;
/**
* @brief TTS Stream configurations, if any entry is zero then the configuration will be set to default values
*/
typedef struct {
audio_stream_type_t type; /*!< Stream type */
int buf_sz; /*!< Audio Element Buffer size */
int out_rb_size; /*!< Size of output ringbuffer */
int task_stack; /*!< Task stack size */
int task_core; /*!< Task running in core (0 or 1) */
int task_prio; /*!< Task priority (based on freeRTOS priority) */
bool ext_stack; /*!< Allocate stack on extern ram */
} tts_stream_cfg_t;
#define TTS_STREAM_BUF_SIZE (4096)
#define TTS_STREAM_TASK_STACK (3072)
#define TTS_STREAM_TASK_CORE (0)
#define TTS_STREAM_TASK_PRIO (4)
#define TTS_STREAM_RINGBUFFER_SIZE (8 * 1024)
#define TTS_STREAM_CFG_DEFAULT() { \
.type = AUDIO_STREAM_READER, \
.buf_sz = TTS_STREAM_BUF_SIZE, \
.out_rb_size = TTS_STREAM_RINGBUFFER_SIZE, \
.task_stack = TTS_STREAM_TASK_STACK, \
.task_core = TTS_STREAM_TASK_CORE, \
.task_prio = TTS_STREAM_TASK_PRIO, \
.ext_stack = false, \
}
/**
* @brief Create a handle to an Audio Element to stream data from TTS to another Element,
* the stream type only support AUDIO_STREAM_READER for now.
*
* @param config The configuration
*
* @return The Audio Element handle
*/
audio_element_handle_t tts_stream_init(tts_stream_cfg_t *config);
/**
* @brief Set tts stream strings.
*
* @param[in] el The audio element handle
* @param[in] string The string pointer
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t tts_stream_set_strings(audio_element_handle_t el, const char *strings);
/**
* @brief Setting tts stream voice speed.
*
* @param[in] handle The esp_audio instance
* @param[in] speed Speed will be set. 0-5 is legal. 0 is the slowest speed.
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t tts_stream_set_speed(audio_element_handle_t el, tts_voice_speed_t speed);
/**
* @brief Get tts stream voice speed.
*
* @param[in] handle The esp_audio instance
* @param[in] speed Return tts stream Speed will be [0,5]
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t tts_stream_get_speed(audio_element_handle_t el, tts_voice_speed_t *speed);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/audio_stream/include/tts_stream.h
|
C
|
apache-2.0
| 4,340
|
/*
* * ESPRESSIF MIT License
*
* Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "audio_mem.h"
#include "audio_sys.h"
#include "audio_error.h"
#include "audio_element.h"
#include "esp_log.h"
#include "esp_err.h"
#include "soc/ledc_struct.h"
#include "soc/ledc_reg.h"
#include "pwm_stream.h"
static const char *TAG = "PWM_STREAM";
#define BUFFER_MIN_SIZE (256UL)
#define SAMPLE_RATE_MAX (48000)
#define SAMPLE_RATE_MIN (8000)
#define CHANNEL_LEFT_INDEX (0)
#define CHANNEL_RIGHT_INDEX (1)
#define CHANNEL_LEFT_MASK (0x01)
#define CHANNEL_RIGHT_MASK (0x02)
#define AUDIO_PWM_CH_MAX (2)
typedef struct {
char *buf; /**< Original pointer */
uint32_t volatile head; /**< ending pointer */
uint32_t volatile tail; /**< Read pointer */
uint32_t size; /**< Buffer size */
uint32_t is_give; /**< semaphore give flag */
SemaphoreHandle_t semaphore; /**< Semaphore for data */
} data_list_t;
typedef data_list_t *pwm_data_handle_t;
typedef enum {
AUDIO_PWM_STATUS_UNINIT = 0, /*!< pwm audio uninitialized */
AUDIO_PWM_STATUS_IDLE = 1, /*!< pwm audio idle */
AUDIO_PWM_STATUS_BUSY = 2, /*!< pwm audio busy */
} audio_pwm_status_t;
typedef struct {
audio_pwm_config_t config; /**< pwm audio config struct */
ledc_channel_config_t ledc_channel[AUDIO_PWM_CH_MAX]; /**< ledc channel config */
ledc_timer_config_t ledc_timer; /**< ledc timer config */
timg_dev_t *timg_dev; /**< timer group register pointer */
pwm_data_handle_t data; /**< audio data pointer */
uint32_t channel_mask; /**< channel gpio mask */
uint32_t channel_set_num; /**< channel audio set number */
int32_t framerate; /*!< frame rates in Hz */
int32_t bits_per_sample; /*!< bits per sample (16, 32) */
audio_pwm_status_t status;
} audio_pwm_t;
typedef audio_pwm_t *audio_pwm_handle_t;
static volatile uint32_t *g_ledc_left_conf0_val = NULL;
static volatile uint32_t *g_ledc_left_conf1_val = NULL;
static volatile uint32_t *g_ledc_left_duty_val = NULL;
static volatile uint32_t *g_ledc_right_conf0_val = NULL;
static volatile uint32_t *g_ledc_right_conf1_val = NULL;
static volatile uint32_t *g_ledc_right_duty_val = NULL;
static audio_pwm_handle_t g_audio_pwm_handle = NULL;
typedef struct pwm_stream {
audio_stream_type_t type;
pwm_stream_cfg_t config;
bool is_open;
bool uninstall_drv;
} pwm_stream_t;
static esp_err_t pwm_data_list_destroy(pwm_data_handle_t data)
{
if (data == NULL) {
return ESP_ERR_INVALID_ARG;
}
if (data->buf) {
audio_free(data->buf);
}
if (data->semaphore) {
vSemaphoreDelete(data->semaphore);
}
audio_free(data);
data = NULL;
return ESP_OK;
}
static pwm_data_handle_t pwm_data_list_create(int size)
{
if (size < (BUFFER_MIN_SIZE << 2)) {
ESP_LOGE(TAG, "Invalid buffer size, Minimum = %d", (int32_t)(BUFFER_MIN_SIZE << 2));
return NULL;
}
pwm_data_handle_t data = audio_calloc(1, sizeof(data_list_t));
AUDIO_NULL_CHECK(TAG, data, goto data_error);
data->buf = audio_calloc(1, size);
AUDIO_NULL_CHECK(TAG, data->buf, goto data_error);
data->semaphore = xSemaphoreCreateBinary();
AUDIO_NULL_CHECK(TAG, data->semaphore, goto data_error);
data->is_give = 0;
data->head = data->tail = 0;
data->size = size;
return data;
data_error:
if (data->semaphore != NULL) {
vSemaphoreDelete(data->semaphore);
data->semaphore = NULL;
}
if (data->buf) {
audio_free(data->buf);
data->buf = NULL;
}
if (data) {
audio_free(data);
data = NULL;
}
return NULL;
}
static uint32_t IRAM_ATTR pwm_data_list_get_count(pwm_data_handle_t data)
{
uint32_t tail = data->tail;
if (data->head >= tail) {
return (data->head - tail);
}
return (data->size - (tail - data->head));
}
static uint32_t IRAM_ATTR pwm_data_list_get_free(pwm_data_handle_t data)
{
return (data->size - pwm_data_list_get_count(data) - 1);
}
static esp_err_t pwm_data_list_flush(pwm_data_handle_t data)
{
data->tail = data->head = 0;
return ESP_OK;
}
static esp_err_t IRAM_ATTR pwm_data_list_read_byte(pwm_data_handle_t data, uint8_t *outdata)
{
uint32_t tail = data->tail;
if ((tail == data->head) || (tail == (data->head + 1))) {
return ESP_FAIL;
}
*outdata = data->buf[tail];
tail++;
if (tail == data->size) {
tail = 0;
}
data->tail = tail;
return ESP_OK;
}
static esp_err_t pwm_data_list_write_byte(pwm_data_handle_t data, const uint8_t indata)
{
uint32_t next_head = data->head + 1;
if (next_head == data->size) {
next_head = 0;
}
if (next_head == data->tail) {
return ESP_FAIL;
}
data->buf[data->head] = indata;
data->head = next_head;
return ESP_OK;
}
static esp_err_t pwm_data_list_wait_semaphore(pwm_data_handle_t data, TickType_t ticks_to_wait)
{
data->is_give = 0;
if (xSemaphoreTake(data->semaphore, ticks_to_wait) == pdTRUE) {
return ESP_OK;
}
return ESP_FAIL;
}
static inline void ledc_set_left_duty_fast(uint32_t duty_val)
{
*g_ledc_left_duty_val = (duty_val) << 4;
*g_ledc_left_conf0_val |= 0x00000014;
*g_ledc_left_conf1_val |= 0x80000000;
}
static inline void ledc_set_right_duty_fast(uint32_t duty_val)
{
*g_ledc_right_duty_val = (duty_val) << 4;
*g_ledc_right_conf0_val |= 0x00000014;
*g_ledc_right_conf1_val |= 0x80000000;
}
static void IRAM_ATTR timer_group_isr(void *para)
{
audio_pwm_handle_t handle = g_audio_pwm_handle;
if (handle == NULL) {
return;
}
if (handle->timg_dev->int_st_timers.val & BIT(handle->config.timer_num)) {
handle->timg_dev->int_clr_timers.val |= (1UL << handle->config.timer_num);
}
#ifdef CONFIG_IDF_TARGET_ESP32S2
handle->timg_dev->hw_timer[handle->config.timer_num].config.tx_alarm_en = TIMER_ALARM_EN;
#elif CONFIG_IDF_TARGET_ESP32
handle->timg_dev->hw_timer[handle->config.timer_num].config.alarm_en = TIMER_ALARM_EN;
#elif CONFIG_IDF_TARGET_ESP32S3
handle->timg_dev->hw_timer[handle->config.timer_num].config.tn_alarm_en = TIMER_ALARM_EN;
#endif
static uint8_t wave_h, wave_l;
static uint16_t value;
if (handle->channel_mask & CHANNEL_LEFT_MASK) {
if (handle->config.duty_resolution > 8) {
pwm_data_list_read_byte(handle->data, &wave_l);
if (ESP_OK == pwm_data_list_read_byte(handle->data, &wave_h)) {
value = ((wave_h << 8) | wave_l);
ledc_set_left_duty_fast(value);
}
} else {
if (ESP_OK == pwm_data_list_read_byte(handle->data, &wave_h)) {
ledc_set_left_duty_fast(wave_h);
}
}
}
if (handle->channel_mask & CHANNEL_RIGHT_MASK) {
if (handle->channel_set_num == 1) {
if (handle->config.duty_resolution > 8) {
ledc_set_right_duty_fast(value);
} else {
ledc_set_right_duty_fast(wave_h);
}
} else {
if (handle->config.duty_resolution > 8) {
pwm_data_list_read_byte(handle->data, &wave_l);
if (ESP_OK == pwm_data_list_read_byte(handle->data, &wave_h)) {
value = ((wave_h << 8) | wave_l);
ledc_set_right_duty_fast(value);
}
} else {
if (ESP_OK == pwm_data_list_read_byte(handle->data, &wave_h)) {
ledc_set_right_duty_fast(wave_h);
}
}
}
} else {
if (handle->channel_set_num == 2) {
if (handle->config.duty_resolution > 8) {
pwm_data_list_read_byte(handle->data, &wave_h);
pwm_data_list_read_byte(handle->data, &wave_h);
} else {
pwm_data_list_read_byte(handle->data, &wave_h);
}
pwm_data_list_read_byte(handle->data, &wave_l);
}
}
if (0 == handle->data->is_give && pwm_data_list_get_free(handle->data) > BUFFER_MIN_SIZE) {
handle->data->is_give = 1;
BaseType_t xHigherPriorityTaskWoken;
xSemaphoreGiveFromISR(handle->data->semaphore, &xHigherPriorityTaskWoken);
if (pdFALSE != xHigherPriorityTaskWoken) {
portYIELD_FROM_ISR();
}
}
}
static esp_err_t audio_pwm_init(const audio_pwm_config_t *cfg)
{
esp_err_t res = ESP_OK;
AUDIO_NULL_CHECK(TAG, cfg, return ESP_ERR_INVALID_ARG);
if (!(cfg->tg_num < TIMER_GROUP_MAX)) {
ESP_LOGE(TAG, "%s:%d (%s): AUDIO PWM TIMER GROUP NUMBER IS %d AND SHOULD BE 0 OR 1", __FILENAME__, __LINE__, __FUNCTION__, cfg->tg_num);
}
if (!(cfg->timer_num < TIMER_MAX)) {
ESP_LOGE(TAG, "%s:%d (%s): AUDIO PWM TIMER NUMBER IS %d AND SHOULD BE 0 OR 1", __FILENAME__, __LINE__, __FUNCTION__, cfg->timer_num);
}
if (cfg->duty_resolution < 8 || cfg->duty_resolution > 10) {
ESP_LOGE(TAG, "%s:%d (%s): AUDIO PWM RESOLUTION IS %d AND SHOULD BE 8, 9, 10", __FILENAME__, __LINE__, __FUNCTION__, cfg->duty_resolution);
}
audio_pwm_handle_t handle = NULL;
handle = audio_calloc(1, sizeof(audio_pwm_t));
AUDIO_NULL_CHECK(TAG, handle, goto init_error);
handle->data = pwm_data_list_create(cfg->data_len);
AUDIO_NULL_CHECK(TAG, handle->data, goto init_error);
handle->config = *cfg;
g_audio_pwm_handle = handle;
if (cfg->tg_num == TIMER_GROUP_0) {
handle->timg_dev = &TIMERG0;
} else {
handle->timg_dev = &TIMERG1;
}
handle->channel_mask = 0;
if (handle->config.gpio_num_left >= 0) {
handle->ledc_channel[CHANNEL_LEFT_INDEX].channel = handle->config.ledc_channel_left;
handle->ledc_channel[CHANNEL_LEFT_INDEX].duty = 0;
handle->ledc_channel[CHANNEL_LEFT_INDEX].gpio_num = handle->config.gpio_num_left;
handle->ledc_channel[CHANNEL_LEFT_INDEX].speed_mode = LEDC_LOW_SPEED_MODE;
handle->ledc_channel[CHANNEL_LEFT_INDEX].hpoint = 0;
handle->ledc_channel[CHANNEL_LEFT_INDEX].timer_sel = handle->config.ledc_timer_sel;
handle->ledc_channel[CHANNEL_LEFT_INDEX].intr_type = LEDC_INTR_DISABLE;
res = ledc_channel_config(&handle->ledc_channel[CHANNEL_LEFT_INDEX]);
AUDIO_CHECK(TAG, ESP_OK == res, goto init_error, "AUDIO PWM LEFT CHANNEL CONFIG ERROR");
handle->channel_mask |= CHANNEL_LEFT_MASK;
}
if (handle->config.gpio_num_right >= 0) {
handle->ledc_channel[CHANNEL_RIGHT_INDEX].channel = handle->config.ledc_channel_right;
handle->ledc_channel[CHANNEL_RIGHT_INDEX].duty = 0;
handle->ledc_channel[CHANNEL_RIGHT_INDEX].gpio_num = handle->config.gpio_num_right;
handle->ledc_channel[CHANNEL_RIGHT_INDEX].speed_mode = LEDC_LOW_SPEED_MODE;
handle->ledc_channel[CHANNEL_RIGHT_INDEX].hpoint = 0;
handle->ledc_channel[CHANNEL_RIGHT_INDEX].timer_sel = handle->config.ledc_timer_sel;
handle->ledc_channel[CHANNEL_RIGHT_INDEX].intr_type = LEDC_INTR_DISABLE;
res = ledc_channel_config(&handle->ledc_channel[CHANNEL_RIGHT_INDEX]);
AUDIO_CHECK(TAG, ESP_OK == res, goto init_error, "AUDIO PWM RIGHT CHANNEL CONFIG ERROR");
handle->channel_mask |= CHANNEL_RIGHT_MASK;
}
AUDIO_CHECK(TAG, 0 != handle->channel_mask, goto init_error, "AUDIO PWM CHANNEL MASK IS 0");
#ifdef CONFIG_IDF_TARGET_ESP32S2
handle->ledc_timer.clk_cfg = LEDC_USE_APB_CLK;
#endif
handle->ledc_timer.speed_mode = LEDC_LOW_SPEED_MODE;
handle->ledc_timer.duty_resolution = handle->config.duty_resolution;
handle->ledc_timer.timer_num = handle->config.ledc_timer_sel;
uint32_t freq = (APB_CLK_FREQ / (1 << handle->ledc_timer.duty_resolution));
handle->ledc_timer.freq_hz = freq - (freq % 1000);
res = ledc_timer_config(&handle->ledc_timer);
AUDIO_CHECK(TAG, ESP_OK == res, goto init_error, "AUDIO PWM TIMER ERROR");
g_ledc_left_duty_val = &LEDC.channel_group[handle->ledc_timer.speed_mode].channel[handle->ledc_channel[CHANNEL_LEFT_INDEX].channel].duty.val;
g_ledc_left_conf0_val = &LEDC.channel_group[handle->ledc_timer.speed_mode].channel[handle->ledc_channel[CHANNEL_LEFT_INDEX].channel].conf0.val;
g_ledc_left_conf1_val = &LEDC.channel_group[handle->ledc_timer.speed_mode].channel[handle->ledc_channel[CHANNEL_LEFT_INDEX].channel].conf1.val;
g_ledc_right_duty_val = &LEDC.channel_group[handle->ledc_timer.speed_mode].channel[handle->ledc_channel[CHANNEL_RIGHT_INDEX].channel].duty.val;
g_ledc_right_conf0_val = &LEDC.channel_group[handle->ledc_timer.speed_mode].channel[handle->ledc_channel[CHANNEL_RIGHT_INDEX].channel].conf0.val;
g_ledc_right_conf1_val = &LEDC.channel_group[handle->ledc_timer.speed_mode].channel[handle->ledc_channel[CHANNEL_RIGHT_INDEX].channel].conf1.val;
handle->status = AUDIO_PWM_STATUS_IDLE;
return res;
init_error:
if (handle->data) {
audio_free(handle->data);
handle->data = NULL;
}
if (handle) {
audio_free(handle);
handle = NULL;
}
return ESP_FAIL;
}
esp_err_t audio_pwm_set_param(int rate, ledc_timer_bit_t bits, int ch)
{
esp_err_t res = ESP_OK;
AUDIO_CHECK(TAG, g_audio_pwm_handle->status != AUDIO_PWM_STATUS_BUSY, return ESP_FAIL, "AUDIO PWM CAN NOT SET PARAM, WHEN AUDIO PWM STATUS IS BUSY");
if (rate > SAMPLE_RATE_MAX || rate < SAMPLE_RATE_MIN) {
ESP_LOGE(TAG, "%s:%d (%s): AUDIO PWM SAMPLE IS %d AND SHOULD BE BETWEEN 8000 AND 48000", __FILENAME__, __LINE__, __FUNCTION__, rate);
}
if (!(bits == 32 || bits == 16 || bits == 8)) {
ESP_LOGE(TAG, "%s:%d (%s): AUDIO PWM BITS IS %d AND SHOULD BE 8, 16, 32", __FILENAME__, __LINE__, __FUNCTION__, bits);
}
if (!(ch == 2 || ch == 1)) {
ESP_LOGE(TAG, "%s:%d (%s): AUDIO PWM CH IS %d AND SHOULD BE 1 OR 2", __FILENAME__, __LINE__, __FUNCTION__, ch);
}
audio_pwm_handle_t handle = g_audio_pwm_handle;
handle->framerate = rate;
handle->bits_per_sample = bits;
handle->channel_set_num = ch;
timer_config_t config = {0};
config.divider = 16;
config.counter_dir = TIMER_COUNT_UP;
config.counter_en = TIMER_PAUSE;
config.alarm_en = TIMER_ALARM_EN;
config.intr_type = TIMER_INTR_LEVEL;
config.auto_reload = 1;
#ifdef TIMER_GROUP_SUPPORTS_XTAL_CLOCK
config.clk_src = TIMER_SRC_CLK_APB;
#endif
timer_init(handle->config.tg_num, handle->config.timer_num, &config);
timer_set_counter_value(handle->config.tg_num, handle->config.timer_num, 0x00000000ULL);
timer_set_alarm_value(handle->config.tg_num, handle->config.timer_num, (TIMER_BASE_CLK / config.divider) / handle->framerate);
timer_enable_intr(handle->config.tg_num, handle->config.timer_num);
timer_isr_register(handle->config.tg_num, handle->config.timer_num, timer_group_isr, NULL, ESP_INTR_FLAG_IRAM, NULL);
return res;
}
esp_err_t audio_pwm_set_sample_rate(int rate)
{
esp_err_t res;
AUDIO_CHECK(TAG, g_audio_pwm_handle->status != AUDIO_PWM_STATUS_BUSY, return ESP_FAIL, "AUDIO PWM CAN NOT SET PARAM, WHEN AUDIO PWM STATUS IS BUSY");
if (rate > SAMPLE_RATE_MAX || rate < SAMPLE_RATE_MIN) {
ESP_LOGE(TAG, "%s:%d (%s): AUDIO PWM SAMPLE IS %d AND SHOULD BE BETWEEN 8000 AND 48000", __FILENAME__, __LINE__, __FUNCTION__, rate);
}
audio_pwm_handle_t handle = g_audio_pwm_handle;
handle->framerate = rate;
uint16_t div = 1;
#ifdef CONFIG_IDF_TARGET_ESP32S2
div = (uint16_t)handle->timg_dev->hw_timer[handle->config.timer_num].config.tx_divider;
#elif CONFIG_IDF_TARGET_ESP32
div = (uint16_t)handle->timg_dev->hw_timer[handle->config.timer_num].config.divider;
#elif CONFIG_IDF_TARGET_ESP32S3
div = (uint16_t)handle->timg_dev->hw_timer[handle->config.timer_num].config.tn_divider;
#endif
res = timer_set_alarm_value(handle->config.tg_num, handle->config.timer_num, (TIMER_BASE_CLK / div) / handle->framerate);
return res;
}
static esp_err_t pwm_data_convert(pwm_data_handle_t data, uint8_t *inbuf, int32_t bits_per, int32_t duty, uint32_t bytes)
{
int8_t shift = bits_per - duty;
uint32_t len = bytes;
if (bits_per == 16) {
len >>= 1;
uint16_t *buf_16b = (uint16_t *)inbuf;
uint16_t value;
int16_t temp;
if (duty > 8) {
for (size_t i = 0; i < len; i++) {
temp = buf_16b[i];
value = temp + 0x7fff;
value >>= shift;
pwm_data_list_write_byte(data, value);
pwm_data_list_write_byte(data, value >> 8);
}
} else {
for (size_t i = 0; i < len; i++) {
temp = buf_16b[i];
value = temp + 0x7fff;
value >>= shift;
pwm_data_list_write_byte(data, value);
}
}
} else if (bits_per == 32) {
len >>= 2;
uint32_t *buf_32b = (uint32_t *)inbuf;
uint32_t value;
int32_t temp;
if (duty > 8) {
for (size_t i = 0; i < len; i++) {
temp = buf_32b[i];
value = temp + 0x7fffffff;
value >>= shift;
pwm_data_list_write_byte(data, value);
pwm_data_list_write_byte(data, value >> 8);
}
} else {
for (size_t i = 0; i < len; i++) {
temp = buf_32b[i];
value = temp + 0x7fffffff;
value >>= shift;
pwm_data_list_write_byte(data, value);
}
}
} else {
ESP_LOGE(TAG, "Only support bits (16 or 32), now bits_per is %d", bits_per);
}
return ESP_OK;
}
esp_err_t audio_pwm_write(uint8_t *inbuf, size_t inbuf_len, size_t *bytes_written, TickType_t ticks_to_wait)
{
esp_err_t res = ESP_OK;
audio_pwm_handle_t handle = g_audio_pwm_handle;
AUDIO_NULL_CHECK(TAG, inbuf, return ESP_FAIL);
*bytes_written = 0;
pwm_data_handle_t data = handle->data;
while (inbuf_len) {
if (ESP_OK == pwm_data_list_wait_semaphore(data, ticks_to_wait)) {
uint32_t free = pwm_data_list_get_free(data);
uint32_t bytes_can_write = inbuf_len;
if (inbuf_len > free) {
bytes_can_write = free;
}
bytes_can_write &= 0xfffffffc;
if (0 == bytes_can_write) {
*bytes_written += inbuf_len;
return ESP_OK;
}
pwm_data_convert(data, inbuf, handle->bits_per_sample, handle->config.duty_resolution, bytes_can_write);
inbuf += bytes_can_write;
inbuf_len -= bytes_can_write;
*bytes_written += bytes_can_write;
} else {
res = ESP_FAIL;
}
}
return res;
}
static esp_err_t audio_pwm_start(void)
{
esp_err_t res;
audio_pwm_handle_t handle = g_audio_pwm_handle;
if (handle->status != AUDIO_PWM_STATUS_IDLE) {
ESP_LOGE(TAG, "%s:%d (%s): AUDIO PWM STATE IS %d, AND SHOULD BE IDLE WHEN PWM START", __FILENAME__, __LINE__, __FUNCTION__, handle->status);
}
handle->status = AUDIO_PWM_STATUS_BUSY;
timer_enable_intr(handle->config.tg_num, handle->config.timer_num);
res = timer_start(handle->config.tg_num, handle->config.timer_num);
return res;
}
static esp_err_t audio_pwm_stop(void)
{
audio_pwm_handle_t handle = g_audio_pwm_handle;
timer_pause(handle->config.tg_num, handle->config.timer_num);
timer_disable_intr(handle->config.tg_num, handle->config.timer_num);
pwm_data_list_flush(handle->data);
handle->status = AUDIO_PWM_STATUS_IDLE;
return ESP_OK;
}
static esp_err_t audio_pwm_deinit(void)
{
audio_pwm_handle_t handle = g_audio_pwm_handle;
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
handle->status = AUDIO_PWM_STATUS_UNINIT;
audio_pwm_stop();
for (size_t i = 0; i < AUDIO_PWM_CH_MAX; i++) {
if (handle->ledc_channel[i].gpio_num >= 0) {
ledc_stop(handle->ledc_channel[i].speed_mode, handle->ledc_channel[i].channel, 0);
}
}
for (size_t i = 0; i < AUDIO_PWM_CH_MAX; i++) {
if (handle->ledc_channel[i].gpio_num >= 0) {
gpio_set_direction(handle->ledc_channel[i].gpio_num, GPIO_MODE_INPUT);
}
}
pwm_data_list_destroy(handle->data);
audio_free(handle);
return ESP_OK;
}
static int _pwm_write(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait, void *context)
{
size_t bytes_written = 0;
audio_pwm_write((uint8_t *)buffer, len, &bytes_written, ticks_to_wait);
return bytes_written;
}
static esp_err_t _pwm_destroy(audio_element_handle_t self)
{
esp_err_t res = ESP_OK;
pwm_stream_t *pwm = (pwm_stream_t *)audio_element_getdata(self);
if (pwm->uninstall_drv) {
res = audio_pwm_deinit();
}
audio_free(pwm);
return res;
}
static esp_err_t _pwm_open(audio_element_handle_t self)
{
esp_err_t res = ESP_OK;
pwm_stream_t *pwm = (pwm_stream_t *)audio_element_getdata(self);
if (pwm->is_open) {
return ESP_OK;
}
res = audio_element_set_input_timeout(self, 2000 / portTICK_RATE_MS);
pwm->is_open = true;
return res;
}
static esp_err_t _pwm_close(audio_element_handle_t self)
{
esp_err_t res = ESP_OK;
pwm_stream_t *pwm = (pwm_stream_t *)audio_element_getdata(self);
pwm->is_open = false;
if (AEL_STATE_PAUSED != audio_element_get_state(self)) {
audio_element_report_pos(self);
audio_element_set_byte_pos(self, 0);
res = audio_pwm_stop();
}
return res;
}
static int _pwm_process(audio_element_handle_t self, char *in_buffer, int in_len)
{
int r_size = audio_element_input(self, in_buffer, in_len);
int w_size = 0;
if (r_size == AEL_IO_TIMEOUT) {
memset(in_buffer, 0x00, in_len);
r_size = in_len;
}
if (r_size > 0) {
w_size = audio_element_output(self, in_buffer, r_size);
audio_element_update_byte_pos(self, w_size);
} else {
w_size = r_size;
}
return w_size;
}
audio_element_handle_t pwm_stream_init(pwm_stream_cfg_t *config)
{
audio_element_cfg_t cfg = DEFAULT_AUDIO_ELEMENT_CONFIG();
audio_element_handle_t el;
audio_pwm_init(&config->pwm_config);
cfg.open = _pwm_open;
cfg.close = _pwm_close;
cfg.process = _pwm_process;
cfg.destroy = _pwm_destroy;
cfg.tag = "pwm";
cfg.out_rb_size = config->out_rb_size;
cfg.task_stack = config->task_stack;
cfg.task_prio = config->task_prio;
cfg.task_core = config->task_core;
cfg.buffer_len = config->buffer_len;
cfg.stack_in_ext = config->ext_stack;
if (config->type == AUDIO_STREAM_WRITER) {
cfg.write = _pwm_write;
} else {
ESP_LOGE(TAG, "PWM stream only support AUDIO_STREAM_WRITER mode, not support %d", config->type);
return NULL;
}
pwm_stream_t *pwm = audio_calloc(1, sizeof(pwm_stream_t));
AUDIO_NULL_CHECK(TAG, pwm, return NULL);
memcpy(&pwm->config, config, sizeof(pwm_stream_cfg_t));
pwm->type = AUDIO_STREAM_WRITER;
pwm->uninstall_drv = true;
el = audio_element_init(&cfg);
audio_element_setdata(el, pwm);
ESP_LOGD(TAG, "stream init,el:%p", el);
return el;
}
esp_err_t pwm_stream_set_clk(audio_element_handle_t pwm_stream, int rate, int bits, int ch)
{
esp_err_t res = ESP_OK;
res |= audio_pwm_set_param(rate, bits, ch);
res |= audio_pwm_start();
return res;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/audio_stream/pwm_stream.c
|
C
|
apache-2.0
| 25,123
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 <sys/unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include "errno.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "raw_stream.h"
#include "audio_common.h"
#include "audio_mem.h"
#include "audio_element.h"
#include "esp_system.h"
#include "esp_log.h"
static const char *TAG = "RAW_STREAM";
typedef struct raw_stream {
audio_stream_type_t type;
} raw_stream_t;
int raw_stream_read(audio_element_handle_t pipeline, char *buffer, int len)
{
int ret = audio_element_input(pipeline, buffer, len);
if (ret == AEL_IO_DONE || ret == AEL_IO_OK) {
audio_element_report_status(pipeline, AEL_STATUS_STATE_FINISHED);
} else if (ret < 0) {
audio_element_report_status(pipeline, AEL_STATUS_STATE_STOPPED);
}
return ret;
}
int raw_stream_write(audio_element_handle_t pipeline, char *buffer, int len)
{
int ret = audio_element_output(pipeline, buffer, len);
if (ret == AEL_IO_DONE || ret == AEL_IO_OK) {
audio_element_report_status(pipeline, AEL_STATUS_STATE_FINISHED);
} else if (ret < 0) {
audio_element_report_status(pipeline, AEL_STATUS_STATE_STOPPED);
}
return ret;
}
static esp_err_t _raw_destroy(audio_element_handle_t self)
{
raw_stream_t *raw = (raw_stream_t *)audio_element_getdata(self);
audio_free(raw);
return ESP_OK;
}
audio_element_handle_t raw_stream_init(raw_stream_cfg_t *config)
{
raw_stream_t *raw = audio_calloc(1, sizeof(raw_stream_t));
AUDIO_MEM_CHECK(TAG, raw, return NULL);
audio_element_cfg_t cfg = DEFAULT_AUDIO_ELEMENT_CONFIG();
cfg.task_stack = -1; // No need task
cfg.destroy = _raw_destroy;
cfg.tag = "raw";
cfg.out_rb_size = config->out_rb_size;
raw->type = config->type;
audio_element_handle_t el = audio_element_init(&cfg);
AUDIO_MEM_CHECK(TAG, el, {
audio_free(raw);
return NULL;
});
audio_element_setdata(el, raw);
ESP_LOGD(TAG, "stream init,el:%p", el);
return el;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/audio_stream/raw_stream.c
|
C
|
apache-2.0
| 3,276
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 <sys/unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include "errno.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "spiffs_stream.h"
#include "audio_common.h"
#include "audio_mem.h"
#include "audio_element.h"
#include "wav_head.h"
#include "esp_log.h"
#define FILE_WAV_SUFFIX_TYPE "wav"
#define FILE_OPUS_SUFFIX_TYPE "opus"
#define FILE_AMR_SUFFIX_TYPE "amr"
#define FILE_AMRWB_SUFFIX_TYPE "Wamr"
static const char *TAG = "SPIFFS_STREAM";
typedef enum {
STREAM_TYPE_UNKNOWN,
STREAM_TYPE_WAV,
STREAM_TYPE_OPUS,
STREAM_TYPE_AMR,
STREAM_TYPE_AMRWB,
} wr_stream_type_t;
typedef struct spiffs_stream {
audio_stream_type_t type;
int block_size;
bool is_open;
FILE *file;
wr_stream_type_t w_type;
bool write_header;
} spiffs_stream_t;
static wr_stream_type_t get_type(const char *str)
{
char *relt = strrchr(str, '.');
if (relt != NULL) {
relt ++;
ESP_LOGD(TAG, "result = %s", relt);
if (strncasecmp(relt, FILE_WAV_SUFFIX_TYPE, 3) == 0) {
return STREAM_TYPE_WAV;
} else if (strncasecmp(relt, FILE_OPUS_SUFFIX_TYPE, 4) == 0) {
return STREAM_TYPE_OPUS;
} else if (strncasecmp(relt, FILE_AMR_SUFFIX_TYPE, 3) == 0) {
return STREAM_TYPE_AMR;
} else if (strncasecmp(relt, FILE_AMRWB_SUFFIX_TYPE, 4) == 0) {
return STREAM_TYPE_AMRWB;
} else {
return STREAM_TYPE_UNKNOWN;
}
} else {
return STREAM_TYPE_UNKNOWN;
}
}
static esp_err_t _spiffs_open(audio_element_handle_t self)
{
spiffs_stream_t *spiffs = (spiffs_stream_t *)audio_element_getdata(self);
audio_element_info_t info;
char *uri = audio_element_get_uri(self);
ESP_LOGD(TAG, "_spiffs_open, %s", uri);
char *path = strstr(uri, "/spiffs");
audio_element_getinfo(self, &info);
if (path == NULL) {
ESP_LOGE(TAG, "Need file path to open");
return ESP_FAIL;
}
if (spiffs->is_open) {
ESP_LOGE(TAG, "Already opened");
return ESP_FAIL;
}
if (spiffs->type == AUDIO_STREAM_READER) {
spiffs->file = fopen(path, "r");
struct stat siz = { 0 };
stat(path, &siz);
info.total_bytes = siz.st_size;
ESP_LOGI(TAG, "File size is %d byte, pos:%d", (int)siz.st_size, (int)info.byte_pos);
if (spiffs->file && (info.byte_pos > 0)) {
if (fseek(spiffs->file, info.byte_pos, SEEK_SET) != 0) {
ESP_LOGE(TAG, "Error seek file");
return ESP_FAIL;
}
}
} else if (spiffs->type == AUDIO_STREAM_WRITER) {
spiffs->file = fopen(path, "w+");
spiffs->w_type = get_type(path);
if (spiffs->file && STREAM_TYPE_WAV == spiffs->w_type) {
wav_header_t info = {0};
fwrite(&info, 1, sizeof(wav_header_t), spiffs->file);
fsync(fileno(spiffs->file));
} else if (spiffs->file && (STREAM_TYPE_AMR == spiffs->w_type) && (spiffs->write_header == true)) {
fwrite("#!AMR\n", 1, 6, spiffs->file);
fsync(fileno(spiffs->file));
} else if (spiffs->file && (STREAM_TYPE_AMRWB == spiffs->w_type) && (spiffs->write_header == true)) {
fwrite("#!AMR-WB\n", 1, 9, spiffs->file);
fsync(fileno(spiffs->file));
}
} else {
ESP_LOGE(TAG, "SPIFFS must be Reader or Writer");
return ESP_FAIL;
}
if (spiffs->file == NULL) {
ESP_LOGE(TAG, "Failed to open file %s", path);
return ESP_FAIL;
}
spiffs->is_open = true;
if (info.byte_pos && fseek(spiffs->file, info.byte_pos, SEEK_SET) != 0) {
ESP_LOGE(TAG, "Failed to seek to %d/%d", (int)info.byte_pos, (int)info.total_bytes);
return ESP_FAIL;
}
int ret = audio_element_set_total_bytes(self, info.total_bytes);
return ret;
}
static int _spiffs_read(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait, void *context)
{
spiffs_stream_t *spiffs = (spiffs_stream_t *)audio_element_getdata(self);
audio_element_info_t info;
audio_element_getinfo(self, &info);
ESP_LOGD(TAG, "read len=%d, pos=%d/%d", len, (int)info.byte_pos, (int)info.total_bytes);
int rlen = fread(buffer, 1, len, spiffs->file);
if (rlen <= 0) {
ESP_LOGW(TAG, "No more data, ret:%d", rlen);
} else {
audio_element_update_byte_pos(self, rlen);
}
return rlen;
}
static int _spiffs_write(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait, void *context)
{
spiffs_stream_t *spiffs = (spiffs_stream_t *)audio_element_getdata(self);
audio_element_info_t info;
audio_element_getinfo(self, &info);
int wlen = fwrite(buffer, 1, len, spiffs->file);
fsync(fileno(spiffs->file));
ESP_LOGD(TAG, "write:%d, errno:%d, pos:%d", wlen, errno, (int)info.byte_pos);
if (wlen > 0) {
audio_element_update_byte_pos(self, wlen);
}
return wlen;
}
static int _spiffs_process(audio_element_handle_t self, char *in_buffer, int in_len)
{
int r_size = audio_element_input(self, in_buffer, in_len);
int w_size = 0;
if (r_size > 0) {
w_size = audio_element_output(self, in_buffer, r_size);
} else {
w_size = r_size;
}
return w_size;
}
static esp_err_t _spiffs_close(audio_element_handle_t self)
{
spiffs_stream_t *spiffs = (spiffs_stream_t *)audio_element_getdata(self);
if (AUDIO_STREAM_WRITER == spiffs->type
&& spiffs->file
&& STREAM_TYPE_WAV == spiffs->w_type) {
wav_header_t *wav_info = (wav_header_t *) audio_malloc(sizeof(wav_header_t));
AUDIO_MEM_CHECK(TAG, wav_info, return ESP_ERR_NO_MEM);
if (fseek(spiffs->file, 0, SEEK_SET) != 0) {
ESP_LOGE(TAG, "Error seek file, line=%d", __LINE__);
}
audio_element_info_t info;
audio_element_getinfo(self, &info);
wav_head_init(wav_info, info.sample_rates, info.bits, info.channels);
wav_head_size(wav_info, (uint32_t)info.byte_pos);
fwrite(wav_info, 1, sizeof(wav_header_t), spiffs->file);
fsync(fileno(spiffs->file));
audio_free(wav_info);
}
if (spiffs->is_open) {
fclose(spiffs->file);
spiffs->is_open = false;
}
if (AEL_STATE_PAUSED != audio_element_get_state(self)) {
audio_element_report_pos(self);
audio_element_set_byte_pos(self, 0);
}
return ESP_OK;
}
static esp_err_t _spiffs_destroy(audio_element_handle_t self)
{
spiffs_stream_t *spiffs = (spiffs_stream_t *)audio_element_getdata(self);
audio_free(spiffs);
return ESP_OK;
}
audio_element_handle_t spiffs_stream_init(spiffs_stream_cfg_t *config)
{
audio_element_handle_t el;
spiffs_stream_t *spiffs = audio_calloc(1, sizeof(spiffs_stream_t));
AUDIO_MEM_CHECK(TAG, spiffs, return NULL);
audio_element_cfg_t cfg = DEFAULT_AUDIO_ELEMENT_CONFIG();
cfg.open = _spiffs_open;
cfg.close = _spiffs_close;
cfg.process = _spiffs_process;
cfg.destroy = _spiffs_destroy;
cfg.task_stack = config->task_stack;
cfg.task_prio = config->task_prio;
cfg.task_core = config->task_core;
cfg.out_rb_size = config->out_rb_size;
cfg.buffer_len = config->buf_sz;
if (cfg.buffer_len == 0) {
cfg.buffer_len = SPIFFS_STREAM_BUF_SIZE;
}
cfg.tag = "spiffs";
spiffs->type = config->type;
spiffs->write_header = config->write_header;
if (config->type == AUDIO_STREAM_WRITER) {
cfg.write = _spiffs_write;
} else {
cfg.read = _spiffs_read;
}
el = audio_element_init(&cfg);
AUDIO_MEM_CHECK(TAG, el, goto _spiffs_init_exit);
audio_element_setdata(el, spiffs);
return el;
_spiffs_init_exit:
audio_free(spiffs);
return NULL;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/audio_stream/spiffs_stream.c
|
C
|
apache-2.0
| 9,109
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 <stdio.h>
#include <string.h>
#include "lwip/sockets.h"
#include "esp_transport_tcp.h"
#include "esp_log.h"
#include "esp_err.h"
#include "audio_mem.h"
#include "tcp_client_stream.h"
static const char *TAG = "TCP_STREAM";
#define CONNECT_TIMEOUT_MS 100
typedef struct tcp_stream {
esp_transport_handle_t t;
audio_stream_type_t type;
int sock;
int port;
char *host;
bool is_open;
int timeout_ms;
tcp_stream_event_handle_cb hook;
void *ctx;
} tcp_stream_t;
static int _get_socket_error_code_reason(const char *str, int sockfd)
{
uint32_t optlen = sizeof(int);
int result;
int err;
err = getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &result, &optlen);
if (err == -1) {
ESP_LOGE(TAG, "%s, getsockopt failed", str);
return -1;
}
if (result != 0) {
ESP_LOGW(TAG, "%s error, error code: %d, reason: %s", str, err, strerror(result));
}
return result;
}
static esp_err_t _dispatch_event(audio_element_handle_t el, tcp_stream_t *tcp, void *data, int len, tcp_stream_status_t state)
{
if (el && tcp && tcp->hook) {
tcp_stream_event_msg_t msg = { 0 };
msg.data = data;
msg.data_len = len;
msg.sock_fd = tcp->t;
msg.source = el;
return tcp->hook(&msg, state, tcp->ctx);
}
return ESP_FAIL;
}
static esp_err_t _tcp_open(audio_element_handle_t self)
{
AUDIO_NULL_CHECK(TAG, self, return ESP_FAIL);
tcp_stream_t *tcp = (tcp_stream_t *)audio_element_getdata(self);
if (tcp->is_open) {
ESP_LOGE(TAG, "Already opened");
return ESP_FAIL;
}
ESP_LOGI(TAG, "Host is %s, port is %d\n", tcp->host, tcp->port);
esp_transport_handle_t t = esp_transport_tcp_init();
AUDIO_NULL_CHECK(TAG, t, return ESP_FAIL);
tcp->sock = esp_transport_connect(t, tcp->host, tcp->port, CONNECT_TIMEOUT_MS);
if (tcp->sock < 0) {
_get_socket_error_code_reason(__func__, tcp->sock);
esp_transport_destroy(t);
return ESP_FAIL;
}
tcp->is_open = true;
tcp->t = t;
_dispatch_event(self, tcp, NULL, 0, TCP_STREAM_STATE_CONNECTED);
return ESP_OK;
}
static esp_err_t _tcp_read(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait, void *context)
{
tcp_stream_t *tcp = (tcp_stream_t *)audio_element_getdata(self);
int rlen = esp_transport_read(tcp->t, buffer, len, tcp->timeout_ms);
if (rlen < 0) {
_get_socket_error_code_reason(__func__, tcp->sock);
return ESP_FAIL;
} else if (rlen == 0) {
ESP_LOGI(TAG, "Get end of the file");
} else {
audio_element_update_byte_pos(self, rlen);
}
ESP_LOGD(TAG, "read len=%d, rlen=%d", len, rlen);
return rlen;
}
static esp_err_t _tcp_write(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait, void *context)
{
tcp_stream_t *tcp = (tcp_stream_t *)audio_element_getdata(self);
int wlen = esp_transport_write(tcp->t, buffer, len, tcp->timeout_ms);
if (wlen < 0) {
_get_socket_error_code_reason(__func__, tcp->sock);
return ESP_FAIL;
}
ESP_LOGD(TAG, "write len=%d, rlen=%d", len, wlen);
return wlen;
}
static esp_err_t _tcp_process(audio_element_handle_t self, char *in_buffer, int in_len)
{
int r_size = audio_element_input(self, in_buffer, in_len);
int w_size = 0;
if (r_size > 0) {
w_size = audio_element_output(self, in_buffer, r_size);
if (w_size > 0) {
audio_element_update_byte_pos(self, r_size);
}
} else {
w_size = r_size;
}
return w_size;
}
static esp_err_t _tcp_close(audio_element_handle_t self)
{
AUDIO_NULL_CHECK(TAG, self, return ESP_FAIL);
tcp_stream_t *tcp = (tcp_stream_t *)audio_element_getdata(self);
AUDIO_NULL_CHECK(TAG, tcp, return ESP_FAIL);
if (!tcp->is_open) {
ESP_LOGE(TAG, "Already closed");
return ESP_FAIL;
}
if (-1 == esp_transport_close(tcp->t)) {
ESP_LOGE(TAG, "TCP stream close failed");
return ESP_FAIL;
}
tcp->is_open = false;
if (AEL_STATE_PAUSED != audio_element_get_state(self)) {
audio_element_set_byte_pos(self, 0);
}
return ESP_OK;
}
static esp_err_t _tcp_destroy(audio_element_handle_t self)
{
AUDIO_NULL_CHECK(TAG, self, return ESP_FAIL);
tcp_stream_t *tcp = (tcp_stream_t *)audio_element_getdata(self);
AUDIO_NULL_CHECK(TAG, tcp, return ESP_FAIL);
if (tcp->t) {
esp_transport_destroy(tcp->t);
tcp->t = NULL;
}
audio_free(tcp);
return ESP_OK;
}
audio_element_handle_t tcp_stream_init(tcp_stream_cfg_t *config)
{
AUDIO_NULL_CHECK(TAG, config, return NULL);
audio_element_cfg_t cfg = DEFAULT_AUDIO_ELEMENT_CONFIG();
audio_element_handle_t el;
cfg.open = _tcp_open;
cfg.close = _tcp_close;
cfg.process = _tcp_process;
cfg.destroy = _tcp_destroy;
cfg.task_stack = config->task_stack;
cfg.task_prio = config->task_prio;
cfg.task_core = config->task_core;
cfg.stack_in_ext = config->ext_stack;
cfg.tag = "tcp_client";
if (cfg.buffer_len == 0) {
cfg.buffer_len = TCP_STREAM_BUF_SIZE;
}
tcp_stream_t *tcp = audio_calloc(1, sizeof(tcp_stream_t));
AUDIO_MEM_CHECK(TAG, tcp, return NULL);
tcp->type = config->type;
tcp->port = config->port;
tcp->host = config->host;
tcp->timeout_ms = config->timeout_ms;
if (config->event_handler) {
tcp->hook = config->event_handler;
if (config->event_ctx) {
tcp->ctx = config->event_ctx;
}
}
if (config->type == AUDIO_STREAM_WRITER) {
cfg.write = _tcp_write;
} else {
cfg.read = _tcp_read;
}
el = audio_element_init(&cfg);
AUDIO_MEM_CHECK(TAG, el, goto _tcp_init_exit);
audio_element_setdata(el, tcp);
return el;
_tcp_init_exit:
audio_free(tcp);
return NULL;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/audio_stream/tcp_client_stream.c
|
C
|
apache-2.0
| 7,336
|
#
#Component Makefile
#
COMPONENT_ADD_LDFLAGS = -Wl,--whole-archive -l$(COMPONENT_NAME) -Wl,--no-whole-archive
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/audio_stream/test/component.mk
|
Makefile
|
apache-2.0
| 112
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "unity.h"
#include "esp_err.h"
#include "esp_log.h"
#include "audio_pipeline.h"
#include "audio_mem.h"
#include "fatfs_stream.h"
#include "esp_peripherals.h"
#include "board.h"
static const char *TAG = "FATFS_STREAM_TEST";
#define TEST_FATFS_READER "/sdcard/test.mp3"
#define TEST_FATFS_WRITER "/sdcard/WRITER.MP3"
static uint64_t get_file_size(const char *name)
{
FILE *f;
uint64_t size = 0;
f = fopen(name, "rb");
if (f == NULL) {
perror("Error open file");
return -1;
}
fseek(f, 0, SEEK_END);
size = ftell(f);
fclose(f);
return size;
}
static void file_size_comparison(const char *file1, const char *file2)
{
uint64_t size1 = get_file_size(file1);
uint64_t size2 = get_file_size(file2);
ESP_LOGI(TAG, "%s size is %llu, %s size is %llu", file1, size1, file2, size2);
if (size1 == size2) {
ESP_LOGI(TAG, "The two files are the same size");
} else {
ESP_LOGI(TAG, "The two files are not the same size");
}
}
TEST_CASE("fatfs stream init memory", "[esp-adf-stream]")
{
esp_log_level_set("AUDIO_ELEMENT", ESP_LOG_DEBUG);
audio_element_handle_t fatfs_stream_reader;
fatfs_stream_cfg_t fatfs_cfg = FATFS_STREAM_CFG_DEFAULT();
fatfs_cfg.type = AUDIO_STREAM_READER;
int cnt = 2000;
AUDIO_MEM_SHOW("BEFORE FATFS_STREAM_INIT MEMORY TEST");
while (cnt--) {
fatfs_stream_reader = fatfs_stream_init(&fatfs_cfg);
audio_element_deinit(fatfs_stream_reader);
}
AUDIO_MEM_SHOW("AFTER FATFS_STREAM_INIT MEMORY TEST");
}
TEST_CASE("fatfs stream read write loop", "[esp-adf-stream]")
{
audio_pipeline_handle_t pipeline;
audio_element_handle_t fatfs_stream_reader, fatfs_stream_writer;
esp_log_level_set("AUDIO_PIPELINE", ESP_LOG_DEBUG);
esp_log_level_set("AUDIO_ELEMENT", ESP_LOG_DEBUG);
esp_periph_config_t periph_cfg = DEFAULT_ESP_PERIPH_SET_CONFIG();
esp_periph_set_handle_t set = esp_periph_set_init(&periph_cfg);
TEST_ASSERT_NOT_NULL(set);
TEST_ASSERT_EQUAL(ESP_OK, audio_board_sdcard_init(set, SD_MODE_1_LINE));
audio_pipeline_cfg_t pipeline_cfg = DEFAULT_AUDIO_PIPELINE_CONFIG();
pipeline = audio_pipeline_init(&pipeline_cfg);
TEST_ASSERT_NOT_NULL(pipeline);
fatfs_stream_cfg_t fatfs_reader_cfg = FATFS_STREAM_CFG_DEFAULT();
fatfs_reader_cfg.type = AUDIO_STREAM_READER;
fatfs_stream_reader = fatfs_stream_init(&fatfs_reader_cfg);
TEST_ASSERT_NOT_NULL(fatfs_stream_reader);
fatfs_stream_cfg_t fatfs_writer_cfg = FATFS_STREAM_CFG_DEFAULT();
fatfs_writer_cfg.type = AUDIO_STREAM_WRITER;
fatfs_stream_writer = fatfs_stream_init(&fatfs_writer_cfg);
TEST_ASSERT_NOT_NULL(fatfs_stream_writer);
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, fatfs_stream_reader, "file_reader"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, fatfs_stream_writer, "file_writer"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_link(pipeline, (const char *[]) {"file_reader", "file_writer"}, 2));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_set_uri(fatfs_stream_reader, TEST_FATFS_READER));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_set_uri(fatfs_stream_writer, TEST_FATFS_WRITER));
audio_event_iface_cfg_t evt_cfg = AUDIO_EVENT_IFACE_DEFAULT_CFG();
audio_event_iface_handle_t evt = audio_event_iface_init(&evt_cfg);
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_set_listener(pipeline, evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_set_listener(esp_periph_set_get_event_iface(set), evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_run(pipeline));
while (1) {
audio_event_iface_msg_t msg;
esp_err_t ret = audio_event_iface_listen(evt, &msg, portMAX_DELAY);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "[ * ] Event interface error : %d", ret);
continue;
}
if (msg.source_type == AUDIO_ELEMENT_TYPE_ELEMENT && msg.source == (void *) fatfs_stream_reader
&& msg.cmd == AEL_MSG_CMD_REPORT_STATUS
&& (((int)msg.data == AEL_STATUS_STATE_STOPPED) || ((int)msg.data == AEL_STATUS_STATE_FINISHED))) {
ESP_LOGW(TAG, "[ * ] Stop event received");
break;
}
}
file_size_comparison(TEST_FATFS_READER, TEST_FATFS_WRITER);
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_terminate(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, fatfs_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, fatfs_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_remove_listener(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_stop_all(set));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_remove_listener(esp_periph_set_get_event_iface(set), evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_destroy(evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_deinit(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(fatfs_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(fatfs_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_destroy(set));
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/audio_stream/test/fatfs_stream_test.c
|
C
|
apache-2.0
| 6,421
|
#!/user/bin/env python
# ESPRESSIF MIT License
#
# Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
#
# Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
# it is 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.
import os, datetime, sys, urlparse
import SimpleHTTPServer, BaseHTTPServer
import wave
PORT = 8000
HOST = '192.168.199.168'
class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def _set_headers(self, length):
self.send_response(200)
if length > 0:
self.send_header('Content-length', str(length))
self.end_headers()
def _get_chunk_size(self):
data = self.rfile.read(2)
while data[-2:] != b"\r\n":
data += self.rfile.read(1)
return int(data[:-2], 16)
def _get_chunk_data(self, chunk_size):
data = self.rfile.read(chunk_size)
self.rfile.read(2)
return data
def _write_file(self, data):
t = datetime.datetime.utcnow()
time = t.strftime('%Y%m%dT%H%M%SZ')
filename = str.format('{}.mp3', time)
file = open(filename, 'wb')
file.write(bytearray(data))
file.close()
return filename
def do_POST(self):
urlparts = urlparse.urlparse(self.path)
request_file_path = urlparts.path.strip('/')
total_bytes = 0
if (request_file_path == 'upload'):
data = []
# https://stackoverflow.com/questions/24500752/how-can-i-read-exactly-one-response-chunk-with-pythons-http-client
while True:
chunk_size = self._get_chunk_size()
total_bytes += chunk_size
print("Total bytes received: {}".format(total_bytes))
sys.stdout.write("\033[F")
if (chunk_size == 0):
break
else:
chunk_data = self._get_chunk_data(chunk_size)
data += chunk_data
filename = self._write_file(data)
body = 'File {} was written, size {}'.format(filename, total_bytes)
self._set_headers(len(body))
else:
return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
httpd = BaseHTTPServer.HTTPServer((HOST, PORT), Handler)
print("Serving HTTP on {} port {}".format(HOST, PORT));
httpd.serve_forever()
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/audio_stream/test/http_server_read.py
|
Python
|
apache-2.0
| 3,353
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "unity.h"
#include "esp_wifi.h"
#include "esp_http_client.h"
#include "nvs_flash.h"
#include "esp_log.h"
#include "audio_pipeline.h"
#include "audio_mem.h"
#include "audio_element.h"
#include "audio_event_iface.h"
#include "http_stream.h"
#include "i2s_stream.h"
#include "fatfs_stream.h"
#include "aac_decoder.h"
#include "esp_peripherals.h"
#include "periph_wifi.h"
#include "board.h"
static const char *TAG = "HTTP STREAM UNITEST";
static const char URL_RANDOM[] = "0123456789abcdefghijklmnopqrstuvwxyuzABCDEFGHIJKLMNOPQRSTUVWXYUZ-_.!@#$&*()=:/,;?+~";
#define AAC_STREAM_URI "http://open.ls.qingting.fm/live/274/64k.m3u8?format=aac"
#define UNITEST_HTTP_SERVRE_URI "http://192.168.199.168:8000/upload"
#define UNITETS_HTTP_STREAM_WIFI_SSID "ESPRESSIF"
#define UNITETS_HTTP_STREAM_WIFI_PASSWD "espressif"
TEST_CASE("http stream init memory", "[esp-adf-stream]")
{
esp_log_level_set("AUDIO_ELEMENT", ESP_LOG_DEBUG);
audio_element_handle_t http_stream_reader;
http_stream_cfg_t http_cfg = HTTP_STREAM_CFG_DEFAULT();
http_cfg.event_handle = NULL;
http_cfg.type = AUDIO_STREAM_READER;
http_cfg.enable_playlist_parser = true;
int cnt = 2000;
AUDIO_MEM_SHOW("BEFORE HTTP_STREAM_INIT MEMORY TEST");
while (cnt--) {
http_stream_reader = http_stream_init(&http_cfg);
audio_element_deinit(http_stream_reader);
}
AUDIO_MEM_SHOW("AFTER HTTP_STREAM_INIT MEMORY TEST");
}
TEST_CASE("http stream url test", "[esp-adf-stream]")
{
int url_len = 0;
int url_real_len = 0;
char s[2] = {0};
char url_rand[1024];
int url_rand_t = strlen(URL_RANDOM);
char *url = (char *)malloc(1024 + sizeof("http://"));
audio_element_handle_t http_stream_reader;
http_stream_cfg_t http_cfg = HTTP_STREAM_CFG_DEFAULT();
http_cfg.event_handle = NULL;
http_cfg.type = AUDIO_STREAM_READER;
http_cfg.enable_playlist_parser = true;
http_stream_reader = http_stream_init(&http_cfg);
srand((unsigned int)time((time_t*)NULL));
for (int cnt = 0; cnt < 100; cnt++) {
memset(url, 0x00, sizeof("http://"));
strcpy(url, "http://");
url_len = (rand() % 1024);
for ( url_real_len = 0; url_real_len < url_len; url_real_len++) {
sprintf(s, "%c", URL_RANDOM[rand() % (url_rand_t) ]);
strcat(url_rand, s);
}
strcat(url, url_rand);
url[url_len + sizeof("http://") - 1] = '\0';
audio_element_set_uri(http_stream_reader, AAC_STREAM_URI);
}
free(url);
url = NULL;
}
int _http_living_stream_event_handle(http_stream_event_msg_t *msg)
{
if (msg->event_id == HTTP_STREAM_RESOLVE_ALL_TRACKS) {
return ESP_OK;
}
if (msg->event_id == HTTP_STREAM_FINISH_TRACK) {
return http_stream_next_track(msg->el);
}
if (msg->event_id == HTTP_STREAM_FINISH_PLAYLIST) {
return http_stream_restart(msg->el);
}
return ESP_OK;
}
static esp_err_t _http_stream_event_handle(http_stream_event_msg_t *msg)
{
esp_http_client_handle_t http = (esp_http_client_handle_t)msg->http_client;
char len_buf[16];
static int total_write = 0;
if (msg->event_id == HTTP_STREAM_PRE_REQUEST) {
return ESP_OK;
}
if (msg->event_id == HTTP_STREAM_ON_REQUEST) {
// write data
int wlen = sprintf(len_buf, "%x\r\n", msg->buffer_len);
if (esp_http_client_write(http, len_buf, wlen) <= 0) {
return ESP_FAIL;
}
if (esp_http_client_write(http, msg->buffer, msg->buffer_len) <= 0) {
return ESP_FAIL;
}
if (esp_http_client_write(http, "\r\n", 2) <= 0) {
return ESP_FAIL;
}
total_write += msg->buffer_len;
printf("\033[A\33[2K\rTotal bytes written: %d\n", total_write);
return msg->buffer_len;
}
if (msg->event_id == HTTP_STREAM_POST_REQUEST) {
if (esp_http_client_write(http, "0\r\n\r\n", 5) <= 0) {
return ESP_FAIL;
}
return ESP_OK;
}
if (msg->event_id == HTTP_STREAM_FINISH_REQUEST) {
char *buf = calloc(1, 64);
assert(buf);
int read_len = esp_http_client_read(http, buf, 64);
if (read_len <= 0) {
free(buf);
return ESP_FAIL;
}
buf[read_len] = 0;
free(buf);
return ESP_OK;
}
return ESP_OK;
}
TEST_CASE("http stream read", "[esp-adf-stream]")
{
audio_pipeline_handle_t pipeline;
audio_element_handle_t http_stream_reader, fatfs_stream_writer;
esp_log_level_set("AUDIO_PIPELINE", ESP_LOG_DEBUG);
esp_log_level_set("AUDIO_ELEMENT", ESP_LOG_DEBUG);
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES) {
ESP_ERROR_CHECK(nvs_flash_erase());
err = nvs_flash_init();
}
tcpip_adapter_init();
esp_periph_config_t periph_cfg = DEFAULT_ESP_PERIPH_SET_CONFIG();
esp_periph_set_handle_t set = esp_periph_set_init(&periph_cfg);
TEST_ASSERT_NOT_NULL(set);
TEST_ASSERT_EQUAL(ESP_OK, audio_board_sdcard_init(set, SD_MODE_1_LINE));
periph_wifi_cfg_t wifi_cfg = {
.ssid = UNITETS_HTTP_STREAM_WIFI_SSID,
.password = UNITETS_HTTP_STREAM_WIFI_SSID,
};
esp_periph_handle_t wifi_handle = periph_wifi_init(&wifi_cfg);
TEST_ASSERT_NOT_NULL(wifi_handle);
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_start(set, wifi_handle));
TEST_ASSERT_EQUAL(ESP_OK, periph_wifi_wait_for_connected(wifi_handle, portMAX_DELAY));
audio_board_handle_t board_handle = audio_board_init();
TEST_ASSERT_EQUAL(ESP_OK, audio_hal_ctrl_codec(board_handle->audio_hal, AUDIO_HAL_CODEC_MODE_ENCODE, AUDIO_HAL_CTRL_START));
audio_pipeline_cfg_t pipeline_cfg = DEFAULT_AUDIO_PIPELINE_CONFIG();
pipeline = audio_pipeline_init(&pipeline_cfg);
TEST_ASSERT_NOT_NULL(pipeline);
fatfs_stream_cfg_t fatfs_cfg = FATFS_STREAM_CFG_DEFAULT();
fatfs_cfg.type = AUDIO_STREAM_WRITER;
fatfs_stream_writer = fatfs_stream_init(&fatfs_cfg);
TEST_ASSERT_NOT_NULL(fatfs_stream_writer);
TEST_ASSERT_EQUAL(ESP_OK, audio_element_set_uri(fatfs_stream_writer, "/sdcard/test.mp3"));
http_stream_cfg_t http_cfg = HTTP_STREAM_CFG_DEFAULT();
http_cfg.type = AUDIO_STREAM_READER;
http_stream_reader = http_stream_init(&http_cfg);
TEST_ASSERT_NOT_NULL(http_stream_reader);
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, http_stream_reader, "http"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, fatfs_stream_writer, "fatfs"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_link(pipeline, (const char *[]) { "http", "fatfs" }, 2));
audio_event_iface_cfg_t evt_cfg = AUDIO_EVENT_IFACE_DEFAULT_CFG();
audio_event_iface_handle_t evt = audio_event_iface_init(&evt_cfg);
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_set_listener(pipeline, evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_set_listener(esp_periph_set_get_event_iface(set), evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_set_uri(http_stream_reader, "https://dl.espressif.com/dl/audio/ff-16b-2c-44100hz.mp3"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_run(pipeline));
while (1) {
audio_event_iface_msg_t msg;
esp_err_t ret = audio_event_iface_listen(evt, &msg, portMAX_DELAY);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "[ * ] Event interface error : %d", ret);
continue;
}
if (msg.source_type == AUDIO_ELEMENT_TYPE_ELEMENT && msg.source == (void *) http_stream_reader
&& msg.cmd == AEL_MSG_CMD_REPORT_STATUS && (int) msg.data == AEL_STATUS_ERROR_OPEN) {
break;
continue;
}
}
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_terminate(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, http_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, fatfs_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_remove_listener(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_stop_all(set));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_remove_listener(esp_periph_set_get_event_iface(set), evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_destroy(evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_deinit(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(http_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(fatfs_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_destroy(set));
}
/*
* Note : Before run this unitest, please run the http_server_read.py, and Confirm server ip in UNITEST_HTTP_SERVRE_URI
*/
TEST_CASE("http stream write", "[esp-adf-stream]")
{
esp_log_level_set("AUDIO_PIPELINE", ESP_LOG_DEBUG);
esp_log_level_set("AUDIO_ELEMENT", ESP_LOG_DEBUG);
audio_pipeline_handle_t pipeline;
audio_element_handle_t http_stream_writer, fatfs_stream_reader;
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES) {
ESP_ERROR_CHECK(nvs_flash_erase());
err = nvs_flash_init();
}
tcpip_adapter_init();
esp_periph_config_t periph_cfg = DEFAULT_ESP_PERIPH_SET_CONFIG();
esp_periph_set_handle_t set = esp_periph_set_init(&periph_cfg);
TEST_ASSERT_NOT_NULL(set);
TEST_ASSERT_EQUAL(ESP_OK, audio_board_sdcard_init(set, SD_MODE_1_LINE));
periph_wifi_cfg_t wifi_cfg = {
.ssid = UNITETS_HTTP_STREAM_WIFI_SSID,
.password = UNITETS_HTTP_STREAM_WIFI_PASSWD,
};
esp_periph_handle_t wifi_handle = periph_wifi_init(&wifi_cfg);
TEST_ASSERT_NOT_NULL(wifi_handle);
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_start(set, wifi_handle));
TEST_ASSERT_EQUAL(ESP_OK, periph_wifi_wait_for_connected(wifi_handle, portMAX_DELAY));
audio_board_handle_t board_handle = audio_board_init();
TEST_ASSERT_EQUAL(ESP_OK, audio_hal_ctrl_codec(board_handle->audio_hal, AUDIO_HAL_CODEC_MODE_ENCODE, AUDIO_HAL_CTRL_START));
audio_pipeline_cfg_t pipeline_cfg = DEFAULT_AUDIO_PIPELINE_CONFIG();
pipeline = audio_pipeline_init(&pipeline_cfg);
TEST_ASSERT_NOT_NULL(pipeline);
fatfs_stream_cfg_t fatfs_cfg = FATFS_STREAM_CFG_DEFAULT();
fatfs_cfg.type = AUDIO_STREAM_READER;
fatfs_stream_reader = fatfs_stream_init(&fatfs_cfg);
TEST_ASSERT_EQUAL(ESP_OK, audio_element_set_uri(fatfs_stream_reader, "/sdcard/test.mp3"));
http_stream_cfg_t http_cfg = HTTP_STREAM_CFG_DEFAULT();
http_cfg.type = AUDIO_STREAM_WRITER;
http_cfg.event_handle = _http_stream_event_handle;
http_stream_writer = http_stream_init(&http_cfg);
TEST_ASSERT_NOT_NULL(http_stream_writer);
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, fatfs_stream_reader, "fatfs"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, http_stream_writer, "http"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_link(pipeline, (const char *[]) {"fatfs", "http"}, 2));
audio_event_iface_cfg_t evt_cfg = AUDIO_EVENT_IFACE_DEFAULT_CFG();
audio_event_iface_handle_t evt = audio_event_iface_init(&evt_cfg);
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_set_listener(pipeline, evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_set_listener(esp_periph_set_get_event_iface(set), evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_set_uri(http_stream_writer, UNITEST_HTTP_SERVRE_URI));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_run(pipeline));
while (1) {
audio_event_iface_msg_t msg;
esp_err_t ret = audio_event_iface_listen(evt, &msg, portMAX_DELAY);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "[ * ] Event interface error : %d", ret);
continue;
}
if (msg.source_type == AUDIO_ELEMENT_TYPE_ELEMENT && msg.source == (void *) http_stream_writer
&& msg.cmd == AEL_MSG_CMD_REPORT_STATUS && (int) msg.data == AEL_STATUS_ERROR_OPEN) {
break;
continue;
}
}
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_terminate(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, http_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, fatfs_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_remove_listener(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_stop_all(set));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_remove_listener(esp_periph_set_get_event_iface(set), evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_destroy(evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_deinit(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(http_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(fatfs_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK,esp_periph_set_destroy(set));
}
TEST_CASE("http stream living test", "[esp-adf-stream]")
{
esp_log_level_set("AUDIO_PIPELINE", ESP_LOG_DEBUG);
esp_log_level_set("AUDIO_ELEMENT", ESP_LOG_DEBUG);
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES) {
TEST_ASSERT_EQUAL(ESP_OK, nvs_flash_erase());
err = nvs_flash_init();
}
tcpip_adapter_init();
audio_pipeline_handle_t pipeline;
audio_element_handle_t http_stream_reader, i2s_stream_writer, aac_decoder;
audio_board_handle_t board_handle = audio_board_init();
TEST_ASSERT_NOT_NULL(board_handle);
TEST_ASSERT_EQUAL(ESP_OK,audio_hal_ctrl_codec(board_handle->audio_hal, AUDIO_HAL_CODEC_MODE_DECODE, AUDIO_HAL_CTRL_START));
audio_pipeline_cfg_t pipeline_cfg = DEFAULT_AUDIO_PIPELINE_CONFIG();
pipeline = audio_pipeline_init(&pipeline_cfg);
TEST_ASSERT_NOT_NULL(pipeline);
http_stream_cfg_t http_cfg = HTTP_STREAM_CFG_DEFAULT();
http_cfg.event_handle = _http_living_stream_event_handle;
http_cfg.type = AUDIO_STREAM_READER;
http_cfg.enable_playlist_parser = true;
http_stream_reader = http_stream_init(&http_cfg);
TEST_ASSERT_NOT_NULL(http_stream_reader);
i2s_stream_cfg_t i2s_cfg = I2S_STREAM_CFG_DEFAULT();
i2s_cfg.type = AUDIO_STREAM_WRITER;
i2s_stream_writer = i2s_stream_init(&i2s_cfg);
TEST_ASSERT_NOT_NULL(i2s_stream_writer);
aac_decoder_cfg_t aac_cfg = DEFAULT_AAC_DECODER_CONFIG();
aac_decoder = aac_decoder_init(&aac_cfg);
TEST_ASSERT_NOT_NULL(aac_decoder);
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, http_stream_reader, "http"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, aac_decoder, "aac"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, i2s_stream_writer, "i2s"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_link(pipeline, (const char *[]) {"http", "aac", "i2s"}, 3));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_set_uri(http_stream_reader, AAC_STREAM_URI));
esp_periph_config_t periph_cfg = DEFAULT_ESP_PERIPH_SET_CONFIG();
esp_periph_set_handle_t set = esp_periph_set_init(&periph_cfg);
TEST_ASSERT_NOT_NULL(set);
periph_wifi_cfg_t wifi_cfg = {
.ssid = UNITETS_HTTP_STREAM_WIFI_SSID,
.password = UNITETS_HTTP_STREAM_WIFI_PASSWD,
};
esp_periph_handle_t wifi_handle = periph_wifi_init(&wifi_cfg);
TEST_ASSERT_NOT_NULL(wifi_handle);
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_start(set, wifi_handle));
TEST_ASSERT_EQUAL(ESP_OK, periph_wifi_wait_for_connected(wifi_handle, portMAX_DELAY));
audio_event_iface_cfg_t evt_cfg = AUDIO_EVENT_IFACE_DEFAULT_CFG();
audio_event_iface_handle_t evt = audio_event_iface_init(&evt_cfg);
TEST_ASSERT_NOT_NULL(evt);
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_set_listener(pipeline, evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_set_listener(esp_periph_set_get_event_iface(set), evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_run(pipeline));
while (1) {
audio_event_iface_msg_t msg;
esp_err_t ret = audio_event_iface_listen(evt, &msg, portMAX_DELAY);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "[ * ] Event interface error : %d", ret);
continue;
}
if (msg.source_type == AUDIO_ELEMENT_TYPE_ELEMENT
&& msg.source == (void *) aac_decoder
&& msg.cmd == AEL_MSG_CMD_REPORT_MUSIC_INFO) {
audio_element_info_t music_info = {0};
TEST_ASSERT_EQUAL(ESP_OK, audio_element_getinfo(aac_decoder, &music_info));
ESP_LOGI(TAG, "[ * ] Receive music info from aac decoder, sample_rates=%d, bits=%d, ch=%d",
music_info.sample_rates, music_info.bits, music_info.channels);
TEST_ASSERT_EQUAL(ESP_OK, audio_element_setinfo(i2s_stream_writer, &music_info));
TEST_ASSERT_EQUAL(ESP_OK, i2s_stream_set_clk(i2s_stream_writer, music_info.sample_rates, music_info.bits, music_info.channels));
continue;
}
/* restart stream when the first pipeline element (http_stream_reader in this case) receives stop event (caused by reading errors) */
if (msg.source_type == AUDIO_ELEMENT_TYPE_ELEMENT && msg.source == (void *) http_stream_reader
&& msg.cmd == AEL_MSG_CMD_REPORT_STATUS && (int) msg.data == AEL_STATUS_ERROR_OPEN) {
ESP_LOGW(TAG, "[ * ] Restart stream");
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_stop(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_wait_for_stop(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_reset_state(aac_decoder));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_reset_state(i2s_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_reset_ringbuffer(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_reset_items_state(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_run(pipeline));
continue;
}
}
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_terminate(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, http_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, i2s_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, aac_decoder));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_remove_listener(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_stop_all(set));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_remove_listener(esp_periph_set_get_event_iface(set), evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_destroy(evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_deinit(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(http_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(i2s_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(aac_decoder));
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_destroy(set));
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/audio_stream/test/http_stream_test.c
|
C
|
apache-2.0
| 20,075
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 <string.h>
#include "unity.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "sdkconfig.h"
#include "audio_element.h"
#include "audio_pipeline.h"
#include "audio_event_iface.h"
#include "audio_common.h"
#include "fatfs_stream.h"
#include "i2s_stream.h"
#include "mp3_decoder.h"
#include "esp_peripherals.h"
#include "periph_sdcard.h"
#include "audio_alc.h"
#include "audio_mem.h"
#include "board.h"
static const char *TAG = "USE_ALC_EXAMPLE";
typedef struct {
int rate;
int bits;
int ch;
} unitest_i2s_clk__t;
static unitest_i2s_clk__t unitest_i2s_clk[] = {
{8000, 16, 1},
{8000, 32, 1},
{8000, 32, 2},
{16000, 16, 1},
{16000, 32, 1},
{16000, 32, 2},
{32000, 16, 1},
{32000, 32, 1},
{32000, 32, 2},
{48000, 16, 1},
{48000, 16, 2},
{48000, 32, 2},
{48000, 32, 2},
};
static void i2s_volume_alc_task(void *pvParamters)
{
int volume_val = -20;
int vol = 0;
TEST_ASSERT_NOT_NULL(pvParamters);
audio_element_handle_t i2s_stream = (audio_element_handle_t)pvParamters;
while (1)
{
volume_val += 1;
if (volume_val > 20) {
volume_val = -20;
}
ESP_LOGI(TAG, "set vol is %d\n", volume_val);
TEST_ASSERT_EQUAL(ESP_OK, i2s_alc_volume_set(i2s_stream, volume_val));
TEST_ASSERT_EQUAL(ESP_OK, i2s_alc_volume_get(i2s_stream, &vol));
ESP_LOGI(TAG, "get vol is %d\n", vol);
vTaskDelay(200 / portTICK_PERIOD_MS);
}
vTaskDelete(NULL);
}
TEST_CASE("i2s stream init memory test", "[esp-adf-stream]")
{
audio_element_handle_t i2s_stream_writer;
i2s_stream_cfg_t i2s_cfg = I2S_STREAM_CFG_DEFAULT();
i2s_cfg.type = AUDIO_STREAM_WRITER;
int cnt = 2000;
AUDIO_MEM_SHOW("BEFORE I2S_STREAM_INIT MEMORY TEST");
while (cnt--) {
i2s_stream_writer = i2s_stream_init(&i2s_cfg);
audio_element_deinit(i2s_stream_writer);
}
AUDIO_MEM_SHOW("AFTER I2S_STREAM_INIT MEMORY TEST");
}
TEST_CASE("i2s_stream alc test", "[esp-adf-stream]")
{
audio_pipeline_handle_t pipeline;
audio_element_handle_t fatfs_stream_reader, i2s_stream_writer, mp3_decoder;
esp_log_level_set("AUDIO_PIPELINE", ESP_LOG_DEBUG);
esp_log_level_set("AUDIO_ELEMENT", ESP_LOG_DEBUG);
esp_periph_config_t periph_cfg = DEFAULT_ESP_PERIPH_SET_CONFIG();
esp_periph_set_handle_t set = esp_periph_set_init(&periph_cfg);
TEST_ASSERT_NOT_NULL(set);
TEST_ASSERT_EQUAL(ESP_OK, audio_board_sdcard_init(set, SD_MODE_1_LINE));
audio_board_handle_t board_handle = audio_board_init();
TEST_ASSERT_EQUAL(ESP_OK, audio_hal_ctrl_codec(board_handle->audio_hal, AUDIO_HAL_CODEC_MODE_DECODE, AUDIO_HAL_CTRL_START));
audio_pipeline_cfg_t pipeline_cfg = DEFAULT_AUDIO_PIPELINE_CONFIG();
pipeline = audio_pipeline_init(&pipeline_cfg);
TEST_ASSERT_NOT_NULL(pipeline);
fatfs_stream_cfg_t fatfs_cfg = FATFS_STREAM_CFG_DEFAULT();
fatfs_cfg.type = AUDIO_STREAM_READER;
fatfs_stream_reader = fatfs_stream_init(&fatfs_cfg);
TEST_ASSERT_NOT_NULL(fatfs_stream_reader);
i2s_stream_cfg_t i2s_cfg = I2S_STREAM_CFG_DEFAULT();
i2s_cfg.type = AUDIO_STREAM_WRITER;
i2s_cfg.use_alc = true;
i2s_stream_writer = i2s_stream_init(&i2s_cfg);
TEST_ASSERT_NOT_NULL(fatfs_stream_reader);
mp3_decoder_cfg_t mp3_cfg = DEFAULT_MP3_DECODER_CONFIG();
mp3_decoder = mp3_decoder_init(&mp3_cfg);
TEST_ASSERT_NOT_NULL(mp3_decoder);
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, fatfs_stream_reader, "file"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, mp3_decoder, "mp3"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, i2s_stream_writer, "i2s"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_link(pipeline, (const char *[]) {"file", "mp3", "i2s"}, 3));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_set_uri(fatfs_stream_reader, "/sdcard/test.mp3"));
audio_event_iface_cfg_t evt_cfg = AUDIO_EVENT_IFACE_DEFAULT_CFG();
audio_event_iface_handle_t evt = audio_event_iface_init(&evt_cfg);
TEST_ASSERT_NOT_NULL(evt);
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_set_listener(pipeline, evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_set_listener(esp_periph_set_get_event_iface(set), evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_run(pipeline));
xTaskCreate(i2s_volume_alc_task, "i2s_volume_alc_task", 4096, (void *)i2s_stream_writer, 9, NULL);
while (1) {
audio_event_iface_msg_t msg;
esp_err_t ret = audio_event_iface_listen(evt, &msg, portMAX_DELAY);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "[ * ] Event interface error : %d", ret);
continue;
}
if (msg.source_type == AUDIO_ELEMENT_TYPE_ELEMENT && msg.source == (void *)mp3_decoder
&& msg.cmd == AEL_MSG_CMD_REPORT_MUSIC_INFO) {
audio_element_info_t music_info = {0};
TEST_ASSERT_EQUAL(ESP_OK, audio_element_getinfo(mp3_decoder, &music_info));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_setinfo(i2s_stream_writer, &music_info));
TEST_ASSERT_EQUAL(ESP_OK, i2s_stream_set_clk(i2s_stream_writer, music_info.sample_rates, music_info.bits,
music_info.channels));
continue;
}
if (msg.source_type == AUDIO_ELEMENT_TYPE_ELEMENT && msg.source == (void *)i2s_stream_writer
&& msg.cmd == AEL_MSG_CMD_REPORT_STATUS && (int)msg.data == AEL_STATUS_STATE_STOPPED) {
ESP_LOGW(TAG, "[ * ] Stop event received");
break;
}
}
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_terminate(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, fatfs_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, i2s_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, mp3_decoder));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_remove_listener(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_stop_all(set));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_remove_listener(esp_periph_set_get_event_iface(set), evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_destroy(evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_deinit(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(fatfs_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(i2s_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(mp3_decoder));
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_destroy(set));
}
TEST_CASE("i2s_stream write_read_loop", "[esp-adf-stream]")
{
audio_pipeline_handle_t pipeline;
audio_element_handle_t i2s_stream_reader, i2s_stream_writer;
audio_board_handle_t board_handle = audio_board_init();
audio_hal_ctrl_codec(board_handle->audio_hal, AUDIO_HAL_CODEC_MODE_ENCODE, AUDIO_HAL_CTRL_START);
audio_pipeline_cfg_t pipeline_cfg = DEFAULT_AUDIO_PIPELINE_CONFIG();
pipeline = audio_pipeline_init(&pipeline_cfg);
TEST_ASSERT_NOT_NULL(pipeline);
i2s_stream_cfg_t i2s_cfg_read = I2S_STREAM_CFG_DEFAULT();
i2s_cfg_read.type = AUDIO_STREAM_READER;
i2s_stream_reader = i2s_stream_init(&i2s_cfg_read);
TEST_ASSERT_NOT_NULL(i2s_stream_reader);
i2s_stream_cfg_t i2s_cfg_writer = I2S_STREAM_CFG_DEFAULT();
i2s_cfg_writer.type = AUDIO_STREAM_WRITER;
i2s_stream_writer = i2s_stream_init(&i2s_cfg_writer);
TEST_ASSERT_NOT_NULL(i2s_stream_writer);
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, i2s_stream_reader, "i2s_read"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, i2s_stream_writer, "i2s_write"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_link(pipeline, (const char *[]) {"i2s_read", "i2s_write"}, 2));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_run(pipeline));
for (size_t i = 10; i > 0; i--) {
ESP_LOGI(TAG, "test time: %d", i);
}
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_terminate(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, i2s_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, i2s_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_remove_listener(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_deinit(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(i2s_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(i2s_stream_writer));
ESP_LOGI(TAG, "finished the [i2s read write loop test]");
}
TEST_CASE("i2s_stream_clk", "[esp-adf-stream]")
{
audio_element_handle_t i2s_stream_reader;
i2s_stream_cfg_t i2s_cfg = I2S_STREAM_CFG_DEFAULT();
i2s_cfg.type = AUDIO_STREAM_READER;
i2s_stream_reader = i2s_stream_init(&i2s_cfg);
TEST_ASSERT_NOT_NULL(i2s_stream_reader);
for (size_t i = 0; i < (sizeof(unitest_i2s_clk)/sizeof(unitest_i2s_clk[0])); i++) {
ESP_LOGI(TAG, "rate is %d, bits is %d, ch is %d", unitest_i2s_clk[i].rate, unitest_i2s_clk[i].bits, unitest_i2s_clk[i].ch);
TEST_ASSERT_EQUAL(ESP_OK, i2s_stream_set_clk(i2s_stream_reader, unitest_i2s_clk[i].rate, unitest_i2s_clk[i].bits, unitest_i2s_clk[i].ch));
}
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/audio_stream/test/i2s_stream_test.c
|
C
|
apache-2.0
| 10,463
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 <string.h>
#include "unity.h"
#include "esp_log.h"
#include "esp_err.h"
#include "audio_mem.h"
#include "audio_pipeline.h"
#include "esp_peripherals.h"
#include "spiffs_stream.h"
#include "periph_spiffs.h"
static const char *TAG = "SPIFFS_STREAM_TEST";
static uint64_t get_file_size(const char *name)
{
FILE *f;
int size = 0;
f = fopen(name, "rb");
if (f == NULL) {
return -1;
}
fseek(f, 0, SEEK_END);
size = ftell(f);
fclose(f);
return size;
}
static void comparison_file_size(const char *file1, const char *file2)
{
uint64_t size1 = get_file_size(file1);
TEST_ASSERT_TRUE(size1 >= 0);
uint64_t size2 = get_file_size(file2);
TEST_ASSERT_TRUE(size2 >= 0);
if (size1 == size2) {
ESP_LOGI(TAG, "spiffs test successful");
} else {
ESP_LOGI(TAG, "spiffs test failed");
}
}
TEST_CASE("spiffs stream init memory test", "esp-adf-stream")
{
audio_element_handle_t spiffs_stream_reader;
periph_spiffs_cfg_t spiffs_cfg = {
.root = "/spiffs",
.partition_label = NULL,
.max_files = 5,
.format_if_mount_failed = true
};
AUDIO_MEM_SHOW("BEFORE SPIFFS_STREAM_INIT MEMORY TEST");
spiffs_stream_cfg_t spiffs_reader_cfg = SPIFFS_STREAM_CFG_DEFAULT();
spiffs_reader_cfg.type = AUDIO_STREAM_READER;
int cnt = 2000;
while (cnt--) {
spiffs_stream_reader = spiffs_stream_init(&spiffs_reader_cfg);
audio_element_deinit(spiffs_stream_reader);
}
AUDIO_MEM_SHOW("BEFORE SPIFFS_STREAM_INIT MEMORY TEST");
}
/*
* Note Before run this unitest, please prepare the following two steps
* step1 mofify you partition table, For example add "storage, data, spiffs, 0x110000,1M" in partition table
* step2 download esp-audio.bin in flash, the download address is 0x110000
*/
TEST_CASE("Spiffs stream read and write loop test", "[esp-adf-stream]")
{
audio_pipeline_handle_t pipeline;
audio_element_handle_t spiffs_stream_reader, spiffs_stream_writer;
esp_log_level_set("AUDIO_PIPELINE", ESP_LOG_DEBUG);
esp_log_level_set("AUDIO_ELEMENT", ESP_LOG_DEBUG);
esp_periph_config_t periph_cfg = DEFAULT_ESP_PERIPH_SET_CONFIG();
esp_periph_set_handle_t set = esp_periph_set_init(&periph_cfg);
TEST_ASSERT_NOT_NULL(set);
periph_spiffs_cfg_t spiffs_cfg = {
.root = "/spiffs",
.partition_label = NULL,
.max_files = 5,
.format_if_mount_failed = true
};
esp_periph_handle_t spiffs_handle = periph_spiffs_init(&spiffs_cfg);
TEST_ASSERT_NOT_NULL(spiffs_handle);
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_start(set, spiffs_handle));
while (!periph_spiffs_is_mounted(spiffs_handle)) {
vTaskDelay(500 / portTICK_PERIOD_MS);
}
audio_pipeline_cfg_t pipeline_cfg = DEFAULT_AUDIO_PIPELINE_CONFIG();
pipeline = audio_pipeline_init(&pipeline_cfg);
TEST_ASSERT_NOT_NULL(pipeline);
spiffs_stream_cfg_t spiffs_reader_cfg = SPIFFS_STREAM_CFG_DEFAULT();
spiffs_reader_cfg.type = AUDIO_STREAM_READER;
spiffs_stream_reader = spiffs_stream_init(&spiffs_reader_cfg);
TEST_ASSERT_NOT_NULL(spiffs_stream_reader);
spiffs_stream_cfg_t fatfs_writer_cfg = SPIFFS_STREAM_CFG_DEFAULT();
fatfs_writer_cfg.type = AUDIO_STREAM_WRITER;
spiffs_stream_writer = spiffs_stream_init(&fatfs_writer_cfg);
TEST_ASSERT_NOT_NULL(spiffs_stream_writer);
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, spiffs_stream_reader, "spiffs_reader"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, spiffs_stream_writer, "spiffs_writer"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_link(pipeline, (const char *[]) {"spiffs_reader", "spiffs_writer"}, 2));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_set_uri(spiffs_stream_reader, "/spiffs/adf_music.mp3"));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_set_uri(spiffs_stream_writer, "/spiffs/adf_music_writer.mp3"));
audio_event_iface_cfg_t evt_cfg = AUDIO_EVENT_IFACE_DEFAULT_CFG();
audio_event_iface_handle_t evt = audio_event_iface_init(&evt_cfg);
TEST_ASSERT_NOT_NULL(evt);
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_set_listener(pipeline, evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_set_listener(esp_periph_set_get_event_iface(set), evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_run(pipeline));
while (1) {
audio_event_iface_msg_t msg = { 0 };
esp_err_t ret = audio_event_iface_listen(evt, &msg, portMAX_DELAY);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "[ * ] Event interface error : %d", ret);
continue;
}
if (msg.source_type == AUDIO_ELEMENT_TYPE_ELEMENT && msg.source == (void *) spiffs_stream_reader
&& msg.cmd == AEL_MSG_CMD_REPORT_STATUS
&& (((int)msg.data == AEL_STATUS_STATE_STOPPED) || ((int)msg.data == AEL_STATUS_STATE_FINISHED))) {
ESP_LOGW(TAG, "[ * ] Stop event received");
break;
}
}
comparison_file_size("/spiffs/adf_music.mp3", "/spiffs/adf_music_writer.mp3");
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_terminate(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, spiffs_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, spiffs_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_remove_listener(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_stop_all(set));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_remove_listener(esp_periph_set_get_event_iface(set), evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_destroy(evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_deinit(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(spiffs_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(spiffs_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_destroy(set));
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/audio_stream/test/spiffs_stream_test.c
|
C
|
apache-2.0
| 7,134
|
#!/user/bin/env python
# ESPRESSIF MIT License
#
# Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
#
# Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
# it is 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.
import socket
import sys
SERVER_PORT = 8000
SND_BUF_SIZE = 8194
def start_tcp_server(ip, port):
fo = open("esp32.mp3", "r")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (ip, port)
print("starting listen on ip %s, port %s" % server_address)
sock.bind(server_address)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, SND_BUF_SIZE)
try:
sock.listen(1)
except socket.error:
print("fail to listen on port %s" % e)
sys.exit(1)
while True:
print("waiting for client to connect")
client, addr = sock.accept()
break
msg = client.recv(1024)
if not (msg == "hello test"):
exit
msg = fo.read()
if len(msg) <= 0:
print "server read data error"
exit
client .send(msg)
fo.close()
client.close()
sock.close()
print(" close client connect ")
if __name__=='__main__':
start_tcp_server(socket.gethostbyname(socket.getfqdn(socket.gethostname())), SERVER_PORT)
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/audio_stream/test/tcp_client_stream_server_read.py
|
Python
|
apache-2.0
| 2,286
|
#!/user/bin/env python
# ESPRESSIF MIT License
#
# Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
#
# Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
# it is 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.
import socket
import sys
SERVER_PORT = 8000
RECV_BUF_SIZE = 8194
def start_tcp_server(ip, port):
fo = open("esp32.mp3", "w+")
print ("create a file named esp32.p3")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (ip, port)
print("starting listen on ip %s, port %s" % server_address)
sock.bind(server_address)
sock.settimeout(1000)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, RECV_BUF_SIZE)
try:
sock.listen(1)
except socket.error:
print("fail to listen on port %s" % e)
sys.exit(1)
while True:
print("waiting for client to connect")
client, addr = sock.accept()
break
while True:
msg = client.recv(8194)
print('recv data len ', len(msg));
if len(msg) <= 0:
break
fo.write(msg)
fo.close()
client.close()
sock.close()
print(" close client connect ")
if __name__=='__main__':
start_tcp_server(socket.gethostbyname(socket.getfqdn(socket.gethostname())), SERVER_PORT)
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/audio_stream/test/tcp_client_stream_server_write.py
|
Python
|
apache-2.0
| 2,323
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "unity.h"
#include "esp_wifi.h"
#include "esp_http_client.h"
#include "nvs_flash.h"
#include "esp_log.h"
#include "audio_pipeline.h"
#include "audio_mem.h"
#include "audio_element.h"
#include "audio_event_iface.h"
#include "tcp_client_stream.h"
#include "fatfs_stream.h"
#include "esp_peripherals.h"
#include "periph_wifi.h"
#define CONFIG_TCP_URL "192.168.199.118"
#define CONFIG_TCP_PORT 8080
static const char *TAG = "TCP_CLIENT_STREAM_TEST"
TEST_CASE("tcp client stream init memory", "[esp-adf-stream]")
{
esp_log_level_set("AUDIO_ELEMENT", ESP_LOG_DEBUG);
audio_element_handle_t tcp_stream_writer
tcp_stream_cfg_t tcp_cfg = TCP_STREAM_CFG_DEFAULT();
tcp_cfg.type = AUDIO_STREAM_WRITER;
int cnt = 2000;
AUDIO_MEM_SHOW("BEFORE TCP_CLIENT_STREAM_INIT MEMORY TEST");
while (cnt--) {
tcp_stream_writer = tcp_stream_init(&tcp_cfg);
TEST_ASSERT_NOT_NULL(tcp_stream_writer);
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(tcp_stream_writer));
}
AUDIO_MEM_SHOW("AFTER TCP_CLIENT_STREAM_INIT MEMORY TEST");
}
TEST_CASE("tcp client stream write", "[esp-adf-stream]")
{
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES) {
ESP_ERROR_CHECK(nvs_flash_erase());
err = nvs_flash_init();
}
tcpip_adapter_init();
audio_pipeline_handle_t pipeline;
audio_element_handle_t tcp_stream_writer, fatfs_stream_reader;
esp_log_level_set("*", ESP_LOG_WARN);
esp_log_level_set(TAG, ESP_LOG_DEBUG);
esp_periph_config_t periph_cfg = DEFAULT_ESP_PERIPH_SET_CONFIG();
esp_periph_set_handle_t set = esp_periph_set_init(&periph_cfg);
TEST_ASSERT_NOT_NULL(set);
TEST_ASSERT_EQUAL(ESP_OK, audio_board_sdcard_init(set, SD_MODE_1_LINE));
audio_pipeline_cfg_t pipeline_cfg = DEFAULT_AUDIO_PIPELINE_CONFIG();
pipeline = audio_pipeline_init(&pipeline_cfg);
TEST_ASSERT_NOT_NULL(pipeline);
fatfs_stream_cfg_t fatfs_cfg = FATFS_STREAM_CFG_DEFAULT();
fatfs_cfg.type = AUDIO_STREAM_READER;
fatfs_stream_reader = fatfs_stream_init(&fatfs_cfg);
TEST_ASSERT_NOT_NULL(fatfs_stream_reader);
tcp_stream_cfg_t tcp_cfg = TCP_STREAM_CFG_DEFAULT();
tcp_cfg.type = AUDIO_STREAM_WRITER;
tcp_cfg.port = CONFIG_TCP_PORT;
tcp_cfg.host = CONFIG_TCP_URL;
tcp_stream_writer = tcp_stream_init(&tcp_cfg);
TEST_ASSERT_NOT_NULL(tcp_stream_writer);
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, fatfs_stream_reader, "file"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, tcp_stream_writer, "tcp"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_link(pipeline, (const char *[]) {"file", "tcp"}, 2));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_set_uri(fatfs_stream_reader, "/sdcard/test.mp3"));
periph_wifi_cfg_t wifi_cfg = {
.ssid = CONFIG_WIFI_SSID,
.password = CONFIG_WIFI_PASSWORD,
};
esp_periph_handle_t wifi_handle = periph_wifi_init(&wifi_cfg);
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_start(set, wifi_handle));
TEST_ASSERT_EQUAL(ESP_OK, periph_wifi_wait_for_connected(wifi_handle, portMAX_DELAY));
audio_event_iface_cfg_t evt_cfg = AUDIO_EVENT_IFACE_DEFAULT_CFG();
audio_event_iface_handle_t evt = audio_event_iface_init(&evt_cfg);
TEST_ASSERT_NOT_NULL(evt);
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_set_listener(pipeline, evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_set_listener(esp_periph_set_get_event_iface(set), evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_run(pipeline));
while (1) {
audio_event_iface_msg_t msg;
esp_err_t ret = audio_event_iface_listen(evt, &msg, portMAX_DELAY);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "[ * ] Event interface error : %d", ret);
continue;
}
/* Stop when the last pipeline element (fatfs_stream_reader in this case) read stop event */
if (msg.source_type == AUDIO_ELEMENT_TYPE_ELEMENT && msg.source == (void *) fatfs_stream_reader
&& msg.cmd == AEL_MSG_CMD_REPORT_STATUS
&& (((int)msg.data == AEL_STATUS_STATE_STOPPED) || ((int)msg.data == AEL_STATUS_STATE_FINISHED))) {
ESP_LOGW(TAG, "[ * ] Stop event received");
break;
}
}
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_terminate(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, tcp_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, fatfs_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_remove_listener(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_stop_all(set));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_remove_listener(esp_periph_set_get_event_iface(set), evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_destroy(evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_deinit(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(tcp_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(fatfs_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_destroy(set));
}
TEST_CASE("tcp client stream read", "[esp-adf-stream]")
{
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES) {
ESP_ERROR_CHECK(nvs_flash_erase());
err = nvs_flash_init();
}
tcpip_adapter_init();
audio_pipeline_handle_t pipeline;
audio_element_handle_t tcp_stream_writer, fatfs_stream_reader;
esp_log_level_set("*", ESP_LOG_WARN);
esp_log_level_set(TAG, ESP_LOG_DEBUG);
esp_periph_config_t periph_cfg = DEFAULT_ESP_PERIPH_SET_CONFIG();
esp_periph_set_handle_t set = esp_periph_set_init(&periph_cfg);
TEST_ASSERT_NOT_NULL(set);
TEST_ASSERT_EQUAL(ESP_OK, audio_board_sdcard_init(set, SD_MODE_1_LINE));
audio_pipeline_cfg_t pipeline_cfg = DEFAULT_AUDIO_PIPELINE_CONFIG();
pipeline = audio_pipeline_init(&pipeline_cfg);
TEST_ASSERT_NOT_NULL(pipeline);
fatfs_stream_cfg_t fatfs_cfg = FATFS_STREAM_CFG_DEFAULT();
fatfs_cfg.type = AUDIO_STREAM_WRITER;
fatfs_stream_reader = fatfs_stream_init(&fatfs_cfg);
TEST_ASSERT_NOT_NULL(fatfs_stream_reader);
tcp_stream_cfg_t tcp_cfg = TCP_STREAM_CFG_DEFAULT();
tcp_cfg.type = AUDIO_STREAM_READER;
tcp_cfg.port = CONFIG_TCP_PORT;
tcp_cfg.host = CONFIG_TCP_URL;
tcp_stream_writer = tcp_stream_init(&tcp_cfg);
TEST_ASSERT_NOT_NULL(tcp_stream_writer);
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, tcp_stream_writer, "tcp"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, fatfs_stream_reader, "file"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_link(pipeline, (const char *[]) {"tcp", "file"}, 2));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_set_uri(fatfs_stream_reader, "/sdcard/test.mp3"));
periph_wifi_cfg_t wifi_cfg = {
.ssid = CONFIG_WIFI_SSID,
.password = CONFIG_WIFI_PASSWORD,
};
esp_periph_handle_t wifi_handle = periph_wifi_init(&wifi_cfg);
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_start(set, wifi_handle));
TEST_ASSERT_EQUAL(ESP_OK, periph_wifi_wait_for_connected(wifi_handle, portMAX_DELAY));
audio_event_iface_cfg_t evt_cfg = AUDIO_EVENT_IFACE_DEFAULT_CFG();
audio_event_iface_handle_t evt = audio_event_iface_init(&evt_cfg);
TEST_ASSERT_NOT_NULL(evt);
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_set_listener(pipeline, evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_set_listener(esp_periph_set_get_event_iface(set), evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_run(pipeline));
while (1) {
audio_event_iface_msg_t msg;
esp_err_t ret = audio_event_iface_listen(evt, &msg, portMAX_DELAY);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "[ * ] Event interface error : %d", ret);
continue;
}
/* Stop when the last pipeline element (tcp_stream_reader in this case) read stop event */
if (msg.source_type == AUDIO_ELEMENT_TYPE_ELEMENT && msg.source == (void *) tcp_stream_reader
&& msg.cmd == AEL_MSG_CMD_REPORT_STATUS
&& (((int)msg.data == AEL_STATUS_STATE_STOPPED) || ((int)msg.data == AEL_STATUS_STATE_FINISHED))) {
ESP_LOGW(TAG, "[ * ] Stop event received");
break;
}
}
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_terminate(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, tcp_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, fatfs_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_remove_listener(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_stop_all(set));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_remove_listener(esp_periph_set_get_event_iface(set), evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_destroy(evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_deinit(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(tcp_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(fatfs_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_destroy(set));
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/audio_stream/test/tcp_client_stream_test.c
|
C
|
apache-2.0
| 10,438
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "unity.h"
#include "esp_log.h"
#include "audio_pipeline.h"
#include "audio_mem.h"
#include "audio_element.h"
#include "audio_event_iface.h"
#include "tone_stream.h"
#include "fatfs_stream.h"
#include "esp_peripherals.h"
#include "board.h"
const char* tone_uri[] = {
"flash://tone/0_Bt_Reconnect.mp3",
"flash://tone/1_Wechat.mp3",
"flash://tone/2_Welcome_To_Wifi.mp3",
"flash://tone/3_New_Version_Available.mp3",
"flash://tone/4_Bt_Success.mp3",
"flash://tone/5_Freetalk.mp3",
"flash://tone/6_Upgrade_Done.mp3",
"flash://tone/7_shutdown.mp3",
"flash://tone/8_Alarm.mp3",
"flash://tone/9_Wifi_Success.mp3",
"flash://tone/10_Under_Smartconfig.mp3",
"flash://tone/11_Out_Of_Power.mp3",
"flash://tone/12_server_connect.mp3",
"flash://tone/13_hello.mp3",
"flash://tone/14_new_message.mp3",
"flash://tone/15_Please_Retry_Wifi.mp3",
"flash://tone/16_please_setting_wifi.mp3",
"flash://tone/17_Welcome_To_Bt.mp3",
"flash://tone/18_Wifi_Time_Out.mp3",
"flash://tone/19_Wifi_Reconnect.mp3",
"flash://tone/20_server_disconnect.mp3",
};
#define TONE_URL_MAX 21
TEST_CASE("tone stream init memory", "esp-adf-stream")
{
audio_element_handle_t tone_stream_reader;
tone_stream_cfg_t tone_cfg = TONE_STREAM_CFG_DEFAULT();
tone_cfg.type = AUDIO_STREAM_READER;
int cnt = 2000;
AUDIO_MEM_SHOW("BEFORE HTTP_STREAM_INIT MEMORY TEST");
while (cnt--) {
tone_stream_reader = tone_stream_init(&tone_cfg);
audio_element_deinit(tone_stream_reader);
}
AUDIO_MEM_SHOW("AFTER TONE_STREAM_INIT MEMORY TEST");
}
TEST_CASE("tone stream read test", "esp-adf-stream")
{
audio_pipeline_handle_t pipeline;
audio_element_handle_t tone_stream_reader, fatfs_stream_writer;
esp_periph_config_t periph_cfg = DEFAULT_ESP_PERIPH_SET_CONFIG();
esp_periph_set_handle_t set = esp_periph_set_init(&periph_cfg);
TEST_ASSERT_NOT_NULL(set);
TEST_ASSERT_EQUAL(ESP_OK, audio_board_sdcard_init(set, SD_MODE_1_LINE));
audio_pipeline_cfg_t pipeline_cfg = DEFAULT_AUDIO_PIPELINE_CONFIG();
pipeline = audio_pipeline_init(&pipeline_cfg);
TEST_ASSERT_NOT_NULL(pipeline);
tone_stream_cfg_t tone_cfg = TONE_STREAM_CFG_DEFAULT();
tone_cfg.type = AUDIO_STREAM_READER;
tone_stream_reader = tone_stream_init(&tone_cfg);
TEST_ASSERT_NOT_NULL(tone_stream_reader);
fatfs_stream_cfg_t fatfs_cfg = FATFS_STREAM_CFG_DEFAULT();
fatfs_cfg.type = AUDIO_STREAM_WRITER;
fatfs_stream_writer = fatfs_stream_init(&fatfs_cfg);
TEST_ASSERT_NOT_NULL(fatfs_stream_writer);
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, tone_stream_reader, "tone"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, fatfs_stream_writer, "fatfs"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_link(pipeline, (const char *[]) {"tone", "fatfs"}, 2));
uint32_t tone_type = esp_random() % TONE_URL_MAX;
TEST_ASSERT_EQUAL(ESP_OK, audio_element_set_uri(tone_stream_reader, tone_uri[tone_type]));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_set_uri(fatfs_stream_writer, "/sdcard/test.mp3"));
audio_event_iface_cfg_t evt_cfg = AUDIO_EVENT_IFACE_DEFAULT_CFG();
audio_event_iface_handle_t evt = audio_event_iface_init(&evt_cfg);
TEST_ASSERT_NOT_NULL(evt);
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_set_listener(pipeline, evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_run(pipeline));
while (1) {
audio_event_iface_msg_t msg = { 0 };
esp_err_t ret = audio_event_iface_listen(evt, &msg, portMAX_DELAY);
if (ret != ESP_OK) {
continue;
}
if (msg.source_type == AUDIO_ELEMENT_TYPE_ELEMENT && msg.source == (void *) tone_stream_reader
&& msg.cmd == AEL_MSG_CMD_REPORT_STATUS
&& (((int)msg.data == AEL_STATUS_STATE_STOPPED) || ((int)msg.data == AEL_STATUS_STATE_FINISHED))) {
break;
}
}
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_terminate(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, tone_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, fatfs_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_remove_listener(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_destroy(evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_deinit(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(tone_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(fatfs_stream_writer));
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/audio_stream/test/tone_stream_test.c
|
C
|
apache-2.0
| 5,888
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 "unity.h"
#include "esp_err.h"
#include "esp_log.h"
#include "audio_pipeline.h"
#include "audio_mem.h"
#include "tts_stream.h"
#include "i2s_stream.h"
#include "esp_peripherals.h"
#include "board.h"
static void init_tts_stream_test(audio_pipeline_handle_t *pipeline,
audio_element_handle_t *tts_stream_reader,
audio_element_handle_t *i2s_stream_writer,
esp_periph_set_handle_t *set)
{
esp_periph_config_t periph_cfg = DEFAULT_ESP_PERIPH_SET_CONFIG();
*set = esp_periph_set_init(&periph_cfg);
TEST_ASSERT_NOT_NULL(*set);
audio_board_handle_t board_handle = audio_board_init();
audio_hal_ctrl_codec(board_handle->audio_hal, AUDIO_HAL_CODEC_MODE_DECODE, AUDIO_HAL_CTRL_START);
audio_pipeline_cfg_t pipeline_cfg = DEFAULT_AUDIO_PIPELINE_CONFIG();
*pipeline = audio_pipeline_init(&pipeline_cfg);
TEST_ASSERT_NOT_NULL(*pipeline);
tts_stream_cfg_t tts_cfg = TTS_STREAM_CFG_DEFAULT();
tts_cfg.type = AUDIO_STREAM_READER;
*tts_stream_reader = tts_stream_init(&tts_cfg);
TEST_ASSERT_NOT_NULL(*tts_stream_reader);
i2s_stream_cfg_t i2s_cfg = I2S_STREAM_CFG_DEFAULT();
i2s_cfg.type = AUDIO_STREAM_WRITER;
i2s_cfg.i2s_config.sample_rate = 16000;
i2s_cfg.i2s_config.channel_format = I2S_CHANNEL_FMT_ONLY_LEFT;
*i2s_stream_writer = i2s_stream_init(&i2s_cfg);
TEST_ASSERT_NOT_NULL(*i2s_stream_writer);
audio_pipeline_register(*pipeline, *tts_stream_reader, "tts");
audio_pipeline_register(*pipeline, *i2s_stream_writer, "i2s");
const char *link_tag[2] = {"tts", "i2s"};
audio_pipeline_link(*pipeline, &link_tag[0], 2);
}
static void init_audio_event_test(audio_pipeline_handle_t *pipeline,
esp_periph_set_handle_t *set,
audio_event_iface_handle_t *evt)
{
audio_event_iface_cfg_t evt_cfg = AUDIO_EVENT_IFACE_DEFAULT_CFG();
*evt = audio_event_iface_init(&evt_cfg);
TEST_ASSERT_EQUAL(ESP_OK,audio_pipeline_set_listener(*pipeline, *evt));
TEST_ASSERT_EQUAL(ESP_OK,audio_event_iface_set_listener(esp_periph_set_get_event_iface(*set), *evt));
TEST_ASSERT_EQUAL(ESP_OK,audio_pipeline_run(*pipeline));
}
static void deinit_tts_stream_test(audio_pipeline_handle_t *pipeline,
audio_element_handle_t *tts_stream_reader,
audio_element_handle_t *i2s_stream_writer,
esp_periph_set_handle_t *set,
audio_event_iface_handle_t *evt)
{
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_wait_for_stop(*pipeline));
TEST_ASSERT_EQUAL(ESP_OK,audio_pipeline_terminate(*pipeline));
TEST_ASSERT_EQUAL(ESP_OK,audio_pipeline_unregister(*pipeline, *tts_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK,audio_pipeline_unregister(*pipeline, *i2s_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK,audio_pipeline_remove_listener(*pipeline));
TEST_ASSERT_EQUAL(ESP_OK,esp_periph_set_stop_all(*set));
TEST_ASSERT_EQUAL(ESP_OK,audio_event_iface_remove_listener(esp_periph_set_get_event_iface(*set), *evt));
TEST_ASSERT_EQUAL(ESP_OK,audio_event_iface_destroy(*evt));
TEST_ASSERT_EQUAL(ESP_OK,audio_pipeline_deinit(*pipeline));
TEST_ASSERT_EQUAL(ESP_OK,audio_element_deinit(*tts_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK,audio_element_deinit(*i2s_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK,esp_periph_set_destroy(*set));
}
TEST_CASE("tts stream init and deinit memory", "[esp-adf-stream]")
{
AUDIO_MEM_SHOW("TTS STREAM INIT AND DEINIT MEMORY");
esp_log_level_set("AUDIO_ELEMENT", ESP_LOG_DEBUG);
audio_element_handle_t tts_stream_reader;
tts_stream_cfg_t tts_cfg = TTS_STREAM_CFG_DEFAULT();
tts_cfg.type = AUDIO_STREAM_READER;
int cnt = 20;
AUDIO_MEM_SHOW("BEFORE TTS_STREAM_INIT MEMORY TEST");
while (cnt--) {
tts_stream_reader = tts_stream_init(&tts_cfg);
audio_element_deinit(tts_stream_reader);
}
AUDIO_MEM_SHOW("AFTER TTS_STREAM_INIT MEMORY TEST");
}
TEST_CASE("tts stream set and read strings", "[esp-adf-stream]")
{
AUDIO_MEM_SHOW("TTS STREAM SET AND READ STRINGS");
static const char *STRINGS = "乐鑫语音开源框架简称ADF";
esp_log_level_set("AUDIO_ELEMENT", ESP_LOG_DEBUG);
audio_element_handle_t tts_stream_reader;
tts_stream_cfg_t tts_cfg = TTS_STREAM_CFG_DEFAULT();
tts_cfg.type = AUDIO_STREAM_READER;
tts_stream_reader = tts_stream_init(&tts_cfg);
tts_stream_set_strings(tts_stream_reader, STRINGS);
char *uri = audio_element_get_uri(tts_stream_reader);
TEST_ASSERT_EQUAL_STRING(STRINGS, uri);
audio_element_deinit(tts_stream_reader);
}
TEST_CASE("tts stream speed write and read test", "[esp-adf-stream]")
{
AUDIO_MEM_SHOW("TTS STREAM SPEED WRITE AND READ TEST");
audio_element_handle_t tts_stream_reader;
tts_voice_speed_t speed;
esp_log_level_set("AUDIO_ELEMENT", ESP_LOG_DEBUG);
tts_stream_cfg_t tts_cfg = TTS_STREAM_CFG_DEFAULT();
tts_cfg.type = AUDIO_STREAM_READER;
tts_stream_reader = tts_stream_init(&tts_cfg);
TEST_ASSERT_NOT_NULL(tts_stream_reader);
TEST_ASSERT_EQUAL(ESP_OK, tts_stream_set_speed(tts_stream_reader, TTS_VOICE_SPEED_0));
TEST_ASSERT_EQUAL(ESP_OK, tts_stream_get_speed(tts_stream_reader, &speed));
TEST_ASSERT_EQUAL(TTS_VOICE_SPEED_0, speed);
TEST_ASSERT_EQUAL(ESP_OK, tts_stream_set_speed(tts_stream_reader, TTS_VOICE_SPEED_1));
TEST_ASSERT_EQUAL(ESP_OK, tts_stream_get_speed(tts_stream_reader, &speed));
TEST_ASSERT_EQUAL(TTS_VOICE_SPEED_1, speed);
TEST_ASSERT_EQUAL(ESP_OK, tts_stream_set_speed(tts_stream_reader, TTS_VOICE_SPEED_2));
TEST_ASSERT_EQUAL(ESP_OK, tts_stream_get_speed(tts_stream_reader, &speed));
TEST_ASSERT_EQUAL(TTS_VOICE_SPEED_2, speed);
TEST_ASSERT_EQUAL(ESP_OK, tts_stream_set_speed(tts_stream_reader, TTS_VOICE_SPEED_3));
TEST_ASSERT_EQUAL(ESP_OK, tts_stream_get_speed(tts_stream_reader, &speed));
TEST_ASSERT_EQUAL(TTS_VOICE_SPEED_3, speed);
TEST_ASSERT_EQUAL(ESP_OK, tts_stream_set_speed(tts_stream_reader, TTS_VOICE_SPEED_4));
TEST_ASSERT_EQUAL(ESP_OK, tts_stream_get_speed(tts_stream_reader, &speed));
TEST_ASSERT_EQUAL(TTS_VOICE_SPEED_4, speed);
TEST_ASSERT_EQUAL(ESP_OK, tts_stream_set_speed(tts_stream_reader, TTS_VOICE_SPEED_5));
TEST_ASSERT_EQUAL(ESP_OK, tts_stream_get_speed(tts_stream_reader, &speed));
TEST_ASSERT_EQUAL(TTS_VOICE_SPEED_5, speed);
audio_element_deinit(tts_stream_reader);
}
TEST_CASE("tts stream play a chinese string", "[esp-adf-stream]")
{
AUDIO_MEM_SHOW("START PLAY A CHINESE STRING TEST");
audio_pipeline_handle_t pipeline = NULL;
audio_element_handle_t tts_stream_reader = NULL, i2s_stream_writer = NULL;
esp_periph_set_handle_t set = NULL;
audio_event_iface_handle_t evt = NULL;
init_tts_stream_test(&pipeline, &tts_stream_reader, &i2s_stream_writer, &set);
TEST_ASSERT_EQUAL(ESP_OK, tts_stream_set_strings(tts_stream_reader, "乐鑫提供安全、稳定、节能的 AIoT 解决方案"));
init_audio_event_test(&pipeline, &set, &evt);
while (1) {
audio_event_iface_msg_t msg;
esp_err_t ret = audio_event_iface_listen(evt, &msg, portMAX_DELAY);
if (ret != ESP_OK) {
continue;
}
/* Stop when the last pipeline element (i2s_stream_writer in this case) receives stop event */
if (msg.source_type == AUDIO_ELEMENT_TYPE_ELEMENT && msg.source == (void *) i2s_stream_writer
&& msg.cmd == AEL_MSG_CMD_REPORT_STATUS
&& (((int)msg.data == AEL_STATUS_STATE_STOPPED) || ((int)msg.data == AEL_STATUS_STATE_FINISHED))) {
break;
}
}
deinit_tts_stream_test(&pipeline, &tts_stream_reader, &i2s_stream_writer, &set, &evt);
}
TEST_CASE("tts stream play multiple strings", "[esp-adf-stream]")
{
AUDIO_MEM_SHOW("TTS STREAM PLAY MULTIPLE STRINGS");
static const char STRINGS[][80] = {
{"乐鑫科技是一家全球化的无晶圆厂半导体公司"},
{"在中国、捷克、印度、新加坡和巴西均设有办公地"},
{"团队成员来自全世界的 20 多个国家和地区"},
} ;
audio_pipeline_handle_t pipeline = NULL;
audio_element_handle_t tts_stream_reader = NULL, i2s_stream_writer = NULL;
esp_periph_set_handle_t set = NULL;
audio_event_iface_handle_t evt = NULL;
init_tts_stream_test(&pipeline, &tts_stream_reader, &i2s_stream_writer, &set);
TEST_ASSERT_EQUAL(ESP_OK, tts_stream_set_strings(tts_stream_reader, STRINGS));
init_audio_event_test(&pipeline, &set, &evt);
int cnt = 0;
while (1){
audio_event_iface_msg_t msg;
esp_err_t ret = audio_event_iface_listen(evt, &msg, portMAX_DELAY);
if (ret != ESP_OK) {
continue;
}
/* Stop when the last pipeline element (i2s_stream_writer in this case) receives stop event */
if (msg.source_type == AUDIO_ELEMENT_TYPE_ELEMENT && msg.source == (void *) i2s_stream_writer
&& msg.cmd == AEL_MSG_CMD_REPORT_STATUS
&& (((int)msg.data == AEL_STATUS_STATE_STOPPED) || ((int)msg.data == AEL_STATUS_STATE_FINISHED))){
cnt ++;
if(cnt < (sizeof(STRINGS)/sizeof(STRINGS[0]))){
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_reset_ringbuffer(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_reset_elements(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, tts_stream_set_strings(tts_stream_reader, (STRINGS + cnt)));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_change_state(pipeline, AEL_STATE_INIT));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_run(pipeline));
}else{
AUDIO_MEM_SHOW("ALL PLAY FINISHED");
break;
}
}
}
deinit_tts_stream_test(&pipeline, &tts_stream_reader, &i2s_stream_writer, &set, &evt);
}
TEST_CASE("tts stream play-stop and start new chainese string", "[esp-adf-stream]")
{
AUDIO_MEM_SHOW("TTS STREAM PLAY-STOP AND START NEW CHAINESE STRING");
audio_pipeline_handle_t pipeline = NULL;
audio_element_handle_t tts_stream_reader = NULL, i2s_stream_writer = NULL;
esp_periph_set_handle_t set = NULL;
audio_event_iface_handle_t evt = NULL;
init_tts_stream_test(&pipeline, &tts_stream_reader, &i2s_stream_writer, &set);
TEST_ASSERT_EQUAL(ESP_OK, tts_stream_set_strings(tts_stream_reader, "第一个测试的 tts 音频流"));
init_audio_event_test(&pipeline, &set, &evt);
bool play_once_flag = true;
while (1) {
audio_event_iface_msg_t msg;
esp_err_t ret = audio_event_iface_listen(evt, &msg, portMAX_DELAY);
if (ret != ESP_OK) {
continue;
}
if (msg.source_type == AUDIO_ELEMENT_TYPE_ELEMENT && msg.source == (void *) tts_stream_reader){
if(((int)msg.data == AEL_STATUS_STATE_RUNNING) && (play_once_flag)){
play_once_flag = false;
vTaskDelay(1000);
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_stop(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_wait_for_stop(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_reset_state(tts_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_reset_state(i2s_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_reset_ringbuffer(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_reset_items_state(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, tts_stream_set_strings(tts_stream_reader, "停止第一个播放,开始第二个测试的 tts 音频播放"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_run(pipeline));
}
}
/* Stop when the last pipeline element (i2s_stream_writer in this case) receives stop event */
if (msg.source_type == AUDIO_ELEMENT_TYPE_ELEMENT && msg.source == (void *) i2s_stream_writer
&& msg.cmd == AEL_MSG_CMD_REPORT_STATUS){
if(((int)msg.data == AEL_STATUS_STATE_STOPPED) || ((int)msg.data == AEL_STATUS_STATE_FINISHED)){
AUDIO_MEM_SHOW("AEL_STATUS_STATE_FINISHED");
break;
}
}
}
deinit_tts_stream_test(&pipeline, &tts_stream_reader, &i2s_stream_writer, &set, &evt);
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/audio_stream/test/tts_stream_test.c
|
C
|
apache-2.0
| 13,784
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 <stdio.h>
#include <string.h>
#include "esp_log.h"
#include "audio_element.h"
#include "audio_error.h"
#include "audio_mem.h"
#include "tone_partition.h"
#include "tone_stream.h"
static const char *TAG = "TONE_STREAM";
/**
* @brief Parameters of each tone
*/
typedef struct tone_stream {
audio_stream_type_t type; /*!< File operation type */
bool is_open; /*!< Tone stream status */
bool use_delegate; /*!< Tone read with delegate*/
tone_partition_handle_t tone_handle; /*!< Tone partition's operation handle*/
tone_file_info_t cur_file; /*!< Address to read tone file */
const char *partition_label; /*!< Label of tone stored in flash */
} tone_stream_t;
static esp_err_t _tone_open(audio_element_handle_t self)
{
tone_stream_t *stream = (tone_stream_t *)audio_element_getdata(self);
if (stream->is_open) {
ESP_LOGE(TAG, "already opened");
return ESP_FAIL;
}
stream->tone_handle = tone_partition_init(stream->partition_label, stream->use_delegate);
if (stream->tone_handle == NULL) {
return ESP_FAIL;
}
char *flash_url = audio_element_get_uri(self);
flash_url += strlen("flash://tone/");
char *temp = strchr(flash_url, '_');
char find_num[2] = { 0 };
int file_index = 0;
if (temp != NULL) {
strncpy(find_num, flash_url, temp - flash_url);
file_index = strtoul(find_num, 0, 10);
ESP_LOGD(TAG, "Wanted read flash tone index is %d", file_index);
} else {
ESP_LOGE(TAG, "Tone file name is not correct!");
return ESP_FAIL;
}
tone_partition_get_file_info(stream->tone_handle, file_index, &stream->cur_file);
ESP_LOGI(TAG, "Tone offset:%08x, Tone length:%d, pos:%d\n", stream->cur_file.song_adr, stream->cur_file.song_len, file_index);
if (stream->cur_file.song_len <= 0) {
ESP_LOGE(TAG, "Mayebe the flash tone is empty, please ensure the flash's contex");
return ESP_FAIL;
}
audio_element_info_t info = { 0 };
info.total_bytes = stream->cur_file.song_len;
audio_element_setdata(self, stream);
audio_element_set_total_bytes(self, info.total_bytes);
stream->is_open = true;
return ESP_OK;
}
static int _tone_read(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait, void *context)
{
audio_element_info_t info = { 0 };
tone_stream_t *stream = NULL;
stream = (tone_stream_t *)audio_element_getdata(self);
audio_element_getinfo(self, &info);
if (info.byte_pos + len > info.total_bytes) {
len = info.total_bytes - info.byte_pos;
}
if (ESP_OK != tone_partition_file_read(stream->tone_handle, &stream->cur_file, info.byte_pos, buffer, len)) {
ESP_LOGE(TAG, "get tone data error, line:%d", __LINE__);
return ESP_FAIL;
}
if (len <= 0) {
ESP_LOGW(TAG, "No more data,ret:%d ,info.byte_pos:%llu", len, info.byte_pos);
return ESP_OK;
}
audio_element_update_byte_pos(self, len);
return len;
}
static int _tone_process(audio_element_handle_t self, char *in_buffer, int in_len)
{
int r_size = audio_element_input(self, in_buffer, in_len);
int w_size = 0;
if (r_size > 0) {
w_size = audio_element_output(self, in_buffer, r_size);
} else {
w_size = r_size;
}
return w_size;
}
static esp_err_t _tone_close(audio_element_handle_t self)
{
tone_stream_t *stream = (tone_stream_t *)audio_element_getdata(self);
if (stream->is_open) {
stream->is_open = false;
}
tone_partition_deinit(stream->tone_handle);
stream->tone_handle = NULL;
if (AEL_STATE_PAUSED != audio_element_get_state(self)) {
audio_element_set_byte_pos(self, 0);
}
return ESP_OK;
}
static esp_err_t _tone_destroy(audio_element_handle_t self)
{
tone_stream_t *stream = (tone_stream_t *)audio_element_getdata(self);
audio_free(stream);
return ESP_OK;
}
audio_element_handle_t tone_stream_init(tone_stream_cfg_t *config)
{
audio_element_handle_t el;
tone_stream_t *stream = audio_calloc(1, sizeof(tone_stream_t));
AUDIO_MEM_CHECK(TAG, stream, return NULL);
audio_element_cfg_t cfg = DEFAULT_AUDIO_ELEMENT_CONFIG();
cfg.open = _tone_open;
cfg.close = _tone_close;
cfg.process = _tone_process;
cfg.destroy = _tone_destroy;
cfg.task_stack = config->task_stack;
cfg.task_prio = config->task_prio;
cfg.task_core = config->task_core;
cfg.out_rb_size = config->out_rb_size;
cfg.buffer_len = config->buf_sz;
cfg.stack_in_ext = config->extern_stack;
if (cfg.stack_in_ext == true && config->use_delegate == false) {
ESP_LOGE(TAG, "Tone stream must read flash with delegate when stack is allocate in external ram");
goto _tone_init_exit;
}
if (cfg.buffer_len == 0) {
cfg.buffer_len = TONE_STREAM_BUF_SIZE;
}
cfg.tag = "flash";
stream->type = config->type;
stream->use_delegate = config->use_delegate;
if (config->label == NULL) {
ESP_LOGE(TAG, "Please set your tone label");
return NULL;
} else {
stream->partition_label = config->label;
}
if (config->type == AUDIO_STREAM_READER) {
cfg.read = _tone_read;
} else if (config->type == AUDIO_STREAM_WRITER) {
ESP_LOGE(TAG, "No writer for tone stream");
goto _tone_init_exit;
}
el = audio_element_init(&cfg);
AUDIO_MEM_CHECK(TAG, el, goto _tone_init_exit);
audio_element_setdata(el, stream);
return el;
_tone_init_exit:
audio_free(stream);
return NULL;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/audio_stream/tone_stream.c
|
C
|
apache-2.0
| 6,879
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 <string.h>
#include "tts_stream.h"
#include "audio_mem.h"
#include "esp_log.h"
#include "esp_partition.h"
#include "esp_tts_voice_template.h"
static const char *TAG = "TTS_STREAM";
typedef struct tts_stream {
audio_stream_type_t type;
esp_tts_voice_t *voice;
esp_tts_handle_t *tts_handle;
char *prompt;
unsigned int speed;
bool is_open;
} tts_stream_t;
static esp_err_t _tts_stream_open(audio_element_handle_t self)
{
tts_stream_t *tts_stream = (tts_stream_t *)audio_element_getdata(self);
tts_stream->is_open = false;
char *uri = audio_element_get_uri(self);
if (uri == NULL) {
ESP_LOGE(TAG, "The TTS string is not set");
return ESP_FAIL;
}
if (esp_tts_parse_chinese(tts_stream->tts_handle, uri)) {
tts_stream->is_open = true;
ESP_LOGW(TAG, "%s", uri);
return ESP_OK;
} else {
ESP_LOGE(TAG, "The Chinese string parse failed");
}
return ESP_FAIL;
}
static int _tts_stream_read(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait, void *context)
{
tts_stream_t *tts_stream = (tts_stream_t *)audio_element_getdata(self);
int rlen = 0;
uint8_t *pcm_data = (uint8_t *)esp_tts_stream_play(tts_stream->tts_handle, &rlen, tts_stream->speed);
if (rlen <= 0) {
ESP_LOGW(TAG, "No more data,ret:%d", rlen);
} else {
memcpy(buffer, pcm_data, rlen * 2);
audio_element_update_byte_pos(self, rlen * 2);
}
return rlen * 2 ;
}
static int _tts_stream_process(audio_element_handle_t self, char *in_buffer, int in_len)
{
int r_size = audio_element_input(self, in_buffer, in_len);
int w_size = 0;
if (r_size > 0) {
w_size = audio_element_output(self, in_buffer, r_size);
} else {
w_size = r_size;
}
return w_size;
}
static esp_err_t _tts_stream_close(audio_element_handle_t self)
{
tts_stream_t *tts_stream = (tts_stream_t *)audio_element_getdata(self);
if (tts_stream->is_open) {
esp_tts_stream_reset(tts_stream->tts_handle);
tts_stream->is_open = false;
}
return ESP_OK;
}
static esp_err_t _tts_stream_destroy(audio_element_handle_t self)
{
tts_stream_t *tts_stream = (tts_stream_t *)audio_element_getdata(self);
esp_tts_voice_set_free(tts_stream->voice);
esp_tts_destroy(tts_stream->tts_handle);
audio_free(tts_stream);
return ESP_OK;
}
esp_err_t tts_stream_set_strings(audio_element_handle_t el, const char *strings)
{
return audio_element_set_uri(el, strings);
}
esp_err_t tts_stream_set_speed(audio_element_handle_t el, tts_voice_speed_t speed)
{
if (speed > TTS_VOICE_SPEED_MAX) {
ESP_LOGE(TAG, "Invalid parameter, voice speed range is [0 - 5]");
return ESP_FAIL;
}
tts_stream_t *tts_stream = (tts_stream_t *)audio_element_getdata(el);
tts_stream->speed = speed;
return ESP_OK;
}
esp_err_t tts_stream_get_speed(audio_element_handle_t el, tts_voice_speed_t *speed)
{
if(speed == NULL){
ESP_LOGE(TAG, "The speed parameter is NULL");
return ESP_FAIL;
}
tts_stream_t *tts_stream = (tts_stream_t *)audio_element_getdata(el);
*speed = tts_stream->speed;
return ESP_OK;
}
audio_element_handle_t tts_stream_init(tts_stream_cfg_t *config)
{
audio_element_handle_t el;
tts_stream_t *tts_stream = audio_calloc(1, sizeof(tts_stream_t));
AUDIO_MEM_CHECK(TAG, tts_stream, return NULL);
audio_element_cfg_t cfg = DEFAULT_AUDIO_ELEMENT_CONFIG();
cfg.open = _tts_stream_open;
cfg.close = _tts_stream_close;
cfg.process = _tts_stream_process;
cfg.destroy = _tts_stream_destroy;
cfg.task_stack = config->task_stack;
cfg.task_prio = config->task_prio;
cfg.task_core = config->task_core;
cfg.out_rb_size = config->out_rb_size;
cfg.buffer_len = config->buf_sz;
cfg.stack_in_ext = config->ext_stack;
if (cfg.buffer_len == 0) {
cfg.buffer_len = TTS_STREAM_BUF_SIZE;
}
cfg.tag = "tts";
tts_stream->type = config->type;
const esp_partition_t* part = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_FAT, "voice_data");
AUDIO_MEM_CHECK(TAG, part, {
ESP_LOGE(TAG, "Couldn't find voice data partition!");
audio_free(tts_stream);
return NULL;
});
spi_flash_mmap_handle_t mmap;
uint16_t* voicedata;
esp_err_t err = esp_partition_mmap(part, 0, 3 * 1024 * 1024, SPI_FLASH_MMAP_DATA, (const void**)&voicedata, &mmap);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Couldn't map voice data partition!");
audio_free(tts_stream);
return NULL;
}
tts_stream->voice = esp_tts_voice_set_init(&esp_tts_voice_template, voicedata);
AUDIO_MEM_CHECK(TAG, tts_stream->voice, {
ESP_LOGE(TAG, "Couldn't init tts voice set!");
audio_free(tts_stream);
return NULL;
});
tts_stream->tts_handle = esp_tts_create(tts_stream->voice);
AUDIO_MEM_CHECK(TAG, tts_stream->tts_handle, {
ESP_LOGE(TAG, "Couldn't create tts voice handle!");
esp_tts_voice_set_free(tts_stream->voice);
audio_free(tts_stream);
return NULL;
});
tts_stream->speed = TTS_VOICE_SPEED_3;
cfg.read = _tts_stream_read;
el = audio_element_init(&cfg);
AUDIO_MEM_CHECK(TAG, el, goto _tts_stream_init_exit);
audio_element_setdata(el, tts_stream);
return el;
_tts_stream_init_exit:
esp_tts_voice_set_free(tts_stream->voice);
esp_tts_destroy(tts_stream->tts_handle);
audio_free(tts_stream);
return NULL;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/audio_stream/tts_stream.c
|
C
|
apache-2.0
| 6,821
|
set(COMPONENT_SRCS "battery_service.c"
"./monitors/voltage_monitor.c")
set(COMPONENT_ADD_INCLUDEDIRS "include"
"./monitors/include")
set(COMPONENT_REQUIRES esp_adc_cal audio_sal esp_peripherals)
register_component()
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/battery_service/CMakeLists.txt
|
CMake
|
apache-2.0
| 271
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "freertos/queue.h"
#include "freertos/event_groups.h"
#include "esp_log.h"
#include "audio_mem.h"
#include "audio_sys.h"
#include "battery_service.h"
typedef struct battery_service {
xQueueHandle serv_q;
EventGroupHandle_t sync_events;
vol_monitor_handle_t vol_monitor;
bool running;
} battery_service_t;
typedef struct battery_cmd {
enum battery_service_msg {
/* battery service ctrl */
BATTERY_SERVICE_START,
BATTERY_SERVICE_STOP,
BATTERY_SERVICE_DESTROY,
/* battery voltage monitor ctrl */
BATTERY_VOL_SET_REPORT_FREQ,
BATTERY_VOL_REPORT_START,
BATTERY_VOL_REPORT_STOP,
BATTERY_VOL_REPORT_FREQ,
BATTERY_VOL_REPORT_FULL,
BATTERY_VOL_REPORT_LOW,
/* battery charger monitor ctrl - todo*/
} msg_id;
void *pdata;
} battery_msg_t;
#define BATTERY_SERV_SYNC_STARTED (BIT0)
#define BATTERY_SERV_SYNC_STOPPED (BIT1)
#define BATTERY_SERV_SYNC_DESTROYED (BIT2)
static const char *TAG = "BATTERY_SERVICE";
static esp_err_t battery_service_msg_send(void *queue, int msg_id, void *pdata)
{
battery_msg_t msg = { 0 };
msg.msg_id = msg_id;
msg.pdata = pdata;
if (xQueueSend(queue, &msg, 0) != pdPASS) {
ESP_LOGE(TAG, "msg send failed %d", msg.msg_id);
return ESP_FAIL;
}
return ESP_OK;
}
static void battery_vol_monitor_cb(int msg, void *msg_data, void *user_ctx)
{
switch (msg) {
case VOL_MONITOR_EVENT_FREQ_REPORT:
battery_service_msg_send(user_ctx, BATTERY_VOL_REPORT_FREQ, msg_data);
break;
case VOL_MONITOR_EVENT_BAT_FULL:
battery_service_msg_send(user_ctx, BATTERY_VOL_REPORT_FULL, msg_data);
break;
case VOL_MONITOR_EVENT_BAT_LOW:
battery_service_msg_send(user_ctx, BATTERY_VOL_REPORT_LOW, msg_data);
break;
default:
break;
}
}
static void battery_task(void *pvParameters)
{
periph_service_handle_t serv_handle = (periph_service_handle_t)pvParameters;
battery_service_t *service = periph_service_get_data(serv_handle);
periph_service_event_t evt = { 0 };
battery_msg_t msg = { 0 };
service->running = true;
while (service->running) {
if (xQueueReceive(service->serv_q, &msg, portMAX_DELAY) == pdTRUE) {
switch (msg.msg_id) {
case BATTERY_SERVICE_START: {
if (service->vol_monitor != NULL && vol_monitor_set_event_cb(service->vol_monitor, battery_vol_monitor_cb, service->serv_q) == ESP_OK) {
xEventGroupSetBits(service->sync_events, BATTERY_SERV_SYNC_STARTED);
} else {
xEventGroupSetBits(service->sync_events, BATTERY_SERV_SYNC_STOPPED);
}
break;
}
case BATTERY_SERVICE_DESTROY:
service->running = false;
FALL_THROUGH;
// No break, to share the actions of case `BATTERY_SERVICE_STOP`, clear all the monitors.
case BATTERY_SERVICE_STOP: {
if (service->vol_monitor != NULL) {
vol_monitor_set_event_cb(service->vol_monitor, NULL, NULL);
}
xEventGroupSetBits(service->sync_events, BATTERY_SERV_SYNC_STOPPED);
break;
}
/* battery voltage monitor ctrl begin */
case BATTERY_VOL_SET_REPORT_FREQ: {
if (service->vol_monitor != NULL) {
vol_monitor_set_report_freq(service->vol_monitor, (int)msg.pdata);
}
break;
}
case BATTERY_VOL_REPORT_START:
if (service->vol_monitor != NULL) {
vol_monitor_start_freq_report(service->vol_monitor);
}
break;
case BATTERY_VOL_REPORT_STOP:
if (service->vol_monitor != NULL) {
vol_monitor_stop_freq_report(service->vol_monitor);
}
break;
case BATTERY_VOL_REPORT_FREQ: {
evt.type = BAT_SERV_EVENT_VOL_REPORT;
evt.data = msg.pdata;
periph_service_callback(serv_handle, &evt);
break;
}
case BATTERY_VOL_REPORT_FULL: {
evt.type = BAT_SERV_EVENT_BAT_FULL;
evt.data = msg.pdata;
periph_service_callback(serv_handle, &evt);
break;
}
case BATTERY_VOL_REPORT_LOW: {
evt.type = BAT_SERV_EVENT_BAT_LOW;
evt.data = msg.pdata;
periph_service_callback(serv_handle, &evt);
break;
}
/* battery voltage monitor ctrl end */
default:
break;
}
}
}
xEventGroupSetBits(service->sync_events, BATTERY_SERV_SYNC_DESTROYED);
ESP_LOGI(TAG, "battery service destroyed");
vTaskDelete(NULL);
}
static esp_err_t _battery_destroy(periph_service_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_ERR_INVALID_ARG);
battery_service_t *service = periph_service_get_data(handle);
battery_service_msg_send(service->serv_q, BATTERY_SERVICE_DESTROY, NULL);
EventBits_t bits = xEventGroupWaitBits(service->sync_events,
BATTERY_SERV_SYNC_DESTROYED,
true,
true,
pdMS_TO_TICKS(10000));
if (bits & BATTERY_SERV_SYNC_DESTROYED) {
if (service->serv_q) {
vQueueDelete(service->serv_q);
}
if (service->sync_events) {
vEventGroupDelete(service->sync_events);
}
free(service);
return ESP_OK;
} else {
return ESP_FAIL;
}
}
static esp_err_t _battery_start(periph_service_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_ERR_INVALID_ARG);
battery_service_t *service = periph_service_get_data(handle);
battery_service_msg_send(service->serv_q, BATTERY_SERVICE_START, NULL);
EventBits_t bits = xEventGroupWaitBits(service->sync_events,
BATTERY_SERV_SYNC_STARTED | BATTERY_SERV_SYNC_STOPPED,
true,
false,
portMAX_DELAY);
if (bits & BATTERY_SERV_SYNC_STARTED) {
return ESP_OK;
} else {
return ESP_FAIL;
}
}
static esp_err_t _battery_stop(periph_service_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_ERR_INVALID_ARG);
battery_service_t *service = periph_service_get_data(handle);
battery_service_msg_send(service->serv_q, BATTERY_SERVICE_STOP, NULL);
EventBits_t bits = xEventGroupWaitBits(service->sync_events,
BATTERY_SERV_SYNC_STOPPED,
true,
true,
portMAX_DELAY);
if (bits & BATTERY_SERV_SYNC_STOPPED) {
return ESP_OK;
} else {
return ESP_FAIL;
}
}
periph_service_handle_t battery_service_create(battery_service_config_t *config)
{
AUDIO_NULL_CHECK(TAG, config, return NULL);
AUDIO_CHECK(TAG, config->task_stack > 0, return NULL, "battery service should set the task_stack");
battery_service_t *battery_service = audio_calloc(1, sizeof(battery_service_t));
AUDIO_MEM_CHECK(TAG, battery_service, return NULL);
battery_service->serv_q = xQueueCreate(3, sizeof(battery_msg_t));
AUDIO_MEM_CHECK(TAG, battery_service->serv_q, {
goto err;
});
battery_service->sync_events = xEventGroupCreate();
AUDIO_MEM_CHECK(TAG, battery_service->sync_events, {
goto err;
});
battery_service->vol_monitor = config->vol_monitor;
periph_service_config_t cfg = {
.task_stack = config->task_stack,
.task_prio = config->task_prio,
.task_core = config->task_core,
.extern_stack = config->extern_stack,
.task_func = battery_task,
.service_start = _battery_start,
.service_stop = _battery_stop,
.service_ioctl = NULL,
.service_destroy = _battery_destroy,
.service_name = "battery_serv",
.user_data = (void *)battery_service,
};
periph_service_handle_t battery = periph_service_create(&cfg);
AUDIO_MEM_CHECK(TAG, battery, {
goto err;
});
periph_service_set_callback(battery, config->evt_cb, config->cb_ctx);
return battery;
err:
if (battery_service && battery_service->serv_q) {
vQueueDelete(battery_service->serv_q);
}
if (battery_service && battery_service->sync_events) {
vEventGroupDelete(battery_service->sync_events);
}
if (battery_service) {
free(battery_service);
}
return NULL;
}
esp_err_t battery_service_vol_report_switch(periph_service_handle_t handle, bool on_off)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_ERR_INVALID_ARG);
battery_service_t *service = periph_service_get_data(handle);
if (on_off) {
battery_service_msg_send(service->serv_q, BATTERY_VOL_REPORT_START, NULL);
} else {
battery_service_msg_send(service->serv_q, BATTERY_VOL_REPORT_STOP, NULL);
}
return ESP_OK;
}
esp_err_t battery_service_set_vol_report_freq(periph_service_handle_t handle, int freq)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_ERR_INVALID_ARG);
battery_service_t *service = periph_service_get_data(handle);
battery_service_msg_send(service->serv_q, BATTERY_VOL_SET_REPORT_FREQ, (void *)freq);
return ESP_OK;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/battery_service/battery_service.c
|
C
|
apache-2.0
| 11,008
|
#
# "main" pseudo-component makefile.
#
# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.)
COMPONENT_ADD_INCLUDEDIRS := ./include ./monitors/include
COMPONENT_SRCDIRS := . ./monitors
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/battery_service/component.mk
|
Makefile
|
apache-2.0
| 238
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 __BATTERY_SERVICE_H__
#define __BATTERY_SERVICE_H__
#include "periph_service.h"
#include "voltage_monitor.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Battery service event
*/
typedef enum {
BAT_SERV_EVENT_UNKNOWN,
/* Battery monitor's events */
BAT_SERV_EVENT_VOL_REPORT = 1,
BAT_SERV_EVENT_BAT_FULL,
BAT_SERV_EVENT_BAT_LOW,
/* Charger monitor's events */
BAT_SERV_EVENT_CHARGING_BEGIN = 100,
BAT_SERV_EVENT_CHARGING_STOP,
} battery_service_event_t;
/**
* @brief Battery service configure
*/
typedef struct {
/* Service Basic */
int task_stack; /*!< >0 Service task stack; =0 with out task created */
int task_prio; /*!< Service task priority (based on freeRTOS priority) */
int task_core; /*!< Service task running in core (0 or 1) */
bool extern_stack; /*!< Task stack allocate on the extern ram */
periph_service_cb evt_cb; /*!< Service callback function */
void *cb_ctx; /*!< Callback context */
/* Battery monitor */
vol_monitor_handle_t vol_monitor;
/* Charger monitor */
void *charger_monitor; /*!< Not supported yet */
} battery_service_config_t;
#define BATTERY_SERVICE_DEFAULT_CONFIG() \
{ \
.task_stack = 3 * 1024, \
.task_prio = 6, \
.task_core = 0, \
.evt_cb = NULL, \
.cb_ctx = NULL, \
.extern_stack = true, \
.vol_monitor = NULL, \
}
/**
* @brief Create the battery service instance
*
* @param config configuration of the battery service
*
* @return
* - NULL: Failed
* - Others: Success
*/
periph_service_handle_t battery_service_create(battery_service_config_t *config);
/**
* @brief Start or stop the battery voltage report
*
* @param[in] handle pointer to 'periph_service_handle_t' structure
* @param[in] on_off 'true' to start, 'false' to stop
*
* @return
* - ESP_OK: Success
* - ESP_ERR_INVALID_ARG: handle is NULL
*/
esp_err_t battery_service_vol_report_switch(periph_service_handle_t handle, bool on_off);
/**
* @brief Set voltage report freqency
*
* @param[in] handle pointer to 'periph_service_handle_t' structure
* @param[in] freq voltage report freqency
*
* @return
* - ESP_OK: Success
* - ESP_ERR_INVALID_ARG: handle is NULL
*/
esp_err_t battery_service_set_vol_report_freq(periph_service_handle_t handle, int freq);
#ifdef __cplusplus
}
#endif
#endif /* __BATTERY_SERVICE_H__ */
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/battery_service/include/battery_service.h
|
C
|
apache-2.0
| 3,922
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 __VOL_MONITOR_H__
#define __VOL_MONITOR_H__
#include "esp_err.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Battery adc configure
*/
typedef enum {
VOL_MONITOR_EVENT_FREQ_REPORT,
VOL_MONITOR_EVENT_BAT_FULL,
VOL_MONITOR_EVENT_BAT_LOW,
} vol_monitor_event_t;
/**
* @brief Battery adc configure
*/
typedef struct {
bool (*init)(void *); /*!< Voltage read init */
bool (*deinit)(void *); /*!< Voltage read deinit */
int (*vol_get)(void *); /*!< Voltage read interface */
void *user_data; /*!< Parameters for callbacks */
int read_freq; /*!< Voltage read frequency, unit: s*/
int report_freq; /*!< Voltage report frequency, voltage will be report with a interval calculate by (`read_freq` * `report_freq`) */
int vol_full_threshold; /*!< Voltage threshold to report, unit: mV */
int vol_low_threshold; /*!< Voltage threshold to report, unit: mV */
} vol_monitor_param_t;
/**
* @brief voltage monitor handle
*/
typedef void *vol_monitor_handle_t;
/**
* @brief callback define
*/
typedef void (*vol_monitor_event_cb)(int msg_id, void *data, void *user_ctx);
/**
* @brief Create the voltage monitor instance
*
* @param[in] config pointer to 'vol_monitor_param_t' structure
*
* @return
* - NULL: Failed
* - Others: Success
*/
vol_monitor_handle_t vol_monitor_create(vol_monitor_param_t *config);
/**
* @brief Destroy the voltage monitor
*
* @param[in] handle pointer to 'vol_monitor_handle_t' structure
*
* @return
* - ESP_OK: Success
* - Others: Failed
*/
esp_err_t vol_monitor_destroy(vol_monitor_handle_t handle);
/**
* @brief Set the event callback
*
* @param[in] handle pointer to 'vol_monitor_handle_t' structure
* @param[in] event_cb callback used to handle the events of voltage monitor
* @param[in] user_ctx user's data
*
* @return
* - ESP_OK: Success
* - Others: Failed
*/
esp_err_t vol_monitor_set_event_cb(vol_monitor_handle_t handle, vol_monitor_event_cb event_cb, void *user_ctx);
/**
* @brief Start the voltage report with the configured frequency
*
* @param[in] handle pointer to 'vol_monitor_handle_t' structure
*
* @return
* - ESP_OK: Success
* - Others: Failed
*/
esp_err_t vol_monitor_start_freq_report(vol_monitor_handle_t handle);
/**
* @brief Stop the voltage frequency report
*
* @param[in] handle pointer to 'vol_monitor_handle_t' structure
*
* @return
* - ESP_OK: Success
* - Others: Failed
*/
esp_err_t vol_monitor_stop_freq_report(vol_monitor_handle_t handle);
/**
* @brief Set the voltage report frequency
*
* @param[in] handle pointer to 'vol_monitor_handle_t' structure
* @param[in] freq voltage report freqency
*
* @return
* - ESP_OK: Success
* - Others: Failed
*/
esp_err_t vol_monitor_set_report_freq(vol_monitor_handle_t handle, int freq);
#ifdef __cplusplus
}
#endif
#endif /* __BATTERY_SERVICE_H__ */
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/battery_service/monitors/include/voltage_monitor.h
|
C
|
apache-2.0
| 4,297
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "freertos/event_groups.h"
#include "freertos/semphr.h"
#include "esp_log.h"
#include "audio_error.h"
#include "audio_mem.h"
#include "audio_mutex.h"
#include "voltage_monitor.h"
typedef struct {
SemaphoreHandle_t mutex;
vol_monitor_param_t *config;
vol_monitor_event_cb event_cb;
void *user_ctx;
esp_timer_handle_t check_timer;
int read_cnt;
int report_start;
bool full_reported;
bool low_reported;
} vol_monitor_ctx_t;
static const char *TAG = "VOL_MONITOR";
static void vol_check_timer_hdlr(void *arg)
{
vol_monitor_ctx_t *vol_monitor = (vol_monitor_ctx_t *)arg;
if (vol_monitor == NULL || vol_monitor->event_cb == NULL || vol_monitor->config->user_data == NULL) {
return;
}
mutex_lock(vol_monitor->mutex);
int voltage = vol_monitor->config->vol_get(vol_monitor->config->user_data);;
if (vol_monitor->report_start != 0 && ++vol_monitor->read_cnt % vol_monitor->report_start == 0) {
vol_monitor->read_cnt = 0;
vol_monitor->event_cb(VOL_MONITOR_EVENT_FREQ_REPORT, (void *)voltage, vol_monitor->user_ctx);
}
if (vol_monitor->config->vol_low_threshold != 0) {
if (vol_monitor->low_reported == false && voltage <= vol_monitor->config->vol_low_threshold) {
vol_monitor->event_cb(VOL_MONITOR_EVENT_BAT_LOW, (void *)voltage, vol_monitor->user_ctx);
vol_monitor->low_reported = true;
} else if (voltage > vol_monitor->config->vol_low_threshold) {
vol_monitor->low_reported = false;
}
}
if (vol_monitor->config->vol_full_threshold != 0) {
if (vol_monitor->full_reported == false && voltage >= vol_monitor->config->vol_full_threshold) {
vol_monitor->event_cb(VOL_MONITOR_EVENT_BAT_FULL, (void *)voltage, vol_monitor->user_ctx);
vol_monitor->full_reported = true;
} else if (voltage < vol_monitor->config->vol_full_threshold) {
vol_monitor->full_reported = false;
}
}
mutex_unlock(vol_monitor->mutex);
}
static bool vol_monitor_param_check(vol_monitor_param_t *config)
{
if (config->init == NULL) {
ESP_LOGE(TAG, "init NULL");
return false;
}
if (config->deinit == NULL) {
ESP_LOGE(TAG, "deinit NULL");
return false;
}
if (config->vol_get == NULL) {
ESP_LOGE(TAG, "vol_get NULL");
return false;
}
if (config->read_freq <= 0) {
ESP_LOGE(TAG, "Read freq <= 0");
return false;
}
if (config->report_freq < 0) {
ESP_LOGE(TAG, "report freq < 0");
return false;
}
if (config->vol_full_threshold < 0 ) {
ESP_LOGE(TAG, "vol_full_threshold < 0");
return false;
}
if (config->vol_low_threshold < 0 ) {
ESP_LOGE(TAG, "vol_low_threshold < 0");
return false;
}
if (config->vol_full_threshold != 0 && config->vol_low_threshold >= config->vol_full_threshold) {
ESP_LOGE(TAG, "vol_low_threshold >= vol_full_threshold");
return false;
}
return true;
}
vol_monitor_handle_t vol_monitor_create(vol_monitor_param_t *config)
{
AUDIO_NULL_CHECK(TAG, config, return NULL);
vol_monitor_ctx_t *vol_monitor = audio_calloc(1, sizeof(vol_monitor_ctx_t));
AUDIO_MEM_CHECK(TAG, vol_monitor, return NULL);
if (!vol_monitor_param_check(config)) {
goto error;
}
vol_monitor->config = config;
vol_monitor->config->init(vol_monitor->config->user_data);
vol_monitor->mutex = mutex_create();
/* init timer */
if (vol_monitor->config->read_freq > 0) {
const esp_timer_create_args_t timer_args = {
.callback = vol_check_timer_hdlr,
.arg = vol_monitor,
.dispatch_method = ESP_TIMER_TASK,
.name = "report",
};
if (esp_timer_create(&timer_args, &vol_monitor->check_timer) != ESP_OK
|| esp_timer_start_periodic(vol_monitor->check_timer, vol_monitor->config->read_freq * 1000 * 1000) != ESP_OK) {
goto error;
}
}
return vol_monitor;
error:
ESP_LOGE(TAG, "vol_monitor_create failed");
if (vol_monitor->check_timer != NULL) {
esp_timer_delete(vol_monitor->check_timer);
}
if (vol_monitor->mutex) {
mutex_destroy(vol_monitor->mutex);
}
if (vol_monitor) {
free(vol_monitor);
}
return NULL;
}
esp_err_t vol_monitor_destroy(vol_monitor_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_ERR_INVALID_ARG);
vol_monitor_ctx_t *vol_monitor = (vol_monitor_ctx_t *)handle;
if (vol_monitor->check_timer != NULL) {
esp_timer_stop(vol_monitor->check_timer);
esp_timer_delete(vol_monitor->check_timer);
vol_monitor->check_timer = NULL;
}
vol_monitor->config->deinit(vol_monitor->config->user_data);
if (vol_monitor->mutex) {
mutex_destroy(vol_monitor->mutex);
}
if (vol_monitor) {
free(vol_monitor);
}
ESP_LOGI(TAG, "vol monitor destroyed");
return ESP_OK;
}
esp_err_t vol_monitor_set_event_cb(vol_monitor_handle_t handle, vol_monitor_event_cb event_cb, void *user_ctx)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
vol_monitor_ctx_t *vol_monitor = (vol_monitor_ctx_t *)handle;
mutex_lock(vol_monitor->mutex);
vol_monitor->event_cb = event_cb;
vol_monitor->user_ctx = user_ctx;
mutex_unlock(vol_monitor->mutex);
return ESP_OK;
}
esp_err_t vol_monitor_start_freq_report(vol_monitor_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_ERR_INVALID_ARG);
vol_monitor_ctx_t *vol_monitor = (vol_monitor_ctx_t *)handle;
esp_err_t ret = ESP_OK;
mutex_lock(vol_monitor->mutex);
if (vol_monitor->config->report_freq > 0) {
vol_monitor->report_start = vol_monitor->config->report_freq;
ret = ESP_OK;
} else {
ESP_LOGW(TAG, "report freq <= 0");
ret = ESP_FAIL;
}
mutex_unlock(vol_monitor->mutex);
return ret;
}
esp_err_t vol_monitor_stop_freq_report(vol_monitor_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_ERR_INVALID_ARG);
vol_monitor_ctx_t *vol_monitor = (vol_monitor_ctx_t *)handle;
mutex_lock(vol_monitor->mutex);
vol_monitor->report_start = 0;
mutex_unlock(vol_monitor->mutex);
return ESP_OK;
}
esp_err_t vol_monitor_set_report_freq(vol_monitor_handle_t handle, int freq)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_ERR_INVALID_ARG);
vol_monitor_ctx_t *vol_monitor = (vol_monitor_ctx_t *)handle;
mutex_lock(vol_monitor->mutex);
vol_monitor->config->report_freq = freq;
if (vol_monitor->config->report_freq > 0 && vol_monitor->report_start > 0) {
vol_monitor->read_cnt = 0;
vol_monitor->report_start = vol_monitor->config->report_freq;
} else if (vol_monitor->config->report_freq == 0) {
vol_monitor->read_cnt = 0;
vol_monitor->report_start = 0;
}
mutex_unlock(vol_monitor->mutex);
return ESP_OK;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/battery_service/monitors/voltage_monitor.c
|
C
|
apache-2.0
| 8,322
|
#
#Component Makefile
#
COMPONENT_ADD_LDFLAGS = -Wl,--whole-archive -l$(COMPONENT_NAME) -Wl,--no-whole-archive
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/battery_service/test/component.mk
|
Makefile
|
apache-2.0
| 112
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 <string.h>
#include "esp_log.h"
#include "audio_mem.h"
#include "board.h"
#include "audio_hal.h"
#include "unity.h"
#include "test_utils.h"
#include "driver/adc.h"
#include "esp_adc_cal.h"
#include "battery_service.h"
static const char *TAG = "battery_test";
TEST_CASE("create without configuration", "[battery_service]")
{
esp_log_level_set("BATTERY_SERVICE", ESP_LOG_NONE);
AUDIO_MEM_SHOW("MEMORY BEFORE");
int cnt = 10000;
while (cnt--) {
periph_service_handle_t battery_service = battery_service_create(NULL);
TEST_ASSERT_NULL(battery_service);
}
AUDIO_MEM_SHOW("MEMORY AFTER");
}
TEST_CASE("create with configuration all zero", "[battery_service]")
{
battery_service_config_t battery_config = { 0 };
AUDIO_MEM_SHOW("MEMORY BEFORE");
int cnt = 10000;
while (cnt--) {
periph_service_handle_t battery_service = battery_service_create(&battery_config);
TEST_ASSERT_NULL(battery_service);
}
AUDIO_MEM_SHOW("MEMORY AFTER");
}
TEST_CASE("create with configration default", "[battery_service]")
{
battery_service_config_t battery_config = BATTERY_SERVICE_DEFAULT_CONFIG();
esp_log_level_set("BATTERY_SERVICE", ESP_LOG_NONE);
AUDIO_MEM_SHOW("MEMORY BEFORE");
int cnt = 10000;
while (cnt--) {
periph_service_handle_t battery_service = battery_service_create(&battery_config);
TEST_ASSERT_NOT_NULL(battery_service);
TEST_ASSERT_EQUAL(ESP_OK, periph_service_destroy(battery_service));
vTaskDelay(1);
}
AUDIO_MEM_SHOW("MEMORY AFTER");
}
typedef struct {
int unit; /*!< ADC unit, see `adc_unit_t` */
int chan; /*!< ADC channel, see `adc_channel_t` */
int width; /*!< ADC width, see `adc_channel_t` */
int atten; /*!< ADC atten, see `adc_atten_t` */
int v_ref; /*!< default vref` */
} vol_adc_param_t;
static bool adc_init(void *user_data)
{
vol_adc_param_t *adc_cfg = (vol_adc_param_t *)user_data;
adc1_config_width(adc_cfg->width);
adc1_config_channel_atten(adc_cfg->chan, adc_cfg->atten);
return true;
}
static bool adc_deinit(void *user_data)
{
return true;
}
static int vol_read(void *user_data)
{
#define ADC_SAMPLES_NUM (10)
vol_adc_param_t *adc_cfg = (vol_adc_param_t *)user_data;
uint32_t data[ADC_SAMPLES_NUM] = { 0 };
uint32_t sum = 0;
int tmp = 0;
#if CONFIG_IDF_TARGET_ESP32
esp_adc_cal_characteristics_t characteristics;
esp_adc_cal_characterize(adc_cfg->unit, adc_cfg->atten, adc_cfg->width, adc_cfg->v_ref, &characteristics);
for (int i = 0; i < ADC_SAMPLES_NUM; ++i) {
esp_adc_cal_get_voltage(adc_cfg->chan, &characteristics, &data[i]);
}
#elif CONFIG_IDF_TARGET_ESP32S2
for (int i = 0; i < ADC_SAMPLES_NUM; i++) {
data[i] = adc1_get_raw((adc1_channel_t)channel);
}
#endif
for (int j = 0; j < ADC_SAMPLES_NUM - 1; j++) {
for (int i = 0; i < ADC_SAMPLES_NUM - j - 1; i++) {
if (data[i] > data[i + 1]) {
tmp = data[i];
data[i] = data[i + 1];
data[i + 1] = tmp;
}
}
}
for (int num = 1; num < ADC_SAMPLES_NUM - 1; num++)
sum += data[num];
return (sum / (ADC_SAMPLES_NUM - 2));
}
TEST_CASE("voltage monitor configure test", "[battery_service]")
{
vol_adc_param_t adc_cfg = {
.unit = ADC_UNIT_1,
.chan = ADC_CHANNEL_1,
.width = ADC_WIDTH_BIT_12,
.atten = ADC_ATTEN_11db,
.v_ref = 1100,
};
vol_monitor_param_t vol_monitor_cfg = {
.init = adc_init,
.deinit = adc_deinit,
.vol_get = vol_read,
.read_freq = 2,
.report_freq = 2,
.vol_full_threshold = 0,
.vol_low_threshold = 0,
};
periph_service_handle_t battery_service = NULL;
battery_service_config_t battery_config = BATTERY_SERVICE_DEFAULT_CONFIG();
vol_monitor_handle_t vol_monitor = NULL;
vol_monitor_cfg.init = NULL;
TEST_ASSERT_NULL(vol_monitor_create(&vol_monitor_cfg));
vol_monitor_cfg.init = adc_init;
printf("\r\n");
vol_monitor_cfg.deinit = NULL;
TEST_ASSERT_NULL(vol_monitor_create(&vol_monitor_cfg));
vol_monitor_cfg.deinit = adc_deinit;
printf("\r\n");
vol_monitor_cfg.vol_get = NULL;
TEST_ASSERT_NULL(vol_monitor_create(&vol_monitor_cfg));
vol_monitor_cfg.vol_get = vol_read;
printf("\r\n");
vol_monitor_cfg.user_data = audio_calloc(1, sizeof(vol_adc_param_t));
AUDIO_MEM_CHECK(TAG, vol_monitor_cfg.user_data, return);
memcpy(vol_monitor_cfg.user_data, &adc_cfg, sizeof(vol_adc_param_t));
// read_freq
vol_monitor_cfg.read_freq = -1;
TEST_ASSERT_NULL(vol_monitor_create(&vol_monitor_cfg));
printf("\r\n");
vol_monitor_cfg.read_freq = 0;
TEST_ASSERT_NULL(vol_monitor_create(&vol_monitor_cfg));
printf("\r\n");
vol_monitor_cfg.read_freq = 100;
TEST_ASSERT_NOT_NULL((vol_monitor = vol_monitor_create(&vol_monitor_cfg)));
TEST_ASSERT_EQUAL(ESP_OK, vol_monitor_destroy(vol_monitor));
vol_monitor = NULL;
printf("\r\n");
// report_freq
vol_monitor_cfg.report_freq = -1;
TEST_ASSERT_NULL(vol_monitor_create(&vol_monitor_cfg));
printf("\r\n");
vol_monitor_cfg.report_freq = 0;
TEST_ASSERT_NOT_NULL((vol_monitor = vol_monitor_create(&vol_monitor_cfg)));
TEST_ASSERT_EQUAL(ESP_OK, vol_monitor_destroy(vol_monitor));
vol_monitor = NULL;
printf("\r\n");
vol_monitor_cfg.report_freq = 100;
TEST_ASSERT_NOT_NULL((vol_monitor = vol_monitor_create(&vol_monitor_cfg)));
TEST_ASSERT_EQUAL(ESP_OK, vol_monitor_destroy(vol_monitor));
vol_monitor = NULL;
printf("\r\n");
// full
vol_monitor_cfg.vol_full_threshold = -1;
TEST_ASSERT_NULL(vol_monitor_create(&vol_monitor_cfg));
printf("\r\n");
vol_monitor_cfg.vol_full_threshold = 0;
TEST_ASSERT_NOT_NULL((vol_monitor = vol_monitor_create(&vol_monitor_cfg)));
TEST_ASSERT_EQUAL(ESP_OK, vol_monitor_destroy(vol_monitor));
vol_monitor = NULL;
printf("\r\n");
vol_monitor_cfg.vol_full_threshold = 100;
TEST_ASSERT_NOT_NULL((vol_monitor = vol_monitor_create(&vol_monitor_cfg)));
TEST_ASSERT_EQUAL(ESP_OK, vol_monitor_destroy(vol_monitor));
vol_monitor = NULL;
printf("\r\n");
// low
vol_monitor_cfg.vol_low_threshold = -1;
TEST_ASSERT_NULL(vol_monitor_create(&vol_monitor_cfg));
printf("\r\n");
vol_monitor_cfg.vol_low_threshold = 0;
TEST_ASSERT_NOT_NULL((vol_monitor = vol_monitor_create(&vol_monitor_cfg)));
TEST_ASSERT_EQUAL(ESP_OK, vol_monitor_destroy(vol_monitor));
printf("\r\n");
vol_monitor_cfg.vol_low_threshold = 50;
TEST_ASSERT_NOT_NULL((vol_monitor = vol_monitor_create(&vol_monitor_cfg)));
TEST_ASSERT_EQUAL(ESP_OK, vol_monitor_destroy(vol_monitor));
vol_monitor = NULL;
printf("\r\n");
vol_monitor_cfg.vol_low_threshold = 100;
TEST_ASSERT_NULL(vol_monitor_create(&vol_monitor_cfg));
printf("\r\n");
vol_monitor_cfg.vol_low_threshold = 200;
TEST_ASSERT_NULL(vol_monitor_create(&vol_monitor_cfg));
printf("\r\n");
free(vol_monitor_cfg.user_data);
}
#define BATTERY_FREQ_REPORT (BIT0)
#define BATTERY_FULL_REPORT (BIT1)
#define BATTERY_LOW_REPORT (BIT2)
EventGroupHandle_t sync_events;
static esp_err_t battery_service_cb(periph_service_handle_t handle, periph_service_event_t *evt, void *ctx)
{
if (evt->type == BAT_SERV_EVENT_VOL_REPORT) {
ESP_LOGI(TAG, "GOT VOL REPORT");
xEventGroupSetBits(sync_events, BATTERY_FREQ_REPORT);
} else if (evt->type == BAT_SERV_EVENT_BAT_FULL) {
ESP_LOGI(TAG, "GOT FULL REPORT");
xEventGroupSetBits(sync_events, BATTERY_FULL_REPORT);
} else if (evt->type == BAT_SERV_EVENT_BAT_LOW) {
ESP_LOGI(TAG, "GOT LOW REPORT");
xEventGroupSetBits(sync_events, BATTERY_LOW_REPORT);
} else {
ESP_LOGE(TAG, "error message");
}
return ESP_OK;
}
TEST_CASE("voltage monitor freq report", "[battery_service]")
{
sync_events = xEventGroupCreate();
TEST_ASSERT_NOT_NULL(sync_events);
vol_adc_param_t adc_cfg = {
.unit = ADC_UNIT_1,
.chan = ADC_CHANNEL_1,
.width = ADC_WIDTH_BIT_12,
.atten = ADC_ATTEN_11db,
.v_ref = 1100,
};
vol_monitor_param_t vol_monitor_cfg = {
.init = adc_init,
.deinit = adc_deinit,
.vol_get = vol_read,
.read_freq = 1,
.report_freq = 1,
.vol_full_threshold = 0,
.vol_low_threshold = 0,
};
vol_monitor_cfg.user_data = audio_calloc(1, sizeof(vol_adc_param_t));
AUDIO_MEM_CHECK(TAG, vol_monitor_cfg.user_data, return);
memcpy(vol_monitor_cfg.user_data, &adc_cfg, sizeof(vol_adc_param_t));
battery_service_config_t battery_config = BATTERY_SERVICE_DEFAULT_CONFIG();
vol_monitor_handle_t vol_monitor = vol_monitor_create(&vol_monitor_cfg);
TEST_ASSERT_NOT_NULL(vol_monitor);
battery_config.vol_monitor = vol_monitor;
battery_config.evt_cb = battery_service_cb;
periph_service_handle_t battery_service = battery_service_create(&battery_config);
TEST_ASSERT_NOT_NULL(battery_service);
TEST_ASSERT_EQUAL(ESP_OK, periph_service_start(battery_service));
TEST_ASSERT_EQUAL(ESP_OK, battery_service_vol_report_switch(battery_service, true));
EventBits_t bits = xEventGroupWaitBits(sync_events, BATTERY_FREQ_REPORT, true, true, pdMS_TO_TICKS(4000));
TEST_ASSERT_EQUAL(BATTERY_FREQ_REPORT, bits & BATTERY_FREQ_REPORT);
TEST_ASSERT_EQUAL(ESP_OK, battery_service_set_vol_report_freq(battery_service, 2));
xEventGroupClearBits(sync_events, BATTERY_FREQ_REPORT);
bits = xEventGroupWaitBits(sync_events, BATTERY_FREQ_REPORT, true, true, pdMS_TO_TICKS(4000));
TEST_ASSERT_EQUAL(BATTERY_FREQ_REPORT, bits & BATTERY_FREQ_REPORT);
TEST_ASSERT_EQUAL(ESP_OK, battery_service_vol_report_switch(battery_service, false));
bits = xEventGroupWaitBits(sync_events, BATTERY_FREQ_REPORT, true, true, pdMS_TO_TICKS(4000));
TEST_ASSERT_NOT_EQUAL(BATTERY_FREQ_REPORT, bits & BATTERY_FREQ_REPORT);
TEST_ASSERT_EQUAL(ESP_OK, periph_service_destroy(battery_service));
TEST_ASSERT_EQUAL(ESP_OK, vol_monitor_destroy(vol_monitor));
vol_monitor = NULL;
vol_monitor_cfg.report_freq = 0;
vol_monitor = vol_monitor_create(&vol_monitor_cfg);
TEST_ASSERT_NOT_NULL(vol_monitor);
battery_config.vol_monitor = vol_monitor;
battery_service = battery_service_create(&battery_config);
TEST_ASSERT_NOT_NULL(battery_service);
TEST_ASSERT_EQUAL(ESP_OK, periph_service_start(battery_service));
TEST_ASSERT_EQUAL(ESP_OK, battery_service_vol_report_switch(battery_service, true));
bits = xEventGroupWaitBits(sync_events, BATTERY_FREQ_REPORT, true, true, pdMS_TO_TICKS(4000));
TEST_ASSERT_EQUAL(0x00000000, bits & BATTERY_FREQ_REPORT);
TEST_ASSERT_EQUAL(ESP_OK, periph_service_destroy(battery_service));
TEST_ASSERT_EQUAL(ESP_OK, vol_monitor_destroy(vol_monitor));
vol_monitor = NULL;
vEventGroupDelete(sync_events);
free(vol_monitor_cfg.user_data);
}
TEST_CASE("voltage monitor battery full message", "[battery_service]")
{
sync_events = xEventGroupCreate();
TEST_ASSERT_NOT_NULL(sync_events);
vol_adc_param_t adc_cfg = {
.unit = ADC_UNIT_1,
.chan = ADC_CHANNEL_1,
.width = ADC_WIDTH_BIT_12,
.atten = ADC_ATTEN_11db,
.v_ref = 1100,
};
vol_monitor_param_t vol_monitor_cfg = {
.init = adc_init,
.deinit = adc_deinit,
.vol_get = vol_read,
.read_freq = 1,
.report_freq = 0,
.vol_full_threshold = 0,
.vol_low_threshold = 0,
};
vol_monitor_cfg.user_data = audio_calloc(1, sizeof(vol_adc_param_t));
AUDIO_MEM_CHECK(TAG, vol_monitor_cfg.user_data, return);
memcpy(vol_monitor_cfg.user_data, &adc_cfg, sizeof(vol_adc_param_t));
battery_service_config_t battery_config = BATTERY_SERVICE_DEFAULT_CONFIG();
vol_monitor_handle_t vol_monitor = vol_monitor_create(&vol_monitor_cfg);
TEST_ASSERT_NOT_NULL(vol_monitor);
battery_config.vol_monitor = vol_monitor;
battery_config.evt_cb = battery_service_cb;
periph_service_handle_t battery_service = battery_service_create(&battery_config);
TEST_ASSERT_NOT_NULL(battery_service);
TEST_ASSERT_EQUAL(ESP_OK, periph_service_start(battery_service));
EventBits_t bits = xEventGroupWaitBits(sync_events, BATTERY_FULL_REPORT, true, true, pdMS_TO_TICKS(4000));
TEST_ASSERT_NOT_EQUAL(BATTERY_FULL_REPORT, bits & BATTERY_FULL_REPORT);
TEST_ASSERT_EQUAL(ESP_OK, periph_service_destroy(battery_service));
TEST_ASSERT_EQUAL(ESP_OK, vol_monitor_destroy(vol_monitor));
vol_monitor = NULL;
vol_monitor_cfg.vol_full_threshold = 100;
vol_monitor = vol_monitor_create(&vol_monitor_cfg);
TEST_ASSERT_NOT_NULL(vol_monitor);
battery_config.vol_monitor = vol_monitor;
battery_service = battery_service_create(&battery_config);
TEST_ASSERT_NOT_NULL(battery_service);
TEST_ASSERT_EQUAL(ESP_OK, periph_service_start(battery_service));
bits = xEventGroupWaitBits(sync_events, BATTERY_FULL_REPORT, true, true, pdMS_TO_TICKS(4000));
TEST_ASSERT_EQUAL(BATTERY_FULL_REPORT, bits & BATTERY_FULL_REPORT);
TEST_ASSERT_EQUAL(ESP_OK, periph_service_destroy(battery_service));
TEST_ASSERT_EQUAL(ESP_OK, vol_monitor_destroy(vol_monitor));
vol_monitor = NULL;
vEventGroupDelete(sync_events);
free(vol_monitor_cfg.user_data);
}
TEST_CASE("voltage monitor battery low message", "[battery_service]")
{
sync_events = xEventGroupCreate();
TEST_ASSERT_NOT_NULL(sync_events);
vol_adc_param_t adc_cfg = {
.unit = ADC_UNIT_1,
.chan = ADC_CHANNEL_1,
.width = ADC_WIDTH_BIT_12,
.atten = ADC_ATTEN_11db,
.v_ref = 1100,
};
vol_monitor_param_t vol_monitor_cfg = {
.init = adc_init,
.deinit = adc_deinit,
.vol_get = vol_read,
.read_freq = 1,
.report_freq = 0,
.vol_full_threshold = 0,
.vol_low_threshold = 0,
};
vol_monitor_cfg.user_data = audio_calloc(1, sizeof(vol_adc_param_t));
AUDIO_MEM_CHECK(TAG, vol_monitor_cfg.user_data, return);
memcpy(vol_monitor_cfg.user_data, &adc_cfg, sizeof(vol_adc_param_t));
battery_service_config_t battery_config = BATTERY_SERVICE_DEFAULT_CONFIG();
vol_monitor_handle_t vol_monitor = vol_monitor_create(&vol_monitor_cfg);
TEST_ASSERT_NOT_NULL(vol_monitor);
battery_config.vol_monitor = vol_monitor;
battery_config.evt_cb = battery_service_cb;
periph_service_handle_t battery_service = battery_service_create(&battery_config);
TEST_ASSERT_NOT_NULL(battery_service);
TEST_ASSERT_EQUAL(ESP_OK, periph_service_start(battery_service));
EventBits_t bits = xEventGroupWaitBits(sync_events, BATTERY_LOW_REPORT, true, true, pdMS_TO_TICKS(4000));
TEST_ASSERT_NOT_EQUAL(BATTERY_LOW_REPORT, bits & BATTERY_LOW_REPORT);
TEST_ASSERT_EQUAL(ESP_OK, periph_service_destroy(battery_service));
TEST_ASSERT_EQUAL(ESP_OK, vol_monitor_destroy(vol_monitor));
vol_monitor = NULL;
vol_monitor_cfg.vol_low_threshold = 10000;
vol_monitor = vol_monitor_create(&vol_monitor_cfg);
TEST_ASSERT_NOT_NULL(vol_monitor);
battery_config.vol_monitor = vol_monitor;
battery_service = battery_service_create(&battery_config);
TEST_ASSERT_NOT_NULL(battery_service);
TEST_ASSERT_EQUAL(ESP_OK, periph_service_start(battery_service));
bits = xEventGroupWaitBits(sync_events, BATTERY_LOW_REPORT, true, true, pdMS_TO_TICKS(4000));
TEST_ASSERT_EQUAL(BATTERY_LOW_REPORT, bits & BATTERY_LOW_REPORT);
TEST_ASSERT_EQUAL(ESP_OK, periph_service_destroy(battery_service));
TEST_ASSERT_EQUAL(ESP_OK, vol_monitor_destroy(vol_monitor));
vol_monitor = NULL;
vEventGroupDelete(sync_events);
free(vol_monitor_cfg.user_data);
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/battery_service/test/test_battery_service.c
|
C
|
apache-2.0
| 17,174
|
set(COMPONENT_ADD_INCLUDEDIRS include)
# Edit following two lines to set component requirements (see docs)
set(COMPONENT_REQUIRES bt audio_sal audio_pipeline esp_peripherals audio_stream audio_hal)
set(COMPONENT_PRIV_REQUIRES nvs_flash)
set(COMPONENT_SRCS ./bluetooth_service.c ./bt_keycontrol.c ./a2dp_stream.c ./hfp_stream.c)
register_component()
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/bluetooth_service/CMakeLists.txt
|
CMake
|
apache-2.0
| 352
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 <stdlib.h>
#include <string.h>
#include "nvs.h"
#include "nvs_flash.h"
#include "esp_log.h"
#include "esp_peripherals.h"
#include "audio_common.h"
#include "audio_mem.h"
#include "audio_thread.h"
#include "sdkconfig.h"
#include "a2dp_stream.h"
#if CONFIG_BT_ENABLED
static const char *TAG = "A2DP_STREAM";
typedef struct {
audio_element_handle_t sink_stream;
audio_element_handle_t source_stream;
a2dp_stream_user_callback_t user_callback;
esp_periph_handle_t bt_avrc_periph;
bool avrcp_conn_state;
audio_stream_type_t stream_type;
uint8_t trans_label;
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
audio_hal_handle_t audio_hal;
bool avrcp_conn_tg_state;
_lock_t volume_lock;
int16_t volume;
bool volume_notify;
#endif
audio_thread_t a2dp_thread;
QueueHandle_t a2dp_queue;
} aadp_info_t;
typedef struct {
enum {
A2DP_TYPE_SINK ,
A2DP_TYPE_DESTORY,
} type;
void *data;
size_t size;
} a2dp_data_t;
static aadp_info_t s_aadp_handler = { 0 };
int16_t default_volume = 50;
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
static void bt_avrc_tg_cb(esp_avrc_tg_cb_event_t event, esp_avrc_tg_cb_param_t *param);
#endif
static const char *audio_state_str[] = { "Suspended", "Stopped", "Started" };
static void bt_avrc_ct_cb(esp_avrc_ct_cb_event_t event, esp_avrc_ct_cb_param_t *param);
static void audio_a2dp_stream_thread(void *pvParameters)
{
(void) pvParameters;
a2dp_data_t recv_msg;
bool _aadp_task_run = true;
while(_aadp_task_run) {
if ( pdTRUE == xQueueReceive (s_aadp_handler.a2dp_queue, &recv_msg, portMAX_DELAY) ) {
switch (recv_msg.type) {
case A2DP_TYPE_SINK:
audio_element_output(s_aadp_handler.sink_stream, (char *)recv_msg.data, recv_msg.size);
audio_free(recv_msg.data);
recv_msg.data = NULL;
break;
case A2DP_TYPE_DESTORY:
_aadp_task_run = false;
break;
default:
break;
}
}
}
ESP_LOGI(TAG, "Delete the audio_a2dp_stream_thread");
vTaskDelete(NULL);
}
static void bt_a2d_sink_cb(esp_a2d_cb_event_t event, esp_a2d_cb_param_t *param)
{
if (s_aadp_handler.user_callback.user_a2d_cb) {
s_aadp_handler.user_callback.user_a2d_cb(event, param);
}
esp_a2d_cb_param_t *a2d = NULL;
switch (event) {
case ESP_A2D_CONNECTION_STATE_EVT:
a2d = (esp_a2d_cb_param_t *)(param);
uint8_t *bda = a2d->conn_stat.remote_bda;
ESP_LOGI(TAG, "A2DP bd address:, [%02x:%02x:%02x:%02x:%02x:%02x]",
bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
if (param->conn_stat.state == ESP_A2D_CONNECTION_STATE_DISCONNECTED) {
ESP_LOGI(TAG, "A2DP connection state = DISCONNECTED");
if (s_aadp_handler.sink_stream) {
audio_element_report_status(s_aadp_handler.sink_stream, AEL_STATUS_INPUT_DONE);
}
if (s_aadp_handler.bt_avrc_periph) {
esp_periph_send_event(s_aadp_handler.bt_avrc_periph, PERIPH_BLUETOOTH_DISCONNECTED, NULL, 0);
}
} else if (param->conn_stat.state == ESP_A2D_CONNECTION_STATE_CONNECTED) {
ESP_LOGI(TAG, "A2DP connection state = CONNECTED");
if (s_aadp_handler.bt_avrc_periph) {
esp_periph_send_event(s_aadp_handler.bt_avrc_periph, PERIPH_BLUETOOTH_CONNECTED, NULL, 0);
}
}
break;
case ESP_A2D_AUDIO_STATE_EVT:
a2d = (esp_a2d_cb_param_t *)(param);
ESP_LOGD(TAG, "A2DP audio state: %s", audio_state_str[a2d->audio_stat.state]);
if (s_aadp_handler.bt_avrc_periph == NULL) {
break;
}
if (ESP_A2D_AUDIO_STATE_STARTED == a2d->audio_stat.state) {
esp_periph_send_event(s_aadp_handler.bt_avrc_periph, PERIPH_BLUETOOTH_AUDIO_STARTED, NULL, 0);
} else if (ESP_A2D_AUDIO_STATE_REMOTE_SUSPEND == a2d->audio_stat.state) {
esp_periph_send_event(s_aadp_handler.bt_avrc_periph, PERIPH_BLUETOOTH_AUDIO_SUSPENDED, NULL, 0);
} else if (ESP_A2D_AUDIO_STATE_STOPPED == a2d->audio_stat.state) {
esp_periph_send_event(s_aadp_handler.bt_avrc_periph, PERIPH_BLUETOOTH_AUDIO_STOPPED, NULL, 0);
}
break;
case ESP_A2D_AUDIO_CFG_EVT:
ESP_LOGI(TAG, "A2DP audio stream configuration, codec type %d", param->audio_cfg.mcc.type);
if (param->audio_cfg.mcc.type == ESP_A2D_MCT_SBC) {
int sample_rate = 16000;
char oct0 = param->audio_cfg.mcc.cie.sbc[0];
if (oct0 & (0x01 << 6)) {
sample_rate = 32000;
} else if (oct0 & (0x01 << 5)) {
sample_rate = 44100;
} else if (oct0 & (0x01 << 4)) {
sample_rate = 48000;
}
ESP_LOGI(TAG, "Bluetooth configured, sample rate=%d", sample_rate);
if (s_aadp_handler.sink_stream == NULL) {
break;
}
audio_element_set_music_info(s_aadp_handler.sink_stream, sample_rate, 2, 16);
audio_element_report_info(s_aadp_handler.sink_stream);
}
break;
default:
ESP_LOGI(TAG, "Unhandled A2DP event: %d", event);
break;
}
}
static void bt_a2d_sink_data_cb(const uint8_t *data, uint32_t len)
{
if (s_aadp_handler.user_callback.user_a2d_sink_data_cb) {
s_aadp_handler.user_callback.user_a2d_sink_data_cb(data, len);
}
if (s_aadp_handler.sink_stream) {
if (audio_element_get_state(s_aadp_handler.sink_stream) == AEL_STATE_RUNNING) {
a2dp_data_t send_msg = {0};
send_msg.data = (uint8_t *) audio_calloc(1, len);
if (!send_msg.data) {
ESP_LOGE(TAG, "No ineffecitive memory to allocate(%d)", __LINE__);
return;
}
memcpy(send_msg.data, data, len);
send_msg.size = len;
send_msg.type = A2DP_TYPE_SINK;
if ((!s_aadp_handler.a2dp_queue) || xQueueSend( s_aadp_handler.a2dp_queue, &send_msg, 0) != pdPASS ) {
ESP_LOGW(TAG, "discard a2dp(%p) sink pkt, A2DP_STREAM_QUEUE_SIZE value needs to be expanded", s_aadp_handler.a2dp_queue);
audio_free(send_msg.data);
send_msg.data = NULL;
}
}
}
}
static void bt_a2d_source_cb(esp_a2d_cb_event_t event, esp_a2d_cb_param_t *param)
{
if (s_aadp_handler.user_callback.user_a2d_cb) {
s_aadp_handler.user_callback.user_a2d_cb(event, param);
}
switch (event) {
case ESP_A2D_CONNECTION_STATE_EVT:
if (param->conn_stat.state == ESP_A2D_CONNECTION_STATE_CONNECTED) {
ESP_LOGI(TAG, "a2dp source connected");
ESP_LOGI(TAG, "a2dp media ready checking ...");
esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_CHECK_SRC_RDY);
if (s_aadp_handler.bt_avrc_periph) {
esp_periph_send_event(s_aadp_handler.bt_avrc_periph, PERIPH_BLUETOOTH_CONNECTED, NULL, 0);
}
} else if (param->conn_stat.state == ESP_A2D_CONNECTION_STATE_DISCONNECTED) {
ESP_LOGI(TAG, "a2dp source disconnected");
esp_bt_gap_start_discovery(ESP_BT_INQ_MODE_GENERAL_INQUIRY, 10, 0);
if (s_aadp_handler.bt_avrc_periph) {
esp_periph_send_event(s_aadp_handler.bt_avrc_periph, PERIPH_BLUETOOTH_DISCONNECTED, NULL, 0);
}
}
break;
case ESP_A2D_MEDIA_CTRL_ACK_EVT:
if (param->media_ctrl_stat.cmd == ESP_A2D_MEDIA_CTRL_CHECK_SRC_RDY &&
param->media_ctrl_stat.status == ESP_A2D_MEDIA_CTRL_ACK_SUCCESS) {
esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_START);
}
break;
default:
break;
}
}
static int32_t bt_a2d_source_data_cb(uint8_t *data, int32_t len)
{
if (s_aadp_handler.source_stream) {
if (audio_element_get_state(s_aadp_handler.source_stream) == AEL_STATE_RUNNING) {
if (len < 0 || data == NULL) {
return 0;
}
len = audio_element_input(s_aadp_handler.source_stream, (char *)data, len);
if (len == AEL_IO_DONE) {
esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_STOP);
if (s_aadp_handler.bt_avrc_periph) {
esp_periph_send_event(s_aadp_handler.bt_avrc_periph, PERIPH_BLUETOOTH_AUDIO_SUSPENDED, NULL, 0);
}
}
return len;
}
}
return 0;
}
static esp_err_t a2dp_sink_destory(audio_element_handle_t self)
{
ESP_LOGI(TAG, "a2dp_sink_destory");
a2dp_data_t destory_msg = {
.type = A2DP_TYPE_DESTORY,
};
if ( xQueueSend( s_aadp_handler.a2dp_queue, &destory_msg, 0 ) != pdPASS ) {
ESP_LOGE(TAG, "Destory audio_a2dp_stream_thread failed");
return ESP_FAIL;
}
s_aadp_handler.sink_stream = NULL;
vQueueDelete(s_aadp_handler.a2dp_queue);
s_aadp_handler.a2dp_queue = NULL;
memset(&s_aadp_handler.user_callback, 0, sizeof(a2dp_stream_user_callback_t));
return ESP_OK;
}
static esp_err_t a2dp_source_destory(audio_element_handle_t self)
{
s_aadp_handler.source_stream = NULL;
memset(&s_aadp_handler.user_callback, 0, sizeof(a2dp_stream_user_callback_t));
return ESP_OK;
}
audio_element_handle_t a2dp_stream_init(a2dp_stream_config_t *config)
{
audio_element_handle_t el = NULL;
audio_element_cfg_t cfg = DEFAULT_AUDIO_ELEMENT_CONFIG();
if (s_aadp_handler.sink_stream || s_aadp_handler.source_stream) {
ESP_LOGE(TAG, "a2dp stream already created. please terminate before create.");
return NULL;
}
cfg.task_stack = -1; // No need task
cfg.tag = "aadp";
esp_avrc_ct_init();
esp_avrc_ct_register_callback(bt_avrc_ct_cb);
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
if (s_aadp_handler.audio_hal == NULL) {
s_aadp_handler.audio_hal = config->audio_hal;
}
esp_avrc_tg_init();
esp_avrc_tg_register_callback(bt_avrc_tg_cb);
esp_avrc_rn_evt_cap_mask_t evt_set = {0};
esp_avrc_rn_evt_bit_mask_operation(ESP_AVRC_BIT_MASK_OP_SET, &evt_set, ESP_AVRC_RN_VOLUME_CHANGE);
esp_avrc_tg_set_rn_evt_cap(&evt_set);
#endif
if (config->type == AUDIO_STREAM_READER) {
// A2DP sink
s_aadp_handler.stream_type = AUDIO_STREAM_READER;
cfg.destroy = a2dp_sink_destory;
el = s_aadp_handler.sink_stream = audio_element_init(&cfg);
esp_a2d_sink_register_data_callback(bt_a2d_sink_data_cb);
esp_a2d_register_callback(bt_a2d_sink_cb);
esp_a2d_sink_init();
} else {
// A2DP source
s_aadp_handler.stream_type = AUDIO_STREAM_WRITER;
cfg.destroy = a2dp_source_destory;
el = s_aadp_handler.source_stream = audio_element_init(&cfg);
esp_a2d_register_callback(bt_a2d_source_cb);
esp_a2d_source_register_data_callback(bt_a2d_source_data_cb);
esp_a2d_source_init();
}
AUDIO_MEM_CHECK(TAG, el, return NULL);
memcpy(&s_aadp_handler.user_callback, &config->user_callback, sizeof(a2dp_stream_user_callback_t));
if ( config->type == AUDIO_STREAM_READER ) {
s_aadp_handler.a2dp_queue = xQueueCreate(A2DP_STREAM_QUEUE_SIZE, sizeof(a2dp_data_t));
if (s_aadp_handler.a2dp_queue == 0) {
ESP_LOGE(TAG, "Create a2dp queue failed(%d)", __LINE__);
return NULL;
}
esp_err_t err = audio_thread_create(&s_aadp_handler.a2dp_thread, "audio_a2dp_stream_thread", audio_a2dp_stream_thread, NULL,
A2DP_STREAM_TASK_STACK, A2DP_STREAM_TASK_PRIO, A2DP_STREAM_TASK_IN_EXT, A2DP_STREAM_TASK_CORE);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Create audio_a2dp_stream_thread failed(%d)", __LINE__);
return NULL;
}
}
return el;
}
esp_err_t a2dp_destroy()
{
if (s_aadp_handler.stream_type == AUDIO_STREAM_READER) {
esp_a2d_sink_deinit();
} else if (s_aadp_handler.stream_type == AUDIO_STREAM_WRITER) {
esp_a2d_source_deinit();
}
return ESP_OK;
}
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
static void bt_avrc_volume_set_by_controller(int16_t volume)
{
ESP_LOGI(TAG, "Volume is set by remote controller %d%%\n", (uint32_t)volume * 100 / 0x7f);
_lock_acquire(&s_aadp_handler.volume_lock);
s_aadp_handler.volume = volume;
_lock_release(&s_aadp_handler.volume_lock);
if (s_aadp_handler.audio_hal) {
audio_hal_set_volume(s_aadp_handler.audio_hal, s_aadp_handler.volume);
}
}
static void bt_avrc_volume_set_by_local(int16_t volume)
{
ESP_LOGI(TAG, "Volume is set locally to: %d%%", volume );
_lock_acquire(&s_aadp_handler.volume_lock);
s_aadp_handler.volume = volume;
_lock_release(&s_aadp_handler.volume_lock);
esp_avrc_rn_param_t rn_param;
rn_param.volume = default_volume;
esp_avrc_tg_send_rn_rsp(ESP_AVRC_RN_VOLUME_CHANGE, ESP_AVRC_RN_RSP_CHANGED, &rn_param);
if (s_aadp_handler.audio_hal) {
audio_hal_set_volume(s_aadp_handler.audio_hal, s_aadp_handler.volume);
}
s_aadp_handler.volume_notify = false;
}
#endif
static void bt_avrc_ct_cb(esp_avrc_ct_cb_event_t event, esp_avrc_ct_cb_param_t *p_param)
{
esp_avrc_ct_cb_param_t *rc = p_param;
switch (event) {
case ESP_AVRC_CT_CONNECTION_STATE_EVT: {
uint8_t *bda = rc->conn_stat.remote_bda;
s_aadp_handler.avrcp_conn_state = rc->conn_stat.connected;
if (rc->conn_stat.connected) {
ESP_LOGD(TAG, "ESP_AVRC_CT_CONNECTION_STATE_EVT");
bt_key_act_sm_init();
} else if (0 == rc->conn_stat.connected) {
bt_key_act_sm_deinit();
}
ESP_LOGD(TAG, "AVRC conn_state evt: state %d, [%02x:%02x:%02x:%02x:%02x:%02x]",
rc->conn_stat.connected, bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
break;
}
case ESP_AVRC_CT_PASSTHROUGH_RSP_EVT: {
if (s_aadp_handler.avrcp_conn_state) {
ESP_LOGD(TAG, "AVRC passthrough rsp: key_code 0x%x, key_state %d", rc->psth_rsp.key_code, rc->psth_rsp.key_state);
bt_key_act_param_t param;
memset(¶m, 0, sizeof(bt_key_act_param_t));
param.evt = event;
param.tl = rc->psth_rsp.tl;
param.key_code = rc->psth_rsp.key_code;
param.key_state = rc->psth_rsp.key_state;
bt_key_act_state_machine(¶m);
}
break;
}
case ESP_AVRC_CT_METADATA_RSP_EVT: {
ESP_LOGD(TAG, "AVRC metadata rsp: attribute id 0x%x, %s", rc->meta_rsp.attr_id, rc->meta_rsp.attr_text);
// free(rc->meta_rsp.attr_text);
break;
}
case ESP_AVRC_CT_CHANGE_NOTIFY_EVT: {
// ESP_LOGD(TAG, "AVRC event notification: %u, param: %u", rc->change_ntf.event_id, rc->change_ntf.event_parameter);
break;
}
case ESP_AVRC_CT_REMOTE_FEATURES_EVT: {
ESP_LOGW(TAG, "AVRC ct remote features %x", rc->rmt_feats.feat_mask);
break;
}
default:
ESP_LOGE(TAG, "%s unhandled evt %d", __func__, event);
break;
}
}
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
static void bt_avrc_tg_cb(esp_avrc_tg_cb_event_t event, esp_avrc_tg_cb_param_t *param)
{
ESP_LOGD(TAG, "%s evt %d", __func__, event);
esp_avrc_tg_cb_param_t *rc = (esp_avrc_tg_cb_param_t *)(param);
switch (event) {
case ESP_AVRC_TG_CONNECTION_STATE_EVT: {
uint8_t *bda = rc->conn_stat.remote_bda;
ESP_LOGI(TAG, "AVRC conn_state evt: state %d, [%02x:%02x:%02x:%02x:%02x:%02x]",
rc->conn_stat.connected, bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
s_aadp_handler.avrcp_conn_tg_state = rc->conn_stat.connected;
break;
}
case ESP_AVRC_TG_PASSTHROUGH_CMD_EVT: {
ESP_LOGI(TAG, "AVRC passthrough cmd: key_code 0x%x, key_state %d", rc->psth_cmd.key_code, rc->psth_cmd.key_state);
break;
}
case ESP_AVRC_TG_SET_ABSOLUTE_VOLUME_CMD_EVT: {
ESP_LOGI(TAG, "AVRC set absolute volume: %d%%", (int)rc->set_abs_vol.volume * 100/ 0x7f);
bt_avrc_volume_set_by_controller(rc->set_abs_vol.volume);
default_volume = rc->set_abs_vol.volume;
break;
}
case ESP_AVRC_TG_REGISTER_NOTIFICATION_EVT: {
ESP_LOGI(TAG, "AVRC register event notification: %d, param: 0x%x", rc->reg_ntf.event_id, rc->reg_ntf.event_parameter);
if (rc->reg_ntf.event_id == ESP_AVRC_RN_VOLUME_CHANGE) {
s_aadp_handler.volume_notify = true;
esp_avrc_rn_param_t rn_param;
rn_param.volume = default_volume;
ESP_LOGI(TAG, "rn_param.volume:%d", rn_param.volume);
esp_avrc_tg_send_rn_rsp(ESP_AVRC_RN_VOLUME_CHANGE, ESP_AVRC_RN_RSP_INTERIM, &rn_param);
}
break;
}
case ESP_AVRC_TG_REMOTE_FEATURES_EVT: {
ESP_LOGW(TAG, "AVRC tg remote features %x, CT features %x", rc->rmt_feats.feat_mask, rc->rmt_feats.ct_feat_flag);
break;
}
default:
ESP_LOGE(TAG, "%s unhandled evt %d", __func__, event);
break;
}
}
#endif
static esp_err_t _bt_avrc_periph_init(esp_periph_handle_t periph)
{
return ESP_OK;
}
static esp_err_t _bt_avrc_periph_run(esp_periph_handle_t self, audio_event_iface_msg_t *msg)
{
return ESP_OK;
}
static esp_err_t _bt_avrc_periph_destroy(esp_periph_handle_t periph)
{
esp_avrc_ct_deinit();
s_aadp_handler.bt_avrc_periph = NULL;
return ESP_OK;
}
esp_periph_handle_t bt_create_periph()
{
if (s_aadp_handler.bt_avrc_periph) {
ESP_LOGE(TAG, "bt periph have been created");
return NULL;
}
s_aadp_handler.bt_avrc_periph = esp_periph_create(PERIPH_ID_BLUETOOTH, "periph_bt");
esp_periph_set_function(s_aadp_handler.bt_avrc_periph, _bt_avrc_periph_init, _bt_avrc_periph_run, _bt_avrc_periph_destroy);
return s_aadp_handler.bt_avrc_periph;
}
static esp_err_t periph_bt_avrc_passthrough_cmd(esp_periph_handle_t periph, uint8_t cmd)
{
esp_err_t err = ESP_OK;
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
if(s_aadp_handler.avrcp_conn_tg_state) {
if (cmd == ESP_AVRC_PT_CMD_VOL_DOWN) {
int16_t volume = (default_volume - 5) < 0 ? 0 : (default_volume - 5);
if(volume <= 0){
volume = 0;
}
bt_avrc_volume_set_by_local(volume);
default_volume = volume;
return err;
} else if (cmd == ESP_AVRC_PT_CMD_VOL_UP) {
int16_t volume = (default_volume + 5) > 0x7f ? 0x7f : (default_volume + 5);
if(volume >= 100){
volume = 100;
}
bt_avrc_volume_set_by_local(volume);
default_volume = volume;
return err;
}
}
#endif
if (s_aadp_handler.avrcp_conn_state) {
bt_key_act_param_t param;
memset(¶m, 0, sizeof(bt_key_act_param_t));
param.evt = ESP_AVRC_CT_KEY_STATE_CHG_EVT;
param.key_code = cmd;
param.key_state = 0;
param.tl = s_aadp_handler.trans_label & 0x0F;
s_aadp_handler.trans_label = (s_aadp_handler.trans_label + 2) & 0x0f;
bt_key_act_state_machine(¶m);
}
return err;
}
esp_err_t periph_bt_play(esp_periph_handle_t periph)
{
esp_err_t err = ESP_OK;
if (s_aadp_handler.stream_type == AUDIO_STREAM_READER) {
err = periph_bt_avrc_passthrough_cmd(periph, ESP_AVRC_PT_CMD_PLAY);
} else {
err = esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_CHECK_SRC_RDY);
}
return err;
}
esp_err_t periph_bt_pause(esp_periph_handle_t periph)
{
esp_err_t err = ESP_OK;
if (s_aadp_handler.stream_type == AUDIO_STREAM_READER) {
err = periph_bt_avrc_passthrough_cmd(periph, ESP_AVRC_PT_CMD_PAUSE);
} else {
err = esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_SUSPEND);
}
return err;
}
esp_err_t periph_bt_stop(esp_periph_handle_t periph)
{
esp_err_t err = ESP_OK;
if (s_aadp_handler.stream_type == AUDIO_STREAM_READER) {
err = periph_bt_avrc_passthrough_cmd(periph, ESP_AVRC_PT_CMD_STOP);
} else {
esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_STOP);
}
return err;
}
esp_err_t periph_bt_avrc_next(esp_periph_handle_t periph)
{
return periph_bt_avrc_passthrough_cmd(periph, ESP_AVRC_PT_CMD_FORWARD);
}
esp_err_t periph_bt_avrc_prev(esp_periph_handle_t periph)
{
return periph_bt_avrc_passthrough_cmd(periph, ESP_AVRC_PT_CMD_BACKWARD);
}
esp_err_t periph_bt_avrc_rewind(esp_periph_handle_t periph)
{
return periph_bt_avrc_passthrough_cmd(periph, ESP_AVRC_PT_CMD_REWIND);
}
esp_err_t periph_bt_avrc_fast_forward(esp_periph_handle_t periph)
{
return periph_bt_avrc_passthrough_cmd(periph, ESP_AVRC_PT_CMD_FAST_FORWARD);
}
esp_err_t periph_bt_discover(esp_periph_handle_t periph)
{
if (s_aadp_handler.stream_type == AUDIO_STREAM_READER) {
return esp_bt_gap_start_discovery(ESP_BT_INQ_MODE_GENERAL_INQUIRY, 10, 0);
}
return ESP_OK;
}
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
esp_err_t periph_bt_volume_up(esp_periph_handle_t periph)
{
return periph_bt_avrc_passthrough_cmd(periph, ESP_AVRC_PT_CMD_VOL_UP);
}
esp_err_t periph_bt_volume_down(esp_periph_handle_t periph)
{
return periph_bt_avrc_passthrough_cmd(periph, ESP_AVRC_PT_CMD_VOL_DOWN);
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/bluetooth_service/a2dp_stream.c
|
C
|
apache-2.0
| 23,318
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 <stdlib.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "audio_mem.h"
#include "sdkconfig.h"
#if __has_include("esp_idf_version.h")
#include "esp_idf_version.h"
#else
#define ESP_IDF_VERSION_VAL(major, minor, patch) 1
#endif
#if CONFIG_BT_ENABLED
#include "esp_a2dp_api.h"
#include "esp_avrc_api.h"
#include "esp_bt.h"
#include "esp_bt_device.h"
#include "esp_bt_main.h"
#include "esp_gap_bt_api.h"
#include "bluetooth_service.h"
#include "bt_keycontrol.h"
static const char *TAG = "BLUETOOTH_SERVICE";
#define BT_SOURCE_DEFAULT_REMOTE_NAME "ESP-ADF-SPEAKER"
#define VALIDATE_BT(periph, ret) \
if (!(periph && esp_periph_get_id(periph) == PERIPH_ID_BLUETOOTH)) { \
ESP_LOGE(TAG, "Invalid Bluetooth periph, at line %d", __LINE__); \
return ret; \
}
/* A2DP source global state */
typedef enum {
BT_SOURCE_STATE_IDLE,
BT_SOURCE_STATE_DISCOVERING,
BT_SOURCE_STATE_DISCOVERED,
BT_SOURCE_STATE_UNCONNECTED,
BT_SOURCE_STATE_CONNECTING,
BT_SOURCE_STATE_CONNECTED,
BT_SOURCE_STATE_DISCONNECTING,
} esp_a2d_source_state_t;
typedef uint8_t esp_peer_bdname_t[ESP_BT_GAP_MAX_BDNAME_LEN + 1];
typedef struct bluetooth_service {
audio_element_handle_t stream;
esp_periph_handle_t periph;
audio_stream_type_t stream_type;
esp_bd_addr_t remote_bda;
esp_peer_bdname_t peer_bdname;
esp_a2d_connection_state_t connection_state;
esp_a2d_source_state_t source_a2d_state;
esp_a2d_audio_state_t audio_state;
uint64_t pos;
uint8_t tl;
bool avrc_connected;
int a2dp_sample_rate;
} bluetooth_service_t;
bluetooth_service_t *g_bt_service = NULL;
static const char *conn_state_str[] = { "Disconnected", "Connecting", "Connected", "Disconnecting" };
static const char *audio_state_str[] = { "Suspended", "Stopped", "Started" };
static void bt_a2d_sink_cb(esp_a2d_cb_event_t event, esp_a2d_cb_param_t *p_param)
{
esp_a2d_cb_param_t *a2d = NULL;
switch (event) {
case ESP_A2D_CONNECTION_STATE_EVT:
a2d = (esp_a2d_cb_param_t *)(p_param);
uint8_t *bda = a2d->conn_stat.remote_bda;
ESP_LOGD(TAG, "A2DP connection state: %s, [%02x:%02x:%02x:%02x:%02x:%02x]",
conn_state_str[a2d->conn_stat.state], bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
if (g_bt_service->connection_state == ESP_A2D_CONNECTION_STATE_DISCONNECTED
&& a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_CONNECTED) {
memcpy(&g_bt_service->remote_bda, &a2d->conn_stat.remote_bda, sizeof(esp_bd_addr_t));
g_bt_service->connection_state = a2d->conn_stat.state;
ESP_LOGD(TAG, "A2DP connection state = CONNECTED");
if (g_bt_service->periph) {
esp_periph_send_event(g_bt_service->periph, PERIPH_BLUETOOTH_CONNECTED, NULL, 0);
}
}
if (memcmp(&g_bt_service->remote_bda, &a2d->conn_stat.remote_bda, sizeof(esp_bd_addr_t)) == 0
&& g_bt_service->connection_state == ESP_A2D_CONNECTION_STATE_CONNECTED
&& a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_DISCONNECTED) {
memset(&g_bt_service->remote_bda, 0, sizeof(esp_bd_addr_t));
g_bt_service->connection_state = ESP_A2D_CONNECTION_STATE_DISCONNECTED;
ESP_LOGD(TAG, "A2DP connection state = DISCONNECTED");
if (g_bt_service->stream) {
audio_element_report_status(g_bt_service->stream, AEL_STATUS_INPUT_DONE);
}
if (g_bt_service->periph) {
esp_periph_send_event(g_bt_service->periph, PERIPH_BLUETOOTH_DISCONNECTED, NULL, 0);
}
}
break;
case ESP_A2D_AUDIO_STATE_EVT:
a2d = (esp_a2d_cb_param_t *)(p_param);
ESP_LOGD(TAG, "A2DP audio state: %s", audio_state_str[a2d->audio_stat.state]);
g_bt_service->audio_state = a2d->audio_stat.state;
if (ESP_A2D_AUDIO_STATE_STARTED == a2d->audio_stat.state) {
g_bt_service->pos = 0;
}
if (g_bt_service->periph == NULL) {
break;
}
if (ESP_A2D_AUDIO_STATE_STARTED == a2d->audio_stat.state) {
esp_periph_send_event(g_bt_service->periph, PERIPH_BLUETOOTH_AUDIO_STARTED, NULL, 0);
} else if (ESP_A2D_AUDIO_STATE_REMOTE_SUSPEND == a2d->audio_stat.state) {
esp_periph_send_event(g_bt_service->periph, PERIPH_BLUETOOTH_AUDIO_SUSPENDED, NULL, 0);
} else if (ESP_A2D_AUDIO_STATE_STOPPED == a2d->audio_stat.state) {
esp_periph_send_event(g_bt_service->periph, PERIPH_BLUETOOTH_AUDIO_STOPPED, NULL, 0);
}
break;
case ESP_A2D_AUDIO_CFG_EVT:
a2d = (esp_a2d_cb_param_t *)(p_param);
ESP_LOGD(TAG, "A2DP audio stream configuration, codec type %d", a2d->audio_cfg.mcc.type);
if (a2d->audio_cfg.mcc.type == ESP_A2D_MCT_SBC) {
int sample_rate = 16000;
char oct0 = a2d->audio_cfg.mcc.cie.sbc[0];
if (oct0 & (0x01 << 6)) {
sample_rate = 32000;
} else if (oct0 & (0x01 << 5)) {
sample_rate = 44100;
} else if (oct0 & (0x01 << 4)) {
sample_rate = 48000;
}
g_bt_service->a2dp_sample_rate = sample_rate;
ESP_LOGD(TAG, "Bluetooth configured, sample rate=%d", sample_rate);
if (g_bt_service->stream == NULL) {
break;
}
audio_element_set_music_info(g_bt_service->stream, sample_rate, 2, 16);
audio_element_report_info(g_bt_service->stream);
}
break;
default:
ESP_LOGD(TAG, "Unhandled A2DP event: %d", event);
break;
}
}
static void bt_a2d_sink_data_cb(const uint8_t *data, uint32_t len)
{
if (g_bt_service->stream) {
if (audio_element_get_state(g_bt_service->stream) == AEL_STATE_RUNNING) {
audio_element_output(g_bt_service->stream, (char *)data, len);
}
}
}
static int32_t bt_a2d_source_data_cb(uint8_t *data, int32_t len)
{
if (g_bt_service->stream) {
if (audio_element_get_state(g_bt_service->stream) == AEL_STATE_RUNNING) {
if (len < 0 || data == NULL) {
return 0;
}
len = audio_element_input(g_bt_service->stream, (char *)data, len);
if (len == AEL_IO_DONE) {
if (g_bt_service->periph) {
esp_periph_send_event(g_bt_service->periph, PERIPH_BLUETOOTH_AUDIO_SUSPENDED, NULL, 0);
}
}
return len;
}
}
return 0;
}
static char *bda2str(esp_bd_addr_t bda, char *str, size_t size)
{
if (bda == NULL || str == NULL || size < 18) {
return NULL;
}
uint8_t *p = bda;
sprintf(str, "%02x:%02x:%02x:%02x:%02x:%02x",
p[0], p[1], p[2], p[3], p[4], p[5]);
return str;
}
static bool get_name_from_eir(uint8_t *eir, uint8_t *bdname, uint8_t *bdname_len)
{
uint8_t *rmt_bdname = NULL;
uint8_t rmt_bdname_len = 0;
if (!eir) {
return false;
}
rmt_bdname = esp_bt_gap_resolve_eir_data(eir, ESP_BT_EIR_TYPE_CMPL_LOCAL_NAME, &rmt_bdname_len);
if (!rmt_bdname) {
rmt_bdname = esp_bt_gap_resolve_eir_data(eir, ESP_BT_EIR_TYPE_SHORT_LOCAL_NAME, &rmt_bdname_len);
}
if (rmt_bdname) {
if (rmt_bdname_len > ESP_BT_GAP_MAX_BDNAME_LEN) {
rmt_bdname_len = ESP_BT_GAP_MAX_BDNAME_LEN;
}
if (bdname) {
memcpy(bdname, rmt_bdname, rmt_bdname_len);
bdname[rmt_bdname_len] = '\0';
}
if (bdname_len) {
*bdname_len = rmt_bdname_len;
}
return true;
}
return false;
}
static void filter_inquiry_scan_result(esp_bt_gap_cb_param_t *param)
{
char bda_str[18];
uint32_t cod = 0;
int32_t rssi = -129; /* invalid value */
uint8_t *eir = NULL;
esp_peer_bdname_t peer_bdname;
esp_bt_gap_dev_prop_t *p;
ESP_LOGI(TAG, "Scanned device: %s", bda2str(param->disc_res.bda, bda_str, 18));
for (int i = 0; i < param->disc_res.num_prop; i++) {
p = param->disc_res.prop + i;
switch (p->type) {
case ESP_BT_GAP_DEV_PROP_COD:
cod = *(uint32_t *)(p->val);
ESP_LOGI(TAG, "--Class of Device: 0x%x", cod);
break;
case ESP_BT_GAP_DEV_PROP_RSSI:
rssi = *(int8_t *)(p->val);
ESP_LOGI(TAG, "--RSSI: %d", rssi);
break;
case ESP_BT_GAP_DEV_PROP_EIR:
eir = (uint8_t *)(p->val);
get_name_from_eir(eir, (uint8_t *)&peer_bdname, NULL);
ESP_LOGI(TAG, "--Name: %s", peer_bdname);
break;
case ESP_BT_GAP_DEV_PROP_BDNAME:
default:
break;
}
}
/* search for device with MAJOR service class as "rendering" in COD */
if (!esp_bt_gap_is_valid_cod(cod) || !(esp_bt_gap_get_cod_srvc(cod) & ESP_BT_COD_SRVC_RENDERING)) {
return;
}
/* search for device named "peer_bdname" in its extended inquiry response */
if (eir) {
get_name_from_eir(eir, (uint8_t *)&peer_bdname, NULL);
if (strcmp((char *)peer_bdname, (char *)&g_bt_service->peer_bdname) != 0) {
return;
}
ESP_LOGI(TAG, "Found a target device, address %s, name %s", bda_str, (uint8_t *)peer_bdname);
g_bt_service->source_a2d_state = BT_SOURCE_STATE_DISCOVERED;
memcpy(&g_bt_service->remote_bda, param->disc_res.bda, ESP_BD_ADDR_LEN);
ESP_LOGI(TAG, "Cancel device discovery ...");
esp_bt_gap_cancel_discovery();
}
}
static void bt_avrc_ct_cb(esp_avrc_ct_cb_event_t event, esp_avrc_ct_cb_param_t *p_param)
{
esp_avrc_ct_cb_param_t *rc = p_param;
switch (event) {
case ESP_AVRC_CT_CONNECTION_STATE_EVT: {
uint8_t *bda = rc->conn_stat.remote_bda;
g_bt_service->avrc_connected = rc->conn_stat.connected;
if (rc->conn_stat.connected) {
ESP_LOGD(TAG, "ESP_AVRC_CT_CONNECTION_STATE_EVT");
bt_key_act_sm_init();
} else if (0 == rc->conn_stat.connected) {
bt_key_act_sm_deinit();
}
ESP_LOGD(TAG, "AVRC conn_state evt: state %d, [%02x:%02x:%02x:%02x:%02x:%02x]",
rc->conn_stat.connected, bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
break;
}
case ESP_AVRC_CT_PASSTHROUGH_RSP_EVT: {
if (g_bt_service->avrc_connected) {
ESP_LOGD(TAG, "AVRC passthrough rsp: key_code 0x%x, key_state %d", rc->psth_rsp.key_code, rc->psth_rsp.key_state);
bt_key_act_param_t param;
memset(¶m, 0, sizeof(bt_key_act_param_t));
param.evt = event;
param.tl = rc->psth_rsp.tl;
param.key_code = rc->psth_rsp.key_code;
param.key_state = rc->psth_rsp.key_state;
bt_key_act_state_machine(¶m);
}
break;
}
case ESP_AVRC_CT_METADATA_RSP_EVT: {
ESP_LOGD(TAG, "AVRC metadata rsp: attribute id 0x%x, %s", rc->meta_rsp.attr_id, rc->meta_rsp.attr_text);
// free(rc->meta_rsp.attr_text);
break;
}
case ESP_AVRC_CT_CHANGE_NOTIFY_EVT: {
ESP_LOGD(TAG, "AVRC event notification: %d", rc->change_ntf.event_id);
break;
}
case ESP_AVRC_CT_REMOTE_FEATURES_EVT: {
ESP_LOGD(TAG, "AVRC remote features %x", rc->rmt_feats.feat_mask);
break;
}
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
case ESP_AVRC_CT_GET_RN_CAPABILITIES_RSP_EVT: {
ESP_LOGD(TAG, "remote rn_cap: count %d, bitmask 0x%x", rc->get_rn_caps_rsp.cap_count,
rc->get_rn_caps_rsp.evt_set.bits);
break;
}
#endif
default:
ESP_LOGE(TAG, "%s unhandled evt %d", __func__, event);
break;
}
}
static void bt_app_gap_cb(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param)
{
switch (event) {
case ESP_BT_GAP_DISC_RES_EVT: {
filter_inquiry_scan_result(param);
break;
}
case ESP_BT_GAP_DISC_STATE_CHANGED_EVT: {
if (param->disc_st_chg.state == ESP_BT_GAP_DISCOVERY_STOPPED) {
if (g_bt_service->source_a2d_state == BT_SOURCE_STATE_DISCOVERED) {
g_bt_service->source_a2d_state = BT_SOURCE_STATE_CONNECTING;
ESP_LOGI(TAG, "Device discovery stopped.");
ESP_LOGI(TAG, "a2dp connecting to peer: %s", g_bt_service->peer_bdname);
esp_a2d_source_connect(g_bt_service->remote_bda);
} else if (g_bt_service->source_a2d_state != BT_SOURCE_STATE_IDLE) {
// not discovered, continue to discover
ESP_LOGI(TAG, "Device discovery failed, continue to discover...");
esp_bt_gap_start_discovery(ESP_BT_INQ_MODE_GENERAL_INQUIRY, 10, 0);
}
} else if (param->disc_st_chg.state == ESP_BT_GAP_DISCOVERY_STARTED) {
ESP_LOGI(TAG, "Discovery started.");
}
break;
}
case ESP_BT_GAP_RMT_SRVCS_EVT:
case ESP_BT_GAP_RMT_SRVC_REC_EVT:
break;
case ESP_BT_GAP_AUTH_CMPL_EVT: {
if (param->auth_cmpl.stat == ESP_BT_STATUS_SUCCESS) {
ESP_LOGI(TAG, "authentication success: %s", param->auth_cmpl.device_name);
esp_log_buffer_hex(TAG, param->auth_cmpl.bda, ESP_BD_ADDR_LEN);
} else {
ESP_LOGI(TAG, "authentication failed, status:%d", param->auth_cmpl.stat);
}
break;
}
case ESP_BT_GAP_PIN_REQ_EVT: {
ESP_LOGI(TAG, "ESP_BT_GAP_PIN_REQ_EVT min_16_digit:%d", param->pin_req.min_16_digit);
if (param->pin_req.min_16_digit) {
ESP_LOGI(TAG, "Input pin code: 0000 0000 0000 0000");
esp_bt_pin_code_t pin_code = { 0 };
esp_bt_gap_pin_reply(param->pin_req.bda, true, 16, pin_code);
} else {
ESP_LOGI(TAG, "Input pin code: 1234");
esp_bt_pin_code_t pin_code;
pin_code[0] = '1';
pin_code[1] = '2';
pin_code[2] = '3';
pin_code[3] = '4';
esp_bt_gap_pin_reply(param->pin_req.bda, true, 4, pin_code);
}
break;
}
default: {
ESP_LOGI(TAG, "event: %d", event);
break;
}
}
return;
}
static void bt_a2d_source_cb(esp_a2d_cb_event_t event, esp_a2d_cb_param_t *param)
{
ESP_LOGI(TAG, "%s state %d, evt 0x%x", __func__, g_bt_service->source_a2d_state, event);
switch (g_bt_service->source_a2d_state) {
case BT_SOURCE_STATE_DISCOVERING:
case BT_SOURCE_STATE_DISCOVERED:
break;
case BT_SOURCE_STATE_UNCONNECTED:
break;
case BT_SOURCE_STATE_CONNECTING:
if (param->conn_stat.state == ESP_A2D_CONNECTION_STATE_CONNECTED) {
ESP_LOGI(TAG, "a2dp connected");
g_bt_service->source_a2d_state = BT_SOURCE_STATE_CONNECTED;
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
esp_bt_gap_set_scan_mode(ESP_BT_NON_CONNECTABLE, ESP_BT_NON_DISCOVERABLE);
#else
esp_bt_gap_set_scan_mode(ESP_BT_SCAN_MODE_NONE);
#endif
if (g_bt_service->periph) {
esp_periph_send_event(g_bt_service->periph, PERIPH_BLUETOOTH_CONNECTED, NULL, 0);
}
ESP_LOGI(TAG, "a2dp media ready checking ...");
esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_CHECK_SRC_RDY);
} else if (param->conn_stat.state == ESP_A2D_CONNECTION_STATE_DISCONNECTED) {
g_bt_service->source_a2d_state = BT_SOURCE_STATE_UNCONNECTED;
}
break;
case BT_SOURCE_STATE_CONNECTED:
if (event == ESP_A2D_MEDIA_CTRL_ACK_EVT) {
if (param->media_ctrl_stat.cmd == ESP_A2D_MEDIA_CTRL_CHECK_SRC_RDY && param->media_ctrl_stat.status == ESP_A2D_MEDIA_CTRL_ACK_SUCCESS) {
ESP_LOGI(TAG, "a2dp media ready, starting ...");
esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_START);
} else if (param->media_ctrl_stat.cmd == ESP_A2D_MEDIA_CTRL_START && param->media_ctrl_stat.status == ESP_A2D_MEDIA_CTRL_ACK_SUCCESS) {
ESP_LOGI(TAG, "a2dp media start successfully.");
g_bt_service->audio_state = ESP_A2D_AUDIO_STATE_STARTED;
} else if (param->media_ctrl_stat.cmd != ESP_A2D_MEDIA_CTRL_SUSPEND) {
// not started successfully, transfer to idle state
ESP_LOGI(TAG, "a2dp media start failed.");
g_bt_service->audio_state = BT_SOURCE_STATE_IDLE;
}
} else if (event == ESP_A2D_CONNECTION_STATE_EVT && param->conn_stat.state == ESP_A2D_CONNECTION_STATE_DISCONNECTED) {
g_bt_service->source_a2d_state = BT_SOURCE_STATE_UNCONNECTED;
if (g_bt_service->periph) {
esp_periph_send_event(g_bt_service->periph, PERIPH_BLUETOOTH_DISCONNECTED, NULL, 0);
}
}
break;
case BT_SOURCE_STATE_DISCONNECTING:
break;
default:
ESP_LOGE(TAG, "%s invalid state %d", __func__, g_bt_service->source_a2d_state);
break;
}
}
esp_err_t bluetooth_service_start(bluetooth_service_cfg_t *config)
{
if (g_bt_service) {
ESP_LOGE(TAG, "Bluetooth service have been initialized");
return ESP_FAIL;
}
g_bt_service = audio_calloc(1, sizeof(bluetooth_service_t));
AUDIO_MEM_CHECK(TAG, g_bt_service, return ESP_ERR_NO_MEM);
ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_BLE));
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
if (esp_bt_controller_init(&bt_cfg) != ESP_OK) {
AUDIO_ERROR(TAG, "initialize controller failed");
return ESP_FAIL;
}
if (esp_bt_controller_enable(ESP_BT_MODE_BTDM) != ESP_OK) {
AUDIO_ERROR(TAG, "enable controller failed");
return ESP_FAIL;
}
if (esp_bluedroid_init() != ESP_OK) {
AUDIO_ERROR(TAG, "initialize bluedroid failed");
return ESP_FAIL;
}
if (esp_bluedroid_enable() != ESP_OK) {
AUDIO_ERROR(TAG, "enable bluedroid failed");
return ESP_FAIL;
}
if (config->device_name) {
esp_bt_dev_set_device_name(config->device_name);
} else {
if (config->mode == BLUETOOTH_A2DP_SINK) {
esp_bt_dev_set_device_name("ESP-ADF-SPEAKER");
} else {
esp_bt_dev_set_device_name("ESP-ADF-SOURCE");
}
}
esp_avrc_ct_init();
esp_avrc_ct_register_callback(bt_avrc_ct_cb);
if (config->mode == BLUETOOTH_A2DP_SINK) {
esp_a2d_sink_init();
esp_a2d_sink_register_data_callback(bt_a2d_sink_data_cb);
esp_a2d_register_callback(bt_a2d_sink_cb);
// TODO: Use this function for IDF version higher than v3.0
// esp_a2d_sink_register_data_callback(bt_a2d_data_cb);
g_bt_service->stream_type = AUDIO_STREAM_READER;
} else {
/*
* Set default parameters for Legacy Pairing
* Use variable pin, input pin code when pairing
*/
esp_bt_pin_type_t pin_type = ESP_BT_PIN_TYPE_VARIABLE;
esp_bt_pin_code_t pin_code;
esp_bt_gap_set_pin(pin_type, 0, pin_code);
esp_a2d_register_callback(bt_a2d_source_cb);
esp_bt_gap_register_callback(bt_app_gap_cb);
esp_a2d_source_register_data_callback(bt_a2d_source_data_cb);
esp_a2d_source_init();
/* start device discovery */
ESP_LOGI(TAG, "Starting device discovery...");
if (config->remote_name) {
memcpy(&g_bt_service->peer_bdname, config->remote_name, strlen(config->remote_name) + 1);
} else {
memcpy(&g_bt_service->peer_bdname, BT_SOURCE_DEFAULT_REMOTE_NAME, strlen(BT_SOURCE_DEFAULT_REMOTE_NAME) + 1);
}
g_bt_service->source_a2d_state = BT_SOURCE_STATE_DISCOVERING;
g_bt_service->stream_type = AUDIO_STREAM_WRITER;
esp_bt_gap_start_discovery(ESP_BT_INQ_MODE_GENERAL_INQUIRY, 10, 0);
}
/* set discoverable and connectable mode */
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE);
#else
esp_bt_gap_set_scan_mode(ESP_BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE);
#endif
g_bt_service->a2dp_sample_rate = 44100;
return ESP_OK;
}
esp_err_t bluetooth_service_destroy()
{
if (g_bt_service && (g_bt_service->stream || g_bt_service->periph)) {
AUDIO_ERROR(TAG, "Stream and periph need to stop first");
return ESP_FAIL;
}
if (g_bt_service) {
esp_avrc_ct_deinit();
if (g_bt_service->stream_type == AUDIO_STREAM_READER) {
esp_a2d_sink_deinit();
} else {
esp_a2d_source_deinit();
}
esp_bluedroid_disable();
esp_bluedroid_deinit();
esp_bt_controller_disable();
esp_bt_controller_deinit();
esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT);
audio_free(g_bt_service);
g_bt_service = NULL;
}
return ESP_OK;
}
static esp_err_t _bt_stream_destroy(audio_element_handle_t self)
{
g_bt_service->stream = NULL;
return ESP_OK;
}
audio_element_handle_t bluetooth_service_create_stream()
{
if (g_bt_service && g_bt_service->stream) {
ESP_LOGE(TAG, "Bluetooth stream have been created");
return NULL;
}
audio_element_cfg_t cfg = DEFAULT_AUDIO_ELEMENT_CONFIG();
cfg.task_stack = -1; // No need task
cfg.destroy = _bt_stream_destroy;
cfg.tag = "bt";
g_bt_service->stream = audio_element_init(&cfg);
AUDIO_MEM_CHECK(TAG, g_bt_service->stream, return NULL);
audio_element_setdata(g_bt_service->stream, g_bt_service);
return g_bt_service->stream;
}
static esp_err_t _bt_periph_init(esp_periph_handle_t periph)
{
return ESP_OK;
}
static esp_err_t _bt_periph_run(esp_periph_handle_t self, audio_event_iface_msg_t *msg)
{
return ESP_OK;
}
static esp_err_t _bt_periph_destroy(esp_periph_handle_t periph)
{
g_bt_service->periph = NULL;
return ESP_OK;
}
esp_periph_handle_t bluetooth_service_create_periph()
{
AUDIO_NULL_CHECK(TAG, g_bt_service, return NULL);
if (g_bt_service && g_bt_service->periph) {
ESP_LOGE(TAG, "Bluetooth periph have been created");
return NULL;
}
g_bt_service->periph = esp_periph_create(PERIPH_ID_BLUETOOTH, "periph_bt");
esp_periph_set_function(g_bt_service->periph, _bt_periph_init, _bt_periph_run, _bt_periph_destroy);
return g_bt_service->periph;
}
static esp_err_t periph_bluetooth_passthrough_cmd(esp_periph_handle_t periph, uint8_t cmd)
{
VALIDATE_BT(periph, ESP_FAIL);
if (g_bt_service->audio_state != ESP_A2D_AUDIO_STATE_STARTED) {
//return ESP_FAIL;
}
esp_err_t err = ESP_OK;
if (g_bt_service->avrc_connected) {
bt_key_act_param_t param;
memset(¶m, 0, sizeof(bt_key_act_param_t));
param.evt = ESP_AVRC_CT_KEY_STATE_CHG_EVT;
param.key_code = cmd;
param.key_state = 0;
param.tl = (g_bt_service->tl) & 0x0F;
g_bt_service->tl = (g_bt_service->tl + 2) & 0x0f;
bt_key_act_state_machine(¶m);
}
return err;
}
esp_err_t periph_bluetooth_play(esp_periph_handle_t periph)
{
AUDIO_NULL_CHECK(TAG, g_bt_service, return ESP_FAIL);
esp_err_t err = ESP_OK;
if (g_bt_service->stream_type == AUDIO_STREAM_READER) {
err = periph_bluetooth_passthrough_cmd(periph, ESP_AVRC_PT_CMD_PLAY);
} else {
err = esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_CHECK_SRC_RDY);
}
return err;
}
esp_err_t periph_bluetooth_pause(esp_periph_handle_t periph)
{
AUDIO_NULL_CHECK(TAG, g_bt_service, return ESP_FAIL);
esp_err_t err = ESP_OK;
if (g_bt_service->stream_type == AUDIO_STREAM_READER) {
err = periph_bluetooth_passthrough_cmd(periph, ESP_AVRC_PT_CMD_PAUSE);
} else {
err = esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_SUSPEND);
}
return err;
}
esp_err_t periph_bluetooth_stop(esp_periph_handle_t periph)
{
AUDIO_NULL_CHECK(TAG, g_bt_service, return ESP_FAIL);
esp_err_t err = ESP_OK;
if (g_bt_service->stream_type == AUDIO_STREAM_READER) {
err = periph_bluetooth_passthrough_cmd(periph, ESP_AVRC_PT_CMD_STOP);
} else {
esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_STOP);
g_bt_service->audio_state = ESP_A2D_AUDIO_STATE_STOPPED;
}
return err;
}
esp_err_t periph_bluetooth_next(esp_periph_handle_t periph)
{
return periph_bluetooth_passthrough_cmd(periph, ESP_AVRC_PT_CMD_FORWARD);
}
esp_err_t periph_bluetooth_prev(esp_periph_handle_t periph)
{
return periph_bluetooth_passthrough_cmd(periph, ESP_AVRC_PT_CMD_BACKWARD);
}
esp_err_t periph_bluetooth_rewind(esp_periph_handle_t periph)
{
return periph_bluetooth_passthrough_cmd(periph, ESP_AVRC_PT_CMD_REWIND);
}
esp_err_t periph_bluetooth_fast_forward(esp_periph_handle_t periph)
{
return periph_bluetooth_passthrough_cmd(periph, ESP_AVRC_PT_CMD_FAST_FORWARD);
}
esp_err_t periph_bluetooth_discover(esp_periph_handle_t periph)
{
AUDIO_NULL_CHECK(TAG, g_bt_service, return ESP_FAIL);
if (g_bt_service->stream_type == AUDIO_STREAM_READER) {
return esp_bt_gap_start_discovery(ESP_BT_INQ_MODE_GENERAL_INQUIRY, 10, 0);
}
return ESP_OK;
}
esp_err_t periph_bluetooth_cancel_discover(esp_periph_handle_t periph)
{
AUDIO_NULL_CHECK(TAG, g_bt_service, return ESP_FAIL);
if (g_bt_service->stream_type == AUDIO_STREAM_READER) {
g_bt_service->source_a2d_state = BT_SOURCE_STATE_IDLE;
return esp_bt_gap_cancel_discovery();
}
return ESP_OK;
}
esp_err_t periph_bluetooth_connect(esp_periph_handle_t periph, bluetooth_addr_t remote_bda)
{
AUDIO_NULL_CHECK(TAG, g_bt_service, return ESP_FAIL);
if (g_bt_service->stream_type == AUDIO_STREAM_READER) {
g_bt_service->source_a2d_state = BT_SOURCE_STATE_DISCOVERED;
memcpy(&g_bt_service->remote_bda, remote_bda, BLUETOOTH_ADDR_LEN);
ESP_LOGI(TAG, "Cancel device discovery and connect remote device.");
return esp_bt_gap_cancel_discovery();
}
return ESP_OK;
}
int periph_bluetooth_get_a2dp_sample_rate()
{
AUDIO_NULL_CHECK(TAG, g_bt_service, return -1);
return g_bt_service->a2dp_sample_rate;
}
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/bluetooth_service/bluetooth_service.c
|
C
|
apache-2.0
| 28,851
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 <stdlib.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/timers.h"
#include "freertos/queue.h"
#if CONFIG_BT_ENABLED
#include "audio_error.h"
#include "esp_system.h"
#include "bt_keycontrol.h"
#include "esp_log.h"
static const char *BTKEYCTRL_TAG = "BT_KEYCTRL";
typedef enum {
KEY_ACT_STATE_IDLE,
KEY_ACT_STATE_PRESS,
KEY_ACT_STATE_RELEASE
} key_act_state_t;
typedef struct {
key_act_state_t state;
uint32_t key_code;
TimerHandle_t key_tmr;
uint8_t tl;
} key_act_cb_t;
static void key_act_state_hdl_idle(key_act_cb_t *key_cb, bt_key_act_param_t *param);
static void key_act_state_hdl_press(key_act_cb_t *key_cb, bt_key_act_param_t *param);
static void key_act_state_hdl_release(key_act_cb_t *key_cb, bt_key_act_param_t *param);
static void key_act_time_out(void *p);
static key_act_cb_t key_cb;
void bt_key_act_state_machine(bt_key_act_param_t *param)
{
ESP_LOGD(BTKEYCTRL_TAG, "key_ctrl cb: tl %d, state: %d", key_cb.tl, key_cb.state);
switch (key_cb.state) {
case KEY_ACT_STATE_IDLE:
key_act_state_hdl_idle(&key_cb, param);
break;
case KEY_ACT_STATE_PRESS:
key_act_state_hdl_press(&key_cb, param);
break;
case KEY_ACT_STATE_RELEASE:
key_act_state_hdl_release(&key_cb, param);
break;
default:
ESP_LOGD(BTKEYCTRL_TAG, "Invalid key_ctrl state: %d", key_cb.state);
break;
}
}
static void key_act_time_out(void *p)
{
bt_key_act_param_t param;
memset(¶m, 0, sizeof(bt_key_act_param_t));
param.evt = ESP_AVRC_CT_PT_RSP_TO_EVT;
bt_key_act_state_machine(¶m);
}
esp_err_t bt_key_act_sm_init(void)
{
if (key_cb.key_tmr) {
ESP_LOGW(BTKEYCTRL_TAG, "%s timer not released", __func__);
xTimerDelete(key_cb.key_tmr, portMAX_DELAY);
key_cb.key_tmr = NULL;
}
memset(&key_cb, 0, sizeof(key_act_cb_t));
int tmr_id = 0xfe;
key_cb.tl = 0;
key_cb.state = KEY_ACT_STATE_IDLE;
key_cb.key_code = 0;
key_cb.key_tmr = xTimerCreate("key_tmr", portMAX_DELAY,
pdFALSE, (void *)tmr_id, key_act_time_out);
if (key_cb.key_tmr == NULL) {
ESP_LOGW(BTKEYCTRL_TAG, "%s timer creation failure", __func__);
return false;
}
return true;
}
void bt_key_act_sm_deinit(void)
{
if (key_cb.key_tmr) {
xTimerDelete(key_cb.key_tmr, portMAX_DELAY);
key_cb.key_tmr = NULL;
}
memset(&key_cb, 0, sizeof(key_act_cb_t));
}
static void key_act_state_hdl_idle(key_act_cb_t *key_cb, bt_key_act_param_t *param)
{
AUDIO_MEM_CHECK(BTKEYCTRL_TAG, key_cb, return);
AUDIO_MEM_CHECK(BTKEYCTRL_TAG, param, return);
if(key_cb->state != KEY_ACT_STATE_IDLE) {
ESP_LOGE(BTKEYCTRL_TAG, "ERROR STATE: bluetooth key action state should be KEY_ACT_STATE_IDLE!");
return;
}
if (param->evt == ESP_AVRC_CT_KEY_STATE_CHG_EVT) {
key_cb->tl = param->tl;
key_cb->key_code = param->key_code;
esp_avrc_ct_send_passthrough_cmd(param->tl, param->key_code, ESP_AVRC_PT_CMD_STATE_PRESSED);
xTimerStart(key_cb->key_tmr, 500 / portTICK_RATE_MS);
key_cb->state = KEY_ACT_STATE_PRESS;
}
}
static void key_act_state_hdl_press(key_act_cb_t *key_cb, bt_key_act_param_t *param)
{
AUDIO_MEM_CHECK(BTKEYCTRL_TAG, key_cb, return);
AUDIO_MEM_CHECK(BTKEYCTRL_TAG, param, return);
if(key_cb->state != KEY_ACT_STATE_PRESS) {
ESP_LOGE(BTKEYCTRL_TAG, "ERROR STATE: bluetooth key action state should be KEY_ACT_STATE_PRESS!");
return;
}
if (param->evt == ESP_AVRC_CT_PASSTHROUGH_RSP_EVT) {
if (key_cb->tl != param->tl || key_cb->key_code != param->key_code
|| ESP_AVRC_PT_CMD_STATE_PRESSED != param->key_state) {
ESP_LOGW(BTKEYCTRL_TAG, "Key pressed hdlr: invalid state");
return;
}
key_cb->tl = (key_cb->tl + 1) & 0x0F;
esp_avrc_ct_send_passthrough_cmd(key_cb->tl, param->key_code, ESP_AVRC_PT_CMD_STATE_RELEASED);
xTimerReset(key_cb->key_tmr, 500 / portTICK_RATE_MS);
key_cb->state = KEY_ACT_STATE_RELEASE;
} else if (param->evt == ESP_AVRC_CT_PT_RSP_TO_EVT) {
key_cb->tl = 0;
key_cb->key_code = 0;
key_cb->state = KEY_ACT_STATE_IDLE;
}
}
static void key_act_state_hdl_release(key_act_cb_t *key_cb, bt_key_act_param_t *param)
{
AUDIO_MEM_CHECK(BTKEYCTRL_TAG, key_cb, return);
AUDIO_MEM_CHECK(BTKEYCTRL_TAG, param, return);
if(key_cb->state != KEY_ACT_STATE_RELEASE) {
ESP_LOGE(BTKEYCTRL_TAG, "ERROR STATE: bluetooth key action state should be KEY_ACT_STATE_RELEASE!");
return;
}
if (param->evt == ESP_AVRC_CT_PASSTHROUGH_RSP_EVT) {
if (key_cb->tl != param->tl || key_cb->key_code != param->key_code
|| ESP_AVRC_PT_CMD_STATE_RELEASED != param->key_state) {
return;
}
xTimerStop(key_cb->key_tmr, 500 / portTICK_RATE_MS);
key_cb->state = KEY_ACT_STATE_IDLE;
key_cb->key_code = 0;
} else if (param->evt == ESP_AVRC_CT_PT_RSP_TO_EVT) {
key_cb->tl = 0;
key_cb->key_code = 0;
key_cb->state = KEY_ACT_STATE_IDLE;
}
}
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/bluetooth_service/bt_keycontrol.c
|
C
|
apache-2.0
| 6,482
|
#
# "main" pseudo-component makefile.
#
# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.)
COMPONENT_INCLUDEDIRS := include
COMPONENT_SRCDIRS :=.
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/bluetooth_service/component.mk
|
Makefile
|
apache-2.0
| 202
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 <stdio.h>
#include <string.h>
#include "esp_log.h"
#include "raw_stream.h"
#include "audio_element.h"
#include "audio_mem.h"
#include "sdkconfig.h"
#include "hfp_stream.h"
#if CONFIG_BT_ENABLED
static const char *TAG = "HFP_STREAM";
#define ESP_HFP_RINGBUF_SIZE 3600
#define ESP_HFP_TASK_SIZE 2048
#define ESP_HFP_TASK_PRIORITY 23
static bool is_get_data = true;
static hfp_stream_user_callback_t hfp_stream_user_callback;
static audio_element_handle_t hfp_incoming_stream = NULL;
static audio_element_handle_t hfp_outgoing_stream = NULL;
const char *c_hf_evt_str[] = {
"CONNECTION_STATE_EVT", /*!< connection state changed event */
"AUDIO_STATE_EVT", /*!< audio connection state change event */
"VR_STATE_CHANGE_EVT", /*!< voice recognition state changed */
"CALL_IND_EVT", /*!< call indication event */
"CALL_SETUP_IND_EVT", /*!< call setup indication event */
"CALL_HELD_IND_EVT", /*!< call held indicator event */
"NETWORK_STATE_EVT", /*!< network state change event */
"SIGNAL_STRENGTH_IND_EVT", /*!< signal strength indication event */
"ROAMING_STATUS_IND_EVT", /*!< roaming status indication event */
"BATTERY_LEVEL_IND_EVT", /*!< battery level indication event */
"CURRENT_OPERATOR_EVT", /*!< current operator name event */
"RESP_AND_HOLD_EVT", /*!< response and hold event */
"CLIP_EVT", /*!< Calling Line Identification notification event */
"CALL_WAITING_EVT", /*!< call waiting notification */
"CLCC_EVT", /*!< listing current calls event */
"VOLUME_CONTROL_EVT", /*!< audio volume control event */
"AT_RESPONSE", /*!< audio volume control event */
"SUBSCRIBER_INFO_EVT", /*!< subscriber information event */
"INBAND_RING_TONE_EVT", /*!< in-band ring tone settings */
"LAST_VOICE_TAG_NUMBER_EVT", /*!< requested number from AG event */
"RING_IND_EVT", /*!< ring indication event */
};
// esp_hf_client_connection_state_t
const char *c_connection_state_str[] = {
"disconnected",
"connecting",
"connected",
"slc_connected",
"disconnecting",
};
// esp_hf_client_audio_state_t
const char *c_audio_state_str[] = {
"disconnected",
"connecting",
"connected",
"connected_msbc",
};
/// esp_hf_vr_state_t
const char *c_vr_state_str[] = {
"disabled",
"enabled",
};
// esp_hf_service_availability_status_t
const char *c_service_availability_status_str[] = {
"unavailable",
"available",
};
// esp_hf_roaming_status_t
const char *c_roaming_status_str[] = {
"inactive",
"active",
};
// esp_hf_client_call_state_t
const char *c_call_str[] = {
"NO call in progress",
"call in progress",
};
// esp_hf_client_callsetup_t
const char *c_call_setup_str[] = {
"NONE",
"INCOMING",
"OUTGOING_DIALING",
"OUTGOING_ALERTING"
};
// esp_hf_client_callheld_t
const char *c_call_held_str[] = {
"NONE held",
"Held and Active",
"Held",
};
// esp_hf_response_and_hold_status_t
const char *c_resp_and_hold_str[] = {
"HELD",
"HELD ACCEPTED",
"HELD REJECTED",
};
// esp_hf_client_call_direction_t
const char *c_call_dir_str[] = {
"outgoing",
"incoming",
};
// esp_hf_client_call_state_t
const char *c_call_state_str[] = {
"active",
"held",
"dialing",
"alerting",
"incoming",
"waiting",
"held_by_resp_hold",
};
// esp_hf_current_call_mpty_type_t
const char *c_call_mpty_type_str[] = {
"single",
"multi",
};
// esp_hf_volume_control_target_t
const char *c_volume_control_target_str[] = {
"SPEAKER",
"MICROPHONE"
};
// esp_hf_at_response_code_t
const char *c_at_response_code_str[] = {
"OK",
"ERROR"
"ERR_NO_CARRIER",
"ERR_BUSY",
"ERR_NO_ANSWER",
"ERR_DELAYED",
"ERR_BLACKLILSTED",
"ERR_CME",
};
// esp_hf_subscriber_service_type_t
const char *c_subscriber_service_type_str[] = {
"unknown",
"voice",
"fax",
};
// esp_hf_client_in_band_ring_state_t
const char *c_inband_ring_state_str[] = {
"NOT provided",
"Provided",
};
esp_err_t hfp_open_and_close_evt_cb_register(esp_hf_audio_open_t open_cb, esp_hf_audio_close_t close_cb)
{
if ((open_cb == NULL)||(close_cb == NULL)) {
return ESP_FAIL;
}
hfp_stream_user_callback.user_hfp_open_cb = open_cb;
hfp_stream_user_callback.user_hfp_close_cb = close_cb;
return ESP_OK;
}
static uint32_t bt_app_hf_client_outgoing_cb(uint8_t *p_buf, uint32_t sz)
{
int out_len_bytes = 0;
if (is_get_data) {
out_len_bytes = audio_element_input(hfp_outgoing_stream, (char *)p_buf, sz);
}
if (out_len_bytes == sz) {
is_get_data = false;
return sz;
} else {
is_get_data = true;
return 0;
}
}
static void bt_app_hf_client_incoming_cb(const uint8_t *buf, uint32_t sz)
{
if (hfp_incoming_stream) {
if (audio_element_get_state(hfp_incoming_stream) == AEL_STATE_RUNNING) {
audio_element_output(hfp_incoming_stream, (char *)buf, sz);
esp_hf_client_outgoing_data_ready();
}
}
}
/* callback for HF_CLIENT */
void bt_hf_client_cb(esp_hf_client_cb_event_t event, esp_hf_client_cb_param_t *param)
{
if (event <= ESP_HF_CLIENT_RING_IND_EVT) {
ESP_LOGI(TAG, "APP HFP event: %s", c_hf_evt_str[event]);
} else {
ESP_LOGE(TAG, "APP HFP invalid event %d", event);
}
switch (event) {
case ESP_HF_CLIENT_CONNECTION_STATE_EVT:
ESP_LOGI(TAG, "--Connection state %s, peer feats 0x%x, chld_feats 0x%x",
c_connection_state_str[param->conn_stat.state],
param->conn_stat.peer_feat,
param->conn_stat.chld_feat);
break;
case ESP_HF_CLIENT_AUDIO_STATE_EVT:
ESP_LOGI(TAG, "--Audio state %s",
c_audio_state_str[param->audio_stat.state]);
if ((param->audio_stat.state == ESP_HF_CLIENT_AUDIO_STATE_CONNECTED)
|| (param->audio_stat.state == ESP_HF_CLIENT_AUDIO_STATE_CONNECTED_MSBC)) {
if(hfp_stream_user_callback.user_hfp_open_cb != NULL) {
if (param->audio_stat.state == ESP_HF_CLIENT_AUDIO_STATE_CONNECTED) {
hfp_stream_user_callback.user_hfp_open_cb(HF_DATA_CVSD);
} else {
hfp_stream_user_callback.user_hfp_open_cb(HF_DATA_MSBC);
}
}
esp_hf_client_register_data_callback(bt_app_hf_client_incoming_cb,
bt_app_hf_client_outgoing_cb);
} else if (param->audio_stat.state == ESP_HF_CLIENT_AUDIO_STATE_DISCONNECTED) {
if (hfp_stream_user_callback.user_hfp_close_cb != NULL) {
hfp_stream_user_callback.user_hfp_close_cb();
}
}
break;
case ESP_HF_CLIENT_BVRA_EVT:
ESP_LOGI(TAG, "--VR state %s",
c_vr_state_str[param->bvra.value]);
break;
case ESP_HF_CLIENT_CIND_SERVICE_AVAILABILITY_EVT:
ESP_LOGI(TAG, "--NETWORK state %s",
c_service_availability_status_str[param->service_availability.status]);
break;
case ESP_HF_CLIENT_CIND_ROAMING_STATUS_EVT:
ESP_LOGI(TAG, "--ROAMING: %s",
c_roaming_status_str[param->roaming.status]);
break;
case ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT:
ESP_LOGI(TAG, "--Signal strength: %d",
param->signal_strength.value);
break;
case ESP_HF_CLIENT_CIND_BATTERY_LEVEL_EVT:
ESP_LOGI(TAG, "--Battery level %d",
param->battery_level.value);
break;
case ESP_HF_CLIENT_COPS_CURRENT_OPERATOR_EVT:
ESP_LOGI(TAG, "--Operator name: %s",
param->cops.name);
break;
case ESP_HF_CLIENT_CIND_CALL_EVT:
ESP_LOGI(TAG, "--Call indicator %s",
c_call_str[param->call.status]);
break;
case ESP_HF_CLIENT_CIND_CALL_SETUP_EVT:
ESP_LOGI(TAG, "--Call setup indicator %s",
c_call_setup_str[param->call_setup.status]);
break;
case ESP_HF_CLIENT_CIND_CALL_HELD_EVT:
ESP_LOGI(TAG, "--Call held indicator %s",
c_call_held_str[param->call_held.status]);
break;
case ESP_HF_CLIENT_BTRH_EVT:
ESP_LOGI(TAG, "--Response and hold %s",
c_resp_and_hold_str[param->btrh.status]);
break;
case ESP_HF_CLIENT_CLIP_EVT:
ESP_LOGI(TAG, "--Clip number %s",
(param->clip.number == NULL) ? "NULL" : (param->clip.number));
break;
case ESP_HF_CLIENT_CCWA_EVT:
ESP_LOGI(TAG, "--Call_waiting %s",
(param->ccwa.number == NULL) ? "NULL" : (param->ccwa.number));
break;
case ESP_HF_CLIENT_CLCC_EVT:
ESP_LOGI(TAG, "--Current call: idx %d, dir %s, state %s, mpty %s, number %s",
param->clcc.idx,
c_call_dir_str[param->clcc.dir],
c_call_state_str[param->clcc.status],
c_call_mpty_type_str[param->clcc.mpty],
(param->clcc.number == NULL) ? "NULL" : (param->clcc.number));
break;
case ESP_HF_CLIENT_VOLUME_CONTROL_EVT:
ESP_LOGI(TAG, "--Volume_target: %s, volume %d",
c_volume_control_target_str[param->volume_control.type],
param->volume_control.volume);
break;
case ESP_HF_CLIENT_AT_RESPONSE_EVT:
ESP_LOGI(TAG, "--AT response event, code %d, cme %d",
param->at_response.code, param->at_response.cme);
break;
case ESP_HF_CLIENT_CNUM_EVT:
ESP_LOGI(TAG, "--Subscriber type %s, number %s",
c_subscriber_service_type_str[param->cnum.type],
(param->cnum.number == NULL) ? "NULL" : param->cnum.number);
break;
case ESP_HF_CLIENT_BSIR_EVT:
ESP_LOGI(TAG, "--Inband ring state %s",
c_inband_ring_state_str[param->bsir.state]);
break;
case ESP_HF_CLIENT_BINP_EVT:
ESP_LOGI(TAG, "--Last voice tag number: %s",
(param->binp.number == NULL) ? "NULL" : param->binp.number);
break;
default:
ESP_LOGI(TAG, "HF_CLIENT EVT: %d", event);
break;
}
}
esp_err_t hfp_service_init()
{
esp_hf_client_register_callback(bt_hf_client_cb);
esp_hf_client_init();
return ESP_OK;
}
static esp_err_t _hfp_stream_destroy(audio_element_handle_t self)
{
hfp_stream_config_t *hfp = (hfp_stream_config_t *)audio_element_getdata(self);
audio_free(hfp);
return ESP_OK;
}
audio_element_handle_t hfp_stream_init(hfp_stream_config_t *config)
{
AUDIO_NULL_CHECK(TAG, config, return NULL);
audio_element_handle_t el = NULL;
hfp_stream_config_t *hfp = audio_calloc(1, sizeof(hfp_stream_config_t));
AUDIO_MEM_CHECK(TAG, hfp, return NULL);
audio_element_cfg_t cfg = DEFAULT_AUDIO_ELEMENT_CONFIG();
cfg.task_stack = -1; // No need task
cfg.destroy = _hfp_stream_destroy;
hfp->type = config->type;
if (config->type == INCOMING_STREAM) {
ESP_LOGI(TAG, "incoming stream init");
cfg.tag = "hfp";
el = audio_element_init(&cfg);
hfp_incoming_stream = el;
AUDIO_MEM_CHECK(TAG, el, {
audio_free(hfp);
return NULL;
});
audio_element_setdata(el, hfp);
} else if (config->type == OUTGOING_STREAM) {
ESP_LOGI(TAG, "outgoing stream init");
cfg.tag = "hfp_outgoing";
el = audio_element_init(&cfg);
hfp_outgoing_stream = el;
AUDIO_MEM_CHECK(TAG, el, {
audio_free(hfp);
return NULL;
});
audio_element_setdata(el, hfp);
} else {
ESP_LOGE(TAG, "error stream type");
}
return el;
}
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/bluetooth_service/hfp_stream.c
|
C
|
apache-2.0
| 13,328
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 _A2DP_STREAM_H_
#define _A2DP_STREAM_H_
#include "audio_error.h"
#include "audio_element.h"
#include "audio_hal.h"
#ifdef __cplusplus
extern "C" {
#endif
#if CONFIG_BT_ENABLED
#include "esp_bt.h"
#include "esp_bt_main.h"
#include "esp_bt_device.h"
#include "esp_gap_bt_api.h"
#include "esp_a2dp_api.h"
#include "esp_avrc_api.h"
#include "bt_keycontrol.h"
#if __has_include("esp_idf_version.h")
#include "esp_idf_version.h"
#else
#define ESP_IDF_VERSION_VAL(major, minor, patch) 1
#endif
typedef struct {
esp_a2d_cb_t user_a2d_cb;
esp_a2d_sink_data_cb_t user_a2d_sink_data_cb;
esp_a2d_source_data_cb_t user_a2d_source_data_cb;
} a2dp_stream_user_callback_t;
typedef struct {
audio_stream_type_t type;
a2dp_stream_user_callback_t user_callback;
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
audio_hal_handle_t audio_hal;
#endif
} a2dp_stream_config_t;
/**
* a2dp task is only created in a2dp sink mode
*/
#define A2DP_STREAM_TASK_STACK ( 2 * 1024 )
#define A2DP_STREAM_TASK_CORE ( 0 )
#define A2DP_STREAM_TASK_PRIO ( 22 )
#define A2DP_STREAM_TASK_IN_EXT ( true )
#define A2DP_STREAM_QUEUE_SIZE ( 20 )
/**
* @brief Create a handle to an Audio Element to stream data from A2DP to another Element
* or get data from other elements sent to A2DP, depending on the configuration
* the stream type, either AUDIO_STREAM_READER or AUDIO_STREAM_WRITER.
*
* @param config The configuration
*
* @return The Audio Element handle
*/
audio_element_handle_t a2dp_stream_init(a2dp_stream_config_t *config);
/**
* @brief Destroy and cleanup A2DP profile.
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t a2dp_destroy();
/**
* @brief Create Bluetooth peripheral.
* The returned bluetooth peripheral compatible with existing peripherals and can be used with the ESP Peripherals
*
* @return The Peripheral handle
*/
esp_periph_handle_t bt_create_periph();
/**
* @brief Send the AVRC passthrough command (PLAY) to the Bluetooth device
*
* @param[in] periph The periph
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_bt_play(esp_periph_handle_t periph);
/**
* @brief Send the AVRC passthrough command (PAUSE) to the Bluetooth device
*
* @param[in] periph The periph
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_bt_pause(esp_periph_handle_t periph);
/**
* @brief Send the AVRC passthrough command (STOP) to the Bluetooth device
*
* @param[in] periph The periph
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_bt_stop(esp_periph_handle_t periph);
/**
* @brief Send the AVRC passthrough command (NEXT) to the Bluetooth device
*
* @param[in] periph The periph
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_bt_avrc_next(esp_periph_handle_t periph);
/**
* @brief Send the AVRC passthrough command (PREV) to the Bluetooth device
*
* @param[in] periph The periph
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_bt_avrc_prev(esp_periph_handle_t periph);
/**
* @brief Send the AVRC passthrough command (REWIND) to the Bluetooth device
*
* @param[in] periph The periph
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_bt_avrc_rewind(esp_periph_handle_t periph);
/**
* @brief Send the AVRC passthrough command (FAST FORWARD) to the Bluetooth device
*
* @param[in] periph The periph
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_bt_avrc_fast_forward(esp_periph_handle_t periph);
/**
* @brief Start device discovery.
*
* @param[in] periph The periph
*
* @return
* - ESP_OK : Succeed
* - ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
* - ESP_ERR_INVALID_ARG: if invalid parameters are provided
* - ESP_FAIL: others
*/
esp_err_t periph_bt_discover(esp_periph_handle_t periph);
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
/**
* @brief Send the AVRC passthrough command (VOL_UP) to the Bluetooth device
*
* @param[in] periph The periph
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_bt_volume_up(esp_periph_handle_t periph);
/**
* @brief Send the AVRC passthrough command (VOL_DOWN) to the Bluetooth device
*
* @param[in] periph The periph
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_bt_volume_down(esp_periph_handle_t periph);
#endif
#endif
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/bluetooth_service/include/a2dp_stream.h
|
C
|
apache-2.0
| 5,860
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 _BLUETOOTH_SERVICE_H_
#define _BLUETOOTH_SERVICE_H_
#include "freertos/event_groups.h"
#include "audio_error.h"
#include "audio_element.h"
#include "esp_peripherals.h"
#include "bt_keycontrol.h"
#ifdef __cplusplus
extern "C" {
#endif
#define ESP_A2DP_SAMPLE_RATE 44100
/**
* brief Bluetooth service working mode
*/
typedef enum {
BLUETOOTH_A2DP_SINK, /*!< A2DP Bluetooth sink audio, ESP32 will receive audio data from other bluetooth devices */
BLUETOOTH_A2DP_SOURCE, /*!< A2DP Bluetooth source audio, ESP32 can send audio data to other bluetooth devices */
} bluetooth_service_mode_t;
/**
*brief Bluetooth service configuration
*/
typedef struct {
const char *device_name; /*!< Bluetooth local device name */
const char *remote_name; /*!< Bluetooth remote device name */
bluetooth_service_mode_t mode; /*!< Bluetooth working mode */
} bluetooth_service_cfg_t;
/**
*brief Bluetooth address length
*/
#define BLUETOOTH_ADDR_LEN 6
/**
*brief Bluetooth device address
*/
typedef uint8_t bluetooth_addr_t[BLUETOOTH_ADDR_LEN];
/**
* @brief Initialize and start the Bluetooth service. This function can only be called for one time,
* and `bluetooth_service_destroy` must be called after use.
*
* @param config The configuration
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t bluetooth_service_start(bluetooth_service_cfg_t *config);
/**
* @brief Create Bluetooth stream, it is valid when Bluetooth service has started.
* The returned audio stream compatible with existing audio streams and can be used with the Audio Pipeline
*
* @return The Audio Element handle
*/
audio_element_handle_t bluetooth_service_create_stream();
/**
* @brief Create Bluetooth peripheral, it is valid when Bluetooth service has started.
* The returned bluetooth peripheral compatible with existing peripherals and can be used with the ESP Peripherals
*
* @return The Peripheral handle
*/
esp_periph_handle_t bluetooth_service_create_periph();
/**
* @brief Send the AVRC passthrough command (PLAY) to the Bluetooth device
*
* @param[in] periph The periph
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_bluetooth_play(esp_periph_handle_t periph);
/**
* @brief Send the AVRC passthrough command (PAUSE) to the Bluetooth device
*
* @param[in] periph The periph
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_bluetooth_pause(esp_periph_handle_t periph);
/**
* @brief Send the AVRC passthrough command (STOP) to the Bluetooth device
*
* @param[in] periph The periph
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_bluetooth_stop(esp_periph_handle_t periph);
/**
* @brief Send the AVRC passthrough command (NEXT) to the Bluetooth device
*
* @param[in] periph The periph
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_bluetooth_next(esp_periph_handle_t periph);
/**
* @brief Send the AVRC passthrough command (PREV) to the Bluetooth device
*
* @param[in] periph The periph
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_bluetooth_prev(esp_periph_handle_t periph);
/**
* @brief Send the AVRC passthrough command (REWIND) to the Bluetooth device
*
* @param[in] periph The periph
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_bluetooth_rewind(esp_periph_handle_t periph);
/**
* @brief Send the AVRC passthrough command (FAST FORWARD) to the Bluetooth device
*
* @param[in] periph The periph
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_bluetooth_fast_forward(esp_periph_handle_t periph);
/**
* @brief Start device discovery.
*
* @param[in] periph The periph
*
* @return
* - ESP_OK : Succeed
* - ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
* - ESP_ERR_INVALID_ARG: if invalid parameters are provided
* - ESP_FAIL: others
*/
esp_err_t periph_bluetooth_discover(esp_periph_handle_t periph);
/**
* @brief Cancel device discovery.
*
* @param[in] periph The periph
*
* @return
* - ESP_OK : Succeed
* - ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
* - ESP_FAIL: others
*/
esp_err_t periph_bluetooth_cancel_discover(esp_periph_handle_t periph);
/**
* @brief Connect remote Device.
*
* @param[in] periph The periph
* @param[in] remote_bda remote Bluetooth device address
* @return
* - ESP_OK : Succeed
* - ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
* - ESP_FAIL: others
*/
esp_err_t periph_bluetooth_connect(esp_periph_handle_t periph, bluetooth_addr_t remote_bda);
/**
* @brief Destroy and cleanup bluetooth service, this function must be called after destroying
* the Bluetoth Stream and Bluetooth Peripheral created by `bluetooth_service_create_stream` and `bluetooth_service_create_periph`
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t bluetooth_service_destroy();
/**
* @brief Get a2dp sample rate.
*
* @return
* - sample rate
*/
int periph_bluetooth_get_a2dp_sample_rate();
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/bluetooth_service/include/bluetooth_service.h
|
C
|
apache-2.0
| 6,559
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 __BT_KEYCONTROL_H__
#define __BT_KEYCONTROL_H__
#if CONFIG_BT_ENABLED
#include "esp_avrc_api.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
*brief Bluetooth key action parameter
*/
typedef struct {
uint32_t evt; /*!< AVRC Controller callback events */
uint32_t key_code; /*!< passthrough command code */
uint8_t key_state; /*!< 0 for PRESSED, 1 for RELEASED */
uint8_t tl; /*!< transaction label, 0 to 15 */
} bt_key_act_param_t;
/**
*brief Bluetooth AVRC callback events
*/
#define ESP_AVRC_CT_KEY_STATE_CHG_EVT (ESP_AVRC_CT_REMOTE_FEATURES_EVT + 1) /*!< key-press action is triggered */
#define ESP_AVRC_CT_PT_RSP_TO_EVT (ESP_AVRC_CT_REMOTE_FEATURES_EVT + 2) /*!< passthrough-command response time-out */
/**
* brief Bluetooth peripheral event id
*/
typedef enum {
PERIPH_BLUETOOTH_UNKNOWN = 0, /*!< No event */
PERIPH_BLUETOOTH_CONNECTED, /*!< A bluetooth device was connected */
PERIPH_BLUETOOTH_DISCONNECTED, /*!< Last connection was disconnected */
PERIPH_BLUETOOTH_AUDIO_STARTED, /*!< The audio session has been started */
PERIPH_BLUETOOTH_AUDIO_SUSPENDED, /*!< The audio session has been suspended */
PERIPH_BLUETOOTH_AUDIO_STOPPED, /*!< The audio session has been stopped */
} periph_bluetooth_event_id_t;
/**
* @brief Initialize bluetooth key action state machine
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t bt_key_act_sm_init(void);
/**
* @brief De-initialize bluetooth key action state machine
*/
void bt_key_act_sm_deinit(void);
/**
* @brief Set bluetooth key action state
*
* @param[in] Bluetooth key action parameter
*
*/
void bt_key_act_state_machine(bt_key_act_param_t *param);
#ifdef __cplusplus
}
#endif
#endif
#endif /* __BT_KEYCONTROL_H__ */
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/bluetooth_service/include/bt_keycontrol.h
|
C
|
apache-2.0
| 3,070
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 _HFP_STREAM_H_
#define _HFP_STREAM_H_
#include "audio_element.h"
#ifdef __cplusplus
extern "C" {
#endif
#if CONFIG_BT_ENABLED
#include "esp_bt.h"
#include "esp_hf_client_api.h"
typedef enum {
HF_DATA_CVSD = 0,
HF_DATA_MSBC = 1,
} hfp_data_enc_type_t;
typedef enum {
INCOMING_STREAM = 0,
OUTGOING_STREAM = 1,
} hfp_stream_type_t;
typedef void (* esp_hf_audio_open_t)(hfp_data_enc_type_t type);
typedef void (* esp_hf_audio_close_t)(void);
typedef struct {
esp_hf_audio_open_t user_hfp_open_cb;
esp_hf_audio_close_t user_hfp_close_cb;
} hfp_stream_user_callback_t;
typedef struct {
hfp_stream_type_t type;
} hfp_stream_config_t;
/**
* @brief Register hfp audio open and close event callback function for application.
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t hfp_open_and_close_evt_cb_register(esp_hf_audio_open_t open_cb, esp_hf_audio_close_t close_cb);
/**
* @brief Initialize and start the hfp service. This function can only be called for one time.
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t hfp_service_init(void);
/**
* @brief Create hfp stream, it is valid when Bluetooth is enabled.
*
* @return The Audio Element handle
*/
audio_element_handle_t hfp_stream_init(hfp_stream_config_t *config);
#endif
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/bluetooth_service/include/hfp_stream.h
|
C
|
apache-2.0
| 2,605
|
COMPONENT_ADD_LDFLAGS = -Wl,--whole-archive -l$(COMPONENT_NAME) -Wl,--no-whole-archive
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/bluetooth_service/test/component.mk
|
Makefile
|
apache-2.0
| 86
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include "esp_log.h"
#include "esp_system.h"
#include "unity.h"
#include "audio_element.h"
#include "audio_pipeline.h"
#include "audio_event_iface.h"
#include "audio_common.h"
#include "i2s_stream.h"
#include "esp_peripherals.h"
#include "periph_touch.h"
#include "board.h"
#include "bluetooth_service.h"
static const char *TAG = "TEST_BLUETOOTH_SERVICE";
/**
* Usage case test
*/
TEST_CASE("Initialize a2dp sink, create bluetooth stream and destroy stream later", "[bluetooth_service]")
{
bluetooth_service_cfg_t bt_cfg = {
.device_name = "ESP-ADF-SPEAKER",
.mode = BLUETOOTH_A2DP_SINK,
};
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES) {
ESP_ERROR_CHECK(nvs_flash_erase());
err = nvs_flash_init();
}
ESP_LOGI(TAG, "Init Bluetooth service");
TEST_ASSERT_EQUAL(ESP_OK, bluetooth_service_start(&bt_cfg));
vTaskDelay(100 / portTICK_PERIOD_MS);
ESP_LOGI(TAG, "Init Bluetooth service repeatedly");
TEST_ASSERT_NOT_EQUAL(ESP_OK, bluetooth_service_start(&bt_cfg));
ESP_LOGI(TAG, "Create Bluetooth stream");
audio_element_handle_t bt_stream_reader = bluetooth_service_create_stream();
TEST_ASSERT_NOT_NULL(bt_stream_reader);
ESP_LOGI(TAG, "Create Bluetooth stream repeatedly");
TEST_ASSERT_NULL(bluetooth_service_create_stream());
ESP_LOGI(TAG, "Initialize peripherals");
esp_periph_config_t periph_cfg = DEFAULT_ESP_PERIPH_SET_CONFIG();
esp_periph_set_handle_t set = esp_periph_set_init(&periph_cfg);
TEST_ASSERT_NOT_NULL(set);
ESP_LOGI(TAG, "Create Bluetooth peripheral");
esp_periph_handle_t bt_periph = bluetooth_service_create_periph();
TEST_ASSERT_NOT_NULL(bt_periph);
ESP_LOGI(TAG, "Create Bluetooth peripheral repeatedly");
TEST_ASSERT_NULL(bluetooth_service_create_periph());
audio_element_run(bt_stream_reader);
ESP_LOGI(TAG, "Start bt peripheral");
TEST_ASSERT_FALSE(esp_periph_start(set, bt_periph));
vTaskDelay(100 / portTICK_PERIOD_MS);
ESP_LOGI(TAG, "Destory stream");
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_stop_all(set));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_stop(bt_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(bt_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_destroy(set));
TEST_ASSERT_EQUAL(ESP_OK, bluetooth_service_destroy());
TEST_ASSERT_EQUAL(ESP_OK, nvs_flash_deinit());
}
TEST_CASE("Initialize a2dp source, create bluetooth stream and destroy stream later", "[bluetooth_service]")
{
bluetooth_service_cfg_t bt_cfg = {
.mode = BLUETOOTH_A2DP_SOURCE,
};
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES) {
ESP_ERROR_CHECK(nvs_flash_erase());
err = nvs_flash_init();
}
ESP_LOGI(TAG, "Init Bluetooth service");
TEST_ASSERT_EQUAL(ESP_OK, bluetooth_service_start(&bt_cfg));
ESP_LOGI(TAG, "Init Bluetooth service repeatedly");
TEST_ASSERT_NOT_EQUAL(ESP_OK, bluetooth_service_start(&bt_cfg));
ESP_LOGI(TAG, "Create Bluetooth stream");
audio_element_handle_t bt_stream_writer = bluetooth_service_create_stream();
TEST_ASSERT_NOT_NULL(bt_stream_writer);
ESP_LOGI(TAG, "Create Bluetooth stream repeatedly");
TEST_ASSERT_NULL(bluetooth_service_create_stream());
ESP_LOGI(TAG, "Initialize peripherals");
esp_periph_config_t periph_cfg = DEFAULT_ESP_PERIPH_SET_CONFIG();
esp_periph_set_handle_t set = esp_periph_set_init(&periph_cfg);
TEST_ASSERT_NOT_NULL(set);
ESP_LOGI(TAG, "Create Bluetooth peripheral");
esp_periph_handle_t bt_periph = bluetooth_service_create_periph();
TEST_ASSERT_NOT_NULL(bt_periph);
ESP_LOGI(TAG, "Create Bluetooth peripheral repeatedly");
TEST_ASSERT_NULL(bluetooth_service_create_periph());
audio_element_run(bt_stream_writer);
ESP_LOGI(TAG, "Start bt peripheral");
TEST_ASSERT_FALSE(esp_periph_start(set, bt_periph));
vTaskDelay(100 / portTICK_PERIOD_MS);
ESP_LOGI(TAG, "Destory stream");
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_stop_all(set));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_stop(bt_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(bt_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_destroy(set));
TEST_ASSERT_EQUAL(ESP_OK, bluetooth_service_destroy());
TEST_ASSERT_EQUAL(ESP_OK, nvs_flash_deinit());
}
TEST_CASE("Initialize a2dp sink, test discovery and cancel discovery", "[bluetooth_service]")
{
bluetooth_service_cfg_t bt_cfg = {
.device_name = "ESP-ADF-SPEAKER",
.mode = BLUETOOTH_A2DP_SINK,
};
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES) {
ESP_ERROR_CHECK(nvs_flash_erase());
err = nvs_flash_init();
}
ESP_LOGI(TAG, "Init Bluetooth service");
TEST_ASSERT_EQUAL(ESP_OK, bluetooth_service_start(&bt_cfg));
ESP_LOGI(TAG, "Create Bluetooth stream");
audio_element_handle_t bt_stream_reader = bluetooth_service_create_stream();
TEST_ASSERT_NOT_NULL(bt_stream_reader);
ESP_LOGI(TAG, "Initialize peripherals");
esp_periph_config_t periph_cfg = DEFAULT_ESP_PERIPH_SET_CONFIG();
esp_periph_set_handle_t set = esp_periph_set_init(&periph_cfg);
TEST_ASSERT_NOT_NULL(set);
ESP_LOGI(TAG, "Create Bluetooth peripheral");
esp_periph_handle_t bt_periph = bluetooth_service_create_periph();
TEST_ASSERT_NOT_NULL(bt_periph);
ESP_LOGI(TAG, "Start bt peripheral");
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_start(set, bt_periph));
vTaskDelay(100 / portTICK_PERIOD_MS);
TEST_ASSERT_EQUAL(ESP_OK, periph_bluetooth_discover(bt_periph));
vTaskDelay(1000 / portTICK_PERIOD_MS);
TEST_ASSERT_EQUAL(ESP_OK, periph_bluetooth_cancel_discover(bt_periph));
audio_element_run(bt_stream_reader);
ESP_LOGI(TAG, "Destory stream");
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_stop_all(set));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_stop(bt_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(bt_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_destroy(set));
TEST_ASSERT_EQUAL(ESP_OK, bluetooth_service_destroy());
TEST_ASSERT_EQUAL(ESP_OK, nvs_flash_deinit());
}
TEST_CASE("Initialize a2dp sink, test avrcp passthrough cmd", "[bluetooth_service]")
{
audio_pipeline_handle_t pipeline;
audio_element_handle_t bt_stream_reader, i2s_stream_writer;
bluetooth_service_cfg_t bt_cfg = {
.device_name = "ESP-ADF-SPEAKER",
.mode = BLUETOOTH_A2DP_SINK,
};
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES) {
ESP_ERROR_CHECK(nvs_flash_erase());
err = nvs_flash_init();
}
ESP_LOGI(TAG, "Init Bluetooth service");
TEST_ASSERT_EQUAL(ESP_OK, bluetooth_service_start(&bt_cfg));
ESP_LOGI(TAG, "Start codec chip");
audio_board_handle_t board_handle = audio_board_init();
TEST_ASSERT_NOT_NULL(board_handle);
TEST_ASSERT_EQUAL(ESP_OK, audio_hal_ctrl_codec(board_handle->audio_hal, AUDIO_HAL_CODEC_MODE_DECODE, AUDIO_HAL_CTRL_START));
ESP_LOGI(TAG, "Create audio pipeline for playback");
audio_pipeline_cfg_t pipeline_cfg = DEFAULT_AUDIO_PIPELINE_CONFIG();
pipeline = audio_pipeline_init(&pipeline_cfg);
TEST_ASSERT_NOT_NULL(pipeline);
ESP_LOGI(TAG, "Create i2s stream to write data to codec chip");
i2s_stream_cfg_t i2s_cfg = I2S_STREAM_CFG_DEFAULT();
i2s_cfg.type = AUDIO_STREAM_WRITER;
i2s_stream_writer = i2s_stream_init(&i2s_cfg);
TEST_ASSERT_NOT_NULL(i2s_stream_writer);
ESP_LOGI(TAG, "Create Bluetooth stream");
bt_stream_reader = bluetooth_service_create_stream();
TEST_ASSERT_NOT_NULL(bt_stream_reader);
ESP_LOGI(TAG, "Register all elements to audio pipeline");
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, bt_stream_reader, "bt"));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, i2s_stream_writer, "i2s"));
ESP_LOGI(TAG, "Link it together [Bluetooth]-->bt_stream_reader-->i2s_stream_writer-->[codec_chip]");
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_link(pipeline, (const char *[]) {"bt", "i2s"}, 2));
ESP_LOGI(TAG, "Initialize peripherals");
esp_periph_config_t periph_cfg = DEFAULT_ESP_PERIPH_SET_CONFIG();
esp_periph_set_handle_t set = esp_periph_set_init(&periph_cfg);
TEST_ASSERT_NOT_NULL(set);
ESP_LOGI(TAG, "Initialize Touch peripheral");
TEST_ASSERT_EQUAL(ESP_OK, audio_board_key_init(set));
ESP_LOGI(TAG, "Create Bluetooth peripheral");
esp_periph_handle_t bt_periph = bluetooth_service_create_periph();
TEST_ASSERT_NOT_NULL(bt_periph);
ESP_LOGI(TAG, "Start bt peripheral");
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_start(set, bt_periph));
ESP_LOGI(TAG, "Set up event listener");
audio_event_iface_cfg_t evt_cfg = AUDIO_EVENT_IFACE_DEFAULT_CFG();
audio_event_iface_handle_t evt = audio_event_iface_init(&evt_cfg);
TEST_ASSERT_NOT_NULL(evt);
ESP_LOGI(TAG, "Listening event from all elements of pipeline");
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_set_listener(pipeline, evt));
ESP_LOGI(TAG, "Listening event from peripherals");
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_set_listener(esp_periph_set_get_event_iface(set), evt));
ESP_LOGI(TAG, "Start audio_pipeline");
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_run(pipeline));
ESP_LOGI(TAG, "Listen for all pipeline events");
while (1) {
audio_event_iface_msg_t msg;
esp_err_t ret = audio_event_iface_listen(evt, &msg, portMAX_DELAY);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "[ * ] Event interface error : %d", ret);
continue;
}
if (msg.source_type == AUDIO_ELEMENT_TYPE_ELEMENT && msg.source == (void *) bt_stream_reader
&& msg.cmd == AEL_MSG_CMD_REPORT_MUSIC_INFO) {
audio_element_info_t music_info = {0};
audio_element_getinfo(bt_stream_reader, &music_info);
ESP_LOGI(TAG, "[ * ] Receive music info from Bluetooth, sample_rates=%d, bits=%d, ch=%d",
music_info.sample_rates, music_info.bits, music_info.channels);
audio_element_setinfo(i2s_stream_writer, &music_info);
i2s_stream_set_clk(i2s_stream_writer, music_info.sample_rates, music_info.bits, music_info.channels);
continue;
}
if (msg.source_type == PERIPH_ID_TOUCH
&& msg.cmd == PERIPH_TOUCH_TAP
&& msg.source == (void *)esp_periph_set_get_by_id(set, PERIPH_ID_TOUCH)) {
if ((int) msg.data == get_input_play_id()) {
ESP_LOGI(TAG, "[ * ] [Play] touch tap event");
TEST_ASSERT_EQUAL(ESP_OK, periph_bluetooth_play(bt_periph));
} else if ((int) msg.data == get_input_set_id()) {
ESP_LOGI(TAG, "[ * ] [Set] touch tap event");
TEST_ASSERT_EQUAL(ESP_OK, periph_bluetooth_pause(bt_periph));
} else if ((int) msg.data == get_input_volup_id()) {
ESP_LOGI(TAG, "[ * ] [Vol+] touch tap event");
TEST_ASSERT_EQUAL(ESP_OK, periph_bluetooth_next(bt_periph));
} else if ((int) msg.data == get_input_voldown_id()) {
ESP_LOGI(TAG, "[ * ] [Vol-] touch tap event");
TEST_ASSERT_EQUAL(ESP_OK, periph_bluetooth_prev(bt_periph));
}
}
/* Stop when the Bluetooth is disconnected or suspended */
if (msg.source_type == PERIPH_ID_BLUETOOTH
&& msg.source == (void *)bt_periph) {
if (msg.cmd == PERIPH_BLUETOOTH_DISCONNECTED) {
ESP_LOGW(TAG, "[ * ] Bluetooth disconnected");
break;
}
}
/* Stop when the last pipeline element (i2s_stream_writer in this case) receives stop event */
if (msg.source_type == AUDIO_ELEMENT_TYPE_ELEMENT && msg.source == (void *) i2s_stream_writer
&& msg.cmd == AEL_MSG_CMD_REPORT_STATUS
&& (((int)msg.data == AEL_STATUS_STATE_STOPPED) || ((int)msg.data == AEL_STATUS_STATE_FINISHED))) {
ESP_LOGW(TAG, "[ * ] Stop event received");
break;
}
}
ESP_LOGI(TAG, "Stop audio_pipeline");
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_terminate(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, bt_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unregister(pipeline, i2s_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_remove_listener(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_stop_all(set));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_remove_listener(esp_periph_set_get_event_iface(set), evt));
TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_destroy(evt));
ESP_LOGI(TAG, "Release all resources");
TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_deinit(pipeline));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(bt_stream_reader));
TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(i2s_stream_writer));
TEST_ASSERT_EQUAL(ESP_OK, esp_periph_set_destroy(set));
TEST_ASSERT_EQUAL(ESP_OK, bluetooth_service_destroy());
TEST_ASSERT_EQUAL(ESP_OK, nvs_flash_deinit());
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/bluetooth_service/test/test_bluetooth_service.c
|
C
|
apache-2.0
| 14,559
|
set(COMPONENT_ADD_INCLUDEDIRS ./dueros/lightduer/include)
# Edit following two lines to set component requirements (see docs)
set(COMPONENT_SRCS )
register_component()
IF (NOT (CONFIG_IDF_TARGET STREQUAL "esp32c3"))
IF (IDF_VERSION_MAJOR GREATER 3)
target_link_libraries(${COMPONENT_TARGET} INTERFACE "-L${CMAKE_CURRENT_LIST_DIR}/dueros/lightduer")
target_link_libraries(${COMPONENT_TARGET} INTERFACE duer-device-v4x)
ELSE ()
target_link_libraries(${COMPONENT_TARGET} INTERFACE "-L${CMAKE_CURRENT_LIST_DIR}/dueros/lightduer")
target_link_libraries(${COMPONENT_TARGET} INTERFACE duer-device)
ENDIF (IDF_VERSION_MAJOR GREATER 3)
ENDIF()
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/CMakeLists.txt
|
CMake
|
apache-2.0
| 640
|
#
# Component Makefile
#
# DuerOS LightDuer Module
LIGHTDUER_PATH := dueros/lightduer
COMPONENT_ADD_INCLUDEDIRS += $(LIGHTDUER_PATH)/include
COMPONENT_SRCDIRS :=
ifdef IDF_VERSION_MAJOR
ifneq ($(IDF_VERSION_MAJOR),3)
COMPONENT_ADD_LDFLAGS += -L$(COMPONENT_PATH)/$(LIGHTDUER_PATH) -lduer-device-v4x
else
COMPONENT_ADD_LDFLAGS += -L$(COMPONENT_PATH)/$(LIGHTDUER_PATH) -lduer-device
endif
else
COMPONENT_ADD_LDFLAGS += -L$(COMPONENT_PATH)/$(LIGHTDUER_PATH) -lduer-device
endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/component.mk
|
Makefile
|
apache-2.0
| 477
|
/*
Copyright (c) 2009 Dave Gamble
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 baidu_json__h
#define baidu_json__h
#include "stdlib.h"
#ifdef __cplusplus
extern "C"
{
#endif
/* baidu_json Types: */
#define baidu_json_False (1 << 0)
#define baidu_json_True (1 << 1)
#define baidu_json_NULL (1 << 2)
#define baidu_json_Number (1 << 3)
#define baidu_json_String (1 << 4)
#define baidu_json_Array (1 << 5)
#define baidu_json_Object (1 << 6)
#define baidu_json_IsReference 256
#define baidu_json_StringIsConst 512
/* The baidu_json structure: */
typedef struct baidu_json
{
/* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
struct baidu_json *next;
struct baidu_json *prev;
/* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
struct baidu_json *child;
/* The type of the item, as above. */
int type;
/* The item's string, if type==baidu_json_String */
char *valuestring;
/* The item's number, if type==baidu_json_Number */
int valueint;
/* The item's number, if type==baidu_json_Number */
double valuedouble;
/* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
char *string;
} baidu_json;
typedef struct baidu_json_Hooks
{
void *(*malloc_fn)(size_t sz);
void (*free_fn)(void *ptr);
} baidu_json_Hooks;
/* Supply malloc, realloc and free functions to baidu_json */
extern void baidu_json_InitHooks(baidu_json_Hooks* hooks);
extern int baidu_json_Uninit(void);
/* Supply a block of JSON, and this returns a baidu_json object you can interrogate. Call baidu_json_Delete when finished. */
extern baidu_json *baidu_json_Parse(const char *value);
/* Render a baidu_json entity to text for transfer/storage. Free the char* when finished. */
extern char *baidu_json_Print(const baidu_json *item);
/* Render a baidu_json entity to text for transfer/storage without any formatting. Free the char* when finished. */
extern char *baidu_json_PrintUnformatted(const baidu_json *item);
/* Render a baidu_json entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
extern char *baidu_json_PrintBuffered(const baidu_json *item, int prebuffer, int fmt);
/* Delete a baidu_json entity and all subentities. */
extern void baidu_json_Delete(baidu_json *c);
/* Returns the number of items in an array (or object). */
extern int baidu_json_GetArraySize(const baidu_json *array);
/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
extern baidu_json *baidu_json_GetArrayItem(const baidu_json *array, int item);
/* Get item "string" from object. Case insensitive. */
extern baidu_json *baidu_json_GetObjectItem(const baidu_json *object, const char *string);
extern int baidu_json_HasObjectItem(const baidu_json *object, const char *string);
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when baidu_json_Parse() returns 0. 0 when baidu_json_Parse() succeeds. */
extern const char *baidu_json_GetErrorPtr(void);
/* These calls create a baidu_json item of the appropriate type. */
extern baidu_json *baidu_json_CreateNull(void);
extern baidu_json *baidu_json_CreateTrue(void);
extern baidu_json *baidu_json_CreateFalse(void);
extern baidu_json *baidu_json_CreateBool(int b);
extern baidu_json *baidu_json_CreateNumber(double num);
// len indicate the length of string, if len <=0, the length will be got throuth strlen(string)
extern baidu_json *baidu_json_CreateString(const char *string, size_t len);
extern baidu_json *baidu_json_CreateArray(void);
extern baidu_json *baidu_json_CreateObject(void);
/* These utilities create an Array of count items. */
extern baidu_json *baidu_json_CreateIntArray(const int *numbers, int count);
extern baidu_json *baidu_json_CreateFloatArray(const float *numbers, int count);
extern baidu_json *baidu_json_CreateDoubleArray(const double *numbers, int count);
extern baidu_json *baidu_json_CreateStringArray(const char **strings, int count);
/* Append item to the specified array/object. */
extern void baidu_json_AddItemToArray(baidu_json *array, baidu_json *item);
extern void baidu_json_AddItemToObject(baidu_json *object, const char *string, baidu_json *item);
extern void baidu_json_AddItemToObjectCS(baidu_json *object, const char *string, baidu_json *item); /* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the baidu_json object */
/* Append reference to item to the specified array/object. Use this when you want to add an existing baidu_json to a new baidu_json, but don't want to corrupt your existing baidu_json. */
extern void baidu_json_AddItemReferenceToArray(baidu_json *array, baidu_json *item);
extern void baidu_json_AddItemReferenceToObject(baidu_json *object, const char *string, baidu_json *item);
/* Remove/Detatch items from Arrays/Objects. */
extern baidu_json *baidu_json_DetachItemFromArray(baidu_json *array, int which);
extern void baidu_json_DeleteItemFromArray(baidu_json *array, int which);
extern baidu_json *baidu_json_DetachItemFromObject(baidu_json *object, const char *string);
extern void baidu_json_DeleteItemFromObject(baidu_json *object, const char *string);
/* Update array items. */
extern void baidu_json_InsertItemInArray(baidu_json *array, int which, baidu_json *newitem); /* Shifts pre-existing items to the right. */
extern void baidu_json_ReplaceItemInArray(baidu_json *array, int which, baidu_json *newitem);
extern void baidu_json_ReplaceItemInObject(baidu_json *object,const char *string,baidu_json *newitem);
/* Duplicate a baidu_json item */
extern baidu_json *baidu_json_Duplicate(const baidu_json *item, int recurse);
/* Duplicate will create a new, identical baidu_json item to the one you pass, in new memory that will
need to be released. With recurse!=0, it will duplicate any children connected to the item.
The item->next and ->prev pointers are always zero on return from Duplicate. */
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error. If not, then baidu_json_GetErrorPtr() does the job. */
extern baidu_json *baidu_json_ParseWithOpts(const char *value, const char **return_parse_end, int require_null_terminated);
extern void baidu_json_Minify(char *json);
extern void baidu_json_release(void *ptr);
/* Macros for creating things quickly. */
#define baidu_json_AddNullToObject(object,name) baidu_json_AddItemToObject(object, name, baidu_json_CreateNull())
#define baidu_json_AddTrueToObject(object,name) baidu_json_AddItemToObject(object, name, baidu_json_CreateTrue())
#define baidu_json_AddFalseToObject(object,name) baidu_json_AddItemToObject(object, name, baidu_json_CreateFalse())
#define baidu_json_AddBoolToObject(object,name,b) baidu_json_AddItemToObject(object, name, baidu_json_CreateBool(b))
#define baidu_json_AddNumberToObject(object,name,n) baidu_json_AddItemToObject(object, name, baidu_json_CreateNumber(n))
#define baidu_json_AddStringToObject(object,name,s) baidu_json_AddItemToObject(object, name, baidu_json_CreateString(s, 0))
#define baidu_json_AddStringToObjectWithLength(object,name,s,len) baidu_json_AddItemToObject(object, name, baidu_json_CreateString(s, len))
/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the baidu_json object */
#define baidu_json_AddNullToObjectCS(object,name) baidu_json_AddItemToObjectCS(object, name, baidu_json_CreateNull())
#define baidu_json_AddTrueToObjectCS(object,name) baidu_json_AddItemToObjectCS(object, name, baidu_json_CreateTrue())
#define baidu_json_AddFalseToObjectCS(object,name) baidu_json_AddItemToObjectCS(object, name, baidu_json_CreateFalse())
#define baidu_json_AddBoolToObjectCS(object,name,b) baidu_json_AddItemToObjectCS(object, name, baidu_json_CreateBool(b))
#define baidu_json_AddNumberToObjectCS(object,name,n) baidu_json_AddItemToObjectCS(object, name, baidu_json_CreateNumber(n))
#define baidu_json_AddStringToObjectCS(object,name,s) baidu_json_AddItemToObjectCS(object, name, baidu_json_CreateString(s, 0))
#define baidu_json_AddStringToObjectCSWithLength(object,name,s,len) baidu_json_AddItemToObjectCS(object, name, baidu_json_CreateString(s, len))
/* When assigning an integer value, it needs to be propagated to valuedouble too. */
#define baidu_json_SetIntValue(object,val) ((object) ? (object)->valueint = (object)->valuedouble = (val) : (val))
#define baidu_json_SetNumberValue(object,val) ((object) ? (object)->valueint = (object)->valuedouble = (val) : (val))
/* Macro for iterating over an array */
#define baidu_json_ArrayForEach(pos, head) for(pos = (head)->child; pos != NULL; pos = pos->next)
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/baidu_json.h
|
C
|
apache-2.0
| 10,177
|
#ifndef DUER_DEVICE_VAD_H
#define DUER_DEVICE_VAD_H
#ifdef __cplusplus
extern "C" {
#endif
// Copyright 2017 Baidu Inc. All Rights Reserved.
// Author: liuzhiyu (liuzhiyu04@baidu.com)
//
// device vad
// default , do not modify
#define SAMPLE_RATE (16000)
#define VAD_10MS_SIZE (SAMPLE_RATE/100*2)
#define VAD_20MS_SIZE (SAMPLE_RATE/100*4)
#define VAD_FRAME_MS (80) // 80ms
#define VAD_INPUT_MS (20) // 20ms
#define VAD_CACHE_SIZE (VAD_FRAME_MS/VAD_INPUT_MS)
#define VAD_VOICE_NUM_IN_FRAME (2) // if a frame which is 80ms len, have >= 20ms voice, detect speaking
// can change
#define VAD_IGNORE_HOTWORD_TIME (2 * VAD_FRAME_MS) // 2*80 ms
#define VAD_SPEAKING_SILENCE_VALID_TIME (6 * VAD_FRAME_MS) // 6*80 ms
#define VAD_VOICE_VALID_TIME (5 * VAD_FRAME_MS) // 5*80 ms
// human stop speak
int vad_stop_speak(void);
void vad_stop_speak_done(void);
// human start speak
int vad_start_speak(void);
void vad_start_speak_done(void);
// run vad state machine
int device_vad(char *buff, size_t length);
// when wakeup use this function
void vad_set_wakeup(void);
// when cloud vad work, use this function
void vad_set_playing(void);
// ms recommendation is a multiple of VAD_FRAME_MS
void vad_set_silence_valid_time(unsigned int ms);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/device_vad.h
|
C
|
apache-2.0
| 1,277
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/**
* File: lightduer_2nd_wakeup.h
* Auth: Sijun Li (lisijun@baidu.com)
* Desc: apply APIs to support cloud second wakeup.
*/
#ifndef BAIDU_DUER_LIGHTDUER_2ND_WAKEUP_H
#define BAIDU_DUER_LIGHTDUER_2ND_WAKEUP_H
#ifdef __cplusplus
extern "C" {
#endif
#ifdef DUER_SECOND_WAKEUP_ENABLE
/*
* Define type of callback of second wakeup directive.
*
* @param is_wakeup: Success: > 0
* Failed: <= 0
*
* @return void
*/
typedef void (*duer_on_2nd_wakeup_handler)(int is_wakeup);
/*
* Initialize second wakeup feature.
*
* @param handler: callback of second wakeup directive.
*
* @return: DUER_OK if successful, else failed.
*/
duer_status_t duer_2nd_wakeup_init(void);
/*
* Set callback to get second wakeup result.
*
* @param handler, the point of handler defined by user.
*/
void duer_2nd_wakeup_set_handler(duer_on_2nd_wakeup_handler handler);
#endif//DUER_SECOND_WAKEUP_ENABLE
#ifdef __cplusplus
}
#endif
#endif/*BAIDU_DUER_LIGHTDUER_2ND_WAKEUP_H*/
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_2nd_wakeup.h
|
C
|
apache-2.0
| 1,605
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/**
* File: baidu_ca_adapter.h
* Auth: Su Hao (suhao@baidu.com)
* Desc: Adapt the IoT CA to different platform.
*/
#ifndef BAIDU_DUER_IOT_CA_ADAPTER_BAIDU_CA_ADAPTER_H
#define BAIDU_DUER_IOT_CA_ADAPTER_BAIDU_CA_ADAPTER_H
#ifdef __cplusplus
extern "C" {
#endif
extern void baidu_ca_adapter_initialize(void);
extern void baidu_ca_adapter_finalize(void);
#ifdef __cplusplus
}
#endif
#endif/*BAIDU_DUER_IOT_CA_ADAPTER_BAIDU_CA_ADAPTER_H*/
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_adapter.h
|
C
|
apache-2.0
| 1,060
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/**
* File: lightduer_aes.h
* Auth: Leliang Zhang(zhangleliang@baidu.com)
* Desc: Provide the aes encryption(only CBC mode support now).
*/
#ifndef BAIDU_DUER_LIGHTDUER_AES_H
#define BAIDU_DUER_LIGHTDUER_AES_H
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
// aes context, real type depend on the implementation
typedef void *duer_aes_context;
// get the initialized aes context
duer_aes_context duer_aes_context_init(void);
/*
*set the key used in the encryption and decryption
*@param ctx, got from duer_aes_context_init
*@param key, the key will be used,
*@param keybits, the length of @key in bits, should be one of 128, 192, 256
*@return, DUER_OK on success, or other error code
*/
int duer_aes_setkey(duer_aes_context ctx,
const unsigned char *key,
unsigned int keybits);
/*
*set the iv used in the encryption and decryption
*@param ctx, got from duer_aes_context_init
*@param iv, the iv will be used, it's 16 bytes length.
*@return, DUER_OK on success, or other error code
*/
int duer_aes_setiv(duer_aes_context ctx, unsigned char iv[16]);
/*
*encrypt the input info, use the key/iv from @duer_aes_setkey and @duer_aes_setiv
*@param ctx, got from duer_aes_context_init
*@param length, the length of the input, should be multiple of 16
*@param input, the content will be encrypted
*#param output, the encrypted content
*@return, DUER_OK on success, or other error code
*/
int duer_aes_cbc_encrypt(duer_aes_context ctx,
size_t length,
const unsigned char* input,
unsigned char* output);
/*
*decrypt the input info, use the key/iv from @duer_aes_setkey and @duer_aes_setiv
*@param ctx, got from duer_aes_context_init
*@param length, the length of the input, should be multiple of 16
*@param input, the content will be decrypted
*#param output, the decrypted content
*@return, DUER_OK on success, or other error code
*/
int duer_aes_cbc_decrypt(duer_aes_context ctx,
size_t length,
const unsigned char* input,
unsigned char* output);
/*
*destroy the context
*@param ctx, got from duer_aes_context_init
*@return, DUER_OK on success, or other error code
*/
int duer_aes_context_destroy(duer_aes_context ctx);
#ifdef __cplusplus
}
#endif
#endif/*BAIDU_DUER_LIGHTDUER_AES_H*/
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_aes.h
|
C
|
apache-2.0
| 3,047
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
// Author: Gang Chen (chengang12@baidu.com)
//
// Description: The AP information APIs.
#ifndef BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_AP_INFO_H
#define BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_AP_INFO_H
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* Obtain the wifi signal status
*
* @Return duer_status_t:
* DUER_OK, DUER_ERR_FAILED, DUER_ERR_WIFI_SIGNAL_WEAK OR DUER_ERR_WIFI_DISCONNECTED
*/
DUER_INT duer_status_t duer_wifi_status_get(void);
/*
* The wifi signal status callbacks
* Return the wifi signal status
*/
typedef duer_status_t (*duer_get_wifi_status_f)();
/*
* Initial the AP information callbacks for Baidu CA
*
* @Param f_wifi_status, in, the function obtain the wifi signal status
*/
DUER_EXT void baidu_ca_ap_info_init(duer_get_wifi_status_f f_wifi_status);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_AP_INFO_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_ap_info.h
|
C
|
apache-2.0
| 1,584
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/**
* File: lightduer_bind_device.h
* Auth: Chen Xihao (chenxihao@baidu.com)
* Desc: Support WeChat Subscription to bind device
*/
#ifndef BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_BIND_DEVICE_H
#define BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_BIND_DEVICE_H
#include "lightduer_types.h"
#include "lightduer_dcs_router.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* DESC:
* Start the task to bind device.
*
* PARAM:
* @param[in] uuid: the uuid of device
* @param[in] bind_token: the bind token of device
* @param[in] lifecycle: the lifecycle of task in seconds, at least 60s
*
* @RETURN: success return DUER_OK, failed return DUER_ERR_FAILED.
*/
duer_status_t duer_start_bind_device_task(const char *uuid,
const char *bind_token, size_t lifecycle);
/**
* DESC:
* Stop the task that bind device.
*
* PARAM: none
*
* @RETURN: success return DUER_OK, failed return DUER_ERR_FAILED.
*/
duer_status_t duer_stop_bind_device_task(void);
/**
* DESC:
* Send utoken to cloud to bind device.
*
* PARAM:
* @param[in] utoken: the token passed from App
* @param[in] callback: the callback function to receive the bind result
*
* @RETURN: success return DUER_OK, failed return other.
*/
duer_status_t duer_bind_device_use_utoken(const char *utoken, dcs_directive_handler callback);
#ifdef __cplusplus
}
#endif
#endif /* BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_BIND_DEVICE_H */
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_bind_device.h
|
C
|
apache-2.0
| 2,018
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
// Author: Su Hao (suhao@baidu.com)
//
// Desc: Provide the API for external applications.
#ifndef BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_INCLUDE_BAIDU_CA_H
#define BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_INCLUDE_BAIDU_CA_H
#include "lightduer_types.h"
#include "lightduer_coap.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* Acquire the handler
*
* @Param soc_ctx, in socket context
* @Return duer_handler, the global context handler
*/
DUER_EXT duer_handler baidu_ca_acquire(duer_transevt_func soc_ctx);
/*
* Acquire the resources for response
*
* @Param hdlr, in, the handler will be operated
* @Param list_res, in, resource list
* @Param list_res_size, in resource list length
* @Return duer_status_t, in, the operation result
*/
DUER_EXT duer_status_t baidu_ca_add_resources(duer_handler hdlr,
const duer_res_t list_res[],
duer_size_t list_res_size);
/*
* Load the configuration infomation
*
* @Param hdlr, in, the handler will be operated
* @Param data, in, the configuration data
* @Param size, in, the data size
* @Return duer_status_t, in, the operation result
*/
DUER_EXT duer_status_t baidu_ca_load_configuration(duer_handler hdlr, const void *data, duer_size_t size);
DUER_EXT duer_status_t baidu_ca_unload_configuration(duer_handler hdlr);
/*
* Start run the Baidu CA, prepare the environment.
*
* @Param hdlr, in, the handler will be operated
* @Return duer_status_t, in, the operation result
*/
DUER_EXT duer_status_t baidu_ca_start(duer_handler hdlr);
/*
*
* Determine the CA is started.
*
* @Param hdlr, in, the handler will be operated
* @Return duer_bool, DUER_TRUE if started, else return DUER_FALSE.
*/
DUER_EXT duer_bool baidu_ca_is_started(duer_handler hdlr);
/*
*
* Determine the CA is stopped.
*
* @Param hdlr, in, the handler will be operated
* @Return duer_bool, DUER_TRUE if stopped, else return DUER_FALSE.
*/
DUER_EXT duer_bool baidu_ca_is_stopped(duer_handler hdlr);
/*
* Set the Reporter report response callback.
*
* @Param hdlr, in, the handler will be operated
* @Param f_response, in, the callback for notify user the report data response
* @Return duer_status_t, in, the operation result
*/
DUER_EXT duer_status_t baidu_ca_report_set_response_callback(duer_handler hdlr,
duer_notify_f f_response,
duer_context context);
/*
* Set the transmit data callback.
*
* @Param hdlr, in, the handler will be operated
* @Param f_transmit, in, the callback for transmit encoded data.
* @Return duer_status_t, in, the operation result
*/
DUER_EXT duer_status_t baidu_ca_report_set_data_tx_callback(duer_handler hdlr, duer_transmit_f f_transmit);
/*
* Build the message body that will be reported.
*
* @Param hdlr, in, the handler will be operated
* @Param data, in, the message report data
* @Param size, in, the data size
* @Param confirmable, in, the report data QoS
* @Return duer_msg_t *, in, the generated message body,
* it SHOULD be released by ${link baidu_ca_release_message}
*/
DUER_EXT duer_msg_t* baidu_ca_build_report_message(duer_handler hdlr,
duer_bool confirmable);
/*
* Build the message body that will be responsed to remote.
*
* @Param hdlr, in, the handler will be operated
* @Param msg, in, the message that remote requested
* @Param msg_code, out, the response message code
* @Return duer_msg_t *, in, the generated message body,
* it SHOULD be released by ${link baidu_ca_release_message}
*/
DUER_EXT duer_msg_t* baidu_ca_build_response_message(duer_handler hdlr,
const duer_msg_t* msg,
duer_u8_t msg_code);
/*
* Build the seperate response to the request with the token.
*
* @Param hdlr, in, the handler will be operated
* @Param ptoken, in, the token used in the message
* @Param token_len, in, the length of the token
* @Param msg_code, in, the response message code
* @Param confirmable, in,
* @Return duer_msg_t *, out, the generated message body,
* it SHOULD be released by ${link baidu_ca_release_message}
*/
DUER_EXT duer_msg_t* baidu_ca_build_seperate_response_message(duer_handler hdlr,
const char *ptoken,
duer_size_t token_len,
int msg_code,
duer_bool confirmable);
/*
* Release the message that generated by baidu_ca_build_XXXX_message.
*
* @Param hdlr, in, the handler will be operated
* @Param msg, in, the message that remote requested
*/
DUER_EXT void baidu_ca_release_message(duer_handler hdlr, duer_msg_t* msg);
/*
* Send the message
*
* @Param hdlr, in, the handler will be operated
* @Param msg, in, the msg will be sent
* @Param addr, in, the remote addr
* @Return duer_status_t, in, the operation result
*/
DUER_EXT duer_status_t baidu_ca_send_data(duer_handler hdlr,
const duer_msg_t* msg,
const duer_addr_t* addr);
/*
* Send the user data
*
* @Param hdlr, in, the handler will be operated
* @Param data, in, the user data
* @Param size, in, the data size
* @Param addr, in, the remote addr
* @Return duer_status_t, in, the operation result
*/
DUER_EXT duer_status_t baidu_ca_send_data_directly(duer_handler hdlr,
const void *data,
duer_size_t szie,
const duer_addr_t* addr);
/*
* When the message data has ready to be received
*
* @Param hdlr, in, the handler will be operated
* @Param addr, in, the remote addr
* @Return duer_status_t, in, the operation result
*/
DUER_EXT duer_status_t baidu_ca_data_available(duer_handler hdlr,
const duer_addr_t* addr);
/*
* Execute the cached CoAP data, such as blockwise, resending...
*
* @Param hdlr, in, the handler will be operated
* @Return duer_status_t, in, the operation result
*/
DUER_EXT duer_status_t baidu_ca_exec(duer_handler hdlr);
/*
* Stop the Baidu CA.
*
* @Param hdlr, in, the handler will be operated
* @Return duer_status_t, in, the operation result
*/
DUER_EXT duer_status_t baidu_ca_stop(duer_handler hdlr);
/*
* Release the handler
*
* @Param hdlr, in, the handler will be operated
* @Return duer_status_t, in, the operation result
*/
DUER_EXT duer_status_t baidu_ca_release(duer_handler hdlr);
/*
* Obtain the uuid
*
* @Param hdlr, in, the handler will be operated
* @Return const char *, The UUID string
*/
DUER_EXT const char *baidu_ca_get_uuid(duer_handler hdlr);
/*
* Obtain the rsa cacrt
*
* @Param hdlr, in, the handler will be operated
* @Return const char *, The RSA CACRT string
*/
DUER_EXT const char *baidu_ca_get_rsa_cacrt(duer_handler hdlr);
/*
* Obtain the bindToken
*
* @Param hdlr, in, the handler will be operated
* @Return const char *, The bindToken string
*/
DUER_EXT const char *baidu_ca_get_bind_token(duer_handler hdlr);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_INCLUDE_BAIDU_CA_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_ca.h
|
C
|
apache-2.0
| 8,151
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
// Author: Su Hao (suhao@baidu.com)
//
// Description: Baidu CA configuration.
#ifndef BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_CONF_H
#define BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_CONF_H
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef void* duer_conf_handler;
/*
* Create the configuation from buffer
*
* @Param data, in, the configuation stream
* @Param size, in, the data size
* @Return duer_conf_handler, the handler for operating the configuation
*/
DUER_INT duer_conf_handler duer_conf_create(const void* data, duer_size_t size);
/*
* Get the string from the configuration by the key
*
* @Param hdlr, in, the handler for configuation
* @Param key, in, the key of the item
* @Return const char *, the string value of the key
*/
DUER_INT const char* duer_conf_get_string(duer_conf_handler hdlr, const char* key);
/*
* Get the unsigned short from the configuration by the key
*
* @Param hdlr, in, the handler for configuation
* @Param key, in, the key of the item
* @Return duer_u16_t, the unsigned short value of the key
*/
DUER_INT duer_u16_t duer_conf_get_ushort(duer_conf_handler hdlr, const char* key);
/*
* Get the unsigned int from the configuration by the key
*
* @Param hdlr, in, the handler for configuation
* @Param key, in, the key of the item
* @Return duer_u32_t, the unsigned int value of the key
*/
DUER_INT duer_u32_t duer_conf_get_uint(duer_conf_handler hdlr, const char* key);
/*
* Get the string from the configuration by the key
*
* @Param hdlr, in, the handler for configuation
*/
DUER_INT void duer_conf_destroy(duer_conf_handler hdlr);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_CONF_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_ca_conf.h
|
C
|
apache-2.0
| 2,383
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
// Author: Su Hao (suhao@baidu.com)
//
// Description: The CoAP adapter.
#ifndef BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_COAP_H
#define BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_COAP_H
#include "lightduer_types.h"
#include "lightduer_lib.h"
#include "lightduer_network_defs.h"
#include "lightduer_coap_defs.h"
#include "lightduer_coap_ep.h"
#define DUER_COAP_MESSAGE_ID_INVALID (0)
#ifdef __cplusplus
extern "C" {
#endif
typedef void* duer_coap_handler;
typedef duer_status_t (*duer_coap_result_f)(duer_context ctx,
duer_coap_handler hdlr,
const duer_msg_t* msg,
const duer_addr_t* addr);
/*
* Acquire the coap handler.
*
* @Param f_result, in, the callback for user handling events
* @Param context, in, the user context for f_result callback
* @Param ctx_context, in, the user socket context
* @Param key_info, something generated on up layer, but used on down layer
* @Return duer_coap_handler, the coap context
*/
DUER_INT duer_coap_handler duer_coap_acquire(duer_coap_result_f f_result,
duer_context context,
duer_transevt_func ctx_context,
const void *key_info);
/*
* Set tx function callback
*
* @Param hdlr, in, the CoAP context
* @Param tx, in, the tx function callback
* @Return duer_status_t, the connect status
*/
DUER_INT duer_status_t duer_coap_set_tx_callback(duer_coap_handler hdlr, duer_transmit_f tx);
/*
* Connect to remote CoAP server
*
* @Param hdlr, in, the CoAP context
* @Param addr, in, the remote server address
* @Param data, in, the security suite data
* @Param size, in, the data size
* @Return duer_status_t, the connect status
*/
DUER_INT duer_status_t duer_coap_connect(duer_coap_handler hdlr,
const duer_addr_t* addr,
const void* data,
duer_size_t size);
/*
* Disconnect from remote CoAP server
*
* @Param hdlr, in, the CoAP context
* @Return duer_status_t, the connect status
*/
DUER_INT duer_status_t duer_coap_disconnect(duer_coap_handler hdlr);
/*
* Add the resource for CoAP request from other endpoints
*
* @Param hdlr, in, the CoAP context
* @Param res, in, the resource information
* @Return duer_status_t, the result
*/
DUER_INT duer_status_t duer_coap_resource_add(duer_coap_handler hdlr,
const duer_res_t* res);
/*
* Remove the resource for CoAP request from other endpoints
*
* @Param hdlr, in, the CoAP context
* @Param path, in, the resource path
* @Return duer_status_t, the result
*/
DUER_INT duer_status_t duer_coap_resource_remove(duer_coap_handler coap,
const char* path);
/*
* Register endpoint by LWM2M
*
* @Param hdlr, in, the CoAP context
* @Param ep, in, the endpoint information
* @Return duer_status_t, if > 0, the result is the register message id, else is the error status
*/
DUER_INT duer_status_t duer_coap_register(duer_coap_handler coap,
const duer_coap_ep_t* ep);
/*
* Unregister the endpoint by LWM2M
*
* @Param hdlr, in, the CoAP context
* @Return duer_status_t, if > 0, the result is the unregister message id, else is the error status
*/
DUER_INT duer_status_t duer_coap_unregister(duer_coap_handler coap);
/*
* Update registration by LWM2M
*
* @Param hdlr, in, the CoAP context
* @Param lifetime, in, the endpoint lifetime
* @Return duer_status_t, if > 0, the result is the update registration message id,
* else is the error status
*/
DUER_INT duer_status_t duer_coap_update_registration(duer_coap_handler coap,
duer_u32_t lifetime);
/*
* Send the CoAP message
*
* @Param hdlr, in, the CoAP context
* @Param msg, in, the CoAP message
* @Return duer_status_t, the result
*/
DUER_INT duer_status_t duer_coap_send(duer_coap_handler coap, const duer_msg_t* msg);
/*
* Send the data directly
*
* @Param hdlr, in, the CoAP context
* @Param data, in, the user data
* @Param size, in, the data size
* @Return duer_status_t, the result
*/
DUER_INT duer_status_t duer_coap_send_data(duer_coap_handler hdlr, const void *data, duer_size_t size);
/*
* Receive the CoAP message
*
* @Param hdlr, in, the CoAP context
* @Return duer_status_t, the result
*/
DUER_INT duer_status_t duer_coap_data_available(duer_coap_handler coap);
/*
* Execute the cached CoAP data
*
* @Param hdlr, in, the CoAP context
* @Param timestamp, in, the timestamp for mark the message
* @Return duer_status_t, the result
*/
DUER_INT duer_status_t duer_coap_exec(duer_coap_handler hdlr, duer_u32_t timestamp);
/*
* Release the CoAP context
*
* @Param hdlr, in, the CoAP context
* @Return duer_status_t, the result
*/
DUER_INT duer_status_t duer_coap_release(duer_coap_handler coap);
/*
* Set read timeout
*
* @Param hdlr, in, the CoAP context
* @Param timeout, in, the timeout value by milliseconds
* @Return duer_bool, if match return DUER_TRUE, else return DUER_FALSE
*/
DUER_INT duer_status_t duer_coap_set_read_timeout(duer_coap_handler coap, duer_u32_t timeout);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_COAP_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_coap.h
|
C
|
apache-2.0
| 6,170
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
// Author: Su Hao (suhao@baidu.com)
//
// Description: CoAP common definitions
#ifndef LIBDUER_DEVICE_FRAMEWORK_INCLUDE_LIGHTDUER_COAP_DEFS_H
#define LIBDUER_DEVICE_FRAMEWORK_INCLUDE_LIGHTDUER_COAP_DEFS_H
#include "lightduer_types.h"
#include "lightduer_network_defs.h"
#include "lightduer_net_transport.h"
/*
* The message codes.
*/
typedef enum {
DUER_MSG_EMPTY_MESSAGE = 0,
// Request message code
DUER_MSG_REQ_GET = 1,
DUER_MSG_REQ_POST = 2,
DUER_MSG_REQ_PUT = 3,
DUER_MSG_REQ_DELETE = 4,
// Response message code
DUER_MSG_RSP_CREATED = 65, // 2.01
DUER_MSG_RSP_DELETED = 66, // 2.02
DUER_MSG_RSP_VALID = 67, // 2.03
DUER_MSG_RSP_CHANGED = 68, // 2.04
DUER_MSG_RSP_CONTENT = 69, // 2.05
DUER_MSG_RSP_CONTINUE = 95, // 2.31
DUER_MSG_RSP_BAD_REQUEST = 128, // 4.00
DUER_MSG_RSP_UNAUTHORIZED = 129, // 4.01
DUER_MSG_RSP_BAD_OPTION = 130, // 4.02
DUER_MSG_RSP_FORBIDDEN = 131, // 4.03
DUER_MSG_RSP_NOT_FOUND = 132, // 4.04
DUER_MSG_RSP_METHOD_NOT_ALLOWED = 133, // 4.05
DUER_MSG_RSP_NOT_ACCEPTABLE = 134, // 4.06
DUER_MSG_RSP_REQUEST_ENTITY_INCOMPLETE = 136, // 4.08
DUER_MSG_RSP_PRECONDITION_FAILED = 140, // 4.12
DUER_MSG_RSP_REQUEST_ENTITY_TOO_LARGE = 141, // 4.13
DUER_MSG_RSP_UNSUPPORTED_CONTENT_FORMAT = 143, // 4.15
DUER_MSG_RSP_INTERNAL_SERVER_ERROR = 160, // 5.00
DUER_MSG_RSP_NOT_IMPLEMENTED = 161, // 5.01
DUER_MSG_RSP_BAD_GATEWAY = 162, // 5.02
DUER_MSG_RSP_SERVICE_UNAVAILABLE = 163, // 5.03
DUER_MSG_RSP_GATEWAY_TIMEOUT = 164, // 5.04
DUER_MSG_RSP_PROXYING_NOT_SUPPORTED = 165, // 5.05
DUER_MSG_RSP_INVALID = 0xFF, // used in seperate response
} duer_msg_code_e;
/**
* CoAP Message type, used in CoAP Header
*/
typedef enum {
DUER_MSG_TYPE_CONFIRMABLE = 0x00, // Reliable Request messages
DUER_MSG_TYPE_NON_CONFIRMABLE = 0x10, // Non-reliable Request and Response messages
DUER_MSG_TYPE_ACKNOWLEDGEMENT = 0x20, // Response to a Confirmable Request
DUER_MSG_TYPE_RESET = 0x30 // Answer a Bad Request
} duer_msg_type_e;
/*
* The resource operation permission
*/
typedef enum {
DUER_RES_OP_GET = 0x01, // Get operation allowed
DUER_RES_OP_PUT = 0x02, // Put operation allowed
DUER_RES_OP_POST = 0x04, // Post operation allowed
DUER_RES_OP_DELETE = 0x08 // Delete operation allowed
} duer_resource_operation_e;
/*
* The resource mode
*/
typedef enum {
DUER_RES_MODE_STATIC, // Static resources have some value that doesn't change
DUER_RES_MODE_DYNAMIC, // Dynamic resources are handled in application
} duer_resource_mode_e;
typedef struct _duer_context_s duer_context_t;
typedef int (*duer_report_callback)(duer_context_t *);
struct _duer_context_s {
void * _param;
int _status;
duer_report_callback _on_report_start;
duer_report_callback _on_report_finish;
};
/*
* The message definition
*/
typedef struct _duer_message_s {
duer_u16_t token_len;
duer_u8_t msg_type;
duer_u8_t msg_code;
duer_u16_t msg_id;
duer_u16_t path_len;
duer_u16_t query_len;
duer_u16_t payload_len;
duer_u8_t* token;
duer_u8_t* path;
duer_u8_t* query;
duer_u8_t* payload;
duer_u32_t create_timestamp;
duer_context_t *context;
} duer_msg_t;
/*
* The status notification to user.
*/
typedef duer_status_t (*duer_notify_f)(duer_context ctx,
duer_msg_t* msg,
duer_addr_t* addr);
/*
* The transmit coap data callback.
*/
typedef duer_status_t (*duer_transmit_f)(duer_trans_handler hdlr, const void *data, duer_size_t size, duer_addr_t *addr);
/*
* The resource for user
*/
typedef struct _duer_resource_s {
duer_u8_t mode: 2; // the resource mode, SEE in ${link duer_resource_mode_e}
duer_u8_t allowed: 6; // operation permission, SEE in ${link duer_resource_operation_e}
char* path; // the resource path identify
union {
duer_notify_f f_res; // dynamic resource handle function, NULL if static
struct {
void* data; // static resource value data, NULL if dynamic
duer_size_t size; // static resource size
} s_res;
} res;
} duer_res_t;
#define DUER_MESSAGE_IS_RESPONSE(_code) ((_code) > DUER_MSG_REQ_DELETE)
#endif // LIBDUER_DEVICE_FRAMEWORK_INCLUDE_LIGHTDUER_COAP_DEFS_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_coap_defs.h
|
C
|
apache-2.0
| 5,723
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
// Author: Su Hao (suhao@baidu.com)
//
// Description: The CoAP endpoint definitions.
#ifndef BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_COAP_EP_H
#define BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_COAP_EP_H
#include "lightduer_lib.h"
#define LIFETIME_MAX_LEN (10)
#ifdef __cplusplus
extern "C" {
#endif
/**
* Endpoint registration parameters
*/
typedef struct _baidu_ca_coap_endpoint_s {
char* name_ptr; // Endpoint name
duer_size_t name_len;
char* type_ptr; // Endpoint type
duer_size_t type_len;
char* lifetime_ptr; // Endpoint lifetime in seconds. eg. "1200" = 1200 seconds
duer_size_t lifetime_len;
duer_addr_t* address; // Endpoint address to be accessed by the server, optional, default NULL
} duer_coap_ep_t, *duer_coap_ep_ptr;
/*
* Create the endpoint.
*
* @Param hdlr, in, the global context for baidu ca
* @Param name, in, the endpoint name
* @Param type, in, the endpoint type
* @Param lifetime, in, the lifetime of the endpoint
* @Param addr, in, the endpoint address to be accessed by the server, optional, default NULL
* @Return duer_coap_ep_ptr, the endpoint context pointer
*/
DUER_INT duer_coap_ep_ptr duer_coap_ep_create(const char* name,
const char* type,
duer_u32_t lifetime,
const duer_addr_t* addr);
/*
* Destroy the endpoint that created by ${link duer_coap_ep_create}.
*
* @Param hdlr, in, the global context for baidu ca
* @Param ptr, in, the endpoint context pointer
* @Return duer_status_t, the operation result
*/
DUER_INT duer_status_t duer_coap_ep_destroy(duer_coap_ep_ptr ptr);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_COAP_EP_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_coap_ep.h
|
C
|
apache-2.0
| 2,526
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
// Author: Su Hao (suhao@baidu.com)
//
// Description: Adapter for mbed-trace.
#ifndef BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_MBEDTRACE_H
#define BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_MBEDTRACE_H
#include "lightduer_types.h"
/*
* Enable the mbed trace
*/
DUER_INT void duer_coap_trace_enable(void);
/*
* Disable the mbed trace
*/
DUER_INT void duer_coap_trace_disable(void);
#endif // BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_MBEDTRACE_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_coap_trace.h
|
C
|
apache-2.0
| 1,116
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/**
* File: lightduer_connagent.h
* Auth: Su Hao (suhao@baidu.com)
* Desc: Light duer APIS.
*/
#ifndef BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_H
#define BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_H
#include "lightduer_types.h"
#include "lightduer_network_defs.h"
#include "lightduer_coap_defs.h"
#include "baidu_json.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum _duer_event_id_enum {
DUER_EVENT_STARTED,
DUER_EVENT_STOPPED
} duer_event_id;
typedef struct _duer_event_data_s {
int _event; //< Event id, see in @{link duer_event_id}
int _code; //< the return code
void * _object; //< The return content
} duer_event_t;
/**
* The action result callback
*/
typedef void (*duer_event_callback)(duer_event_t *);
/**
* Initialize the environment.
*/
void duer_initialize(void);
/**
* Set all actions event callback
*
* @param callback, the event change result callback.
*/
void duer_set_event_callback(duer_event_callback callback);
/**
* Start the LightDuer egnine.
*
* @param data, the configuration data
* @param size, the data size
* @return int, the start result, success return DUER_OK, failed return DUER_ERR_FAILED.
*/
int duer_start(const void *data, size_t size);
/**
* Add route resources for Server requested, this should be called after CA started.
*
* @param msg, const duer_res_t *, the resources list
* @param length, size_t, the resources length
* @return int, success return DUER_OK, failed return DUER_ERR_FAILED.
*/
int duer_add_resources(const duer_res_t *res, size_t length);
/**
* Call it when data is ready.
*
* @return int, the start result, success return DUER_OK, failed return DUER_ERR_FAILED.
*/
int duer_data_available(void);
/**
* Send data to server.
*
* @param data, const baidu_json *, the data point values.
* @return int, the report data result, success return DUER_OK, failed return DUER_ERR_FAILED.
*/
int duer_data_report(const baidu_json *data);
/**
* Send data to server.
*
* @param data, const baidu_json *, the data point values.
* @return int, the report data result, success return DUER_OK, failed return DUER_ERR_FAILED.
*/
int duer_data_report_async(duer_context_t *context, const baidu_json *data);
/**
* Response the request from Origin Server.
*
* @param msg, const duer_msg_t *, the request message structure.
* @param msg_code, int, the message code, see in @{link duer_msg_code_e}.
* @param data, const void *, the payload data.
* @param size, size_t, the payload size.
* @return int, the send response result, success return DUER_OK, failed return DUER_ERR_FAILED.
* @Note: if response ACK without response data,
* set msg_code = DUER_MSG_EMPTY_MESSAGE, and data = NULL, size = 0
*/
int duer_response(const duer_msg_t *msg, int msg_code, const void *data, duer_size_t size);
/**
* the seperate response message for an request
* @param token, const char* , the token got from the corresponding request
* @param token_len, duer_size_t, the length of the token
* @param msg_code, int, the message code, see in @{link duer_msg_code_e}
* @param data, const baidu_json *, the payload of the message
* @return int, the send response result, success return DUER_OK, failed return DUER_ERR_FAILED.
*/
int duer_seperate_response(const char *token,
duer_size_t token_len,
int msg_code,
const baidu_json *data);
/**
* Stop the LightDuer engine.
*
* @return int, the stop result, success return DUER_OK, failed return DUER_ERR_FAILED.
*/
int duer_stop(void);
/**
* Stop the LightDuer engine.
* @param reason, int, the stop code which indicate the stop reason
* @return int, the stop result, success return DUER_OK, failed return DUER_ERR_FAILED.
*/
int duer_stop_with_reason(int reason);
/**
* clear the queue cache data.
* @param timestamp, clean the message with create_timestamp before timestamp
*/
int duer_clear_data(duer_u32_t timestamp);
/**
* the callback to handle coap response message.
*/
void duer_coap_response_callback(duer_context ctx,
duer_msg_t* msg,
duer_addr_t* addr);
/**
* Finalize the environment.
*/
int duer_finalize(void);
#ifdef __cplusplus
}
#endif
#endif/*BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_H*/
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_connagent.h
|
C
|
apache-2.0
| 4,967
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/**
* File: lightduer_data_cache.h
* Auth: Su Hao (suhao@baidu.com)
* Desc: Light duer stored the send data.
*/
#ifndef BAIDU_DUER_LIGHTDUER_COMMON_LIGHTDUER_DATA_CACHE_H
#define BAIDU_DUER_LIGHTDUER_COMMON_LIGHTDUER_DATA_CACHE_H
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _duer_transmit_data_s {
void * data;
size_t size;
} duer_dcache_item;
void duer_dcache_initialize(void);
/**
* @param data, the memory address
* @param size, the size of memory
* @param need_copy, indicate whether the memroy @data need another copy
* DUER_FALSE means the invoker transfer the memory ownership,
* DUER_TRUE is default value, which means invoker still own the memory,
* so invoker have the responsibility to release it when no long used.
*/
duer_status_t duer_dcache_push(const void *data, size_t size, duer_bool need_copy);
duer_dcache_item *duer_dcache_top(void);
void duer_dcache_pop(void);
void *duer_dcache_create_iterator(void);
void *duer_dcache_get_next(void *iterator);
duer_dcache_item *duer_dcache_get_data(void *iterator);
size_t duer_dcache_length(void);
void duer_dcache_clear(void);
void duer_dcache_finalize(void);
#ifdef __cplusplus
}
#endif
#endif/*BAIDU_DUER_LIGHTDUER_COMMON_LIGHTDUER_DATA_CACHE_H*/
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_data_cache.h
|
C
|
apache-2.0
| 1,925
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/**
* File: lightduer_dcs.h
* Auth: Gang Chen (chengang12@baidu.com)
* Desc: Light duer DCS APIS.
*/
#ifndef BAIDU_DUER_LIGHTDUER_DCS_H
#define BAIDU_DUER_LIGHTDUER_DCS_H
#include "baidu_json.h"
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
DCS_PLAY_CMD,
DCS_PAUSE_CMD,
DCS_PREVIOUS_CMD,
DCS_NEXT_CMD,
DCS_PLAY_CONTROL_EVENT_NUMBER,
} duer_dcs_play_control_cmd_t;
typedef enum {
DCS_MEDIA_ERROR_UNKNOWN, // unknown error
// server invalid response, such as bad request, forbidden, not found .etc
DCS_MEDIA_ERROR_INVALID_REQUEST,
DCS_MEDIA_ERROR_SERVICE_UNAVAILABLE, // device cannot connect to server
DCS_MEDIA_ERROR_INTERNAL_SERVER_ERROR, // server failed to handle device's request
DCS_MEDIA_ERROR_INTERNAL_DEVICE_ERROR, // device internal error
} duer_dcs_audio_error_t;
typedef enum {
DCS_RECOMMEND_POWER_ON,
DCS_RECOMMEND_OUT_OF_BOX,
DCS_RECOMMEND_TIME_NUMBER,
} duer_dcs_recommend_time_t;
typedef struct {
const char *url;
int offset;
const char *audio_item_id;
} duer_dcs_audio_info_t;
enum duer_dcs_device_capability {
DCS_TTS_HTTPS_PROTOCAL_SUPPORTED = 0x01, // the device support https protocal to playing tts
DCS_WECHAT_SUPPORTED = 0x02, // the device support wechat
};
/**
* Internal used private namespace.
*/
extern const char *DCS_PRIVATE_NAMESPACE;
/**
* Initialize the dcs framework.
*
* @return none.
*/
void duer_dcs_framework_init(void);
/**
* Uninitialize the DCS module.
*
* @return none.
*/
void duer_dcs_uninitialize(void);
/**
* DESC:
* Initialize dcs voice input interface.
*
* PARAM: none
*
* @RETURN: none
*/
void duer_dcs_voice_input_init(void);
/**
* DESC:
* Notify DCS when recorder start to record.
*
* PARAM: none
*
* @RETURN: 0 when success, negative when fail.
*/
int duer_dcs_on_listen_started(void);
/**
* DESC:
* There is no VAD in translate scene,
* hence developer needs to call this function to notify DCS framework after recording finished.
*
* PARAM: none
*
* @RETURN: 0 when success, negative when fail.
*/
int duer_dcs_on_listen_stopped(void);
/**
* DESC:
* Developer needs to implement this interface to start recording.
*
* PARAM: none
*
* @RETURN: none.
*/
void duer_dcs_listen_handler(void);
/**
* DESC:
* Developer needs to implement this interface to stop recording.
*
* PARAM: none
*
* @RETURN: none.
*/
void duer_dcs_stop_listen_handler(void);
/**
* DESC:
* Initialize dcs voice output interface
*
* PARAM: none
*
* @RETURN: none
*/
void duer_dcs_voice_output_init(void);
/**
* DESC:
*
* It should be called when speech finished, used to notify DCS level.
*
* PARAM: none
*
* @RETURN: none
*/
void duer_dcs_speech_on_finished(void);
/**
* DESC:
* Developer needs to implement this interface to play speech.
*
* PARAM:
* @param[in] url: the url of the speech need to play
*
* @RETURN: none.
*/
void duer_dcs_speak_handler(const char *url);
/**
* DESC:
* Developer needs to implement this interface to stop speech.
*
* PARAM:
* @param: none
*
* @RETURN: none.
*/
void duer_dcs_stop_speak_handler(void);
/**
* DESC:
* Initialize dcs speaker controler interface to enable volume control function.
*
* PARAM: none
*
* @RETURN: none
*/
void duer_dcs_speaker_control_init(void);
/**
* DESC:
* Notify DCS when volume changed
*
* PARAM: none
*
* @RETURN: 0 when success, negative when fail.
*/
int duer_dcs_on_volume_changed(void);
/**
* DESC:
* Notify DCS when mute state changed.
*
* PARAM: none
*
* @RETURN: 0 when success, negative when fail.
*/
int duer_dcs_on_mute(void);
/**
* DESC:
* Developer needs to implement this interface, it is used to get volume state.
*
* @param[out] volume: current volume value.
* @param[out] is_mute: current mute state.
*
* @RETURN: none.
*/
void duer_dcs_get_speaker_state(int *volume, duer_bool *is_mute);
/**
* DESC:
* Developer needs to implement this interface to set volume.
*
* PARAM:
* @param[in] volume: the value of the volume need to set
*
* @RETURN: none.
*/
void duer_dcs_volume_set_handler(int volume);
/**
* DESC:
* Developer needs to implement this interface to adjust volume.
*
* PARAM:
* @param[in] volume: the value need to adjusted.
*
* @RETURN: none.
*/
void duer_dcs_volume_adjust_handler(int volume);
/**
* DESC:
* Developer needs to implement this interface to change mute state.
*
* PARAM:
* @param[in] is_mute: set/discard mute.
*
* @RETURN: none.
*/
void duer_dcs_mute_handler(duer_bool is_mute);
/**
* DESC:
* Initialize dcs audio player interface.
*
* PARAM: none
*
* @RETURN: none
*/
void duer_dcs_audio_player_init(void);
/**
* DESC:
* User can also use this API to subscribe FM.
*
* PARAM[in] url: the url identify the FM.
*
* @RETURN: 0 when success, negative when fail.
*/
int duer_dcs_on_link_clicked(const char *url);
/**
* DESC:
* Notify DCS when an audio is finished.
*
* PARAM: none
*
* @RETURN: none.
*/
void duer_dcs_audio_on_finished(void);
/**
* DESC:
* Notify DCS when failed to play audio.
*
* PARAM[in] type: the error type
* PARAM[in] msg: the error message
*
* @RETURN: 0 when success, negative when fail.
*/
int duer_dcs_audio_play_failed(duer_dcs_audio_error_t type, const char *msg);
/**
* DESC:
* Report StreamMetadataExtracted event if metadata is found in the audio.
*
* PARAM[in] metadata: the metadata need to report, its layout is:
* "metadata": {
* "{{STRING}}": "{{STRING}}",
* "{{STRING}}": {{BOOLEAN}}
* "{{STRING}}": "{{STRING NUMBER}}"
* ...
* }
*
* @RETURN: 0 when success, negative when fail.
*/
int duer_dcs_audio_report_metadata(baidu_json *metadata);
/**
* DESC:
* Notify DCS when audio is stuttered.
*
* PARAM[in] is_stuttuered: DUER_TRUE when stutter started(download speed lower than play speed),
* DUER_FALSE when stutter finished(the audio resume play).
*/
int duer_dcs_audio_on_stuttered(duer_bool is_stuttered);
/**
* DESC:
* Developer needs to implement this interface to play audio.
*
* PARAM:
* @param[in] audio_info: the info of the audio need to play
*
* @RETURN: none.
*/
void duer_dcs_audio_play_handler(const duer_dcs_audio_info_t *audio_info);
/**
* DESC:
* Developer needs to implement this interface to stop audio player.
*
* PARAM: none
*
* @RETURN: none.
*/
void duer_dcs_audio_stop_handler(void);
/**
* DESC:
* Notify DCS when an audio is stopped not by DCS API.
*
* PARAM: none
*
* @RETURN: none.
*/
void duer_dcs_audio_on_stopped(void);
/**
* DESC:
* Developer needs to implement this interface to resume audio play.
*
* PARAM:
* @param[in] audio_info: the info of the audio need to resumed
*
* @RETURN: none.
*/
void duer_dcs_audio_resume_handler(const duer_dcs_audio_info_t *audio_info);
/**
* DESC:
* Developer needs to implement this interface to pause audio play.
*
* PARAM: none
*
* @RETURN: none.
*/
void duer_dcs_audio_pause_handler(void);
/**
* DESC:
* Developer needs to implement this interface, it's used to get the audio play progress.
*
* PARAM: none
*
* @RETURN: the play position of the audio.
*/
int duer_dcs_audio_get_play_progress(void);
/**
* DESC:
* Realize play control(play, pause, next/previous audio) by send command to DCS.
*
* PARAM[in] cmd: command type.
*
* @RETURN: 0 when success, negative when fail.
*/
int duer_dcs_send_play_control_cmd(duer_dcs_play_control_cmd_t cmd);
/**
* DESC:
* Report current state after device boot.
*
* PARAM: none
*
* @RETURN: 0 if succuss, negative if failed.
*/
int duer_dcs_sync_state(void);
/**
* DESC:
* Sending an "Exited" event to close the multi dialogue.
*
* @RETURN: 0 if succuss, negative if failed.
*/
int duer_dcs_close_multi_dialog(void);
/**
* DESC:
* Initialize dcs screen interface.
*
* PARAM: none
*
* @RETURN: none
*/
void duer_dcs_screen_init(void);
/**
* DESC:
* Developer needs to implement this interface to get the ASR result.
*
* PARAM[in] text: the ASR text result.
* PARAM[in] type: "INTERMEDIATE" or "FINAL".
*
* @RETURN: DUER_OK if success,
* DUER_MSG_RSP_BAD_REQUEST if the payload is invalid,
* DUER_ERR_FAILED if other error happened.
*/
duer_status_t duer_dcs_input_text_handler(const char *text, const char *type);
/**
* DESC:
* Developer needs to implement this interface to get render card.
*
* PARAM[in] payload: the information of the render card, please reference the DCS document.
*
* @RETURN: DUER_OK if success,
* DUER_MSG_RSP_BAD_REQUEST if the payload is invalid,
* DUER_ERR_FAILED if other error happened.
*/
duer_status_t duer_dcs_render_card_handler(baidu_json *payload);
/**
* DESC:
* Developer needs to implement this interface to open/close bluetooth.
*
* PARAM[in] is_switch: open bluetooth if is_switch is DUER_TRUE, otherwise close bluetooth.
* PARAM[in] target: Reserved parameter, currently its value is "default".
*
* @RETURN: None
*/
void duer_dcs_bluetooth_set_handler(duer_bool is_switch, const char *target);
/**
* DESC:
* Developer needs to implement this interface to connect/disconnect bluetooth to device.
*
* PARAM[in] is_connect: connect bluetooth if is_connect is DUER_TRUE, otherwise disconnect bluetooth.
* PARAM[in] target: Reserved parameter, currently its value is "default".
*
* @RETURN: None
*/
void duer_dcs_bluetooth_connect_handler(duer_bool is_connect, const char *target);
/**
* DESC:
* Initialize device control interface, such as control the bluetooth.
*
* PARAM: none
*
* @RETURN: none
*/
void duer_dcs_device_control_init(void);
/**
* DESC:
* Used to declare the device capability, such as: whether https or wechat are supported.
* It is unnecessary if the device don't have the capability defined in duer_dcs_device_capability.
* @PARAM[in] capability: the device capability, it's the or value of the member in
* duer_dcs_device_capability.
* @RETURN: DUER_OK if success, negative if failed.
*/
duer_status_t duer_dcs_capability_declare(duer_u32_t capability);
/**
* DESC:
* Sending RecommendationRequested event, and DCS server will recommend a resource to device.
* Currently, only the scene of "POWER_ON" is supported, that means this function should be called
* only one time(when device power_on).
*
* @PARAM[in] type: type of the scene.
* @RETURN: 0 if succuss, negative if failed.
*/
int duer_dcs_recommend_request(duer_dcs_recommend_time_t time);
/**
* DESC:
* Similar to duer_dcs_on_listen_started, except not create new dialog id, but get current one.
*
* PARAM: none
*
* @RETURN: 0 when success, negative when fail.
*/
int duer_dcs_on_listen_started_with_current_dialogid(void);
/**
* DESC:
* Developer needs to implement this interface to pause local player.
*
* PARAM: none
*
* @RETURN: None
*/
void duer_dcs_local_player_pause_handler(void);
/**
* DESC:
* Developer needs to implement this interface to resume local player.
*
* PARAM: none
*
* @RETURN: None
*/
void duer_dcs_local_player_resume_handler(void);
/**
* DESC:
* Developer needs to implement this interface to stop local player.
*
* PARAM: none
*
* @RETURN: None
*/
void duer_dcs_local_player_stop_handler(void);
/**
* DESC:
* Notify DCS module when local player paused.
*
* PARAM: none
*
* @RETURN: None
*/
void duer_dcs_local_player_on_paused(void);
/**
* DESC:
* Notify DCS module when local player playing.
*
* PARAM: none
*
* @RETURN: None
*/
void duer_dcs_local_player_on_played(void);
/**
* DESC:
* Notify DCS module when local player stopped.
*
* PARAM: none
*
* @RETURN: None
*/
void duer_dcs_local_player_on_stopped(void);
/**
* DESC:
* Get the client context.
*
* PARAM: none
*
* @RETURN: NULL if failed, pointer point to the client context if success.
*/
baidu_json *duer_dcs_get_client_context(void);
#ifdef __cplusplus
}
#endif
#endif/*BAIDU_DUER_LIGHTDUER_DCS_H*/
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_dcs.h
|
C
|
apache-2.0
| 12,775
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/**
* File: lightduer_dcs_alert.h
* Auth: Gang Chen (chengang12@baidu.com)
* Desc: Light duer alert APIs.
*/
#ifndef BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_DCS_ALERT_H
#define BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_DCS_ALERT_H
#include "baidu_json.h"
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
SET_ALERT_SUCCESS,
SET_ALERT_FAIL,
DELETE_ALERT_SUCCESS,
DELETE_ALERT_FAIL,
ALERT_START,
ALERT_STOP,
} duer_dcs_alert_event_type;
typedef struct {
char *type; // "ALARM" or "TIMER"
char *time; // the time of the alert, ISO 8601 format.
char *token; // the alert token, it is the unique identification of an alert
} duer_dcs_alert_info_type;
/**
* DESC:
* Init alert.
*
* PARAM: none
*
* @RETURN: none.
*/
void duer_dcs_alert_init(void);
/**
* DESC:
* Report alert event
*
* PARAM:
* @param[in] token: the token of the alert.
* @param[in] type: event type, refer to duer_alert_event_type.
*
* @return: 0 when success, negative value when failed.
*/
int duer_dcs_report_alert_event(const char *token, duer_dcs_alert_event_type type);
/**
* DESC:
* Developer needs to implement this interface to set alert.
*
* PARAM:
* @param[in] directive: the set alert directive.
*
* @RETURN: DUER_OK if success,
* DUER_MSG_RSP_BAD_REQUEST if the directive is invalid,
* DUER_ERR_FAILED if other error happened.
*/
duer_status_t duer_dcs_tone_alert_set_handler(const baidu_json *directive);
/**
* DESC:
* Developer needs to implement this interface to delete alert.
*
* PARAM:
* @param[in] token: the token of the alert need to delete.
*
* @RETURN: none.
*/
void duer_dcs_alert_delete_handler(const char *token);
/**
* DESC:
* Add a alert info to the alert list, it should be used in duer_dcs_get_all_alert callback.
* This API could be used in duer_dcs_get_all_alert, so DCS can get all alerts info.
*
* PARAM:
* @param[out] alert_list: used to store the alert info.
* @param[in] alert_info: the info about the alert, such as token, schedule time.
* @param[in] is_active: whether this alert is sounding.
*
* @return: 0 when success, negative value when failed.
*/
int duer_insert_alert_list(baidu_json *alert_list,
duer_dcs_alert_info_type *alert_info,
duer_bool is_active);
/**
* DESC:
* It's used to get all alert info by DCS.
* Developer can implement this interface by call duer_dcs_report_alert to report all alert info.
*
* PARAM:
* @param[out] alert_list: a json array used to store all alert info.
*
* @RETURN: none.
*/
void duer_dcs_get_all_alert(baidu_json *alert_list);
#ifdef __cplusplus
}
#endif
#endif/*BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_DCS_ALERT_H*/
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_dcs_alert.h
|
C
|
apache-2.0
| 3,395
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/**
* File: lightduer_dcs_infrared_control.h
* Auth: Chang Li (changli@baidu.com)
* Desc: Light duer DCS APIS for infrared control.
*/
#ifndef BAIDU_DUER_LIGHTDUER_DCS_INFRARED_CONTROL_H
#define BAIDU_DUER_LIGHTDUER_DCS_INFRARED_CONTROL_H
#include "lightduer_types.h"
#include <stdint.h>
typedef enum {
DCS_INFRARED_SEND_COMPLETED,
DCS_INFRARED_SEND_FAILED,
DCS_INFRARED_RECEIVED,
DCS_INFRARED_RECEIVE_TIMEOUT
} duer_infrared_event_t;
typedef struct _ray_item_t {
struct _ray_item_t *next;
uint32_t carrier_freq;
uint32_t interval_ms;
uint16_t pattern_cnt;
uint16_t pattern[];
} duer_ray_item_t;
typedef struct {
duer_ray_item_t *head;
} duer_ray_item_list_t;
/**
* DESC:
* Destroy the ray item list and reclaim memory.
*
* PARAM[in] list: Infrared ray data.
*
* @RETURN: None
*/
void duer_destroy_ray_items(duer_ray_item_list_t *list);
/**
* DESC:
* Developer needs to implement this interface to send infrared data.
* Note, it's asynchronized.
*
* PARAM[in] list: Infrared ray data. Note: need to be reclaimed after use.
*
* @RETURN: None
*/
void duer_dcs_infrared_send_handler(duer_ray_item_list_t *list);
/**
* DESC:
* Developer needs to implement this interface to receive infrared data.
*
* PARAM[in] timeout_ms: the time device wait for the infrared data.
*
* @RETURN: None
*/
void duer_dcs_infrared_receive_handler(long timeout_ms);
/**
* DESC:
* report infrared event to cloud.
*
* PARAM[in] event: infrared event.
*
* PARAM[in] array: pattern array for DCS_INFRARED_RECEIVED event.
*
* PARAM[in] cnt: pattern count for DCS_INFRARED_RECEIVED event.
*
* @RETURN: DUER_OK for sucess, others for failure.
*/
int duer_dcs_infrared_control_report(duer_infrared_event_t event, uint16_t *array, int cnt);
/**
* DESC:
* Initialize infrared control interface.
*
* PARAM: none
*
* @RETURN: none
*/
void duer_dcs_infrared_control_init(void);
#endif // BAIDU_DUER_LIGHTDUER_DCS_INFRARED_CONTROL_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_dcs_infrared_control.h
|
C
|
apache-2.0
| 2,605
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/**
* File: lightduer_dcs_local.h
* Auth: Gang Chen (chengang12@baidu.com)
* Desc: Provide some functions for dcs module locally.
*/
#ifndef BAIDU_DUER_LIGHTDUER_DCS_LOCAL_H
#define BAIDU_DUER_LIGHTDUER_DCS_LOCAL_H
#include <stdlib.h>
#include <stdint.h>
#include "baidu_json.h"
#include "lightduer_types.h"
#include "lightduer_log.h"
#include "lightduer_dcs_router.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
DCS_DIALOG_FINISHED,
DCS_RECORD_STARTED,
DCS_SPEECH_NEED_PLAY,
DCS_SPEECH_FINISHED,
DCS_AUDIO_NEED_PLAY,
DCS_AUDIO_FINISHED,
DCS_AUDIO_STOPPED,
DCS_NEED_OPEN_MIC,
DCS_ALERT_STARTED,
DCS_ALERT_FINISHED,
} duer_dcs_channel_switch_event_t;
#ifdef DCS_CRITICAL_LOCK_DEBUG
#define DUER_DCS_CRITICAL_ENTER() \
do {\
DUER_LOGI("%s entry", __FUNCTION__);\
duer_dcs_critical_enter_internal();\
DUER_LOGI("in");\
} while (0)
#define DUER_DCS_CRITICAL_EXIT() \
do {\
DUER_LOGI("%s exit", __FUNCTION__);\
duer_dcs_critical_exit_internal();\
DUER_LOGI("out");\
} while (0)
#else
#define DUER_DCS_CRITICAL_ENTER() duer_dcs_critical_enter_internal()
#define DUER_DCS_CRITICAL_EXIT() duer_dcs_critical_exit_internal()
#endif
// resouce path
extern const char *DCS_DUER_DIRECTIVE_PATH;
extern const char *DCS_DUER_PRIVATE_PATH;
extern const char *DCS_IOTCLOUD_DIRECTIVE_PATH;
extern const char *DCS_IOTCLOUD_EVENT_PATH;
// namespace
extern const char *DCS_AUDIO_PLAYER_NAMESPACE;
extern const char *DCS_VOICE_OUTPUT_NAMESPACE;
extern const char *DCS_VOICE_INPUT_NAMESPACE;
extern const char *DCS_SCREEN_NAMESPACE;
extern const char *DCS_SCREEN_EXTENDED_CARD_NAMESPACE;
extern const char *DCS_IOT_CLOUD_SYSTEM_NAMESPACE;
extern const char *DCS_PLAYBACK_CONTROL_NAMESPACE;
extern const char *DCS_RECOMMEND_NAMESPACE;
// message keys
extern const char *DCS_DIRECTIVE_KEY;
extern const char *DCS_CLIENT_CONTEXT_KEY;
extern const char *DCS_EVENT_KEY;
extern const char *DCS_HEADER_KEY;
extern const char *DCS_PAYLOAD_KEY;
// header keys
extern const char *DCS_NAMESPACE_KEY;
extern const char *DCS_NAME_KEY;
extern const char *DCS_MESSAGE_ID_KEY;
extern const char *DCS_DIALOG_REQUEST_ID_KEY;
// payload keys
extern const char *DCS_TOKEN_KEY;
extern const char *DCS_TYPE_KEY;
extern const char *DCS_CODE_KEY;
extern const char *DCS_VOLUME_KEY;
extern const char *DCS_URL_KEY;
extern const char *DCS_ACTIVE_ALERTS_KEY;
extern const char *DCS_TARGET_KEY;
extern const char *DCS_SCHEDULED_TIME_KEY;
extern const char *DCS_PLAYER_ACTIVITY_KEY;
extern const char *DCS_ALL_ALERTS_KEY;
extern const char *DCS_ERROR_KEY;
extern const char *DCS_MUTE_KEY;
extern const char *DCS_INITIATOR_KEY;
extern const char *DCS_AUDIO_ITEM_KEY;
extern const char *DCS_CLEAR_BEHAVIOR_KEY;
extern const char *DCS_PLAY_BEHAVIOR_KEY;
extern const char *DCS_INACTIVE_TIME_IN_SECONDS_KEY;
extern const char *DCS_OFFSET_IN_MILLISECONDS_KEY;
extern const char *DCS_TIMEOUT_IN_MILLISECONDS_KEY;
extern const char *DCS_METADATA_KEY;
extern const char *DCS_TEXT_KEY;
extern const char *DCS_CONNECTION_SWITCH_KEY;
extern const char *DCS_DESCRIPTION_KEY;
extern const char *DCS_BLUETOOTH_KEY;
extern const char *DCS_MUTED_KEY;
extern const char *DCS_UNPARSED_DIRECTIVE_KEY;
extern const char *DCS_FORMAT_KEY;
extern const char *DCS_MESSAGE_KEY;
extern const char *DCS_QUERY_KEY;
extern const char *DCS_TIME_OF_RECOMMEND;
extern const char *DCS_STUTTER_DURATION;
extern const char *DCS_PREVIOUS_DIALOG_ID_KEY;
extern const char *DCS_ACTIVE_DIALOG_ID_KEY;
// directive name
extern const char *DCS_SPEAK_NAME;
extern const char *DCS_PLAY_NAME;
extern const char *DCS_STOP_NAME;
extern const char *DCS_CLEAR_QUEUE_NAME;
extern const char *DCS_LISTEN_NAME;
extern const char *DCS_GET_STATUS_NAME;
extern const char *DCS_STOP_SPEAK_NAME;
extern const char *DCS_SET_BLUETOOTH_NAME;
extern const char *DCS_RENDER_CARD_NAME;
extern const char *DCS_SET_ALERT_NAME;
extern const char *DCS_STOP_LISTEN_NAME;
extern const char *DCS_SET_BLUETOOTH_CONNECTION_NAME;
extern const char *DCS_SET_MUTE_NAME;
extern const char *DCS_DELETE_ALERT_NAME;
extern const char *DCS_RENDER_VOICE_INPUT_TEXT_NAME;
extern const char *DCS_SET_VOLUME_NAME;
extern const char *DCS_ADJUST_VOLUME_NAME;
extern const char *DCS_TEXT_INPUT_NAME;
extern const char *DCS_RENDER_WEATHER;
extern const char *DCS_RENDER_PLAYER_INFO;
extern const char *DCS_RENDER_AUDIO_LIST;
extern const char *DCS_RENDER_ALBUM_LIST;
extern const char *DCS_SET_ACTIVE_DIALOG;
// internal directive.
extern const char *DCS_DIALOGUE_FINISHED_NAME;
extern const char *DCS_THROW_EXCEPTION_NAME;
extern const char *DCS_RESET_USER_INACTIVITY_NAME;
extern const char *DCS_NOP_NAME;
extern const char *DCS_IOT_CLOUD_CONTEXT;
// event name
extern const char *DCS_SYNCHRONIZE_STATE_NAME;
extern const char *DCS_EXCEPTION_ENCOUNTERED_NAME;
extern const char *DCS_VOLUME_STATE_NAME;
extern const char *DCS_LISTEN_STARTED_NAME;
extern const char *DCS_SPEECH_STARTED_NAME;
extern const char *DCS_ALERTS_STATE_NAME;
extern const char *DCS_LISTEN_TIMED_OUT_NAME;
extern const char *DCS_EXITED_NAME;
extern const char *DCS_PLAYBACK_STATE_NAME;
extern const char *DCS_SPEECH_FINISHED_NAME;
extern const char *DCS_VOLUME_CHANGED_NAME;
extern const char *DCS_MUTE_CHANGED_NAME;
extern const char *DCS_SPEECH_STATE_NAME;
extern const char *DCS_LINK_CLICKED_NAME;
extern const char *DCS_RECOMMEND_NAME;
// internal exception type
extern const char *DCS_UNEXPECTED_INFORMATION_RECEIVED_TYPE;
extern const char *DCS_INTERNAL_ERROR_TYPE;
extern const char *DCS_UNSUPPORTED_OPERATION_TYPE;
/**
* DESC:
* Get current dialog request id.
*
* PARAM: none
*
* @RETURN: current dialog request id
*/
const char *duer_get_request_id_internal(void);
/**
* DESC:
* Create a new dialog request id for each conversation.
*
* PARAM: none
*
* @RETURN: the new dialog request id
*/
const char *duer_create_request_id_internal(void);
/**
* DESC:
* Get the client context.
*
* PARAM: none
*
* @RETURN: NULL if failed, pointer point to the client context if success.
*/
baidu_json *duer_get_client_context_internal(void);
/**
* DESC:
* Check whether there is a speech waiting to play.
*
* PARAM: none
*
* @RETURN: DUER_TRUE if a speech is waiting to play, DUER_FALSE if not.
*/
duer_bool duer_speech_need_play_internal(void);
/**
* DESC:
* Pause the audio player.
*
* PARAM is_breaking: breaking a audio or a new audio is pending
*
* @RETURN: none.
*/
void duer_pause_audio_internal(duer_bool is_breaking);
/**
* DESC:
* Resume the audio player.
*
* PARAM: none
*
* @RETURN: none.
*/
void duer_resume_audio_internal(void);
/**
* DESC:
* Notify that speech is stopped.
*
* PARAM: none
*
* @RETURN: none.
*/
void duer_speech_on_stop_internal(void);
/**
* DESC:
* Notify that audio is stopped.
*
* PARAM: none
*
* @RETURN: none.
*/
void duer_dcs_audio_on_stopped_internal(void);
/**
* DESC:
* Report exception.
*
* @PARAM[in] directive: which directive cause to the exception
* @PARAM[in] directive_len: the length of directive, if directive_len <=0, the value got from strlen
* @PARAM[in] type: exception type
* @PARAM[in] msg: excetpion content
*
* @RETURN: 0 if success, negative if failed.
*/
int duer_report_exception_internal(const char* directive, size_t directive_len,
const char* type, const char* msg);
/**
* DESC:
* get Report exception in baidu_json format.
*
* @PARAM[in] directive: which directive cause to the exception
* @PARAM[in] directive_len: the length of directive, if directive_len <=0, the value got from strlen
* @PARAM[in] type: exception type
* @PARAM[in] msg: excetpion content
*
* @RETURN: NULL if failed.
*/
baidu_json *duer_get_exception_internal(const char *directive, size_t directive_len,
const char *type, const char *msg);
/**
* DESC:
* Declare the system interface.
*
* @PARAM: none
*
* @RETURN: none.
*/
void duer_declare_sys_interface_internal(void);
/**
* DESC:
* Used to reset user activety time.
*
* @PARAM: none
*
* @RETURN: none.
*/
void duer_user_activity_internal(void);
/**
* DESC:
* Returns a pointer to a new string which is a duplicate of the string 'str'.
*
* @PARAM[in] str: the string need to duplicated.
*
* @RETURN: a pointer to the duplicated string, or NULL if insufficient memory was available.
*/
char *duer_strdup_internal(const char *str);
/**
* DESC:
* Used to check whether there is a multiple rounds dialogue.
*
* @PARAM: none
*
* @RETURN: DUER_TRUE if it is multiple round dialogue.
*/
duer_bool duer_is_multiple_round_dialogue(void);
/**
* DESC:
* Checking whether a audio is playing.
*
* @RETURN: Reture DUER_TRUE if audio is playing, else returen DUER_FALSE.
*/
duer_bool duer_audio_is_playing_internal(void);
/**
* DESC:
* Chosing the highest priority play channel.
*
* @RETURN: None.
*/
void duer_play_channel_control_internal(duer_dcs_channel_switch_event_t event);
/**
* DESC:
* Checking whether a audio is paused by higher play channel.
*
* @RETURN: Reture DUER_TRUE if audio is paused, else returen DUER_FALSE.
*/
duer_bool duer_audio_is_paused_internal(void);
/**
* DESC:
* Initialize the local resource, such as lock.
*
* @RETURN: None.
*/
void duer_dcs_local_init_internal(void);
/**
* DESC:
* Checking whether the micphone is recording or not.
*
* @RETURN: Reture DUER_TRUE if audio is paused, else returen DUER_FALSE.
*/
duer_bool duer_is_recording_internal(void);
/**
* DESC:
* Starting the audio player.
*
* @RETURN: None.
*/
void duer_start_audio_play_internal(void);
/**
* DESC:
* DCS mode use it to report data.
*
* @PARAM[in] data: the report data.
* @PARAM[in] is_transparent: some items might be added to data if it is DUER_FALSE,
* such as the English to Chinese or Chinese to English translate flag.
*
* @RETURN: success return DUER_OK, failed return DUER_ERR_FAILED.
*/
int duer_dcs_data_report_internal(baidu_json *data, duer_bool is_transparent);
/**
* DESC:
* Open micphone.
*
* @PARAM: none.
*
* @RETURN: none.
*/
void duer_open_mic_internal(void);
/**
* DESC:
* Cancel the cached directive.
*
* @PARAM: none.
*
* @RETURN: none.
*/
void duer_cancel_caching_directive_internal(void);
/**
* DESC:
* Used to check should we resume audio after dialog finish or not.
*
* @PARAM: none.
*
* @RETURN: DUER_TRUE: don't resume audio until dialog finish directive executed.
*/
duer_bool duer_wait_dialog_finished_internal(void);
/**
* DESC:
* Used to exit multi dialog by reporting Exited event.
*
* @PARAM: none.
*
* @RETURN: DUER_OK if success, negative if failed.
*/
int duer_dcs_sys_exit_internal(void);
/**
* DESC:
* Used to notify DCS router that tts play finished.
*
* @PARAM: none.
*
* @RETURN: none.
*/
void duer_speak_directive_finished_internal(void);
/**
* DESC:
* Enter the critical areas.
* We use the same lock to protect the most critical areas, as:
* 1. it isn't hithly concurrent program
* 2. the execute time of function in DCS module is short
* 3. same recource
*
* @PARAM: none.
*
* @RETURN: DUER_OK if success, negative if failed.
*/
duer_status_t duer_dcs_critical_enter_internal(void);
/**
* DESC:
* Exit the critical areas.
* We use the same lock to protect the most critical areas, as:
* 1. it isn't hithly concurrent program
* 2. the execute time of function in DCS module is short
* 3. same recource
*
* @PARAM: none.
*
* @RETURN: DUER_OK if success, negative if failed.
*/
duer_status_t duer_dcs_critical_exit_internal(void);
/**
* DESC:
* Uninitialize the DCS voice output interface.
*
* @PARAM: none.
*
* @RETURN: none.
*/
void duer_dcs_voice_output_uninitialize_internal(void);
/**
* DESC:
* Uninitialize the DCS voice input interface.
*
* @PARAM: none.
*
* @RETURN: none.
*/
void duer_dcs_voice_input_uninitialize_internal(void);
/**
* DESC:
* Uninitialize the DCS system interface.
*
* @PARAM: none.
*
* @RETURN: none.
*/
void duer_sys_interface_uninitialize_internal(void);
/**
* DESC:
* Uninitialize the speaker control interface.
*
* @PARAM: none.
*
* @RETURN: none.
*/
void duer_dcs_speaker_control_uninitialize_internal(void);
/**
* DESC:
* Uninitialize the DCS screen interface.
*
* @PARAM: none.
*
* @RETURN: none.
*/
void duer_dcs_screen_uninitialize_internal(void);
/**
* DESC:
* Initialize the DCS play control interface.
*
* @PARAM: none.
*
* @RETURN: none.
*/
void duer_dcs_play_control_init_internal(void);
/**
* DESC:
* Uninitialize the DCS play control interface.
*
* @PARAM: none.
*
* @RETURN: none.
*/
void duer_dcs_play_control_uninitialize_internal(void);
/**
* DESC:
* Uninitialize the DCS device control interface.
*
* @PARAM: none.
*
* @RETURN: none.
*/
void duer_dcs_device_control_uninitialize_internal(void);
/**
* DESC:
* Uninitialize the DCS infrared control interface.
*
* @PARAM: none.
*
* @RETURN: none.
*/
void duer_dcs_infrared_control_uninitialize_internal(void);
/**
* DESC:
* Uninitialize the DCS audio player interface.
*
* @PARAM: none.
*
* @RETURN: none.
*/
void duer_dcs_audio_player_uninitialize_internal(void);
/**
* DESC:
* Uninitialize the DCS alert interface.
*
* @PARAM: none.
*
* @RETURN: none.
*/
void duer_dcs_alert_uninitialize_internal(void);
/**
* DESC:
* Used to stop the micphone when tts coming.
*
* @PARAM: none.
*
* @RETURN: none.
*/
void duer_listen_stop_internal(void);
/**
* DESC:
* Uninitialize the DCS local resource.
*
* @PARAM: none.
*
* @RETURN: none.
*/
void duer_dcs_local_uninitialize_internal(void);
/**
* DESC:
* Generate msg id
* @PARAM: none.
*
* @RETURN: the new msg id.
*/
const char *duer_generate_msg_id_internal(void);
/**
* Add dcs directive.
*
* @param directive: the directive info, include directive name, handler, etc.
* @param count, how many directives will be added.
* @param name_space: the namespace of the directives needed to add
* @return 0 if success, negative if failed.
*/
duer_status_t duer_add_dcs_directive_internal(const duer_directive_list *directive,
size_t count,
const char *name_space);
/**
* Register callback to get client context.
* Sometimes dcs need to know the device's state.
* Hence, some callbacks are needed to get client context.
*
* @param cb: the callback to get client context.
* @return 0 if success, negative if failed.
*/
duer_status_t duer_reg_client_context_cb_internal(dcs_client_context_handler cb);
/**
* DESC:
* Checking whether local player is paused by higher play channel.
*
* @RETURN: Reture DUER_TRUE if local player is paused, else returen DUER_FALSE.
*/
duer_bool duer_local_player_is_paused_internal(void);
/**
* DESC:
* Checking whether local player is playing.
*
* @RETURN: Reture DUER_TRUE if local player is playing, else returen DUER_FALSE.
*/
duer_bool duer_local_player_is_playing_internal(void);
/**
* DESC:
* Pause the loacl player.
*
* @RETURN: none.
*/
void duer_pause_local_player_internal(void);
/**
* DESC:
* Resume the loacl player.
*
* @RETURN: none.
*/
void duer_resume_local_player_internal(void);
/**
* DESC:
* Stop the loacl player.
*
* @RETURN: none.
*/
void duer_stop_local_player_internal(void);
/**
* Set dialog id.
*
* @param dialog_id: the new dialog id.
* @return 0 if success, negative if failed.
*/
duer_status_t duer_set_dialog_id_internal(const char *dialog_id);
#ifdef __cplusplus
}
#endif
#endif/*BAIDU_DUER_LIGHTDUER_DCS_LOCAL_H*/
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_dcs_local.h
|
C
|
apache-2.0
| 16,296
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/**
* File: lightduer_dcs_router.h
* Auth: Gang Chen (chengang12@baidu.com)
* Desc: Light duer DCS APIS.
*/
#ifndef BAIDU_DUER_LIGHTDUER_DCS_ROUTER_H
#define BAIDU_DUER_LIGHTDUER_DCS_ROUTER_H
#include <stdlib.h>
#include "baidu_json.h"
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* DCS directive handler. The handler will be implemented by developer.
*
* @PARAM[in] directive: the directive info, include directive name, handler, etc.
*
* @return: return code must be one of following values:
* // no error.
* DUER_OK = 0,
* // directive format incorrect, such missing token in Play directive.
* DUER_MSG_RSP_BAD_REQUEST = 128,
* // device doesn't support this directive,
* DUER_MSG_RSP_NOT_FOUND = 132, // 4.04
* // all other errors.
* DUER_ERR_FAILED = -0x0001,
* // directive parameter value invalid.
* DUER_ERR_INVALID_PARAMETER = -0x0010,
* // memory overflow.
* DUER_ERR_MEMORY_OVERLOW = -0x0011,
*/
typedef duer_status_t (*dcs_directive_handler)(const baidu_json *directive);
typedef baidu_json* (*dcs_client_context_handler)();
typedef struct {
const char *directive_name;
dcs_directive_handler cb;
} duer_directive_list;
/**
* Add dcs directive.
*
* @param directive: the directive info, include directive name, handler, etc.
* @param count, how many directives will be added.
* @param name_space: the namespace of the directives needed to add
* @return 0 if success, negative if failed.
*/
duer_status_t duer_add_dcs_directive(const duer_directive_list *directive,
size_t count,
const char *name_space);
/**
* Register callback to get client context.
* Sometimes dcs need to know the device's state.
* Hence, some callbacks are needed to get client context.
*
* @param cb: the callback to get client context.
* @return 0 if success, negative if failed.
*/
duer_status_t duer_reg_client_context_cb(dcs_client_context_handler cb);
/**
* DESC:
* Used to create dcs event.
*
* @PARAM[in] namespace: the namespace of the event need to report.
* @PARAM[in] name: the name the event need to report.
* @PARAM[in] need_msg_id: including messageId item or not.
* @RETURN: pinter of the created dcs event if success, or NULL if failed.
*/
baidu_json *duer_create_dcs_event(const char *name_space, const char *name, duer_bool need_msg_id);
/**
* DESC:
* Used to cancel a dcs dialog: the response of a dialogue will be ignored
* if user calling this API before receiving the response.
*
* @PARAM[in] none.
* @RETURN: none.
*/
void duer_dcs_dialog_cancel(void);
#ifdef __cplusplus
}
#endif
#endif/*BAIDU_DUER_LIGHTDUER_DCS_ROUTER_H*/
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_dcs_router.h
|
C
|
apache-2.0
| 3,449
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
// Author: Su Hao (suhao@baidu.com)
//
// Description: The APIs for debug.
#ifndef BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_DEBUG_H
#define BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_DEBUG_H
#include "lightduer_types.h"
#ifndef DUER_DEBUG_BUF_SIZE
#ifdef DUER_RELEASE_VERSION
#define DUER_DEBUG_BUF_SIZE (64)
#else
#define DUER_DEBUG_BUF_SIZE (512)
#endif
#endif // DUER_DEBUG_BUF_SIZE
#ifdef __cplusplus
extern "C" {
#endif
/*
* The debug output
*/
typedef void (*duer_debug_f)(duer_context ctx,
duer_u32_t level,
const char* file,
duer_u32_t line,
const char* fmt);
/*
* Set the debug output
*
* @Param ctx, duer_context, the debug context for user
* @Param f_debug, duer_debug_f, the debug output function
*/
DUER_EXT void baidu_ca_debug_init(duer_context ctx, duer_debug_f f_debug);
DUER_INT void duer_debug_print(duer_u32_t level, const char* file,
duer_u32_t line, const char* msg);
DUER_INT void duer_debug(duer_u32_t level, const char* file, duer_u32_t line,
const char* fmt, ...);
DUER_INT void duer_dump(duer_u32_t level, const char* file, duer_u32_t line,
const char *tag, const void *data, duer_size_t size);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_DEBUG_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_debug.h
|
C
|
apache-2.0
| 2,077
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/*
* File: lightduer_dev_info.h
* Auth: Zhong Shuai (zhongshuai@baidu.com)
* Desc: Device information
*/
#ifndef BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_DEV_INFO_H
#define BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_DEV_INFO_H
#include "lightduer_system_info.h"
#ifdef __cplusplus
extern "C" {
#endif
struct DevInfo {
char firmware_version[FIRMWARE_VERSION_LEN + 1];
};
struct DevInfoOps {
/*
* Provide firmware information about the current system
*/
int (*get_firmware_version)(char *firmware_version);
/*
* Set firmware information about the current system
*/
int (*set_firmware_version)(char const *firmware_version);
};
/*
* Set the firmware version of the current system
*
* @param firmware_version:
*
* @return int: Success: DUER_OK
* Failed: Other
*/
extern int duer_set_firmware_version(char const *firmware_version);
/*
* Get the firmware version of the current system
*
* @param firmware_version: size > FIRMWARE_VERSION_LEN
* @param len: string length
*
* @return int: Success: DUER_OK
* Failed: Other
*/
extern int duer_get_firmware_version(char *firmware_version, size_t len);
/*
* Report device info to Duer Cloud
*
* @param info:
*
* @return int: Success: DUER_OK
* Failed: Other
*/
extern int duer_report_device_info(void);
/*
* Register device info ops
*
* @param ops:
*
* @return int: Success: DUER_OK
* Failed: Other
*/
extern int duer_register_device_info_ops(struct DevInfoOps *ops);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_DEV_INFO_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_dev_info.h
|
C
|
apache-2.0
| 2,233
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/*
* Auth: Leliang Zhang(zhangleliang@baidu.com)
* Desc: device log report
*/
#ifndef BAIDU_DUER_LIGHTDUER_DS_LOG_H
#define BAIDU_DUER_LIGHTDUER_DS_LOG_H
#include "baidu_json.h"
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum _duer_ds_log_version_enum {
DUER_DS_LOG_VERSION_UNKNOWN = 0x00,
DUER_DS_LOG_VERSION_1_0 = 0x01,
DUER_DS_LOG_VERSION_2_0 = 0x02,
DUER_DS_LOG_VERSION_MAX = 0x08
} duer_ds_log_version_enum_t;
typedef enum _duer_ds_log_level_enum {
DUER_DS_LOG_LEVEL_FATAL = 0x01,
DUER_DS_LOG_LEVEL_ERROR = 0x02,
DUER_DS_LOG_LEVEL_WARN = 0x03,
DUER_DS_LOG_LEVEL_INFO = 0x04,
DUER_DS_LOG_LEVEL_DEBUG = 0x05,
DUER_DS_LOG_LEVEL_MAX = 0x08
} duer_ds_log_level_enum_t;
typedef enum {
DUER_DS_LOG_IMPORTANCE_NORMAL = 0x00,
DUER_DS_LOG_IMPORTANCE_MUST_REPORT = 0x01,
} duer_ds_log_importance_enum_t;
#ifndef DUER_DS_LOG_DEFAULT_REPORT_LEVEL
#define DUER_DS_LOG_DEFAULT_REPORT_LEVEL DUER_DS_LOG_LEVEL_INFO
#endif
#ifndef DUER_DS_LOG_DEFAULT_CACHE_LEVEL
#define DUER_DS_LOG_DEFAULT_CACHE_LEVEL DUER_DS_LOG_DEFAULT_REPORT_LEVEL
#endif
/*
* update the report level,
* DUER_DS_LOG_LEVEL_FATAL <= log_level <= DUER_DS_LOG_LEVEL_DEBUG
* if < DUER_DS_LOG_LEVEL_FATAL, set to DUER_DS_LOG_LEVEL_FATAL
* if > DUER_DS_LOG_LEVEL_DEBUG, set to DUER_DS_LOG_LEVEL_DEBUG
* @param log_level
* @return DUER_OK on success, other fail
*
*/
duer_status_t duer_ds_log_set_report_level(duer_ds_log_level_enum_t log_level);
/**
* init the control point for setting report level
*/
void duer_ds_log_init(void);
typedef enum _duer_ds_log_module_enum {
DUER_DS_LOG_MODULE_CA = 0x01,
DUER_DS_LOG_MODULE_RECORDER = 0x02,
DUER_DS_LOG_MODULE_MEDIA = 0x03,
DUER_DS_LOG_MODULE_HTTP = 0x04,
DUER_DS_LOG_MODULE_DCS = 0x05,
DUER_DS_LOG_MODULE_APP = 0x06,
DUER_DS_LOG_MODULE_WIFICFG = 0x07,
DUER_DS_LOG_MODULE_SYSTEM = 0x08,
DUER_DS_LOG_MODULE_ANALYSIS = 0x09,
DUER_DS_LOG_MODULE_BIND = 0x0A,
DUER_DS_LOG_MODULE_SONIC = 0x0B,
DUER_DS_LOG_MODULE_SMARTCFG = 0x0C,
DUER_DS_LOG_MODULE_AIRKISS = 0x0D,
DUER_DS_LOG_MODULE_PM = 0x0E,
DUER_DS_LOG_MODULE_MAX = 0x20
} duer_ds_log_module_enum_t;
typedef enum _duer_ds_log_family_enum {
DUER_DS_LOG_FAMILY_UNKNOWN = 0x00,
DUER_DS_LOG_FAMILY_MEMORY = 0x01,
DUER_DS_LOG_FAMILY_NETWORK = 0x02,
DUER_DS_LOG_FAMILY_MAX = 0x0F
} duer_ds_log_family_enum_t;
/**
* {
* "duer_trace_info": {
* "code": [打点信息],
* "message": [详细信息], // 可选
* "ts": [当前时间戳]
* }
* }
* the code format:
* 0 1 2 3
* 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |X| Ver |X| Lel |X X X| Module | Family| Code |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*/
#define MASK_VERSION 0x70000000
#define BITS_VERSION 0x07
#define OFFSET_VERSION 28
#define MASK_LEVEL 0x07000000
#define BITS_LEVEL 0x07
#define OFFSET_LEVEL 24
#define MASK_MODULE 0x001F0000
#define BITS_MODULE 0x1F
#define OFFSET_MODULE 16
#define MASK_FAMILY 0x0000F000
#define BITS_FAMILY 0x0F
#define OFFSET_FAMILY 12
#define MASK_CODE 0x00000FFF
#define BITS_CODE 0x0FFF
#define OFFSET_CODE 0
/**
* generate the code in the above format from the input parameter
* @param log_version
* @param log_level
* @param log_module
* @param log_family
* @param log_code
* @return return the code in the above format
*/
duer_u32_t duer_ds_log_generate_code(duer_ds_log_version_enum_t log_version,
duer_ds_log_level_enum_t log_level,
duer_ds_log_module_enum_t log_module,
duer_ds_log_family_enum_t log_family,
int log_code);
/**
* @param log_code the code in the above format which is 32bits
* @return the version
*/
duer_u32_t duer_ds_log_get_log_version(duer_u32_t log_code);
/**
* @param log_code the code in the above format which is 32bits
* @return the level
*/
duer_u32_t duer_ds_log_get_log_level(duer_u32_t log_code);
/**
* @param log_code the code in the above format which is 32bits
* @return the module
*/
duer_u32_t duer_ds_log_get_log_module(duer_u32_t log_code);
/**
* @param log_code the code in the above format which is 32bits
* @return the family
*/
duer_u32_t duer_ds_log_get_log_family(duer_u32_t log_code);
/**
* @param log_code the code in the above format which is 32bits
* @return the code
*/
duer_u32_t duer_ds_log_get_log_code(duer_u32_t log_code);
/**
* #param log_version the version of the log
* @param log_level the log level, Fatal, Error, Warn, Info, Debug
* @param log_module the module code
* @param log_family the family of this log
* @param log_code the code for this info, maybe use to parse the content of message
* only the low 12bits use
* @param log_message the content of the info, in json format
* the caller should not try to release this if exist.
* @return DUER_OK on success, or fail
* an example:
* {
* "duer_trace_info": {
* "code": 2001, //
* "message": {
* "reason": "REBOOT",
* "count": 1
* },
* "ts": 220509360
* }
* }
*/
duer_status_t duer_ds_log_v_f(duer_ds_log_version_enum_t log_version,
duer_ds_log_level_enum_t log_level,
duer_ds_log_module_enum_t log_module,
duer_ds_log_family_enum_t log_family,
int log_code,
const baidu_json *log_message,
duer_ds_log_importance_enum_t importance);
duer_status_t duer_ds_log_f(duer_ds_log_level_enum_t log_level,
duer_ds_log_module_enum_t log_module,
duer_ds_log_family_enum_t log_family,
int log_code,
const baidu_json *log_message,
duer_ds_log_importance_enum_t importance);
duer_status_t duer_ds_log(duer_ds_log_level_enum_t log_level,
duer_ds_log_module_enum_t log_module,
int log_code,
const baidu_json *log_message);
duer_status_t duer_ds_log_important(duer_ds_log_level_enum_t log_level,
duer_ds_log_module_enum_t log_module,
int log_code,
const baidu_json *log_message);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIGHTDUER_DS_LOG_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_ds_log.h
|
C
|
apache-2.0
| 7,612
|
/**
* Copyright (2018) Baidu Inc. All rights reserved.
*
* 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.
*/
/*
* Auth: Chen Xihao(chenxihao@baidu.com)
* Desc: airkiss related report log
*/
#ifndef BAIDU_DUER_LIGHTDUER_DS_LOG_AIRKISS_H
#define BAIDU_DUER_LIGHTDUER_DS_LOG_AIRKISS_H
#include "baidu_json.h"
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum _duer_ds_log_airkiss_code {
DUER_DS_LOG_AIRKISS_START = 0x201,
DUER_DS_LOG_AIRKISS_FINISHED = 0x202,
DUER_DS_LOG_AIRKISS_FAILED = 0x401,
} duer_ds_log_airkiss_code_t;
/**
* common function to report the log of airkiss
*/
duer_status_t duer_ds_log_airkiss(duer_ds_log_airkiss_code_t log_code,
const baidu_json *message);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIGHTDUER_DS_LOG_AIRKISS_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_ds_log_airkiss.h
|
C
|
apache-2.0
| 1,374
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/*
* Auth: Chen Xihao(chenxihao@baidu.com)
* Desc: audio play related report log
*/
#ifndef BAIDU_DUER_LIGHTDUER_DS_LOG_AUDIO_H
#define BAIDU_DUER_LIGHTDUER_DS_LOG_AUDIO_H
#include "baidu_json.h"
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum _duer_ds_log_audio_code {
DUER_DS_LOG_AUDIO_BUFFER_INFO = 0x001,
DUER_DS_LOG_AUDIO_PLAY_START = 0x002,
DUER_DS_LOG_AUDIO_PLAY_PAUSE = 0x003,
DUER_DS_LOG_AUDIO_PLAY_RESUME = 0x004,
DUER_DS_LOG_AUDIO_PLAY_STOP = 0x005,
DUER_DS_LOG_AUDIO_PLAY_FINISH = 0x006,
DUER_DS_LOG_AUDIO_CODEC_VERSION = 0x007,
DUER_DS_LOG_AUDIO_INFO = 0x008,
DUER_DS_LOG_AUDIO_M4A_HEAD_SIZE = 0x009,
DUER_DS_LOG_AUDIO_CONTENT_TYPE = 0x00a,
DUER_DS_LOG_AUDIO_DOWNLOAD_DELAY = 0x00b,
DUER_DS_LOG_AUDIO_PLAY_DELAY = 0x00c,
DUER_DS_LOG_AUDIO_NO_MEMORY = 0x301,
DUER_DS_LOG_AUDIO_UNSUPPORT_FORMAT = 0x302,
DUER_DS_LOG_AUDIO_UNSUPPORT_BITRATE = 0x303,
DUER_DS_LOG_AUDIO_HEAD_TOO_LARGE = 0x304,
DUER_DS_LOG_AUDIO_DOWNLOAD_FAILED = 0x305,
DUER_DS_LOG_AUDIO_PLAYER_ERROR = 0x306,
DUER_DS_LOG_AUDIO_BUFFER_ERROR = 0x307,
DUER_DS_LOG_AUDIO_CODEC_ERROR = 0x308,
DUER_DS_LOG_AUDIO_NULL_POINTER = 0x309,
DUER_DS_LOG_AUDIO_INVALID_CONTEXT = 0x30a,
DUER_DS_LOG_AUDIO_URL_NO_DATA = 0x30b,
DUER_DS_LOG_AUDIO_PLAY_FAILED = 0x30c,
DUER_DS_LOG_AUDIO_M4A_INVALID_HEADER = 0x401,
DUER_DS_LOG_AUDIO_M4A_PARSE_HEADER_ERROR = 0x402,
DUER_DS_LOG_AUDIO_HLS_PARSE_M3U8_ERROR = 0x501,
DUER_DS_LOG_AUDIO_HLS_DOWNLOAD_ERROR = 0x502,
DUER_DS_LOG_AUDIO_HLS_RELOAD_ERROR = 0x503,
DUER_DS_LOG_AUDIO_SOFT_DECODER_ERROR = 0x601,
DUER_DS_LOG_AUDIO_USER_DEFINED_ERROR = 0xf01,
} duer_ds_log_audio_code_t;
typedef struct duer_ds_audio_info_s {
duer_u32_t duration;
duer_u32_t block_count;
duer_u32_t max_codec_bitrate;
duer_u32_t min_codec_bitrate;
duer_u32_t avg_codec_bitrate;
duer_u32_t request_play_ts;
duer_u32_t request_download_ts;
} duer_ds_audio_info_t;
#define DUER_DS_LOG_AUDIO_MEMORY_OVERFLOW() duer_ds_log_audio_memory_overflow(__FILE__, __LINE__)
#define DUER_DS_LOG_AUDIO_NULL_POINTER() duer_ds_log_audio_null_pointer(__FILE__, __LINE__)
#define DUER_DS_LOG_AUDIO_INVALID_CONTEXT() duer_ds_log_audio_invalid_context(__FILE__, __LINE__)
/**
* common function to report the log of audio play moudle
*/
duer_status_t duer_ds_log_audio(duer_ds_log_audio_code_t log_code, const baidu_json *log_message);
/**
* report the message for log code DUER_DS_LOG_AUDIO_BUFFER_INFO
* {
* "size": [buffer size],
* "type": [buffer type] // 0: heap, 1: data segment, 2: psram 3: file
* }
*/
duer_status_t duer_ds_log_audio_buffer_info(duer_u32_t size, duer_u32_t type);
/**
* report the message for log code DUER_DS_LOG_AUDIO_PLAY_START
* {
* "url": [url of audio],
* "source_type": [source type]
* }
*/
duer_status_t duer_ds_log_audio_play_start(const char *url, duer_u32_t type);
/**
* report the message for log code DUER_DS_LOG_AUDIO_PLAY_STOP
* {
* "duration": [播放时长],
* "block_count": [卡顿次数],
* "codec_bitrate": {
* "max" : [最大码率],
* "min" : [最小码率],
* "avg" : [平均码率]
* }
* }
*/
duer_status_t duer_ds_log_audio_play_stop(duer_u32_t duration, duer_u32_t block_count,
duer_u32_t max_bitrate, duer_u32_t min_bitrate, duer_u32_t avg_bitrate);
/**
* report the message for log code DUER_DS_LOG_AUDIO_PLAY_FINISH
* {
* "duration": [播放时长],
* "block_count": [卡顿次数],
* "codec_bitrate": {
* "max" : [最大码率],
* "min" : [最小码率],
* "avg" : [平均码率]
* }
* }
*/
duer_status_t duer_ds_log_audio_play_finish(duer_u32_t duration, duer_u32_t block_count,
duer_u32_t max_bitrate, duer_u32_t min_bitrate, duer_u32_t avg_bitrate);
/**
* report the message for log code DUER_DS_LOG_AUDIO_CODEC_VERSION
* {
* "version": [codec版本号]
* }
*/
duer_status_t duer_ds_log_audio_codec_version(const char *version);
/**
* report the message for log code DUER_DS_LOG_AUDIO_INFO
* {
* "bitrate": [比特率],
* "sample_rate": [采样率],
* "bits_per_sample": [位宽],
* "channels": [声道数]
* }
*/
duer_status_t duer_ds_log_audio_info(duer_u32_t bitrate,
duer_u32_t sample_rate, duer_u32_t bits_per_sample, duer_u32_t channels);
/**
* report the message for log code DUER_DS_LOG_AUDIO_M4A_HEAD_SIZE
* {
* "head_size": [m4a头大小]
* }
*/
duer_status_t duer_ds_log_audio_m4a_head_size(duer_u32_t size);
/**
* report the message for log code DUER_DS_LOG_AUDIO_CONTENT_TYPE
* {
* "content_type": [http下载类型]
* }
*/
duer_status_t duer_ds_log_audio_content_type(const char *type);
/**
* report the message for log code DUER_DS_LOG_AUDIO_DOWNLOAD_DELAY
* {
* "delay": [时延,单位ms]
* }
*/
duer_status_t duer_ds_log_audio_download_delay(void);
/**
* report the message for log code DUER_DS_LOG_AUDIO_PLAY_DELAY
* {
* "delay": [时延,单位ms]
* }
*/
duer_status_t duer_ds_log_audio_play_delay(void);
/**
* report the message for log code DUER_DS_LOG_AUDIO_NO_MEMORY
* {
* "file": [发生内存分配错误的文件],
* "line": [发生内存分配错误的行号]
* }
*/
duer_status_t duer_ds_log_audio_memory_overflow(const char *file, duer_u32_t line);
/**
* report the message for log code DUER_DS_LOG_AUDIO_NULL_POINTER
* {
* "file": the file name where error happens
* "line": the line number where error happens
* }
*/
duer_status_t duer_ds_log_audio_null_pointer(const char *file, duer_u32_t line);
/**
* report the message for log code DUER_DS_LOG_AUDIO_INVALID_CONTEXT
* {
* "file": the file name where error happens
* "line": the line number where error happens
* }
*/
duer_status_t duer_ds_log_audio_invalid_context(const char *file, duer_u32_t line);
/**
* report the message for log code DUER_DS_LOG_AUDIO_HLS_PARSE_M3U8_ERROR
* {
* "line": [解析出错的行号]
* }
*/
duer_status_t duer_ds_log_audio_hls_parse_m3u8_error(duer_u32_t line);
/**
* report the message for log code DUER_DS_LOG_AUDIO_FRAMEWORK_ERROR
* {
* "error_code": Internal error code for audio framework
* }
*/
duer_status_t duer_ds_log_audio_framework_error(int error_code);
/**
* report the message for log code DUER_DS_LOG_AUDIO_PLAYER_ERROR
* {
* "error_code": Internal error code for audio player
* }
*/
duer_status_t duer_ds_log_audio_player_error(int error_code);
/**
* report the message for log code DUER_DS_LOG_AUDIO_PLAY_FAILED
* {
* "url": [音频url]
* }
*/
duer_status_t duer_ds_log_audio_play_failed(const char *url);
/**
* report the message for log code DUER_DS_LOG_AUDIO_USER_DEFINED_ERROR
* {
* "error_code": user defined error code
* }
*/
duer_status_t duer_ds_log_audio_user_defined_error(int error_code);
/**
* record the timestamp when request to play
*/
duer_status_t duer_ds_log_audio_request_play(void);
/**
* record the timestamp when request to download
*/
duer_status_t duer_ds_log_audio_request_download(void);
extern duer_ds_audio_info_t g_audio_infos;
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIGHTDUER_DS_LOG_AUDIO_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_ds_log_audio.h
|
C
|
apache-2.0
| 8,336
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/*
* Auth: Su Hao(suhao@baidu.com)
* Desc: Record the audio player errors
*/
#ifndef BAIDU_DUER_LIBDUER_DEVICE_MODULES_DEVICES_STATUS_LIGHTDUER_DS_LOG_AUDIO_PLAYER_H
#define BAIDU_DUER_LIBDUER_DEVICE_MODULES_DEVICES_STATUS_LIGHTDUER_DS_LOG_AUDIO_PLAYER_H
#include "baidu_json.h"
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum _duer_dslog_audply_code_e {
DUER_DS_LOG_AUDPLY_FINISHED = 0x001,
DUER_DS_LOG_AUDPLY_TERMINATED = 0x002,
// Internal Errors
DUER_DS_LOG_AUDPLY_INTERNAL_ERROR = 0x500,
// HTTP errors
DUER_DS_LOG_AUDPLY_HTTP_REQUEST_ERROR,
DUER_DS_LOG_AUDPLY_HTTP_RESPONSE_ERROR,
// File errors
DUER_DS_LOG_AUDPLY_FILE_ERROR,
// Codec errors
DUER_DS_LOG_AUDPLY_CODEC_ERROR,
} duer_dslog_audply_code_t;
/**
* common function to report the log of audio play moudle
*
* @param log_code, duer_dslog_audply_code_t, defined the error type
* @param uri, const char *, file path or url
* @param speed, float, download speed average
* @param code, int, internal error code, 0 means not report
* @param file, conat char *, file where the error occurs
* @param line, int, the file line where the error occurs
*/
duer_status_t duer_ds_log_audply(duer_dslog_audply_code_t log_code, const char *uri,
float speed, int code, const char *file, int line);
#define DUER_DS_LOG_AUDPLY_INFO(_code, _uri, _speed) \
duer_ds_log_audply(_code, _uri, _speed, 0, NULL, 0)
#define DUER_DS_LOG_AUDPLY_ERROR(_code, _uri, _speed, _errcode) \
duer_ds_log_audply(_code, _uri, _speed, _errcode, __FILE__, __LINE__)
#define DUER_DS_LOG_AUDPLY_ERROR_ONLY(_code, _uri, _speed, _errcode) \
duer_ds_log_audply(_code, _uri, _speed, _errcode, NULL, 0)
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIBDUER_DEVICE_MODULES_DEVICES_STATUS_LIGHTDUER_DS_LOG_AUDIO_PLAYER_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_ds_log_audio_player.h
|
C
|
apache-2.0
| 2,544
|
/**
* Copyright (2018) Baidu Inc. All rights reserved.
*
* 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.
*/
/*
* Auth: Chen Xihao(chenxihao@baidu.com)
* Desc: bind device module related report log
*/
#ifndef BAIDU_DUER_LIGHTDUER_DS_LOG_BIND_H
#define BAIDU_DUER_LIGHTDUER_DS_LOG_BIND_H
#include "baidu_json.h"
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum _duer_ds_log_bind_code {
DUER_DS_LOG_BIND_CONFIG_WIFI_AIRKISS = 0x001,
DUER_DS_LOG_BIND_CONFIG_WIFI_SMARTCONFIG = 0x002,
DUER_DS_LOG_BIND_CONFIG_WIFI_SONIC = 0x003,
DUER_DS_LOG_BIND_CONFIG_WIFI_BT = 0x004,
DUER_DS_LOG_BIND_TASK_START = 0x005,
DUER_DS_LOG_BIND_SEND_RESP = 0x006,
DUER_DS_LOG_BIND_TASK_END = 0x007,
DUER_DS_LOG_BIND_NO_MEMORY = 0x301,
DUER_DS_LOG_BIND_INVALID_PARAMS = 0x302,
DUER_DS_LOG_BIND_START_TASK_FAILED = 0x303,
DUER_DS_LOG_BIND_INIT_AES_FAILED = 0x304,
DUER_DS_LOG_BIND_INIT_SOCKET_FAILED = 0x305,
DUER_DS_LOG_BIND_BIND_SOCKET_FAILED = 0x306,
DUER_DS_LOG_BIND_ENCRYPT_FAILED = 0x307,
DUER_DS_LOG_BIND_SOCKET_ERROR = 0x308,
} duer_ds_log_bind_code_t;
/**
* common function to report the log of bind device moudle
*/
duer_status_t duer_ds_log_bind(duer_ds_log_bind_code_t log_code);
int duer_ds_log_report_bind_result(duer_u32_t req_port,
duer_u32_t resp_success_count, duer_u32_t resp_fail_count);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIGHTDUER_DS_LOG_BIND_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_ds_log_bind.h
|
C
|
apache-2.0
| 2,153
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/*
* Auth: Leliang Zhang(zhangleliang@baidu.com)
* Desc: ca related trace log
*/
#ifndef BAIDU_DUER_LIGHTDUER_DS_LOG_CA_H
#define BAIDU_DUER_LIGHTDUER_DS_LOG_CA_H
#include "baidu_json.h"
#include "lightduer_ds_log.h"
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* tracelog for CA module
* @param log_level
* @param log_code
* @param log_message
* @return
* more info pls see lightduer_ds_log.h
*/
duer_status_t duer_ds_log_ca(duer_ds_log_level_enum_t log_level,
int log_code,
const baidu_json *log_message);
/*
* log code.
*/
typedef enum _duer_ds_log_ca_enum {
DUER_DS_LOG_CA_INIT = 0x001,
DUER_DS_LOG_CA_START = 0x002,
DUER_DS_LOG_CA_START_STATE_CHANGE = 0x003,
DUER_DS_LOG_CA_START_CONNECT = 0x004,
DUER_DS_LOG_CA_STARTED = 0x005,
DUER_DS_LOG_CA_REGISTER_CONTROL_POINT = 0x006,
DUER_DS_LOG_CA_CALL_CONTROL_POINT = 0x007,
DUER_DS_LOG_CA_STOPPED = 0x008,
DUER_DS_LOG_CA_CLEAR_DATA = 0x009,
DUER_DS_LOG_CA_HTTP_DNS = 0x00A,
DUER_DS_LOG_CA_ERR = 0x300,
DUER_DS_LOG_CA_START_PROFILE_ERR = 0x301,
DUER_DS_LOG_CA_CONNECT_DNS_ERR = 0x302,
DUER_DS_LOG_CA_CONNECT_IP_ERR = 0x303,
DUER_DS_LOG_CA_START_STATE_REG_FAIL = 0x304,
DUER_DS_LOG_CA_SEND_ERROR = 0x305,
DUER_DS_LOG_CA_RECV_ERROR = 0x306,
DUER_DS_LOG_CA_MBEDTLS_ERR = 0x307,
DUER_DS_LOG_CA_TCPHEADER_ERR = 0x308,
DUER_DS_LOG_CA_COAP_PARSE_ERR = 0x309,
DUER_DS_LOG_CA_MALLOC_FAIL = 0x400,
DUER_DS_LOG_CA_LOG_CODE_MAX = 0xFFF
} duer_ds_log_ca_enum_t;
/**
* tracelog for CA module with FATAL log level
* @param log_code
* @param log_message
* @return
* more info pls see lightduer_ds_log.h
*/
duer_status_t duer_ds_log_ca_fatal(int log_code,
const baidu_json *log_message);
/**
* tracelog for CA module with ERROR log level
* @param log_code
* @param log_message
* @return
* more info pls see lightduer_ds_log.h
*/
duer_status_t duer_ds_log_ca_error(int log_code,
const baidu_json *log_message);
/**
* tracelog for CA module with WARN log level
* @param log_code
* @param log_message
* @return
* more info pls see lightduer_ds_log.h
*/
duer_status_t duer_ds_log_ca_warn(int log_code,
const baidu_json *log_message);
/**
* tracelog for CA module with INFO log level
* @param log_code
* @param log_message
* @return
* more info pls see lightduer_ds_log.h
*/
duer_status_t duer_ds_log_ca_info(int log_code,
const baidu_json *log_message);
/**
* tracelog for CA module with DEBUG log level
* @param log_code
* @param log_message
* @return
* more info pls see lightduer_ds_log.h
*/
duer_status_t duer_ds_log_ca_debug(int log_code,
const baidu_json *log_message);
/**
* try to cache the log_code
* @param log_code the error code
*/
duer_status_t duer_ds_log_ca_cache_error(int log_code);
/**
* @param from old state
* @param to new state
* report the message for log code DUER_DS_LOG_CA_START_STATE_CHANGE
* {
* "from": [旧状态],
* "to": [新的状态]
* }
*/
duer_status_t duer_ds_log_ca_start_state_change(int from, int to);
/**
* report the message for log code DUER_DS_LOG_CA_START_CONNECT
* {
* "host": [连接主机],
* "port": [连接端口]
* }
*/
duer_status_t duer_ds_log_ca_start_connect(const char *host, int port);
/**
* report the message for log code DUER_DS_LOG_CA_STARTED
* {
* "reason": [启动原因],
* "count": [启动次数],
* "connect_time:" [成功连接花费时间 ms]
* }
*/
duer_status_t duer_ds_log_ca_started(duer_status_t reason, int count, duer_u32_t connect_time);
/*
* control point type
*/
typedef enum _duer_ds_log_ca_controlpoint_type_enum {
DUER_CA_CP_TYPE_STATIC = 0x000,
DUER_CA_CP_TYPE_DYNAMIC = 0x001
} duer_ds_log_ca_controlpoint_type_enum_t;
/**
* report the message for log code DUER_DS_LOG_CA_REGISTER_CONTROL_POINT
* {
* "name": [制点名称],
* "type": [STATIC|DYNAMIC]
* }
*/
duer_status_t duer_ds_log_ca_register_cp(const char *name,
duer_ds_log_ca_controlpoint_type_enum_t type);
/**
* report the message for log code DUER_DS_LOG_CA_CALL_CONTROL_POINT
* {
* "name": [制点名称]
* }
*/
duer_status_t duer_ds_log_ca_call_cp(const char *name);
/**
* report the message for log code DUER_DS_LOG_CA_MBEDTLS_ERR
* {
* "code": [错误代码]
* }
*/
duer_status_t duer_ds_log_ca_mbedtls_error(duer_s32_t code);
/**
* report the message for log code DUER_DS_LOG_CA_MALLOC_FAIL
* {
* "file": [出错文件],
"line": [出错行号]
* }
*/
duer_status_t duer_ds_log_ca_malloc_error(const char *file, duer_u32_t line);
#define DUER_DS_LOG_CA_MEMORY_OVERFLOW() duer_ds_log_ca_malloc_error(__FILE__, __LINE__)
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIGHTDUER_DS_LOG_CA_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_ds_log_ca.h
|
C
|
apache-2.0
| 5,881
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/*
* Auth: Leliang Zhang(zhangleliang@baidu.com)
* Desc: trace log cache, cache the trace log when ca disconnect
*/
#ifndef BAIDU_DUER_LIGHTDUER_DS_LOG_CACHE_H
#define BAIDU_DUER_LIGHTDUER_DS_LOG_CACHE_H
#include "baidu_json.h"
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* try to cache the tracelog info
* @param code: the trace log code, see lightduer_ds_log.h for more info
* @param message: the additional message for the @code
* @param timestamp: the timestamp when generate the trace log
*/
duer_status_t duer_ds_log_cache_push(duer_u32_t code, const baidu_json *message, duer_u32_t timestamp);
/**
* invoke this after CA connected, try to report the tracelog cached when CA disconnect.
*/
duer_status_t duer_ds_log_cache_report(void);
/**
* initialize the resource
*/
duer_status_t duer_ds_log_cache_initialize(void);
/**
* release the resources
*/
duer_status_t duer_ds_log_cache_finalize(void);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIGHTDUER_DS_LOG_CACHE_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_ds_log_cache.h
|
C
|
apache-2.0
| 1,649
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/*
* Auth: Gang Chen(chengang12@baidu.com)
* Desc: dcs module log report
*/
#ifndef BAIDU_DUER_LIGHTDUER_DS_LOG_DCS_H
#define BAIDU_DUER_LIGHTDUER_DS_LOG_DCS_H
#ifdef __cplusplus
extern "C" {
#endif
#include "lightduer_types.h"
#include "baidu_json.h"
typedef enum {
DUER_DS_LOG_DCS_DIRECTIVE_DROPPED = 0x201,
DUER_DS_LOG_DCS_OLD_DIRECTIVE_DROPPED = 0x202,
DUER_DS_LOG_DCS_MEMORY_ERROR = 0x301,
DUER_DS_LOG_DCS_HANDLER_UNREALIZED = 0x302,
DUER_DS_LOG_DCS_REPORT_EVENT_FAILED = 0x303,
DUER_DS_LOG_DCS_PARAM_ERROR = 0x304,
DUER_DS_LOG_DCS_STOP_LISTEN_MISSING = 0x305,
DUER_DS_LOG_DCS_ADD_DIRECTIVE_FAILED = 0x401,
} duer_ds_log_dcs_code_t;
/**
* Report ds log for dcs module
*/
duer_status_t duer_ds_log_dcs(duer_ds_log_dcs_code_t log_code, const baidu_json *log_message);
/**
* Report ds log with direction information:
* {
* "file" : "dcs.c",
* "line" : 100
* }
*/
duer_status_t duer_ds_log_dcs_report_with_dir(duer_ds_log_dcs_code_t log_code,
const char *file,
int line);
/**
* Report ds log when directive is dropped:
* {
* "current_dialog_id" : "aaaaaaabbbbbbbbb", // current dialogId
* "directive_dialog_id" : "bbbbbbbbbaaaaaaa", // dialogId of this directive
* "directive" : "play" // directive name
* }
*/
duer_status_t duer_ds_log_dcs_directive_drop(const char *current_id,
const char *directive_id,
const char *name);
/**
* Report ds log if the handler is not realized:
* {
* "handler_name" : "duer_dcs_speak_handler"
* }
*/
duer_status_t duer_ds_log_dcs_handler_unrealize(const char *func);
/**
* Report ds log if add directive failed:
* {
* "directive" : "play"
* }
*/
duer_status_t duer_ds_log_dcs_add_directive_fail(const char *name);
/**
* Report ds log if event report failed:
* {
* "event_name" : "SetAlertFailed"
* }
*/
duer_status_t duer_ds_log_dcs_event_report_fail(const char *name);
#define DUER_DS_LOG_REPORT_DCS_MEMORY_ERROR() \
duer_ds_log_dcs_report_with_dir(DUER_DS_LOG_DCS_MEMORY_ERROR, __FILE__, __LINE__)
#define DUER_DS_LOG_REPORT_DCS_PARAM_ERROR() \
duer_ds_log_dcs_report_with_dir(DUER_DS_LOG_DCS_PARAM_ERROR, __FILE__, __LINE__)
#define DUER_DS_LOG_REPORT_DCS_HANDLER_UNREALIZE() duer_ds_log_dcs_handler_unrealize(__func__)
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIGHTDUER_DS_LOG_DCS_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_ds_log_dcs.h
|
C
|
apache-2.0
| 3,363
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/*
* Auth: Su Hao(suhao@baidu.com)
* Desc: Record the end to end delay
*/
#ifndef BAIDU_DUER_LIBDUER_DEVICE_MODULES_DEVICE_STATUS_LIGHTDUER_DS_LOG_E2E_H
#define BAIDU_DUER_LIBDUER_DEVICE_MODULES_DEVICE_STATUS_LIGHTDUER_DS_LOG_E2E_H
#include "baidu_json.h"
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
DUER_E2E_1ST_WAKEUP,
DUER_E2E_RECORD_FINISH,
DUER_E2E_SEND,
DUER_E2E_RESPONSE,
DUER_E2E_PLAY,
DUER_E2E_CODEC,
#ifdef DUER_SECOND_WAKEUP_ENABLE
DUER_E2E_WAKEUP_SEND_ENQUEUE,
DUER_E2E_WAKEUP_SEND,
DUER_E2E_2ND_WAKEUP,
#endif//DUER_SECOND_WAKEUP_ENABLE
DUER_E2E_EVENT_TOTAL,
} duer_ds_e2e_event_t;
typedef const char* (*duer_ds_e2e_get_dialog_id_cb)(void);
#ifdef DUER_STATISTICS_E2E
void duer_ds_e2e_event(duer_ds_e2e_event_t evt);
void duer_ds_e2e_set_report_codec_timestamp(void);
void duer_ds_e2e_set_not_report_codec_timestamp(void);
void duer_ds_e2e_set_vad_silence_time(duer_u32_t silence_time);
void duer_ds_e2e_set_dialog_id_cb(duer_ds_e2e_get_dialog_id_cb cb);
duer_bool duer_ds_e2e_wait_response(void);
#else
#define duer_ds_e2e_set_report_codec_timestamp(...)
#define duer_ds_e2e_set_not_report_codec_timestamp(...)
#define duer_ds_e2e_set_vad_silence_time(...)
#define duer_ds_e2e_event(...)
#define duer_ds_e2e_set_dialog_id_cb(...)
#define duer_ds_e2e_wait_response(...)
#endif
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIBDUER_DEVICE_MODULES_DEVICE_STATUS_LIGHTDUER_DS_LOG_E2E_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_ds_log_e2e.h
|
C
|
apache-2.0
| 2,119
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/*
* Auth: Gang Chen(chengang12@baidu.com)
* Desc: http module log report
*/
#ifndef BAIDU_DUER_LIGHTDUER_DS_LOG_HTTP_H
#define BAIDU_DUER_LIGHTDUER_DS_LOG_HTTP_H
#ifdef __cplusplus
extern "C" {
#endif
#include "lightduer_types.h"
#include "stdbool.h"
#include "baidu_json.h"
typedef enum {
DUER_DS_LOG_HTTP_INIT = 0x101,
DUER_DS_LOG_HTTP_DESTROYED = 0x102,
DUER_DS_LOG_HTTP_COMMON_ERROR = 0x103,
DUER_DS_LOG_HTTP_PERSISTENT_CONN_TIMEOUT = 0x104,
DUER_DS_LOG_HTTP_DOWNLOAD_STARTED = 0x105,
// Attention: 0x106, 0x107, 0x201 must be reserved, as they had been used in old version SDK
DUER_DS_LOG_HTTP_ZERO_BYTE_DOWNLOAD = 0x202,
DUER_DS_LOG_HTTP_DOWNLOAD_STOPPED = 0x203,
DUER_DS_LOG_HTTP_DOWNLOAD_FINISHED = 0x204,
DUER_DS_LOG_HTTP_SOCKET_CONN_FAILED = 0x301,
DUER_DS_LOG_HTTP_URL_PARSE_FAILED = 0x302,
DUER_DS_LOG_HTTP_SEND_FAILED = 0x303,
DUER_DS_LOG_HTTP_DOWNLOAD_FAILED = 0x304,
DUER_DS_LOG_HTTP_INIT_FAILED = 0x305,
DUER_DS_LOG_HTTP_CONNECT_CLOSED_BY_SERVER = 0x306,
DUER_DS_LOG_HTTP_REQUEST_SEND_FAILED = 0x307,
DUER_DS_LOG_HTTP_HEADER_SEND_FAILED = 0x308,
DUER_DS_LOG_HTTP_RESPONSE_RECEIVE_FAILED = 0x309,
DUER_DS_LOG_HTTP_HEADER_RECEIVE_FAILED = 0x30a,
DUER_DS_LOG_HTTP_CHUNK_SIZE_RECEIVE_FAILED = 0x30b,
DUER_DS_LOG_HTTP_CHUNK_RECEIVE_FAILED = 0x30c,
DUER_DS_LOG_HTTP_CONTENT_RECEIVE_FAILED = 0x30d,
DUER_DS_LOG_HTTP_MEMORY_ERROR = 0x30e,
DUER_DS_LOG_HTTP_PARAM_ERROR = 0x310,
DUER_DS_LOG_HTTP_RECEIVE_FAILED = 0x311,
DUER_DS_LOG_HTTP_REDIRECT_FAILED = 0x312,
DUER_DS_LOG_HTTP_DNS_GET_IP = 0x313,
DUER_DS_LOG_HTTP_TOO_MANY_REDIRECT = 0x314,
DUER_DS_LOG_HTTP_SOCKET_INIT_FAILED = 0x401,
DUER_DS_LOG_HTTP_SOCKET_OPEN_FAILED = 0x402,
} duer_ds_log_http_code_t;
// used to statistic the download info when download finished/stopped/failed
typedef struct {
const char *url;
int ret_code;
size_t upload_size;
size_t download_size;
int download_speed;
int resume_count;
size_t content_len;
bool is_chunked;
} duer_ds_log_http_statistic_t;
/**
* Report ds log for http module
*/
duer_status_t duer_ds_log_http(duer_ds_log_http_code_t log_code, const baidu_json *log_message);
/**
* Report ds log with direction information:
* {
* "file" : "http.c",
* "line" : 100
* }
*/
duer_status_t duer_ds_log_http_report_with_dir(duer_ds_log_http_code_t log_code,
const char *file,
int line);
/**
* Report ds log when http download function is exit, it include the statistic information.
*/
duer_status_t duer_ds_log_http_download_exit(duer_ds_log_http_code_t log_code,
duer_ds_log_http_statistic_t *statistic);
/**
* Report ds log when http persistent is timeout and be closed.
*/
duer_status_t duer_ds_log_http_persisten_conn_timeout(const char *host);
/**
* Report ds log with url:
* {
* "url" : "baidu.com"
* }
*/
duer_status_t duer_ds_log_http_report_with_url(duer_ds_log_http_code_t log_code, const char *url);
/**
* Report ds log with error code:
* {
* "err_code" : -3007
* }
*/
duer_status_t duer_ds_log_http_report_err_code(duer_ds_log_http_code_t log_code, int err_code);
/**
* Report ds log when redirect failed, it include the redirect location:
* {
* "location" : "http://test.com"
* }
*/
duer_status_t duer_ds_log_http_redirect_fail(const char *location);
/**
* Report ds log when redirect too many times, it include the redirect count:
* {
* "redirect_count" : 31
* }
*/
duer_status_t duer_ds_log_http_too_many_redirect(int count);
#define DUER_DS_LOG_REPORT_HTTP_MEMORY_ERROR() \
duer_ds_log_http_report_with_dir(DUER_DS_LOG_HTTP_MEMORY_ERROR, __FILE__, __LINE__)
#define DUER_DS_LOG_REPORT_HTTP_PARAM_ERROR() \
duer_ds_log_http_report_with_dir(DUER_DS_LOG_HTTP_PARAM_ERROR, __FILE__, __LINE__)
#define DUER_DS_LOG_REPORT_HTTP_COMMON_ERROR() \
duer_ds_log_http_report_with_dir(DUER_DS_LOG_HTTP_COMMON_ERROR, __FILE__, __LINE__)
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIGHTDUER_DS_LOG_HTTP_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_ds_log_http.h
|
C
|
apache-2.0
| 5,358
|
/**
* Copyright (2018) Baidu Inc. All rights reserved.
*
* 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.
*/
/*
* Auth: Chen Xihao(chenxihao@baidu.com)
* Desc: power manager module related report log
*/
#ifndef BAIDU_DUER_LIGHTDUER_DS_LOG_PM_H
#define BAIDU_DUER_LIGHTDUER_DS_LOG_PM_H
#include "baidu_json.h"
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum _duer_ds_log_pm_code {
DUER_DS_LOG_PM_SLEEP = 0x201,
DUER_DS_LOG_PM_WAKEUP = 0x202,
} duer_ds_log_pm_code_t;
/**
* common function to report the log of pm
*/
duer_status_t duer_ds_log_pm(duer_ds_log_pm_code_t log_code, const baidu_json *message);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIGHTDUER_DS_LOG_PM_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_ds_log_pm.h
|
C
|
apache-2.0
| 1,256
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/*
* Auth: Yiheng Li(liyiheng01@baidu.com)
* Desc: recorder module log report
*/
#ifndef BAIDU_DUER_LIGHTDUER_DS_LOG_RECORDER_H
#define BAIDU_DUER_LIGHTDUER_DS_LOG_RECORDER_H
#include "lightduer_types.h"
#include "baidu_json.h"
#define REC_LOG_MOD_NAME(name) (#name)
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
DUER_DS_LOG_REC_START = 0x001,
DUER_DS_LOG_REC_STOP = 0x002,
}duer_ds_log_rec_code_t;
/**
* update compress infomation,set start/end = duer_timestamp() before/after compress functions
*/
void duer_ds_rec_compress_info_update(const duer_u32_t start, const duer_u32_t end);
/**
* update compress infomation,set start/end = duer_timestamp() before/after compress functions
*/
void duer_ds_rec_delay_info_update(const duer_u32_t request, const duer_u32_t send_start, const duer_size_t send_finish);
/**
* report the log code DUER_DS_LOG_REC_START
* {
* "id": [session id]
* }
*/
duer_status_t duer_ds_log_rec_start(duer_u32_t id);
/**
* report the message for log code DUER_DS_LOG_REC_STOP
* {
* "id": [session id],
* "speex_compress" : {
* "max" : [maximum consuming time of compressing one frame in speex],
* "min" : [minimum consuming time of compressing one frame in speex],
* "avg" : [average consuming time of compressing one frame in speex]
* },
* "request_delay": {
* "max" : [maximum consuming time of request send a voice fragment in ca],
* "min" : [minimum consuming time of request send a voice fragment in ca],
* "avg" : [average consuming time of request send a voice fragment in ca]
* },
* "network_delay": {
* "max" : [maximum consuming time of socket send a voice fragment],
* "min" : [minimum consuming time of socket send a voice fragment],
* "avg" : [average consuming time of socket send a voice fragment]
* },
* "total_delay": {
* "max" : [maximum consuming time of send a voice fragment],
* "min" : [minimum consuming time of send a voice fragment],
* "avg" : [average consuming time of send a voice fragment]
* },
* }
*/
duer_status_t duer_ds_log_rec_stop(duer_u32_t id);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIGHTDUER_DS_LOG_RECORDER_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_ds_log_recorder.h
|
C
|
apache-2.0
| 2,896
|
/**
* Copyright (2018) Baidu Inc. All rights reserved.
*
* 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.
*/
/*
* Auth: Chen Xihao(chenxihao@baidu.com)
* Desc: SmartConfig related report log
*/
#ifndef BAIDU_DUER_LIGHTDUER_DS_LOG_SMART_CONFIG_H
#define BAIDU_DUER_LIGHTDUER_DS_LOG_SMART_CONFIG_H
#include "baidu_json.h"
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum _duer_ds_log_smart_cfg_code {
DUER_DS_LOG_SMART_CFG_START = 0x201,
DUER_DS_LOG_SMART_CFG_LOCK_CHANNEL = 0x202,
DUER_DS_LOG_SMART_CFG_LEAD_COMPLETED = 0x203,
DUER_DS_LOG_SMART_CFG_FINISHED = 0x204,
DUER_DS_LOG_SMART_CFG_FAILED = 0x401,
} duer_ds_log_smart_cfg_code_t;
typedef struct duer_ds_log_smart_cfg_info_s {
duer_size_t packet_counts;
duer_size_t data_counts;
duer_size_t data_invalids;
duer_size_t decode_counts;
} duer_ds_log_smart_cfg_info_t;
/**
* common function to report the log of smart config
*/
duer_status_t duer_ds_log_smart_cfg(duer_ds_log_smart_cfg_code_t log_code,
const baidu_json *message);
/**
* report the log that smart config receive all lead code
*/
duer_status_t duer_ds_log_smart_cfg_lead_completed(duer_size_t data_len);
/**
* report the log that smart config finished
*/
duer_status_t duer_ds_log_smart_cfg_finished(duer_ds_log_smart_cfg_info_t *info);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIGHTDUER_DS_LOG_SMART_CONFIG_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_ds_log_smart_config.h
|
C
|
apache-2.0
| 1,990
|
/**
* Copyright (2018) Baidu Inc. All rights reserved.
*
* 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.
*/
/*
* Auth: Su Hao(suhao@baidu.com)
* Desc: Sonic decode related report log
*/
#ifndef BAIDU_DUER_LIBDUER_DEVICE_MODULES_DEVICE_STATUS_LIGHTDUER_DS_LOG_SONIC_DECODE_H
#define BAIDU_DUER_LIBDUER_DEVICE_MODULES_DEVICE_STATUS_LIGHTDUER_DS_LOG_SONIC_DECODE_H
#include "baidu_json.h"
#include "lightduer_types.h"
#include "lightduer_math.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum _duer_ds_log_sonic_decode_code {
DUER_DS_LOG_SONICCODEC_DECODE_START = 0x101, // 开始解码 Info 否
DUER_DS_LOG_SONICCODEC_DECODE_FETCHED_START = 0x102, // 接收第一人同步信息 Info 否
DUER_DS_LOG_SONICCODEC_DECODE_BLOCK_ERROR = 0x301, // 收到错误的block Debug 否
DUER_DS_LOG_SONICCODEC_DECODE_FRAGMENT_FETCHED = 0x103,// 收到正确的fragment Debug 否
DUER_DS_LOG_SONICCODEC_DECODE_FRAGMENT_ERROR = 0x302, // 收到错误的fragment Debug 否
DUER_DS_LOG_SONICCODEC_DECODE_FRAME_COMPLETE = 0x104, // 收到完整的Frame Debug 否
DUER_DS_LOG_SONICCODEC_DECODE_FINISH = 0x105, // 解码结束 Info 否
DUER_DS_LOG_SONICCODEC_DECODE_FAILED = 0x303, // 解码失败 Error 否
} duer_ds_log_sonic_decode_code_t;
DUER_INT duer_status_t duer_ds_log_sonicdec_start(void);
DUER_INT duer_status_t duer_ds_log_sonicdec_audio_analysis(const duer_coef_t *data, duer_size_t size);
DUER_INT duer_status_t duer_ds_log_sonicdec_fetched_start(void);
DUER_INT duer_status_t duer_ds_log_sonicdec_block_error(void);
DUER_INT duer_status_t duer_ds_log_sonicdec_fragment_fetched(void);
DUER_INT duer_status_t duer_ds_log_sonicdec_fragment_error(void);
DUER_INT duer_status_t duer_ds_log_sonicdec_frame_complete(int length);
DUER_INT duer_status_t duer_ds_log_sonicdec_finish(void);
DUER_INT duer_status_t duer_ds_log_sonicdec_failed(void);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIBDUER_DEVICE_MODULES_DEVICE_STATUS_LIGHTDUER_DS_LOG_SONIC_DECODE_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_ds_log_sonic_decode.h
|
C
|
apache-2.0
| 2,575
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/*
* Auth: Gang Chen(chengang12@baidu.com)
* Desc: Save the ds log to ROM.
*/
#ifndef BAIDU_DUER_LIGHTDUER_DS_LOG_STORAGE_H
#define BAIDU_DUER_LIGHTDUER_DS_LOG_STORAGE_H
#ifdef DUER_DS_LOG_STORAGE_ENABLED
#ifdef __cplusplus
extern "C" {
#endif
#include "lightduer_types.h"
#include "lightduer_flash_ring_buf.h"
duer_status_t duer_ds_log_storage_push(const char *log);
duer_status_t duer_ds_log_storage_send(void);
duer_status_t duer_ds_log_storage_init(duer_flash_context_t *ctx,
duer_flash_config_t *config);
#ifdef __cplusplus
}
#endif
#endif // DUER_DS_LOG_STORAGE_ENABLED
#endif // BAIDU_DUER_LIGHTDUER_DS_LOG_STORAGE_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_ds_log_storage.h
|
C
|
apache-2.0
| 1,291
|
/**
* Copyright (2018) Baidu Inc. All rights reserved.
*
* 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.
*/
/*
* Auth: Chen Xihao(chenxihao@baidu.com)
* Desc: wifi config related report log
*/
#ifndef BAIDU_DUER_LIGHTDUER_DS_LOG_WIFI_CONFIG_H
#define BAIDU_DUER_LIGHTDUER_DS_LOG_WIFI_CONFIG_H
#include "baidu_json.h"
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum _duer_ds_log_wifi_cfg_code {
DUER_DS_LOG_WIFI_CFG_START = 0x101,
DUER_DS_LOG_WIFI_CFG_SCAN_RESLUTS = 0x102,
DUER_DS_LOG_WIFI_CFG_LOCKED = 0x103,
DUER_DS_LOG_WIFI_CFG_CONNECTING = 0x104,
DUER_DS_LOG_WIFI_CFG_CONNECTED = 0x105,
DUER_DS_LOG_WIFI_CFG_FINISHED = 0x106,
DUER_DS_LOG_WIFI_CFG_TIMEOUT = 0x401,
DUER_DS_LOG_WIFI_CFG_FAILED = 0x402,
} duer_ds_log_wifi_cfg_code_t;
typedef enum _duer_wifi_cfg_err_code {
DUER_WIFI_CFG_SUCCESS = 0,
DUER_WIFI_CFG_STOP = 1,
DUER_WIFI_CFG_ERR_NORMAL = 2,
DUER_WIFI_CFG_ERR_NO_MEMORY = 3,
DUER_WIFI_CFG_ERR_SSID_INVALID = 4,
DUER_WIFI_CFG_ERR_HANDSHARK = 5,
} duer_wifi_cfg_err_code_t;
typedef enum _duer_wifi_cfg_method {
DUER_WIFI_CFG_UNKOWN = 0,
DUER_WIFI_CFG_AIRKISS = 1,
DUER_WIFI_CFG_SMART_CONFIG = 2,
DUER_WIFI_CFG_SONIC = 3,
DUER_WIFI_CFG_BLUE_TOOTH = 4,
} duer_wifi_cfg_method_t;
#define CHECK_WIFI_CFG_ID() \
if (duer_ds_log_wifi_cfg_get_id() == 0) { \
DUER_LOGE("should call duer_ds_log_wifi_cfg_start first"); \
return DUER_ERR_FAILED; \
}
/**
* common function to report the log of wifi config
*/
duer_status_t duer_ds_log_wifi_cfg(duer_ds_log_wifi_cfg_code_t log_code,
const baidu_json *message);
/**
* report the log that wifi config start
*/
duer_status_t duer_ds_log_wifi_cfg_start(void);
/**
* report the message for log code DUER_DS_LOG_WIFI_CFG_SCAN_RESLUTS
* {
* "list": [
* "SSID名称1", "SSID名称2", ...
* ],
* }
*/
duer_status_t duer_ds_log_wifi_cfg_scan_resluts(const char **ssids, duer_size_t num);
/**
* report the log that wifi config finished
*/
duer_status_t duer_ds_log_wifi_cfg_finished(duer_wifi_cfg_err_code_t code,
duer_wifi_cfg_method_t method);
/**
* report the log that wifi config failed
*/
duer_status_t duer_ds_log_wifi_cfg_failed(duer_wifi_cfg_err_code_t err_code, int rssi);
/**
* get the id of wifi config
*/
int duer_ds_log_wifi_cfg_get_id(void);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIGHTDUER_DS_LOG_WIFI_CONFIG_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_ds_log_wifi_config.h
|
C
|
apache-2.0
| 3,180
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/*
* Auth: Leliang Zhang(zhangleliang@baidu.com)
* Desc: device status report
*/
#ifndef BAIDU_DUER_LIGHTDUER_DS_REPORT_H
#define BAIDU_DUER_LIGHTDUER_DS_REPORT_H
#include "baidu_json.h"
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* the return baidu_json* will be handled by the caller
* so the callee should not try to release the baidu_json*
*/
typedef baidu_json* (*duer_ds_report_function_t)(void);
typedef enum _duer_ds_report_type_enum {
DUER_DS_ONCE, // report only once
DUER_DS_PERIODIC, // report periodically
DUER_DS_TOTAL
} duer_ds_report_type_enum_t;
/**
* all the register functions will be invoked when try to report the device status.
* all the modules which have status to report should call this to register the
* functions.
*/
duer_status_t duer_ds_register_report_function(duer_ds_report_function_t report_function);
/**
* initiate a device status report, DUER_DS_ONCE or DUER_DS_PERIODIC decided by type
* if the periodic timer already started, stop it , restart it with the new interval
* @param type, DUER_DS_ONCE or DUER_DS_PERIODIC
* @param interval, if the report type is DUER_DS_PERIODIC, then this indicate the interval
* 0, means use the default value, now is 5min
* @return, DUER_OK on success, or failed
* report format:
* duer_device_status contains an array
* all the info collect from the functions registed is one item in the array.
* {
* "duer_device_status": [
* {
* "avg_connect_time": "500ms",
* "disconnect_count": 0
* },
* {
* "upload_size": "10Bytes",
* "down_size": "20Bytes"
* }
* ]
* }
*/
duer_status_t duer_ds_report_start(duer_ds_report_type_enum_t type, duer_u32_t interval);
/**
* try to stop the periodic report.
*/
duer_status_t duer_ds_report_stop(void);
/**
* try to destroy report list.
*/
duer_status_t duer_ds_report_destroy(void);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIGHTDUER_DS_REPORT_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_ds_report.h
|
C
|
apache-2.0
| 2,720
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/*
* Auth: Leliang Zhang(zhangleliang@baidu.com)
* Desc: device status ca report
*/
#ifndef BAIDU_DUER_LIGHTDUER_DS_REPORT_CA_H
#define BAIDU_DUER_LIGHTDUER_DS_REPORT_CA_H
#include "baidu_json.h"
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
duer_status_t duer_ds_report_ca_update_avg_latency(duer_u32_t al);
duer_status_t duer_ds_report_ca_update_send_max_packet(duer_u32_t smp);
duer_status_t duer_ds_report_ca_inc_valid_recv(void);
duer_status_t duer_ds_report_ca_inc_recv_count(void);
duer_status_t duer_ds_report_ca_update_recv_max_packet(duer_u32_t rmp);
duer_status_t duer_ds_report_ca_inc_error_mbedtls(void);
duer_status_t duer_ds_report_ca_inc_error_tcpheader(void);
duer_status_t duer_ds_report_ca_inc_error_coap(void);
duer_status_t duer_ds_report_ca_inc_error_connect(void);
/**
* generate the ca status report
* this function used in @duer_ds_register_report_function
* "ca_status": {
* "connection": {
* "disconnect_time": 100,
* "max_connect": 200,
* "reconnect_count": 2
* },
* "send": {
* "avg_latency": 20,
* "max_packet": 1900
* },
* "recv": {
* "valid_recv": 800,
* "recv_count": 1000,
* "max_packet": 1900
* },
* "error": {
* "mbedtls": 0,
* "tcp_header": 0,
* "coap": 0,
* "connect_fail": 0
* }
* }
*/
baidu_json* duer_ds_report_ca_status(void);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIGHTDUER_DS_REPORT_CA_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_ds_report_ca.h
|
C
|
apache-2.0
| 2,153
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/**
* File: lightduer_engine.h
* Auth: Su Hao (suhao@baidu.com)
* Desc: Light duer IoT CA engine.
*/
#ifndef BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_ENGINE_H
#define BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_ENGINE_H
#include "baidu_json.h"
#include "lightduer_types.h"
#include "lightduer_coap_defs.h"
#ifdef __cplusplus
extern "C" {
#endif
enum duer_engine_events_enum {
DUER_EVT_CREATE,
DUER_EVT_START,
DUER_EVT_ADD_RESOURCES,
DUER_EVT_SEND_DATA,
DUER_EVT_DATA_AVAILABLE,
DUER_EVT_STOP,
DUER_EVT_DESTROY,
DUER_EVENTS_TOTAL
};
typedef void (*duer_engine_notify_func)(int event, int status, int what, void *object);
void duer_engine_register_notify(duer_engine_notify_func func);
void duer_engine_create(int what, void *object);
void duer_engine_set_response_callback(int what, void *object);
void duer_engine_start(int what, void *object);
void duer_engine_add_resources(int what, void *object);
void duer_engine_data_available(int what, void *object);
int duer_engine_enqueue_report_data(duer_context_t *context, const baidu_json *data);
void duer_engine_send(int what, void *object);
void duer_engine_stop(int what, void *object);
void duer_engine_destroy(int what, void *object);
int duer_engine_qcache_length(void);
duer_bool duer_engine_is_started(void);
void duer_engine_clear_data(int what, void *object);
const char *duer_engine_get_uuid(void);
const char *duer_engine_get_bind_token(void);
const char *duer_engine_get_rsa_cacrt(void);
#ifdef __cplusplus
}
#endif
#endif/*BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_ENGINE_H*/
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_engine.h
|
C
|
apache-2.0
| 2,203
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
// Author: Zhang Leliang (zhangleliang@baidu.com)
//
// Description: parser for the args
#ifndef BAIDU_DUER_LIBDUER_DEVICE_MODULES_CONNAGNET_LIGHTDUER_EVENT_EMITTER_H
#define BAIDU_DUER_LIBDUER_DEVICE_MODULES_CONNAGNET_LIGHTDUER_EVENT_EMITTER_H
#include "lightduer_events.h"
#ifdef __cplusplus
extern "C" {
#endif
void duer_emitter_create(void);
int duer_emitter_emit(duer_events_func func, int what, void *object);
void duer_emitter_destroy(void);
#ifdef __cplusplus
}
#endif
#endif/*BAIDU_DUER_LIBDUER_DEVICE_MODULES_CONNAGNET_LIGHTDUER_EVENT_EMITTER_H*/
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_event_emitter.h
|
C
|
apache-2.0
| 1,181
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/**
* File: lightduer_events.h
* Auth: Su Hao (suhao@baidu.com)
* Desc: Light duer events looper.
*/
#ifndef BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_EVENTS_H
#define BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_EVENTS_H
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef void (*duer_events_func)(int what, void *object);
typedef struct _duer_event_status_message_s {
int _status;
duer_events_func _func;
int _what;
void * _object;
} duer_evtst_message_t;
typedef void *duer_events_handler;
duer_events_handler duer_events_create(const char *name, size_t stack_size, size_t queue_length);
duer_events_handler duer_events_create_with_priority(const char *name, size_t stack_size,
size_t queue_length, int priority);
int duer_events_call(duer_events_handler handler, duer_events_func func, int what, void *object);
void duer_events_destroy(duer_events_handler handler);
#ifdef __cplusplus
}
#endif
#endif/*BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_EVENTS_H*/
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_events.h
|
C
|
apache-2.0
| 1,720
|
/**
* Copyright (2018) Baidu Inc. All rights reserved.
*
* 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.
*/
// Author: Chen Yun (chenyun08@baidu.com)
//
// Description: Wrapper for file operation.
#ifndef BAIDU_DUER_LIBDUER_DEVICE_FRAMEWORK_CORE_LIGHTDUER_FILE_H
#define BAIDU_DUER_LIBDUER_DEVICE_FRAMEWORK_CORE_LIGHTDUER_FILE_H
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef void *duer_file_t;
/*
* The file system operation callbacks
*/
typedef duer_file_t (*duer_fs_open)(const char *filename, const char *mode);
typedef size_t (*duer_fs_read)(void *buffer, size_t size, size_t count, duer_file_t stream);
typedef size_t (*duer_fs_write)(const void *buffer, size_t size, size_t count, duer_file_t stream);
typedef long(*duer_fs_size)(duer_file_t stream);
typedef int (*duer_fs_seek)(duer_file_t stream, long offset, int origin);
typedef long(*duer_fs_tell)(duer_file_t stream);
typedef int (*duer_fs_close)(duer_file_t stream);
/*
* Initial the file system callbacks for file opeation
*
* @Param f_open, open file
* @Param f_read, read block of data from stream
* @Param f_write, write block of data to stream
* @Param f_seek, reposition stream position indicator
* @Param f_tell, get current position in stream
* @Param f_close, close file
*/
DUER_EXT void duer_file_init(duer_fs_open f_open,
duer_fs_read f_read,
duer_fs_write f_write,
duer_fs_size f_size,
duer_fs_seek f_seek,
duer_fs_tell f_tell,
duer_fs_close f_close);
/*
* @describe Opens the file whose name is specified in the parameter filename and associates
* it with a stream that can be identified in future operations by the FILE pointer returned.
* @Param filename, C string containing the name of the file to be opened.Its value shall
* follow the file name specifications of the running environment and can include a path
* (if supported by the system).
* @Param mode,C string containing a file access mode. It can be:"r" read: Open file for
* input operations. The file must exist."w" write: Create an empty file for output operations.
* If a file with the same name already exists, its contents are discarded and the file is
* treated as a new empty file."a" append: Open file for output at the end of a file. Output
* operations always write data at the end of the file, expanding it. Repositioning operations
* (fseek, fsetpos, rewind) are ignored. The file is created if it does not exist."r+" read/update:
* Open a file for update (both for input and output). The file must exist.
* "w+" write/update: Create an empty file and open it for update (both for input and output). If a file with the same
* name already exists its contents are discarded and the file is treated as a new empty file.
* "a+" append/update: Open a file for update (both for input and output) with all output operations writing data at the
* end of the file. Repositioning operations (fseek, fsetpos, rewind) affects the next input operations, but output operations
* move the position back to the end of file. The file is created if it does not exist.
* @Return If the file is successfully opened, the function returns a pointer to a FILE object that can be used to identify
* the stream on future operations.Otherwise, a null pointer is returned.
*/
DUER_EXT duer_file_t duer_file_open(const char *filename, const char *mode);
/*
* @describe Read block of data from stream
* @Param buffer, Pointer to a block of memory with a size of at least (size*count) bytes, converted to a void*.
* @Param size, in bytes, of each element to be read.size_t is an unsigned integral type.
* @Param count,Number of elements, each one with a size of size bytes.size_t is an unsigned integral type.
* @Param, Pointer to a FILE object that specifies an input stream.
* @Return The total number of elements successfully read is returned.
*/
DUER_EXT size_t duer_file_read(void *buffer,
size_t size,
size_t count,
duer_file_t stream);
/*
* @describe Write block of data to stream
* @Param buffer, Pointer to the array of elements to be written, converted to a const void*.
* @Param size, Size in bytes of each element to be written.size_t is an unsigned integral type.
* @Param count,Number of elements, each one with a size of size bytes.size_t is an unsigned integral type.
* @Param, Pointer to a FILE object that specifies an output stream.
* @Return The total number of elements successfully written is returned.
*/
DUER_EXT size_t duer_file_write(const void *buffer,
size_t size,
size_t count,
duer_file_t stream);
/*
* @describe gets the size of a file.
* @Param stream, Pointer to the open file object structure.
* @Return Returns the size of the file in unit of byte.
*/
DUER_EXT long duer_file_size(duer_file_t stream);
/*
* @describe Sets the position indicator associated with the stream to a new position.
* @Param stream,pointer to a FILE object that identifies the stream.
* @Param offset,Binary files: Number of bytes to offset from origin.Text files: Either zero, or a value returned by ftell.
* @Param origin,Position used as reference for the offset. It is specified by one of the following constants defined
* in <cstdio> exclusively to be used as arguments for this function:
* Constant Reference position
* SEEK_SET Beginning of file
* SEEK_CUR Current position of the file pointer
* SEEK_END End of file *
* @Return if successful, the function returns zero.Otherwise, it returns non-zero value.
*/
DUER_EXT int duer_file_seek(duer_file_t stream, long offset, int origin);
/*
* @describe returns the current value of the position indicator of the stream.
* @Param stream, pointer to a FILE object that identifies the stream.
* @Return On success, the current value of the position indicator is returned.
* On failure, -1L is returned, and errno is set to a system-specific positive value.
*/
DUER_EXT long duer_file_tell(duer_file_t stream);
/*
* @describe closes the file associated with the stream and disassociates it.
* @Param stream, pointer to a FILE object that specifies the stream to be closed.
* @Return if the stream is successfully closed, a zero value is returned.
* On failure, EOF is returned.
*/
DUER_EXT int duer_file_close(duer_file_t stream);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIBDUER_DEVICE_FRAMEWORK_CORE_LIGHTDUER_FILE_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_file.h
|
C
|
apache-2.0
| 7,281
|
// Copyright (2018) Baidu Inc. All rights reserved.
/**
* File: lightduer_flash.h
* Auth: Sijun Li(lisijun@baidu.com)
* Desc: Common defines for flash strings module.
*/
#ifndef BAIDU_DUER_LIGHTDUER_FLASH_H
#define BAIDU_DUER_LIGHTDUER_FLASH_H
#ifdef __cplusplus
extern "C" {
#endif
#include "lightduer_types.h"
#define FLASH_MAGIC 0x56BD50C4
#define FLASH_MAGIC_BITMASK 0xffffffff
#define FLASH_LEN_BITMASK 0xffffffff
#define FLASH_INVALID_ADDR 0xffffffff
typedef enum {
DUER_ERR_FLASH_CORRUPT = -2,
DUER_ERR_FLASH_FULL = -3,
}duer_flash_errcode;
/*
* Configuration of flash operations.
* xxx_align_bits: Number of last bits of address to be aligned.
* For example, Bits=5 indicates header's last 5 bits are '0'.
*/
typedef struct {
// For erase.
int sector_align_bits;
// For write.
int page_align_bits;
// For read.
int word_align_bits;
} duer_flash_config_t;
typedef struct {
void *handle;
unsigned int len;
void *object;
} duer_flash_context_t;
typedef struct {
unsigned int magic; // Magic number to check data valid;
unsigned int len; // Length of payload string;
// Used to know the sequence of the data in the flash, it's used in flash ring buf
unsigned int sequence_num;
} duer_flash_data_header;
inline unsigned int flash_addr_align_floor(unsigned int addr, int bits) {
addr >>= bits;
addr <<= bits;
return addr;
}
inline unsigned int flash_addr_align_ceil(unsigned int addr, int bits) {
unsigned int bitmask = (1 << bits) - 1;
if (addr & bitmask) {
addr >>= bits;
addr += 1;
addr <<= bits;
}
return addr;
}
inline unsigned int flash_addr_cycle(unsigned int addr, int size) {
if (addr >= size) {
return (addr - size);
} else {
return addr;
}
}
/**
* DESC:
* Developer needs to implement this interface to read flash.
*
* @PARAM[in] ctx: pointer of context.
* @PARAM[in] addr: the address offset of flash to read.
* @PARAM[out] buf: the buffer to store read data.
* @PARAM[in] len: length of byte to read.
*
* @RETURN: 0 when success, else when fail.
*/
extern int duer_flash_read(
duer_flash_context_t *ctx,
unsigned int addr,
void *buf,
unsigned int len);
/**
* DESC:
* Developer needs to implement this interface to write flash.
*
* @PARAM[in] ctx: pointer of context.
* @PARAM[in] addr: the address offset of flash to write.
* @PARAM[in] buf: the buffer stored writing data.
* @PARAM[in] len: length of byte to write.
*
* @RETURN: 0 when success, else when fail.
*/
extern int duer_flash_write(
duer_flash_context_t *ctx,
unsigned int addr,
void *buf,
unsigned int len);
/**
* DESC:
* Developer needs to implement this interface to erase flash.
*
* @PARAM[in] ctx: pointer of context.
* @PARAM[in] addr: the address offset start of flash to erase.
* @PARAM[in] len: length of byte to erase.
*
* @RETURN: 0 when success, else when fail.
*/
extern int duer_flash_erase(
duer_flash_context_t *ctx,
unsigned int addr,
unsigned int len);
int duer_payload_write_flash(
duer_flash_context_t *ctx,
unsigned int addr_start,
duer_flash_data_header *p_flash_header,
const char *payload_string,
int payload_len,
int page_size);
#ifdef __cplusplus
}
#endif
#endif//BAIDU_DUER_LIGHTDUER_FLASH_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_flash.h
|
C
|
apache-2.0
| 3,511
|
// Copyright (2018) Baidu Inc. All rights reserved.
/**
* File: lightduer_flash_ring_buf.h
* Auth: Gang Chen(chengang12@baidu.com)
* Desc: APIs of store string list to flash.
*/
#ifndef BAIDU_DUER_LIGHTDUER_FLASH_RING_BUF_H
#define BAIDU_DUER_LIGHTDUER_FLASH_RING_BUF_H
#ifdef __cplusplus
extern "C" {
#endif
#include "lightduer_types.h"
#include "lightduer_flash.h"
typedef struct {
duer_flash_context_t ctx;
int ele_count;
unsigned int sequence_num;
unsigned int ele_header;
unsigned int ele_tail;
} duer_flash_ring_buf_context_t;
/**
* DESC:
* Should be called in duer_flash_init,
* This function will only take effect when first time called.
*
* PARAM config: configuration of hardware flash.
*
* @RETURN: none
*/
extern void duer_flash_ring_buf_set_config(const duer_flash_config_t *config);
void duer_flash_ring_buf_load(duer_flash_ring_buf_context_t *ctx);
char *duer_flash_ring_buf_top(duer_flash_ring_buf_context_t *ctx);
duer_status_t duer_flash_ring_buf_header_remove(duer_flash_ring_buf_context_t *ctx);
duer_status_t duer_flash_ring_buf_append(duer_flash_ring_buf_context_t *ctx, const char *msg);
#ifdef __cplusplus
}
#endif
#endif//BAIDU_DUER_LIGHTDUER_FLASH_RING_BUF_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_flash_ring_buf.h
|
C
|
apache-2.0
| 1,228
|
// Copyright (2018) Baidu Inc. All rights reserved.
/**
* File: lightduer_flash_strings.h
* Auth: Sijun Li(lisijun@baidu.com)
* Desc: APIs of store string list to flash.
*/
#ifndef BAIDU_DUER_LIGHTDUER_FLASH_STRINGS_H
#define BAIDU_DUER_LIGHTDUER_FLASH_STRINGS_H
#ifdef __cplusplus
extern "C" {
#endif
#include "lightduer_flash.h"
typedef enum {
ALARM_FLASH = 0,
MAX_FLASH_MODULE = 1,
}duer_flash_module;
typedef struct {
duer_flash_context_t ctx;
int max_ele_count;
unsigned int *ele_list;
} duer_flash_string_context_t;
typedef char *(*duer_raw2string_func)(void *);
typedef void (*duer_free_string_func)(char *);
// Need users to implement to adapt different platform.
/**
* DESC:
* Developer needs to implement this interface to init flash context.
* Must call duer_set_flash_config in this function.
*
* @PARAM[in] module: selected module, corresponding to context.
*
* @RETURN: pointer of created context.
*/
extern duer_flash_string_context_t *duer_flash_init(duer_flash_module module);
/**
* DESC:
* Should be called in duer_flash_init,
* This function will only take effect when first time called.
*
* PARAM config: configuration of hardware flash.
*
* @RETURN: none
*/
extern void duer_set_flash_config(const duer_flash_config_t *config);
// High level APIs.
/**
* DESC:
* Append one flash string element to flash data. if flash data is empty, the element will be
* written to the begining of flash addr (address offset = 0).
*
* @PARAM[in] ctx: pointer of context.
* @PARAM[in] raw_data: raw data of element needs to store to flash.
* @PARAM[in] raw2string_func: function to convert raw_data to string. if this param is NULL,
* treat raw_data as a string.
* @PARAM[in] free_string_func: function to free the string created by raw2string_func. Must
* not NULL when raw2string_func not NULL.
*
* @RETURN: 0 when success, else when fail.
*/
extern int duer_append_to_flash(
duer_flash_string_context_t *ctx,
void *raw_data,
duer_raw2string_func raw2string_func,
duer_free_string_func free_string_func);
/**
* DESC:
* Get the first and last flash element address offset, and reset the status in ctx.
* MUST be called before duer_update_to_flash.
*
* @PARAM[in] ctx: pointer of context.
* @PARAM[out] p_first_ele_addr: the address offset of frist flash element.
* @PARAM[out] p_last_ele_addr: the address offset of last flash element.
*
* @RETURN: none
*/
extern void duer_update_to_flash_prepare(
duer_flash_string_context_t *ctx,
unsigned int *p_first_ele_addr,
unsigned int *p_last_ele_addr);
/**
* DESC:
* Update to add one flash string element.
* MUST be called before duer_update_to_flash.
*
* @PARAM[in] ctx: pointer of context.
* @PARAM[in] raw_data: raw data of element needs to store to flash.
* @PARAM[in] raw2string_func: function to convert raw_data to string. if this param is NULL,
* treat raw_data as a string.
* @PARAM[in] free_string_func: function to free the string created by raw2string_func. Must
* not NULL when raw2string_func not NULL.
* @PARAM[out] p_last_ele_addr: new address offset of last flash element, after updating.
* this value will be used when updating next element.
*
* @RETURN: 0 when success, else when fail.
*/
extern int duer_update_to_flash(
duer_flash_string_context_t *ctx,
void *raw_data,
duer_raw2string_func raw2string_func,
duer_free_string_func free_string_func,
unsigned int *p_last_ele_addr);
/**
* DESC:
* Update the flash header, to mark the data added via duer_update_to_flash as new data,
* and mark as old data as deleted.
* Must be called after all elements updated to flash.
*
* Note: we keep this function out of duer_update_to_flash to prevent data lossing. For example,
* if hardware reboot when updating flash, the old data will still be stored in flash
* because the header havn't updated.
*
* @PARAM[in] ctx: pointer of context.
* @PARAM[in] raw_data: raw data of element needs to store to flash.
* @PARAM[in] raw2string_func: function to convert raw_data to string. if this param is NULL,
* treat raw_data as a string.
* @PARAM[in] free_string_func: function to free the string created by raw2string_func. Must
* not NULL when raw2string_func not NULL.
* @PARAM[out] p_last_ele_addr: new address offset of last flash element, after updating.
* this value will be used when updating next element.
*
* @RETURN: 0 when success, else when fail.
*/
extern void duer_update_flash_header(
duer_flash_string_context_t *ctx,
unsigned int first_ele_addr);
/**
* DESC:
* Scan the flash area to retrieve flash element's address, and store in ctx.
*
* @PARAM[in] ctx: pointer of context.
*
* @RETURN: none
*/
extern void duer_get_all_ele_from_flash(
duer_flash_string_context_t *ctx);
/**
* DESC:
* Get flash header of element, to retrieve information of element, like string length.
* SHOULD be called before duer_parse_flash_ele_to_string.
*
* @PARAM[in] ctx: pointer of context.
* @PARAM[in] flash_index: index of flash element to get.
* @PARAM[out] p_header: pointer to store header output.
*
* @RETURN: 0 when success, else when fail.
*/
extern int duer_get_flash_header(
duer_flash_string_context_t *ctx,
unsigned int flash_index,
duer_flash_data_header *p_header);
/**
* DESC:
* Get the string value of flash element.
*
* @PARAM[in] ctx: pointer of context.
* @PARAM[in] flash_index: index of flash element to get.
* @PARAM[in] header: flash header value.
* @PARAM[out] payload_string: buffer to store string output. Must allocate memory according to
* length value stored in header, before call this function.
*
* @RETURN: 0 when success, else when fail.
*/
extern void duer_parse_flash_ele_to_string(
duer_flash_string_context_t *ctx,
unsigned int flash_index,
duer_flash_data_header data,
char *payload_string);
#ifdef __cplusplus
}
#endif
#endif//BAIDU_DUER_LIGHTDUER_FLASH_STRINGS_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_flash_strings.h
|
C
|
apache-2.0
| 6,233
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/**
* File: lightduer_http_client.h
* Author: Pan Haijun, Gang Chen(chengang12@baidu.com)
* Desc: HTTP Client Head File
*/
#ifndef BAIDU_DUER_LIGHTDUER_HTTP_CLIENT_H
#define BAIDU_DUER_LIGHTDUER_HTTP_CLIENT_H
#include <stdlib.h>
#include <stdio.h>
#include "lightduer_timers.h"
#ifdef __cplusplus
extern "C" {
#endif
#define DUER_HTTP_CONTENT_TYPE_LEN_MAX (32) // the max length of "content type" section
//http client results
typedef enum {
DUER_HTTP_ERR_FAILED = -1,
DUER_HTTP_OK, // Success
DUER_HTTP_PROCESSING, // Processing
DUER_HTTP_ERR_PARSE, // url Parse error
DUER_HTTP_ERR_DNS, // Could not resolve name
DUER_HTTP_ERR_PRTCL, // Protocol error
DUER_HTTP_ERR_NOT_FOUND, // HTTP 404 Error
DUER_HTTP_ERR_REFUSED, // HTTP 403 Error
DUER_HTTP_ERR_TIMEOUT, // Connection timeout
DUER_HTTP_ERR_CONNECT, // Connection error
DUER_HTTP_CLOSED, // Connection was closed by remote host
DUER_HTTP_ERR_NOT_SUPPORT, // not supported feature
DUER_HTTP_REDIRECTTION, // take a redirection when http header contains 'Location'
DUER_HTTP_TOO_MANY_REDIRECT, // redirect too many times
} duer_http_result_t;
typedef enum {
DUER_HTTP_GET, // Just 'GET' is supported, other methods are reserved
DUER_HTTP_POST, // reserved
DUER_HTTP_PUT, // reserved
DUER_HTTP_DELETE, // reserved
DUER_HTTP_HEAD // reserved
} duer_http_method_t;
typedef struct {
duer_handler n_handle;
duer_handler (*init)(void *socket_args);
int (*open)(duer_handler socket_handle);
int (*connect)(duer_handler socket_handle, const char *host, const int port);
void (*set_blocking)(duer_handler socket_handle, int blocking);
void (*set_timeout)(duer_handler socket_handle, int timeout);
int (*recv)(duer_handler socket_handle, void *data, unsigned size);
int (*send)(duer_handler socket_handle, const void *data, unsigned size);
int (*close)(duer_handler socket_handle);
void (*destroy)(duer_handler socket_handle);
} duer_http_socket_ops_t;
//to tell data output callback user that if the current data block is first block or last block
typedef enum {
DUER_HTTP_DATA_FIRST = 0x1,
DUER_HTTP_DATA_MID = 0x2,
DUER_HTTP_DATA_LAST = 0x4
} duer_http_data_pos_t;
/**
*
* DESC:
* the callback to handler the data download by http
*
* PARAM:
* @param[in] p_user_ctx: usr ctx registed by user
* @param[in] pos: to identify if it is data stream's start, or middle , or end of data stream
* @param[in] buf: buffer stored media data
* @param[in] len: data length in 'buf'
* @param[in] type: data type to identify media or others
*
* @RETURN: negative number when failed
*/
typedef int (*duer_http_data_handler)(void *p_user_ctx, duer_http_data_pos_t pos,
const char *buf, size_t len, const char *type);
/**
* DESC:
* sometimes other module need to know which url is used to download data.
* this callback is used to get the url
*
* PARAM:
* @param[in] p_user_ctx: usr ctx registed by user
* @param[in] url: the url used by http to download data
*
* RETURN: none
*/
typedef void (*duer_http_get_url_cb_t)(void *p_user_ctx, const char *url);
typedef struct {
const char **pps_custom_headers;
size_t sz_headers_count;
int n_http_response_code; // http response code
duer_http_socket_ops_t ops; // socket operations
int scheme; // http or https type,1 is https, 0 is http
duer_http_data_handler data_hdlr_cb; // callback for output data
void *p_data_hdlr_ctx; // users args for data_hdlr_cb
int n_http_content_len; // http content length
// http content type
char p_http_content_type[DUER_HTTP_CONTENT_TYPE_LEN_MAX];
char *p_location; // http header "Location"
int stop_flag;
// to get the url used to download, the last url will be returned if 302 location happen
duer_http_get_url_cb_t get_url_cb;
int n_is_chunked;
size_t sz_chunk_size;
char *p_chunk_buf;
size_t recv_size; // size of the data have been dwonload
// the count of http continuously try to resume from break-point
int resume_retry_count;
char *buf; // buf used to receive data
duer_http_data_pos_t data_pos; // play position
char *last_host; // the lastest connected host
unsigned short last_port; // the lastest connected port
duer_timer_handler connect_keep_timer; // used to close persistent connect
size_t upload_size; // size of the data have been upload
} duer_http_client_t;
/**
* DESC:
* init the http client
*
* PARAM:
* @param[in] p_client: pointer of the http client
*
* RETURN: DUER_HTTP_OK if success, DUER_HTTP_ERR_FAILED if failed
*/
duer_http_result_t duer_http_init(duer_http_client_t *p_client);
/**
* DESC:
* destroy the http client
*
* PARAM:
* @param[in] p_client: pointer of the http client
*
* RETURN: none
*/
void duer_http_destroy(duer_http_client_t *p_client);
/**
* DESC:
* to init http client socket operations
*
* PARAM:
* @param[in] p_client: pointer of the http client
* @param[in] p_ops: socket operations set
* @param[in] socket_args: args for ops "get_inst"
*
* RETURN: DUER_HTTP_OK if success, DUER_HTTP_ERR_FAILED if failed
*/
duer_http_result_t duer_http_init_socket_ops(duer_http_client_t *p_client,
duer_http_socket_ops_t *p_ops,
void *socket_args);
/**
* DESC:
* register data output handler callback to handle data block
*
* @param[in] p_client: pointer of the http client
* @param[in] data_hdlr_cb: data output handler callback to be registered
* @param[in] p_usr_ctx: user context for data output handler
*
* @RETURN none
*/
void duer_http_reg_data_hdlr(duer_http_client_t *p_client,
duer_http_data_handler data_hdlr_cb,
void *p_usr_ctx);
/**
*
* DESC:
* register callback to get the url which is used by http to get data
*
* PARAM:
* @param[in] p_client: pointer point to the duer_http_client_t
* @param[in] cb: the callback to be registered
*
* @RETURN none
*/
void duer_http_reg_url_get_cb(duer_http_client_t *p_client, duer_http_get_url_cb_t cb);
/**
* DESC:
* Set custom headers for request.
* Pass NULL, 0 to turn off custom headers.
*
* PARAM:
* @param[in] p_client: pointer point to the duer_http_client_t
* @param[in] headers: an array (size multiple of two) key-value pairs,
* must remain valid during the whole HTTP session
* const char * hdrs[] =
* {
* "Connection", "keep-alive",
* "Accept", "text/html",
* "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64)",
* "Accept-Encoding", "gzip,deflate,sdch",
* "Accept-Language", "en-US,en;q=0.8",
* };
*
* duer_http_set_cust_headers(hdrs, 5);
* @param[in] pairs: number of key-value pairs
*
* @RETURN none
*/
void duer_http_set_cust_headers(duer_http_client_t *p_client, const char **headers, size_t pairs);
/**
* DESC:
* get data by http client
*
* PARAM:
* @param[in] p_client: pointer point to the duer_http_client_t
* @param[in] url: url resource
* @param[in] pos: the position to receive the http data,
* sometimes user only want to get part of the data
* @param[in] connect_keep_time: how long time the connection should be kept after download finish
*
* RETURN DUER_HTTP_OK if success, other duer_http_result_t type code if failed
*/
duer_http_result_t duer_http_get(duer_http_client_t *p_client,
const char *url,
const size_t pos,
const int connect_keep_time);
/**
* DESC:
* get http response code
*
* PARAM:
* @param[in] p_client: pointer point to the duer_http_client_t
*
* @RETURN none
*/
int duer_http_get_rsp_code(duer_http_client_t *p_client);
/**
* DESC:
* Notify the http module to stop download.
*
* @param[in] p_client: pointer of the http client
*
* @RETURN none
*/
void duer_http_stop_notify(duer_http_client_t *p_client);
/**
* DESC:
* get http download progress
*
* PARAM:
* @param[in] p_client: pointer point to the duer_http_client_t
* @param[out] total_size: pointer point to a varirable to receive the total size to be download,
* 0 will be returned if it's chunk transfer
* @param[out] recv_size: pointer point to a varirable to receive the data size have been download
*
* RETURN none
*/
void duer_http_get_download_progress(duer_http_client_t *p_client,
size_t *total_size,
size_t *recv_size);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIGHTDUER_HTTP_CLIENT_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_http_client.h
|
C
|
apache-2.0
| 10,189
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/**
* File: lightduer_http_client_ops.h
* Author: Zhong Shuai(zhongshuai@baidu.com)
* Desc: HTTP Client OPS Head File
*/
#ifndef BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_HTTP_CLIENT_OPS_H
#define BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_HTTP_CLIENT_OPS_H
#ifdef __cplusplus
extern "C" {
#endif
#include "lightduer_http_client.h"
extern duer_http_client_t *duer_create_http_client(void);
extern void duer_destory_http_client(duer_http_client_t *client);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_HTTP_CLIENT_OPS_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_http_client_ops.h
|
C
|
apache-2.0
| 1,168
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/**
* File: lightduer_http_client_ops.h
* Auth: CHEN YUN (chenyun08@baidu.com)
* Desc: HTTP DNS Client Socket Head File
*/
#ifndef BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_HTTP_DNS_CLIENT_OPS_H
#define BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_HTTP_DNS_CLIENT_OPS_H
#include "lightduer_http_client.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum
{
HTTP_DNS_QUERY_UNKNOWN = -1,
HTTP_DNS_QUERY_START,
HTTP_DNS_QUERYING,
HTTP_DNS_QUERY_SUCC,
HTTP_DNS_QUERY_FAIL,
}duer_http_dns_query_state_t;
void duer_http_dns_task_init();
void duer_http_dns_task_destroy();
char *duer_http_dns_query(char *host, int timeout);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_HTTP_DNS_CLIENT_OPS_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_http_dns_client_ops.h
|
C
|
apache-2.0
| 1,353
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/**
* File: lightduer_interactive_class.h
* Auth: Chen Xihao (chenxihao@baidu.com)
* Desc: Interactive class APIs.
*/
#ifndef BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_INTERACTIVE_CLASS_H
#define BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_INTERACTIVE_CLASS_H
#include <stdbool.h>
#include "baidu_json.h"
#include "lightduer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct duer_interactive_class_handler_s {
duer_status_t (*handle_control_light)(bool on);
duer_status_t (*handle_notice)(baidu_json *payload);
} duer_interactive_class_handler_t;
/**
* DESC:
* Init interactive class.
*
* PARAM: none
*
* @RETURN: none.
*/
void duer_interactive_class_init(void);
/**
* DESC:
* Open interactive class.
*
* PARAM: none
*
* @RETURN: success return DUER_OK, failed return DUER_ERR_FAILED.
*/
duer_status_t duer_interactive_class_open(void);
/**
* DESC:
* Close interactive class.
*
* PARAM: none
*
* @RETURN: success return DUER_OK, failed return DUER_ERR_FAILED.
*/
duer_status_t duer_interactive_class_close(void);
/**
* DESC:
* Whether interactive class is living.
*
* PARAM: none
*
* @RETURN: living return true, not return false.
*/
bool duer_interactive_class_is_living(void);
/**
* DESC:
* Set the handler to handle callbacks, such as control light, handle notice
*
* PARAM: handler, the point of handler defined by user
*
* @RETURN: none.
*/
void duer_interactive_class_set_handler(duer_interactive_class_handler_t *handler);
#ifdef __cplusplus
}
#endif
#endif /* BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_INTERACTIVE_CLASS_H */
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_interactive_class.h
|
C
|
apache-2.0
| 2,210
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/**
* File: lightduer_key.h
* Auth: Zhong Shuai (zhongshuai@baidu.com)
* Desc: Key Event Handle Interface
*/
#ifndef BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_KEY_H
#define BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_KEY_H
enum KeyType {
START_KEY = 1,
STOP_KEY = 2,
END_KEY = 3,
NEXT_KEY = 4,
PREVIOUS_KEY = 5,
REPEAT_KEY = 6,
};
/*
* Init LightDuer key handler framework
*
* @param void: None
*
* @return int: Success: DUER_OK
* Failed: DUER_ERR_FAILED.
*/
extern int duer_init_key_handler(void);
/*
* Report key event to event framework
* Call this API in IRQ context as the last func
*
* @param void: enum KeyType key
* START_KEY
* STOP_KEY
* END_KEY
* NEXT_KEY
* PREVIOUS_KEY
* REPEAT_KEY
*
* int value
*
* @return int: Success: DUER_OK
* Failed: DUER_ERR_FAILED.
*
*/
extern int duer_report_key_event(enum KeyType key, int value);
#endif // BAIDU_DUER_LIGHTDUER_INCLUDE_LIGHTDUER_KEY_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_key.h
|
C
|
apache-2.0
| 1,701
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
// Author: Su Hao (suhao@baidu.com)
//
// Description: The internal common header.
#ifndef BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_INTERNAL_H
#define BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_INTERNAL_H
#include <string.h>
#define DUER_MEMCPY(...) memcpy(__VA_ARGS__)
#define DUER_MEMCMP(...) memcmp(__VA_ARGS__)
#define DUER_MEMSET(...) memset(__VA_ARGS__)
#define DUER_MEMMOVE(...) memmove(__VA_ARGS__)
#define DUER_STRLEN(...) strlen(__VA_ARGS__)
#define DUER_STRCMP(...) strcmp(__VA_ARGS__)
#define DUER_STRNCPY(...) strncpy(__VA_ARGS__)
#define DUER_STRNCMP(...) strncmp(__VA_ARGS__)
#define DUER_SNPRINTF(...) snprintf(__VA_ARGS__)
#define DUER_STRNCASECMP(...) strncasecmp(__VA_ARGS__)
#define DUER_SSCANF(...) sscanf(__VA_ARGS__)
#define DUER_STRSTR(...) strstr(__VA_ARGS__)
#define DUER_STRCHR(...) strchr(__VA_ARGS__)
#define DUER_STRNCAT(...) strncat(__VA_ARGS__)
// Suppress Compiler warning Function&Variable declared never referenced
#define ALLOW_UNUSED_LOCAL(VAR_FUNC) (void)(VAR_FUNC)
#endif // BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_INTERNAL_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_lib.h
|
C
|
apache-2.0
| 1,834
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
/**
* File: duer_log.h
* Auth: Su Hao(suhao@baidu.com)
* Desc: Print log.
*/
#ifndef LIBDUER_DEVICE_FRAMEWORK_CORE_LIGHTDUER_LOG_H
#define LIBDUER_DEVICE_FRAMEWORK_CORE_LIGHTDUER_LOG_H
#include "lightduer_debug.h"
#define DUER_STRING_OUTPUT(_x) (((_x) == NULL) ? ("NULL") : (_x))
#ifndef DUER_DEBUG_LEVEL
#define DUER_DEBUG_LEVEL 3
#endif
#ifdef DUER_DEBUG_LEVEL
#define DUER_DEBUG_EXT(_l, _f, _li, ...) duer_debug(_l, _f, _li, __VA_ARGS__)
#define DUER_DUMP_EXT(_l, _f, _li, _tag, _data, _size) duer_dump(_l, _f, _li, _tag, _data, _size)
#else
#define DUER_DEBUG_EXT(...)
#define DUER_DUMP_EXT(...)
#endif
#if defined(DUER_DEBUG_LEVEL) && (DUER_DEBUG_LEVEL >= 5)
#define DUER_LOGV_EXT(_f, _l, ...) DUER_DEBUG_EXT(5, _f, _l, __VA_ARGS__)
#define DUER_DUMPV_EXT(_f, _l, ...) DUER_DUMP_EXT(5, _f, _l, __VA_ARGS__)
#else
#define DUER_LOGV_EXT(...)
#define DUER_DUMPV_EXT(...)
#endif
#if defined(DUER_DEBUG_LEVEL) && (DUER_DEBUG_LEVEL >= 4)
#define DUER_LOGD_EXT(_f, _l, ...) DUER_DEBUG_EXT(4, _f, _l, __VA_ARGS__)
#define DUER_DUMPD_EXT(_f, _l, ...) DUER_DUMP_EXT(4, _f, _l, __VA_ARGS__)
#else
#define DUER_LOGD_EXT(...)
#define DUER_DUMPD_EXT(...)
#endif
#if defined(DUER_DEBUG_LEVEL) && (DUER_DEBUG_LEVEL >= 3)
#define DUER_LOGI_EXT(_f, _l, ...) DUER_DEBUG_EXT(3, _f, _l, __VA_ARGS__)
#define DUER_DUMPI_EXT(_f, _l, ...) DUER_DUMP_EXT(3, _f, _l, __VA_ARGS__)
#else
#define DUER_LOGI_EXT(...)
#define DUER_DUMPI_EXT(...)
#endif
#if defined(DUER_DEBUG_LEVEL) && (DUER_DEBUG_LEVEL >= 2)
#define DUER_LOGW_EXT(_f, _l, ...) DUER_DEBUG_EXT(2, _f, _l, __VA_ARGS__)
#define DUER_DUMPW_EXT(_f, _l, ...) DUER_DUMP_EXT(2, _f, _l, __VA_ARGS__)
#else
#define DUER_LOGW_EXT(...)
#define DUER_DUMPW_EXT(...)
#endif
#if defined(DUER_DEBUG_LEVEL) && (DUER_DEBUG_LEVEL >= 1)
#define DUER_LOGE_EXT(_f, _l, ...) DUER_DEBUG_EXT(1, _f, _l, __VA_ARGS__)
#define DUER_DUMPE_EXT(_f, _l, ...) DUER_DUMP_EXT(1, _f, _l, __VA_ARGS__)
#else
#define DUER_LOGE_EXT(...)
#define DUER_DUMPE_EXT(...)
#endif
#if defined(DUER_DEBUG_LEVEL) && (DUER_DEBUG_LEVEL >= 0)
#define DUER_LOGWTF_EXT(_f, _l, ...) DUER_DEBUG_EXT(0, _f, _l, __VA_ARGS__)
#define DUER_DUMPWTF_EXT(_f, _l, ...) DUER_DUMP_EXT(0, _f, _l, __VA_ARGS__)
#else
#define DUER_LOGWTF_EXT(...)
#define DUER_DUMPWTF_EXT(...)
#endif
#define DUER_DEBUG(_l, ...) DUER_DEBUG_EXT(_l, __FILE__, __LINE__, __VA_ARGS__)
#define DUER_LOGV(...) DUER_LOGV_EXT(__FILE__, __LINE__, __VA_ARGS__)
#define DUER_LOGD(...) DUER_LOGD_EXT(__FILE__, __LINE__, __VA_ARGS__)
#define DUER_LOGI(...) DUER_LOGI_EXT(__FILE__, __LINE__, __VA_ARGS__)
#define DUER_LOGW(...) DUER_LOGW_EXT(__FILE__, __LINE__, __VA_ARGS__)
#define DUER_LOGE(...) DUER_LOGE_EXT(__FILE__, __LINE__, __VA_ARGS__)
#define DUER_LOGWTF(...) DUER_LOGWTF_EXT(__FILE__, __LINE__, __VA_ARGS__)
#define DUER_DUMP(_l, ...) DUER_DUMP_EXT(_l, __FILE__, __LINE__, __VA_ARGS__)
#define DUER_DUMPV(...) DUER_DUMPV_EXT(__FILE__, __LINE__, __VA_ARGS__)
#define DUER_DUMPD(...) DUER_DUMPD_EXT(__FILE__, __LINE__, __VA_ARGS__)
#define DUER_DUMPI(...) DUER_DUMPI_EXT(__FILE__, __LINE__, __VA_ARGS__)
#define DUER_DUMPW(...) DUER_DUMPW_EXT(__FILE__, __LINE__, __VA_ARGS__)
#define DUER_DUMPE(...) DUER_DUMPE_EXT(__FILE__, __LINE__, __VA_ARGS__)
#define DUER_DUMPWTF(...) DUER_DUMPWTF_EXT(__FILE__, __LINE__, __VA_ARGS__)
#endif/*LIBDUER_DEVICE_FRAMEWORK_CORE_LIGHTDUER_LOG_H*/
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_log.h
|
C
|
apache-2.0
| 4,102
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
// Author: Su Hao (suhao@baidu.com)
//
// Description: The APIs for memory management.
#ifndef BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_MEMORY_H
#define BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_MEMORY_H
#include "lightduer_types.h"
#include "lightduer_lib.h"
#ifdef DUER_HEAP_MONITOR
#ifndef DUER_MEMORY_USAGE
#define DUER_MEMORY_USAGE // DUER_HEAP_MONITOR rely on this
#endif
#ifndef DUER_HM_MODULE_NAME
#error "DUER_HM_MODULE_NAME should be defined if the heapmonitor function needed"
// #else
// #define STR_HELPER(x) #x
// #define STR(x) STR_HELPER(x)
// #error #DUER_HM_MODULE_NAME
// #warning "error:"##DUER_HM_MODULE_NAME
#endif
#undef HM_KEYWORD
#define HM_KEYWORD(symbol) symbol,
typedef enum _duer_memory_hm_module_e {
DUER_MEMORY_HM_MIN = 0,
#include "lightduer_memory_hm_keywords.h"
DUER_MEMORY_HM_MAX,
} duer_memory_hm_module_e;
#endif // DUER_HEAP_MONITOR
#ifdef DUER_MEMORY_USAGE
#ifndef DUER_HEAP_MONITOR
DUER_INT void duer_memdbg_usage();
#define DUER_MEMDBG_USAGE(...) duer_memdbg_usage()
#else
#ifdef DUER_HEAP_MONITOR_DEBUG
DUER_INT void duer_memdbg_usage();
#define DUER_MEMDBG_USAGE(...) duer_memdbg_usage()
#else // DUER_HEAP_MONITOR_DEBUG
#define DUER_MEMDBG_USAGE(...)
#endif // DUER_HEAP_MONITOR_DEBUG
#endif
#else
#define DUER_MEMDBG_USAGE(...)
#endif
#if defined(DUER_HEAP_MONITOR)
#define DUER_MALLOC(_s) duer_malloc_hm(_s, DUER_HM_MODULE_NAME)
#define DUER_CALLOC(_s, _n) duer_calloc_hm((_s) * (_n), DUER_HM_MODULE_NAME)
#define DUER_REALLOC(_p, _s) duer_realloc_hm(_p, _s, DUER_HM_MODULE_NAME)
#define DUER_FREE(_p) duer_free_hm(_p)
#elif DUER_MEMORY_DEBUG
#define DUER_MALLOC(_s) duer_malloc_ext(_s, __FILE__, __LINE__)
#define DUER_CALLOC(_s, _n) duer_calloc_ext((_s) * (_n), __FILE__, __LINE__)
#define DUER_REALLOC(_p, _s) duer_realloc_ext(_p, _s, __FILE__, __LINE__)
#define DUER_FREE(_p) duer_free_ext(_p, __FILE__, __LINE__)
#else/*DUER_MEMORY_DEBUG*/
#define DUER_MALLOC(_s) duer_malloc(_s)
#define DUER_CALLOC(_s, _n) duer_calloc((_s) * (_n))
#define DUER_REALLOC(_p, _s) duer_realloc(_p, _s)
#define DUER_FREE(_p) duer_free(_p)
#endif/*DUER_HEAP_MONITOR*/
#ifdef __cplusplus
extern "C" {
#endif
/*
* Adapt the memory management functions.
*/
typedef void* (*duer_malloc_f)(duer_context context, duer_size_t size);
typedef void* (*duer_realloc_f)(duer_context context, void*, duer_size_t size);
typedef void (*duer_free_f)(duer_context context, void* p);
/*
* Set the memory management functions.
*
* @Param ctx, duer_context, in, the memory context for user
* @Param f_malloc, duer_malloc_f, the memory alloc function for user
* @Param f_realloc, duer_realloc_f, the memory realloc function for user,
* @Param f_free, duer_free_f, the memory free function for user
*
* If f_malloc or f_free set to NULL, we will use default libc instead all of it;
* If only f_realloc set to NULL, we will realized it by f_malloc and f_free.
*/
DUER_EXT void baidu_ca_memory_init(duer_context context,
duer_malloc_f f_malloc,
duer_realloc_f f_realloc,
duer_free_f f_free);
/*
* uninit the memory operations in baidu_ca_memory_init.
*/
DUER_EXT void baidu_ca_memory_uninit(void);
/*
* malloc function for bjson
*
* @Param size, duer_size_t, the expected size of the memory
* @Return the alloced memory pointer
*/
DUER_INT void* duer_malloc_bjson(duer_size_t size);
/*
* free function bjson
*
* @Param ptr, void *, the alloced memory
*/
DUER_INT void duer_free_bjson(void* ptr);
#if defined(DUER_HEAP_MONITOR)
DUER_INT void baidu_ca_memory_hm_init(void);
DUER_INT void baidu_ca_memory_hm_destroy(void);
/*
* malloc function for heap monitor
*
* @Param size, duer_size_t, the expected size of the memory
* @Param module, duer_memory_hm_module_e, the tag for where the memroy used
* @Return the alloced memory pointer
*/
DUER_INT void* duer_malloc_hm(duer_size_t size, duer_memory_hm_module_e module);
/*
* cmalloc function zero-initialize the memory before return
*
* @Param size, duer_size_t, the expected size of the memory
* @Param module, duer_memory_hm_module_e, the tag for where the memroy used
* @Return the alloced memory pointer
*/
DUER_INT void* duer_calloc_hm(duer_size_t size, duer_memory_hm_module_e module);
/*
* realloc function
*
* @Param ptr, void *, the old alloced memory
* @Param size, duer_size_t, the expected size of the memory
* @Param module, duer_memory_hm_module_e, the tag for where the memroy used
* @Return the new alloced memory pointer
*/
DUER_INT void* duer_realloc_hm(void* ptr, duer_size_t size, duer_memory_hm_module_e module);
/*
* free function
*
* @Param ptr, void *, the alloced memory
*/
DUER_INT void duer_free_hm(void* ptr);
#else
/*
* malloc function
*
* @Param size, duer_size_t, the expected size of the memory
* @Param file, const char *, the file name when alloc the memory
* @Param line, duer_u32_t, the line number of the file when alloc the memory
* @Return the alloced memory pointer
*/
DUER_INT void* duer_malloc_ext(duer_size_t size, const char* file, duer_u32_t line);
/*
* malloc function, zero-initialize before return
*
* @Param size, duer_size_t, the expected size of the memory
* @Param file, const char *, the file name when alloc the memory
* @Param line, duer_u32_t, the line number of the file when alloc the memory
* @Return the alloced memory pointer
*/
DUER_INT void* duer_calloc_ext(duer_size_t size, const char* file, duer_u32_t line);
/*
* realloc function
*
* @Param ptr, void *, the old alloced memory
* @Param size, duer_size_t, the expected size of the memory
* @Param file, const char *, the file name when alloc the memory
* @Param line, duer_u32_t, the line number of the file when alloc the memory
* @Return the new alloced memory pointer
*/
DUER_INT void* duer_realloc_ext(void* ptr, duer_size_t size, const char* file,
duer_u32_t line);
/*
* free function
*
* @Param ptr, void *, the alloced memory
* @Param file, const char *, the file name when alloc the memory
* @Param line, duer_u32_t, the line number of the file when alloc the memory
*/
DUER_INT void duer_free_ext(void* ptr, const char* file, duer_u32_t line);
/*
* malloc function
*
* @Param size, duer_size_t, the expected size of the memory
* @Return the alloced memory pointer
*/
DUER_INT void* duer_malloc(duer_size_t size);
/*
* cmalloc function zero-initialize the memory before return
*
* @Param size, duer_size_t, the expected size of the memory
* @Return the alloced memory pointer
*/
DUER_INT void* duer_calloc(duer_size_t size);
/*
* realloc function
*
* @Param ptr, void *, the old alloced memory
* @Param size, duer_size_t, the expected size of the memory
* @Return the new alloced memory pointer
*/
DUER_INT void* duer_realloc(void* ptr, duer_size_t size);
/*
* free function
*
* @Param ptr, void *, the alloced memory
*/
DUER_INT void duer_free(void* ptr);
#endif
#ifdef __cplusplus
}
#endif
#endif // BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_MEMORY_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_memory.h
|
C
|
apache-2.0
| 7,859
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
// Author: zhangleliang(zhangleliang@baidu.com)
//
// Description: definition about the heap monitor module
#ifdef DUER_HEAP_MONITOR
#ifdef HM_KEYWORD
HM_KEYWORD(DUER_HM_DUER_DEVICE)
HM_KEYWORD(DUER_HM_PLATFORM)
HM_KEYWORD(DUER_HM_PORT_LPT230)
HM_KEYWORD(DUER_HM_PORT_LPB100)
HM_KEYWORD(DUER_HM_PORT_LINUX)
HM_KEYWORD(DUER_HM_PORT_FREERTOS)
HM_KEYWORD(DUER_HM_FLASH_STRINGS)
HM_KEYWORD(DUER_HM_CONNAGENT)
HM_KEYWORD(DUER_HM_DCS)
HM_KEYWORD(DUER_HM_DEVICE_STATUS)
HM_KEYWORD(DUER_HM_DEVICE_INFO)
HM_KEYWORD(DUER_HM_HTTP)
HM_KEYWORD(DUER_HM_NTP)
HM_KEYWORD(DUER_HM_BIND_DEVICE)
HM_KEYWORD(DUER_HM_VOICE_ENGINE)
HM_KEYWORD(DUER_HM_COAP)
HM_KEYWORD(DUER_HM_SYSTEM_INFO)
HM_KEYWORD(DUER_HM_INTERACTIVE_CLASS)
HM_KEYWORD(DUER_HM_OTA)
HM_KEYWORD(DUER_HM_DCS3_LINUX_DEMO)
HM_KEYWORD(DUER_HM_TRACKER)
HM_KEYWORD(DUER_HM_LINUX_DEMO)
HM_KEYWORD(DUER_HM_SPEEX_ENCODER)
HM_KEYWORD(DUER_HM_FRAMEWORK)
HM_KEYWORD(DUER_HM_MBEDTLS)
HM_KEYWORD(DUER_HM_NSDL)
HM_KEYWORD(DUER_HM_CJSON)
HM_KEYWORD(DUER_HM_DEVICE_VAD)
HM_KEYWORD(DUER_HM_SPEEX)
HM_KEYWORD(DUER_HM_ZLIBLITE)
HM_KEYWORD(DUER_HM_MBED)
HM_KEYWORD(DUER_HM_SONIC_CODEC)
HM_KEYWORD(DUER_HM_SMARTCONFIG)
HM_KEYWORD(DUER_HM_DATA_PARSER)
#else
#error "define HM_KEYWORD is needed if use heap monitor function"
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_memory_hm_keywords.h
|
C
|
apache-2.0
| 2,012
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
// Author: Su Hao (suhao@baidu.com)
//
// Description: Wrapper for mutex
#ifndef BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_MUTEX_H
#define BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_MUTEX_H
#include "lightduer_types.h"
//#include "lightduer_ca.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef void* duer_mutex_t;
/*
* Create mutex context
*
* @Return duer_mutex_t, the created mutex context
*/
DUER_INT duer_mutex_t duer_mutex_create(void);
/*
* Mutex lock
*
* @Return duer_mutex_t, the mutex context
*/
DUER_INT duer_status_t duer_mutex_lock(duer_mutex_t mutex);
/*
* Mutex unlock
*
* @Return duer_mutex_t, the mutex context
*/
DUER_INT duer_status_t duer_mutex_unlock(duer_mutex_t mutex);
/*
* Destroy the mutex context
*
* @Return duer_mutex_t, the mutex context
*/
DUER_INT duer_status_t duer_mutex_destroy(duer_mutex_t mutex);
/*
* The mutex callbacks
*/
typedef duer_mutex_t (*duer_mutex_create_f)();
typedef duer_status_t (*duer_mutex_lock_f)(duer_mutex_t mtx);
typedef duer_status_t (*duer_mutex_unlock_f)(duer_mutex_t mtx);
typedef duer_status_t (*duer_mutex_destroy_f)(duer_mutex_t mtx);
/*
* Initial the mutex callbacks for Baidu CA
*
* @Param f_create, in, the function create mutex context
* @Param f_lock, in, the function mutex lock
* @Param f_unlock, in, the function mutex unlock
* @Param f_destroy, in, the function destroy mutex context
*/
DUER_EXT void baidu_ca_mutex_init(duer_mutex_create_f f_create,
duer_mutex_lock_f f_lock,
duer_mutex_unlock_f f_unlock,
duer_mutex_destroy_f f_destroy);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_MUTEX_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_mutex.h
|
C
|
apache-2.0
| 2,397
|
/**
* Copyright (2017) Baidu Inc. All rights reserved.
*
* 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.
*/
// Author: Chang Li (changli@baidu.com)
//
// Description: NTP client API decleration.
#include <stdint.h>
#ifndef BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_IOT_NTP_H
#define BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_IOT_NTP_H
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _DuerTime {
uint32_t sec;
uint32_t usec;
} DuerTime;
#define NTP_PKG_LEN 48
#define NTP_MAC_LEN 20 // contains 4 Bytes:Key ID and 16 Bytes:Message Authentication Code
#define MD5_KEYID_LEN 4
#define MD5_DIGEST_LEN 16
#define MD5_KEY_LEN 16
typedef struct _md5_key {
uint32_t key_id;
char key_str[MD5_KEY_LEN];
} Md5Key;
/**
* @brief get NTP time
*
* @param host: NTP server name. If host is NULL, use "s2c.time.edu.cn" by
* default.
*
* @param timeout: timeout to acquire the NTP time, unit is micro seconds. If
* it's 0, use 2000 ms by default.
*
* @param result_time: the acquired NTP time.
*
* @param key: Using keyed MD5 for Authentication for some specific NTP servers.
* If unnecessary, specify it NULL.
*
* @return 0 is okay, netgative value is failed.
*/
int duer_ntp_client(char* host, int timeout, DuerTime* result_time, Md5Key* key);
#ifdef __cplusplus
}
#endif
#endif // BAIDU_IOT_TINYDU_IOT_OS_SRC_IOT_BAIDU_CA_SOURCE_BAIDU_CA_IOT_NTP_H
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/clouds/dueros/lightduer/include/lightduer_net_ntp.h
|
C
|
apache-2.0
| 1,927
|