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.
*
*/
#include "unity.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "freertos/queue.h"
#include "esp_event_cast.h"
#include "esp_log.h"
#include "audio_mem.h"
static const char *TAG = "EVT_CAST_TEST";
#define TEST_QUEUE_NUMBER 50
static void task_send(void *pv)
{
esp_event_cast_handle_t broadcast = (esp_event_cast_handle_t)pv;
int buf[3] = {0};
int i = 0x33;
while (1) {
vTaskDelay(5000 / portTICK_RATE_MS);
memset(&buf, i++, sizeof(buf));
esp_event_cast_broadcasting(broadcast, &buf);
printf("%s, i = %x, count=%x\r\n", __func__, i, esp_event_cast_get_count(broadcast));
AUDIO_MEM_SHOW(TAG);
}
vTaskDelete(NULL);
}
static void task_recv0(void *pv)
{
esp_event_cast_handle_t broadcast = (esp_event_cast_handle_t)pv;
xQueueHandle que = xQueueCreate(3, 12);
int buf[3] = {0};
while (buf[0] != (500)) {
esp_event_cast_register(broadcast, que);
xQueueReceive(que, & buf, portMAX_DELAY);
esp_event_cast_unregister(broadcast, que);
printf("[%8s], que = %p, data=%d, %d, %d\r\n", __func__, que, buf[0], buf[1], buf[2]);
}
vQueueDelete(que);
vTaskDelete(NULL);
}
static void task_recv1(void *pv)
{
esp_event_cast_handle_t broadcast = (esp_event_cast_handle_t)pv;
xQueueHandle que = xQueueCreate(3, 12);
esp_event_cast_register(broadcast, que);
int buf[3] = {0};
while (buf[0] != (50)) {
xQueueReceive(que, & buf, portMAX_DELAY);
printf("[%8s], que = %p, data=%d, %d, %d\r\n", __func__, que, buf[0], buf[1], buf[2]);
}
esp_event_cast_unregister(broadcast, que);
vQueueDelete(que);
vTaskDelete(NULL);
}
static void task_recv2(void *pv)
{
esp_event_cast_handle_t broadcast = (esp_event_cast_handle_t)pv;
xQueueHandle que = xQueueCreate(3, 12);
esp_event_cast_register(broadcast, que);
int buf[3] = {0};
while (buf[0] != (50)) {
xQueueReceive(que, & buf, portMAX_DELAY);
printf("[%8s], que = %p, data=%d, %d, %d\r\n", __func__, que, buf[0], buf[1], buf[2]);
}
esp_event_cast_unregister(broadcast, que);
vQueueDelete(que);
vTaskDelete(NULL);
}
static void task_recv3(void *pv)
{
esp_event_cast_handle_t broadcast = (esp_event_cast_handle_t)pv;
xQueueHandle que = xQueueCreate(3, 12);
esp_event_cast_register(broadcast, que);
int buf[3] = {0};
while (buf[0] != (50)) {
xQueueReceive(que, & buf, portMAX_DELAY);
printf("[%8s], que = %p, data=%d, %d, %d\r\n", __func__, que, buf[0], buf[1], buf[2]);
}
esp_event_cast_unregister(broadcast, que);
vQueueDelete(que);
vTaskDelete(NULL);
}
static void task_recv4(void *pv)
{
esp_event_cast_handle_t broadcast = (esp_event_cast_handle_t)pv;
xQueueHandle que = xQueueCreate(3, 12);
esp_event_cast_register(broadcast, que);
int buf[3] = {0};
while (buf[0] != (50)) {
xQueueReceive(que, &buf, portMAX_DELAY);
printf("[%8s], que = %p, data=%d, %d, %d\r\n", __func__, que, buf[0], buf[1], buf[2]);
}
esp_event_cast_unregister(broadcast, que);
vQueueDelete(que);
vTaskDelete(NULL);
}
TEST_CASE("create and destroy", "[esp_event_cast]")
{
ESP_LOGI(TAG, "[✓] setup Wi-Fi and SDcard");
AUDIO_MEM_SHOW(TAG);
esp_event_cast_handle_t broadcast = NULL;
for (int i = 0; i < TEST_QUEUE_NUMBER; ++i) {
broadcast = esp_event_cast_create();
esp_event_cast_destroy(broadcast);
}
AUDIO_MEM_SHOW(TAG);
xQueueHandle que_handle[TEST_QUEUE_NUMBER];
for (int i = 0; i < TEST_QUEUE_NUMBER; ++i) {
que_handle[i] = xQueueCreate(3, 12);
}
for (int i = 0; i < 20; ++i) {
broadcast = esp_event_cast_create();
for (int i = 0; i < TEST_QUEUE_NUMBER; ++i) {
esp_event_cast_register(broadcast, que_handle[i]);
}
ESP_LOGI(TAG, "count is %d", esp_event_cast_get_count(broadcast));
esp_event_cast_destroy(broadcast);
}
for (int i = 0; i < TEST_QUEUE_NUMBER; ++i) {
vQueueDelete(que_handle[i]);
que_handle[i] = NULL;
}
AUDIO_MEM_SHOW(TAG);
}
TEST_CASE("register and unregister", "[esp_event_cast]")
{
ESP_LOGI(TAG, "[✓] setup Wi-Fi and SDcard");
AUDIO_MEM_SHOW(TAG);
esp_event_cast_handle_t broadcast = NULL;
xQueueHandle que_handle[TEST_QUEUE_NUMBER];
for (int i = 0; i < TEST_QUEUE_NUMBER; ++i) {
que_handle[i] = xQueueCreate(3, 12);
}
for (int i = 0; i < 20; ++i) {
broadcast = esp_event_cast_create();
for (int i = 0; i < TEST_QUEUE_NUMBER; ++i) {
esp_event_cast_register(broadcast, que_handle[i]);
}
ESP_LOGI(TAG, "count is %d", esp_event_cast_get_count(broadcast));
for (int i = 0; i < TEST_QUEUE_NUMBER / 2; ++i) {
esp_event_cast_unregister(broadcast, que_handle[i]);
}
ESP_LOGI(TAG, "count is %d", esp_event_cast_get_count(broadcast));
esp_event_cast_destroy(broadcast);
}
for (int i = 0; i < TEST_QUEUE_NUMBER; ++i) {
vQueueDelete(que_handle[i]);
que_handle[i] = NULL;
}
AUDIO_MEM_SHOW(TAG);
}
TEST_CASE("broadcasting from task and receiver", "[esp_event_cast]")
{
ESP_LOGI(TAG, "[✓] setup Wi-Fi and SDcard");
AUDIO_MEM_SHOW(TAG);
esp_event_cast_handle_t broadcast = esp_event_cast_create();
xTaskCreate(task_recv1,
"task_recv1",
2048,
broadcast,
1,
NULL);
xTaskCreate(task_recv2,
"task_recv2",
2048,
broadcast,
3,
NULL);
xTaskCreate(task_recv3,
"task_recv3",
2048,
broadcast,
23,
NULL);
xTaskCreate(task_recv4,
"task_recv4",
2048,
broadcast,
10,
NULL);
AUDIO_MEM_SHOW(TAG);
int buf[3] = {0};
for (int i = 20; i <= 50; ++i) {
vTaskDelay(1000 / portTICK_RATE_MS);
buf[0] = i;
buf[1] = i;
buf[2] = i;
esp_event_cast_broadcasting(broadcast, &buf);
printf("[Broadcast data], i = %d, count=%x\r\n", i, esp_event_cast_get_count(broadcast));
AUDIO_MEM_SHOW(TAG);
}
vTaskDelay(3000 / portTICK_PERIOD_MS);
AUDIO_MEM_SHOW(TAG);
esp_event_cast_destroy(broadcast);
}
TEST_CASE("Received data in real time", "[esp_event_cast]")
{
ESP_LOGI(TAG, "[✓] setup Wi-Fi and SDcard");
AUDIO_MEM_SHOW(TAG);
esp_event_cast_handle_t broadcast = esp_event_cast_create();
xTaskCreate(task_recv0,
"task_recv0",
2048,
broadcast,
15,
NULL);
int buf[3] = {0};
for (int i = 1; i <= 500; ++i) {
// vTaskDelay(1000 / portTICK_RATE_MS);
buf[0] = i;
buf[1] = i;
buf[2] = i;
esp_event_cast_broadcasting(broadcast, &buf);
printf("[Broadcast data], i = %d, count=%x\r\n", i, esp_event_cast_get_count(broadcast));
AUDIO_MEM_SHOW(TAG);
}
vTaskDelay(3000 / portTICK_PERIOD_MS);
AUDIO_MEM_SHOW(TAG);
esp_event_cast_destroy(broadcast);
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_event_cast/test/esp_event_cast_test.c
|
C
|
apache-2.0
| 8,860
|
list(APPEND COMPONENT_ADD_INCLUDEDIRS ./include
./lib/adc_button
./lib/gpio_isr
./lib/button
./lib/blufi
./lib/IS31FL3216
./lib/aw2013
./lib/tca9554
./driver/i2c_bus)
list(APPEND COMPONENT_SRCS ./esp_peripherals.c
./periph_adc_button.c
./periph_button.c
./periph_console.c
./periph_gpio_isr.c
./periph_is31fl3216.c
./periph_led.c
./periph_spiffs.c
./periph_wifi.c
./periph_aw2013.c
./periph_ws2812.c
./lib/button/button.c
./lib/blufi/blufi_security.c
./lib/blufi/wifibleconfig.c
./lib/adc_button/adc_button.c
./lib/IS31FL3216/IS31FL3216.c
./lib/tca9554/tca9554.c
./driver/i2c_bus/i2c_bus.c
./lib/gpio_isr/gpio_isr.c)
IF (CONFIG_IDF_TARGET STREQUAL "esp32")
list(APPEND COMPONENT_ADD_INCLUDEDIRS ./lib/sdcard ./lib/touch)
list(APPEND COMPONENT_SRCS ./lib/sdcard/sdcard.c ./periph_sdcard.c ./periph_touch.c ./lib/touch/touch.c)
ELSEIF (CONFIG_IDF_TARGET STREQUAL "esp32s3")
list(APPEND COMPONENT_ADD_INCLUDEDIRS ./lib/sdcard ./lib/touch)
list(APPEND COMPONENT_SRCS ./lib/sdcard/sdcard.c ./periph_sdcard.c ./periph_touch.c ./lib/touch/touch.c)
ELSEIF((ONFIG_IDF_TARGET STREQUAL "esp32s2"))
list(APPEND COMPONENT_ADD_INCLUDEDIRS ./lib/touch)
list(APPEND COMPONENT_SRCS ./periph_touch.c ./lib/touch/touch.c)
ENDIF ()
set(COMPONENT_REQUIRES driver audio_hal esp_adc_cal audio_sal fatfs console audio_pipeline audio_board spiffs display_service esp_dispatcher bt mbedtls wpa_supplicant)
register_component()
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/CMakeLists.txt
|
CMake
|
apache-2.0
| 1,824
|
#
# "main" pseudo-component makefile.
#
# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.)
COMPONENT_ADD_INCLUDEDIRS := ./include ./lib/adc_button ./lib/gpio_isr ./driver/i2c_bus ./lib/aw2013
COMPONENT_SRCDIRS := . ./lib ./lib/sdcard ./lib/button ./lib/touch ./lib/blufi ./lib/adc_button ./lib/IS31FL3216 ./driver/i2c_bus ./lib/gpio_isr ./lib/aw2013
COMPONENT_PRIV_INCLUDEDIRS := ./lib/sdcard ./lib/button ./lib/touch ./lib/blufi ./lib/IS31FL3216 ./driver/i2c_bus
CFLAGS+=-D__FILENAME__=\"$(<F)\"
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/component.mk
|
Makefile
|
apache-2.0
| 554
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2017 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD>
*
* Permission is hereby granted for use on ESPRESSIF SYSTEMS products only, 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 "esp_log.h"
#include "driver/i2c.h"
#include "i2c_bus.h"
#include "audio_mutex.h"
#include "audio_mem.h"
#define ESP_INTR_FLG_DEFAULT (0)
#define ESP_I2C_MASTER_BUF_LEN (0)
#define I2C_ACK_CHECK_EN 1
#define I2C_BUS_CHECK(a, str, ret) if(!(a)) { \
ESP_LOGE(TAG, "%s:%d (%s):%s", __FILE__, __LINE__, __FUNCTION__, str); \
return (ret); \
}
typedef struct {
i2c_config_t i2c_conf; /*!<I2C bus parameters*/
i2c_port_t i2c_port; /*!<I2C port number */
} i2c_bus_t;
static const char *TAG = "I2C_BUS";
static i2c_bus_t *i2c_bus[I2C_NUM_MAX];
static xSemaphoreHandle _busLock;
i2c_bus_handle_t i2c_bus_create(i2c_port_t port, i2c_config_t *conf)
{
I2C_BUS_CHECK(port < I2C_NUM_MAX, "I2C port error", NULL);
I2C_BUS_CHECK(conf != NULL, "Configuration not initialized", NULL);
if (i2c_bus[port]) {
ESP_LOGW(TAG, "%s:%d: I2C bus has been already created, [port:%d]", __FUNCTION__, __LINE__, port);
return i2c_bus[port];
}
i2c_bus[port] = (i2c_bus_t *) audio_calloc(1, sizeof(i2c_bus_t));
i2c_bus[port]->i2c_conf = *conf;
i2c_bus[port]->i2c_port = port;
esp_err_t ret = i2c_param_config(i2c_bus[port]->i2c_port, &i2c_bus[port]->i2c_conf);
if (ret != ESP_OK) {
goto error;
}
ret = i2c_driver_install(i2c_bus[port]->i2c_port, i2c_bus[port]->i2c_conf.mode, ESP_I2C_MASTER_BUF_LEN, ESP_I2C_MASTER_BUF_LEN, ESP_INTR_FLG_DEFAULT);
if (ret != ESP_OK) {
goto error;
}
if (_busLock) {
mutex_destroy(_busLock);
}
_busLock = mutex_create();
return (i2c_bus_handle_t) i2c_bus[port];
error:
if (i2c_bus[port]) {
audio_free(i2c_bus[port]);
}
return NULL;
}
esp_err_t i2c_bus_write_bytes(i2c_bus_handle_t bus, int addr, uint8_t *reg, int regLen, uint8_t *data, int datalen)
{
I2C_BUS_CHECK(bus != NULL, "Handle error", ESP_FAIL);
i2c_bus_t *p_bus = (i2c_bus_t *) bus;
I2C_BUS_CHECK(p_bus->i2c_port < I2C_NUM_MAX, "I2C port error", ESP_FAIL);
I2C_BUS_CHECK(data != NULL, "Not initialized input data pointer", ESP_FAIL);
esp_err_t ret = ESP_OK;
mutex_lock(_busLock);
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
ret |= i2c_master_start(cmd);
ret |= i2c_master_write_byte(cmd, addr, 1);
ret |= i2c_master_write(cmd, reg, regLen, I2C_ACK_CHECK_EN);
ret |= i2c_master_write(cmd, data, datalen, I2C_ACK_CHECK_EN);
ret |= i2c_master_stop(cmd);
ret |= i2c_master_cmd_begin(p_bus->i2c_port, cmd, 1000 / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
mutex_unlock(_busLock);
I2C_BUS_CHECK(ret == 0, "I2C Bus WriteReg Error", ESP_FAIL);
return ret;
}
esp_err_t i2c_bus_write_data(i2c_bus_handle_t bus, int addr, uint8_t *data, int datalen)
{
I2C_BUS_CHECK(bus != NULL, "Handle error", ESP_FAIL);
i2c_bus_t *p_bus = (i2c_bus_t *) bus;
I2C_BUS_CHECK(p_bus->i2c_port < I2C_NUM_MAX, "I2C port error", ESP_FAIL);
I2C_BUS_CHECK(data != NULL, "Not initialized input data pointer", ESP_FAIL);
esp_err_t ret = ESP_OK;
mutex_lock(_busLock);
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
ret |= i2c_master_start(cmd);
ret |= i2c_master_write_byte(cmd, addr, 1);
ret |= i2c_master_write(cmd, data, datalen, I2C_ACK_CHECK_EN);
ret |= i2c_master_stop(cmd);
ret |= i2c_master_cmd_begin(p_bus->i2c_port, cmd, 1000 / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
mutex_unlock(_busLock);
I2C_BUS_CHECK(ret == 0, "I2C Bus WriteReg Error", ESP_FAIL);
return ret;
}
esp_err_t i2c_bus_read_bytes(i2c_bus_handle_t bus, int addr, uint8_t *reg, int reglen, uint8_t *outdata, int datalen)
{
I2C_BUS_CHECK(bus != NULL, "Handle error", ESP_FAIL);
i2c_bus_t *p_bus = (i2c_bus_t *) bus;
I2C_BUS_CHECK(p_bus->i2c_port < I2C_NUM_MAX, "I2C port error", ESP_FAIL);
I2C_BUS_CHECK(outdata != NULL, "Not initialized output data buffer pointer", ESP_FAIL);
esp_err_t ret = ESP_OK;
mutex_lock(_busLock);
i2c_cmd_handle_t cmd;
cmd = i2c_cmd_link_create();
ret |= i2c_master_start(cmd);
ret |= i2c_master_write_byte(cmd, addr, I2C_ACK_CHECK_EN);
ret |= i2c_master_write(cmd, reg, reglen, I2C_ACK_CHECK_EN);
ret |= i2c_master_stop(cmd);
ret |= i2c_master_cmd_begin(p_bus->i2c_port, cmd, 1000 / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
cmd = i2c_cmd_link_create();
ret |= i2c_master_start(cmd);
ret |= i2c_master_write_byte(cmd, addr | 0x01, I2C_ACK_CHECK_EN);
for (int i = 0; i < datalen - 1; i++) {
ret |= i2c_master_read_byte(cmd, &outdata[i], 0);
}
ret |= i2c_master_read_byte(cmd, &outdata[datalen - 1], 1);
ret = i2c_master_stop(cmd);
ret = i2c_master_cmd_begin(p_bus->i2c_port, cmd, 1000 / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
mutex_unlock(_busLock);
I2C_BUS_CHECK(ret == 0, "I2C Bus ReadReg Error", ESP_FAIL);
return ret;
}
esp_err_t i2c_bus_delete(i2c_bus_handle_t bus)
{
I2C_BUS_CHECK(bus != NULL, "Handle error", ESP_FAIL);
i2c_bus_t *p_bus = (i2c_bus_t *) bus;
i2c_driver_delete(p_bus->i2c_port);
i2c_bus[p_bus->i2c_port] = NULL;
audio_free(p_bus);
mutex_destroy(_busLock);
_busLock = NULL;
return ESP_OK;
}
esp_err_t i2c_bus_cmd_begin(i2c_bus_handle_t bus, i2c_cmd_handle_t cmd, portBASE_TYPE ticks_to_wait)
{
I2C_BUS_CHECK(bus != NULL, "Handle error", ESP_FAIL);
I2C_BUS_CHECK(cmd != NULL, "I2C cmd error", ESP_FAIL);
i2c_bus_t *p_bus = (i2c_bus_t *) bus;
esp_err_t ret = i2c_master_cmd_begin(p_bus->i2c_port, cmd, ticks_to_wait);
return ret;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/driver/i2c_bus/i2c_bus.c
|
C
|
apache-2.0
| 6,935
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2017 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD>
*
* Permission is hereby granted for use on ESPRESSIF SYSTEMS products only, 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 _IOT_I2C_BUS_H_
#define _IOT_I2C_BUS_H_
#include "driver/i2c.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef void *i2c_bus_handle_t;
/**
* @brief Create and init I2C bus and return a I2C bus handle
*
* @param port I2C port number
* @param conf Pointer to I2C parameters
*
* @return
* - I2C bus handle
*/
i2c_bus_handle_t i2c_bus_create(i2c_port_t port, i2c_config_t *conf);
/**
* @brief Write bytes to I2C bus
*
* @param bus I2C bus handle
* @param addr The address of the device
* @param reg The register of the device
* @param regLen The length of register
* @param data The data pointer
* @param datalen The length of data
*
* @return
* - NULL Fail
* - Others Success
*/
esp_err_t i2c_bus_write_bytes(i2c_bus_handle_t bus, int addr, uint8_t *reg, int regLen, uint8_t *data, int datalen);
/**
* @brief Write data to I2C bus
*
* @param bus I2C bus handle
* @param addr The address of the device
* @param data The data pointer
* @param datalen The length of data
*
* @return
* - NULL Fail
* - Others Success
*/
esp_err_t i2c_bus_write_data(i2c_bus_handle_t bus, int addr, uint8_t *data, int datalen);
/**
* @brief Read bytes to I2C bus
*
* @param bus I2C bus handle
* @param addr The address of the device
* @param reg The register of the device
* @param regLen The length of register
* @param outdata The outdata pointer
* @param datalen The length of outdata
*
* @return
* - NULL Fail
* - Others Success
*/
esp_err_t i2c_bus_read_bytes(i2c_bus_handle_t bus, int addr, uint8_t *reg, int reglen, uint8_t *outdata, int datalen);
/**
* @brief Delete and release the I2C bus object
*
* @param bus I2C bus handle
*
* @return
* - ESP_OK Success
* - ESP_FAIL Fail
*/
esp_err_t i2c_bus_delete(i2c_bus_handle_t bus);
/**
* @brief I2C start sending buffered commands
*
* @param bus I2C bus handle
* @param cmd I2C cmd handle
* @param ticks_to_wait Maximum blocking time
*
* @return
* - ESP_OK Success
* - ESP_FAIL Fail
*/
esp_err_t i2c_bus_cmd_begin(i2c_bus_handle_t bus, i2c_cmd_handle_t cmd, portBASE_TYPE ticks_to_wait);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/driver/i2c_bus/i2c_bus.h
|
C
|
apache-2.0
| 3,566
|
/*
* 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 <string.h>
#include "sys/queue.h"
#include "driver/gpio.h"
#include "esp_log.h"
#include "audio_event_iface.h"
#include "audio_mutex.h"
#include "esp_peripherals.h"
#include "audio_thread.h"
#include "audio_mem.h"
static const char *TAG = "ESP_PERIPH";
#define DEFAULT_ESP_PERIPH_WAIT_TICK (10/portTICK_RATE_MS)
struct esp_periph {
char *tag;
bool disabled;
esp_periph_id_t periph_id;
esp_periph_func init;
esp_periph_run_func run;
esp_periph_func destroy;
esp_periph_state_t state;
void *source;
void *periph_data;
esp_periph_event_t *on_evt;
TimerHandle_t timer;
STAILQ_ENTRY(esp_periph) entries;
};
typedef struct esp_periph_sets {
EventGroupHandle_t state_event_bits;
xSemaphoreHandle lock;
int task_stack;
int task_prio;
int task_core;
audio_thread_t audio_thread;
bool ext_stack;
bool run;
esp_periph_event_t event_handle;
STAILQ_HEAD(esp_periph_list_item, esp_periph) periph_list;
} esp_periph_set_t;
static const int STARTED_BIT = BIT0;
static const int STOPPED_BIT = BIT1;
static esp_err_t esp_periph_wait_for_stop(esp_periph_set_handle_t periph_set_handle, TickType_t ticks_to_wait);
static esp_err_t process_peripheral_event(audio_event_iface_msg_t *msg, void *context)
{
esp_periph_handle_t periph_evt = (esp_periph_handle_t) msg->source;
esp_periph_handle_t periph;
esp_periph_set_t *sets = context;
STAILQ_FOREACH(periph, &sets->periph_list, entries) {
if (periph->periph_id == periph_evt->periph_id
&& periph_evt->state == PERIPH_STATE_RUNNING
&& periph_evt->run
&& !periph_evt->disabled) {
return periph_evt->run(periph_evt, msg);
}
}
return ESP_OK;
}
static void esp_periph_task(void *pv)
{
esp_periph_handle_t periph;
esp_periph_set_handle_t periph_set_handle = (esp_periph_set_handle_t)pv;
ESP_LOGD(TAG, "esp_periph_task is running, handle:%p", periph_set_handle);
xEventGroupSetBits(periph_set_handle->state_event_bits, STARTED_BIT);
xEventGroupClearBits(periph_set_handle->state_event_bits, STOPPED_BIT);
while (periph_set_handle->run) {
mutex_lock(periph_set_handle->lock);
STAILQ_FOREACH(periph, &periph_set_handle->periph_list, entries) {
if (periph->disabled) {
continue;
}
if (periph->state == PERIPH_STATE_INIT && periph->init) {
ESP_LOGD(TAG, "PERIPH[%s]->init", periph->tag);
if (periph->init(periph) == ESP_OK) {
periph->state = PERIPH_STATE_RUNNING;
} else {
periph->state = PERIPH_STATE_ERROR;
}
}
}
mutex_unlock(periph_set_handle->lock);
audio_event_iface_waiting_cmd_msg(esp_periph_set_get_event_iface(periph_set_handle));
}
STAILQ_FOREACH(periph, &periph_set_handle->periph_list, entries) {
esp_periph_stop_timer(periph);
if (periph->destroy) {
periph->destroy(periph);
}
}
xEventGroupClearBits(periph_set_handle->state_event_bits, STARTED_BIT);
xEventGroupSetBits(periph_set_handle->state_event_bits, STOPPED_BIT);
vTaskDelete(NULL);
}
esp_periph_set_handle_t esp_periph_set_init(esp_periph_config_t *config)
{
esp_periph_set_t *periph_sets = NULL;
int _err_step = 1;
bool _success =
(
(periph_sets = audio_calloc(1, sizeof(esp_periph_set_t))) && _err_step ++ &&
(periph_sets->state_event_bits = xEventGroupCreate()) && _err_step ++ &&
(periph_sets->lock = mutex_create()) && _err_step ++
);
AUDIO_MEM_CHECK(TAG, _success, {
goto _periph_init_failed;
});
STAILQ_INIT(&periph_sets->periph_list);
//TODO: Should we uninstall gpio isr service??
//TODO: Because gpio need for sdcard and gpio, then install isr here
gpio_install_isr_service(ESP_INTR_FLAG_LEVEL1);
periph_sets->run = false;
xEventGroupClearBits(periph_sets->state_event_bits, STARTED_BIT);
xEventGroupSetBits(periph_sets->state_event_bits, STOPPED_BIT);
periph_sets->task_stack = config->task_stack;
periph_sets->task_prio = config->task_prio;
periph_sets->task_core = config->task_core;
periph_sets->ext_stack = config->extern_stack;
audio_event_iface_cfg_t event_cfg = AUDIO_EVENT_IFACE_DEFAULT_CFG();
event_cfg.queue_set_size = 0;
event_cfg.context = periph_sets;
event_cfg.on_cmd = process_peripheral_event;
periph_sets->event_handle.iface = audio_event_iface_init(&event_cfg);
AUDIO_MEM_CHECK(TAG, periph_sets->event_handle.iface, goto _periph_init_failed);
audio_event_iface_set_cmd_waiting_timeout(periph_sets->event_handle.iface, DEFAULT_ESP_PERIPH_WAIT_TICK);
return periph_sets;
_periph_init_failed:
if (periph_sets) {
mutex_destroy(periph_sets->lock);
vEventGroupDelete(periph_sets->state_event_bits);
if (periph_sets->event_handle.iface) {
audio_event_iface_destroy(periph_sets->event_handle.iface);
}
audio_free(periph_sets);
periph_sets = NULL;
}
return NULL;
}
esp_err_t esp_periph_set_destroy(esp_periph_set_handle_t periph_set_handle)
{
if (periph_set_handle == NULL) {
AUDIO_ERROR(TAG, "Peripherals have not been initialized");
return ESP_FAIL;
}
periph_set_handle->run = false;
esp_periph_wait_for_stop(periph_set_handle, portMAX_DELAY);
esp_periph_handle_t item, tmp;
STAILQ_FOREACH_SAFE(item, &periph_set_handle->periph_list, entries, tmp) {
STAILQ_REMOVE(&periph_set_handle->periph_list, item, esp_periph, entries);
audio_free(item->tag);
audio_free(item);
}
mutex_destroy(periph_set_handle->lock);
vEventGroupDelete(periph_set_handle->state_event_bits);
gpio_uninstall_isr_service();
audio_event_iface_destroy(periph_set_handle->event_handle.iface);
audio_free(periph_set_handle);
periph_set_handle = NULL;
return ESP_OK;
}
esp_err_t esp_periph_set_stop_all(esp_periph_set_handle_t periph_set_handle)
{
if (periph_set_handle == NULL) {
AUDIO_ERROR(TAG, "Peripherals have not been initialized");
return ESP_FAIL;
}
esp_periph_handle_t periph;
STAILQ_FOREACH(periph, &periph_set_handle->periph_list, entries) {
periph->disabled = true;
}
return ESP_OK;
}
esp_periph_handle_t esp_periph_set_get_by_id(esp_periph_set_handle_t periph_set_handle, int periph_id)
{
esp_periph_handle_t periph;
if (periph_set_handle == NULL) {
AUDIO_ERROR(TAG, "Peripherals have not been initialized");
return NULL;
}
mutex_lock(periph_set_handle->lock);
STAILQ_FOREACH(periph, &periph_set_handle->periph_list, entries) {
if (periph->periph_id == periph_id) {
mutex_unlock(periph_set_handle->lock);
return periph;
}
}
ESP_LOGD(TAG, "Periph id %d not found", periph_id);
mutex_unlock(periph_set_handle->lock);
return NULL;
}
audio_event_iface_handle_t esp_periph_set_get_event_iface(esp_periph_set_handle_t periph_set_handle)
{
return periph_set_handle->event_handle.iface;
}
esp_err_t esp_periph_set_register_callback(esp_periph_set_handle_t periph_set_handle, esp_periph_event_handle_t cb, void *user_context)
{
if (periph_set_handle == NULL) {
return ESP_FAIL;
} else {
periph_set_handle->event_handle.cb = cb;
periph_set_handle->event_handle.user_ctx = user_context;
return ESP_OK;
}
}
QueueHandle_t esp_periph_set_get_queue(esp_periph_set_handle_t periph_set_handle)
{
return audio_event_iface_get_queue_handle(periph_set_handle->event_handle.iface);
}
esp_err_t esp_periph_wait_for_stop(esp_periph_set_handle_t periph_set_handle, TickType_t ticks_to_wait)
{
EventGroupHandle_t ev_bits = periph_set_handle->state_event_bits;
EventBits_t uxBits = xEventGroupWaitBits(ev_bits, STOPPED_BIT, false, true, ticks_to_wait);
if (uxBits & STOPPED_BIT) {
return ESP_OK;
}
return ESP_FAIL;
}
esp_err_t esp_periph_set_list_init(esp_periph_set_handle_t periph_set)
{
esp_periph_handle_t periph;
STAILQ_FOREACH(periph, &periph_set->periph_list, entries) {
if (periph->init) {
periph->init(periph);
}
}
return ESP_OK;
}
esp_err_t esp_periph_set_list_run(esp_periph_set_handle_t periph_set, audio_event_iface_msg_t msg)
{
esp_periph_handle_t periph;
STAILQ_FOREACH(periph, &periph_set->periph_list, entries) {
if (periph->run) {
periph->run(periph, &msg);
}
}
return ESP_OK;
}
esp_err_t esp_periph_set_list_destroy(esp_periph_set_handle_t periph_set)
{
esp_periph_handle_t periph;
STAILQ_FOREACH(periph, &periph_set->periph_list, entries) {
if (periph->destroy) {
periph->destroy(periph);
}
}
return ESP_OK;
}
esp_periph_handle_t esp_periph_create(int periph_id, const char *tag)
{
esp_periph_handle_t new_entry = audio_calloc(1, sizeof(struct esp_periph));
AUDIO_MEM_CHECK(TAG, new_entry, return NULL);
if (tag) {
new_entry->tag = audio_strdup(tag);
} else {
new_entry->tag = audio_strdup("periph");
}
AUDIO_MEM_CHECK(TAG, new_entry->tag, {
audio_free(new_entry);
return NULL;
})
new_entry->state = PERIPH_STATE_INIT;
new_entry->periph_id = periph_id;
return new_entry;
}
esp_err_t esp_periph_set_function(esp_periph_handle_t periph,
esp_periph_func init,
esp_periph_run_func run,
esp_periph_func destroy)
{
periph->init = init;
periph->run = run;
periph->destroy = destroy;
return ESP_OK;
}
esp_err_t esp_periph_start(esp_periph_set_handle_t periph_set_handle, esp_periph_handle_t periph)
{
if (periph_set_handle == NULL) {
AUDIO_ERROR(TAG, "Peripherals have not been initialized");
return ESP_FAIL;
}
if (esp_periph_set_get_by_id(periph_set_handle, periph->periph_id) != NULL) {
ESP_LOGI(TAG, "This peripheral has been added");
periph->disabled = false;
} else {
esp_periph_register_on_events(periph, &periph_set_handle->event_handle);
STAILQ_INSERT_TAIL(&periph_set_handle->periph_list, periph, entries);
}
if (periph_set_handle->run == false && periph_set_handle->task_stack > 0) {
periph_set_handle->run = true;
if (audio_thread_create(&periph_set_handle->audio_thread,
"esp_periph",
esp_periph_task,
periph_set_handle,
periph_set_handle->task_stack,
periph_set_handle->task_prio,
periph_set_handle->ext_stack,
periph_set_handle->task_core) != ESP_OK) {
ESP_LOGE(TAG, "Create [%s] task failed", periph->tag);
return ESP_FAIL;
}
}
return ESP_OK;
}
esp_err_t esp_periph_stop(esp_periph_handle_t periph)
{
if (periph) {
periph->disabled = true;
return ESP_OK;
}
return ESP_OK;
}
esp_err_t esp_periph_send_cmd(esp_periph_handle_t periph, int cmd, void *data, int data_len)
{
if (periph->on_evt == NULL) {
return ESP_FAIL;
}
audio_event_iface_msg_t msg;
msg.cmd = cmd;
msg.source = periph;
msg.source_type = periph->periph_id;
msg.data = (void *)data;
msg.data_len = data_len;
return audio_event_iface_cmd(periph->on_evt->iface, &msg);
}
esp_err_t esp_periph_send_cmd_from_isr(esp_periph_handle_t periph, int cmd, void *data, int data_len)
{
if (periph->on_evt == NULL) {
return ESP_FAIL;
}
audio_event_iface_msg_t msg;
msg.cmd = cmd;
msg.source = periph;
msg.source_type = periph->periph_id;
msg.data = (void *)data;
msg.data_len = data_len;
return audio_event_iface_cmd_from_isr(periph->on_evt->iface, &msg);
}
esp_err_t esp_periph_send_event(esp_periph_handle_t periph, int event_id, void *data, int data_len)
{
if (periph->on_evt == NULL) {
return ESP_FAIL;
}
audio_event_iface_msg_t msg;
msg.source_type = periph->periph_id;
msg.cmd = event_id;
msg.data = data;
msg.data_len = data_len;
msg.need_free_data = false;
msg.source = periph;
if (periph->on_evt->cb) {
periph->on_evt->cb(&msg, periph->on_evt->user_ctx);
}
return audio_event_iface_sendout(periph->on_evt->iface, &msg);
}
esp_err_t esp_periph_start_timer(esp_periph_handle_t periph, TickType_t interval_tick, timer_callback callback)
{
if (periph->timer == NULL) {
periph->timer = xTimerCreate("periph_itmer", interval_tick, pdTRUE, periph, callback);
if (xTimerStart(periph->timer, 0) != pdTRUE) {
AUDIO_ERROR(TAG, "Error to starting timer");
return ESP_FAIL;
}
}
return ESP_OK;
}
esp_err_t esp_periph_stop_timer(esp_periph_handle_t periph)
{
if (periph->timer) {
xTimerStop(periph->timer, portMAX_DELAY);
xTimerDelete(periph->timer, portMAX_DELAY);
periph->timer = NULL;
}
return ESP_OK;
}
esp_err_t esp_periph_set_data(esp_periph_handle_t periph, void *data)
{
periph->periph_data = data;
return ESP_OK;
}
void *esp_periph_get_data(esp_periph_handle_t periph)
{
return periph->periph_data;
}
esp_periph_state_t esp_periph_get_state(esp_periph_handle_t periph)
{
return periph->state;
}
esp_periph_id_t esp_periph_get_id(esp_periph_handle_t periph)
{
return periph->periph_id;
}
esp_err_t esp_periph_set_id(esp_periph_handle_t periph, esp_periph_id_t periph_id)
{
periph->periph_id = periph_id;
return ESP_OK;
}
esp_err_t esp_periph_init(esp_periph_handle_t periph)
{
return periph->init(periph);
}
esp_err_t esp_periph_run(esp_periph_handle_t periph)
{
return periph->run(periph, NULL);
}
esp_err_t esp_periph_destroy(esp_periph_handle_t periph)
{
return periph->destroy(periph);
}
esp_err_t esp_periph_register_on_events(esp_periph_handle_t periph, esp_periph_event_t *evts)
{
periph->on_evt = evts;
return ESP_OK;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/esp_peripherals.c
|
C
|
apache-2.0
| 16,167
|
/*
* 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 _ESP_PERIPHERALS_H_
#define _ESP_PERIPHERALS_H_
#include "audio_error.h"
#include "audio_event_iface.h"
#include "audio_common.h"
#include "freertos/event_groups.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Peripheral Identify, this must be unique for each peripheral added to the peripherals list
*/
typedef enum {
PERIPH_ID_BUTTON = AUDIO_ELEMENT_TYPE_PERIPH + 1,
PERIPH_ID_TOUCH = AUDIO_ELEMENT_TYPE_PERIPH + 2,
PERIPH_ID_SDCARD = AUDIO_ELEMENT_TYPE_PERIPH + 3,
PERIPH_ID_WIFI = AUDIO_ELEMENT_TYPE_PERIPH + 4,
PERIPH_ID_FLASH = AUDIO_ELEMENT_TYPE_PERIPH + 5,
PERIPH_ID_AUXIN = AUDIO_ELEMENT_TYPE_PERIPH + 6,
PERIPH_ID_ADC = AUDIO_ELEMENT_TYPE_PERIPH + 7,
PERIPH_ID_CONSOLE = AUDIO_ELEMENT_TYPE_PERIPH + 8,
PERIPH_ID_BLUETOOTH = AUDIO_ELEMENT_TYPE_PERIPH + 9,
PERIPH_ID_LED = AUDIO_ELEMENT_TYPE_PERIPH + 10,
PERIPH_ID_SPIFFS = AUDIO_ELEMENT_TYPE_PERIPH + 11,
PERIPH_ID_ADC_BTN = AUDIO_ELEMENT_TYPE_PERIPH + 12,
PERIPH_ID_IS31FL3216 = AUDIO_ELEMENT_TYPE_PERIPH + 13,
PERIPH_ID_GPIO_ISR = AUDIO_ELEMENT_TYPE_PERIPH + 14,
PERIPH_ID_WS2812 = AUDIO_ELEMENT_TYPE_PERIPH + 15,
PERIPH_ID_AW2013 = AUDIO_ELEMENT_TYPE_PERIPH + 16
} esp_periph_id_t;
/**
* @brief Peripheral working state
*/
typedef enum {
PERIPH_STATE_NULL,
PERIPH_STATE_INIT,
PERIPH_STATE_RUNNING,
PERIPH_STATE_PAUSE,
PERIPH_STATE_STOPPING,
PERIPH_STATE_ERROR,
PERIPH_STATE_STATUS_MAX,
} esp_periph_state_t;
typedef struct esp_periph_sets* esp_periph_set_handle_t;
typedef struct esp_periph* esp_periph_handle_t;
typedef esp_err_t (*esp_periph_func)(esp_periph_handle_t periph);
typedef esp_err_t (*esp_periph_run_func)(esp_periph_handle_t periph, audio_event_iface_msg_t *msg);
typedef esp_err_t (*esp_periph_event_handle_t)(audio_event_iface_msg_t *event, void *context);
typedef void (*timer_callback)(xTimerHandle tmr);
/**
* @brief Common peripherals configurations
*/
typedef struct {
int task_stack; /*!< >0 Service task stack size; =0 without 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; /*!< Service task stack allocate on extern ram */
} esp_periph_config_t;
/**
* @brief peripheral events
*/
typedef struct esp_periph_event {
void *user_ctx; /*!< peripheral context data */
esp_periph_event_handle_t cb; /*!< peripheral callback function */
audio_event_iface_handle_t iface; /*!< peripheral event */
} esp_periph_event_t;
#define DEFAULT_ESP_PERIPH_STACK_SIZE (4*1024)
#define DEFAULT_ESP_PERIPH_TASK_PRIO (5)
#define DEFAULT_ESP_PERIPH_TASK_CORE (0)
#define DEFAULT_ESP_PERIPH_SET_CONFIG() {\
.task_stack = DEFAULT_ESP_PERIPH_STACK_SIZE, \
.task_prio = DEFAULT_ESP_PERIPH_TASK_PRIO, \
.task_core = DEFAULT_ESP_PERIPH_TASK_CORE, \
.extern_stack = false, \
}
/**
* @brief Initialize esp_peripheral sets, create empty peripherals list.
* Call this function before starting any peripherals (with `esp_periph_start`). This call will initialize the data needed
* for esp_peripherals to work, but does not actually create the task. The `event_handle` is optional if you want to
* receive events from this callback function. The esp_peripherals task will send all events out to event_iface, can be
* listen by event_iface by `esp_periph_get_event_iface`. The `user_context` will sent `esp_periph_event_handle_t`
* as *context parameter.
*
* @param[in] config The configurations
*
* @return The peripheral sets instance
*/
esp_periph_set_handle_t esp_periph_set_init(esp_periph_config_t* config);
/**
* @brief This function will stop and kill the monitor task, calling all destroy callback functions of the peripheral
* (so you do not need to destroy the peripheral object manually).
* It will also remove all memory allocated to the peripherals list,
* so you need to call the `esp_periph_set_init` function again if you want to use it.
*
* @param periph_set_handle The esp_periph_set_handle_t instance
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_periph_set_destroy(esp_periph_set_handle_t periph_set_handle);
/**
* @brief Stop monitoring all peripherals, the peripheral state is still kept. This funciton only temporary disables the peripheral.
*
* @param periph_set_handle The esp_periph_set_handle_t instance
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_periph_set_stop_all(esp_periph_set_handle_t periph_set_handle);
/**
* @brief Get the peripheral handle by Peripheral ID
*
* @param periph_set_handle The esp_periph_set_handle_t instance
*
* @param[in] periph_id as esp_periph_id_t, or any ID you use when calling `esp_periph_create`
*
*
* @return The esp_periph_handle_t
*/
esp_periph_handle_t esp_periph_set_get_by_id(esp_periph_set_handle_t periph_set_handle, int periph_id);
/**
* @brief Return the event_iface used by this esp_peripherals
*
* @param periph_set_handle The esp_periph_set_handle_t instance
*
* @return The audio event iface handle
*/
audio_event_iface_handle_t esp_periph_set_get_event_iface(esp_periph_set_handle_t periph_set_handle);
/**
* @brief Register peripheral sets event callback function.
*
* @param periph_set_handle The esp_periph_set_handle_t instance
* @param cb The event handle callback function
* @param user_context The user context pointer
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_periph_set_register_callback(esp_periph_set_handle_t periph_set_handle, esp_periph_event_handle_t cb, void* user_context);
/**
* @brief Peripheral is using event_iface to control the event, all events are send out to event_iface queue.
* This function will be useful in case we want to read events directly from the event_iface queue.
*
* @param periph_set_handle The esp_periph_set_handle_t instance
*
* @return The queue handle
*/
QueueHandle_t esp_periph_set_get_queue(esp_periph_set_handle_t periph_set_handle);
/**
* @brief Call this function to initialize all the listed peripherals.
* @note Work with no task peripheral set only
*
* @param periph_set_handle The esp_periph_set_handle_t instance
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_periph_set_list_init(esp_periph_set_handle_t periph_set_handle);
/**
* @brief Call this function to run all the listed peripherals.
* @note Work with no task peripheral set only
*
* @param periph_set_handle The esp_periph_set_handle_t instance
* @param msg The audio_event_iface_msg_t handle message
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_periph_set_list_run(esp_periph_set_handle_t periph_set_handle, audio_event_iface_msg_t msg);
/**
* @brief Call this function to destroy all the listed peripherals.
* @note Work with no task peripheral set only
*
* @param periph_set_handle The esp_periph_set_handle_t instance
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_periph_set_list_destroy(esp_periph_set_handle_t periph_set_handle);
/**
* @brief Call this function to initialize a new peripheral
*
* @param[in] periph_id The periph identifier
* @param[in] tag The tag name, we named it easy to get in debug logs
*
* @return The peripheral handle
*/
esp_periph_handle_t esp_periph_create(int periph_id, const char *tag);
/**
* @brief Each peripheral has a cycle of sequential operations from initialization,
* execution of commands to destroying the peripheral. These operations are
* represented by functions passed as call parameters to this function.
*
* @param[in] periph The periph
* @param[in] init The initialize
* @param[in] run The run
* @param[in] destroy The destroy
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_periph_set_function(esp_periph_handle_t periph,
esp_periph_func init,
esp_periph_run_func run,
esp_periph_func destroy);
/**
* @brief Add the peripheral to peripherals list, enable and start monitor task (if task stack size > 0)
*
* @param[in] periph_set_handle The esp_periph_set_handle_t instance
* @param[in] periph The peripheral instance
*
* @note
* This peripheral must be first created by calling `esp_periph_create`
*
* @return
* - ESP_OK on success
* - ESP_FAIL when any errors
*/
esp_err_t esp_periph_start(esp_periph_set_handle_t periph_set_handle, esp_periph_handle_t periph);
/**
* @brief Stop monitoring the peripheral, the peripheral state is still kept. This funciton only temporary disables the peripheral.
*
* @param[in] periph The periph
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_periph_stop(esp_periph_handle_t periph);
/**
* @brief When this function is called, the command is passed to the event_iface command queue,
* and the `esp_periph_run_func` of this peripheral will be executed in the main peripheral task.
* This function can be called from any task, basically it only sends a queue to the main peripheral task
*
* @param[in] periph The periph
* @param[in] cmd The command
* @param data The data
* @param[in] data_len The data length
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_periph_send_cmd(esp_periph_handle_t periph, int cmd, void *data, int data_len);
/**
* @brief Similar to `esp_periph_send_cmd`, but it can be called in the hardware interrupt handle
*
* @param[in] periph The periph
* @param[in] cmd The command
* @param data The data
* @param[in] data_len The data length
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_periph_send_cmd_from_isr(esp_periph_handle_t periph, int cmd, void *data, int data_len);
/**
* @brief In addition to sending an event via event_iface, this function will dispatch the `event_handle` callback
* if the event_handle callback is provided at `esp_periph_init`
*
* @param[in] periph The peripheral
* @param[in] event_id The event identifier
* @param data The data
* @param[in] data_len The data length
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_periph_send_event(esp_periph_handle_t periph, int event_id, void *data, int data_len);
/**
* @brief Each peripheral can initialize a timer, which is by default NULL.
* When this function is called, the timer for the peripheral is created
* and it invokes the callback function every interval tick.
*
* @note
* - You do not need to stop or destroy the timer, when the `esp_periph_destroy` function is called, it will stop and destroy all
* - This timer using FreeRTOS Timer, with autoreload = true
*
* @param[in] periph The peripheral
* @param[in] interval_tick The interval tick
* @param[in] callback The callback
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_periph_start_timer(esp_periph_handle_t periph, TickType_t interval_tick, timer_callback callback);
/**
* @brief Stop peripheral timer
*
* @param[in] periph The peripheral
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_periph_stop_timer(esp_periph_handle_t periph);
/**
* @brief Set the user data
*
* @note Make sure the `data` lifetime is sufficient, this function does not copy all data, it only stores the data pointer
*
* @param[in] periph The peripheral
* @param data The data
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_periph_set_data(esp_periph_handle_t periph, void* data);
/**
* @brief Get the user data stored in the peripheral
*
* @param[in] periph The peripheral
*
* @return Peripheral data pointer
*/
void* esp_periph_get_data(esp_periph_handle_t periph);
/**
* @brief Get the current state of peripheral.
*
* @param[in] periph The handle of peripheral
*
* @return The peripharal working state
*/
esp_periph_state_t esp_periph_get_state(esp_periph_handle_t periph);
/**
* @brief Get Peripheral identifier
*
* @param[in] periph The peripheral
*
* @return The peripheral identifier
*/
esp_periph_id_t esp_periph_get_id(esp_periph_handle_t periph);
/**
* @brief Set Peripheral identifier
*
* @param[in] periph The peripheral
* @param[in] periph_id The peripheral identifier
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_periph_set_id(esp_periph_handle_t periph, esp_periph_id_t periph_id);
/**
* @brief Call this to execute `init` function of peripheral instance
*
* @param periph The peripheral handle
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_periph_init(esp_periph_handle_t periph);
/**
* @brief Call this to execute `run` function of peripheral instance
*
* @param periph The peripheral handle
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_periph_run(esp_periph_handle_t periph);
/**
* @brief Call this to execute `destroy` function of peripheral instance
*
* @param periph The peripheral handle
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_periph_destroy(esp_periph_handle_t periph);
/**
* @brief Rigster peripheral on event handle
*
* @param periph The peripheral handle
* @param evts The esp_periph_event_t handle
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_periph_register_on_events(esp_periph_handle_t periph, esp_periph_event_t * evts);
#define periph_tick_get esp_periph_tick_get
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/include/esp_peripherals.h
|
C
|
apache-2.0
| 15,693
|
/*
* 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 _PERIPH_ADC_BUTTON_H_
#define _PERIPH_ADC_BUTTON_H_
#include "driver/adc.h"
#include "adc_button.h"
#include "esp_peripherals.h"
#ifdef __cplusplus
extern "C" {
#endif
#define ADC_BUTTON_STACK_SIZE 2500
#define ADC_BUTTON_TASK_PRIORITY 10
#define ADC_BUTTON_TASK_CORE_ID 0
/**
* @brief The configuration of ADC Button
*/
typedef struct {
adc_arr_t *arr; /*!< An array with configuration of buttons */
int arr_size; /*!< The array size */
adc_btn_task_cfg_t task_cfg; /*!< Adc button task configuration */
} periph_adc_button_cfg_t;
#define PERIPH_ADC_BUTTON_DEFAULT_CONFIG() { \
.task_cfg = { \
.task_stack = ADC_BUTTON_STACK_SIZE, \
.task_core = ADC_BUTTON_TASK_CORE_ID, \
.task_prio = ADC_BUTTON_TASK_PRIORITY,\
.ext_stack = false \
} \
}
typedef enum {
PERIPH_ADC_BUTTON_IDLE = 0,
PERIPH_ADC_BUTTON_PRESSED,
PERIPH_ADC_BUTTON_RELEASE,
PERIPH_ADC_BUTTON_LONG_PRESSED,
PERIPH_ADC_BUTTON_LONG_RELEASE,
} periph_adc_button_event_id_t;
/**
* ESP32 ADC1 channels and GPIO table
* ADC1_CHANNEL_0 - GPIO36
* ADC1_CHANNEL_1 - GPIO37
* ADC1_CHANNEL_2 - GPIO38
* ADC1_CHANNEL_3 - GPIO39
* ADC1_CHANNEL_4 - GPIO32
* ADC1_CHANNEL_5 - GPIO33
* ADC1_CHANNEL_6 - GPIO34
* ADC1_CHANNEL_7 - GPIO35
*
**/
#define ADC_DEFAULT_ARR() { \
.adc_ch = ADC1_CHANNEL_3, \
.adc_level_step = NULL, \
.total_steps = 6, \
.press_judge_time = 3000, \
}
/**
* @brief Create the button peripheral handle for esp_peripherals.
*
* @note The handle created by this function is automatically destroyed when esp_periph_destroy is called.
*
* @param btn_cfg The button configuration.
*
* @return The esp peripheral handle.
*/
esp_periph_handle_t periph_adc_button_init(periph_adc_button_cfg_t *btn_cfg);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/include/periph_adc_button.h
|
C
|
apache-2.0
| 3,240
|
/*
* 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 _PERIPH_AW2013_H_
#define _PERIPH_AW2013_H_
#include "esp_peripherals.h"
#include "aw2013.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
AW2013_MODE_LED,
AW2013_MODE_FADE,
AW2013_MODE_AUTO
} periph_aw2013_mode_t;
/**
* @brief Configuration of aw2013
*/
typedef struct {
periph_aw2013_mode_t mode; /*!< Work mode of aw2013 */
aw2013_brightness_t bright; /*!< The brightness of aw2013 */
uint32_t rgb_value; /*!< rgb value to be set */
} periph_aw2013_cfg_t;
/**
* @brief Initializate aw2013
*
* @param aw2013_cfg Parameters of aw2013
*
* @return
* - NULL Error
* - others Success
*/
esp_periph_handle_t periph_aw2013_init(periph_aw2013_cfg_t *aw2013_cfg);
/**
* @brief Set the brightness of aw2013
*
* @param periph The aw2013's handle
* @param bright The brightness to be set
*
* @return
* - ESP_OK Success
* - ESP_FAIL Error
*/
esp_err_t periph_aw2013_set_brightless(esp_periph_handle_t periph, aw2013_brightness_t bright);
/**
* @brief Set the time periods of aw2013
*
* @param periph The aw2013's handle
* @param time The time period to be set
* @param level The time value to be set
*
* @return
* - ESP_OK Success
* - ESP_FAIL Error
*/
esp_err_t periph_aw2013_set_time(esp_periph_handle_t periph, aw2013_time_t time, aw2013_time_level_t level);
/**
* @brief Set the work mode of aw2013
*
* @param periph The aw2013's handle
* @param mode The work mode to be set
*
* @return
* - ESP_OK Success
* - ESP_FAIL Error
*/
esp_err_t periph_aw2013_set_mode(esp_periph_handle_t periph, periph_aw2013_mode_t mode);
/**
* @brief Set the rgb value of aw2013
*
* @param periph The aw2013's handle
* @param value The value for rgb to be set
*
* @return
* - ESP_OK Success
* - ESP_FAIL Error
*/
esp_err_t periph_aw2013_set_rgb_value(esp_periph_handle_t periph, uint32_t value);
/**
* @brief Set the repeat time in auto flash mode
*
* @param periph The aw2013's handle
* @param cnt Cycle times to be set
*
* @return
* - ESP_OK Success
* - ESP_FAIL Error
*/
esp_err_t periph_aw2013_set_repeat_time(esp_periph_handle_t periph, uint8_t cnt);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/include/periph_aw2013.h
|
C
|
apache-2.0
| 3,504
|
/*
* 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 _BUTTON_DEV_H_
#define _BUTTON_DEV_H_
#include "sys/queue.h"
#include "audio_error.h"
#include "audio_common.h"
#include "esp_peripherals.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief The Button peripheral configuration
*/
typedef struct {
uint64_t gpio_mask; /*!< GPIO Mask using for this Button peripheral, it is BIT(GPIO_NUM), ex: GPIO_SEL_36 | GPIO_SEL_36 */
int long_press_time_ms; /*!< Long press duration in milliseconds, default is 2000ms */
} periph_button_cfg_t;
/**
* @brief Peripheral button event id
*/
typedef enum {
PERIPH_BUTTON_UNCHANGE = 0, /*!< No event */
PERIPH_BUTTON_PRESSED, /*!< When button is pressed */
PERIPH_BUTTON_RELEASE, /*!< When button is released */
PERIPH_BUTTON_LONG_PRESSED, /*!< When button is pressed and kept for more than `long_press_time_ms` */
PERIPH_BUTTON_LONG_RELEASE, /*!< When button is released and event PERIPH_BUTTON_LONG_PRESSED happened */
} periph_button_event_id_t;
/**
* @brief Create the button peripheral handle for esp_peripherals.
*
* @note The handle was created by this function automatically destroy when `esp_periph_destroy` is called
*
* @param but_cfg The but configuration
*
* @return The esp peripheral handle
*/
esp_periph_handle_t periph_button_init(periph_button_cfg_t* but_cfg);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/include/periph_button.h
|
C
|
apache-2.0
| 2,628
|
/*
* 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 _PERIPH_CONSOLE_H_
#define _PERIPH_CONSOLE_H_
#include "sys/queue.h"
#include "audio_error.h"
#include "esp_peripherals.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef esp_err_t (*console_cmd_callback_t)(esp_periph_handle_t periph, int argc, char *argv[]);
#define CONSOLE_DEFAULT_TASK_PRIO (5)
#define CONSOLE_DEFAULT_TASK_STACK (1024*5)
#define CONSOLE_DEFAULT_BUFFER_SIZE (256)
#define CONSOLE_DEFAULT_PROMPT_STRING "esp32>"
/**
* @brief Command structure
*/
typedef struct {
const char *cmd; /*!< Name of command, must be unique */
int id; /*!< Command ID will be sent together when the command is matched */
const char *help; /*!< Explanation of the command */
console_cmd_callback_t func; /*!< Function callback for the command */
} periph_console_cmd_t;
/**
* @brief Console Peripheral configuration
*/
typedef struct {
int command_num; /*!< Total number of commands */
const periph_console_cmd_t *commands; /*!< Pointer to array of commands */
int task_stack; /*!< Console task stack, using default if the value is zero */
int task_prio; /*!< Console task priority (based on freeRTOS priority), using default if the value is zero */
int buffer_size; /*!< Size of console input buffer */
const char *prompt_string; /*!< Console prompt string, using default CONSOLE_PROMPT_STRING if the pointer is NULL */
} periph_console_cfg_t;
/**
* @brief Initialize Console Peripheral
*
* @param config The configuration
*
* @return The esp peripheral handle
*/
esp_periph_handle_t periph_console_init(periph_console_cfg_t *config);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/include/periph_console.h
|
C
|
apache-2.0
| 3,100
|
/*
* 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 _PERIPH_GPIO_ISR_H_
#define _PERIPH_GPIO_ISR_H_
#include "esp_peripherals.h"
#include "driver/gpio.h"
#include "gpio_isr.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @breif Set the gpio number and gpio interruption type
*/
typedef struct {
int gpio_num; /*!< gpio number */
gpio_int_type_t type; /*!< interruption type */
} gpio_isr_info_t;
/**
* @brief The configuration of gpio isr
*/
typedef struct {
int info_size; /*!< number of gpio to be register */
gpio_isr_info_t *gpio_isr_info; /*!< an array of gpio's infomation */
}periph_gpio_isr_cfg_t;
/**
* @brief Create the gpio's interrupt service routines handle for esp_peripherals
*
* @param isr_config The gpio isr configuration
*
* @return The esp peripheral handle
*/
esp_periph_handle_t periph_gpio_isr_init(periph_gpio_isr_cfg_t *isr_config);
/**
* @breif Add a gpio to isr
*
* @param gpio_info The gpio interruption type and gpio number
*
* @return
* - ESP_OK success
* - ESP_FAIL fail
*/
esp_err_t periph_gpio_isr_add(gpio_isr_info_t *gpio_info);
/**
* @brief Unregister a gpio from isr
*
* @param The number of gpio to be unregistered
*
*@return
* - ESP_OK success
* - ESP_FAIL failed
*/
esp_err_t periph_gpio_isr_delete(int gpio_num);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/include/periph_gpio_isr.h
|
C
|
apache-2.0
| 2,624
|
/*
* 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 __PERIPH_IS31FL3216_H__
#define __PERIPH_IS31FL3216_H__
#include "esp_peripherals.h"
#ifdef __cplusplus
extern "C" {
#endif
#define IS31FL3216_CH_NUM 16 //Should be less than or equal to 16
#define BLUE_LED_MAX_NUM 12
typedef enum {
IS31FL3216_STATE_UNKNOWN,
IS31FL3216_STATE_OFF,
IS31FL3216_STATE_ON,
IS31FL3216_STATE_FLASH,
IS31FL3216_STATE_BY_AUDIO,
IS31FL3216_STATE_SHIFT,
} periph_is31fl3216_state_t;
typedef enum {
PERIPH_IS31_SHIFT_MODE_UNKNOWN,
PERIPH_IS31_SHIFT_MODE_ACC, /*!< accumulation mode */
PERIPH_IS31_SHIFT_MODE_SINGLE,
} periph_is31_shift_mode_t;
/**
* @brief The configuration of is31fl3216
*/
typedef struct {
uint32_t duty[IS31FL3216_CH_NUM]; /*!<An array of the is31fl3216's duty*/
uint16_t is31fl3216_pattern; /*!<Current enable channel*/
periph_is31fl3216_state_t state; /*!<The state of all the channels*/
} periph_is31fl3216_cfg_t;
/**
* @brief Initializate the is31fl3216
*
* @param is31fl3216_config
*
* @return
* - ESP_OK Success
* - ESP_FAIL Fail
*/
esp_periph_handle_t periph_is31fl3216_init(periph_is31fl3216_cfg_t *is31fl3216_config);
/**
* @brief Set the state of all the channels
*
* @param periph The is31fl3216 handle
* @param state The state of all channels
*
* @return
* - ESP_OK Success
* - ESP_FAIL Fail
*/
esp_err_t periph_is31fl3216_set_state(esp_periph_handle_t periph, periph_is31fl3216_state_t state);
/**
* @brief Set the current enable channels
*
* @param periph The is31fl3216 handle
* @param blink_pattern The bit pattern of enabled channels
*
* @return
* - ESP_OK Success
* - ESP_FAIL Fail
*/
esp_err_t periph_is31fl3216_set_blink_pattern(esp_periph_handle_t periph, uint16_t blink_pattern);
/**
* @brief Set the duty of the channel
*
* @param periph The is31fl3216 handle
* @param index The channel number
* @param value The value of the channel's duty to be set
*
* @return
* - ESP_OK Success
* - ESP_FAIL Fail
*/
esp_err_t periph_is31fl3216_set_duty(esp_periph_handle_t periph, uint8_t index, uint8_t value);
/**
* @brief Set the duty step of flash
*
* @param periph The is31fl3216 handle
* @param step The step of flash
*
* @return
* - ESP_OK Success
* - ESP_FAIL Fail
*/
esp_err_t periph_is31fl3216_set_duty_step(esp_periph_handle_t periph, uint8_t step);
/**
* @brief Set the internval time
*
* @param periph The is31fl3216 handle
* @param interval_ms Time of interval
*
* @return
* - ESP_OK Success
* - ESP_FAIL Fail
*/
esp_err_t periph_is31fl3216_set_interval(esp_periph_handle_t periph, uint16_t interval_ms);
/**
* @brief Set the shift mode
*
* @param periph The is31fl3216 handle
* @param mode Mode of periph_is31_shift_mode_t
*
* @return
* - ESP_OK Success
* - ESP_FAIL Fail
*/
esp_err_t periph_is31fl3216_set_shift_mode(esp_periph_handle_t periph, periph_is31_shift_mode_t mode);
/**
* @brief Set the light on numbers
*
* @param periph The is31fl3216 handle
* @param light_on_num Enabled led number
* @param max_light_num Maximum led number
*
* @return
* - ESP_OK Success
* - ESP_FAIL Fail
*/
esp_err_t periph_is31fl3216_set_light_on_num(esp_periph_handle_t periph, uint16_t light_on_num, uint16_t max_light_num);
/**
* @brief Set the action time
*
* @param periph The is31fl3216 handle
* @param act_ms Action time, unit is millisecond, 0 is infinite
*
* @return
* - ESP_OK Success
* - ESP_FAIL Fail
*/
esp_err_t periph_is31fl3216_set_act_time(esp_periph_handle_t periph, uint16_t act_ms);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/include/periph_is31fl3216.h
|
C
|
apache-2.0
| 5,360
|
/*
* 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 _PERIPH_LED_H_
#define _PERIPH_LED_H_
#include "sys/queue.h"
#include "driver/ledc.h"
#include "esp_err.h"
#include "audio_common.h"
#include "esp_peripherals.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Peripheral LED event id
*/
typedef enum {
PERIPH_LED_UNCHANGE = 0, /*!< No event */
PERIPH_LED_BLINK_FINISH, /*!< When LED blink is finished */
} periph_led_event_id_t;
/**
* @brief Peripheral LED idle output level
*/
typedef enum {
PERIPH_LED_IDLE_LEVEL_LOW, /*!< Low level output */
PERIPH_LED_IDLE_LEVEL_HIGH /*!< High level output */
} periph_led_idle_level_t;
/**
* @brief The LED peripheral configuration
*/
typedef struct {
ledc_mode_t led_speed_mode; /*!< LEDC speed speed_mode, high-speed mode or low-speed mode */
ledc_timer_bit_t led_duty_resolution; /*!< LEDC channel duty resolution */
ledc_timer_t led_timer_num; /*!< Select the timer source of channel (0 - 3) */
uint32_t led_freq_hz; /*!< LEDC timer frequency (Hz) */
int gpio_num; /*!< Optional, < 0 invalid gpio number */
} periph_led_cfg_t;
/**
* @brief Create the LED peripheral handle for esp_peripherals
*
* @note The handle was created by this function automatically destroy when `esp_periph_destroy` is called
*
* @param config The configuration
*
* @return The esp peripheral handle
*/
esp_periph_handle_t periph_led_init(periph_led_cfg_t* config);
/**
* @brief Bink LED Peripheral, this function will automatically configure the gpio_num to control the LED,
* with `time_on_ms` as the time (in milliseconds) switch from OFF to ON (or ON if fade is disabled),
* and `time_off_ms` as the time (in milliseconds) switch from ON to OFF (or OFF if fade is disabled).
* When switching from ON -> OFF and vice versa, the loop decreases once, and will turn off the effect when the loop is 0.
* With a loop value less than 0, the LED effect will loop endlessly.
* PERIPH_LED_BLINK_FINISH events will be sent at each end of loop
*
* @param[in] periph The LED periph
* @param[in] gpio_num The gpio number
* @param[in] time_on_ms The time on milliseconds
* @param[in] time_off_ms The time off milliseconds
* @param[in] fade Fading enabled
* @param[in] loop Loop
* @param[in] level idle level
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_led_blink(esp_periph_handle_t periph, int gpio_num, int time_on_ms, int time_off_ms, bool fade, int loop, periph_led_idle_level_t level);
/**
* @brief Stop Blink the LED
*
* @param[in] periph The periph
* @param[in] gpio_num The gpio number
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_led_stop(esp_periph_handle_t periph, int gpio_num);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/include/periph_led.h
|
C
|
apache-2.0
| 4,176
|
/*
* 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 _SDCARD_DEV_H_
#define _SDCARD_DEV_H_
#include "sys/queue.h"
#include "audio_error.h"
#include "audio_common.h"
#include "esp_peripherals.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Peripheral sdcard event id
*/
typedef enum {
SDCARD_STATUS_UNKNOWN, /*!< No event */
SDCARD_STATUS_CARD_DETECT_CHANGE, /*!< Detect changes in the card_detect pin */
SDCARD_STATUS_MOUNTED, /*!< SDCARD mounted successfully */
SDCARD_STATUS_UNMOUNTED, /*!< SDCARD unmounted successfully */
SDCARD_STATUS_MOUNT_ERROR, /*!< SDCARD mount error */
SDCARD_STATUS_UNMOUNT_ERROR, /*!< SDCARD unmount error */
} periph_sdcard_event_id_t;
/**
* @brief SD card mode, SPI, 1-line SD mode, 4-line SD mode
*
*/
typedef enum {
SD_MODE_SPI = 0x0, /*!< sd_card SPI*/
SD_MODE_1_LINE = 0x1, /*!< sd_card 1-line SD mode*/
SD_MODE_4_LINE = 0x2, /*!< sd_card 4-line SD mode*/
SD_MODE_MAX,
} periph_sdcard_mode_t;
/**
* @brief The SD Card Peripheral configuration
*/
typedef struct {
int card_detect_pin; /*!< Card detect gpio number */
const char* root; /*!< Base path for vfs */
periph_sdcard_mode_t mode; /*!< card mode*/
} periph_sdcard_cfg_t;
/**
* @brief Create the sdcard peripheral handle for esp_peripherals
*
* @note The handle was created by this function automatically destroy when `esp_periph_destroy` is called
*
* @param sdcard_config The sdcard configuration
*
* @return The esp peripheral handle
*/
esp_periph_handle_t periph_sdcard_init(periph_sdcard_cfg_t* sdcard_config);
/**
* @brief Check the sdcard is mounted or not.
*
* @param[in] periph The periph
*
* @return SDCARD mounted state
*/
bool periph_sdcard_is_mounted(esp_periph_handle_t periph);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/include/periph_sdcard.h
|
C
|
apache-2.0
| 3,113
|
/*
* 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 _SPIFFS_DEV_H_
#define _SPIFFS_DEV_H_
#include "sys/queue.h"
#include "audio_error.h"
#include "audio_common.h"
#include "esp_peripherals.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Peripheral spiffs event id
*/
typedef enum {
SPIFFS_STATUS_UNKNOWN, /*!< No event */
SPIFFS_STATUS_MOUNTED, /*!< SPIFFS mounted successfully */
SPIFFS_STATUS_UNMOUNTED, /*!< SPIFFS unmounted successfully */
SPIFFS_STATUS_MOUNT_ERROR, /*!< SPIFFS mount error */
SPIFFS_STATUS_UNMOUNT_ERROR, /*!< SPIFFS unmount error */
} periph_spiffs_event_id_t;
/**
* @brief The SPIFFS Peripheral configuration
*/
typedef struct {
const char* root; /*!< Base path for vfs */
const char* partition_label; /*!< Optional, label of SPIFFS partition to use. If set to NULL, first partition with subtype=spiffs will be used. */
size_t max_files; /*!< Maximum number of files that could be open at the same time. */
bool format_if_mount_failed; /*!< If true, it will format the file system if it fails to mount. */
} periph_spiffs_cfg_t;
/**
* @brief Create the spiffs peripheral handle for esp_peripherals
*
* @note The handle created by this function will be automatically destroyed when `esp_periph_destroy` is called
*
* @param spiffs_config The spiffs configuration
*
* @return The esp peripheral handle
*/
esp_periph_handle_t periph_spiffs_init(periph_spiffs_cfg_t* spiffs_config);
/**
* @brief Check if the SPIFFS is mounted or not.
*
* @param[in] periph The periph
*
* @return SPIFFS mounted state
*/
bool periph_spiffs_is_mounted(esp_periph_handle_t periph);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/include/periph_spiffs.h
|
C
|
apache-2.0
| 3,002
|
/*
* 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 _TOUCH_DEV_H_
#define _TOUCH_DEV_H_
#include "sys/queue.h"
#include "audio_error.h"
#include "audio_common.h"
#include "esp_peripherals.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Touch pad selection
*/
typedef enum {
TOUCH_PAD_SEL0 = BIT(0),
TOUCH_PAD_SEL1 = BIT(1),
TOUCH_PAD_SEL2 = BIT(2),
TOUCH_PAD_SEL3 = BIT(3),
TOUCH_PAD_SEL4 = BIT(4),
TOUCH_PAD_SEL5 = BIT(5),
TOUCH_PAD_SEL6 = BIT(6),
TOUCH_PAD_SEL7 = BIT(7),
TOUCH_PAD_SEL8 = BIT(8),
TOUCH_PAD_SEL9 = BIT(9),
} esp_touch_pad_sel_t;
/**
* @brief The Touch peripheral configuration
*/
typedef struct {
int touch_mask; /*!< Touch pad mask using for this Touch peripheral, ex: TOUCH_PAD_SEL0 | TOUCH_PAD_SEL1 */
int tap_threshold_percent; /*!< Tap threshold percent, Tap event will be determined if the percentage value is less than the non-touch value */
int long_tap_time_ms; /*!< Long tap duration in milliseconds, default is 2000ms, PERIPH_TOUCH_LONG_TAP will be occurred if TAP and time hold longer than this value */
} periph_touch_cfg_t;
/**
* @brief Peripheral touch event id
*/
typedef enum {
PERIPH_TOUCH_UNCHANGE = 0, /*!< No event */
PERIPH_TOUCH_TAP, /*!< When touch pad is tapped */
PERIPH_TOUCH_RELEASE, /*!< When touch pad is released after tap */
PERIPH_TOUCH_LONG_TAP, /*!< When touch pad is tapped and held after `long_tap_time_ms` time */
PERIPH_TOUCH_LONG_RELEASE, /*!< When touch pad is released after long tap */
} periph_touch_event_id_t;
/**
* @brief Create the touch peripheral handle for esp_peripherals
*
* @note The handle was created by this function automatically destroy when `esp_periph_destroy` is called
*
* @param config The configuration
*
* @return The esp peripheral handle
*/
esp_periph_handle_t periph_touch_init(periph_touch_cfg_t* config);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/include/periph_touch.h
|
C
|
apache-2.0
| 3,198
|
/*
* 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 _DEV_WIFI_H_
#define _DEV_WIFI_H_
#include "sys/queue.h"
#include "audio_error.h"
#include "audio_common.h"
#include "esp_peripherals.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Peripheral Wi-Fi event id
*/
typedef enum {
PERIPH_WIFI_UNCHANGE = 0,
PERIPH_WIFI_CONNECTING,
PERIPH_WIFI_CONNECTED,
PERIPH_WIFI_DISCONNECTED,
PERIPH_WIFI_SETTING,
PERIPH_WIFI_CONFIG_DONE,
PERIPH_WIFI_CONFIG_ERROR,
PERIPH_WIFI_ERROR,
} periph_wifi_state_t;
/**
* @brief Wi-Fi setup mode type
*/
typedef enum {
WIFI_CONFIG_ESPTOUCH, /*!< Using smartconfig with ESPTOUCH protocol */
WIFI_CONFIG_AIRKISS, /*!< Using smartconfig with AIRKISS protocol */
WIFI_CONFIG_ESPTOUCH_AIRKISS, /*!< Using smartconfig with ESPTOUCH_AIRKISS protocol */
WIFI_CONFIG_WPS, /*!< Using WPS (not support) */
WIFI_CONFIG_BLUEFI, /*!< Using BLUEFI*/
WIFI_CONFIG_WEB, /*!< Using HTTP Server (not support) */
} periph_wifi_config_mode_t;
/**
* @brief The WPA2 enterprise peripheral configuration
*/
typedef struct {
bool diasble_wpa2_e; /*!< Disable wpa2 enterprise */
int eap_method; /*!< TLS: 0, PEAP: 1, TTLS: 2 */
char *ca_pem_start; /*!< binary wpa2 ca pem start */
char *ca_pem_end; /*!< binary wpa2 ca pem end */
char *wpa2_e_cert_start; /*!< binary wpa2 cert start */
char *wpa2_e_cert_end; /*!< binary wpa2 cert end */
char *wpa2_e_key_start; /*!< binary wpa2 key start */
char *wpa2_e_key_end; /*!< binary wpa2 key end */
const char *eap_id; /*!< Identity in phase 1 of EAP procedure */
const char *eap_username; /*!< Username for EAP method (PEAP and TTLS) */
const char *eap_password; /*!< Password for EAP method (PEAP and TTLS) */
} periph_wpa2_enterprise_cfg_t;
/**
* @brief The Wi-Fi peripheral configuration
*/
typedef struct {
bool disable_auto_reconnect; /*!< Disable Wi-Fi auto reconnect */
int reconnect_timeout_ms; /*!< The reconnect timeout after disconnected from Wi-Fi network */
const char *ssid; /*!< SSID of target AP */
const char *password; /*!< password of target AP */
periph_wpa2_enterprise_cfg_t wpa2_e_cfg; /*!< wpa2 enterprise config */
} periph_wifi_cfg_t;
/**
* @brief Create the wifi peripheral handle for esp_peripherals
*
* @note The handle was created by this function automatically destroy when `esp_periph_destroy` is called
*
* @param config The configuration
*
* @return The esp peripheral handle
*/
esp_periph_handle_t periph_wifi_init(periph_wifi_cfg_t* config);
/**
* @brief This function will block current thread (in `tick_to_wait` tick) and wait until ESP32 connected to the Wi-Fi network, and got ip
*
* @param[in] periph The periph
* @param[in] tick_to_wait The tick to wait
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_wifi_wait_for_connected(esp_periph_handle_t periph, TickType_t tick_to_wait);
/**
* @brief Check the Wi-Fi connection status
*
* @param[in] periph The periph
*
* @return Wi-Fi network status
*/
periph_wifi_state_t periph_wifi_is_connected(esp_periph_handle_t periph);
/**
* @brief Start Wi-Fi network setup in `mode`
*
* @param[in] periph The periph
* @param[in] mode The mode
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_wifi_config_start(esp_periph_handle_t periph, periph_wifi_config_mode_t mode);
/**
* @brief Wait for Wi-Fi setup done
* @param[in] periph The periph
* @param[in] tick_to_wait The tick to wait
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_wifi_config_wait_done(esp_periph_handle_t periph, TickType_t tick_to_wait);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/include/periph_wifi.h
|
C
|
apache-2.0
| 5,363
|
/*
* 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 _PERIPH_WS2812_DRIVER_H
#define _PERIPH_WS2812_DRIVER_H
#include "esp_peripherals.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief The RGB peripheral value
*/
typedef uint32_t periph_rgb_value;
#define make_rgb_value(x, y, z) (((int)(z) << 16) + ((int)(y) << 8 )+ (x))
#define LED2812_COLOR_BLACK make_rgb_value(0, 0, 0)
#define LED2812_COLOR_BLUE make_rgb_value(0, 0, 255)
#define LED2812_COLOR_GREEN make_rgb_value(0, 255, 0)
#define LED2812_COLOR_CYAN make_rgb_value(0, 255, 255)
#define LED2812_COLOR_RED make_rgb_value(255, 0, 0)
#define LED2812_COLOR_PURPLE make_rgb_value(255, 0, 255)
#define LED2812_COLOR_YELLOW make_rgb_value(255, 255, 0)
#define LED2812_COLOR_WHITE make_rgb_value(255, 255, 255)
#define LED2812_COLOR_ORANGE make_rgb_value(255, 165, 0)
/**
* @brief The ws2812 peripheral configuration
*/
typedef struct {
int gpio_num; /*!< The GPIO number of ws2812*/
int led_num; /*!< The number of ws2812 */
}periph_ws2812_cfg_t;
/**
* @brief The periph ws2812 mode
*/
typedef enum {
PERIPH_WS2812_BLINK,
PERIPH_WS2812_FADE,
PERIPH_WS2812_ONE,
} periph_ws2812_mode_t;
/**
* @brief The periph ws2812 control config
*/
typedef struct periph_ws2812_ctrl_cfg {
periph_rgb_value color; /*!< The RGB value */
uint32_t time_on_ms; /*!< The time on milliseconds, suggest min is 100 ms */
uint32_t time_off_ms; /*!< The time off milliseconds, suggest min is 100 ms */
uint32_t loop; /*!< The times offloop */
periph_ws2812_mode_t mode; /*!< ws2812 mode (setting color, blink or fade) */
} periph_ws2812_ctrl_cfg_t;
/**
* @brief Create the ws2812 peripheral handle for esp_peripherals
*
* @note The handle was created by this function automatically destroy when `esp_periph_destroy` is called
*
* @param config The configuration
*
* @return The esp peripheral handle
*/
esp_periph_handle_t periph_ws2812_init(periph_ws2812_cfg_t *config);
/**
* @brief Control ws2812 Peripheral
*
* @param[in] periph The ws2812 periph
* @param[in] control_cfg The ws2812 color config
* @param[in] ctx The ctx
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_ws2812_control(esp_periph_handle_t periph, periph_ws2812_ctrl_cfg_t *control_cfg, void *ctx);
/**
* @brief Stop ws2812
*
* @param[in] periph The periph
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t periph_ws2812_stop(esp_periph_handle_t periph);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/include/periph_ws2812.h
|
C
|
apache-2.0
| 3,917
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD>
*
* Permission is hereby granted for use on ESPRESSIF SYSTEMS products only, 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 "driver/i2c.h"
#include "esp_log.h"
#include "IS31FL3216.h"
#include "i2c_bus.h"
#include "audio_mem.h"
#define IS31FL3216_WRITE_BIT 0x00
#define I2C_MASTER_SCL_IO 23 /*!< gpio number for I2C master clock */
#define I2C_MASTER_SDA_IO 18 /*!< gpio number for I2C master data */
#define I2C_MASTER_NUM I2C_NUM_0 /*!< I2C port number for master dev */
#define I2C_MASTER_FREQ_HZ 100000 /*!< I2C master clock frequency */
#define IS31FL3216_ADDRESS 0xE8 /*!< I2C Addr*/
#define IS31_ERROR_CHECK(con) if(!(con)) {ESP_LOGE(TAG,"err line: %d", __LINE__);}
#define IS31_PARAM_CHECK(con) if(!(con)) {ESP_LOGE(TAG,"Parameter error: %d", __LINE__);}
#define IS31_CHECK_I2C_RES(res) if(ret == ESP_FAIL) {ESP_LOGE(TAG, "Is31fl3216[%s]: FAIL\n", __FUNCTION__);} \
else if(ret == ESP_ERR_TIMEOUT) {ESP_LOGE(TAG, "Is31fl3216[%s]: TIMEOUT\n", __FUNCTION__);}
typedef struct {
i2c_bus_handle_t bus;
uint16_t addr;
} is31fl3216_dev_t;
uint8_t Is31Value[10] = {0x80, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static char *TAG = "IS31";
/**
* @brief set software shutdown mode
*/
static esp_err_t is31fl3216_write_reg(is31fl3216_handle_t handle, is31fl3216_reg_t regAddr, uint8_t *data, uint8_t data_num)
{
IS31_PARAM_CHECK(NULL != data);
is31fl3216_dev_t *dev = (is31fl3216_dev_t *) handle;
esp_err_t ret = i2c_bus_write_bytes(dev->bus, IS31FL3216_ADDRESS | IS31FL3216_WRITE_BIT, (uint8_t *)®Addr, 1, data, data_num);
return ret;
}
/**
* @brief change channels PWM duty cycle data register
*/
static esp_err_t is31fl3218S_channel_duty_by_bits(is31fl3216_handle_t handle, uint32_t by_bits, uint8_t duty)
{
for (int i = 0; i < IS31FL3216_CH_NUM_MAX; i++) {
if ((by_bits >> i) & 0x1) {
esp_err_t ret = is31fl3216_write_reg(handle, IS31FL3216_REG_PWM_16 + (IS31FL3216_CH_NUM_MAX - i - 1), &duty, 1);
if (ret == ESP_OK) {
//PASS
} else {
IS31_CHECK_I2C_RES(ret);
return ret;
}
}
}
return ESP_OK;
}
/**
* @brief Load PWM Register and LED Control Registers data
*/
esp_err_t is31fl3216_update_reg(is31fl3216_handle_t handle)
{
IS31_PARAM_CHECK(NULL != handle);
uint8_t m = 0;
return is31fl3216_write_reg(handle, IS31FL3216_REG_UPDATE, &m, 1);
}
/**
* @brief set software shutdown mode
*/
esp_err_t is31fl3216_power(is31fl3216_handle_t handle, is31fl3216_pwr_t mode)
{
IS31_PARAM_CHECK(NULL != handle);
if (IS31FL3216_PWR_SHUTDOWN == mode) {
Is31Value[IS31FL3216_REG_CONFIG] = (Is31Value[IS31FL3216_REG_CONFIG] & (~(1 << 7))) | (1 << 7);
} else if (IS31FL3216_PWR_NORMAL == mode) {
Is31Value[IS31FL3216_REG_CONFIG] = (Is31Value[IS31FL3216_REG_CONFIG] & (~(1 << 7)));
} else {
return ESP_FAIL;
}
esp_err_t ret = is31fl3216_write_reg(handle, IS31FL3216_REG_CONFIG, (uint8_t *) &Is31Value[IS31FL3216_REG_CONFIG], 1);
return ret;
}
esp_err_t is31fl3216_work_mode_set(is31fl3216_handle_t handle, is31fl3216_work_mode_t mode)
{
IS31_PARAM_CHECK(NULL != handle);
if (IS31FL3216_MODE_PWM == mode) {
Is31Value[IS31FL3216_REG_CONFIG] = (Is31Value[IS31FL3216_REG_CONFIG] & (~(3 << 5)));
} else if (IS31FL3216_MODE_AUTO_FRAME == mode) {
Is31Value[IS31FL3216_REG_CONFIG] = (Is31Value[IS31FL3216_REG_CONFIG] & (~(3 << 5))) | (1 << 5);
} else if (IS31FL3216_MODE_FRAME == mode) {
Is31Value[IS31FL3216_REG_CONFIG] = (Is31Value[IS31FL3216_REG_CONFIG] & (~(3 << 5))) | (2 << 5);
} else {
return ESP_FAIL;
}
esp_err_t ret = is31fl3216_write_reg(handle, IS31FL3216_REG_CONFIG, (uint8_t *) &Is31Value[IS31FL3216_REG_CONFIG], 1);
return ret;
}
/**
* @brief change channels PWM duty cycle data register
*/
esp_err_t is31fl3216_ch_duty_set(is31fl3216_handle_t handle, is31_pwm_channel_t ch_bits, uint8_t duty)
{
esp_err_t ret = ESP_OK;
IS31_PARAM_CHECK(NULL != handle);
ret = is31fl3218S_channel_duty_by_bits(handle, ch_bits, duty);
if (ret != ESP_OK) {
IS31_CHECK_I2C_RES(ret);
return ret;
}
ret = is31fl3216_update_reg(handle);
if (ret != ESP_OK) {
IS31_CHECK_I2C_RES(ret);
return ret;
}
return ESP_OK;
}
/**
* @brief change channels PWM duty cycle data register
*/
esp_err_t is31fl3216_ch_enable(is31fl3216_handle_t handle, is31_pwm_channel_t ch_bits)
{
esp_err_t ret = ESP_OK;
IS31_PARAM_CHECK(NULL != handle);
uint16_t value = 0;
for (int i = 0; i < IS31FL3216_CH_NUM_MAX; ++i) {
if ((ch_bits >> i) & 0x01) {
value |= (1 << i);
}
}
Is31Value[IS31FL3216_REG_LED_CTRL_H] |= value >> 8;
Is31Value[IS31FL3216_REG_LED_CTRL_L] |= value;
ret = is31fl3216_write_reg(handle, IS31FL3216_REG_LED_CTRL_H, &Is31Value[IS31FL3216_REG_LED_CTRL_H], 2);
return ret;
}
/**
* @brief change channels PWM duty cycle data register
*/
esp_err_t is31fl3216_ch_disable(is31fl3216_handle_t handle, is31_pwm_channel_t ch_bits)
{
esp_err_t ret = ESP_OK;
IS31_PARAM_CHECK(NULL != handle);
uint16_t value = ((uint16_t)Is31Value[IS31FL3216_REG_LED_CTRL_H]) << 8;
value |= Is31Value[IS31FL3216_REG_LED_CTRL_L];
for (int i = 0; i < IS31FL3216_CH_NUM_MAX; ++i) {
if ((ch_bits >> i) & 0x01) {
value = value & (~(1 << i));
}
}
Is31Value[IS31FL3216_REG_LED_CTRL_H] = value >> 8;
Is31Value[IS31FL3216_REG_LED_CTRL_L] = value;
ret = is31fl3216_write_reg(handle, IS31FL3216_REG_LED_CTRL_H, &Is31Value[IS31FL3216_REG_LED_CTRL_H], 2);
return ret;
}
esp_err_t is31fl3216_cur_mode_set(is31fl3216_handle_t handle, is31fl3216_cur_mode_t mode)
{
IS31_PARAM_CHECK(NULL != handle);
if (IS31FL3216_CUR_MODE_REXT == mode) {
Is31Value[IS31FL3216_REG_CONFIG] = (Is31Value[IS31FL3216_REG_CONFIG] & (~(1 << 4)));
} else if (IS31FL3216_CUR_MODE_AUDIO == mode) {
Is31Value[IS31FL3216_REG_CONFIG] = (Is31Value[IS31FL3216_REG_CONFIG] & (~(1 << 4))) | (1 << 4);
} else {
return ESP_FAIL;
}
esp_err_t ret = is31fl3216_write_reg(handle, IS31FL3216_REG_CONFIG, (uint8_t *) &Is31Value[IS31FL3216_REG_CONFIG], 1);
return ret;
}
esp_err_t is31fl3216_cur_value_set(is31fl3216_handle_t handle, is31fl3216_cur_value_t value)
{
IS31_PARAM_CHECK(NULL != handle);
Is31Value[IS31FL3216_REG_LED_EFFECT] = (Is31Value[IS31FL3216_REG_LED_EFFECT] & (~(7 << 4))) | value << 4;
esp_err_t ret = is31fl3216_write_reg(handle, IS31FL3216_REG_LED_EFFECT, &Is31Value[IS31FL3216_REG_LED_EFFECT], 1);
return ret;
}
esp_err_t is31fl3216_ags_value_set(is31fl3216_handle_t handle, is31fl3216_ags_value_t value)
{
IS31_PARAM_CHECK(NULL != handle);
Is31Value[IS31FL3216_REG_LED_EFFECT] = (Is31Value[IS31FL3216_REG_LED_EFFECT] & (~(7 << 0))) | value << 0;
esp_err_t ret = is31fl3216_write_reg(handle, IS31FL3216_REG_LED_EFFECT, &Is31Value[IS31FL3216_REG_LED_EFFECT], 1);
return ret;
}
esp_err_t is31fl3216_agc_cfg(is31fl3216_handle_t handle, uint32_t en)
{
IS31_PARAM_CHECK(NULL != handle);
Is31Value[IS31FL3216_REG_LED_EFFECT] = (Is31Value[IS31FL3216_REG_LED_EFFECT] & (~(1 << 3))) | en << 3;
esp_err_t ret = is31fl3216_write_reg(handle, IS31FL3216_REG_LED_EFFECT, &Is31Value[IS31FL3216_REG_LED_EFFECT], 1);
return ret;
}
esp_err_t is31fl3216_cascade_mode_set(is31fl3216_handle_t handle, is31fl3216_cascade_mode_t mode)
{
IS31_PARAM_CHECK(NULL != handle);
Is31Value[IS31FL3216_REG_LED_EFFECT] = (Is31Value[IS31FL3216_REG_LED_EFFECT] & (~(1 << 7))) | mode << 7;
esp_err_t ret = is31fl3216_write_reg(handle, IS31FL3216_REG_LED_EFFECT, &Is31Value[IS31FL3216_REG_LED_EFFECT], 1);
return ret;
}
esp_err_t is31fl3216_sample_rate_set(is31fl3216_handle_t handle, uint32_t value)
{
IS31_PARAM_CHECK(NULL != handle);
uint8_t dat = value;
esp_err_t ret = is31fl3216_write_reg(handle, IS31FL3216_REG_ADC_RATE, &dat, 1);
return ret;
}
esp_err_t is31fl3216_frame_time_set(is31fl3216_handle_t handle, is31fl3216_delay_time_t time)
{
IS31_PARAM_CHECK(NULL != handle);
uint8_t dat = time << 5;
esp_err_t ret = is31fl3216_write_reg(handle, IS31FL3216_REG_FRAME_DELAY, &dat, 1);
return ret;
}
esp_err_t is31fl3216_first_frame_set(is31fl3216_handle_t handle, uint32_t frame)
{
IS31_PARAM_CHECK(NULL != handle);
uint8_t dat = frame << 5;
esp_err_t ret = is31fl3216_write_reg(handle, IS31FL3216_REG_FRAME_START, &dat, 1);
return ret;
}
esp_err_t is31fl3216_frame_value_set(is31fl3216_handle_t handle, uint32_t num, uint8_t *data, uint32_t len)
{
IS31_PARAM_CHECK(NULL != handle);
IS31_PARAM_CHECK(NULL != data);
uint8_t startAddr = IS31FL3216_REG_FRAME1_CTRL + (num - 1) * 18;
esp_err_t ret = is31fl3216_write_reg(handle, startAddr, data, len);
return ret;
}
esp_err_t is31fl3216_reset(is31fl3216_handle_t handle)
{
esp_err_t ret = ESP_OK;
uint8_t dat = 0x00;
IS31_PARAM_CHECK(NULL != handle);
ret = is31fl3216_power(handle, IS31FL3216_PWR_NORMAL);
if (ret) {
return ret;
}
for (int i = 0; i < IS31FL3216_CH_NUM_MAX; ++i) {
ret = is31fl3216_ch_duty_set(handle, 1 << i, 0);
if (ret) {
return ret;
}
}
ret = is31fl3216_ch_enable(handle, IS31FL3216_CH_ALL);
if (ret) {
return ret;
}
ret = is31fl3216_write_reg(handle, IS31FL3216_REG_LED_EFFECT, &dat, 1);
if (ret) {
return ret;
}
ret = is31fl3216_write_reg(handle, IS31FL3216_REG_CH_CONFIG, &dat, 1);
return ret;
}
/**
* @brief i2c master initialization
*/
is31fl3216_handle_t is31fl3216_init(void)
{
i2c_config_t conf = {0};
conf.mode = I2C_MODE_MASTER;
conf.sda_io_num = I2C_MASTER_SDA_IO;
conf.sda_pullup_en = GPIO_PULLUP_ENABLE;
conf.scl_io_num = I2C_MASTER_SCL_IO;
conf.scl_pullup_en = GPIO_PULLUP_ENABLE;
conf.master.clk_speed = I2C_MASTER_FREQ_HZ;
is31fl3216_dev_t *led = (is31fl3216_dev_t *) audio_calloc(1, sizeof(is31fl3216_dev_t));
led->bus = i2c_bus_create(I2C_MASTER_NUM, &conf);
led->addr = IS31FL3216_ADDRESS;
IS31_ERROR_CHECK(ESP_OK == is31fl3216_power(led, IS31FL3216_PWR_NORMAL));
IS31_ERROR_CHECK(ESP_OK == is31fl3216_cur_mode_set(led, IS31FL3216_CUR_MODE_REXT));
IS31_ERROR_CHECK(ESP_OK == is31fl3216_cur_value_set(led, IS31FL3216_CUR_0_75));
return (is31fl3216_handle_t) led;
}
esp_err_t is31fl3216_deinit(is31fl3216_handle_t handle)
{
is31fl3216_dev_t *dev = (is31fl3216_dev_t *) handle;
if (dev->bus) {
i2c_bus_delete(dev->bus);
dev->bus = NULL;
}
audio_free(dev);
return ESP_OK;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/lib/IS31FL3216/IS31FL3216.c
|
C
|
apache-2.0
| 12,044
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD>
*
* Permission is hereby granted for use on ESPRESSIF SYSTEMS products only, 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 _IOT_IS31FL3216_H_
#define _IOT_IS31FL3216_H_
#include "driver/i2c.h"
#ifdef __cplusplus
extern "C" {
#endif
#define IS31FL3216_CH_NUM_MAX 16
#define IS31FL3216_DUTY_MAX 255
typedef enum {
IS31FL3216_PWR_NORMAL = 0, /**< Normal operation */
IS31FL3216_PWR_SHUTDOWN, /**< Software shutdown mode */
IS31FL3216_PWR_MAX,
} is31fl3216_pwr_t;
typedef enum {
IS31FL3216_MODE_PWM = 0, /**< PWM control mode operation*/
IS31FL3216_MODE_AUTO_FRAME, /**< Auto frame play mode operation */
IS31FL3216_MODE_FRAME, /**< Audio frame mode operation */
IS31FL3216_MODE_MAX,
} is31fl3216_work_mode_t;
typedef enum {
IS31FL3216_CUR_MODE_REXT = 0, /**< Output current is set by register */
IS31FL3216_CUR_MODE_AUDIO, /**< Output current is modulated by audio signal */
IS31FL3216_CUR_MODE_MAX,
} is31fl3216_cur_mode_t;
typedef enum {
IS31FL3216_CUR_1_00 = 0, /**< Output Current Selection */
IS31FL3216_CUR_0_75,
IS31FL3216_CUR_0_50,
IS31FL3216_CUR_0_25,
IS31FL3216_CUR_2_00,
IS31FL3216_CUR_1_75,
IS31FL3216_CUR_1_50,
IS31FL3216_CUR_1_25,
IS31FL3216_CUR_MAX,
} is31fl3216_cur_value_t;
typedef enum {
IS31FL3216_CASCADE_MASTER = 0, /**< Chip Cascade Mode */
IS31FL3216_CASCADE_SLAVE,
} is31fl3216_cascade_mode_t;
typedef enum {
IS31FL3216_AGS_0DB = 0, /**< Audio Gain Selection */
IS31FL3216_AGS_3DB,
IS31FL3216_AGS_6DB,
IS31FL3216_AGS_9DB,
IS31FL3216_AGS_12DB,
IS31FL3216_AGS_15DB,
IS31FL3216_AGS_18DB,
IS31FL3216_AGS_21DB,
IS31FL3216_AGS_MAX,
} is31fl3216_ags_value_t;
typedef enum {
IS31FL3216_TIME_32MS = 0, /**< Frame Delay Time */
IS31FL3216_TIME_64MS,
IS31FL3216_TIME_128MS,
IS31FL3216_TIME_256MS,
IS31FL3216_TIME_512MS,
IS31FL3216_TIME_1024MS,
IS31FL3216_TIME_2048MS,
IS31FL3216_TIME_4096MS,
IS31FL3216_TIME_MAX,
} is31fl3216_delay_time_t;
typedef enum {
IS31FL3216_REG_CONFIG = 0x00, /* Configuration register */
IS31FL3216_REG_LED_CTRL_H = 0x01, /* LED control register OUT9-OUT16 enable bit */
IS31FL3216_REG_LED_CTRL_L = 0x02, /* LED control register OUT1-OUT8 enable bit */
IS31FL3216_REG_LED_EFFECT = 0x03, /* Set the output current and the audio gain */
IS31FL3216_REG_CH_CONFIG = 0x04, /* Set the operating mode of OUT9~OUT16 */
IS31FL3216_REG_GPIO_CONFIG = 0x05, /* Set the operating mode of OUT9~OUT16 as the GPIO port */
IS31FL3216_REG_OUTPUT = 0x06, /* Set the logic level of OUT9~OUT16 as the output port */
IS31FL3216_REG_INPUT_CTRL = 0x07, /* Set the interrupt function of OUT9~OUT16 */
IS31FL3216_REG_STATE = 0x08, /* Store the state of OUT9~OUT16 as the input port */
IS31FL3216_REG_ADC_RATE = 0x09, /* Set the ADC sample rate of the input signal */
IS31FL3216_REG_PWM_16 = 0x10, /* Set the PWM duty cycle data */
IS31FL3216_REG_PWM_15,
IS31FL3216_REG_PWM_14,
IS31FL3216_REG_PWM_13,
IS31FL3216_REG_PWM_12,
IS31FL3216_REG_PWM_11,
IS31FL3216_REG_PWM_10,
IS31FL3216_REG_PWM_09,
IS31FL3216_REG_PWM_08,
IS31FL3216_REG_PWM_07,
IS31FL3216_REG_PWM_06,
IS31FL3216_REG_PWM_05,
IS31FL3216_REG_PWM_04,
IS31FL3216_REG_PWM_03,
IS31FL3216_REG_PWM_02,
IS31FL3216_REG_PWM_01,
IS31FL3216_REG_FRAME1_CTRL = 0x20, /* Store the data of 8 frames */
IS31FL3216_REG_FRAME1_PWM = 0x22,
IS31FL3216_REG_FRAME2_CTRL = 0x32,
IS31FL3216_REG_FRAME2_PWM = 0x34,
IS31FL3216_REG_FRAME3_CTRL = 0x44,
IS31FL3216_REG_FRAME3_PWM = 0x46,
IS31FL3216_REG_FRAME4_CTRL = 0x56,
IS31FL3216_REG_FRAME4_PWM = 0x58,
IS31FL3216_REG_FRAME5_CTRL = 0x68,
IS31FL3216_REG_FRAME5_PWM = 0x6A,
IS31FL3216_REG_FRAME6_CTRL = 0x7A,
IS31FL3216_REG_FRAME6_PWM = 0x7C,
IS31FL3216_REG_FRAME7_CTRL = 0x8C,
IS31FL3216_REG_FRAME7_PWM = 0x8E,
IS31FL3216_REG_FRAME8_CTRL = 0x9E,
IS31FL3216_REG_FRAME8_PWM = 0xA0,
IS31FL3216_REG_UPDATE = 0xB0, /* Load PWM Register data */
IS31FL3216_REG_FRAME_DELAY = 0xB6, /* Set the delay time between each frame */
IS31FL3216_REG_FRAME_START = 0xB7, /* Set the start frame in Auto Frame Play Mode */
IS31FL3216_REG_MAX,
} is31fl3216_reg_t;
typedef enum {
IS31FL3216_CH_1 = 0x0001, /**< channel by bit shit */
IS31FL3216_CH_2 = 0x0002,
IS31FL3216_CH_3 = 0x0004,
IS31FL3216_CH_4 = 0x0008,
IS31FL3216_CH_5 = 0x0010,
IS31FL3216_CH_6 = 0x0020,
IS31FL3216_CH_7 = 0x0040,
IS31FL3216_CH_8 = 0x0080,
IS31FL3216_CH_9 = 0x0100,
IS31FL3216_CH_10 = 0x0200,
IS31FL3216_CH_11 = 0x0400,
IS31FL3216_CH_12 = 0x0800,
IS31FL3216_CH_13 = 0x1000,
IS31FL3216_CH_14 = 0x2000,
IS31FL3216_CH_15 = 0x4000,
IS31FL3216_CH_16 = 0x8000,
IS31FL3216_CH_ALL = 0xFFFF,
} is31_pwm_channel_t;
typedef void *is31fl3216_handle_t;
/**
* @brief The Shutdown Register sets software shutdown mode of IS31FL3216.
*
* @param handle led dev handle
* @param mode shutdown mode or Normal
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
* - ESP_ERR_TIMEOUT timeout
*/
esp_err_t is31fl3216_power(is31fl3216_handle_t handle, is31fl3216_pwr_t mode);
/**
* @brief set the duty for the channels
*
* @param handle led dev handle
* @param ch_bits the sequence num of channels //e.g.: 1UL << the number of channel
* @param duty set the duty between 0-255
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t is31fl3216_ch_duty_set(is31fl3216_handle_t handle, is31_pwm_channel_t ch_bits, uint8_t duty);
/**
* @brief set the work mode of channels
*
* @param handle led dev handle
* @param mode led work mode
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t is31fl3216_work_mode_set(is31fl3216_handle_t handle, is31fl3216_work_mode_t mode);
/**
* @brief enable the channels
*
* @param handle led dev handle
* @param ch_bits the sequence num of channels //e.g.: ch_bits = 1UL << the number of channel
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t is31fl3216_ch_enable(is31fl3216_handle_t handle, is31_pwm_channel_t ch_bits);
/**
* @brief disable the channels
*
* @param handle led dev handle
* @param ch_bits the sequence num of channels //e.g.: chbits = 1UL << the number of channel
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t is31fl3216_ch_disable(is31fl3216_handle_t handle, is31_pwm_channel_t ch_bits);
/**
* @brief set the mode of output current
*
* @param handle led dev handle
* @param mode output current mode
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t is31fl3216_cur_mode_set(is31fl3216_handle_t handle, is31fl3216_cur_mode_t mode);
/**
* @brief set the value of output current
*
* @param handle led dev handle
* @param value output current value
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t is31fl3216_cur_value_set(is31fl3216_handle_t handle, is31fl3216_cur_value_t value);
/**
* @brief choose the audio gain
*
* @param handle led dev handle
* @param value selection of audio gain
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t is31fl3216_ags_value_set(is31fl3216_handle_t handle, is31fl3216_ags_value_t value);
/**
* @brief enable or disable audio gain
*
* @param handle led dev handle
* @param en 0 or 1 to switch the audio gain
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t is31fl3216_agc_cfg(is31fl3216_handle_t handle, uint32_t en);
/**
* @brief set the mode of chip cascade
*
* @param handle led dev handle
* @param mode chip cascade mode
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t is31fl3216_cascade_mode_set(is31fl3216_handle_t handle, is31fl3216_cascade_mode_t mode);
/**
* @brief update the register
*
* @param handle led dev handle
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t is31fl3216_update_reg(is31fl3216_handle_t handle);
/**
* @brief set the sample rate
*
* @param handle led dev handle
* @param value set value
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t is31fl3216_sample_rate_set(is31fl3216_handle_t handle, uint32_t value);
/**
* @brief set the frame time
*
* @param handle led dev handle
* @param time time to set
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t is31fl3216_frame_time_set(is31fl3216_handle_t handle, is31fl3216_delay_time_t time);
/**
* @brief choose the first frame to play
*
* @param handle led dev handle
* @param frame the seqence num of frame
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t is31fl3216_first_frame_set(is31fl3216_handle_t handle, uint32_t frame);
/**
* @brief write frame data
*
* @param handle led dev handle
* @param num the seqence num of frame
* @param data data to write
* @param len the length of data
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t is31fl3216_frame_value_set(is31fl3216_handle_t handle, uint32_t num, uint8_t *data, uint32_t len);
/**
* @brief IS31FL3216 will reset all registers to default value.
*
* @param handle led dev handle
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
* - ESP_ERR_TIMEOUT timeout
*/
esp_err_t is31fl3216_reset(is31fl3216_handle_t handle);
/**
* @brief Create and init sensor object and return a led handle
*
* @param bus I2C bus object handle
*
* @return
* - NULL Fail
* - Others Success
*/
is31fl3216_handle_t is31fl3216_init(void);
/**
* @brief Delete and release a LED object
*
* @param sensor object handle of Is31fl3216
* @param del_bus Whether to delete the I2C bus
*
* @return
* - ESP_OK Success
* - ESP_FAIL Fail
*/
esp_err_t is31fl3216_deinit(is31fl3216_handle_t handle);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/lib/IS31FL3216/IS31FL3216.h
|
C
|
apache-2.0
| 11,402
|
/*
* 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 <stdio.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "driver/adc.h"
#include "math.h"
#include "audio_mem.h"
#include "esp_adc_cal.h"
#include "string.h"
#include "adc_button.h"
#include "esp_log.h"
#include "audio_thread.h"
#define V_REF 1100
#define ADC_SAMPLES_NUM 10
#define ADC_SAMPLE_INTERVAL_TIME_MS 20
#define DIAL_VOL_INTERVAL_TIME_MS 150
#define ADC_BTN_INVALID_ID -1
#define ADC_BTN_INVALID_ACT_ID -2
#define ADC_BTN_DETECT_TIME_MS 20
#define ADC_BTN_DETECTED_CNT 2
#ifndef ENABLE_ADC_VOLUME
#define USER_KEY_MAX 7
#endif
static char *TAG = "ADC_BTN";
static EventGroupHandle_t g_event_bit;
typedef struct {
adc_button_callback btn_callback;
adc_btn_list *head;
void *user_data;
audio_thread_t audio_thread;
} adc_btn_tag_t;
static const int default_step_level[USER_KEY_MAX] = {0, 683, 1193, 1631, 2090, 2578, 3103};
static const int DESTROY_BIT = BIT0;
static bool _task_flag;
adc_btn_list *adc_btn_create_list(adc_arr_t *adc_conf, int channels)
{
adc_btn_list *head = NULL;
adc_btn_list *node = NULL;
adc_btn_list *find = NULL;
for (int i = 0; i < channels; i++) {
node = (adc_btn_list *)audio_calloc(1, sizeof(adc_btn_list));
if (NULL == node) {
ESP_LOGE(TAG, "Memory allocation failed! Line: %d", __LINE__);
return NULL;
}
memset(node, 0, sizeof(adc_btn_list));
adc_arr_t *info = &(node->adc_info);
memcpy(info, adc_conf + i, sizeof(adc_arr_t));
info->adc_level_step = (int *)audio_calloc(1, (info->total_steps + 1) * sizeof(int));
memset(info->adc_level_step, 0, (info->total_steps + 1) * sizeof(int));
if (NULL == info->adc_level_step) {
ESP_LOGE(TAG, "Memory allocation failed! Line: %d", __LINE__);
audio_free(node);
return NULL;
}
if (adc_conf[i].adc_level_step == NULL) {
memcpy(info->adc_level_step, default_step_level, USER_KEY_MAX * sizeof(int));
} else {
memcpy(info->adc_level_step, adc_conf[i].adc_level_step, (adc_conf[i].total_steps + 1) * sizeof(int));
}
if (info->total_steps > USER_KEY_MAX) {
ESP_LOGE(TAG, "The total_steps should be less than USER_KEY_MAX");
audio_free(info->adc_level_step);
audio_free(node);
}
node->btn_dscp = (btn_decription *)audio_calloc(1, sizeof(btn_decription) * (adc_conf[i].total_steps));
if (NULL == node->btn_dscp) {
ESP_LOGE(TAG, "Memory allocation failed! Line: %d", __LINE__);
audio_free(info->adc_level_step);
audio_free(node);
}
memset(node->btn_dscp, 0, sizeof(btn_decription) * (adc_conf[i].total_steps));
node->next = NULL;
if (NULL == head) {
head = node;
find = head;
} else {
find->next = node;
find = node;
}
}
return head;
}
esp_err_t adc_btn_destroy_list(adc_btn_list *head)
{
if (head == NULL) {
ESP_LOGD(TAG, "The head of list is null");
return ESP_OK;
}
adc_btn_list *find = head;
adc_btn_list *tmp = find;
while (find) {
adc_arr_t *info = &(find->adc_info);
tmp = find->next;
audio_free(find->btn_dscp);
audio_free(info->adc_level_step);
audio_free(find);
find = tmp;
}
return ESP_OK;
}
static int get_adc_voltage(int channel)
{
uint32_t data[ADC_SAMPLES_NUM] = { 0 };
uint32_t sum = 0;
int tmp = 0;
esp_adc_cal_characteristics_t characteristics;
#if CONFIG_IDF_TARGET_ESP32
esp_adc_cal_characterize(ADC_UNIT_1, ADC_ATTEN_11db, ADC_WIDTH_12Bit, V_REF, &characteristics);
#elif CONFIG_IDF_TARGET_ESP32S2
esp_adc_cal_characterize(ADC_UNIT_1, ADC_ATTEN_11db, ADC_WIDTH_BIT_13, 0, &characteristics);
#else
esp_adc_cal_characterize(ADC_UNIT_1, ADC_ATTEN_11db, ADC_WIDTH_12Bit, 0, &characteristics);
#endif
for (int i = 0; i < ADC_SAMPLES_NUM; ++i) {
esp_adc_cal_get_voltage(channel, &characteristics, &data[i]);
}
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));
}
static int get_button_id(adc_btn_list *node, int adc)
{
int m = ADC_BTN_INVALID_ID;
adc_arr_t *info = &(node->adc_info);
for (int i = 0; i < info->total_steps; i++) {
ESP_LOGV(TAG, "max:%d, adc:%d, i:%d, %d, %d", info->total_steps, adc, i, info->adc_level_step[i], info->adc_level_step[i + 1]);
if ((adc > info->adc_level_step[i])
&& (adc <= info->adc_level_step[i + 1])) {
m = i;
break;
}
}
return m;
}
static void reset_btn(btn_decription *btn_dscp, int btn_num)
{
memset(btn_dscp, 0, sizeof(btn_decription) * btn_num);
for (int i = 0; i < btn_num; ++i) {
btn_dscp[i].active_id = ADC_BTN_INVALID_ID;
}
}
static adc_btn_state_t get_adc_btn_state(int adc_value, int act_id, adc_btn_list *node)
{
adc_btn_state_t st = ADC_BTN_STATE_IDLE;
adc_arr_t *info = &(node->adc_info);
btn_decription *btn_dscp = node->btn_dscp;
int id = get_button_id(node, adc_value);
if (id == ADC_BTN_INVALID_ID) {
if (act_id == ADC_BTN_INVALID_ACT_ID) {
// No old act id and new act id.
return ADC_BTN_STATE_IDLE;
}
if (btn_dscp[act_id].click_cnt <= 1) {
return ADC_BTN_STATE_IDLE;
}
// Have old act ID, new id is invalid
// Need to send release event
if (btn_dscp[act_id].click_cnt < (info->press_judge_time / ADC_BTN_DETECT_TIME_MS)) {
ESP_LOGD(TAG, "pressed: Act ID:%d, ID:%d, Cnt:%d", act_id, id, btn_dscp[act_id].click_cnt);
st = ADC_BTN_STATE_RELEASE;
} else {
ESP_LOGD(TAG, "long press release: Act ID:%d, ID:%d, Cnt:%d", act_id, id, btn_dscp[act_id].click_cnt);
st = ADC_BTN_STATE_LONG_RELEASE;
}
btn_dscp[act_id].active_id = -1;
btn_dscp[act_id].long_click = 0;
btn_dscp[act_id].click_cnt = 0;
return st;
}
// 1.ID is valid and act ID is invalid.
if (act_id == ADC_BTN_INVALID_ACT_ID) {
// First new act id
btn_dscp[id].active_id = id;
return ADC_BTN_STATE_IDLE;
}
// 2.ID and act ID are valid, but not equal.
if (id != act_id) {
ESP_LOGW(TAG, "Old ID:%d, New ID:%d, Cnt:%d", act_id, id, btn_dscp[act_id].click_cnt);
// Invalid the act ID
btn_dscp[act_id].active_id = -1;
btn_dscp[act_id].long_click = 0;
// Set the new id act ID
btn_dscp[id].active_id = id;
// Maybe need to check release long pressed.
if (btn_dscp[act_id].click_cnt < ADC_BTN_DETECTED_CNT) {
btn_dscp[act_id].click_cnt = 0;
return ADC_BTN_STATE_IDLE;
}
btn_dscp[act_id].click_cnt = 0;
// Have old act ID, new id is invalid
// Need to send release event
if (btn_dscp[act_id].click_cnt < (info->press_judge_time / ADC_BTN_DETECT_TIME_MS)) {
ESP_LOGD(TAG, "pressed: Act ID:%d, ID:%d, Cnt:%d", act_id, id, btn_dscp[act_id].click_cnt);
return ADC_BTN_STATE_RELEASE;
} else {
ESP_LOGD(TAG, "long press release: Act ID:%d, ID:%d, Cnt:%d", act_id, id, btn_dscp[act_id].click_cnt);
return ADC_BTN_STATE_LONG_RELEASE;
}
}
// 3.ID and act ID are valid, and equal.
btn_dscp[act_id].click_cnt++;
if (btn_dscp[act_id].click_cnt == ADC_BTN_DETECTED_CNT) {
return ADC_BTN_STATE_PRESSED;
}
if (btn_dscp[act_id].long_click) {
return ADC_BTN_STATE_IDLE;
}
if (btn_dscp[act_id].click_cnt >= (info->press_judge_time / ADC_BTN_DETECT_TIME_MS)) {
//Send long click event.
ESP_LOGD(TAG, "long press: Act ID:%d, ID:%d, Cnt:%d", act_id, id, btn_dscp[act_id].click_cnt);
st = ADC_BTN_STATE_LONG_PRESSED;
btn_dscp[act_id].long_click = 1;
}
return st;
}
static void button_task(void *parameters)
{
_task_flag = true;
adc_btn_tag_t *tag = (adc_btn_tag_t *)parameters;
adc_btn_list *head = tag->head;
adc_btn_list *find = head;
xEventGroupClearBits(g_event_bit, DESTROY_BIT);
#if CONFIG_IDF_TARGET_ESP32S2
adc1_config_width(ADC_WIDTH_BIT_13);
#else
adc1_config_width(ADC_WIDTH_BIT_12);
#endif
while (find) {
adc_arr_t *info = &(find->adc_info);
reset_btn(find->btn_dscp, info->total_steps);
adc1_config_channel_atten(info->adc_ch, ADC_ATTEN_11db);
find = find->next;
}
find = head;
#if defined ENABLE_ADC_VOLUME
adc1_config_channel_atten(DIAL_adc_ch, ADC_ATTEN_11db);
short adc_vol_prev = ADC_BTN_INVALID_ID;
short adc_vol_cur = ADC_BTN_INVALID_ID;
short internal_time_ms = DIAL_VOL_INTERVAL_TIME_MS / ADC_SAMPLE_INTERVAL_TIME_MS; /// 10 * 10 = 100ms
static bool empty_flag;
static bool full_flag;
bool is_first_time = true;
#endif // ENABLE_ADC_VOLUME
static adc_btn_state_t cur_state = ADC_BTN_STATE_ADC;
adc_btn_state_t btn_st = ADC_BTN_STATE_IDLE;
int cur_act_id = ADC_BTN_INVALID_ACT_ID;
while (_task_flag) {
#if defined ENABLE_ADC_VOLUME
if (internal_time_ms == 0) {
adc_vol_cur = get_adc_voltage(DIAL_adc_ch);
internal_time_ms = DIAL_VOL_INTERVAL_TIME_MS / ADC_SAMPLE_INTERVAL_TIME_MS;
if (adc_vol_prev > 0) {
short n = abs(adc_vol_cur - adc_vol_prev);
if (is_first_time) {
is_first_time = false;
}
if (adc_vol_cur < 200) {
if (empty_flag == false) {
ESP_LOGI(TAG, "ABS_LOW:%d, %d->0", n, adc_vol_cur / 25);
empty_flag = true;
}
} else if (adc_vol_cur > 2500) {
if (full_flag == false) {
ESP_LOGI(TAG, "ABS_HIGH:%d, %d->100", n, adc_vol_cur / 25);
full_flag = true;
}
} else if (n > 80) {
empty_flag = false;
full_flag = false;
}
}
adc_vol_prev = adc_vol_cur;
}
internal_time_ms--;
#else
find = head;
while (find) {
adc_arr_t *info = &(find->adc_info);
int act_id = ADC_BTN_INVALID_ACT_ID;
btn_decription *btn_dscp = find->btn_dscp;
switch (cur_state) {
case ADC_BTN_STATE_ADC: {
int adc = get_adc_voltage(info->adc_ch);
ESP_LOGD(TAG, "ADC:%d", adc);
for (int i = 0; i < info->total_steps; ++i) {
if (btn_dscp[i].active_id > ADC_BTN_INVALID_ID) {
act_id = i;
break;
}
}
btn_st = get_adc_btn_state(adc, act_id, find);
if (btn_st != ADC_BTN_STATE_IDLE) {
cur_act_id = act_id;
cur_state = btn_st;
ESP_LOGD(TAG, "ADC ID:%d", act_id);
}
break;
}
case ADC_BTN_STATE_PRESSED: {
tag->btn_callback((void *)tag->user_data, info->adc_ch, cur_act_id, ADC_BTN_STATE_PRESSED);
cur_state = ADC_BTN_STATE_ADC;
break;
}
case ADC_BTN_STATE_LONG_PRESSED: {
tag->btn_callback((void *)tag->user_data, info->adc_ch, cur_act_id, ADC_BTN_STATE_LONG_PRESSED);
cur_state = ADC_BTN_STATE_ADC;
break;
}
case ADC_BTN_STATE_LONG_RELEASE: {
tag->btn_callback((void *)tag->user_data, info->adc_ch, cur_act_id, ADC_BTN_STATE_LONG_RELEASE);
cur_state = ADC_BTN_STATE_ADC;
break;
}
case ADC_BTN_STATE_RELEASE: {
tag->btn_callback((void *)tag->user_data, info->adc_ch, cur_act_id, ADC_BTN_STATE_RELEASE);
cur_state = ADC_BTN_STATE_ADC;
break;
}
default:
ESP_LOGE(TAG, "Not support state %d", cur_state);
break;
}
find = find->next;
}
#endif // ENABLE_ADC_VOLUME
vTaskDelay(ADC_SAMPLE_INTERVAL_TIME_MS / portTICK_PERIOD_MS);
}
if (g_event_bit) {
xEventGroupSetBits(g_event_bit, DESTROY_BIT);
}
audio_free(tag);
vTaskDelete(NULL);
}
void adc_btn_delete_task(void)
{
if (_task_flag) {
_task_flag = false;
}
if (g_event_bit) {
xEventGroupWaitBits(g_event_bit, DESTROY_BIT, pdTRUE, pdFALSE, portMAX_DELAY);
vEventGroupDelete(g_event_bit);
g_event_bit = NULL;
}
}
void adc_btn_init(void *user_data, adc_button_callback cb, adc_btn_list *head, adc_btn_task_cfg_t *task_cfg)
{
adc_btn_tag_t *tag = audio_calloc(1, sizeof(adc_btn_tag_t));
if (NULL == tag) {
ESP_LOGE(TAG, "Memory allocation failed! Line: %d", __LINE__);
return;
}
tag->user_data = user_data;
tag->head = head;
tag->btn_callback = cb;
g_event_bit = xEventGroupCreate();
audio_thread_create(&tag->audio_thread,
"button_task", button_task,
(void *)tag,
task_cfg->task_stack,
task_cfg->task_prio,
task_cfg->ext_stack,
task_cfg->task_core);
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/lib/adc_button/adc_button.c
|
C
|
apache-2.0
| 15,570
|
/*
* 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 _ADC_BUTTON_H_
#define _ADC_BUTTON_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "esp_err.h"
typedef enum {
USER_KEY_ID0,
USER_KEY_ID1,
USER_KEY_ID2,
USER_KEY_ID3,
USER_KEY_ID4,
USER_KEY_ID5,
USER_KEY_ID6,
USER_KEY_MAX,
} user_key_id_num;
typedef struct {
int adc_ch;
int *adc_level_step;
int total_steps;
int press_judge_time;
} adc_arr_t;
typedef enum {
ADC_BTN_STATE_IDLE, // 0: idle
ADC_BTN_STATE_ADC, // 1: detect
ADC_BTN_STATE_PRESSED, // 2: pressed
ADC_BTN_STATE_RELEASE, // 3: press released
ADC_BTN_STATE_LONG_PRESSED, // 4: long pressed
ADC_BTN_STATE_LONG_RELEASE, // 5: long Press released
} adc_btn_state_t;
typedef struct {
int active_id;
int click_cnt; // Timer tick count
int long_click;
} btn_decription;
typedef struct adc_btn {
adc_arr_t adc_info;
btn_decription *btn_dscp;
struct adc_btn *next;
} adc_btn_list;
typedef struct {
int task_stack;
int task_prio;
int task_core;
bool ext_stack;
} adc_btn_task_cfg_t;
typedef void (*adc_button_callback) (void *user_data, int adc, int id, adc_btn_state_t state);
void adc_btn_init(void *user_data, adc_button_callback cb, adc_btn_list *head, adc_btn_task_cfg_t *task_cfg);
adc_btn_list *adc_btn_create_list(adc_arr_t *adc_conf, int channels);
esp_err_t adc_btn_destroy_list(adc_btn_list *head);
void adc_btn_delete_task(void);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/lib/adc_button/adc_button.h
|
C
|
apache-2.0
| 2,778
|
/*
* 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 "i2c_bus.h"
#include "board.h"
#include "aw2013.h"
#include "esp_log.h"
#define AW2013_ADDR 0x8a
#define AW2013_MAX_LED_NUM 3
#define AW2013_MAX_REPEAT_TIME 15
static const char *TAG = "AW2013";
static i2c_bus_handle_t i2c_handle;
esp_err_t aw2013_set_repeat_time(uint8_t cnt)
{
esp_err_t ret = ESP_OK;
AUDIO_NULL_CHECK(TAG, i2c_handle, return ESP_FAIL);
uint8_t reg_val = 0;
uint8_t reg_addr = 0x0;
cnt %= AW2013_MAX_REPEAT_TIME;
for (int i = 0; i < AW2013_MAX_LED_NUM; i++) {
reg_addr = AW2013_REG_LED0T0CNT + AW2013_MAX_LED_NUM * i;
ret |= i2c_bus_read_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
reg_val &= 0xf0;
reg_val |= cnt;
ret |= i2c_bus_write_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
}
return ret;
}
esp_err_t aw2013_set_time(aw2013_time_t time, aw2013_time_level_t level)
{
if (level > AW2013_TIME_LEVEL_8 || time > AW2013_TIME_4) {
ESP_LOGE(TAG, "Invalid parameters, time: %d, level: %d", time, level);
return ESP_FAIL;
}
uint8_t reg_val = 0;
uint8_t reg_addr = 0x0;
esp_err_t ret = ESP_OK;
AUDIO_NULL_CHECK(TAG, i2c_handle, return ESP_FAIL);
for (int i = 0; i < AW2013_MAX_LED_NUM; i++) {
switch (time) {
case AW2013_TIME_0: {
reg_addr = AW2013_REG_LED0T0CNT + AW2013_MAX_LED_NUM * i;
ret |= i2c_bus_read_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
reg_val &= 0x0f;
reg_val |= (level << 4);
ret |= i2c_bus_write_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
break;
}
case AW2013_TIME_1: {
if (level > AW2013_TIME_LEVEL_7) {
level = AW2013_TIME_LEVEL_7;
}
reg_addr = AW2013_REG_LED0T1T2 + AW2013_MAX_LED_NUM * i;
ret |= i2c_bus_read_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
reg_val &= 0x8f;
reg_val |= (level << 4);
ret |= i2c_bus_write_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
break;
}
case AW2013_TIME_2: {
if (level > AW2013_TIME_LEVEL_5) {
level = AW2013_TIME_LEVEL_5;
}
reg_addr = AW2013_REG_LED0T1T2 + AW2013_MAX_LED_NUM * i;
ret |= i2c_bus_read_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
reg_val &= 0xf8;
reg_val |= level;
ret |= i2c_bus_write_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
break;
}
case AW2013_TIME_3: {
if (level > 7) {
level = 7;
}
reg_addr = AW2013_REG_LED0T3T4 + AW2013_MAX_LED_NUM * i;
ret |= i2c_bus_read_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
reg_val &= 0x8f;
reg_val |= (level << 4);
ret |= i2c_bus_write_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
break;
}
case AW2013_TIME_4: {
if (level > 7) {
level = 7;
}
reg_addr = AW2013_REG_LED0T3T4 + AW2013_MAX_LED_NUM * i;
ret |= i2c_bus_read_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
reg_val &= 0xf8;
reg_val |= level;
ret |= i2c_bus_write_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
break;
}
default: {
return ESP_FAIL;
}
}
}
return ret;
}
esp_err_t aw2013_enable_fade_mode(bool en)
{
esp_err_t ret = ESP_OK;
uint8_t reg_val = 0;
uint8_t reg_addr = 0x0;
AUDIO_NULL_CHECK(TAG, i2c_handle, return ESP_FAIL);
if (en) {
for (int i = 0; i < AW2013_MAX_LED_NUM; i++) {
reg_addr = AW2013_REG_LCFG0 + i;
ret |= i2c_bus_read_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
reg_val &= ~(0x01 << 4);
reg_val |= (0x03 << 5);
ret |= i2c_bus_write_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
}
} else {
for (int i = 0; i < AW2013_MAX_LED_NUM; i++) {
reg_addr = AW2013_REG_LCFG0 + i;
ret |= i2c_bus_read_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
reg_val &= ~(0x03 << 5);
ret |= i2c_bus_write_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
}
}
return ret;
}
esp_err_t aw2013_enable_auto_flash(bool en)
{
esp_err_t ret = ESP_OK;
uint8_t reg_val = 0;
uint8_t reg_addr = 0x0;
AUDIO_NULL_CHECK(TAG, i2c_handle, return ESP_FAIL);
if (en) {
for (int i = 0; i < AW2013_MAX_LED_NUM; i++) {
reg_addr = AW2013_REG_LCFG0 + i;
ret |= i2c_bus_read_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
reg_val |= (0x01 << 4);
ret |= i2c_bus_write_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
}
} else {
for (int i = 0; i < AW2013_MAX_LED_NUM; i++) {
reg_addr = AW2013_REG_LCFG0 + i;
ret |= i2c_bus_read_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
reg_val &= ~(0x01 << 4);
ret |= i2c_bus_write_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
}
}
return ret;
}
esp_err_t aw2013_set_pwm_value(uint32_t value)
{
esp_err_t ret = ESP_OK;
uint8_t reg_val = 0;
uint8_t reg_addr = 0x0;
AUDIO_NULL_CHECK(TAG, i2c_handle, return ESP_FAIL);
reg_addr = AW2013_REG_PWM0;
reg_val = (value >> 16) & 0xff;
ret |= i2c_bus_write_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
reg_addr = AW2013_REG_PWM1;
reg_val = (value >> 8) & 0xff;
ret |= i2c_bus_write_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
reg_addr = AW2013_REG_PWM2;
reg_val = value & 0xff;
ret |= i2c_bus_write_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
return ret;
}
esp_err_t aw2013_set_brightness(aw2013_brightness_t bright)
{
esp_err_t ret = ESP_OK;
uint8_t reg_val = 0;
uint8_t reg_addr = 0x0;
AUDIO_NULL_CHECK(TAG, i2c_handle, return ESP_FAIL);
if (bright > AW2013_BRIGHT_3) {
bright = AW2013_BRIGHT_3;
}
for (int i = 0; i < AW2013_MAX_LED_NUM; i++) {
reg_addr = AW2013_REG_LCFG0 + i;
ret |= i2c_bus_read_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
reg_val &= 0xfc;
reg_val |= bright;
ret |= i2c_bus_write_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
}
return ret;
}
esp_err_t aw2013_reset(void)
{
esp_err_t ret = ESP_OK;
uint8_t reg_val = 0;
uint8_t reg_addr = 0x0;
AUDIO_NULL_CHECK(TAG, i2c_handle, return ESP_FAIL);
reg_addr = AW2013_REG_RESET;
reg_addr = AW2013_RESET_VALUE;
ret |= i2c_bus_write_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
reg_addr = AW2013_REG_GCR;
reg_val = 0x01;
ret |= i2c_bus_write_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
reg_addr = AW2013_REG_LCTR;
reg_val = 0x07;
ret |= i2c_bus_write_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
ret |= aw2013_set_brightness(1);
return ret;
}
esp_err_t aw2013_init(void)
{
esp_err_t ret = ESP_OK;
i2c_config_t config = {
.mode = I2C_MODE_MASTER,
.master.clk_speed = 100000
};
ret |= get_i2c_pins(AW2013_I2C_PORT, &config);
i2c_handle = i2c_bus_create(AW2013_I2C_PORT, &config);
ret |= aw2013_reset();
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Fail to init aw2013");
}
return ret;
}
esp_err_t aw2013_deinit(void)
{
esp_err_t ret = ESP_OK;
uint8_t reg_addr = AW2013_REG_RESET;
uint8_t reg_val = AW2013_RESET_VALUE;
AUDIO_NULL_CHECK(TAG, i2c_handle, return ESP_FAIL);
ret |= i2c_bus_write_bytes(i2c_handle, AW2013_ADDR, ®_addr, 1, ®_val, 1);
ret |= i2c_bus_delete(i2c_handle);
return ret;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/lib/aw2013/aw2013.c
|
C
|
apache-2.0
| 9,766
|
/*
* 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 _AW2013_H_
#define _AW2013_H_
#include "esp_log.h"
#include "esp_err.h"
#ifdef __cplusplus
extern "C" {
#endif
#define AW2013_I2C_PORT I2C_NUM_0
#define AW2013_RESET_VALUE 0x55
#define AW2013_REG_RESET 0x00
#define AW2013_REG_GCR 0x01
#define AW2013_REG_LCTR 0x30
#define AW2013_REG_LCFG0 0x31
#define AW2013_REG_LCFG1 0x32
#define AW2013_REG_LCFG2 0x33
#define AW2013_REG_PWM0 0x34
#define AW2013_REG_PWM1 0x35
#define AW2013_REG_PWM2 0x36
#define AW2013_REG_LED0T1T2 0x37
#define AW2013_REG_LED1T1T2 0x3A
#define AW2013_REG_LED2T1T2 0x3D
#define AW2013_REG_LED0T3T4 0x38
#define AW2013_REG_LED1T3T4 0x3B
#define AW2013_REG_LED2T3T4 0x3E
#define AW2013_REG_LED0T0CNT 0x39
#define AW2013_REG_LED1T0CNT 0x3C
#define AW2013_REG_LED2T0CNT 0x3F
typedef enum {
AW2013_BRIGHT_0, // Turn off the lights, the electric current is 0mA
AW2013_BRIGHT_1, // 5mA
AW2013_BRIGHT_2, // 10mA
AW2013_BRIGHT_3, // 15mA
} aw2013_brightness_t;
// Time periods of a auto flash cycle
/*-------------------------------------------*\
| __________ |
| /| |\ |
| / | | \ |
| / | | \ |
| ________/ | | \__________ |
| | | | | | | |
| |<--t0->|t1 |<--t2-->|t3 |<--t4-->| |
\*-------------------------------------------*/
typedef enum {
AW2013_TIME_0, // T0
AW2013_TIME_1, // T1
AW2013_TIME_2, // T2
AW2013_TIME_3, // T3
AW2013_TIME_4 // T4
} aw2013_time_t;
typedef enum { // T1-T4 T0
AW2013_TIME_LEVEL_0, // 0.13s (T0 0s)
AW2013_TIME_LEVEL_1, // 0.26s (T0 0.13s)
AW2013_TIME_LEVEL_2, // 0.52s (T0 0.26s)
AW2013_TIME_LEVEL_3, // 1.04s (T0 0.52s)
AW2013_TIME_LEVEL_4, // 2.08s (T0 1.04s)
AW2013_TIME_LEVEL_5, // 4.16s (T0 2.08s)
AW2013_TIME_LEVEL_6, // 8.32s (T0 4.16s)
AW2013_TIME_LEVEL_7, // 16.64s (T0 8.32s)
AW2013_TIME_LEVEL_8, // (T0 16.64s)
} aw2013_time_level_t;
/**
* @brief Initialize the aw2013 chip
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t aw2013_init(void);
/**
* @brief Deinitialize the aw2013 chip
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t aw2013_deinit(void);
/**
* @brief Reset the aw2013 chip
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t aw2013_reset(void);
/**
* @brief Set rgb value for the aw2013
*
* @param value The value to be set
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t aw2013_set_pwm_value(uint32_t value);
/**
* @brief Set repeat times for auto flash
*
* @param cnt Number of repetitions
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t aw2013_set_repeat_time(uint8_t cnt);
/**
* @brief Set the time for each time period for auto flash
*
* @param time The time period
* @param level The time to be set
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t aw2013_set_time(aw2013_time_t time, aw2013_time_level_t level);
/**
* @brief Set the brightness
*
* @param bright The brightness to be set
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t aw2013_set_brightness(aw2013_brightness_t bright);
/**
* @brief Enable the auto flash fuction
*
* @param en Whether to enable
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t aw2013_enable_auto_flash(bool en);
/**
* @brief Enable the fade fuction
*
* @param en Whether to enable
*
* @return
* - ESP_OK Success
* - ESP_FAIL error
*/
esp_err_t aw2013_enable_fade_mode(bool en);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/lib/aw2013/aw2013.h
|
C
|
apache-2.0
| 5,136
|
/*
* 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 "sdkconfig.h"
#include "audio_mem.h"
#ifdef CONFIG_BLUEDROID_ENABLED
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "esp_log.h"
#include "esp_system.h"
#include "mbedtls/aes.h"
#include "mbedtls/dhm.h"
#include "mbedtls/md5.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 (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
#ifdef CONFIG_IDF_TARGET_ESP32
#include "esp32/rom/crc.h"
#else
#include "esp32s2beta/rom/crc.h"
#endif // CONFIG_IDF_TARGET_ESP32
#else
#include "rom/crc.h"
#endif //(ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
#define BLUFI_SECURITY_TAG "BLUFI_SECURITY"
/*
The SEC_TYPE_xxx is for self-defined packet data type in the procedure of "BLUFI negotiate key"
If using other negotiation procedure to exchange (or generate) a key, the user should redefine the type by yourself.
*/
#define SEC_TYPE_DH_PARAM_LEN 0x00
#define SEC_TYPE_DH_PARAM_DATA 0x01
#define SEC_TYPE_DH_P 0x02
#define SEC_TYPE_DH_G 0x03
#define SEC_TYPE_DH_PUBLIC 0x04
struct blufi_security {
#define DH_SELF_PUB_KEY_LEN 128
#define DH_SELF_PUB_KEY_BIT_LEN (DH_SELF_PUB_KEY_LEN * 8)
uint8_t self_public_key[DH_SELF_PUB_KEY_LEN];
#define SHARE_KEY_LEN 128
#define SHARE_KEY_BIT_LEN (SHARE_KEY_LEN * 8)
uint8_t share_key[SHARE_KEY_LEN];
size_t share_len;
#define PSK_LEN 16
uint8_t psk[PSK_LEN];
uint8_t *dh_param;
int dh_param_len;
uint8_t iv[16];
mbedtls_dhm_context dhm;
mbedtls_aes_context aes;
};
static struct blufi_security *blufi_sec;
static int myrand (void *rng_state, unsigned char *output, size_t len)
{
size_t i;
for (i = 0; i < len; ++i) {
output[i] = esp_random();
}
return ESP_OK;
}
void blufi_dh_negotiate_data_handler(uint8_t *data, int len, uint8_t **output_data, int *output_len, bool *need_free)
{
int ret;
uint8_t type = data[0];
if (blufi_sec == NULL) {
ESP_LOGE(BLUFI_SECURITY_TAG, "BLUFI Security is not initialized");
return;
}
switch (type) {
case SEC_TYPE_DH_PARAM_LEN:
blufi_sec->dh_param_len = ((data[1]<<8)|data[2]);
if (blufi_sec->dh_param) {
audio_free(blufi_sec->dh_param);
blufi_sec->dh_param = NULL;
}
blufi_sec->dh_param = (uint8_t *)audio_calloc(1, blufi_sec->dh_param_len);
if (blufi_sec->dh_param == NULL) {
ESP_LOGE(BLUFI_SECURITY_TAG, "%s, Malloc failed", __func__);
return;
}
break;
case SEC_TYPE_DH_PARAM_DATA:{
if (blufi_sec->dh_param == NULL) {
ESP_LOGE(BLUFI_SECURITY_TAG, "%s, Blufi_sec->dh_param == NULL", __func__);
return;
}
uint8_t *param = blufi_sec->dh_param;
memcpy(blufi_sec->dh_param, &data[1], blufi_sec->dh_param_len);
ret = mbedtls_dhm_read_params(&blufi_sec->dhm, ¶m, ¶m[blufi_sec->dh_param_len]);
if (ret) {
ESP_LOGE(BLUFI_SECURITY_TAG, "%s Read param failed %d", __func__, ret);
return;
}
audio_free(blufi_sec->dh_param);
blufi_sec->dh_param = NULL;
ret = mbedtls_dhm_make_public(&blufi_sec->dhm, (int) mbedtls_mpi_size( &blufi_sec->dhm.P ), blufi_sec->self_public_key, blufi_sec->dhm.len, myrand, NULL);
if (ret) {
ESP_LOGE(BLUFI_SECURITY_TAG, "%s Make public failed %d", __func__, ret);
return;
}
mbedtls_dhm_calc_secret( &blufi_sec->dhm,
blufi_sec->share_key,
SHARE_KEY_BIT_LEN,
&blufi_sec->share_len,
NULL, NULL);
mbedtls_md5(blufi_sec->share_key, blufi_sec->share_len, blufi_sec->psk);
mbedtls_aes_setkey_enc(&blufi_sec->aes, blufi_sec->psk, 128);
/* Alloc output data */
*output_data = &blufi_sec->self_public_key[0];
*output_len = blufi_sec->dhm.len;
*need_free = false;
}
break;
case SEC_TYPE_DH_P:
break;
case SEC_TYPE_DH_G:
break;
case SEC_TYPE_DH_PUBLIC:
break;
}
}
int blufi_aes_encrypt(uint8_t iv8, uint8_t *crypt_data, int crypt_len)
{
int ret;
size_t iv_offset = 0;
uint8_t iv0[16];
memcpy(iv0, blufi_sec->iv, sizeof(blufi_sec->iv));
/* Set iv8 as the iv0[0] */
iv0[0] = iv8;
ret = mbedtls_aes_crypt_cfb128(&blufi_sec->aes, MBEDTLS_AES_ENCRYPT, crypt_len, &iv_offset, iv0, crypt_data, crypt_data);
if (ret) {
return ESP_FAIL;
}
return crypt_len;
}
int blufi_aes_decrypt(uint8_t iv8, uint8_t *crypt_data, int crypt_len)
{
int ret;
size_t iv_offset = 0;
uint8_t iv0[16];
memcpy(iv0, blufi_sec->iv, sizeof(blufi_sec->iv));
/* Set iv8 as the iv0[0] */
iv0[0] = iv8;
ret = mbedtls_aes_crypt_cfb128(&blufi_sec->aes, MBEDTLS_AES_DECRYPT, crypt_len, &iv_offset, iv0, crypt_data, crypt_data);
if (ret) {
return ESP_FAIL;
}
return crypt_len;
}
uint16_t blufi_crc_checksum(uint8_t iv8, uint8_t *data, int len)
{
/* This iv8 ignore, not used */
return crc16_be(0, data, len);
}
esp_err_t blufi_security_init(void)
{
blufi_sec = (struct blufi_security *)audio_calloc(1, sizeof(struct blufi_security));
if (blufi_sec == NULL) {
return ESP_FAIL;
}
mbedtls_dhm_init(&blufi_sec->dhm);
mbedtls_aes_init(&blufi_sec->aes);
memset(blufi_sec->iv, 0x0, 16);
return ESP_OK;
}
esp_err_t blufi_security_deinit(void)
{
if (blufi_sec == NULL) {
return ESP_FAIL;
}
if (blufi_sec->dh_param){
audio_free(blufi_sec->dh_param);
blufi_sec->dh_param = NULL;
}
mbedtls_dhm_free(&blufi_sec->dhm);
mbedtls_aes_free(&blufi_sec->aes);
memset(blufi_sec, 0x0, sizeof(struct blufi_security));
audio_free(blufi_sec);
blufi_sec = NULL;
return ESP_OK;
}
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/lib/blufi/blufi_security.c
|
C
|
apache-2.0
| 7,214
|
/*
* 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 _BLUFI_SECURITY_H_
#define _BLUFI_SECURITY_H_
#include "esp_log.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief BLUFI negotiate data handler
*
* @param[in] data data from phone
* @param[in] len length of data from phone
* @param[in] output_data data to be sent to phone
* @param[in] output_len length of data to be sent to phone
*/
void blufi_dh_negotiate_data_handler(uint8_t *data, int len, uint8_t **output_data, int *output_len, bool *need_free);
/**
* @brief BLUFI encrypt the data after negotiating a share key
*
* @param[in] iv8 initial vector(8bit), normally, blufi core will input packet sequence number
* @param[in] crypt_data plain text and encrypted data, the encrypt function must support autochthonous encrypt
* @param[in] crypt_len length of plain text
*
* @return Nonnegative number is encrypted length, if error, return negative number;
*/
int blufi_aes_encrypt(uint8_t iv8, uint8_t *crypt_data, int crypt_len);
/**
* @brief BLUFI decrypt the data after negotiating a share key
*
* @param[in] iv8 initial vector(8bit), normally, blufi core will input packet sequence number
* @param[in] crypt_data encrypted data and plain text, the encrypt function must support autochthonous decrypt
* @param[in] crypt_len length of encrypted text
*
* @return Nonnegative number is decrypted length, if error, return negative number;
*/
int blufi_aes_decrypt(uint8_t iv8, uint8_t *crypt_data, int crypt_len);
/**
* @brief BLUFI CRC check sum function
*
* @param[in] iv8 initial vector(8bit), normally, blufi core will input packet sequence number
* @param[in] data data need to checksum
* @param[in] len length of data
*
* @return None
*/
uint16_t blufi_crc_checksum(uint8_t iv8, uint8_t *data, int len);
/**
* @brief Initialize and allocate the resource for BLUFI security
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t blufi_security_init(void);
/**
* @brief Uninitialize and free the resource for BLUFI security
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t blufi_security_deinit(void);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/lib/blufi/blufi_security.h
|
C
|
apache-2.0
| 3,464
|
/*
* 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 <stdio.h>
#include <string.h>
#include <assert.h>
#include <math.h>
#include "audio_mem.h"
#include "audio_idf_version.h"
#ifdef CONFIG_BLUEDROID_ENABLED
#include "esp_system.h"
#include "esp_bt.h"
#include "esp_log.h"
#include "audio_error.h"
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 3, 0))
#include "esp_blufi.h"
#else
#include "esp_blufi_api.h"
#endif
#include "esp_bt_defs.h"
#include "esp_gap_ble_api.h"
#include "esp_bt_device.h"
#include "esp_bt_main.h"
#include "esp_gap_bt_api.h"
#include "esp_smartconfig.h"
#include "audio_error.h"
#include "esp_wifi.h"
#include "wifibleconfig.h"
#include "periph_wifi.h"
#include "blufi_security.h"
#define WIFI_BLE_TAG "WIFI_BLE_CONFIG"
#define BLUFI_DEVICE_NAME "BLUFI_DEVICE"
#define WIFI_LIST_NUM (10)
static uint8_t wifi_ble_service_uuid128[32] = {
/* LSB <--------------------------------------------------------------------------------> MSB */
//first uuid, 16bit, [12],[13] is the value
0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00,
};
typedef struct wifi_ble_config {
uint8_t ble_server_if;
uint16_t ble_conn_id;
wifi_config_t sta_config;
esp_periph_handle_t periph;
} wifi_ble_config_t;
static wifi_ble_config_t *g_wifi_ble_config = NULL;
static void wifi_ble_event_callback(esp_blufi_cb_event_t event, esp_blufi_cb_param_t *param);
static esp_ble_adv_data_t wifi_ble_adv_data = {
.set_scan_rsp = false,
.include_name = true,
.include_txpower = true,
.min_interval = 0x100,
.max_interval = 0x100,
.appearance = 0x00,
.manufacturer_len = 0,
.p_manufacturer_data = NULL,
.service_data_len = 0,
.p_service_data = NULL,
.service_uuid_len = 16,
.p_service_uuid = wifi_ble_service_uuid128,
.flag = 0x6,
};
static esp_ble_adv_params_t wifi_ble_adv_params = {
.adv_int_min = 0x100,
.adv_int_max = 0x100,
.adv_type = ADV_TYPE_IND,
.own_addr_type = BLE_ADDR_TYPE_PUBLIC,
.channel_map = ADV_CHNL_ALL,
.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY,
};
static esp_blufi_callbacks_t wifi_ble_callbacks = {
.event_cb = wifi_ble_event_callback,
.negotiate_data_handler = blufi_dh_negotiate_data_handler,
.encrypt_func = blufi_aes_encrypt,
.decrypt_func = blufi_aes_decrypt,
.checksum_func = blufi_crc_checksum,
};
static void wifi_ble_gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
{
switch (event) {
case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT:
esp_ble_gap_start_advertising(&wifi_ble_adv_params);
break;
default:
break;
}
}
esp_err_t ble_config_stop(void)
{
if (g_wifi_ble_config != NULL) {
audio_free(g_wifi_ble_config);
g_wifi_ble_config = NULL;
}
blufi_security_deinit();
esp_blufi_profile_deinit();
esp_bluedroid_disable();
esp_bluedroid_deinit();
return ESP_OK;
}
static void wifi_ble_event_callback(esp_blufi_cb_event_t event, esp_blufi_cb_param_t *param)
{
/* actually, should post to blufi_task handle the procedure,
* now, as a audio_ble, we do it more simply */
esp_err_t ret ;
switch (event) {
case ESP_BLUFI_EVENT_INIT_FINISH:
ESP_LOGI(WIFI_BLE_TAG, "BLUFI init finish");
esp_ble_gap_set_device_name(BLUFI_DEVICE_NAME);
esp_ble_gap_config_adv_data(&wifi_ble_adv_data);
break;
case ESP_BLUFI_EVENT_DEINIT_FINISH:
ESP_LOGI(WIFI_BLE_TAG, "BLUFI deinit finish");
break;
case ESP_BLUFI_EVENT_BLE_CONNECT:
ESP_LOGI(WIFI_BLE_TAG, "BLUFI ble connect");
esp_smartconfig_stop();
g_wifi_ble_config->ble_server_if = param->connect.server_if;
g_wifi_ble_config->ble_conn_id = param->connect.conn_id;
break;
case ESP_BLUFI_EVENT_BLE_DISCONNECT:
ESP_LOGI(WIFI_BLE_TAG, "BLUFI ble disconnect");
break;
case ESP_BLUFI_EVENT_SET_WIFI_OPMODE:
ESP_LOGI(WIFI_BLE_TAG, "BLUFI Set WIFI opmode %d", param->wifi_mode.op_mode);
ESP_ERROR_CHECK( esp_wifi_set_mode(param->wifi_mode.op_mode) );
break;
case ESP_BLUFI_EVENT_REQ_CONNECT_TO_AP:
ESP_LOGI(WIFI_BLE_TAG, "BLUFI request wifi connect to AP");
esp_wifi_disconnect();
if (ESP_OK != esp_wifi_connect()) {
esp_periph_send_event(g_wifi_ble_config->periph, PERIPH_WIFI_CONFIG_ERROR, NULL, 0);
} else {
esp_periph_send_event(g_wifi_ble_config->periph, PERIPH_WIFI_CONFIG_DONE, NULL, 0);
ble_config_stop();
}
break;
case ESP_BLUFI_EVENT_REQ_DISCONNECT_FROM_AP:
ESP_LOGI(WIFI_BLE_TAG, "BLUFI request wifi disconnect from AP");
esp_wifi_disconnect();
break;
case ESP_BLUFI_EVENT_GET_WIFI_STATUS: {
wifi_mode_t mode;
esp_blufi_extra_info_t info;
esp_wifi_get_mode(&mode);
memset(&info, 0, sizeof(esp_blufi_extra_info_t));
info.sta_bssid_set = true;
info.sta_ssid = g_wifi_ble_config->sta_config.sta.ssid;
esp_blufi_send_wifi_conn_report(mode, ESP_BLUFI_STA_CONN_SUCCESS, 0, &info);
ESP_LOGI(WIFI_BLE_TAG, "BLUFI get wifi status from AP");
break;
}
case ESP_BLUFI_EVENT_RECV_SLAVE_DISCONNECT_BLE:
ESP_LOGI(WIFI_BLE_TAG, "BLUFI close a gatt connection");
esp_blufi_close(g_wifi_ble_config->ble_server_if, g_wifi_ble_config->ble_conn_id);
break;
case ESP_BLUFI_EVENT_DEAUTHENTICATE_STA:
/* TODO */
break;
case ESP_BLUFI_EVENT_RECV_STA_BSSID:
memcpy(g_wifi_ble_config->sta_config.sta.bssid, param->sta_bssid.bssid, 6);
g_wifi_ble_config->sta_config.sta.bssid_set = 1;
esp_wifi_set_config(WIFI_IF_STA, &g_wifi_ble_config->sta_config);
ESP_LOGI(WIFI_BLE_TAG, "Recv STA BSSID %s", g_wifi_ble_config->sta_config.sta.bssid);
break;
case ESP_BLUFI_EVENT_RECV_STA_SSID:
strncpy((char *)g_wifi_ble_config->sta_config.sta.ssid, (char *)param->sta_ssid.ssid, param->sta_ssid.ssid_len);
g_wifi_ble_config->sta_config.sta.ssid[param->sta_ssid.ssid_len] = '\0';
ret = esp_wifi_set_config(WIFI_IF_STA, &g_wifi_ble_config->sta_config);
ESP_LOGI(WIFI_BLE_TAG, "Recv STA SSID ret %d %s", ret, g_wifi_ble_config->sta_config.sta.ssid);
break;
case ESP_BLUFI_EVENT_RECV_STA_PASSWD:
strncpy((char *)g_wifi_ble_config->sta_config.sta.password, (char *)param->sta_passwd.passwd, param->sta_passwd.passwd_len);
g_wifi_ble_config->sta_config.sta.password[param->sta_passwd.passwd_len] = '\0';
esp_wifi_set_config(WIFI_IF_STA, &g_wifi_ble_config->sta_config);
ESP_LOGI(WIFI_BLE_TAG, "Recv STA PASSWORD %s", g_wifi_ble_config->sta_config.sta.password);
break;
default:
ESP_LOGE(WIFI_BLE_TAG, "Event %d is not supported", event);
break;
}
}
esp_err_t ble_config_start(esp_periph_handle_t periph)
{
ESP_LOGI(WIFI_BLE_TAG, "ble_config_start");
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
if (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_IDLE) {
if (esp_bt_controller_init(&bt_cfg) != ESP_OK) {
ESP_LOGE(WIFI_BLE_TAG, "%s initialize controller failed", __func__);
return ESP_FAIL;
}
if (esp_bt_controller_enable(ESP_BT_MODE_BLE) != ESP_OK) {
ESP_LOGE(WIFI_BLE_TAG, "%s enable controller failed", __func__);
return ESP_FAIL;
}
}
if (esp_bluedroid_get_status() == ESP_BLUEDROID_STATUS_UNINITIALIZED) {
if (esp_bluedroid_init() != ESP_OK) {
ESP_LOGE(WIFI_BLE_TAG, "%s esp_bluedroid_init failed", __func__);
return ESP_FAIL;
}
if (esp_bluedroid_enable() != ESP_OK) {
ESP_LOGE(WIFI_BLE_TAG, "%s esp_bluedroid_enable failed", __func__);
return ESP_FAIL;
}
}
ESP_LOGI(WIFI_BLE_TAG, "BD ADDR: "ESP_BD_ADDR_STR"", ESP_BD_ADDR_HEX(esp_bt_dev_get_address()));
ESP_LOGI(WIFI_BLE_TAG, "BLUFI VERSION %04x", esp_blufi_get_version());
g_wifi_ble_config = audio_calloc(1, sizeof(wifi_ble_config_t));
AUDIO_MEM_CHECK(WIFI_BLE_TAG, g_wifi_ble_config, return ESP_FAIL);
g_wifi_ble_config->periph = periph;
blufi_security_init();
esp_ble_gap_register_callback(wifi_ble_gap_event_handler);
esp_blufi_register_callbacks(&wifi_ble_callbacks);
esp_blufi_profile_init();
return ESP_OK;
}
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/lib/blufi/wifibleconfig.c
|
C
|
apache-2.0
| 10,133
|
/*
* 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 _WIFI_BLECONFIG_H_
#define _WIFI_BLECONFIG_H_
#include "esp_err.h"
#include "esp_peripherals.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Start Wi-Fi BLE config
*
* @param[in] periph The peripheral handle
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t ble_config_start(esp_periph_handle_t periph);
/**
* @brief Stop Wi-Fi BLE config.
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t ble_config_stop(void);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/lib/blufi/wifibleconfig.h
|
C
|
apache-2.0
| 1,745
|
/*
* 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 <stdio.h>
#include <string.h>
#include <sys/time.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "esp_log.h"
#include "driver/gpio.h"
#include "sys/queue.h"
#include "button.h"
#include "audio_mem.h"
#ifdef periph_tick_get
#define tick_get periph_tick_get
#else
static long long tick_get()
{
struct timeval te;
gettimeofday(&te, NULL);
long long milliseconds = te.tv_sec * 1000LL + te.tv_usec / 1000;
return milliseconds;
}
#endif
static const char *TAG = "BUTTON";
typedef struct esp_button_item {
int gpio_num;
long long last_press_tick;
bool long_pressed;
STAILQ_ENTRY(esp_button_item) entry;
} esp_button_item_t;
struct esp_button {
int long_press_time_ms;
uint64_t gpio_mask;
STAILQ_HEAD(esp_button_list, esp_button_item) btn_list;
};
static button_status_t button_get_state(esp_button_handle_t button, esp_button_item_t *btn_item)
{
int level = gpio_get_level(btn_item->gpio_num);
int active_level = 0;
int deactive_level = 1;
if (btn_item->last_press_tick == 0 && level == active_level) {
btn_item->last_press_tick = tick_get();
btn_item->long_pressed = false;
return BTN_PRESSED;
}
if (level == deactive_level && btn_item->last_press_tick && tick_get() - btn_item->last_press_tick > button->long_press_time_ms) {
btn_item->last_press_tick = 0;
btn_item->long_pressed = false;
return BTN_LONG_RELEASE;
}
if (level == deactive_level && btn_item->last_press_tick) {
btn_item->last_press_tick = 0;
btn_item->long_pressed = false;
return BTN_RELEASE;
}
if (btn_item->long_pressed == false && level == active_level && tick_get() - btn_item->last_press_tick > button->long_press_time_ms) {
btn_item->long_pressed = true;
return BTN_LONG_PRESS;
}
return BTN_UNCHANGE;
}
esp_button_handle_t button_init(button_config_t *config)
{
esp_button_handle_t btn = audio_calloc(1, sizeof(struct esp_button));
AUDIO_MEM_CHECK(TAG, btn, return NULL);
if (config->gpio_mask <= 0) {
ESP_LOGE(TAG, "required at least 1 gpio");
return NULL;
}
btn->gpio_mask = config->gpio_mask;
btn->long_press_time_ms = config->long_press_time_ms;
if (btn->long_press_time_ms == 0) {
btn->long_press_time_ms = DEFAULT_LONG_PRESS_TIME_MS;
}
gpio_config_t gpiocfg = {
.pin_bit_mask = btn->gpio_mask,
.mode = GPIO_MODE_INPUT,
.pull_up_en = GPIO_PULLUP_ENABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_ANYEDGE,
};
gpio_config(&gpiocfg);
uint64_t gpio_mask = btn->gpio_mask;
int gpio_num = 0;
STAILQ_INIT(&btn->btn_list);
while (gpio_mask) {
if (gpio_mask & 0x01) {
ESP_LOGD(TAG, "Mask = %llx, current_mask = %llx, idx=%d", btn->gpio_mask, gpio_mask, gpio_num);
esp_button_item_t *new_btn = audio_calloc(1, sizeof(esp_button_item_t));
AUDIO_MEM_CHECK(TAG, new_btn, {
button_destroy(btn);
return NULL;
});
new_btn->gpio_num = gpio_num;
if (config->button_intr_handler) {
gpio_set_intr_type(gpio_num, GPIO_INTR_ANYEDGE);
gpio_isr_handler_add(gpio_num, config->button_intr_handler, config->intr_context);
gpio_intr_enable(gpio_num);
}
STAILQ_INSERT_TAIL(&btn->btn_list, new_btn, entry);
}
gpio_mask >>= 1;
gpio_num ++;
}
return btn;
}
bool button_read(esp_button_handle_t button, button_result_t *result)
{
esp_button_item_t *btn_item;
button_status_t btn_status;
bool changed = false;
memset(result, 0, sizeof(button_result_t));
uint64_t tmp;
STAILQ_FOREACH(btn_item, &button->btn_list, entry) {
btn_status = button_get_state(button, btn_item);
switch (btn_status) {
case BTN_UNCHANGE:
break;
case BTN_PRESSED:
changed = true;
tmp = 0x01;
tmp <<= btn_item->gpio_num;
result->press_mask |= tmp;
break;
case BTN_RELEASE:
changed = true;
tmp = 0x01;
tmp <<= btn_item->gpio_num;
result->release_mask |= tmp;
break;
case BTN_LONG_RELEASE:
changed = true;
tmp = 0x01;
tmp <<= btn_item->gpio_num;
result->long_release_mask |= tmp;
break;
case BTN_LONG_PRESS:
changed = true;
tmp = 0x01;
tmp <<= btn_item->gpio_num;
result->long_press_mask |= tmp;
break;
}
}
return changed;
}
esp_err_t button_destroy(esp_button_handle_t button)
{
esp_button_item_t *btn_item, *tmp;
STAILQ_FOREACH_SAFE(btn_item, &button->btn_list, entry, tmp) {
gpio_intr_disable(btn_item->gpio_num);
gpio_isr_handler_remove(btn_item->gpio_num);
STAILQ_REMOVE(&button->btn_list, btn_item, esp_button_item, entry);
audio_free(btn_item);
}
audio_free(button);
return ESP_OK;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/lib/button/button.c
|
C
|
apache-2.0
| 6,624
|
/*
* 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 _ESP_BUTTON_
#define _ESP_BUTTON_
#include "driver/gpio.h"
#include "audio_error.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief { item_description }
*/
typedef enum {
BTN_UNCHANGE = 0,
BTN_PRESSED,
BTN_RELEASE,
BTN_LONG_PRESS,
BTN_LONG_RELEASE,
} button_status_t;
/**
* @brief { item_description }
*/
typedef struct {
uint64_t press_mask;
uint64_t release_mask;
uint64_t long_press_mask;
uint64_t long_release_mask;
} button_result_t;
typedef struct esp_button *esp_button_handle_t;
typedef void (*gpio_intr_handler)(void *);
/**
* @brief { item_description }
*/
typedef struct {
int long_press_time_ms;
uint64_t gpio_mask;
gpio_intr_handler button_intr_handler;
void *intr_context;
} button_config_t;
#define DEFAULT_LONG_PRESS_TIME_MS (2*1000)
/**
* @brief { function_description }
*
* @param config The configuration
*
* @return { description_of_the_return_value }
*/
esp_button_handle_t button_init(button_config_t *config);
/**
* @brief { function_description }
*
* @param[in] button The button
* @param result The result
*
* @return { description_of_the_return_value }
*/
bool button_read(esp_button_handle_t button, button_result_t *result);
/**
* @brief { function_description }
*
* @param[in] button The button
*
* @return { description_of_the_return_value }
*/
esp_err_t button_destroy(esp_button_handle_t button);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/lib/button/button.h
|
C
|
apache-2.0
| 2,758
|
/*
* 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 "esp_log.h"
#include "driver/gpio.h"
static const char *TAG = "GPIO_ISR";
esp_err_t gpio_isr_init(int gpio_num, gpio_int_type_t type, gpio_isr_t gpio_isr_handle_func, void *isr_param)
{
esp_err_t ret = ESP_OK;
if (gpio_num < 0 || NULL == gpio_isr_handle_func) {
ESP_LOGE(TAG, "Please check the parameters!");
return ESP_OK;
}
ret |= gpio_set_direction(gpio_num, GPIO_MODE_INPUT);
ret |= gpio_set_intr_type(gpio_num, type);
ret |= gpio_isr_handler_add(gpio_num, gpio_isr_handle_func, isr_param);
ret |= gpio_intr_enable(gpio_num);
return ret;
}
esp_err_t gpio_isr_deinit(int gpio_num)
{
esp_err_t ret = ESP_OK;
if (gpio_num < 0) {
ESP_LOGE(TAG, "The gpio number should greater than or equal to 0");
return ESP_FAIL;
}
ret |= gpio_isr_handler_remove(gpio_num);
ret |= gpio_intr_disable(gpio_num);
return ret;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/lib/gpio_isr/gpio_isr.c
|
C
|
apache-2.0
| 2,145
|
/*
* 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 _GPIO_ISR_H_
#define _GPIO_ISR_H_
#include "esp_err.h"
#include "driver/gpio.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Initialize the gpio's interrupt service routines.
*
* @param gpio_num The number of gpio to be initialized
* @param type The type of interrupts
* @param gpio_isr_handle_func Interrupt handler
* @param isr_param The parameters of interrupt handler
*
* @return
*/
esp_err_t gpio_isr_init(int gpio_num, gpio_int_type_t type, gpio_isr_t gpio_isr_handle_func, void *isr_param);
/**
* @brief Deinitialize the gpio isr
*
* @param gpio_num The number of gpio to be deinitialized
*
* @return
* - ESP_OK on success
* - ESP_FAIL on failed
*/
esp_err_t gpio_isr_deinit(int gpio_num);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/lib/gpio_isr/gpio_isr.h
|
C
|
apache-2.0
| 2,081
|
/*
* 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 <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "esp_err.h"
#include "esp_vfs_fat.h"
#include "driver/sdmmc_host.h"
#include "driver/sdmmc_defs.h"
#include "driver/gpio.h"
#include "sdcard.h"
#include "board.h"
static const char *TAG = "SDCARD";
int g_gpio = -1;
#define PIN_NUM_MISO 2
#define PIN_NUM_MOSI 15
#define PIN_NUM_CLK 14
#define PIN_NUM_CS 13
static void sdmmc_card_print_info(const sdmmc_card_t *card)
{
ESP_LOGD(TAG, "Name: %s\n", card->cid.name);
ESP_LOGD(TAG, "Type: %s\n", (card->ocr & SD_OCR_SDHC_CAP) ? "SDHC/SDXC" : "SDSC");
ESP_LOGD(TAG, "Speed: %s\n", (card->csd.tr_speed > 25000000) ? "high speed" : "default speed");
ESP_LOGD(TAG, "Size: %lluMB\n", ((uint64_t) card->csd.capacity) * card->csd.sector_size / (1024 * 1024));
ESP_LOGD(TAG, "CSD: ver=%d, sector_size=%d, capacity=%d read_bl_len=%d\n",
card->csd.csd_ver,
card->csd.sector_size, card->csd.capacity, card->csd.read_block_len);
ESP_LOGD(TAG, "SCR: sd_spec=%d, bus_width=%d\n", card->scr.sd_spec, card->scr.bus_width);
}
esp_err_t sdcard_mount(const char *base_path, periph_sdcard_mode_t mode)
{
if (mode >= SD_MODE_MAX) {
ESP_LOGE(TAG, "PLease select the correct sd mode: 1-line SD mode, 4-line SD mode or SPI mode!, current mode is %d", mode);
return ESP_FAIL;
}
sdmmc_card_t *card = NULL;
esp_err_t ret = 0;
esp_vfs_fat_sdmmc_mount_config_t mount_config = {
.format_if_mount_failed = false,
.max_files = get_sdcard_open_file_num_max(),
};
if (mode != SD_MODE_SPI) {
ESP_LOGI(TAG, "Using 1-line SD mode, 4-line SD mode, base path=%s", base_path);
sdmmc_host_t host = SDMMC_HOST_DEFAULT();
// host.max_freq_khz = SDMMC_FREQ_HIGHSPEED;
sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT();
// slot_config.gpio_cd = g_gpio;
slot_config.width = mode & 0X01;
// Enable internal pullups on enabled pins. The internal pullups
// are insufficient however, please make sure 10k external pullups are
// connected on the bus. This is for debug / example purpose only.
slot_config.flags |= SDMMC_SLOT_FLAG_INTERNAL_PULLUP;
#if CONFIG_IDF_TARGET_ESP32S3
slot_config.clk = ESP_SD_PIN_CLK;
slot_config.cmd = ESP_SD_PIN_CMD;
slot_config.d0 = ESP_SD_PIN_D0;
slot_config.d1 = ESP_SD_PIN_D1;
slot_config.d2 = ESP_SD_PIN_D2;
slot_config.d3 = ESP_SD_PIN_D3;
slot_config.d4 = ESP_SD_PIN_D4;
slot_config.d5 = ESP_SD_PIN_D5;
slot_config.d6 = ESP_SD_PIN_D6;
slot_config.d7 = ESP_SD_PIN_D7;
slot_config.cd = ESP_SD_PIN_CD;
slot_config.wp = ESP_SD_PIN_WP;
ESP_LOGI(TAG, "Using 1-line SD mode");
#else
gpio_set_pull_mode(GPIO_NUM_15, GPIO_PULLUP_ONLY);
gpio_set_pull_mode(GPIO_NUM_2, GPIO_PULLUP_ONLY);
gpio_set_pull_mode(GPIO_NUM_13, GPIO_PULLUP_ONLY);
if (mode == SD_MODE_4_LINE) {
gpio_set_pull_mode(GPIO_NUM_4, GPIO_PULLUP_ONLY);
gpio_set_pull_mode(GPIO_NUM_12, GPIO_PULLUP_ONLY);
}
#endif
ret = esp_vfs_fat_sdmmc_mount(base_path, &host, &slot_config, &mount_config, &card);
} else {
ESP_LOGI(TAG, "Using SPI mode, base path=%s", base_path);
sdmmc_host_t host = SDSPI_HOST_DEFAULT();
sdspi_slot_config_t slot_config = SDSPI_SLOT_CONFIG_DEFAULT();
slot_config.gpio_miso = PIN_NUM_MISO;
slot_config.gpio_mosi = PIN_NUM_MOSI;
slot_config.gpio_sck = PIN_NUM_CLK;
slot_config.gpio_cs = PIN_NUM_CS;
ret = esp_vfs_fat_sdmmc_mount(base_path, &host, &slot_config, &mount_config, &card);
}
switch (ret) {
case ESP_OK:
// Card has been initialized, print its properties
sdmmc_card_print_info(card);
ESP_LOGI(TAG, "CID name %s!\n", card->cid.name);
break;
case ESP_ERR_INVALID_STATE:
ESP_LOGE(TAG, "File system already mounted");
break;
case ESP_FAIL:
ESP_LOGE(TAG, "Failed to mount filesystem. If you want the card to be formatted, set format_if_mount_failed = true.");
break;
default:
ESP_LOGE(TAG, "Failed to initialize the card (%d). Make sure SD card lines have pull-up resistors in place.", ret);
break;
}
return ret;
}
esp_err_t sdcard_unmount(void)
{
esp_err_t ret = esp_vfs_fat_sdmmc_unmount();
if (ret == ESP_ERR_INVALID_STATE) {
ESP_LOGE(TAG, "File system not mounted");
}
return ret;
}
bool sdcard_is_exist()
{
if (g_gpio >= 0) {
return (gpio_get_level(g_gpio) == 0x00);
} else {
return true;
}
return false;
}
int IRAM_ATTR sdcard_read_detect_pin(void)
{
if (g_gpio >= 0) {
return gpio_get_level(g_gpio);
} else {
return -1;
}
return 0;
}
esp_err_t sdcard_destroy()
{
if (g_gpio >= 0) {
return gpio_isr_handler_remove(g_gpio);
}
return ESP_OK;
}
esp_err_t sdcard_init(int card_detect_pin, void (*detect_intr_handler)(void *), void *isr_context)
{
esp_err_t ret = ESP_OK;
if (card_detect_pin >= 0) {
gpio_set_direction(card_detect_pin, GPIO_MODE_INPUT);
if (detect_intr_handler) {
gpio_set_intr_type(card_detect_pin, GPIO_INTR_ANYEDGE);
gpio_isr_handler_add(card_detect_pin, detect_intr_handler, isr_context);
gpio_intr_enable(card_detect_pin);
}
gpio_pullup_en(card_detect_pin);
}
g_gpio = card_detect_pin;
return ret;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/lib/sdcard/sdcard.c
|
C
|
apache-2.0
| 6,920
|
/*
* 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 _ESP_SDCARD_H_
#define _ESP_SDCARD_H_
#include "audio_error.h"
#include "periph_sdcard.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief { function_description }
*
* @param[in] gpio The gpio
* @param[in] detect_intr_handler The detect intr handler
* @param isr_context The isr context
*
* @return { description_of_the_return_value }
*/
esp_err_t sdcard_init(int gpio, void (*detect_intr_handler)(void *), void *isr_context);
/**
* @brief mount sdcard to FAT filesystem
*
* @param base_path path where partition should be registered (e.g. "/sdcard")
*
* @return
* - ESP_OK on success
* - ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount was already called
* - ESP_ERR_NO_MEM if memory can not be allocated
* - ESP_FAIL if partition can not be mounted
* - other error codes from SDMMC or SPI drivers, SDMMC protocol, or FATFS drivers
*/
esp_err_t sdcard_mount(const char* base_path, periph_sdcard_mode_t mode);
/**
* @brief Unmount FAT filesystem and release resources acquired using esp_vfs_fat_sdmmc_mount
*
* @return
* - ESP_OK on success
* - ESP_ERR_INVALID_STATE if sd_card_mount hasn't been called
*/
esp_err_t sdcard_unmount(void);
/**
* @brief remove the sdcard device GPIO interruption in Audio board
*
* @return
* - ESP_OK on success
* - ESP_FAIL destory sdcard gpio handle failed
*/
esp_err_t sdcard_destroy(void);
/**
* @brief get the status of sdcard is insert or not
*
* @return
* - true sdcard is insert
* - false sdcard is unplug
*/
bool sdcard_is_exist();
/**
* @brief Read value of CARD DETECT Pin
*
* @return value of CARD DETECT PIN
*/
int sdcard_read_detect_pin(void);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/lib/sdcard/sdcard.h
|
C
|
apache-2.0
| 3,041
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2021 <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 "driver/gpio.h"
#include "i2c_bus.h"
#include "board.h"
#include "esp_log.h"
#include "tca9554.h"
#define TCA9554_ADDR 0x40
static char *TAG = "TCA9554";
static i2c_bus_handle_t i2c_handle;
#define SET_BITS(_m, _s, _v) ((_v) ? (_m)|((_s)) : (_m)&~((_s)))
#define GET_BITS(_m, _s) (((_m) & (_s)) ? true : false)
#define TCA9554_INPUT_PORT 0x00
#define TCA9554_OUTPUT_PORT 0x01
#define TCA9554_POLARITY_INVERSION_PORT 0x02
#define TCA9554_CONFIGURATION_PORT 0x03
static esp_err_t tca9554_write_reg(uint8_t reg_addr, uint8_t data)
{
return i2c_bus_write_bytes(i2c_handle, TCA9554_ADDR, ®_addr, sizeof(reg_addr), &data, sizeof(data));
}
static char tca9554_read_reg(uint8_t reg_addr)
{
uint8_t data;
i2c_bus_read_bytes(i2c_handle, TCA9554_ADDR, ®_addr, sizeof(reg_addr), &data, sizeof(data));
return data;
}
static int i2c_init(gpio_num_t clk, gpio_num_t sda)
{
int res = 0;
i2c_config_t es_i2c_cfg = {
.mode = I2C_MODE_MASTER,
.sda_pullup_en = GPIO_PULLUP_ENABLE,
.scl_pullup_en = GPIO_PULLUP_ENABLE,
.master.clk_speed = 100000,
.scl_io_num = clk,
.sda_io_num = sda,
};
i2c_handle = i2c_bus_create(I2C_NUM_0, &es_i2c_cfg);
return res;
}
esp_tca9554_io_level_t tca9554_get_input_state(esp_tca9554_gpio_num_t gpio_num)
{
char data = 0;
if (gpio_num < TCA9554_GPIO_NUM_MAX) {
data = tca9554_read_reg(TCA9554_INPUT_PORT);
} else {
ESP_LOGE(TAG, "gpio num is error, current gpio: %d", gpio_num);
return TCA9554_LEVEL_ERROR;
}
return GET_BITS(data, gpio_num);
}
esp_tca9554_io_level_t tca9554_get_output_state(esp_tca9554_gpio_num_t gpio_num)
{
char data = 0;
if (gpio_num < TCA9554_GPIO_NUM_MAX) {
data = tca9554_read_reg(TCA9554_OUTPUT_PORT);
} else {
ESP_LOGE(TAG, "gpio num is error, current gpio: %d", gpio_num);
return TCA9554_LEVEL_ERROR;
}
return GET_BITS(data, gpio_num);
}
esp_err_t tca9554_set_output_state(esp_tca9554_gpio_num_t gpio_num, esp_tca9554_io_level_t level)
{
char data;
esp_err_t res = ESP_FAIL;
if (gpio_num < TCA9554_GPIO_NUM_MAX) {
data = tca9554_read_reg(TCA9554_OUTPUT_PORT);
res = tca9554_write_reg(TCA9554_OUTPUT_PORT, SET_BITS(data, gpio_num, level));
} else {
ESP_LOGE(TAG, "gpio num is error, current gpio: %d", gpio_num);
}
return res;
}
esp_err_t tca9554_set_polarity_inversion(esp_tca9554_gpio_num_t gpio_num, esp_tca9554_io_polarity_t polarity)
{
char data;
esp_err_t res = ESP_FAIL;
if (gpio_num < TCA9554_GPIO_NUM_MAX) {
data = tca9554_read_reg(TCA9554_POLARITY_INVERSION_PORT);
res = tca9554_write_reg(TCA9554_POLARITY_INVERSION_PORT, SET_BITS(data, gpio_num, polarity));
} else {
ESP_LOGE(TAG, "gpio num is error, current gpio: %d", gpio_num);
}
return res;
}
esp_tca9554_io_config_t tca9554_get_io_config(esp_tca9554_gpio_num_t gpio_num)
{
char data = 0;
if (gpio_num < TCA9554_GPIO_NUM_MAX) {
data = tca9554_read_reg(TCA9554_CONFIGURATION_PORT);
} else {
ESP_LOGE(TAG, "gpio num is error, current gpio: %d", gpio_num);
return TCA9554_LEVEL_ERROR;
}
return GET_BITS(data, gpio_num);
}
esp_err_t tca9554_set_io_config(esp_tca9554_gpio_num_t gpio_num, esp_tca9554_io_config_t io_config)
{
char data;
esp_err_t res = ESP_FAIL;
if (gpio_num < TCA9554_GPIO_NUM_MAX) {
data = tca9554_read_reg(TCA9554_CONFIGURATION_PORT);
res = tca9554_write_reg(TCA9554_CONFIGURATION_PORT, SET_BITS(data, gpio_num, io_config));
} else {
ESP_LOGE(TAG, "gpio num is error, current gpio: %d", gpio_num);
}
return res;
}
void tca9554_read_all()
{
for (int i = 0; i < 0x04; i++) {
uint8_t reg = tca9554_read_reg(i);
ets_printf("REG:%02x, %02x\n", i, reg);
}
}
esp_err_t tca9554_init(esp_tca9554_config_t *cfg)
{
esp_err_t ret = ESP_OK;
i2c_init(cfg->i2c_scl, cfg->i2c_sda);
return ret;
}
esp_err_t tca9554_deinit()
{
i2c_bus_delete(i2c_handle);
return ESP_OK;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/lib/tca9554/tca9554.c
|
C
|
apache-2.0
| 5,404
|
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2021 <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 _TCA9554_H
#define _TCA9554_H
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
TCA9554_GPIO_NUM_0 = BIT(0),
TCA9554_GPIO_NUM_1 = BIT(1),
TCA9554_GPIO_NUM_2 = BIT(2),
TCA9554_GPIO_NUM_3 = BIT(3),
TCA9554_GPIO_NUM_4 = BIT(4),
TCA9554_GPIO_NUM_5 = BIT(5),
TCA9554_GPIO_NUM_6 = BIT(6),
TCA9554_GPIO_NUM_7 = BIT(7),
TCA9554_GPIO_NUM_MAX
} esp_tca9554_gpio_num_t;
typedef enum {
TCA9554_IO_LOW,
TCA9554_IO_HIGH,
TCA9554_LEVEL_ERROR
} esp_tca9554_io_level_t;
typedef enum {
TCA9554_IO_RETAINED,
TCA9554_IO_INVERTED
} esp_tca9554_io_polarity_t;
typedef enum {
TCA9554_IO_OUTPUT,
TCA9554_IO_INPUT
} esp_tca9554_io_config_t;
typedef struct {
gpio_num_t i2c_sda;
gpio_num_t i2c_scl;
gpio_num_t interrupt_output;
} esp_tca9554_config_t;
/*
* @brief Initialize TCA9554 chip
*
* @param codec_cfg configuration of TCA9554
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t tca9554_init(esp_tca9554_config_t *cfg);
/**
* @brief Deinitialize TCA9554 chip
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t tca9554_deinit(void);
/*
* @brief Get TCA9554 input level
*
* @param gpio_num GPIO of TCA9554
*
* @return
* - esp_tca9554_io_level_t
*/
esp_tca9554_io_level_t tca9554_get_input_state(esp_tca9554_gpio_num_t gpio_num);
/*
* @brief Get PCA95xian39 output level
*
* @param gpio_num GPIO of TCA9554
*
* @return
* - esp_tca9554_io_level_t
*/
esp_tca9554_io_level_t tca9554_get_output_state(esp_tca9554_gpio_num_t gpio_num);
/*
* @brief Get TCA9554 output state
*
* @param gpio_num GPIO of TCA9554
*
* @return
* - esp_tca9554_io_level_t
*/
esp_err_t tca9554_set_output_state(esp_tca9554_gpio_num_t gpio_num, esp_tca9554_io_level_t level);
/*
* @brief Set TCA9554 polarity
*
* @param gpio_num GPIO of TCA9554
* polarity polarity
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t tca9554_set_polarity_inversion(esp_tca9554_gpio_num_t gpio_num, esp_tca9554_io_polarity_t polarity);
/*
* @brief Get TCA9554 output level
*
* @param gpio_num GPIO of TCA9554
*
* @return
* - esp_tca9554_io_level_t
*/
esp_tca9554_io_config_t tca9554_get_io_config(esp_tca9554_gpio_num_t gpio_num);
/*
* @brief Set TCA9554 io config
*
* @param gpio_num GPIO of TCA9554
* io_config io config
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t tca9554_set_io_config(esp_tca9554_gpio_num_t gpio_num, esp_tca9554_io_config_t io_config);
/**
* @brief Print all TCA9554 registers
*
* @return
* - void
*/
void tca9554_read_all();
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/lib/tca9554/tca9554.h
|
C
|
apache-2.0
| 3,900
|
/*
* 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 <stdio.h>
#include <string.h>
#include <sys/time.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "esp_log.h"
#include "driver/gpio.h"
#include "driver/touch_pad.h"
#include "sys/queue.h"
#include "touch.h"
#include "sdkconfig.h"
#include "audio_mem.h"
#define TOUCHPAD_TRIGGER_THRESHOLD 100
#define TOUCHPAD_FILTER_PERIOD (30)
#define TOUCHPAD_READ_INTERVAL_MS (TOUCHPAD_FILTER_PERIOD*4)
#define TOUCHPAD_INTIALIZE_TIME_MS 1000
#define UPDATE_THRESHOLD_PERIOD_MS 200
static const char *TAG = "TOUCH";
typedef struct esp_touch_item {
int touch_num;
long long last_tap_tick;
long long update_threshold_tick;
long long last_read_tick;
uint16_t last_read_value;
uint16_t untouch_value;
uint16_t threshold_value;
bool long_tapped;
bool tapped;
STAILQ_ENTRY(esp_touch_item) entry;
} esp_touch_item_t;
struct esp_touch {
int long_tap_time_ms;
int touch_mask;
int tap_threshold_percent;
touch_intr_handler intr_fn;
void *intr_context;
STAILQ_HEAD(esp_touch_list, esp_touch_item) touch_list;
};
#ifdef periph_tick_get
#define tick_get periph_tick_get
#else
static long long tick_get()
{
struct timeval te;
gettimeofday(&te, NULL); // get current time
long long milliseconds = te.tv_sec * 1000LL + te.tv_usec / 1000; // calculate milliseconds
return milliseconds;
}
#endif
static void touch_pad_isr_handler(void* arg)
{
esp_touch_handle_t touch = (esp_touch_handle_t)arg;
#if CONFIG_IDF_TARGET_ESP32
touch_pad_clear_status();
#endif
if (touch->intr_fn) {
touch->intr_fn(touch->intr_context);
}
}
esp_touch_handle_t esp_touch_init(touch_config_t *config)
{
esp_touch_handle_t touch = audio_calloc(1, sizeof(struct esp_touch));
AUDIO_MEM_CHECK(TAG, touch, return NULL);
if (config->touch_mask <= 0) {
ESP_LOGE(TAG, "required at least 1 touch");
return NULL;
}
touch->touch_mask = config->touch_mask;
touch->long_tap_time_ms = config->long_tap_time_ms;
touch->tap_threshold_percent = config->tap_threshold_percent;
if (touch->long_tap_time_ms == 0) {
touch->long_tap_time_ms = DEFAULT_LONG_TAP_TIME_MS;
}
if (touch->tap_threshold_percent == 0) {
touch->tap_threshold_percent = DEFAULT_TOUCH_THRESHOLD_PERCENT;
}
bool _success = (touch_pad_init() == ESP_OK);
AUDIO_MEM_CHECK(TAG, _success, {
audio_free(touch);
return NULL;
});
int touch_mask = touch->touch_mask;
int touch_num = 0;
int touch_index = 0;
STAILQ_INIT(&touch->touch_list);
while (touch_mask) {
if (touch_mask & 0x01) {
ESP_LOGD(TAG, "Mask = %x, current_mask = %x, idx=%d", touch->touch_mask, touch_mask, touch_num);
esp_touch_item_t *new_touch = audio_calloc(1, sizeof(esp_touch_item_t));
AUDIO_MEM_CHECK(TAG, new_touch, {
esp_touch_destroy(touch);
audio_free(touch);
return NULL;
});
new_touch->touch_num = touch_num;
new_touch->last_read_tick = tick_get() + touch_index * 10;
#if CONFIG_IDF_TARGET_ESP32
touch_pad_config(touch_num, 0);
#elif CONFIG_IDF_TARGET_ESP32S2
touch_pad_config(touch_num);
#endif
if (config->touch_intr_handler) {
touch_pad_set_thresh(touch_num, TOUCHPAD_TRIGGER_THRESHOLD);
}
STAILQ_INSERT_TAIL(&touch->touch_list, new_touch, entry);
touch_index ++;
}
touch_mask >>= 1;
touch_num ++;
}
touch->intr_fn = config->touch_intr_handler;
touch->intr_context = config->intr_context;
if (config->touch_intr_handler) {
#if CONFIG_IDF_TARGET_ESP32
touch_pad_isr_register(touch_pad_isr_handler, touch);
touch_pad_intr_enable();
#elif CONFIG_IDF_TARGET_ESP32S2
touch_pad_isr_register(touch_pad_isr_handler, touch, TOUCH_PAD_INTR_MASK_ALL);
touch_pad_intr_enable(TOUCH_PAD_INTR_MASK_ALL);
#endif
}
#if CONFIG_IDF_TARGET_ESP32
touch_pad_filter_start(TOUCHPAD_FILTER_PERIOD);
#endif
return touch;
}
static touch_status_t touch_get_state(esp_touch_handle_t touch, esp_touch_item_t *touch_item, long long tick)
{
if (tick - touch_item->last_read_tick < TOUCHPAD_READ_INTERVAL_MS) {
return TOUCH_UNCHANGE;
}
touch_item->last_read_tick = tick;
esp_err_t err = ESP_OK;
#if CONFIG_IDF_TARGET_ESP32
err = touch_pad_read_filtered(touch_item->touch_num, &touch_item->last_read_value);
#elif CONFIG_IDF_TARGET_ESP32S2
err = ESP_OK;
#endif
if (err != ESP_OK) {
return TOUCH_UNCHANGE;
}
if (touch_item->untouch_value == 0) {
touch_item->untouch_value = touch_item->last_read_value;
int threshold_value = touch_item->untouch_value * touch->tap_threshold_percent / 100;
touch_item->threshold_value = threshold_value;
}
if (!touch_item->tapped && touch_item->last_read_value < touch_item->threshold_value) {
touch_item->tapped = true;
} else if (touch_item->tapped && touch_item->last_read_value > touch_item->threshold_value) {
touch_item->tapped = false;
}
// Update touch threshold
if (tick - touch_item->update_threshold_tick > UPDATE_THRESHOLD_PERIOD_MS && !touch_item->tapped) {
touch_item->update_threshold_tick = tick;
touch_item->untouch_value += touch_item->last_read_value;
touch_item->untouch_value /= 2;
int threshold_value = touch_item->untouch_value * touch->tap_threshold_percent / 100;
touch_item->threshold_value = threshold_value;
// ESP_LOGD(TAG, "UPDATE THRESHOLD[%d]=%d", touch_item->touch_num, threshold_value);
}
if (touch_item->last_tap_tick == 0 && touch_item->tapped) {
touch_item->last_tap_tick = tick_get();
touch_item->long_tapped = false;
ESP_LOGD(TAG, "TOUCH_TAPPED[%d] %d, threshold %d",
touch_item->touch_num, touch_item->last_read_value, touch_item->threshold_value);
return TOUCH_TAP;
}
if (!touch_item->tapped && touch_item->last_tap_tick && tick_get() - touch_item->last_tap_tick > touch->long_tap_time_ms) {
touch_item->last_tap_tick = 0;
touch_item->long_tapped = false;
ESP_LOGD(TAG, "TOUCH_LONG_RELEASE[%d] %d, threshold %d",
touch_item->touch_num, touch_item->last_read_value, touch_item->threshold_value);
return TOUCH_LONG_RELEASE;
}
if (!touch_item->tapped && touch_item->last_tap_tick) {
touch_item->last_tap_tick = 0;
touch_item->long_tapped = false;
ESP_LOGD(TAG, "TOUCH_RELEASE[%d] %d, threshold %d",
touch_item->touch_num, touch_item->last_read_value, touch_item->threshold_value);
return TOUCH_RELEASE;
}
if (touch_item->long_tapped == false && touch_item->tapped && tick_get() - touch_item->last_tap_tick > touch->long_tap_time_ms) {
touch_item->long_tapped = true;
ESP_LOGD(TAG, "TOUCH_LONG_TAP[%d] %d, threshold %d",
touch_item->touch_num, touch_item->last_read_value, touch_item->threshold_value);
return TOUCH_LONG_TAP;
}
return TOUCH_UNCHANGE;
}
bool esp_touch_read(esp_touch_handle_t touch, touch_result_t *result)
{
esp_touch_item_t *touch_item;
touch_status_t touch_status;
bool changed = false;
memset(result, 0, sizeof(touch_result_t));
int tmp;
long long tick = tick_get();
STAILQ_FOREACH(touch_item, &touch->touch_list, entry) {
touch_status = touch_get_state(touch, touch_item, tick);
switch (touch_status) {
case TOUCH_UNCHANGE:
break;
case TOUCH_TAP:
changed = true;
tmp = 0x01;
tmp <<= touch_item->touch_num;
result->tap_mask |= tmp;
break;
case TOUCH_RELEASE:
changed = true;
tmp = 0x01;
tmp <<= touch_item->touch_num;
result->release_mask |= tmp;
break;
case TOUCH_LONG_RELEASE:
changed = true;
tmp = 0x01;
tmp <<= touch_item->touch_num;
result->long_release_mask |= tmp;
break;
case TOUCH_LONG_TAP:
changed = true;
tmp = 0x01;
tmp <<= touch_item->touch_num;
result->long_tap_mask |= tmp;
break;
}
}
return changed;
}
esp_err_t esp_touch_destroy(esp_touch_handle_t touch)
{
esp_touch_item_t *touch_item, *tmp;
#if CONFIG_IDF_TARGET_ESP32
touch_pad_filter_delete();
touch_pad_intr_disable();
#elif CONFIG_IDF_TARGET_ESP32S2
touch_pad_intr_disable(TOUCH_PAD_INTR_MASK_ALL);
#endif
touch_pad_isr_deregister(touch_pad_isr_handler, touch);
STAILQ_FOREACH_SAFE(touch_item, &touch->touch_list, entry, tmp) {
STAILQ_REMOVE(&touch->touch_list, touch_item, esp_touch_item, entry);
audio_free(touch_item);
}
touch_pad_deinit();
audio_free(touch);
return ESP_OK;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/lib/touch/touch.c
|
C
|
apache-2.0
| 10,680
|
/*
* 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 _ESP_TOUCH_PAD_H_
#define _ESP_TOUCH_PAD_H_
#include "audio_error.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief { item_description }
*/
typedef enum {
TOUCH_UNCHANGE = 0,
TOUCH_TAP,
TOUCH_RELEASE,
TOUCH_LONG_TAP,
TOUCH_LONG_RELEASE,
} touch_status_t;
/**
* @brief { item_description }
*/
typedef struct {
int tap_mask;
int release_mask;
int long_tap_mask;
int long_release_mask;
} touch_result_t;
typedef struct esp_touch *esp_touch_handle_t;
typedef void (*touch_intr_handler)(void *);
#define DEFAULT_LONG_TAP_TIME_MS (2*1000)
#define DEFAULT_TOUCH_THRESHOLD_PERCENT (70)
/**
* @brief { item_description }
*/
typedef struct {
int long_tap_time_ms;
int touch_mask;
int tap_threshold_percent;
touch_intr_handler touch_intr_handler;
void *intr_context;
} touch_config_t;
/**
* @brief { function_description }
*
* @param config The configuration
*
* @return { description_of_the_return_value }
*/
esp_touch_handle_t esp_touch_init(touch_config_t *config);
/**
* @brief { function_description }
*
* @param[in] touch The touch
* @param result The result
*
* @return { description_of_the_return_value }
*/
bool esp_touch_read(esp_touch_handle_t touch, touch_result_t *result);
/**
* @brief { function_description }
*
* @param[in] touch The touch
*
* @return { description_of_the_return_value }
*/
esp_err_t esp_touch_destroy(esp_touch_handle_t touch);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/lib/touch/touch.h
|
C
|
apache-2.0
| 2,793
|
/*
* 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 <string.h>
#include "esp_log.h"
#include "audio_error.h"
#include "periph_adc_button.h"
#include "audio_mem.h"
static const char *TAG = "PERIPH_ADC_BUTTON";
typedef struct {
int adc_channels;
adc_btn_list *list;
adc_btn_task_cfg_t task_cfg;
} periph_adc_btn_t;
static void btn_cb(void *user_data, int adc, int id, adc_btn_state_t state)
{
esp_periph_handle_t self = (esp_periph_handle_t)user_data;
periph_adc_button_event_id_t event_id = PERIPH_ADC_BUTTON_IDLE;
if (state == ADC_BTN_STATE_PRESSED) {
event_id = PERIPH_ADC_BUTTON_PRESSED;
} else if (state == ADC_BTN_STATE_LONG_PRESSED) {
event_id = PERIPH_ADC_BUTTON_LONG_PRESSED;
} else if (state == ADC_BTN_STATE_RELEASE) {
event_id = PERIPH_ADC_BUTTON_RELEASE;
} else if (state == ADC_BTN_STATE_LONG_RELEASE) {
event_id = PERIPH_ADC_BUTTON_LONG_RELEASE;
}
//Send ID as data and ADC as data_len
esp_periph_send_event(self, event_id, (void *)id, adc);
}
static esp_err_t _adc_button_destroy(esp_periph_handle_t self)
{
periph_adc_btn_t *periph_adc_btn = esp_periph_get_data(self);
adc_btn_delete_task();
adc_btn_destroy_list(periph_adc_btn->list);
audio_free(periph_adc_btn);
return ESP_OK;
}
static esp_err_t _adc_button_init(esp_periph_handle_t self)
{
periph_adc_btn_t *periph_adc_btn = esp_periph_get_data(self);
adc_btn_init((void *)self, btn_cb, periph_adc_btn->list, &periph_adc_btn->task_cfg);
return ESP_OK;
}
esp_periph_handle_t periph_adc_button_init(periph_adc_button_cfg_t *config)
{
esp_periph_handle_t periph = esp_periph_create(PERIPH_ID_ADC_BTN, "periph_adc_btn");
AUDIO_MEM_CHECK(TAG, periph, return NULL);
periph_adc_btn_t *periph_adc_btn = audio_calloc(1, sizeof(periph_adc_btn_t));
AUDIO_MEM_CHECK(TAG, periph_adc_btn, {
audio_free(periph);
return NULL;
});
periph_adc_btn->adc_channels = config->arr_size;
periph_adc_btn->list = adc_btn_create_list(config->arr, config->arr_size);
memcpy(&periph_adc_btn->task_cfg, &config->task_cfg, sizeof(adc_btn_task_cfg_t));
AUDIO_MEM_CHECK(TAG, periph_adc_btn->list, {
audio_free(periph);
audio_free(periph_adc_btn);
return NULL;
});
esp_periph_set_data(periph, periph_adc_btn);
esp_periph_set_function(periph, _adc_button_init, NULL, _adc_button_destroy);
return periph;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/periph_adc_button.c
|
C
|
apache-2.0
| 3,642
|
/*
* 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 "audio_mem.h"
#include "esp_peripherals.h"
#include "aw2013.h"
#include "periph_aw2013.h"
static const char *TAG = "PERIPH_AW2013";
typedef struct {
aw2013_time_level_t time[5];
aw2013_brightness_t bright;
periph_aw2013_mode_t mode;
uint32_t rgb_value;
uint8_t rpt_time;
} periph_aw2013_t;
static esp_err_t _aw2013_set_mode(periph_aw2013_mode_t mode)
{
esp_err_t ret = ESP_OK;
switch (mode) {
case AW2013_MODE_LED:
ret |= aw2013_enable_auto_flash(false);
ret |= aw2013_enable_fade_mode(false);
break;
case AW2013_MODE_FADE:
ret |= aw2013_enable_auto_flash(false);
ret |= aw2013_enable_fade_mode(true);
break;
case AW2013_MODE_AUTO:
ret |= aw2013_enable_auto_flash(true);
ret |= aw2013_enable_fade_mode(false);
break;
default:
ESP_LOGE(TAG, "Invalid mode :%d", mode);
return ESP_FAIL;
}
return ESP_OK;
}
static esp_err_t _aw2013_init(esp_periph_handle_t self)
{
esp_err_t ret = ESP_OK;
periph_aw2013_t *aw2013 = esp_periph_get_data(self);
ret |= aw2013_init();
for (int i = 0; i <= AW2013_TIME_4; i++) {
ret |= aw2013_set_time(i, aw2013->time[i]);
}
ret |= aw2013_set_repeat_time(aw2013->rpt_time);
ret |= aw2013_set_brightness(aw2013->bright);
ret |= _aw2013_set_mode(aw2013->mode);
ret |= aw2013_set_pwm_value(aw2013->rgb_value);
return ret;
}
static esp_err_t _aw2013_destroy(esp_periph_handle_t self)
{
esp_err_t ret = ESP_OK;
periph_aw2013_t *aw2013 = esp_periph_get_data(self);
ret |= aw2013_deinit();
audio_free(aw2013);
return ret;
}
esp_err_t periph_aw2013_set_brightless(esp_periph_handle_t periph, aw2013_brightness_t bright)
{
periph_aw2013_t *aw2013 = esp_periph_get_data(periph);
if (bright < AW2013_BRIGHT_0 || bright > AW2013_BRIGHT_3) {
ESP_LOGE(TAG, "Fail to set parameters, bright: %d", bright);
return ESP_FAIL;
}
aw2013->bright = bright;
return aw2013_set_brightness(bright);
}
esp_err_t periph_aw2013_set_rgb_value(esp_periph_handle_t periph, uint32_t value)
{
periph_aw2013_t *aw2013 = esp_periph_get_data(periph);
aw2013->rgb_value = value;
return aw2013_set_pwm_value(value);
}
esp_err_t periph_aw2013_set_repeat_time(esp_periph_handle_t periph, uint8_t cnt)
{
periph_aw2013_t *aw2013 = esp_periph_get_data(periph);
aw2013->rpt_time = cnt;
return aw2013_set_repeat_time(cnt);
}
esp_err_t periph_aw2013_set_mode(esp_periph_handle_t periph, periph_aw2013_mode_t mode)
{
if (mode < 0 || mode > AW2013_MODE_AUTO) {
ESP_LOGE(TAG, "Fail to set parameters, mode: %d", mode);
return ESP_FAIL;
}
periph_aw2013_t *aw2013 = esp_periph_get_data(periph);
aw2013->mode = mode;
return _aw2013_set_mode(mode);
}
esp_err_t periph_aw2013_set_time(esp_periph_handle_t periph, aw2013_time_t time, aw2013_time_level_t level)
{
if (time < 0 || time > AW2013_TIME_4 || level < 0 || level > AW2013_TIME_LEVEL_8) {
ESP_LOGE(TAG, "Fail to set parameters, time: %d, level: %d", time, level);
return ESP_FAIL;
}
periph_aw2013_t *aw2013 = esp_periph_get_data(periph);
aw2013->time[time] = level;
return aw2013_set_time(time, level);
}
esp_periph_handle_t periph_aw2013_init(periph_aw2013_cfg_t *aw2013_cfg)
{
esp_periph_handle_t periph = esp_periph_create(PERIPH_ID_AW2013, "periph_aw2013");
AUDIO_NULL_CHECK(TAG, periph, return NULL);
periph_aw2013_t *aw2013 = audio_calloc(1, sizeof(periph_aw2013_t));
AUDIO_MEM_CHECK(TAG, aw2013, {
audio_free(periph);
return NULL;
});
aw2013->mode = aw2013_cfg->mode;
aw2013->bright = aw2013_cfg->bright;
aw2013->rgb_value = aw2013_cfg->rgb_value;
// Default time period
aw2013->time[0] = AW2013_TIME_LEVEL_1;
aw2013->time[1] = AW2013_TIME_LEVEL_3;
aw2013->time[2] = AW2013_TIME_LEVEL_3;
aw2013->time[3] = AW2013_TIME_LEVEL_3;
aw2013->time[4] = AW2013_TIME_LEVEL_2;
// Cycle all the time
aw2013->rpt_time = 0;
esp_periph_set_data(periph, aw2013);
esp_periph_set_function(periph, _aw2013_init, NULL, _aw2013_destroy);
return periph;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/periph_aw2013.c
|
C
|
apache-2.0
| 5,519
|
/*
* 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 "esp_log.h"
#include "button.h"
#include "periph_button.h"
#include "audio_mem.h"
static const char* TAG = "PERIPH_BUTTON";
#define VALIDATE_BTN(periph, ret) if (!(periph && esp_periph_get_id(periph) == PERIPH_ID_BUTTON)) { \
ESP_LOGE(TAG, "Invalid BUTTON periph, at line %d", __LINE__);\
return ret;\
}
typedef struct {
esp_button_handle_t btn;
uint64_t gpio_mask;
int long_press_time_ms;
} periph_button_t;
static void button_send_event(esp_periph_handle_t self, int event_id, uint64_t mask)
{
int gpio_num = 0;
while (mask) {
if (mask & 0x01) {
esp_periph_send_event(self, event_id, (void*)gpio_num, 0);
}
mask >>= 1;
gpio_num ++;
}
}
static esp_err_t _button_run(esp_periph_handle_t self, audio_event_iface_msg_t *msg)
{
button_result_t result;
periph_button_t *periph_btn = esp_periph_get_data(self);
if (button_read(periph_btn->btn, &result)) {
ESP_LOGD(TAG, "Button event, press_mask %llx, release_mask: %llx, long_press_mask: %llx, long_release_mask: %llx",
result.press_mask, result.release_mask, result.long_press_mask, result.long_release_mask);
button_send_event(self, PERIPH_BUTTON_PRESSED, result.press_mask);
button_send_event(self, PERIPH_BUTTON_RELEASE, result.release_mask);
button_send_event(self, PERIPH_BUTTON_LONG_PRESSED, result.long_press_mask);
button_send_event(self, PERIPH_BUTTON_LONG_RELEASE, result.long_release_mask);
}
return ESP_OK;
}
static esp_err_t _button_destroy(esp_periph_handle_t self)
{
periph_button_t *periph_btn = esp_periph_get_data(self);
button_destroy(periph_btn->btn);
audio_free(periph_btn);
return ESP_OK;
}
static void IRAM_ATTR button_intr_handler(void* param)
{
esp_periph_handle_t periph = (esp_periph_handle_t)param;
esp_periph_send_cmd_from_isr(periph, 0, NULL, 0);
}
static void button_timer_handler(xTimerHandle tmr)
{
esp_periph_handle_t periph = (esp_periph_handle_t) pvTimerGetTimerID(tmr);
esp_periph_send_cmd_from_isr(periph, 0, NULL, 0);
}
static esp_err_t _button_init(esp_periph_handle_t self)
{
int ret = 0;
VALIDATE_BTN(self, ESP_FAIL);
periph_button_t *periph_btn = esp_periph_get_data(self);
button_config_t btn_config = {
.gpio_mask = periph_btn->gpio_mask,
.long_press_time_ms = periph_btn->long_press_time_ms,
.button_intr_handler = button_intr_handler,
.intr_context = self,
};
periph_btn->btn = button_init(&btn_config);
esp_periph_start_timer(self, 50/portTICK_RATE_MS, button_timer_handler);
return ret;
}
esp_periph_handle_t periph_button_init(periph_button_cfg_t *config)
{
esp_periph_handle_t periph = esp_periph_create(PERIPH_ID_BUTTON, "periph_btn");
AUDIO_MEM_CHECK(TAG, periph, return NULL);
periph_button_t *periph_btn = audio_calloc(1, sizeof(periph_button_t));
AUDIO_MEM_CHECK(TAG, periph_btn, {
audio_free(periph);
return NULL;
});
periph_btn->gpio_mask = config->gpio_mask;
periph_btn->long_press_time_ms = config->long_press_time_ms;
esp_periph_set_data(periph, periph_btn);
esp_periph_set_function(periph, _button_init, _button_run, _button_destroy);
return periph;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/periph_button.c
|
C
|
apache-2.0
| 4,526
|
/*
* 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 <string.h>
#include "driver/uart.h"
#include "esp_log.h"
#include "esp_console.h"
#include "esp_vfs_dev.h"
#include "sys/queue.h"
#include "argtable3/argtable3.h"
#include "periph_console.h"
#include "audio_mem.h"
#if __has_include("esp_idf_version.h")
#include "esp_idf_version.h"
#else
#define ESP_IDF_VERSION_VAL(major, minor, patch) 1
#endif
#define CONSOLE_MAX_ARGUMENTS (5)
static const char *TAG = "PERIPH_CONSOLE";
static const int STOPPED_BIT = BIT1;
typedef struct periph_console *periph_console_handle_t;
typedef struct periph_console {
char *buffer;
int total_bytes;
bool run;
const periph_console_cmd_t *commands;
int command_num;
EventGroupHandle_t state_event_bits;
int task_stack;
int task_prio;
int buffer_size;
char *prompt_string;
} periph_console_t;
static char *conslole_parse_arguments(char *str, char **saveptr)
{
char *p;
if (str != NULL) {
*saveptr = str;
}
p = *saveptr;
if (!p) {
return NULL;
}
/* Skipping white space.*/
while (*p == ' ' || *p == '\t') {
p++;
}
if (*p == '"') {
/* If an argument starts with a double quote then its delimiter is another quote.*/
p++;
*saveptr = strstr(p, "\"");
} else {
/* The delimiter is white space.*/
*saveptr = strpbrk(p, " \t");
}
/* Replacing the delimiter with a zero.*/
if (*saveptr != NULL) {
*(*saveptr)++ = '\0';
}
return *p != '\0' ? p : NULL;
}
bool console_get_line(periph_console_handle_t console, unsigned max_size, TickType_t time_to_wait)
{
char c;
char tx[3];
int nread = 0;
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
nread = uart_read_bytes(CONFIG_ESP_CONSOLE_UART_NUM, (uint8_t *)&c, 1, time_to_wait);
#else
nread = uart_read_bytes(CONFIG_CONSOLE_UART_NUM, (uint8_t *)&c, 1, time_to_wait);
#endif
if (nread <= 0) {
return false;
}
if ((c == 8) || (c == 127)) { // backspace or del
if (console->total_bytes > 0) {
console->total_bytes --;
tx[0] = c;
tx[1] = 0x20;
tx[2] = c;
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
uart_write_bytes(CONFIG_ESP_CONSOLE_UART_NUM, (const char *)tx, 3);
#else
uart_write_bytes(CONFIG_CONSOLE_UART_NUM, (const char *)tx, 3);
#endif
}
return false;
}
if (c == '\n' || c == '\r') {
tx[0] = '\r';
tx[1] = '\n';
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
uart_write_bytes(CONFIG_ESP_CONSOLE_UART_NUM, (const char *)tx, 2);
#else
uart_write_bytes(CONFIG_CONSOLE_UART_NUM, (const char *)tx, 2);
#endif
console->buffer[console->total_bytes] = 0;
return true;
}
if (c < 0x20) {
return false;
}
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
uart_write_bytes(CONFIG_ESP_CONSOLE_UART_NUM, (const char *)&c, 1);
#else
uart_write_bytes(CONFIG_CONSOLE_UART_NUM, (const char *)&c, 1);
#endif
console->buffer[console->total_bytes++] = (char)c;
if (console->total_bytes > max_size) {
console->total_bytes = 0;
}
return false;
}
static bool console_exec(esp_periph_handle_t self, char *cmd, int argc, char *argv[])
{
periph_console_handle_t console = (periph_console_handle_t)esp_periph_get_data(self);
if (cmd == NULL) {
return false;
}
int i;
for (i = 0; i < console->command_num; i++) {
if (strcasecmp(cmd, console->commands[i].cmd) == 0) {
if (console->commands[i].func) {
console->commands[i].func(self, argc, argv);
return true;
}
int cmd_id = console->commands[i].id;
if (cmd_id == 0) {
cmd_id = i;
}
esp_periph_send_event(self, cmd_id, argv, argc);
return true;
}
}
printf("----------------------\r\n");
printf("Perpheral console HELP\r\n");
printf("----------------------\r\n");
for (i = 0; i < console->command_num; i++) {
printf("%s \t%s\r\n", console->commands[i].cmd, console->commands[i].help);
}
return false;
}
static esp_err_t _console_destroy(esp_periph_handle_t self)
{
periph_console_handle_t console = (periph_console_handle_t)esp_periph_get_data(self);
console->run = false;
xEventGroupWaitBits(console->state_event_bits, STOPPED_BIT, false, true, portMAX_DELAY);
vEventGroupDelete(console->state_event_bits);
if (console->prompt_string) {
audio_free(console->prompt_string);
}
audio_free(console->buffer);
audio_free(console);
return ESP_OK;
}
static void _console_task(void *pv)
{
esp_periph_handle_t self = (esp_periph_handle_t)pv;
char *lp, *cmd, *tokp;
char *args[CONSOLE_MAX_ARGUMENTS + 1];
int n;
periph_console_handle_t console = (periph_console_handle_t)esp_periph_get_data(self);
if (console->total_bytes >= console->buffer_size) {
console->total_bytes = 0;
}
console->run = true;
xEventGroupClearBits(console->state_event_bits, STOPPED_BIT);
const char *prompt_string = CONSOLE_DEFAULT_PROMPT_STRING;
if (console->prompt_string) {
prompt_string = console->prompt_string;
}
printf("\r\n%s ", prompt_string);
while (console->run) {
if (console_get_line(console, console->buffer_size, 10 / portTICK_RATE_MS)) {
if (console->total_bytes) {
ESP_LOGD(TAG, "Read line: %s", console->buffer);
}
lp = conslole_parse_arguments(console->buffer, &tokp);
cmd = lp;
n = 0;
while ((lp = conslole_parse_arguments(NULL, &tokp)) != NULL) {
if (n >= CONSOLE_MAX_ARGUMENTS) {
printf("too many arguments\r\n");
cmd = NULL;
break;
}
args[n++] = lp;
}
args[n] = NULL;
if (console->total_bytes > 0) {
console_exec(self, cmd, n, args);
console->total_bytes = 0;
}
printf("%s ", prompt_string);
}
}
xEventGroupSetBits(console->state_event_bits, STOPPED_BIT);
vTaskDelete(NULL);
}
static esp_err_t _console_init(esp_periph_handle_t self)
{
periph_console_handle_t console = (periph_console_handle_t)esp_periph_get_data(self);
setvbuf(stdin, NULL, _IONBF, 0);
setvbuf(stdout, NULL, _IONBF, 0);
/* Minicom, screen, idf_monitor send CR when ENTER key is pressed */
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 3, 0))
esp_vfs_dev_uart_port_set_rx_line_endings(CONFIG_ESP_CONSOLE_UART_NUM, ESP_LINE_ENDINGS_CR);
#else
esp_vfs_dev_uart_set_rx_line_endings(ESP_LINE_ENDINGS_CR);
#endif
/* Move the caret to the beginning of the next line on '\n' */
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 3, 0))
esp_vfs_dev_uart_port_set_tx_line_endings(CONFIG_ESP_CONSOLE_UART_NUM, ESP_LINE_ENDINGS_CRLF);
#else
esp_vfs_dev_uart_set_tx_line_endings(ESP_LINE_ENDINGS_CRLF);
#endif
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
uart_driver_install(CONFIG_ESP_CONSOLE_UART_NUM, console->buffer_size * 2, 0, 0, NULL, 0);
#else
uart_driver_install(CONFIG_CONSOLE_UART_NUM, console->buffer_size * 2, 0, 0, NULL, 0);
#endif
/* Tell VFS to use UART driver */
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
esp_vfs_dev_uart_use_driver(CONFIG_ESP_CONSOLE_UART_NUM);
#else
esp_vfs_dev_uart_use_driver(CONFIG_CONSOLE_UART_NUM);
#endif
console->buffer = (char *) audio_malloc(console->buffer_size);
AUDIO_MEM_CHECK(TAG, console->buffer, {
return ESP_ERR_NO_MEM;
});
if (xTaskCreate(_console_task, "console_task", console->task_stack, self, console->task_prio, NULL) != pdTRUE) {
ESP_LOGE(TAG, "Error create console task, memory exhausted?");
return ESP_FAIL;
}
return ESP_OK;
}
esp_periph_handle_t periph_console_init(periph_console_cfg_t *config)
{
esp_periph_handle_t periph = esp_periph_create(PERIPH_ID_CONSOLE, "periph_console");
AUDIO_MEM_CHECK(TAG, periph, return NULL);
periph_console_t *console = audio_calloc(1, sizeof(periph_console_t));
AUDIO_MEM_CHECK(TAG, console, {
audio_free(periph);
return NULL;
});
console->commands = config->commands;
console->command_num = config->command_num;
console->task_stack = CONSOLE_DEFAULT_TASK_STACK;
console->task_prio = CONSOLE_DEFAULT_TASK_PRIO;
console->buffer_size = CONSOLE_DEFAULT_BUFFER_SIZE;
if (config->buffer_size > 0) {
console->buffer_size = config->buffer_size;
}
if (config->task_stack > 0) {
console->task_stack = config->task_stack;
}
if (config->task_prio) {
console->task_prio = config->task_prio;
}
if (config->prompt_string) {
console->prompt_string = audio_strdup(config->prompt_string);
AUDIO_MEM_CHECK(TAG, console->prompt_string, {
audio_free(periph);
audio_free(console);
return NULL;
});
}
console->state_event_bits = xEventGroupCreate();
esp_periph_set_data(periph, console);
esp_periph_set_function(periph, _console_init, NULL, _console_destroy);
return periph;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/periph_console.c
|
C
|
apache-2.0
| 10,810
|
/*
* 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 "esp_log.h"
#include "driver/gpio.h"
#include "audio_error.h"
#include "audio_mem.h"
#include "sys/queue.h"
#include "esp_peripherals.h"
#include "periph_gpio_isr.h"
static const char *TAG = "PERIPH_GPIO_ISR";
typedef struct gpio_info_node {
gpio_isr_info_t gpio_info;
STAILQ_ENTRY(gpio_info_node) entries;
} gpio_isr_node_t;
static esp_periph_handle_t g_handle = NULL;
static STAILQ_HEAD(gpio_isr_list, gpio_info_node) gpio_isr_info_list;
static void IRAM_ATTR gpio_isr_handler(void *param)
{
int gpio_num = (int)param;
esp_periph_send_cmd_from_isr(g_handle, gpio_num, NULL, 0);
}
static esp_err_t _gpio_isr_init(esp_periph_handle_t self)
{
esp_err_t ret = ESP_OK;
gpio_isr_node_t *tmp_node = NULL;
gpio_isr_info_t *tmp_info = NULL;
STAILQ_FOREACH(tmp_node, &gpio_isr_info_list, entries) {
tmp_info = &tmp_node->gpio_info;
ret |= gpio_isr_init(tmp_info->gpio_num, tmp_info->type, gpio_isr_handler, (void *)tmp_info->gpio_num);
}
return ret;
}
static esp_err_t _gpio_isr_run(esp_periph_handle_t self, audio_event_iface_msg_t *msg)
{
esp_err_t ret = ESP_OK;
if (msg->cmd >= 0) {
ret = esp_periph_send_event(self, 0, (void *)msg->cmd, 0);
return ret;
}
return ESP_FAIL;
}
static esp_err_t _gpio_isr_destory(esp_periph_handle_t self)
{
esp_err_t ret = ESP_OK;
gpio_isr_node_t *tmp, *item;
gpio_isr_info_t *tmp_info = NULL;
STAILQ_FOREACH_SAFE(item, &gpio_isr_info_list, entries, tmp) {
tmp_info = &item->gpio_info;
ret |= gpio_isr_deinit(tmp_info->gpio_num);
STAILQ_REMOVE(&gpio_isr_info_list, item, gpio_info_node, entries);
audio_free(item);
}
return ret;
}
esp_err_t periph_gpio_isr_add(gpio_isr_info_t *gpio_info)
{
AUDIO_NULL_CHECK(TAG, gpio_info, return ESP_FAIL);
gpio_isr_node_t *tmp_node = NULL;
gpio_isr_info_t *tmp_info = NULL;
STAILQ_FOREACH(tmp_node, &gpio_isr_info_list, entries) {
tmp_info = &tmp_node->gpio_info;
if (tmp_info->gpio_num == gpio_info->gpio_num) {
ESP_LOGW(TAG, "The gpio has already registered isr");
return ESP_FAIL;
}
}
gpio_isr_node_t *gpio_isr_node = (gpio_isr_node_t *)audio_calloc(1, sizeof(gpio_isr_node_t));
AUDIO_NULL_CHECK(TAG, gpio_isr_node, return ESP_FAIL);
memcpy(gpio_isr_node, gpio_info, sizeof(gpio_isr_info_t));
STAILQ_INSERT_TAIL(&gpio_isr_info_list, gpio_isr_node, entries);
return gpio_isr_init(gpio_info->gpio_num, gpio_info->type, gpio_isr_handler, (void *)gpio_info->gpio_num);
}
esp_err_t periph_gpio_isr_delete(int gpio_num)
{
esp_err_t ret = ESP_OK;
if (gpio_num < 0) {
ESP_LOGW(TAG, "The gpio number should be greater than 0");
}
gpio_isr_node_t *tmp_node = NULL;
gpio_isr_info_t *tmp_info = NULL;
STAILQ_FOREACH(tmp_node, &gpio_isr_info_list, entries) {
tmp_info = &tmp_node->gpio_info;
if (tmp_info->gpio_num == gpio_num) {
STAILQ_REMOVE(&gpio_isr_info_list, tmp_node, gpio_info_node, entries);
ret |= gpio_isr_deinit(tmp_info->gpio_num);
audio_free(tmp_node);
return ret;
}
}
ESP_LOGW(TAG, "The gpio %d hasn't been registered", gpio_num);
return ESP_FAIL;
}
esp_periph_handle_t periph_gpio_isr_init(periph_gpio_isr_cfg_t *isr_config)
{
esp_periph_handle_t periph = esp_periph_create(PERIPH_ID_GPIO_ISR, "periph_gpio_isr");
AUDIO_NULL_CHECK(TAG, periph, return NULL);
STAILQ_INIT(&gpio_isr_info_list);
if (isr_config) {
for (int i = 0; i < isr_config->info_size; i++) {
gpio_isr_node_t *gpio_isr_node = (gpio_isr_node_t *)audio_calloc(1, sizeof(gpio_isr_node_t));
AUDIO_NULL_CHECK(TAG, gpio_isr_node, {
audio_free(periph);
return NULL;
});
memcpy(gpio_isr_node, &isr_config->gpio_isr_info[i], sizeof(gpio_isr_info_t));
STAILQ_INSERT_TAIL(&gpio_isr_info_list, gpio_isr_node, entries);
}
}
esp_periph_set_data(periph, &gpio_isr_info_list);
esp_periph_set_function(periph, _gpio_isr_init, _gpio_isr_run, _gpio_isr_destory);
g_handle = periph;
return periph;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/periph_gpio_isr.c
|
C
|
apache-2.0
| 5,493
|
/*
* 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 <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "periph_is31fl3216.h"
#include "IS31FL3216.h"
#include "audio_mem.h"
#include "esp_log.h"
#define IS31FL3216_TASK_STACK_SIZE (2048 + 1024)
#define IS31FL3216_TASK_PRIORITY 3
#define ONE_FRAME_BYTE_SIZE 18
#define DEFAULT_FLASH_STEP 2
static const char *TAG = "PERIPH_IS31";
static const int DESTROY_BIT = BIT0;
#define VALIDATE_IS31FL3216(periph, ret) if (!(periph && esp_periph_get_id(periph) == PERIPH_ID_IS31FL3216)) { \
ESP_LOGE(TAG, "Invalid is31fl3216 periph, at line %d", __LINE__);\
return ret;\
}
static const uint8_t light_audio_frames[8][ONE_FRAME_BYTE_SIZE] = {
{0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff},
{0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xff, 0xff},
{0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xff, 0xff, 0xff},
{0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xff, 0xff, 0xff},
{0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xff, 0xFF, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
};
typedef enum {
PERIPH_IS31_CMD_CHG_STATE,
PERIPH_IS31_CMD_QUIT,
} periph_is31_cmd_t;
typedef struct {
uint16_t max_light_num; // Maximum light number
uint16_t light_num; // Working lights number
uint16_t light_mask; // Light bits mask
int interval_time; // Interval working time
uint16_t act_time; // Action times
uint8_t duty_step; // Duty step
periph_is31_shift_mode_t shift_mode; // Shift mode step
} periph_is31_arg_t;
typedef struct {
periph_is31_arg_t *arg;
uint8_t duty[IS31FL3216_CH_NUM]; // Duty of lights
is31fl3216_handle_t handle;
periph_is31fl3216_state_t cur_state;
QueueHandle_t evt;
EventGroupHandle_t g_event_bit;
} periph_is31fl3216_t;
typedef struct {
periph_is31_cmd_t type;
uint32_t data;
} periph_is31_msg_t;
static esp_err_t is31_leds_ctrl(is31fl3216_handle_t *handle, uint16_t mask)
{
esp_err_t ret = ESP_OK;
for (int i = 0; i < IS31FL3216_CH_NUM; i++) {
if (mask & (1UL << i)) {
ret |= is31fl3216_ch_enable(handle, 1UL << i);
} else {
ret |= is31fl3216_ch_disable(handle, 1UL << i);
}
}
return ret;
}
static esp_err_t is31_leds_duty(is31fl3216_handle_t *handle, int duty, uint16_t mask)
{
esp_err_t ret = ESP_OK;
for (int i = 0; i < IS31FL3216_CH_NUM; i++) {
if (mask & (1UL << i))
ret |= is31fl3216_ch_duty_set(handle, 1UL << i, duty);
}
return ret;
}
static void is31_evt_send(void *que, periph_is31_cmd_t type, uint32_t data, int dir)
{
periph_is31_msg_t evt = {0};
evt.type = type;
evt.data = data;
if (dir) {
xQueueSendToFront(que, &evt, 0) ;
} else {
xQueueSend(que, &evt, 0);
}
}
static esp_err_t is31_change_state(periph_is31fl3216_t *is31, int state, periph_is31_arg_t *arg)
{
esp_err_t ret = ESP_OK;
switch (state) {
case IS31FL3216_STATE_OFF:
ret |= is31fl3216_ch_disable(is31->handle, arg->light_mask);
arg->interval_time = portMAX_DELAY;
is31->cur_state = IS31FL3216_STATE_OFF;
break;
case IS31FL3216_STATE_ON:
if (is31->cur_state == IS31FL3216_STATE_BY_AUDIO) {
ret |= is31fl3216_work_mode_set(is31->handle, IS31FL3216_MODE_PWM);
is31_leds_duty(is31->handle, IS31FL3216_DUTY_MAX, arg->light_mask);
}
is31_leds_ctrl(is31->handle, arg->light_mask);
arg->interval_time = portMAX_DELAY;
is31->cur_state = IS31FL3216_STATE_ON;
break;
case IS31FL3216_STATE_FLASH:
if (is31->cur_state == IS31FL3216_STATE_BY_AUDIO) {
ret |= is31fl3216_work_mode_set(is31->handle, IS31FL3216_MODE_PWM);
}
is31->cur_state = IS31FL3216_STATE_FLASH;
break;
case IS31FL3216_STATE_SHIFT:
if (is31->cur_state == IS31FL3216_STATE_BY_AUDIO) {
ret |= is31fl3216_work_mode_set(is31->handle, IS31FL3216_MODE_PWM);
}
is31->cur_state = IS31FL3216_STATE_SHIFT;
break;
case IS31FL3216_STATE_BY_AUDIO:
is31fl3216_reset(is31->handle);
is31fl3216_work_mode_set(is31->handle, IS31FL3216_MODE_FRAME);
is31fl3216_sample_rate_set(is31->handle, 0xB4); // Set adc sample rate
is31fl3216_frame_value_set(is31->handle, 1, (uint8_t *)&light_audio_frames, sizeof(light_audio_frames));
is31fl3216_first_frame_set(is31->handle, 0);
is31->cur_state = IS31FL3216_STATE_BY_AUDIO;
arg->interval_time = portMAX_DELAY;
break;
default:
ESP_LOGE(TAG, "State %d is not supported", state);
break;
}
return ret;
}
static void is31fl3216_run_task(void *Para)
{
esp_periph_handle_t periph = (esp_periph_handle_t) Para;
periph_is31fl3216_t *is31 = esp_periph_get_data(periph);
periph_is31_arg_t is31_arg = {
.max_light_num = IS31FL3216_CH_NUM,
.light_num = 1,
.light_mask = 1,
.interval_time = 1000,
.act_time = 0,
.duty_step = DEFAULT_FLASH_STEP,
.shift_mode = 0,
};
periph_is31_msg_t msg = {0};
int wait_time_ms = portMAX_DELAY;
bool task_run = true;
xEventGroupClearBits(is31->g_event_bit, DESTROY_BIT);
int cur_duty = 0;
int sig = 2;
int cur_bits_mask = 0;
int i = 0;
uint16_t act_times = 0;
while (task_run) {
if (xQueueReceive(is31->evt, &msg, (wait_time_ms / portTICK_PERIOD_MS))) {
ESP_LOGD(TAG, "cmd:%d, data:%d", msg.type, msg.data);
switch (msg.type) {
case PERIPH_IS31_CMD_CHG_STATE:
memcpy(&is31_arg, is31->arg, sizeof(periph_is31_arg_t));
wait_time_ms = is31->arg->interval_time;
memset(is31->arg, 0, sizeof(periph_is31_arg_t));
is31->arg->interval_time = portMAX_DELAY;
is31->arg->max_light_num = IS31FL3216_CH_NUM;
is31->arg->duty_step = DEFAULT_FLASH_STEP;
is31_change_state(is31, msg.data, &is31_arg);
if (IS31FL3216_STATE_FLASH == msg.data) {
sig = is31_arg.duty_step;
}
if (is31_arg.act_time && wait_time_ms) {
act_times = is31_arg.act_time / wait_time_ms;
} else {
act_times = 0;
}
break;
case PERIPH_IS31_CMD_QUIT:
task_run = false;
if (is31->g_event_bit) {
xEventGroupSetBits(is31->g_event_bit, DESTROY_BIT);
}
break;
default:
break;
}
if (task_run == false) {
ESP_LOGW(TAG, "Quit is31fl3216 task ...");
break;
}
}
switch (is31->cur_state) {
case IS31FL3216_STATE_FLASH: {
is31_leds_duty(is31->handle, cur_duty, is31_arg.light_mask);
is31_leds_ctrl(is31->handle, is31_arg.light_mask);
cur_duty += sig;
if (cur_duty > IS31FL3216_DUTY_MAX) {
cur_duty = IS31FL3216_DUTY_MAX;
sig = -(is31_arg.duty_step);
}
if (cur_duty < 0) {
cur_duty = 0;
sig = (is31_arg.duty_step);
}
}
if (is31_arg.act_time == 0) {
act_times = 0;
break;
}
act_times--;
if (act_times == 0) {
wait_time_ms = portMAX_DELAY;
is31->cur_state = IS31FL3216_STATE_UNKNOWN;
is31_leds_ctrl(is31->handle, 0);
}
break;
case IS31FL3216_STATE_SHIFT:
if (is31_arg.shift_mode == PERIPH_IS31_SHIFT_MODE_SINGLE) {
cur_bits_mask = ((1UL << is31_arg.light_num) - 1) << (i++);
if (i == (is31_arg.max_light_num - is31_arg.light_num + 1)) {
i = 0;
}
} else if (is31_arg.shift_mode == PERIPH_IS31_SHIFT_MODE_ACC) {
cur_bits_mask = (1UL << (is31_arg.light_num * ((i++) + 1))) - 1;
if ((cur_bits_mask >> is31_arg.max_light_num) & 0x01) {
cur_bits_mask = 0;
i = 0;
}
}
is31_leds_duty(is31->handle, IS31FL3216_DUTY_MAX, cur_bits_mask);
is31_leds_ctrl(is31->handle, cur_bits_mask);
ESP_LOGD(TAG, "Mask:%08x, %d", cur_bits_mask, wait_time_ms);
if (is31_arg.act_time == 0) {
act_times = 0;
break;
}
act_times--;
if (act_times == 0) {
wait_time_ms = portMAX_DELAY;
is31->cur_state = IS31FL3216_STATE_UNKNOWN;
is31_leds_ctrl(is31->handle, 0);
}
break;
default:
break;
}
}
vTaskDelete(NULL);
}
esp_err_t periph_is31fl3216_set_state(esp_periph_handle_t periph, periph_is31fl3216_state_t state)
{
periph_is31fl3216_t *is31fl3216 = esp_periph_get_data(periph);
is31_evt_send(is31fl3216->evt, PERIPH_IS31_CMD_CHG_STATE, state, 0);
return ESP_OK;
}
esp_err_t periph_is31fl3216_set_blink_pattern(esp_periph_handle_t periph, uint16_t blink_pattern)
{
periph_is31fl3216_t *is31fl3216 = esp_periph_get_data(periph);
is31fl3216->arg->light_mask = blink_pattern;
return ESP_OK;
}
esp_err_t periph_is31fl3216_set_duty(esp_periph_handle_t periph, uint8_t index, uint8_t value)
{
periph_is31fl3216_t *is31fl3216 = esp_periph_get_data(periph);
is31fl3216->duty[index] = value;
is31fl3216_ch_duty_set(is31fl3216->handle, 1UL << index, is31fl3216->duty[index]);
return ESP_OK;
}
esp_err_t periph_is31fl3216_set_duty_step(esp_periph_handle_t periph, uint8_t step)
{
periph_is31fl3216_t *is31fl3216 = esp_periph_get_data(periph);
is31fl3216->arg->duty_step = step;
return ESP_OK;
}
esp_err_t periph_is31fl3216_set_interval(esp_periph_handle_t periph, uint16_t interval_ms)
{
periph_is31fl3216_t *is31fl3216 = esp_periph_get_data(periph);
is31fl3216->arg->interval_time = interval_ms;
return ESP_OK;
}
esp_err_t periph_is31fl3216_set_shift_mode(esp_periph_handle_t periph, periph_is31_shift_mode_t mode)
{
periph_is31fl3216_t *is31fl3216 = esp_periph_get_data(periph);
is31fl3216->arg->shift_mode = mode;
return ESP_OK;
}
esp_err_t periph_is31fl3216_set_light_on_num(esp_periph_handle_t periph, uint16_t light_on_num, uint16_t max_light_num)
{
periph_is31fl3216_t *is31fl3216 = esp_periph_get_data(periph);
is31fl3216->arg->max_light_num = max_light_num;
is31fl3216->arg->light_num = light_on_num;
return ESP_OK;
}
esp_err_t periph_is31fl3216_set_act_time(esp_periph_handle_t periph, uint16_t act_ms)
{
periph_is31fl3216_t *is31fl3216 = esp_periph_get_data(periph);
is31fl3216->arg->act_time = act_ms;
return ESP_OK;
}
static esp_err_t _is31fl3216_init(esp_periph_handle_t self)
{
periph_is31fl3216_t *is31fl3216 = esp_periph_get_data(self);
esp_err_t ret = ESP_OK;
is31fl3216_ch_disable(is31fl3216->handle, IS31FL3216_CH_ALL);
is31_leds_duty(is31fl3216->handle, 0, IS31FL3216_CH_ALL);
xTaskCreate(is31fl3216_run_task, "is31fl3216_run_task", IS31FL3216_TASK_STACK_SIZE, (void *)self, IS31FL3216_TASK_PRIORITY, NULL);
if (ret) {
ESP_LOGE(TAG, "Failed to initialize is31fl3216");
return ESP_FAIL;
}
return ESP_OK;
}
static esp_err_t _is31fl3216_destroy(esp_periph_handle_t self)
{
VALIDATE_IS31FL3216(self, ESP_FAIL);
periph_is31fl3216_t *is31fl3216 = esp_periph_get_data(self);
is31_evt_send(is31fl3216->evt, PERIPH_IS31_CMD_QUIT, 0, 0);
if (is31fl3216->g_event_bit) {
xEventGroupWaitBits(is31fl3216->g_event_bit, DESTROY_BIT, pdTRUE, pdFALSE, portMAX_DELAY);
vEventGroupDelete(is31fl3216->g_event_bit);
is31fl3216->g_event_bit = NULL;
}
esp_err_t ret = ESP_OK;
ret |= is31fl3216_ch_disable(is31fl3216->handle, IS31FL3216_CH_ALL);
ret |= is31fl3216_deinit(is31fl3216->handle);
audio_free(is31fl3216->arg);
vQueueDelete(is31fl3216->evt);
audio_free(is31fl3216);
if (ret) {
ESP_LOGE(TAG, "Error occurred when stopping the is31fl3216");
return ESP_FAIL;
}
return ESP_OK;
}
esp_periph_handle_t periph_is31fl3216_init(periph_is31fl3216_cfg_t *is31fl3216_config)
{
esp_periph_handle_t periph = esp_periph_create(PERIPH_ID_IS31FL3216, "periph_is31fl3216");
AUDIO_MEM_CHECK(TAG, periph, return NULL);
periph_is31fl3216_t *is31fl3216 = audio_calloc(1, sizeof(periph_is31fl3216_t));
AUDIO_MEM_CHECK(TAG, is31fl3216, {
audio_free(periph);
return NULL;
});
is31fl3216->g_event_bit = xEventGroupCreate();
AUDIO_NULL_CHECK(TAG, is31fl3216->g_event_bit, {
audio_free(periph);
audio_free(is31fl3216);
});
is31fl3216->evt = xQueueCreate(2, sizeof(periph_is31_msg_t));
AUDIO_MEM_CHECK(TAG, is31fl3216->evt, {
audio_free(periph);
vEventGroupDelete(is31fl3216->g_event_bit);
audio_free(is31fl3216);
return NULL;
});
is31fl3216->arg = audio_calloc(1, sizeof(periph_is31_arg_t));
AUDIO_MEM_CHECK(TAG, is31fl3216->arg, {
vQueueDelete(is31fl3216->evt);
vEventGroupDelete(is31fl3216->g_event_bit);
audio_free(periph);
audio_free(is31fl3216);
return NULL;
});
is31fl3216->arg->max_light_num = IS31FL3216_CH_NUM;
is31fl3216->arg->light_num = 0;
is31fl3216->arg->light_mask = 0;
is31fl3216->arg->interval_time = 1000;
is31fl3216->arg->act_time = 0;
is31fl3216->arg->duty_step = DEFAULT_FLASH_STEP;
is31fl3216->arg->shift_mode = PERIPH_IS31_SHIFT_MODE_ACC;
if (is31fl3216_config->duty == NULL) {
ESP_LOGW(TAG, "The duty array is NULL");
} else {
for (int i = 0; i < IS31FL3216_CH_NUM; i++) {
is31fl3216->duty[i] = is31fl3216_config->duty[i];
}
}
is31fl3216->handle = is31fl3216_init();
AUDIO_MEM_CHECK(TAG, is31fl3216, {
audio_free(is31fl3216->arg);
vQueueDelete(is31fl3216->evt);
audio_free(periph);
vEventGroupDelete(is31fl3216->g_event_bit);
audio_free(is31fl3216);
return NULL;
});
esp_periph_set_data(periph, is31fl3216);
esp_periph_set_function(periph, _is31fl3216_init, NULL, _is31fl3216_destroy);
return periph;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/periph_is31fl3216.c
|
C
|
apache-2.0
| 17,171
|
/*
* 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 <string.h>
#include <math.h>
#include "esp_log.h"
#include "audio_mem.h"
#include "audio_sys.h"
#include "periph_led.h"
#include "esp_peripherals.h"
#include "audio_mutex.h"
#define MAX_LED_CHANNEL (8)
static const char *TAG = "PERIPH_LED";
#define VALIDATE_LED(periph, ret) if (!(periph && esp_periph_get_id(periph) == PERIPH_ID_LED)) { \
ESP_LOGE(TAG, "Invalid LED periph, at line %d", __LINE__);\
return ret;\
}
typedef struct {
int index;
int pin;
int high_level_ms;
int low_level_ms;
long long tick;
int loop;
bool is_high_level;
bool fade;
bool stop;
int level;
} periph_led_channel_t;
typedef struct periph_led {
ledc_mode_t led_speed_mode;
ledc_timer_bit_t led_duty_resolution;
ledc_timer_t led_timer_num;
uint32_t led_freq_hz;
QueueHandle_t led_mutex;
periph_led_channel_t channels[MAX_LED_CHANNEL];
} periph_led_t;
static esp_err_t _led_run(esp_periph_handle_t self, audio_event_iface_msg_t *msg)
{
return ESP_OK;
}
static esp_err_t _led_init(esp_periph_handle_t self)
{
VALIDATE_LED(self, ESP_FAIL);
periph_led_t *periph_led = esp_periph_get_data(self);
ledc_timer_config_t ledc_timer = {
.duty_resolution = periph_led->led_duty_resolution, // resolution of PWM duty
.freq_hz = periph_led->led_freq_hz, // frequency of PWM signal
.speed_mode = periph_led->led_speed_mode, // timer mode
.timer_num = periph_led->led_timer_num // timer index
};
// Set configuration of timer0 for high speed channels
ledc_timer_config(&ledc_timer);
ledc_fade_func_install(0);
return ESP_OK;
}
static esp_err_t _led_destroy(esp_periph_handle_t self)
{
periph_led_t *periph_led = esp_periph_get_data(self);
for (int i = 0; i < MAX_LED_CHANNEL; i++) {
periph_led_channel_t *ch = &periph_led->channels[i];
if (ch->index > 0 && ch->pin > 0) {
ledc_stop(periph_led->led_speed_mode, ch->index, ch->level);
}
}
esp_periph_stop_timer(self);
ledc_fade_func_uninstall();
mutex_destroy(periph_led->led_mutex);
audio_free(periph_led);
return ESP_OK;
}
esp_periph_handle_t periph_led_init(periph_led_cfg_t *config)
{
esp_periph_handle_t periph = esp_periph_create(PERIPH_ID_LED, "periph_led");
//check periph
periph_led_t *periph_led = audio_calloc(1, sizeof(periph_led_t));
//check periph_led
periph_led->led_speed_mode = config->led_speed_mode;
periph_led->led_duty_resolution = config->led_duty_resolution;
periph_led->led_timer_num = config->led_timer_num;
periph_led->led_freq_hz = config->led_freq_hz;
periph_led->led_mutex = mutex_create();
if (periph_led->led_freq_hz == 0) {
periph_led->led_freq_hz = 5000;
}
memset(&periph_led->channels, -1, sizeof(periph_led->channels));
esp_periph_set_data(periph, periph_led);
esp_periph_set_function(periph, _led_init, _led_run, _led_destroy);
return periph;
}
static periph_led_channel_t *_find_led_channel(periph_led_t *periph_led, int gpio_num)
{
periph_led_channel_t *ch = NULL;
for (int i = 0; i < MAX_LED_CHANNEL; i++) {
if (periph_led->channels[i].pin == gpio_num) {
ch = &periph_led->channels[i];
ch->index = i;
break;
} else if (periph_led->channels[i].pin == -1) {
ch = &periph_led->channels[i];
ch->index = i;
}
}
return ch;
}
static void led_timer_handler(xTimerHandle tmr)
{
esp_periph_handle_t periph = (esp_periph_handle_t) pvTimerGetTimerID(tmr);
periph_led_t *periph_led = esp_periph_get_data(periph);
mutex_lock(periph_led->led_mutex);
for (int i = 0; i < MAX_LED_CHANNEL; i++) {
periph_led_channel_t *ch = &periph_led->channels[i];
if (ch->pin < 0 || ch->stop == true) {
continue;
}
if (ch->loop == 0) {
ledc_stop(periph_led->led_speed_mode, ch->index, ch->level);
esp_periph_send_event(periph, PERIPH_LED_BLINK_FINISH, (void *)ch->pin, 0);
ch->stop = true;
continue;
}
if (!ch->is_high_level && audio_sys_get_time_ms() - ch->tick > ch->low_level_ms) {
if (ch->loop > 0) {
ch->loop --;
}
// now, switch on
if (ch->fade) {
ledc_set_fade_with_time(periph_led->led_speed_mode, ch->index, pow(2, periph_led->led_duty_resolution) - 1, ch->high_level_ms);
ledc_fade_start(periph_led->led_speed_mode, ch->index, LEDC_FADE_NO_WAIT);
} else {
ledc_set_duty(periph_led->led_speed_mode, ch->index, pow(2, periph_led->led_duty_resolution) - 1);
ledc_update_duty(periph_led->led_speed_mode, ch->index);
}
if (ch->low_level_ms > 0) {
ch->is_high_level = true;
}
ch->tick = audio_sys_get_time_ms();
} else if (ch->is_high_level && audio_sys_get_time_ms() - ch->tick > ch->high_level_ms) {
if (ch->loop > 0) {
ch->loop --;
}
// switch off
if (ch->fade) {
ledc_set_fade_with_time(periph_led->led_speed_mode, ch->index, 0, ch->low_level_ms);
ledc_fade_start(periph_led->led_speed_mode, ch->index, LEDC_FADE_NO_WAIT);
} else {
ledc_set_duty(periph_led->led_speed_mode, ch->index, 0);
ledc_update_duty(periph_led->led_speed_mode, ch->index);
}
if (ch->high_level_ms > 0) {
ch->is_high_level = false;
}
ch->tick = audio_sys_get_time_ms();
}
}
mutex_unlock(periph_led->led_mutex);
}
esp_err_t periph_led_blink(esp_periph_handle_t periph, int gpio_num, int time_on_ms, int time_off_ms, bool fade, int loop, periph_led_idle_level_t level)
{
periph_led_t *periph_led = esp_periph_get_data(periph);
periph_led_channel_t *ch = _find_led_channel(periph_led, gpio_num);
if (ch == NULL) {
return ESP_FAIL;
}
ledc_channel_config_t ledc_channel_cfg = {
.channel = ch->index,
.duty = 0,
.gpio_num = gpio_num,
.speed_mode = periph_led->led_speed_mode,
.timer_sel = periph_led->led_timer_num,
};
ledc_channel_config(&ledc_channel_cfg);
ch->pin = gpio_num;
ch->tick = audio_sys_get_time_ms();
ch->loop = loop;
ch->fade = fade;
if (level == PERIPH_LED_IDLE_LEVEL_LOW) {
ch->is_high_level = false;
ch->high_level_ms = time_on_ms;
ch->low_level_ms = time_off_ms;
} else {
ch->is_high_level = true;
ch->high_level_ms = time_off_ms;
ch->low_level_ms = time_on_ms;
}
ch->stop = false;
ch->level = level;
esp_periph_start_timer(periph, portTICK_RATE_MS, led_timer_handler);
return ESP_OK;
}
esp_err_t periph_led_stop(esp_periph_handle_t periph, int gpio_num)
{
periph_led_t *periph_led = esp_periph_get_data(periph);
periph_led_channel_t *ch = _find_led_channel(periph_led, gpio_num);
if (ch && (ch->pin < 0 || ch->index < 0)) {
return ESP_OK;
}
mutex_lock(periph_led->led_mutex);
ch->stop = true;
ledc_stop(periph_led->led_speed_mode, ch->index, ch->level);
mutex_unlock(periph_led->led_mutex);
return ESP_OK;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/periph_led.c
|
C
|
apache-2.0
| 8,728
|
/*
* 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 "esp_log.h"
#include "driver/sdmmc_host.h"
#include "driver/sdmmc_defs.h"
#include "driver/gpio.h"
#include "sdcard.h"
#include "periph_sdcard.h"
#include "audio_mem.h"
static const char *TAG = "PERIPH_SDCARD";
#define SDCARD_CHECK_TIMEOUT_MS (20)
#define VALIDATE_SDCARD(periph, ret) if (!(periph && esp_periph_get_id(periph) == PERIPH_ID_SDCARD)) { \
ESP_LOGE(TAG, "Invalid SDCARD periph, at line %d", __LINE__);\
return ret;\
}
#define tick_get periph_tick_get
static esp_err_t periph_sdcard_mount(esp_periph_handle_t periph);
static esp_err_t periph_sdcard_unmount(esp_periph_handle_t periph);
typedef struct {
char *root;
int card_detect_pin;
bool is_mounted;
long long last_detect_time;
periph_sdcard_mode_t sd_mode;
} periph_sdcard_t;
static void IRAM_ATTR sdcard_gpio_intr_handler(void *param)
{
esp_periph_handle_t periph = (esp_periph_handle_t)param;
periph_sdcard_t *sdcard = esp_periph_get_data(periph);
if (sdcard_is_exist() && !sdcard->is_mounted) {
esp_periph_send_cmd_from_isr(periph, SDCARD_STATUS_CARD_DETECT_CHANGE, NULL, 0);
} else if (!sdcard_is_exist() && sdcard->is_mounted) {
esp_periph_send_cmd_from_isr(periph, SDCARD_STATUS_CARD_DETECT_CHANGE, NULL, 0);
}
}
static esp_err_t _sdcard_run(esp_periph_handle_t self, audio_event_iface_msg_t *msg)
{
if (msg->cmd != SDCARD_STATUS_CARD_DETECT_CHANGE) {
return ESP_OK;
}
periph_sdcard_t *sdcard = esp_periph_get_data(self);
if (sdcard_is_exist() && !sdcard->is_mounted) {
periph_sdcard_mount(self);
} else if (!sdcard_is_exist() && sdcard->is_mounted) {
periph_sdcard_unmount(self);
}
return ESP_OK;
}
static void sdcard_timer_handler(xTimerHandle tmr)
{
esp_periph_handle_t periph = (esp_periph_handle_t) pvTimerGetTimerID(tmr);
esp_periph_send_cmd(periph, SDCARD_STATUS_CARD_DETECT_CHANGE, NULL, 0);
}
static esp_err_t _sdcard_init(esp_periph_handle_t self)
{
periph_sdcard_t *sdcard = esp_periph_get_data(self);
esp_err_t ret = sdcard_init(sdcard->card_detect_pin, sdcard_gpio_intr_handler, self);
if (sdcard_is_exist()) {
ret |= periph_sdcard_mount(self);
} else {
ESP_LOGE(TAG, "no sdcard detect");
}
esp_periph_start_timer(self, 1000 / portTICK_RATE_MS, sdcard_timer_handler);
return ESP_OK;
}
static esp_err_t _sdcard_destroy(esp_periph_handle_t self)
{
VALIDATE_SDCARD(self, ESP_FAIL);
esp_err_t ret = ESP_OK;
ret |= sdcard_unmount();
ret |= sdcard_destroy();
if (ret != ESP_OK) {
ESP_LOGE(TAG, "stop sdcard error!");
}
periph_sdcard_t *sdcard = esp_periph_get_data(self);
audio_free(sdcard->root);
audio_free(sdcard);
return ret;
}
esp_err_t periph_sdcard_mount(esp_periph_handle_t periph)
{
VALIDATE_SDCARD(periph, ESP_FAIL);
periph_sdcard_t *sdcard = esp_periph_get_data(periph);
int ret = sdcard_mount(sdcard->root, sdcard->sd_mode);
if (ret == ESP_OK) {
ESP_LOGD(TAG, "Mount SDCARD success");
sdcard->is_mounted = true;
return esp_periph_send_event(periph, SDCARD_STATUS_MOUNTED, NULL, 0);
} else if (ret == ESP_ERR_INVALID_STATE) {
ESP_LOGD(TAG, "periph sdcard handle already mounted!");
return ESP_OK;
} else {
esp_periph_send_event(periph, SDCARD_STATUS_MOUNT_ERROR, NULL, 0);
sdcard->is_mounted = false;
ESP_LOGE(TAG, "mount sdcard error!");
return ESP_FAIL;
}
}
esp_err_t periph_sdcard_unmount(esp_periph_handle_t periph)
{
VALIDATE_SDCARD(periph, ESP_FAIL);
periph_sdcard_t *sdcard = esp_periph_get_data(periph);
int ret = sdcard_unmount();
if (ret == ESP_OK) {
ESP_LOGD(TAG, "UnMount SDCARD success");
sdcard->is_mounted = false;
return esp_periph_send_event(periph, SDCARD_STATUS_UNMOUNTED, NULL, 0);
} else {
esp_periph_send_event(periph, SDCARD_STATUS_UNMOUNT_ERROR, NULL, 0);
ESP_LOGE(TAG, "unmount sdcard error!");
sdcard->is_mounted = false;
return ESP_FAIL;
}
return ESP_OK;
}
esp_periph_handle_t periph_sdcard_init(periph_sdcard_cfg_t *sdcard_cfg)
{
esp_periph_handle_t periph = esp_periph_create(PERIPH_ID_SDCARD, "periph_sdcard");
AUDIO_MEM_CHECK(TAG, periph, return NULL);
periph_sdcard_t *sdcard = audio_calloc(1, sizeof(periph_sdcard_t));
AUDIO_MEM_CHECK(TAG, sdcard, {
audio_free(periph);
return NULL;
});
if (sdcard_cfg->root) {
sdcard->root = audio_strdup(sdcard_cfg->root);
} else {
sdcard->root = audio_strdup("/sdcard");
}
AUDIO_MEM_CHECK(TAG, sdcard->root, {
audio_free(sdcard);
audio_free(periph);
return NULL;
});
sdcard->card_detect_pin = sdcard_cfg->card_detect_pin;
sdcard->sd_mode = sdcard_cfg->mode;
esp_periph_set_data(periph, sdcard);
esp_periph_set_function(periph, _sdcard_init, _sdcard_run, _sdcard_destroy);
return periph;
}
bool periph_sdcard_is_mounted(esp_periph_handle_t periph)
{
VALIDATE_SDCARD(periph, ESP_FAIL);
periph_sdcard_t *sdcard = esp_periph_get_data(periph);
return sdcard->is_mounted;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/periph_sdcard.c
|
C
|
apache-2.0
| 6,424
|
/*
* 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 "esp_log.h"
#include "audio_mem.h"
#include "esp_spiffs.h"
#include "periph_spiffs.h"
static const char *TAG = "PERIPH_SPIFFS";
#define VALIDATE_SPIFFS(periph, ret) if (!(periph && esp_periph_get_id(periph) == PERIPH_ID_SPIFFS)) { \
ESP_LOGE(TAG, "Invalid SPIFFS periph, at line %d", __LINE__);\
return ret;\
}
#define SPIFFS_DEFAULT_MAX_FILES 5
static esp_err_t periph_spiffs_mount(esp_periph_handle_t periph);
static esp_err_t periph_spiffs_unmount(esp_periph_handle_t periph);
typedef struct {
char *root;
char *partition_label;
size_t max_files;
bool format_if_mount_failed;
bool is_mounted;
} periph_spiffs_t;
static esp_err_t _spiffs_run(esp_periph_handle_t self, audio_event_iface_msg_t *msg)
{
return ESP_OK;
}
static esp_err_t _spiffs_init(esp_periph_handle_t self)
{
return periph_spiffs_mount(self);;
}
static esp_err_t _spiffs_destroy(esp_periph_handle_t self)
{
VALIDATE_SPIFFS(self, ESP_FAIL);
esp_err_t ret = ESP_OK;
ret |= periph_spiffs_unmount(self);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to unmount SPIFFS");
}
periph_spiffs_t *spiffs = esp_periph_get_data(self);
audio_free(spiffs->root);
if (spiffs->partition_label != NULL) {
audio_free(spiffs->partition_label);
}
audio_free(spiffs);
return ret;
}
esp_err_t periph_spiffs_mount(esp_periph_handle_t periph)
{
VALIDATE_SPIFFS(periph, ESP_FAIL);
periph_spiffs_t *spiffs = esp_periph_get_data(periph);
esp_vfs_spiffs_conf_t conf = {
.base_path = spiffs->root,
.partition_label = spiffs->partition_label,
.max_files = spiffs->max_files,
.format_if_mount_failed = spiffs->format_if_mount_failed
};
// Use settings defined above to initialize and mount SPIFFS filesystem.
// Note: esp_vfs_spiffs_register is an all-in-one convenience function.
esp_err_t ret = esp_vfs_spiffs_register(&conf);
if (ret != ESP_OK) {
if (ret == ESP_FAIL) {
ESP_LOGE(TAG, "Failed to mount or format filesystem");
} else if (ret == ESP_ERR_NOT_FOUND) {
printf("root %s ", spiffs->root);
ESP_LOGE(TAG, "Failed to find SPIFFS partition");
} else {
ESP_LOGE(TAG, "Failed to initialize SPIFFS (%d)", ret);
}
return ESP_FAIL;
}
if (ret == ESP_OK) {
ESP_LOGD(TAG, "Mount SPIFFS success");
spiffs->is_mounted = true;
size_t total = 0, used = 0;
ret = esp_spiffs_info(conf.partition_label, &total, &used);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to get SPIFFS partition information (%d)", ret);
} else {
ESP_LOGI(TAG, "Partition size: total: %d, used: %d", total, used);
}
return esp_periph_send_event(periph, SPIFFS_STATUS_MOUNTED, NULL, 0);
} else if (ret == ESP_ERR_INVALID_STATE) {
ESP_LOGD(TAG, "Periph SPIFFS handle already mounted!");
return ESP_OK;
} else {
esp_periph_send_event(periph, SPIFFS_STATUS_MOUNT_ERROR, NULL, 0);
spiffs->is_mounted = false;
ESP_LOGE(TAG, "Mount SPIFFS error!");
return ESP_FAIL;
}
}
esp_err_t periph_spiffs_unmount(esp_periph_handle_t periph)
{
VALIDATE_SPIFFS(periph, ESP_FAIL);
periph_spiffs_t *spiffs = esp_periph_get_data(periph);
int ret = esp_vfs_spiffs_unregister(spiffs->partition_label);
if (ret == ESP_OK) {
ESP_LOGD(TAG, "Unmount SPIFFS success");
spiffs->is_mounted = false;
return esp_periph_send_event(periph, SPIFFS_STATUS_UNMOUNTED, NULL, 0);
} else {
esp_periph_send_event(periph, SPIFFS_STATUS_UNMOUNT_ERROR, NULL, 0);
ESP_LOGE(TAG, "Unmount SPIFFS error!");
spiffs->is_mounted = false;
return ESP_FAIL;
}
return ESP_OK;
}
esp_periph_handle_t periph_spiffs_init(periph_spiffs_cfg_t *spiffs_cfg)
{
esp_periph_handle_t periph = esp_periph_create(PERIPH_ID_SPIFFS, "periph_spiffs");
AUDIO_MEM_CHECK(TAG, periph, return NULL);
periph_spiffs_t *spiffs = audio_calloc(1, sizeof(periph_spiffs_t));
AUDIO_MEM_CHECK(TAG, spiffs, {
audio_free(periph);
return NULL;
});
if (spiffs_cfg->root) {
spiffs->root = audio_strdup(spiffs_cfg->root);
} else {
spiffs->root = audio_strdup("/spiffs");
}
if (spiffs_cfg->partition_label) {
spiffs->partition_label = audio_strdup(spiffs_cfg->partition_label);
} else {
spiffs->partition_label = NULL;
}
if (spiffs_cfg->max_files < SPIFFS_DEFAULT_MAX_FILES) {
spiffs->max_files = SPIFFS_DEFAULT_MAX_FILES;
} else {
spiffs->max_files = spiffs_cfg->max_files;
}
spiffs->format_if_mount_failed = spiffs_cfg->format_if_mount_failed;
AUDIO_MEM_CHECK(TAG, spiffs->root, {
audio_free(spiffs);
audio_free(periph);
return NULL;
});
esp_periph_set_data(periph, spiffs);
esp_periph_set_function(periph, _spiffs_init, _spiffs_run, _spiffs_destroy);
return periph;
}
bool periph_spiffs_is_mounted(esp_periph_handle_t periph)
{
VALIDATE_SPIFFS(periph, ESP_FAIL);
periph_spiffs_t *spiffs = esp_periph_get_data(periph);
return spiffs->is_mounted;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/periph_spiffs.c
|
C
|
apache-2.0
| 6,492
|
/*
* 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 "esp_log.h"
#include "periph_touch.h"
#include "touch.h"
#include "esp_peripherals.h"
#include "audio_mem.h"
static const char *TAG = "PERIPH_TOUCH";
#define VALIDATE_TOUCH(periph, ret) if (!(periph && esp_periph_get_id(periph) == PERIPH_ID_TOUCH)) { \
ESP_LOGE(TAG, "Invalid TOUCH periph, at line %d", __LINE__);\
return ret;\
}
typedef struct periph_touch {
esp_touch_handle_t touch;
int touch_mask;
int long_tap_time_ms;
int tap_threshold_percent;
touch_result_t result;
} periph_touch_t;
static void touch_send_event(esp_periph_handle_t self, int event_id, int mask)
{
int touch_num = 0;
while (mask) {
if (mask & 0x01) {
esp_periph_send_event(self, event_id, (void *)touch_num, 0);
}
mask >>= 1;
touch_num ++;
}
}
static esp_err_t _touch_run(esp_periph_handle_t self, audio_event_iface_msg_t *msg)
{
periph_touch_t *periph_touch = esp_periph_get_data(self);
touch_send_event(self, PERIPH_TOUCH_TAP, periph_touch->result.tap_mask);
touch_send_event(self, PERIPH_TOUCH_RELEASE, periph_touch->result.release_mask);
touch_send_event(self, PERIPH_TOUCH_LONG_TAP, periph_touch->result.long_tap_mask);
touch_send_event(self, PERIPH_TOUCH_LONG_RELEASE, periph_touch->result.long_release_mask);
return ESP_OK;
}
static void touch_timer_handler(xTimerHandle tmr)
{
esp_periph_handle_t periph = (esp_periph_handle_t) pvTimerGetTimerID(tmr);
periph_touch_t *periph_touch = esp_periph_get_data(periph);
if (esp_touch_read(periph_touch->touch, &periph_touch->result)) {
ESP_LOGD(TAG, "Touch event, tap %x, release_mask: %x, long_tap_mask: %x, long_tap_mask: %x",
periph_touch->result.tap_mask, periph_touch->result.release_mask,
periph_touch->result.long_tap_mask, periph_touch->result.long_release_mask);
esp_periph_send_cmd(periph, 0, NULL, 0);
}
}
static esp_err_t _touch_init(esp_periph_handle_t self)
{
VALIDATE_TOUCH(self, ESP_FAIL);
periph_touch_t *periph_touch = esp_periph_get_data(self);
touch_config_t touch_config = {
.touch_mask = periph_touch->touch_mask,
.long_tap_time_ms = periph_touch->long_tap_time_ms,
.tap_threshold_percent = periph_touch->tap_threshold_percent,
};
periph_touch->touch = esp_touch_init(&touch_config);
esp_periph_start_timer(self, 150 / portTICK_PERIOD_MS, touch_timer_handler);
ESP_LOGW(TAG, "_touch_init");
return ESP_OK;
}
static esp_err_t _touch_destroy(esp_periph_handle_t self)
{
periph_touch_t *periph_touch = esp_periph_get_data(self);
esp_touch_destroy(periph_touch->touch);
audio_free(periph_touch);
return ESP_OK;
}
esp_periph_handle_t periph_touch_init(periph_touch_cfg_t *config)
{
esp_periph_handle_t periph = esp_periph_create(PERIPH_ID_TOUCH, "periph_touch");
AUDIO_MEM_CHECK(TAG, periph, return NULL);
periph_touch_t *periph_touch = audio_calloc(1, sizeof(periph_touch_t));
AUDIO_MEM_CHECK(TAG, periph_touch, {
audio_free(periph);
return NULL;
});
periph_touch->touch_mask = config->touch_mask;
periph_touch->long_tap_time_ms = config->long_tap_time_ms;
periph_touch->tap_threshold_percent = config->tap_threshold_percent;
esp_periph_set_data(periph, periph_touch);
esp_periph_set_function(periph, _touch_init, _touch_run, _touch_destroy);
return periph;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/periph_touch.c
|
C
|
apache-2.0
| 4,667
|
/*
* 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 <string.h>
#include "esp_wpa2.h"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_smartconfig.h"
#include "esp_wifi.h"
#include "esp_peripherals.h"
#include "periph_wifi.h"
#include "wifibleconfig.h"
#include "audio_mem.h"
#if __has_include("esp_idf_version.h")
#include "esp_idf_version.h"
#else
#define ESP_IDF_VERSION_VAL(major, minor, patch) 1
#endif
static const char *TAG = "PERIPH_WIFI";
#define VALIDATE_WIFI(periph, ret) \
if (!(periph && esp_periph_get_id(periph) == PERIPH_ID_WIFI)) { \
ESP_LOGE(TAG, "Invalid WIFI periph, at line %d", __LINE__); \
return ret; \
}
#define DEFAULT_RECONNECT_TIMEOUT_MS (1000)
/* Constants that aren't configurable in menuconfig */
#define EAP_PEAP 1
#define EAP_TTLS 2
typedef struct periph_wifi *periph_wifi_handle_t;
struct periph_wifi {
periph_wifi_state_t wifi_state;
bool disable_auto_reconnect;
bool is_open;
uint8_t max_recon_time;
char *ssid;
char *password;
EventGroupHandle_t state_event;
int reconnect_timeout_ms;
periph_wifi_config_mode_t config_mode;
periph_wpa2_enterprise_cfg_t *wpa2_e_cfg;
};
static const int CONNECTED_BIT = BIT0;
static const int DISCONNECTED_BIT = BIT1;
static const int SMARTCONFIG_DONE_BIT = BIT2;
static const int SMARTCONFIG_ERROR_BIT = BIT3;
static esp_periph_handle_t g_periph = NULL;
esp_err_t periph_wifi_wait_for_connected(esp_periph_handle_t periph, TickType_t tick_to_wait)
{
VALIDATE_WIFI(periph, ESP_FAIL);
periph_wifi_handle_t periph_wifi = (periph_wifi_handle_t)esp_periph_get_data(periph);
EventBits_t connected_bit = xEventGroupWaitBits(periph_wifi->state_event, CONNECTED_BIT, false, true, tick_to_wait);
if (connected_bit & CONNECTED_BIT) {
return ESP_OK;
}
#ifdef CONFIG_BLUEDROID_ENABLED
if (periph_wifi->config_mode == WIFI_CONFIG_BLUEFI) {
ble_config_stop();
}
#endif
return ESP_FAIL;
}
periph_wifi_state_t periph_wifi_is_connected(esp_periph_handle_t periph)
{
VALIDATE_WIFI(periph, false);
periph_wifi_handle_t wifi = (periph_wifi_handle_t)esp_periph_get_data(periph);
return wifi->wifi_state;
}
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
static void _wifi_smartconfig_event_callback(void *arg, esp_event_base_t event_base,
int32_t event_id, void *event_data)
{
wifi_config_t sta_conf;
periph_wifi_handle_t periph_wifi = (periph_wifi_handle_t)esp_periph_get_data(g_periph);
switch (event_id) {
case SC_EVENT_SCAN_DONE:
ESP_LOGD(TAG, "SC_EVENT_SCAN_DONE");
break;
case SC_EVENT_FOUND_CHANNEL:
ESP_LOGD(TAG, "SC_EVENT_FOUND_CHANNEL");
break;
case SC_EVENT_GOT_SSID_PSWD:
ESP_LOGE(TAG, "SC_EVENT_GOT_SSID_PSWD");
smartconfig_event_got_ssid_pswd_t *evt = (smartconfig_event_got_ssid_pswd_t *)event_data;
memset(&sta_conf, 0x00, sizeof(sta_conf));
memcpy(sta_conf.sta.ssid, evt->ssid, sizeof(sta_conf.sta.ssid));
memcpy(sta_conf.sta.password, evt->password, sizeof(sta_conf.sta.password));
sta_conf.sta.bssid_set = evt->bssid_set;
if (sta_conf.sta.bssid_set == true) {
memcpy(sta_conf.sta.bssid, evt->bssid, sizeof(sta_conf.sta.bssid));
}
ESP_LOGE(TAG, "SSID=%s, PASS=%s", sta_conf.sta.ssid, sta_conf.sta.password);
esp_wifi_disconnect();
if (esp_wifi_set_config(WIFI_IF_STA, &sta_conf) != ESP_OK) {
periph_wifi->wifi_state = PERIPH_WIFI_CONFIG_ERROR;
xEventGroupSetBits(periph_wifi->state_event, SMARTCONFIG_ERROR_BIT);
}
if (esp_wifi_connect() != ESP_OK) {
periph_wifi->wifi_state = PERIPH_WIFI_CONFIG_ERROR;
xEventGroupSetBits(periph_wifi->state_event, SMARTCONFIG_ERROR_BIT);
esp_periph_send_event(g_periph, PERIPH_WIFI_CONFIG_ERROR, NULL, 0);
break;
}
break;
case SC_EVENT_SEND_ACK_DONE:
ESP_LOGE(TAG, "SC_EVENT_SEND_ACK_DONE");
periph_wifi->wifi_state = PERIPH_WIFI_CONFIG_DONE;
esp_periph_send_event(g_periph, PERIPH_WIFI_CONFIG_DONE, NULL, 0);
xEventGroupSetBits(periph_wifi->state_event, SMARTCONFIG_DONE_BIT);
esp_smartconfig_stop();
break;
}
}
#else
static void _wifi_smartconfig_event_callback(smartconfig_status_t status, void *pdata)
{
wifi_config_t sta_conf;
smartconfig_type_t *type;
periph_wifi_handle_t periph_wifi = (periph_wifi_handle_t)esp_periph_get_data(g_periph);
switch (status) {
case SC_STATUS_WAIT:
ESP_LOGD(TAG, "SC_STATUS_WAIT");
break;
case SC_STATUS_FIND_CHANNEL:
ESP_LOGD(TAG, "SC_STATUS_FIND_CHANNEL");
break;
case SC_STATUS_GETTING_SSID_PSWD:
type = pdata;
ESP_LOGD(TAG, "SC_STATUS_GETTING_SSID_PSWD, SC_TYPE=%d", (int)*type);
break;
case SC_STATUS_LINK:
ESP_LOGE(TAG, "SC_STATUS_LINK");
memset(&sta_conf, 0x00, sizeof(sta_conf));
memcpy(&sta_conf.sta, pdata, sizeof(wifi_sta_config_t));
ESP_LOGE(TAG, "SSID=%s, PASS=%s", sta_conf.sta.ssid, sta_conf.sta.password);
esp_wifi_disconnect();
if (esp_wifi_set_config(WIFI_IF_STA, &sta_conf) != ESP_OK) {
periph_wifi->wifi_state = PERIPH_WIFI_CONFIG_ERROR;
xEventGroupSetBits(periph_wifi->state_event, SMARTCONFIG_ERROR_BIT);
}
if (esp_wifi_connect() != ESP_OK) {
periph_wifi->wifi_state = PERIPH_WIFI_CONFIG_ERROR;
xEventGroupSetBits(periph_wifi->state_event, SMARTCONFIG_ERROR_BIT);
esp_periph_send_event(g_periph, PERIPH_WIFI_CONFIG_ERROR, NULL, 0);
break;
}
break;
case SC_STATUS_LINK_OVER:
ESP_LOGE(TAG, "SC_STATUS_LINK_OVER");
if (pdata != NULL) {
char phone_ip[4] = { 0 };
memcpy(phone_ip, (const void *)pdata, 4);
ESP_LOGD(TAG, "Phone ip: %d.%d.%d.%d", phone_ip[0], phone_ip[1], phone_ip[2], phone_ip[3]);
periph_wifi->wifi_state = PERIPH_WIFI_CONFIG_DONE;
esp_periph_send_event(g_periph, PERIPH_WIFI_CONFIG_DONE, NULL, 0);
xEventGroupSetBits(periph_wifi->state_event, SMARTCONFIG_DONE_BIT);
} else {
periph_wifi->wifi_state = PERIPH_WIFI_CONFIG_ERROR;
esp_periph_send_event(g_periph, PERIPH_WIFI_CONFIG_ERROR, NULL, 0);
xEventGroupSetBits(periph_wifi->state_event, SMARTCONFIG_ERROR_BIT);
}
esp_smartconfig_stop();
break;
}
}
#endif
esp_err_t periph_wifi_wait_for_disconnected(esp_periph_handle_t periph, TickType_t tick_to_wait)
{
VALIDATE_WIFI(periph, ESP_FAIL);
periph_wifi_handle_t periph_wifi = (periph_wifi_handle_t)esp_periph_get_data(periph);
EventBits_t disconnected_bit = xEventGroupWaitBits(periph_wifi->state_event, DISCONNECTED_BIT, false, true, tick_to_wait);
if (disconnected_bit & DISCONNECTED_BIT) {
return ESP_OK;
}
return ESP_FAIL;
}
esp_err_t periph_wifi_config_start(esp_periph_handle_t periph, periph_wifi_config_mode_t mode)
{
VALIDATE_WIFI(periph, ESP_FAIL);
periph_wifi_handle_t periph_wifi = (periph_wifi_handle_t)esp_periph_get_data(periph);
esp_err_t err = ESP_OK;
periph_wifi->disable_auto_reconnect = true;
periph_wifi->config_mode = mode;
esp_wifi_disconnect();
if (periph_wifi_wait_for_disconnected(periph, portMAX_DELAY) != ESP_OK) {
return ESP_FAIL;
}
periph_wifi->wifi_state = PERIPH_WIFI_SETTING;
if (mode >= WIFI_CONFIG_ESPTOUCH && mode <= WIFI_CONFIG_ESPTOUCH_AIRKISS) {
err = ESP_OK; //0;
// esp_wifi_start();
err |= esp_smartconfig_set_type(mode);
err |= esp_smartconfig_fast_mode(true);
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
smartconfig_start_config_t cfg = SMARTCONFIG_START_CONFIG_DEFAULT();
err |= esp_smartconfig_start(&cfg);
esp_event_handler_register(SC_EVENT, ESP_EVENT_ANY_ID, &_wifi_smartconfig_event_callback, NULL);
#else
err |= esp_smartconfig_start(_wifi_smartconfig_event_callback, 0);
#endif
xEventGroupClearBits(periph_wifi->state_event, SMARTCONFIG_DONE_BIT);
xEventGroupClearBits(periph_wifi->state_event, SMARTCONFIG_ERROR_BIT);
} else if (mode == WIFI_CONFIG_WPS) {
//todo : add wps
return ESP_OK;
} else if (mode == WIFI_CONFIG_BLUEFI) {
#ifdef CONFIG_BLUEDROID_ENABLED
ble_config_start(periph);
#endif
return ESP_OK;
}
return err;
}
esp_err_t periph_wifi_config_wait_done(esp_periph_handle_t periph, TickType_t tick_to_wait)
{
VALIDATE_WIFI(periph, ESP_FAIL);
periph_wifi_handle_t periph_wifi = (periph_wifi_handle_t)esp_periph_get_data(periph);
EventBits_t wificonfig_bit = xEventGroupWaitBits(periph_wifi->state_event,
SMARTCONFIG_DONE_BIT | SMARTCONFIG_ERROR_BIT, false, false, tick_to_wait);
if (wificonfig_bit & SMARTCONFIG_DONE_BIT) {
return ESP_OK;
}
if (wificonfig_bit & SMARTCONFIG_ERROR_BIT) {
return ESP_FAIL;
}
esp_smartconfig_stop();
return ESP_FAIL;
}
static void wifi_reconnect_timer(xTimerHandle tmr)
{
esp_periph_handle_t periph = (esp_periph_handle_t)pvTimerGetTimerID(tmr);
periph_wifi_handle_t periph_wifi = (periph_wifi_handle_t)esp_periph_get_data(periph);
esp_periph_stop_timer(periph);
if (periph_wifi->disable_auto_reconnect != true) {
esp_wifi_connect();
}
}
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
static void _wifi_event_callback(void *arg, esp_event_base_t event_base,
int32_t event_id, void *event_data)
{
esp_periph_handle_t self = (esp_periph_handle_t)arg;
periph_wifi_handle_t periph_wifi = (periph_wifi_handle_t)esp_periph_get_data(self);
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
esp_wifi_connect();
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
ip_event_got_ip_t *event = (ip_event_got_ip_t *) event_data;
ESP_LOGI(TAG, "Got ip:" IPSTR, IP2STR(&event->ip_info.ip));
periph_wifi->wifi_state = PERIPH_WIFI_CONNECTED;
xEventGroupClearBits(periph_wifi->state_event, DISCONNECTED_BIT);
esp_periph_send_event(self, PERIPH_WIFI_CONNECTED, NULL, 0);
xEventGroupSetBits(periph_wifi->state_event, CONNECTED_BIT);
wifi_config_t w_config;
memset(&w_config, 0x00, sizeof(wifi_config_t));
esp_wifi_get_config(WIFI_IF_STA, &w_config);
strcpy(periph_wifi->ssid, (char *)w_config.sta.ssid);
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
periph_wifi->wifi_state = PERIPH_WIFI_DISCONNECTED;
xEventGroupClearBits(periph_wifi->state_event, CONNECTED_BIT);
xEventGroupSetBits(periph_wifi->state_event, DISCONNECTED_BIT);
esp_periph_send_event(self, PERIPH_WIFI_DISCONNECTED, NULL, 0);
ESP_LOGW(TAG, "Wi-Fi disconnected from SSID %s, auto-reconnect %s, reconnect after %d ms",
periph_wifi->ssid,
periph_wifi->disable_auto_reconnect == 0 ? "enabled" : "disabled",
periph_wifi->reconnect_timeout_ms);
if (periph_wifi->disable_auto_reconnect) {
return;
}
esp_periph_start_timer(self, periph_wifi->reconnect_timeout_ms / portTICK_RATE_MS, wifi_reconnect_timer);
} else {
ESP_LOGW(TAG, "WiFi Event cb, Unhandle event_base:%s, event_id:%d", event_base, event_id);
}
}
#else
static esp_err_t _wifi_event_callback(void *ctx, system_event_t *event)
{
esp_periph_handle_t self = (esp_periph_handle_t)ctx;
periph_wifi_handle_t periph_wifi = (periph_wifi_handle_t)esp_periph_get_data(self);
switch (event->event_id) {
case SYSTEM_EVENT_STA_START:
periph_wifi->wifi_state = PERIPH_WIFI_CONNECTING;
esp_wifi_connect();
break;
case SYSTEM_EVENT_STA_CONNECTED:
break;
case SYSTEM_EVENT_STA_GOT_IP:
periph_wifi->wifi_state = PERIPH_WIFI_CONNECTED;
xEventGroupClearBits(periph_wifi->state_event, DISCONNECTED_BIT);
esp_periph_send_event(self, PERIPH_WIFI_CONNECTED, NULL, 0);
xEventGroupSetBits(periph_wifi->state_event, CONNECTED_BIT);
wifi_config_t w_config;
memset(&w_config, 0x00, sizeof(wifi_config_t));
esp_wifi_get_config(WIFI_IF_STA, &w_config);
strcpy(periph_wifi->ssid, (char *)w_config.sta.ssid);
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
periph_wifi->wifi_state = PERIPH_WIFI_DISCONNECTED;
xEventGroupClearBits(periph_wifi->state_event, CONNECTED_BIT);
xEventGroupSetBits(periph_wifi->state_event, DISCONNECTED_BIT);
esp_periph_send_event(self, PERIPH_WIFI_DISCONNECTED, NULL, 0);
ESP_LOGW(TAG, "Wi-Fi disconnected from SSID %s, auto-reconnect %s, reconnect after %d ms",
periph_wifi->ssid,
periph_wifi->disable_auto_reconnect == 0 ? "enabled" : "disabled",
periph_wifi->reconnect_timeout_ms);
if (periph_wifi->disable_auto_reconnect) {
break;
}
esp_periph_start_timer(self, periph_wifi->reconnect_timeout_ms / portTICK_RATE_MS, wifi_reconnect_timer);
break;
default:
break;
}
return ESP_OK;
}
#endif
static esp_err_t _wifi_run(esp_periph_handle_t self, audio_event_iface_msg_t *msg)
{
esp_periph_send_event(self, msg->cmd, NULL, 0);
return ESP_OK;
}
static esp_err_t _wifi_init(esp_periph_handle_t self)
{
periph_wifi_handle_t periph_wifi = (periph_wifi_handle_t)esp_periph_get_data(self);
wifi_config_t wifi_config;
if (periph_wifi->is_open) {
ESP_LOGE(TAG, "Wifi has initialized");
return ESP_FAIL;
}
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
ESP_ERROR_CHECK(esp_event_loop_create_default());
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 1, 0))
esp_netif_create_default_wifi_sta();
#endif
ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &_wifi_event_callback, self));
ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &_wifi_event_callback, self));
#else
#include "esp_event_loop.h"
if (esp_event_loop_get_queue() == NULL) {
ESP_ERROR_CHECK(esp_event_loop_init(_wifi_event_callback, self));
} else {
esp_event_loop_set_cb(_wifi_event_callback, self);
}
#endif
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
memset(&wifi_config, 0x00, sizeof(wifi_config_t));
if (periph_wifi->ssid) {
strcpy((char *)wifi_config.sta.ssid, periph_wifi->ssid);
ESP_LOGD(TAG, "WIFI_SSID=%s", wifi_config.sta.ssid);
if (periph_wifi->password) {
strcpy((char *)wifi_config.sta.password, periph_wifi->password);
ESP_LOGD(TAG, "WIFI_PASS=%s", wifi_config.sta.password);
}
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
}
if (periph_wifi->wpa2_e_cfg->diasble_wpa2_e) {
unsigned int ca_pem_bytes = periph_wifi->wpa2_e_cfg->ca_pem_end - periph_wifi->wpa2_e_cfg->ca_pem_start;
unsigned int client_crt_bytes = periph_wifi->wpa2_e_cfg->wpa2_e_cert_end - periph_wifi->wpa2_e_cfg->wpa2_e_cert_start;
unsigned int client_key_bytes = periph_wifi->wpa2_e_cfg->wpa2_e_key_end - periph_wifi->wpa2_e_cfg->wpa2_e_key_start;
ESP_ERROR_CHECK(esp_wifi_sta_wpa2_ent_set_ca_cert((const unsigned char *)periph_wifi->wpa2_e_cfg->ca_pem_start, ca_pem_bytes));
ESP_ERROR_CHECK(esp_wifi_sta_wpa2_ent_set_cert_key((const unsigned char *)periph_wifi->wpa2_e_cfg->wpa2_e_cert_start, client_crt_bytes, \
(const unsigned char *)periph_wifi->wpa2_e_cfg->wpa2_e_key_start, client_key_bytes, NULL, 0));
ESP_ERROR_CHECK(esp_wifi_sta_wpa2_ent_set_identity((uint8_t *)periph_wifi->wpa2_e_cfg->eap_id, strlen(periph_wifi->wpa2_e_cfg->eap_id)));
if (periph_wifi->wpa2_e_cfg->eap_method == EAP_PEAP || periph_wifi->wpa2_e_cfg->eap_method == EAP_TTLS) {
ESP_ERROR_CHECK(esp_wifi_sta_wpa2_ent_set_username((uint8_t *)periph_wifi->wpa2_e_cfg->eap_username, strlen(periph_wifi->wpa2_e_cfg->eap_username)));
ESP_ERROR_CHECK(esp_wifi_sta_wpa2_ent_set_password((uint8_t *)periph_wifi->wpa2_e_cfg->eap_password, strlen(periph_wifi->wpa2_e_cfg->eap_password)));
}
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
ESP_ERROR_CHECK(esp_wifi_sta_wpa2_ent_enable());
#else
esp_wpa2_config_t wpa2_config = WPA2_CONFIG_INIT_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_sta_wpa2_ent_enable(&wpa2_config));
#endif
}
ESP_ERROR_CHECK(esp_wifi_start());
periph_wifi->is_open = true;
periph_wifi->wifi_state = PERIPH_WIFI_DISCONNECTED;
xEventGroupClearBits(periph_wifi->state_event, CONNECTED_BIT);
xEventGroupSetBits(periph_wifi->state_event, DISCONNECTED_BIT);
return ESP_OK;
}
static esp_err_t _wifi_destroy(esp_periph_handle_t self)
{
periph_wifi_handle_t periph_wifi = (periph_wifi_handle_t)esp_periph_get_data(self);
esp_periph_stop_timer(self);
periph_wifi->disable_auto_reconnect = true;
esp_wifi_disconnect();
periph_wifi_wait_for_disconnected(self, portMAX_DELAY);
esp_wifi_stop();
esp_wifi_deinit();
audio_free(periph_wifi->ssid);
audio_free(periph_wifi->password);
vEventGroupDelete(periph_wifi->state_event);
if (periph_wifi->wpa2_e_cfg != NULL) {
audio_free(periph_wifi->wpa2_e_cfg);
periph_wifi->wpa2_e_cfg = NULL;
}
audio_free(periph_wifi);
g_periph = NULL;
return ESP_OK;
}
esp_periph_handle_t periph_wifi_init(periph_wifi_cfg_t *config)
{
esp_periph_handle_t periph = NULL;
periph_wifi_handle_t periph_wifi = NULL;
bool _success = ((periph = esp_periph_create(PERIPH_ID_WIFI, "periph_wifi"))
&& (periph_wifi = audio_calloc(1, sizeof(struct periph_wifi)))
&& (periph_wifi->state_event = xEventGroupCreate())
&& (config->ssid ? (bool)(periph_wifi->ssid = audio_strdup(config->ssid)) : true)
&& (config->password ? (bool)(periph_wifi->password = audio_strdup(config->password)) : true));
AUDIO_MEM_CHECK(TAG, _success, goto _periph_wifi_init_failed);
periph_wifi->reconnect_timeout_ms = config->reconnect_timeout_ms;
if (periph_wifi->reconnect_timeout_ms == 0) {
periph_wifi->reconnect_timeout_ms = DEFAULT_RECONNECT_TIMEOUT_MS;
}
periph_wifi->disable_auto_reconnect = config->disable_auto_reconnect;
periph_wifi->wpa2_e_cfg = audio_malloc(sizeof(periph_wpa2_enterprise_cfg_t));
AUDIO_NULL_CHECK(TAG, periph_wifi->wpa2_e_cfg, {
audio_free(periph);
goto _periph_wifi_init_failed;
});
memcpy(periph_wifi->wpa2_e_cfg, &config->wpa2_e_cfg, sizeof(periph_wpa2_enterprise_cfg_t));
esp_periph_set_data(periph, periph_wifi);
esp_periph_set_function(periph, _wifi_init, _wifi_run, _wifi_destroy);
g_periph = periph;
return periph;
_periph_wifi_init_failed:
if (periph_wifi) {
vEventGroupDelete(periph_wifi->state_event);
audio_free(periph_wifi->ssid);
audio_free(periph_wifi->password);
audio_free(periph_wifi);
}
return NULL;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/periph_wifi.c
|
C
|
apache-2.0
| 21,290
|
/*
* 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 <driver/rmt.h>
#include "esp_log.h"
#include "audio_mem.h"
#include "audio_sys.h"
#include "periph_ws2812.h"
#include "esp_peripherals.h"
#include "soc/dport_access.h"
#if !defined CONFIG_IDF_TARGET_ESP32C3
#include "soc/dport_reg.h"
#endif
#include "driver/rmt.h"
#include "audio_idf_version.h"
static const char *TAG = "PERIPH_WS2812";
#define DIVIDER 4
#define DURATION 12.5
#define RMTCHANNEL 0
#define MAX_PULSES 32
#define PULSE_T0H ((uint32_t)( 350 / (DURATION*DIVIDER)) & 0x00007FFF )
#define PULSE_T1H ((uint32_t)( 900 / (DURATION*DIVIDER)) & 0x00007FFF )
#define PULSE_T0L ((uint32_t)( 900 / (DURATION*DIVIDER)) & 0x00007FFF )
#define PULSE_T1L ((uint32_t)( 350 / (DURATION*DIVIDER)) & 0x00007FFF )
#define PULSE_TRS ( 50000 / (DURATION*DIVIDER))
#define PULSE_BIT0 (((uint32_t)PULSE_T0L<<16) + (((uint32_t)1)<<15) + (PULSE_T0H))
#define PULSE_BIT1 (((uint32_t)PULSE_T1L<<16) + (((uint32_t)1)<<15) + (PULSE_T1H))
#define FADE_STEP 30
#define INTERVAL_TIME_MS 10
typedef union {
struct __attribute__ ((packed)) {
uint8_t r, g, b;
};
uint32_t num;
} rgb_value;
typedef struct {
periph_rgb_value color;
periph_ws2812_mode_t mode;
uint32_t time_on_ms;
uint32_t time_off_ms;
long long tick;
uint32_t loop;
bool is_on;
bool is_set;
} periph_ws2812_state_t;
typedef struct {
uint32_t pos;
uint32_t half;
uint8_t *buffer;
} periph_ws2812_process_t;
typedef struct periph_ws2812 {
periph_rgb_value *color;
uint32_t led_num;
TimerHandle_t timer;
xSemaphoreHandle sem;
intr_handle_t rmt_intr_handle;
periph_ws2812_state_t *state;
periph_ws2812_process_t process;
} periph_ws2812_t;
static esp_err_t ws2812_init_rmt_channel(int rmt_channel, int gpio_num)
{
rmt_config_t rmt_tx;
rmt_tx.channel = rmt_channel;
rmt_tx.gpio_num = gpio_num;
rmt_tx.mem_block_num = 1;
rmt_tx.clk_div = DIVIDER;
rmt_tx.tx_config.loop_en = false;
rmt_tx.tx_config.carrier_level = 1;
rmt_tx.tx_config.carrier_en = 0;
rmt_tx.tx_config.idle_level = 0;
rmt_tx.tx_config.idle_output_en = true;
rmt_tx.rmt_mode = RMT_MODE_TX;
rmt_config(&rmt_tx);
rmt_driver_install(rmt_tx.channel, 0, 0);
rmt_set_tx_thr_intr_en(RMTCHANNEL, true, MAX_PULSES);
rmt_set_mem_block_num(RMTCHANNEL, 1);
rmt_set_mem_pd(RMTCHANNEL, false);
rmt_set_tx_loop_mode(RMTCHANNEL, false);
rmt_set_source_clk(RMTCHANNEL, RMT_BASECLK_APB);
#if (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(4, 3, 0))
rmt_set_intr_enable_mask(BIT(0) | BIT(24));
#endif
return ESP_OK;
}
static esp_err_t ws2812_data_copy(periph_ws2812_t *ws)
{
unsigned int i, j, len, bit;
len = ws->led_num * 3;;// - ws->process.pos;
rmt_item32_t *rmt_data = malloc(sizeof(rmt_item32_t) * len * 8);
for (i = 0; i < len; i++) {
bit = ws->process.buffer[i];
for (j = 0; j < 8; j++, bit <<= 1) {
if ((bit >> 7) & 0x01) {
rmt_data[j + i * 8].val = PULSE_BIT1;
} else {
rmt_data[j + i * 8].val = PULSE_BIT0;
}
}
if (i + ws->process.pos == ws->led_num * 3 - 1) {
rmt_data[7 + i * 8].duration1 = PULSE_TRS;
}
}
rmt_write_items(RMTCHANNEL, rmt_data, len * 8, portMAX_DELAY);
if (rmt_data) {
free(rmt_data);
rmt_data = NULL;
}
return ESP_OK;
}
static void rmt_handle_tx_end(rmt_channel_t channel, void *arg)
{
portBASE_TYPE taskAwoken = 0;
periph_ws2812_t *ws = (periph_ws2812_t *)(arg);
xSemaphoreGiveFromISR(ws->sem, &taskAwoken);
}
static esp_err_t ws2812_set_colors(periph_ws2812_t *ws)
{
AUDIO_NULL_CHECK(TAG, ws, return ESP_FAIL);
ws->process.buffer = audio_malloc(ws->led_num * 3 * sizeof(uint8_t));
AUDIO_NULL_CHECK(TAG, ws->process.buffer, return ESP_FAIL);
for (int i = 0; i < ws->led_num; i++) {
rgb_value rgb = {
.num = ws->color[i]
};
ws->process.buffer[0 + i * 3] = rgb.g;
ws->process.buffer[1 + i * 3] = rgb.r;
ws->process.buffer[2 + i * 3] = rgb.b;
}
ws->process.pos = 0;
ws->process.half = 0;
ws2812_data_copy(ws);
xSemaphoreTake(ws->sem, portMAX_DELAY);
if (ws->process.buffer) {
audio_free(ws->process.buffer);
ws->process.buffer = NULL;
}
return ESP_OK;
}
static void ws2812_timer_handler(TimerHandle_t tmr)
{
esp_periph_handle_t periph = (esp_periph_handle_t)pvTimerGetTimerID(tmr);
periph_ws2812_t *periph_ws2812 = esp_periph_get_data(periph);
periph_ws2812_state_t *st = periph_ws2812->state;
for ( int i = 0; i < periph_ws2812->led_num; i++ ) {
switch (st[i].mode) {
case PERIPH_WS2812_ONE:
if (st[i].is_on) {
periph_ws2812->color[i] = st[i].color;
ws2812_set_colors(periph_ws2812);
st[i].is_on = false;
st[i].loop = 0;
}
break;
case PERIPH_WS2812_BLINK:
if (st[i].is_set == false) {
continue;
}
if (st[i].loop == 0) {
periph_ws2812->color[i] = LED2812_COLOR_BLACK;
ws2812_set_colors(periph_ws2812);
st[i].is_set = false;
}
if (st[i].is_on && audio_sys_get_time_ms() - st[i].tick > st[i].time_off_ms) {
if (st[i].loop > 0) {
st[i].loop--;
} else {
continue;
}
st[i].is_on = false;
st[i].tick = audio_sys_get_time_ms();
periph_ws2812->color[i] = st[i].color;
ws2812_set_colors(periph_ws2812);
} else if (!st[i].is_on && audio_sys_get_time_ms() - st[i].tick > st[i].time_on_ms) {
st[i].is_on = true;
st[i].tick = audio_sys_get_time_ms();
periph_ws2812->color[i] = LED2812_COLOR_BLACK;
ws2812_set_colors(periph_ws2812);
}
break;
case PERIPH_WS2812_FADE:
if (st[i].is_set == false) {
continue;
}
if (st[i].loop == 0) {
periph_ws2812->color[i] = LED2812_COLOR_BLACK;
ws2812_set_colors(periph_ws2812);
st[i].is_set = false;
continue;
}
if (st[i].is_on && (audio_sys_get_time_ms() - st[i].tick > ((st[i].time_on_ms / FADE_STEP)))) {
st[i].tick = audio_sys_get_time_ms();
rgb_value rgb = {
.num = st[i].color
};
rgb_value rgb1 = {
.num = periph_ws2812->color[i]
};
rgb1.r -= (uint8_t)rgb.r / FADE_STEP;
rgb1.g -= (uint8_t)rgb.g / FADE_STEP;
rgb1.b -= (uint8_t)rgb.b / FADE_STEP;
ws2812_set_colors(periph_ws2812);
periph_ws2812->color[i] = rgb1.num;
if ((rgb1.r <= (uint8_t)rgb.r / FADE_STEP)
&& (rgb1.g <= (uint8_t)rgb.g / FADE_STEP)
&& (rgb1.b <= (uint8_t)rgb.b / FADE_STEP)) {
st[i].is_on = false;
st[i].loop--;
}
} else if ((st[i].is_on == false) && (audio_sys_get_time_ms() - st[i].tick > ((st[i].time_off_ms / FADE_STEP)))) {
st[i].tick = audio_sys_get_time_ms();
rgb_value rgb = {
.num = st[i].color
};
rgb_value rgb1 = {
.num = periph_ws2812->color[i]
};
rgb1.r += (uint8_t)rgb.r / FADE_STEP;
rgb1.g += (uint8_t)rgb.g / FADE_STEP;
rgb1.b += (uint8_t)rgb.b / FADE_STEP;
ws2812_set_colors(periph_ws2812);
periph_ws2812->color[i] = rgb1.num;
if ((((uint8_t)rgb.r - rgb1.r) <= (uint8_t)rgb.r / FADE_STEP)
&& (((uint8_t)rgb.g - rgb1.g) <= (uint8_t)rgb.g / FADE_STEP)
&& (((uint8_t)rgb.b - rgb1.b) <= (uint8_t)rgb.b / FADE_STEP)) {
st[i].is_on = true;
}
}
break;
default:
ESP_LOGW(TAG, "The ws2812 mode[%d] is invalid", st[i].mode);
break;
}
}
}
static esp_err_t _ws2812_run(esp_periph_handle_t periph, audio_event_iface_msg_t *msg)
{
return ESP_OK;
}
static esp_err_t _ws2812_init(esp_periph_handle_t periph)
{
return ESP_OK;
}
static esp_err_t _ws2812_destroy(esp_periph_handle_t periph)
{
periph_ws2812_t *periph_ws2812 = esp_periph_get_data(periph);
AUDIO_NULL_CHECK(TAG, periph_ws2812, return ESP_FAIL);
if (periph_ws2812) {
periph_ws2812_state_t *st = periph_ws2812->state;
for (int i = 0; i < periph_ws2812->led_num; i++) {
st[i].color = LED2812_COLOR_BLACK;
st[i].is_on = true;
st[i].mode = PERIPH_WS2812_ONE;
}
ws2812_set_colors(periph_ws2812);
if (periph_ws2812->color) {
audio_free(periph_ws2812->color);
periph_ws2812->color = NULL;
}
if (periph_ws2812->state) {
audio_free(periph_ws2812->state);
periph_ws2812->state = NULL;
}
esp_periph_stop_timer(periph);
rmt_tx_stop(RMTCHANNEL);
rmt_driver_uninstall(RMTCHANNEL);
vSemaphoreDelete(periph_ws2812->sem);
audio_free(periph_ws2812);
periph_ws2812 = NULL;
}
return ESP_OK;
}
esp_periph_handle_t periph_ws2812_init(periph_ws2812_cfg_t *config)
{
AUDIO_NULL_CHECK(TAG, config, return NULL);
esp_periph_handle_t periph = esp_periph_create(PERIPH_ID_WS2812, "periph_ws2812");
periph_ws2812_t *periph_ws2812 = audio_calloc(1, sizeof(periph_ws2812_t));
AUDIO_NULL_CHECK(TAG, periph_ws2812, goto ws2812_init_err);
periph_ws2812->led_num = config->led_num;
periph_ws2812->timer = NULL;
periph_ws2812->sem = xSemaphoreCreateBinary();
periph_ws2812->rmt_intr_handle = NULL;
periph_ws2812->color = audio_malloc(sizeof(periph_rgb_value) * periph_ws2812->led_num);
AUDIO_NULL_CHECK(TAG, periph_ws2812->color, goto ws2812_init_err);
for (int i = 0; i < periph_ws2812->led_num; i++) {
periph_ws2812->color[i] = LED2812_COLOR_BLACK;
}
periph_ws2812->state = audio_malloc(sizeof(periph_ws2812_state_t) * (periph_ws2812->led_num));
AUDIO_NULL_CHECK(TAG, periph_ws2812->state, goto ws2812_init_err);
ws2812_init_rmt_channel(RMTCHANNEL, (gpio_num_t)config->gpio_num);
esp_periph_set_data(periph, periph_ws2812);
rmt_register_tx_end_callback(rmt_handle_tx_end, (void *)periph_ws2812);
esp_periph_set_function(periph, _ws2812_init, _ws2812_run, _ws2812_destroy);
ws2812_set_colors(periph_ws2812);
ESP_LOGD(TAG, "periph ws2812 init");
return periph;
ws2812_init_err:
if (periph_ws2812->sem) {
vSemaphoreDelete(periph_ws2812->sem);
periph_ws2812->sem = NULL;
}
if (periph_ws2812->color) {
audio_free(periph_ws2812->color);
periph_ws2812->color = NULL;
}
if (periph_ws2812->state) {
audio_free(periph_ws2812->state);
periph_ws2812->state = NULL;
}
if (periph_ws2812) {
audio_free(periph_ws2812);
periph_ws2812 = NULL;
}
if (periph) {
audio_free(periph);
}
periph = NULL;
return periph;
}
esp_err_t periph_ws2812_control(esp_periph_handle_t periph, periph_ws2812_ctrl_cfg_t *control_cfg, void *ctx)
{
periph_ws2812_t *periph_ws2812 = esp_periph_get_data(periph);
AUDIO_NULL_CHECK(TAG, periph_ws2812, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, control_cfg, return ESP_FAIL);
for (int i = 0; i < periph_ws2812->led_num; i++) {
periph_ws2812->state[i].color = control_cfg[i].color;
periph_ws2812->color[i] = control_cfg[i].color;
periph_ws2812->state[i].time_on_ms = control_cfg[i].time_on_ms;
periph_ws2812->state[i].time_off_ms = control_cfg[i].time_off_ms;
periph_ws2812->state[i].tick = audio_sys_get_time_ms();
periph_ws2812->state[i].loop = control_cfg[i].loop;
periph_ws2812->state[i].is_on = true;
periph_ws2812->state[i].is_set = true;
periph_ws2812->state[i].mode = control_cfg[i].mode;
}
esp_periph_start_timer(periph, INTERVAL_TIME_MS / portTICK_RATE_MS, ws2812_timer_handler);
return ESP_OK;
}
esp_err_t periph_ws2812_stop(esp_periph_handle_t periph)
{
periph_ws2812_t *periph_ws2812 = esp_periph_get_data(periph);
AUDIO_NULL_CHECK(TAG, periph_ws2812, return ESP_FAIL);
periph_ws2812_state_t *st = periph_ws2812->state;
for (int i = 0; i < periph_ws2812->led_num; i++) {
st[i].color = LED2812_COLOR_BLACK;
st[i].is_on = true;
st[i].mode = PERIPH_WS2812_ONE;
}
ws2812_set_colors(periph_ws2812);
return ESP_OK;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/periph_ws2812.c
|
C
|
apache-2.0
| 15,122
|
#
#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/esp_peripherals/test/component.mk
|
Makefile
|
apache-2.0
| 112
|
/*
* 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 <string.h>
#include <unistd.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "audio_event_iface.h"
#include "esp_log.h"
#include "esp_err.h"
#include "unity.h"
#include "nvs_flash.h"
#include "tcpip_adapter.h"
#include "audio_mem.h"
#include "esp_peripherals.h"
#include "periph_sdcard.h"
#include "periph_button.h"
#include "periph_touch.h"
#include "periph_wifi.h"
#include "periph_console.h"
#include "periph_led.h"
#include "periph_adc_button.h"
#include "periph_gpio_isr.h"
#include "periph_is31fl3216.h"
#include "periph_spiffs.h"
#include "periph_ws2812.h"
#include "board.h"
static const char *TAG = "ESP_PERIPH_TEST";
#define TEST_PERIPHERALS_MEMORY_LEAK_TIMES 1000
static void periph_adc_button_test(void)
{
ESP_LOGI(TAG, "Set up peripherals handle");
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, "Register ADC button to peripherals");
periph_adc_button_cfg_t adc_btn_cfg = PERIPH_ADC_BUTTON_DEFAULT_CONFIG();
adc_arr_t adc_btn_tag = ADC_DEFAULT_ARR();
adc_btn_tag.total_steps = 6;
int btn_array[7] = {190, 600, 1000, 1375, 1775, 2195, 3100};
adc_btn_tag.adc_level_step = btn_array;
adc_btn_cfg.arr = &adc_btn_tag;
adc_btn_cfg.arr_size = 1;
esp_periph_handle_t adc_btn_handle = periph_adc_button_init(&adc_btn_cfg);
TEST_ASSERT_NOT_NULL(adc_btn_handle);
TEST_ASSERT_FALSE(esp_periph_start(set, adc_btn_handle));
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 peripherals");
TEST_ASSERT_FALSE(audio_event_iface_set_listener(esp_periph_set_get_event_iface(set), evt));
ESP_LOGI(TAG, "Test start, please press buttons on the board ... ");
while (1) {
audio_event_iface_msg_t msg;
TEST_ASSERT_FALSE(audio_event_iface_listen(evt, &msg, portMAX_DELAY));
ESP_LOGI(TAG, "action: %d, act id: %d", msg.cmd, (int)msg.data);
if ((int)msg.data == 0) {
ESP_LOGW(TAG, "press id 0, quit test");
break;
}
}
ESP_LOGI(TAG, "Quit test, release all resources");
TEST_ASSERT_FALSE(esp_periph_set_stop_all(set));
TEST_ASSERT_FALSE(audio_event_iface_remove_listener(esp_periph_set_get_event_iface(set), evt));
TEST_ASSERT_FALSE(audio_event_iface_destroy(evt));
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
}
TEST_CASE("adc button test", "[peripherals]")
{
periph_adc_button_test();
}
static void periph_gpio_button_test(void)
{
ESP_LOGI(TAG, "Set up peripherals handle");
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, "Register gpio button to peripherals");
periph_button_cfg_t btn_cfg = {
.gpio_mask = (1ULL << get_input_rec_id()) | (1ULL << get_input_mode_id()), //REC BTN & MODE BTN
};
esp_periph_handle_t button_handle = periph_button_init(&btn_cfg);
TEST_ASSERT_NOT_NULL(button_handle);
TEST_ASSERT_FALSE(esp_periph_start(set, button_handle));
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 peripherals");
TEST_ASSERT_FALSE(audio_event_iface_set_listener(esp_periph_set_get_event_iface(set), evt));
ESP_LOGI(TAG, "Test start, please press buttons on the board ... ");
while (1) {
audio_event_iface_msg_t msg;
TEST_ASSERT_FALSE(audio_event_iface_listen(evt, &msg, portMAX_DELAY));
ESP_LOGI(TAG, "action: %d, act id: %d", msg.cmd, (int)msg.data);
if ((int)msg.data == get_input_mode_id()) {
ESP_LOGW(TAG, "press [mode] button, quit test");
break;
}
}
ESP_LOGI(TAG, "Quit test, release all resources");
TEST_ASSERT_FALSE(esp_periph_set_stop_all(set));
TEST_ASSERT_FALSE(audio_event_iface_remove_listener(esp_periph_set_get_event_iface(set), evt));
TEST_ASSERT_FALSE(audio_event_iface_destroy(evt));
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
}
TEST_CASE("gpio button test", "[peripherals]")
{
periph_gpio_button_test();
}
static esp_err_t play_func(esp_periph_handle_t periph, int argc, char *argv[])
{
if (argc == 1) {
ESP_LOGI(TAG, "play muisc, url:%s", argv[0]);
} else if (argc == 0) {
ESP_LOGI(TAG, "play");
} else {
ESP_LOGE(TAG, "error input");
}
return ESP_OK;
}
static esp_err_t pause_func(esp_periph_handle_t periph, int argc, char *argv[])
{
if (argc == 0) {
ESP_LOGI(TAG, "pause");
} else {
ESP_LOGE(TAG, "error input");
}
return ESP_OK;
}
static bool task_flag;
static esp_err_t quit_func(esp_periph_handle_t periph, int argc, char *argv[])
{
if (argc == 0) {
ESP_LOGI(TAG, "quit console");
task_flag = false;
} else {
ESP_LOGE(TAG, "error input");
}
return ESP_OK;
}
const periph_console_cmd_t cli_cmd[] = {
{
.cmd = "play",
.id = 0,
.help = "play music",
.func = play_func,
},
{
.cmd = "pause",
.id = 1,
.help = "pause music",
.func = pause_func,
},
{
.cmd = "quit",
.id = 2,
.help = "quit command line",
.func = quit_func
}
};
static void periph_console_test(void)
{
ESP_LOGI(TAG, "Set up peripherals handle");
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, "Register console to peripherals");
periph_console_cfg_t console_cfg = {
.command_num = sizeof(cli_cmd) / sizeof(periph_console_cmd_t),
.commands = cli_cmd,
};
esp_periph_handle_t console_handle = periph_console_init(&console_cfg);
TEST_ASSERT_NOT_NULL(console_handle);
task_flag = true;
ESP_LOGI(TAG, "Start console, please input ...");
TEST_ASSERT_FALSE(esp_periph_start(set, console_handle));
while (task_flag) {
vTaskDelay(10 / portTICK_RATE_MS);
}
ESP_LOGI(TAG, "Quit test, release all resources");
TEST_ASSERT_FALSE(esp_periph_set_stop_all(set));
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
}
TEST_CASE("console test", "[peripherals]")
{
periph_console_test();
}
static void periph_gpio_isr_test(void)
{
ESP_LOGI(TAG, "Set up peripherals handle");
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, "Register gpio isr to peripherals");
gpio_isr_info_t gpio_isr_info = {
.gpio_num = SDCARD_INTR_GPIO,
.type = GPIO_INTR_ANYEDGE
};
periph_gpio_isr_cfg_t gpio_isr_cfg = {
.info_size = 1,
.gpio_isr_info = &gpio_isr_info
};
esp_periph_handle_t gpio_isr_handle = periph_gpio_isr_init(&gpio_isr_cfg);
TEST_ASSERT_NOT_NULL(gpio_isr_handle);
TEST_ASSERT_FALSE(esp_periph_start(set, gpio_isr_handle));
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 peripherals, please insert a sdcard to the board ...");
TEST_ASSERT_FALSE(audio_event_iface_set_listener(esp_periph_set_get_event_iface(set), evt));
while (1) {
audio_event_iface_msg_t msg;
TEST_ASSERT_FALSE(audio_event_iface_listen(evt, &msg, portMAX_DELAY));
if ((int)msg.data == SDCARD_INTR_GPIO) {
ESP_LOGW(TAG, "Detect sdcard insertion, quit test");
break;
}
}
ESP_LOGI(TAG, "Quit test, release all resources");
TEST_ASSERT_FALSE(esp_periph_set_stop_all(set));
TEST_ASSERT_FALSE(audio_event_iface_remove_listener(esp_periph_set_get_event_iface(set), evt));
TEST_ASSERT_FALSE(audio_event_iface_destroy(evt));
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
}
TEST_CASE("gpio isr test", "[peripherals]")
{
periph_gpio_isr_test();
}
static void periph_is31fl3216_test(void)
{
ESP_LOGI(TAG, "Set up peripherals handle");
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_is31fl3216_cfg_t is31fl3216_cfg = {
.state = IS31FL3216_STATE_ON
};
ESP_LOGI(TAG, "Register gpio isr to peripherals");
esp_periph_handle_t is31fl3216_handle = periph_is31fl3216_init(&is31fl3216_cfg);
TEST_ASSERT_FALSE(esp_periph_start(set, is31fl3216_handle));
for (int i = 0; i < BLUE_LED_MAX_NUM; i++) {
TEST_ASSERT_FALSE(periph_is31fl3216_set_duty(is31fl3216_handle, i, 255));
}
TEST_ASSERT_FALSE(periph_is31fl3216_set_light_on_num(is31fl3216_handle, 1, BLUE_LED_MAX_NUM));
TEST_ASSERT_FALSE(periph_is31fl3216_set_interval(is31fl3216_handle, 100));
TEST_ASSERT_FALSE(periph_is31fl3216_set_shift_mode(is31fl3216_handle, PERIPH_IS31_SHIFT_MODE_ACC));
TEST_ASSERT_FALSE(periph_is31fl3216_set_state(is31fl3216_handle, IS31FL3216_STATE_SHIFT));
ESP_LOGI(TAG, "Start testing for 5 seconds...");
vTaskDelay(5000 / portTICK_RATE_MS);
ESP_LOGI(TAG, "Quit test, release all resources");
TEST_ASSERT_FALSE(esp_periph_set_stop_all(set));
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
}
TEST_CASE("is31fl3216 test", "[peripherals]")
{
periph_is31fl3216_test();
}
static void periph_led_test(void)
{
ESP_LOGI(TAG, "Set up peripherals handle");
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_led_cfg_t led_cfg = {
.led_speed_mode = LEDC_LOW_SPEED_MODE,
.led_duty_resolution = LEDC_TIMER_10_BIT,
.led_timer_num = LEDC_TIMER_0,
.led_freq_hz = 5000,
};
esp_periph_handle_t led_handle = periph_led_init(&led_cfg);
TEST_ASSERT_FALSE(esp_periph_start(set, led_handle));
TEST_ASSERT_FALSE(periph_led_blink(led_handle, get_blue_led_gpio(), 1000, 1000, true, -1, 0));
TEST_ASSERT_FALSE(periph_led_blink(led_handle, get_green_led_gpio(), 500, 500, false, 4, 0));
ESP_LOGI(TAG, "running...");
vTaskDelay(1000 / portTICK_RATE_MS);
ESP_LOGI(TAG, "STOP BLUE LED");
TEST_ASSERT_FALSE(periph_led_stop(led_handle, get_blue_led_gpio()));
vTaskDelay(1000 / portTICK_RATE_MS);
ESP_LOGI(TAG, "Changing blink preset...");
TEST_ASSERT_FALSE(periph_led_blink(led_handle, get_blue_led_gpio(), 500, 200, false, -1, 0));
TEST_ASSERT_FALSE(periph_led_blink(led_handle, get_green_led_gpio(), 500, 1000, true, -1, 0));
ESP_LOGI(TAG, "Quit test, release all resources");
TEST_ASSERT_FALSE(esp_periph_set_stop_all(set));
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
}
TEST_CASE("led test", "[peripherals]")
{
periph_led_test();
}
static void periph_sdcard_test(void)
{
ESP_LOGI(TAG, "Set up peripherals handle");
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);
#ifdef CONFIG_ESP_LYRAT_MINI_V1_1_BOARD
gpio_config_t sdcard_pwr_pin_cfg = {
.pin_bit_mask = 1UL << SDCARD_PWR_CTRL,
.mode = GPIO_MODE_OUTPUT,
.pull_up_en = GPIO_PULLUP_DISABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_DISABLE,
};
gpio_config(&sdcard_pwr_pin_cfg);
gpio_set_level(SDCARD_PWR_CTRL, 0);
#endif
periph_sdcard_cfg_t sdcard_cfg = {
.card_detect_pin = get_sdcard_intr_gpio(),
.root = "/sdcard"
};
esp_periph_handle_t sdcard_handle = periph_sdcard_init(&sdcard_cfg);
TEST_ASSERT_NOT_NULL(sdcard_handle);
TEST_ASSERT_FALSE(esp_periph_start(set, sdcard_handle));
while (!periph_sdcard_is_mounted(sdcard_handle)) {
vTaskDelay(500 / portTICK_PERIOD_MS);
}
ESP_LOGI(TAG, "Wirte a string to sdcard");
FILE *fp = fopen("/sdcard/test", "w+");
TEST_ASSERT_NOT_NULL(fp);
char test_str[] = "hello, this is sdcard test";
TEST_ASSERT_EQUAL_INT(strlen(test_str), fwrite(test_str, 1, strlen(test_str), fp));
TEST_ASSERT_FALSE(fsync(fileno(fp)));
TEST_ASSERT_FALSE(fclose(fp));
ESP_LOGI(TAG, "Read a string from sdcard");
fp = fopen("/sdcard/test", "r");
TEST_ASSERT_NOT_NULL(fp);
char *read_str = audio_calloc(1, strlen(test_str) + 1);
TEST_ASSERT_NOT_NULL(read_str);
TEST_ASSERT_EQUAL_INT(strlen(test_str), fread(read_str, 1, strlen(test_str), fp));
ESP_LOGW(TAG, "read string from sdcard file: %s", read_str);
TEST_ASSERT_EQUAL_INT(0, strncmp(read_str, test_str, strlen(test_str)));
ESP_LOGI(TAG, "Quit test, release all resources");
TEST_ASSERT_FALSE(esp_periph_set_stop_all(set));
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
free(read_str);
fclose(fp);
}
TEST_CASE("sdcard test", "[peripherals]")
{
periph_sdcard_test();
}
static void periph_spiffs_test(void)
{
ESP_LOGI(TAG, "Set up peripherals handle");
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",
.max_files = 5,
.format_if_mount_failed = true,
.partition_label = NULL
};
esp_periph_handle_t spiffs_handle = periph_spiffs_init(&spiffs_cfg);
TEST_ASSERT_NOT_NULL(spiffs_handle);
TEST_ASSERT_FALSE(esp_periph_start(set, spiffs_handle));
while (!periph_spiffs_is_mounted(spiffs_handle)) {
vTaskDelay(500 / portTICK_PERIOD_MS);
}
FILE *fp = fopen("/spiffs/test", "w+");
TEST_ASSERT_NOT_NULL(fp);
char test_str[] = "hello, this is spiffs test";
TEST_ASSERT_EQUAL_INT(strlen(test_str), fwrite(test_str, 1, strlen(test_str), fp));
TEST_ASSERT_FALSE(fclose(fp));
ESP_LOGI(TAG, "Read a string from spiffs");
fp = fopen("/spiffs/test", "r");
TEST_ASSERT_NOT_NULL(fp);
char *read_str = audio_calloc(1, strlen(test_str) + 1);
TEST_ASSERT_NOT_NULL(read_str);
TEST_ASSERT_EQUAL_INT(strlen(test_str), fread(read_str, 1, strlen(test_str), fp));
ESP_LOGW(TAG, "read string from spiffs file: %s", read_str);
TEST_ASSERT_EQUAL_INT(0, strncmp(read_str, test_str, strlen(test_str)));
fclose(fp);
ESP_LOGI(TAG, "Quit test, release all resources");
TEST_ASSERT_FALSE(esp_periph_set_stop_all(set));
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
free(read_str);
}
TEST_CASE("spiffs test", "[peripherals]")
{
periph_spiffs_test();
}
static void periph_touch_pad_test(void)
{
ESP_LOGI(TAG, "Set up peripherals handle");
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, "Register touch pad to peripherals");
periph_touch_cfg_t touch_cfg = {
.touch_mask = TOUCH_PAD_SEL4 | TOUCH_PAD_SEL7 | TOUCH_PAD_SEL8 | TOUCH_PAD_SEL9,
.tap_threshold_percent = 70,
};
esp_periph_handle_t touch_handle = periph_touch_init(&touch_cfg);
TEST_ASSERT_NOT_NULL(touch_handle);
TEST_ASSERT_FALSE(esp_periph_start(set, touch_handle));
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 peripherals, please press the touch pad");
TEST_ASSERT_FALSE(audio_event_iface_set_listener(esp_periph_set_get_event_iface(set), evt));
while (1) {
audio_event_iface_msg_t msg;
TEST_ASSERT_FALSE(audio_event_iface_listen(evt, &msg, portMAX_DELAY));
if ((int)msg.data == get_input_set_id()) {
ESP_LOGI(TAG, "[set] touched, quit test");
break;
}
if (msg.cmd == PERIPH_TOUCH_TAP) {
if ((int)msg.data == get_input_play_id()) {
ESP_LOGI(TAG, "[play] touched");
}
if ((int)msg.data == get_input_volup_id()) {
ESP_LOGI(TAG, "[vol+] touched");
}
if ((int)msg.data == get_input_voldown_id()) {
ESP_LOGI(TAG, "[vol-] touched");
}
}
if (msg.cmd == PERIPH_TOUCH_RELEASE) {
if ((int)msg.data == get_input_play_id()) {
ESP_LOGI(TAG, "[play] released");
}
if ((int)msg.data == get_input_volup_id()) {
ESP_LOGI(TAG, "[vol+] released");
}
if ((int)msg.data == get_input_voldown_id()) {
ESP_LOGI(TAG, "[vol-] released");
}
}
}
ESP_LOGI(TAG, "Quit test, release all resources");
TEST_ASSERT_FALSE(esp_periph_set_stop_all(set));
TEST_ASSERT_FALSE(audio_event_iface_remove_listener(esp_periph_set_get_event_iface(set), evt));
TEST_ASSERT_FALSE(audio_event_iface_destroy(evt));
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
}
static void periph_ws2812_test(void)
{
ESP_LOGI(TAG, "Set up peripherals handle");
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_ws2812_cfg_t cfg = {
.gpio_num = GPIO_NUM_3,
.led_num = 2,
};
esp_periph_handle_t handle = periph_ws2812_init(&cfg);
TEST_ASSERT_FALSE(esp_periph_start(set, handle));
periph_ws2812_ctrl_cfg_t *control_cfg = malloc(sizeof(periph_ws2812_ctrl_cfg_t) * cfg.led_num);
control_cfg[0].color = LED2812_COLOR_RED;
control_cfg[0].mode = PERIPH_WS2812_BLINK;
control_cfg[0].loop = 50;
control_cfg[0].time_off_ms = 100;
control_cfg[0].time_on_ms = 1000;
control_cfg[1].color = LED2812_COLOR_BLUE;
control_cfg[1].mode = PERIPH_WS2812_ONE;
control_cfg[1].loop = 50;
control_cfg[1].time_off_ms = 2000;
control_cfg[1].time_on_ms = 2000;
TEST_ASSERT_FALSE(periph_ws2812_control(handle, control_cfg, NULL));
vTaskDelay(5000 / portTICK_PERIOD_MS);
ESP_LOGI(TAG, "Quit test, release all resources");
TEST_ASSERT_FALSE(esp_periph_set_stop_all(set));
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
free(control_cfg);
}
TEST_CASE("touch pad test", "[peripherals]")
{
periph_touch_pad_test();
}
static void periph_wifi_test(void)
{
ESP_LOGI(TAG, "Set up peripherals handle");
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 wifi environment");
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK( nvs_flash_erase() );
ret = nvs_flash_init();
}
ESP_ERROR_CHECK( ret );
tcpip_adapter_init();
periph_wifi_cfg_t wifi_cfg = {0};
wifi_cfg.ssid = "ESP-Audio";
wifi_cfg.password = "esp123456";
esp_periph_handle_t wifi_handle = periph_wifi_init(&wifi_cfg);
esp_periph_start(set, wifi_handle);
periph_wifi_wait_for_connected(wifi_handle, portMAX_DELAY);
vTaskDelay(100 / portTICK_PERIOD_MS);
ESP_LOGI(TAG, "Quit test, release all resources");
TEST_ASSERT_FALSE(esp_periph_set_stop_all(set));
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
TEST_ASSERT_FALSE(nvs_flash_deinit());
}
TEST_CASE("wifi test", "[peripherals]")
{
periph_wifi_test();
}
TEST_CASE("[memory leak test] [gpio isr]", "[peripherals]")
{
int test_count = TEST_PERIPHERALS_MEMORY_LEAK_TIMES;
while (test_count--) {
printf("-------Residual times: %d -------\n", test_count);
periph_gpio_isr_test();
}
}
TEST_CASE("[memory leak test] [adc button]", "[peripherals]")
{
int test_count = TEST_PERIPHERALS_MEMORY_LEAK_TIMES;
while (test_count--) {
printf("-------Residual times: %d -------\n", test_count);
periph_adc_button_test();
}
}
TEST_CASE("[memory leak test] [console]", "[peripherals]")
{
int test_count = TEST_PERIPHERALS_MEMORY_LEAK_TIMES;
while (test_count--) {
printf("-------Residual times: %d -------\n", test_count);
periph_console_test();
}
}
TEST_CASE("[memory leak test] [led]", "[peripherals]")
{
int test_count = TEST_PERIPHERALS_MEMORY_LEAK_TIMES;
while (test_count--) {
printf("-------Residual times: %d -------\n", test_count);
periph_led_test();
}
}
TEST_CASE("[memory leak test] [spiffs]", "[peripherals]")
{
int test_count = TEST_PERIPHERALS_MEMORY_LEAK_TIMES;
while (test_count--) {
printf("-------Residual times: %d -------\n", test_count);
periph_spiffs_test();
}
}
TEST_CASE("[memory leak test] [wifi]", "[peripherals]")
{
int test_count = TEST_PERIPHERALS_MEMORY_LEAK_TIMES;
while (test_count--) {
printf("-------Residual times: %d -------\n", test_count);
periph_wifi_test();
}
}
TEST_CASE("[memory leak test] [gpio button]", "[peripherals]")
{
int test_count = TEST_PERIPHERALS_MEMORY_LEAK_TIMES;
while (test_count--) {
printf("-------Residual times: %d -------\n", test_count);
periph_gpio_button_test();
}
}
TEST_CASE("[memory leak test] [is31fl3216]", "[peripherals]")
{
int test_count = TEST_PERIPHERALS_MEMORY_LEAK_TIMES;
while (test_count--) {
printf("-------Residual times: %d -------\n", test_count);
periph_is31fl3216_test();
}
}
TEST_CASE("[memory leak test] [sdcard]", "[peripherals]")
{
int test_count = TEST_PERIPHERALS_MEMORY_LEAK_TIMES;
while (test_count--) {
printf("-------Residual times: %d -------\n", test_count);
periph_sdcard_test();
}
}
TEST_CASE("[memory leak test] [touch]", "[peripherals]")
{
int test_count = TEST_PERIPHERALS_MEMORY_LEAK_TIMES;
while (test_count--) {
printf("-------Residual times: %d -------\n", test_count);
periph_touch_pad_test();
}
}
TEST_CASE("[memory leak test] [ws2812]", "[peripherals]")
{
int test_count = TEST_PERIPHERALS_MEMORY_LEAK_TIMES;
while (test_count--) {
printf("-------Residual times: %d -------\n", test_count);
periph_ws2812_test();
}
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/esp_peripherals/test/esp_peripherals_test.c
|
C
|
apache-2.0
| 24,244
|
set(COMPONENT_ADD_INCLUDEDIRS ./include)
# Edit following two lines to set component requirements (see docs)
set(COMPONENT_REQUIRES )
set(COMPONENT_PRIV_REQUIRES audio_sal esp_peripherals )
set(COMPONENT_SRCS ./input_key_service.c)
register_component()
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/input_key_service/CMakeLists.txt
|
CMake
|
apache-2.0
| 256
|
#
# Main Makefile. This is basically the same as a component makefile.
COMPONENT_ADD_INCLUDEDIRS := ./include
COMPONENT_SRCDIRS := .
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/input_key_service/component.mk
|
Makefile
|
apache-2.0
| 133
|
/*
* 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 _INPUT_KEY_COM_USER_ID_H_
#define _INPUT_KEY_COM_USER_ID_H_
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief input key user user-defined id
*/
typedef enum {
INPUT_KEY_USER_ID_UNKNOWN = -1, /*!< unknown user id */
INPUT_KEY_USER_ID_REC = 0x01, /*!< user id for recording */
INPUT_KEY_USER_ID_SET = 0x02, /*!< user id for settings */
INPUT_KEY_USER_ID_PLAY = 0x03, /*!< user id for playing */
INPUT_KEY_USER_ID_MODE = 0x04, /*!< user id for mode */
INPUT_KEY_USER_ID_VOLDOWN = 0x05, /*!< user id for volume down */
INPUT_KEY_USER_ID_VOLUP = 0x06, /*!< user id for volume up */
INPUT_KEY_USER_ID_MUTE = 0x07, /*!< user id for mute */
INPUT_KEY_USER_ID_CAPTURE = 0x08, /*!< user id for capture photo */
INPUT_KEY_USER_ID_MSG = 0x09, /*!< user id for message */
INPUT_KEY_USER_ID_BATTERY_CHARGING = 0x0A, /*!< user id for battery charging */
INPUT_KEY_USER_ID_WAKEUP = 0x0B, /*!< user id for GPIO wakeup */
INPUT_KEY_USER_ID_MAX = 0x101,
} input_KEY_user_id_t;
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/input_key_service/include/input_key_com_user_id.h
|
C
|
apache-2.0
| 2,552
|
/*
* 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 _INPUT_KEY_SERVICE_H_
#define _INPUT_KEY_SERVICE_H_
#include "esp_peripherals.h"
#include "periph_service.h"
#include "input_key_com_user_id.h"
#include "board.h"
#ifdef __cplusplus
extern "C" {
#endif
#define INPUT_KEY_SERVICE_TASK_STACK_SIZE (3 * 1024)
#define INPUT_KEY_SERVICE_TASK_PRIORITY (5)
#define INPUT_KEY_SERVICE_TASK_ON_CORE (1)
/**
* @brief input key action id
*/
typedef enum {
INPUT_KEY_SERVICE_ACTION_UNKNOWN = 0, /*!< unknown action id */
INPUT_KEY_SERVICE_ACTION_CLICK, /*!< click action id */
INPUT_KEY_SERVICE_ACTION_CLICK_RELEASE, /*!< click release action id */
INPUT_KEY_SERVICE_ACTION_PRESS, /*!< long press action id */
INPUT_KEY_SERVICE_ACTION_PRESS_RELEASE /*!< long press release id */
} input_key_service_action_id_t;
/**
* @brief input key's infomation
*/
typedef struct {
esp_periph_id_t type; /*!< ID of peripherals */
int user_id; /*!< The key's user id */
int act_id; /*!< The key's action id */
} input_key_service_info_t;
/**
* @brief input key's configuration
*/
typedef struct {
periph_service_config_t based_cfg; /*!< Peripheral service configuration */
esp_periph_set_handle_t handle; /*!< Peripheral set handle */
} input_key_service_cfg_t;
#define INPUT_KEY_SERVICE_DEFAULT_CONFIG() { \
.based_cfg = { \
.task_stack = INPUT_KEY_SERVICE_TASK_STACK_SIZE, \
.task_prio = INPUT_KEY_SERVICE_TASK_PRIORITY, \
.task_core = INPUT_KEY_SERVICE_TASK_ON_CORE, \
.extern_stack = false \
} \
}
/**
* @brief Initialize and start the input key service
*
* @param input_key_config Configuration of input key service
*
* @return NULL failed
* others input key service handle
*/
periph_service_handle_t input_key_service_create(input_key_service_cfg_t *input_key_config);
/**
* @brief Get the state of input key service
*
* @param input_handle The handle of input key service
*
* @return state of input key service
*/
periph_service_state_t get_input_key_service_state(periph_service_handle_t input_handle);
/**
* @brief Add input key's information to service list
*
* @param input_key_handle handle of service
* @param input_key_info input key's information
* @param add_key_num number of keys
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t input_key_service_add_key(periph_service_handle_t input_key_handle, input_key_service_info_t *input_key_info, int add_key_num);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/input_key_service/include/input_key_service.h
|
C
|
apache-2.0
| 3,963
|
/*
* 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 "esp_log.h"
#include "audio_error.h"
#include "audio_mem.h"
#include "sys/queue.h"
#include "esp_peripherals.h"
#include "input_key_service.h"
#include "audio_event_iface.h"
static const char *TAG = "INPUT_KEY_SERVICE";
typedef struct input_key {
input_key_service_info_t input_key_info;
STAILQ_ENTRY(input_key) entries;
} input_key_node_t;
typedef struct {
periph_service_state_t ser_state;
esp_periph_set_handle_t periph_set_handle;
STAILQ_HEAD(key_list, input_key) input_info_list;
} input_key_service_t;
static esp_err_t input_key_service_event_send(periph_service_handle_t input_key_handle, periph_service_state_t state)
{
AUDIO_NULL_CHECK(TAG, input_key_handle, return ESP_ERR_INVALID_ARG);
input_key_service_t *input_key_ser = (input_key_service_t *)periph_service_get_data(input_key_handle);
QueueHandle_t input_ser_queue = esp_periph_set_get_queue(input_key_ser->periph_set_handle);
audio_event_iface_msg_t msg = {0};
msg.source = (void *)input_key_handle;
msg.cmd = state;
if (xQueueSend(input_ser_queue, &msg, portMAX_DELAY) != pdTRUE) {
ESP_LOGW(TAG, "input key service event send failed");
return ESP_FAIL;
}
return ESP_OK;
}
static esp_err_t input_key_service_event_receive(periph_service_handle_t handle, void *msg, TickType_t ticks)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_ERR_INVALID_ARG);
input_key_service_t *input_key_ser = periph_service_get_data(handle);
QueueHandle_t input_ser_queue = esp_periph_set_get_queue(input_key_ser->periph_set_handle);
if (xQueueReceive(input_ser_queue, msg, ticks) != pdTRUE) {
return ESP_FAIL;
}
return ESP_OK;
}
static int get_input_key_user_id(input_key_service_t *input_key_ser, int source_type, int act_id)
{
AUDIO_NULL_CHECK(TAG, input_key_ser, return INPUT_KEY_USER_ID_UNKNOWN);
input_key_service_info_t *key_info = NULL;
input_key_node_t *tmp_node = NULL;
STAILQ_FOREACH(tmp_node, &input_key_ser->input_info_list, entries) {
key_info = &(tmp_node->input_key_info);
if (key_info->type == source_type && key_info->act_id == act_id) {
return key_info->user_id;
}
}
return INPUT_KEY_USER_ID_UNKNOWN;
}
static void input_key_service_task(void *parameters)
{
periph_service_handle_t input_key_handle = (periph_service_handle_t)parameters;
periph_service_event_t ser_evt = {0};
input_key_service_t *input_key_ser = periph_service_get_data(input_key_handle);
input_key_ser->ser_state = PERIPH_SERVICE_STATE_RUNNING;
audio_event_iface_msg_t msg = {0};
while (1) {
if (input_key_service_event_receive(input_key_handle, &msg, portMAX_DELAY) == ESP_OK) {
ser_evt.data = (void *)get_input_key_user_id(input_key_ser, msg.source_type, (int)msg.data);
if ((int)ser_evt.data >= 0) {
ser_evt.type = msg.cmd; // action
ser_evt.source = (void *)msg.source_type;
ser_evt.len = (int)msg.data;
periph_service_callback(input_key_handle, &ser_evt);
}
}
if (msg.source == input_key_handle && msg.cmd == PERIPH_SERVICE_STATE_STOPPED) {
ESP_LOGW(TAG, "The input key service will be destroyed");
break;
}
}
input_key_node_t *item, *tmp;
STAILQ_FOREACH_SAFE(item, &input_key_ser->input_info_list, entries, tmp) {
STAILQ_REMOVE(&input_key_ser->input_info_list, item, input_key, entries);
audio_free(item);
}
audio_free(input_key_ser);
vTaskDelete(NULL);
}
static esp_err_t input_key_service_start(periph_service_handle_t input_key_handle)
{
return ESP_OK;
}
static esp_err_t input_key_service_stop(periph_service_handle_t input_key_handle)
{
return ESP_OK;
}
static esp_err_t input_key_service_destroy(periph_service_handle_t input_key_handle)
{
AUDIO_NULL_CHECK(TAG, input_key_handle, return ESP_ERR_INVALID_ARG);
input_key_service_event_send(input_key_handle, PERIPH_SERVICE_STATE_STOPPED);
return ESP_OK;
}
periph_service_state_t get_input_key_service_state(periph_service_handle_t input_key_handle)
{
AUDIO_NULL_CHECK(TAG, input_key_handle, return PERIPH_SERVICE_STATE_UNKNOWN);
input_key_service_t *input_key_ser = (input_key_service_t *)periph_service_get_data(input_key_handle);
return input_key_ser->ser_state;
}
esp_err_t input_key_service_add_key(periph_service_handle_t input_key_handle, input_key_service_info_t *input_key_info, int add_key_num)
{
AUDIO_NULL_CHECK(TAG, input_key_handle, return ESP_ERR_INVALID_ARG);
AUDIO_NULL_CHECK(TAG, input_key_info, return ESP_ERR_INVALID_ARG);
if (add_key_num <= 0) {
return ESP_FAIL;
}
input_key_service_t *input_key_ser = periph_service_get_data(input_key_handle);
AUDIO_NULL_CHECK(TAG, input_key_ser, return ESP_FAIL);
for (int i = 0; i < add_key_num; i++) {
input_key_node_t *input_key_node = (input_key_node_t *)audio_calloc(1, sizeof(input_key_node_t));
AUDIO_NULL_CHECK(TAG, input_key_node, return ESP_FAIL);
memcpy(&input_key_node->input_key_info, &input_key_info[i], sizeof(input_key_service_info_t));
STAILQ_INSERT_TAIL(&input_key_ser->input_info_list, input_key_node, entries);
}
return ESP_OK;
}
periph_service_handle_t input_key_service_create(input_key_service_cfg_t *input_key_config)
{
AUDIO_NULL_CHECK(TAG, input_key_config, return NULL);
periph_service_config_t *input_cfg = &input_key_config->based_cfg;
periph_service_config_t service_cfg = {
.task_stack = input_cfg->task_stack,
.task_prio = input_cfg->task_prio,
.task_core = input_cfg->task_core,
.extern_stack = input_cfg->extern_stack,
.task_func = input_key_service_task,
.service_start = input_key_service_start,
.service_stop = input_key_service_stop,
.service_destroy = input_key_service_destroy,
.service_ioctl = NULL,
.service_name = "input_key_service",
};
input_key_service_t *input_key_ser = NULL;
periph_service_handle_t input_key_handle = NULL;
input_key_ser = (input_key_service_t *)audio_calloc(1, sizeof(input_key_service_t));
AUDIO_NULL_CHECK(TAG, input_key_ser, goto _create_service_failed);
if (input_key_config->handle) {
input_key_ser->periph_set_handle = input_key_config->handle;
} else {
ESP_LOGE(TAG, "peripherals set handle is NULL");
free(input_key_ser);
return NULL;
}
input_key_ser->ser_state = PERIPH_SERVICE_STATE_UNKNOWN;
STAILQ_INIT(&input_key_ser->input_info_list);
service_cfg.user_data = (void *)input_key_ser;
input_key_handle = periph_service_create(&service_cfg);
AUDIO_NULL_CHECK(TAG, input_key_handle, goto _create_service_failed);
return input_key_handle;
_create_service_failed:
if (input_key_handle) {
audio_free(input_key_handle);
input_key_handle = NULL;
}
if (input_key_ser) {
audio_free(input_key_ser);
input_key_ser = NULL;
}
return NULL;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/input_key_service/input_key_service.c
|
C
|
apache-2.0
| 8,411
|
COMPONENT_ADD_LDFLAGS = -Wl,--whole-archive -l$(COMPONENT_NAME) -Wl,--no-whole-archive
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/input_key_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 "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "input_key_service.h"
#include "esp_peripherals.h"
#include "periph_service.h"
#include "periph_button.h"
#include "periph_touch.h"
#include "periph_adc_button.h"
#include "board.h"
#include "unity.h"
static const char *TAG = "TEST_INPUT_KEY_SERVICE";
static esp_periph_set_handle_t set = NULL;
static esp_err_t test_input_key_service_callback(periph_service_handle_t handle, periph_service_event_t *evt, void *ctx)
{
TEST_ASSERT_NOT_NULL(handle);
TEST_ASSERT_NOT_NULL(evt);
// ESP_LOGI(TAG, "type=>%d, source=>%d, data=>%d, len=>%d", evt->type, (int)evt->source, (int)evt->data, evt->len);
if (evt->type == INPUT_KEY_SERVICE_ACTION_CLICK_RELEASE) {
switch ((int) evt->data) {
case INPUT_KEY_USER_ID_PLAY:
ESP_LOGI(TAG, "[Play] button press");
break;
case INPUT_KEY_USER_ID_SET:
ESP_LOGI(TAG, "[Set] button press");
break;
case INPUT_KEY_USER_ID_VOLUP:
ESP_LOGI(TAG, "[VOL+] button press");
break;
case INPUT_KEY_USER_ID_VOLDOWN:
ESP_LOGI(TAG, "[VOL-] button press");
break;
case INPUT_KEY_USER_ID_MODE:
ESP_LOGI(TAG, "[Mode] button press");
break;
case INPUT_KEY_USER_ID_REC:
ESP_LOGI(TAG, "[Rec] button press");
break;
default:
ESP_LOGI(TAG, "[Userdefined] button press");
break;
}
}
return ESP_OK;
}
static periph_service_handle_t test_input_key_service_create()
{
esp_periph_config_t periph_cfg = DEFAULT_ESP_PERIPH_SET_CONFIG();
set = esp_periph_set_init(&periph_cfg);
TEST_ASSERT_NOT_NULL(set);
TEST_ASSERT_FALSE(audio_board_key_init(set));
input_key_service_info_t input_info[] = INPUT_KEY_DEFAULT_INFO();
input_key_service_cfg_t input_cfg = INPUT_KEY_SERVICE_DEFAULT_CONFIG();
input_cfg.handle = set;
periph_service_handle_t input_key_handle = input_key_service_create(&input_cfg);
TEST_ASSERT_NOT_NULL(input_key_handle);
TEST_ASSERT_FALSE(input_key_service_add_key(input_key_handle, input_info, INPUT_KEY_NUM));
TEST_ASSERT_FALSE(periph_service_set_callback(input_key_handle, test_input_key_service_callback, NULL));
return input_key_handle;
}
static void test_input_key_service_destroy(periph_service_handle_t handle)
{
TEST_ASSERT_FALSE(periph_service_destroy(handle));
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
}
TEST_CASE("Operate input_key_service", "[input_key_service]")
{
periph_service_handle_t input_key_handle = test_input_key_service_create();
ESP_LOGI(TAG, "input key service start, please press the buttons");
vTaskDelay(5000 / portTICK_PERIOD_MS);
test_input_key_service_destroy(input_key_handle);
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/input_key_service/test/test_input_key_service.c
|
C
|
apache-2.0
| 4,184
|
set(COMPONENT_ADD_INCLUDEDIRS include)
# Edit following two lines to set component requirements (see docs)
set(COMPONENT_REQUIRES app_update esp_https_ota)
set(COMPONENT_PRIV_REQUIRES esp_peripherals audio_pipeline audio_sal audio_stream)
set(COMPONENT_SRCS ./esp_fs_ota.c
./ota_service.c
./ota_proc_default.c)
register_component()
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/ota_service/CMakeLists.txt
|
CMake
|
apache-2.0
| 375
|
#
# "main" pseudo-component makefile.
#
# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.)
COMPONENT_ADD_INCLUDEDIRS := include
COMPONENT_SRCDIRS := .
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/ota_service/component.mk
|
Makefile
|
apache-2.0
| 206
|
/*
* 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 <stdlib.h>
#include <string.h>
#include <esp_fs_ota.h>
#include <esp_log.h>
#include <esp_ota_ops.h>
#include <errno.h>
#include "audio_mem.h"
#include "audio_sys.h"
#define IMAGE_HEADER_SIZE (sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t) + sizeof(esp_app_desc_t) + 1)
#define DEFAULT_OTA_BUF_SIZE IMAGE_HEADER_SIZE
static const char *TAG = "esp_fs_ota";
typedef enum {
ESP_FS_OTA_INIT,
ESP_FS_OTA_BEGIN,
ESP_FS_OTA_IN_PROGRESS,
ESP_FS_OTA_SUCCESS,
} esp_fs_ota_state;
struct esp_fs_ota_handle {
esp_ota_handle_t update_handle;
const esp_partition_t *update_partition;
FILE *fp;
char *ota_upgrade_buf;
size_t ota_upgrade_buf_size;
int binary_file_len;
esp_fs_ota_state state;
};
typedef struct esp_fs_ota_handle esp_fs_ota_t;
static esp_err_t _ota_write(esp_fs_ota_t *fs_ota_handle, const void *buffer, size_t buf_len)
{
if (buffer == NULL || fs_ota_handle == NULL) {
return ESP_FAIL;
}
esp_err_t err = esp_ota_write(fs_ota_handle->update_handle, buffer, buf_len);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Error: esp_ota_write failed! err=0x%d", err);
} else {
fs_ota_handle->binary_file_len += buf_len;
ESP_LOGD(TAG, "Written image length %d", fs_ota_handle->binary_file_len);
err = ESP_ERR_FS_OTA_IN_PROGRESS;
}
return err;
}
esp_err_t esp_fs_ota_begin(esp_fs_ota_config_t *ota_config, esp_fs_ota_handle_t *handle)
{
esp_err_t err;
if (handle == NULL || ota_config == NULL || ota_config->path == NULL) {
ESP_LOGE(TAG, "esp_fs_ota_begin: Invalid argument");
if (handle) {
*handle = NULL;
}
return ESP_ERR_INVALID_ARG;
}
esp_fs_ota_t *fs_ota_handle = audio_calloc(1, sizeof(esp_fs_ota_t));
if (!fs_ota_handle) {
ESP_LOGE(TAG, "Couldn't allocate memory to upgrade data buffer");
*handle = NULL;
return ESP_ERR_NO_MEM;
}
/* open */
fs_ota_handle->fp = fopen(&ota_config->path[6], "r");
if (fs_ota_handle->fp == NULL) {
ESP_LOGE(TAG, "Failed to open the app bin %s", &ota_config->path[6]);
err = ESP_FAIL;
goto failure;
}
fs_ota_handle->update_partition = NULL;
ESP_LOGI(TAG, "Starting OTA...");
fs_ota_handle->update_partition = esp_ota_get_next_update_partition(NULL);
if (fs_ota_handle->update_partition == NULL) {
ESP_LOGE(TAG, "Passive OTA partition not found");
err = ESP_FAIL;
goto failure;
}
ESP_LOGI(TAG, "Writing to partition subtype %d at offset 0x%x",
fs_ota_handle->update_partition->subtype, fs_ota_handle->update_partition->address);
const int alloc_size = (ota_config->buffer_size > DEFAULT_OTA_BUF_SIZE) ? ota_config->buffer_size : DEFAULT_OTA_BUF_SIZE;
fs_ota_handle->ota_upgrade_buf = (char *)audio_calloc(1, alloc_size);
if (!fs_ota_handle->ota_upgrade_buf) {
ESP_LOGE(TAG, "Couldn't allocate memory to upgrade data buffer");
err = ESP_ERR_NO_MEM;
goto failure;
}
fs_ota_handle->ota_upgrade_buf_size = alloc_size;
fs_ota_handle->binary_file_len = 0;
*handle = (esp_fs_ota_handle_t)fs_ota_handle;
fs_ota_handle->state = ESP_FS_OTA_BEGIN;
return ESP_OK;
failure:
if (fs_ota_handle->fp) {
fclose(fs_ota_handle->fp);
}
audio_free(fs_ota_handle);
*handle = NULL;
return err;
}
esp_err_t esp_fs_ota_get_img_desc(esp_fs_ota_handle_t fs_ota_handle, esp_app_desc_t *new_app_info)
{
esp_fs_ota_t *handle = (esp_fs_ota_t *)fs_ota_handle;
if (handle == NULL || new_app_info == NULL) {
ESP_LOGE(TAG, "esp_fs_ota_read_img_desc: Invalid argument");
return ESP_ERR_INVALID_ARG;
}
if (handle->state < ESP_FS_OTA_BEGIN) {
ESP_LOGE(TAG, "esp_fs_ota_read_img_desc: Invalid state");
return ESP_FAIL;
}
/*
* `data_read_size` holds number of bytes needed to read complete header.
* `bytes_read` holds number of bytes read.
*/
int data_read_size = IMAGE_HEADER_SIZE;
int data_read = 0, bytes_read = 0;
/*
* while loop is added to download complete image headers, even if the headers
* are not sent in a single packet.
*/
while (data_read_size > 0) {
data_read = fread((handle->ota_upgrade_buf + bytes_read), 1, data_read_size, handle->fp);
if (data_read <= 0) {
ESP_LOGE(TAG, "Connection closed, errno = %d", errno);
break;
}
data_read_size -= data_read;
bytes_read += data_read;
}
if (data_read_size > 0) {
ESP_LOGE(TAG, "Complete headers were not read");
return ESP_FAIL;
}
handle->binary_file_len = bytes_read;
memcpy(new_app_info, &handle->ota_upgrade_buf[sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t)], sizeof(esp_app_desc_t));
return ESP_OK;
}
esp_err_t esp_fs_ota_perform(esp_fs_ota_handle_t fs_ota_handle)
{
esp_fs_ota_t *handle = (esp_fs_ota_t *)fs_ota_handle;
if (handle == NULL) {
ESP_LOGE(TAG, "esp_fs_ota_perform: Invalid argument");
return ESP_ERR_INVALID_ARG;
}
if (handle->state < ESP_FS_OTA_BEGIN) {
ESP_LOGE(TAG, "esp_fs_ota_perform: Invalid state");
return ESP_FAIL;
}
esp_err_t err;
int data_read;
switch (handle->state) {
case ESP_FS_OTA_BEGIN:
err = esp_ota_begin(handle->update_partition, OTA_SIZE_UNKNOWN, &handle->update_handle);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ota_begin failed (%s)", esp_err_to_name(err));
return err;
}
handle->state = ESP_FS_OTA_IN_PROGRESS;
/* In case `esp_fs_ota_read_img_desc` was invoked first,
then the image data read there should be written to OTA partition
*/
if (handle->binary_file_len) {
return _ota_write(handle, (const void *)handle->ota_upgrade_buf, handle->binary_file_len);
}
/* falls through */
case ESP_FS_OTA_IN_PROGRESS:
data_read = fread(handle->ota_upgrade_buf, 1, handle->ota_upgrade_buf_size, handle->fp);
if (data_read <= 0) {
if (!feof(handle->fp)) {
return ESP_FAIL;
}
} else if (data_read > 0) {
return _ota_write(handle, (const void *)handle->ota_upgrade_buf, data_read);
}
handle->state = ESP_FS_OTA_SUCCESS;
break;
default:
ESP_LOGE(TAG, "Invalid ESP FS OTA State");
return ESP_FAIL;
break;
}
return ESP_OK;
}
esp_err_t esp_fs_ota_finish(esp_fs_ota_handle_t fs_ota_handle)
{
esp_fs_ota_t *handle = (esp_fs_ota_t *)fs_ota_handle;
if (handle == NULL) {
return ESP_ERR_INVALID_ARG;
}
if (handle->state < ESP_FS_OTA_BEGIN) {
return ESP_FAIL;
}
esp_err_t err = ESP_OK;
switch (handle->state) {
case ESP_FS_OTA_SUCCESS:
case ESP_FS_OTA_IN_PROGRESS:
err = esp_ota_end(handle->update_handle);
FALL_THROUGH;
case ESP_FS_OTA_BEGIN:
if (handle->ota_upgrade_buf) {
audio_free(handle->ota_upgrade_buf);
}
if (handle->fp) {
fclose(handle->fp);
}
break;
default:
ESP_LOGE(TAG, "Invalid ESP FS OTA State");
break;
}
if ((err == ESP_OK) && (handle->state == ESP_FS_OTA_SUCCESS)) {
esp_err_t err = esp_ota_set_boot_partition(handle->update_partition);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ota_set_boot_partition failed! err=0x%d", err);
}
}
audio_free(handle);
return err;
}
int esp_fs_ota_get_image_len_read(esp_fs_ota_handle_t fs_ota_handle)
{
esp_fs_ota_t *handle = (esp_fs_ota_t *)fs_ota_handle;
if (handle == NULL) {
return -1;
}
if (handle->state < ESP_FS_OTA_IN_PROGRESS) {
return -1;
}
return handle->binary_file_len;
}
esp_err_t esp_fs_ota(esp_fs_ota_config_t *ota_config)
{
if (!ota_config) {
ESP_LOGE(TAG, "fs ota path not found");
return ESP_ERR_INVALID_ARG;
}
esp_fs_ota_handle_t fs_ota_handle = NULL;
esp_err_t err = esp_fs_ota_begin(ota_config, &fs_ota_handle);
if (fs_ota_handle == NULL) {
return ESP_FAIL;
}
while (1) {
err = esp_fs_ota_perform(fs_ota_handle);
if (err != ESP_ERR_FS_OTA_IN_PROGRESS) {
break;
}
}
esp_err_t ota_finish_err = esp_fs_ota_finish(fs_ota_handle);
if (err != ESP_OK) {
/* If there was an error in esp_fs_ota_perform(),
then it is given more precedence than error in esp_fs_ota_finish()
*/
return err;
} else if (ota_finish_err != ESP_OK) {
return ota_finish_err;
}
return ESP_OK;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/ota_service/esp_fs_ota.c
|
C
|
apache-2.0
| 10,217
|
/*
* 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.
*
*/
#pragma once
#include <bootloader_common.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef void *esp_fs_ota_handle_t;
#define ESP_ERR_FS_OTA_BASE (0x10000)
#define ESP_ERR_FS_OTA_IN_PROGRESS (ESP_ERR_FS_OTA_BASE + 1) /* OTA operation in progress */
/**
* @brief ESP FS OTA configuration
*/
typedef struct {
const char *path; /*!< file path */
const int buffer_size;
} esp_fs_ota_config_t;
/**
* @brief Upgrade the firmware from filesystem.
*
* @param[in] ota_config pointer to esp_fs_ota_config_t structure.
*
* @note This API handles the entire OTA operation, so if this API is being used
* then no other APIs from `esp_fs_ota` component should be called.
* If more information and control is needed during the FS OTA process,
* then one can use `esp_fs_ota_begin` and subsequent APIs. If this API returns
* successfully, esp_restart() must be called to boot from the new firmware image.
*
* @return
* - ESP_OK: OTA data updated, next reboot will use specified partition.
* - ESP_FAIL: For generic failure.
* - ESP_ERR_INVALID_ARG: Invalid argument
* - ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image
* - ESP_ERR_NO_MEM: Cannot allocate memory for OTA operation.
* - ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed.
* - For other return codes, refer OTA documentation in esp-idf's app_update component.
*/
esp_err_t esp_fs_ota(esp_fs_ota_config_t *ota_config);
/**
* @brief Start FS OTA Firmware upgrade
*
* This function initializes ESP FS OTA context and open the firmware file.
* This function must be invoked first. If this function returns successfully, then `esp_fs_ota_perform` should be
* called to continue with the OTA process and there should be a call to `esp_fs_ota_finish` on
* completion of OTA operation or on failure in subsequent operations.
*
* @param[in] ota_config pointer to esp_fs_ota_config_t structure
* @param[out] handle pointer to an allocated data of type `esp_fs_ota_handle_t`
* which will be initialised in this function
*
* @return
* - ESP_OK: FS OTA Firmware upgrade context initialised and file opened successful
* - ESP_FAIL: For generic failure.
* - ESP_ERR_INVALID_ARG: Invalid argument (missing/incorrect config, etc.)
* - For other return codes, refer documentation in app_update component and esp_http_client
* component in esp-idf.
*/
esp_err_t esp_fs_ota_begin(esp_fs_ota_config_t *ota_config, esp_fs_ota_handle_t *handle);
/**
* @brief Read image data from file stream and write it to OTA partition
*
* This function reads image data from file stream and writes it to OTA partition. This function
* must be called only if esp_fs_ota_begin() returns successfully.
* This function must be called in a loop since it returns after every file read operation thus
* giving you the flexibility to stop OTA operation midway.
*
* @param[in] fs_ota_handle pointer to esp_fs_ota_handle_t structure
*
* @return
* - ESP_ERR_FS_OTA_IN_PROGRESS: OTA update is in progress, call this API again to continue.
* - ESP_OK: OTA update was successful
* - ESP_FAIL: OTA update failed
* - ESP_ERR_INVALID_ARG: Invalid argument
* - ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image
* - ESP_ERR_NO_MEM: Cannot allocate memory for OTA operation.
* - ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed.
* - For other return codes, refer OTA documentation in esp-idf's app_update component.
*/
esp_err_t esp_fs_ota_perform(esp_fs_ota_handle_t fs_ota_handle);
/**
* @brief Clean-up FS OTA Firmware upgrade and close the file stream.
*
* This function closes the file stream and frees the ESP FS OTA context.
* This function switches the boot partition to the OTA partition containing the
* new firmware image.
*
* @note If this API returns successfully, esp_restart() must be called to
* boot from the new firmware image
*
* @param[in] fs_ota_handle pointer to esp_fs_ota_handle_t structure
*
* @return
* - ESP_OK: Clean-up successful
* - ESP_ERR_INVALID_STATE
* - ESP_ERR_INVALID_ARG: Invalid argument
* - ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image
*/
esp_err_t esp_fs_ota_finish(esp_fs_ota_handle_t fs_ota_handle);
/**
* @brief Reads app description from image header. The app description provides information
* like the "Firmware version" of the image.
*
* @note This API can be called only after esp_fs_ota_begin() and before esp_fs_ota_perform().
* Calling this API is not mandatory.
*
* @param[in] fs_ota_handle pointer to esp_fs_ota_handle_t structure
* @param[out] new_app_info pointer to an allocated esp_app_desc_t structure
*
* @return
* - ESP_ERR_INVALID_ARG: Invalid arguments
* - ESP_FAIL: Failed to read image descriptor
* - ESP_OK: Successfully read image descriptor
*/
esp_err_t esp_fs_ota_get_img_desc(esp_fs_ota_handle_t fs_ota_handle, esp_app_desc_t *new_app_info);
/*
* @brief This function returns OTA image data read so far.
*
* @note This API should be called only if `esp_fs_ota_perform()` has been called atleast once or
* if `esp_fs_ota_get_img_desc` has been called before.
*
* @param[in] fs_ota_handle pointer to esp_https_ota_handle_t structure
*
* @return
* - -1 On failure
* - total bytes read so far
*/
int esp_fs_ota_get_image_len_read(esp_fs_ota_handle_t fs_ota_handle);
#ifdef __cplusplus
}
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/ota_service/include/esp_fs_ota.h
|
C
|
apache-2.0
| 6,816
|
/*
* 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 __OTA_PROC_DEFAULT__
#define __OTA_PROC_DEFAULT__
#include "esp_ota_ops.h"
#include "esp_partition.h"
#include "audio_element.h"
#include "ota_service.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief get the default process of `app partition` upgrade
*
* @param[in] handle pointer to `ota_upgrade_ops_t` structure
*
* @return
* - void
*/
void ota_app_get_default_proc(ota_upgrade_ops_t *ops);
/**
* @brief get the default process of `data partition` upgrade
*
* @param[in] handle pointer to `ota_upgrade_ops_t` structure
*
* @return
* - void
*/
void ota_data_get_default_proc(ota_upgrade_ops_t *ops);
/**
* @brief read from the stream of upgrading
*
* @param[in] handle pointer to upgrade handle
* @param[in] buf pointer to receive buffer
* @param[in] wanted_size bytes to read
*
* @return
* - OTA_SERV_ERR_REASON_SUCCESS: Success
* - Others: Failed
*/
ota_service_err_reason_t ota_data_image_stream_read(void *handle, char *buf, int wanted_size);
/**
* @brief write to the data partition under upgrading
*
* @param[in] handle pointer to upgrade handle
* @param[in] buf pointer to data buffer
* @param[in] size bytes to write
*
* @return
* - OTA_SERV_ERR_REASON_SUCCESS: Success
* - Others: Failed
*/
ota_service_err_reason_t ota_data_partition_write(void *handle, char *buf, int size);
/**
* @brief Generate a number by image version
* @Note The version should be (V0.0.0 - V255.255.255)
*
* @param[in] handle pointer to upgrade handle
*
* @return
* - -1: Failed
* - Others: version number
*/
int ota_get_version_number(char *version);
#ifdef __cplusplus
}
#endif
#endif /*__OTA_PROC_DEFAULT__*/
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/ota_service/include/ota_proc_default.h
|
C
|
apache-2.0
| 3,094
|
/*
* 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 __OTA_SERVICE_H__
#define __OTA_SERVICE_H__
#include "esp_partition.h"
#include "periph_service.h"
#ifdef __cplusplus
extern "C" {
#endif
#define OTA_SERVICE_ERR_REASON_BASE (0x90000)
typedef struct {
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) */
periph_service_cb evt_cb; /*!< Service callback function */
void *cb_ctx; /*!< Callback context */
} ota_service_config_t;
#define OTA_SERVICE_DEFAULT_CONFIG() \
{ \
.task_stack = 4096, \
.task_prio = 5, \
.task_core = 1, \
.evt_cb = NULL, \
.cb_ctx = NULL, \
}
typedef struct {
esp_partition_type_t type;
char *label;
char *uri;
char *cert_pem;
} ota_node_attr_t;
typedef enum {
OTA_SERV_EVENT_TYPE_RESULT,
OTA_SERV_EVENT_TYPE_FINISH
} ota_service_event_type_t;
typedef enum {
OTA_SERV_ERR_REASON_UNKNOWN = ESP_FAIL,
OTA_SERV_ERR_REASON_SUCCESS = ESP_OK,
OTA_SERV_ERR_REASON_NULL_POINTER = OTA_SERVICE_ERR_REASON_BASE + 1,
OTA_SERV_ERR_REASON_URL_PARSE_FAIL = OTA_SERVICE_ERR_REASON_BASE + 2,
OTA_SERV_ERR_REASON_ERROR_VERSION = OTA_SERVICE_ERR_REASON_BASE + 3,
OTA_SERV_ERR_REASON_NO_HIGHER_VERSION = OTA_SERVICE_ERR_REASON_BASE + 4,
OTA_SERV_ERR_REASON_ERROR_MAGIC_WORD = OTA_SERVICE_ERR_REASON_BASE + 5,
OTA_SERV_ERR_REASON_ERROR_PROJECT_NAME = OTA_SERVICE_ERR_REASON_BASE + 6,
OTA_SERV_ERR_REASON_FILE_NOT_FOUND = OTA_SERVICE_ERR_REASON_BASE + 7,
OTA_SERV_ERR_REASON_PARTITION_NOT_FOUND = OTA_SERVICE_ERR_REASON_BASE + 8,
OTA_SERV_ERR_REASON_PARTITION_WT_FAIL = OTA_SERVICE_ERR_REASON_BASE + 9,
OTA_SERV_ERR_REASON_PARTITION_RD_FAIL = OTA_SERVICE_ERR_REASON_BASE + 10,
OTA_SERV_ERR_REASON_STREAM_INIT_FAIL = OTA_SERVICE_ERR_REASON_BASE + 11,
OTA_SERV_ERR_REASON_STREAM_RD_FAIL = OTA_SERVICE_ERR_REASON_BASE + 12,
OTA_SERV_ERR_REASON_GET_NEW_APP_DESC_FAIL = OTA_SERVICE_ERR_REASON_BASE + 13,
} ota_service_err_reason_t;
typedef struct {
ota_node_attr_t node;
ota_service_err_reason_t (*prepare)(void **handle, ota_node_attr_t *node);
ota_service_err_reason_t (*need_upgrade)(void *handle, ota_node_attr_t *node);
ota_service_err_reason_t (*execute_upgrade)(void *handle, ota_node_attr_t *node);
ota_service_err_reason_t (*finished_check)(void *handle, ota_node_attr_t *node, ota_service_err_reason_t result);
bool reboot_flag;
bool break_after_fail;
} ota_upgrade_ops_t;
typedef struct {
uint8_t id;
ota_service_err_reason_t result;
} ota_result_t;
/**
* @brief Create the OTA service instance
*
* @param config configuration of the OTA service
*
* @return
* - NULL: Failed
* - Others: Success
*/
periph_service_handle_t ota_service_create(ota_service_config_t *config);
/**
* @brief Configure the upgrade parameter
* @Note This function is not thread safe
*
* This function will set the parameter table to ota service,
* and the ota service will upgrade the partitions defined in the table one by one,
*
* @param[in] handle pointer to 'periph_service_handle_t' structure
* @param[in] list pointer to 'ota_upgrade_ops_t' structure
* @param[in] list_len length of the 'list'
*
* @return
* - ESP_OK: Success
* - Others: Failed
*/
esp_err_t ota_service_set_upgrade_param(periph_service_handle_t handle, ota_upgrade_ops_t *list, int list_len);
#ifdef __cplusplus
}
#endif
#endif /* __OTA_SERVICE_H__ */
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/ota_service/include/ota_service.h
|
C
|
apache-2.0
| 5,084
|
/*
* 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 "audio_mem.h"
#include "esp_https_ota.h"
#include "esp_fs_ota.h"
#include "esp_log.h"
#include "fatfs_stream.h"
#include "http_stream.h"
#include "ota_proc_default.h"
#define READER_BUF_LEN (1024 * 2)
typedef struct {
audio_element_handle_t r_stream;
const esp_partition_t *partition;
int write_offset;
char read_buf[READER_BUF_LEN];
} ota_data_upgrade_ctx_t;
typedef struct {
void *ota_handle;
esp_err_t (*get_img_desc)(void *handle, esp_app_desc_t *new_app_info);
esp_err_t (*perform)(void *handle);
int (*get_image_len_read)(void *handle);
bool (*all_read)(void *handle);
esp_err_t (*finish)(void *handle);
} ota_app_upgrade_ctx_t;
static const char *TAG = "OTA_DEFAULT";
static ota_service_err_reason_t validate_image_header(esp_app_desc_t *new_app_info)
{
if (new_app_info == NULL) {
return OTA_SERV_ERR_REASON_NULL_POINTER;
}
const esp_partition_t *running = esp_ota_get_running_partition();
esp_app_desc_t running_app_info;
if (esp_ota_get_partition_description(running, &running_app_info) == ESP_OK) {
ESP_LOGI(TAG, "Running firmware version: %s, the incoming firmware version %s", running_app_info.version, new_app_info->version);
}
if (ota_get_version_number(new_app_info->version) < 0) {
ESP_LOGE(TAG, "Error version incoming");
return OTA_SERV_ERR_REASON_ERROR_VERSION;
}
if (ota_get_version_number(new_app_info->version) <= ota_get_version_number(running_app_info.version)) {
ESP_LOGW(TAG, "Current running version is the same as or higher than a new. We will not continue the update.");
return OTA_SERV_ERR_REASON_NO_HIGHER_VERSION;
}
return OTA_SERV_ERR_REASON_SUCCESS;
}
static ota_service_err_reason_t ota_app_partition_prepare(void **handle, ota_node_attr_t *node)
{
ota_app_upgrade_ctx_t *context = audio_calloc(1, sizeof(ota_app_upgrade_ctx_t));
AUDIO_NULL_CHECK(TAG, context, return OTA_SERV_ERR_REASON_NULL_POINTER);
*handle = context;
if (strstr(node->uri, "file://")) {
context->get_img_desc = esp_fs_ota_get_img_desc;
context->perform = esp_fs_ota_perform;
context->get_image_len_read = esp_fs_ota_get_image_len_read;
context->all_read = NULL;
context->finish = esp_fs_ota_finish;
esp_fs_ota_config_t ota_config = {
.path = node->uri,
.buffer_size = 5 * 1024,
};
esp_err_t err = esp_fs_ota_begin(&ota_config, &context->ota_handle);
if (err != ESP_OK) {
ESP_LOGE(TAG, "ESP FS OTA Begin failed");
return OTA_SERV_ERR_REASON_UNKNOWN;
}
} else if (strstr(node->uri, "https://") || strstr(node->uri, "http://")) {
context->get_img_desc = esp_https_ota_get_img_desc;
context->perform = esp_https_ota_perform;
context->get_image_len_read = esp_https_ota_get_image_len_read;
context->all_read = esp_https_ota_is_complete_data_received;
context->finish = esp_https_ota_finish;
esp_http_client_config_t config = {
.url = node->uri,
.cert_pem = node->cert_pem,
.timeout_ms = 5000,
};
esp_https_ota_config_t ota_config = {
.http_config = &config,
};
esp_err_t err = esp_https_ota_begin(&ota_config, &context->ota_handle);
if (err != ESP_OK) {
ESP_LOGE(TAG, "ESP HTTPS OTA Begin failed");
return OTA_SERV_ERR_REASON_UNKNOWN;
}
} else {
return OTA_SERV_ERR_REASON_URL_PARSE_FAIL;
}
return OTA_SERV_ERR_REASON_SUCCESS;
}
static ota_service_err_reason_t ota_app_partition_need_upgrade(void *handle, ota_node_attr_t *node)
{
ota_app_upgrade_ctx_t *context = (ota_app_upgrade_ctx_t *)handle;
AUDIO_NULL_CHECK(TAG, context, return OTA_SERV_ERR_REASON_NULL_POINTER);
AUDIO_NULL_CHECK(TAG, context->ota_handle, return OTA_SERV_ERR_REASON_NULL_POINTER);
esp_app_desc_t app_desc;
esp_err_t err = context->get_img_desc(context->ota_handle, &app_desc);
if (err != ESP_OK) {
ESP_LOGE(TAG, "get_img_desc failed");
return OTA_SERV_ERR_REASON_GET_NEW_APP_DESC_FAIL;
}
return validate_image_header(&app_desc);
}
static esp_err_t ota_app_partition_exec_upgrade(void *handle, ota_node_attr_t *node)
{
ota_app_upgrade_ctx_t *context = (ota_app_upgrade_ctx_t *)handle;
AUDIO_NULL_CHECK(TAG, context, return OTA_SERV_ERR_REASON_NULL_POINTER);
AUDIO_NULL_CHECK(TAG, context->ota_handle, return OTA_SERV_ERR_REASON_NULL_POINTER);
esp_err_t err = ESP_FAIL;
while (1) {
err = context->perform(context->ota_handle);
if (err != ESP_ERR_HTTPS_OTA_IN_PROGRESS && err != ESP_ERR_FS_OTA_IN_PROGRESS ) {
break;
}
ESP_LOGI(TAG, "Image bytes read: %d", context->get_image_len_read(context->ota_handle));
}
return err;
}
static esp_err_t ota_app_partition_finish(void *handle, ota_node_attr_t *node, ota_service_err_reason_t result)
{
ota_app_upgrade_ctx_t *context = (ota_app_upgrade_ctx_t *)handle;
AUDIO_NULL_CHECK(TAG, context->ota_handle, return OTA_SERV_ERR_REASON_NULL_POINTER);
esp_err_t err = context->finish(context->ota_handle);
if (err != ESP_OK) {
if (err == ESP_ERR_OTA_VALIDATE_FAILED) {
ESP_LOGE(TAG, "Image validation failed, image is corrupted");
}
ESP_LOGE(TAG, "upgrade failed %d", err);
}
audio_free(handle);
return err;
}
void ota_app_get_default_proc(ota_upgrade_ops_t *ops)
{
ops->prepare = ota_app_partition_prepare;
ops->need_upgrade = ota_app_partition_need_upgrade;
ops->execute_upgrade = ota_app_partition_exec_upgrade;
ops->finished_check = ota_app_partition_finish;
}
static ota_service_err_reason_t ota_data_partition_prepare(void **handle, ota_node_attr_t *node)
{
ota_data_upgrade_ctx_t *context = audio_calloc(1, sizeof(ota_data_upgrade_ctx_t));
AUDIO_NULL_CHECK(TAG, context, return OTA_SERV_ERR_REASON_NULL_POINTER);
*handle = context;
context->partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_ANY, node->label);
if (context->partition == NULL) {
ESP_LOGE(TAG, "partition [%s] not found", node->label);
return OTA_SERV_ERR_REASON_PARTITION_NOT_FOUND;
}
ESP_LOGI(TAG, "data upgrade uri %s", node->uri);
if (strstr(node->uri, "file://")) {
fatfs_stream_cfg_t fs_cfg = FATFS_STREAM_CFG_DEFAULT();
fs_cfg.type = AUDIO_STREAM_READER;
context->r_stream = fatfs_stream_init(&fs_cfg);
} else if (strstr(node->uri, "https://") || strstr(node->uri, "http://")) {
http_stream_cfg_t http_cfg = HTTP_STREAM_CFG_DEFAULT();
http_cfg.type = AUDIO_STREAM_READER;
context->r_stream = http_stream_init(&http_cfg);
} else {
ESP_LOGE(TAG, "not support uri");
return OTA_SERV_ERR_REASON_URL_PARSE_FAIL;
}
audio_element_set_uri(context->r_stream, node->uri);
if (audio_element_process_init(context->r_stream) != ESP_OK) {
ESP_LOGE(TAG, "reader stream init failed");
return OTA_SERV_ERR_REASON_STREAM_INIT_FAIL;
}
return OTA_SERV_ERR_REASON_SUCCESS;
}
static ota_service_err_reason_t ota_data_partition_exec_upgrade(void *handle, ota_node_attr_t *node)
{
int r_size = 0;
ota_data_upgrade_ctx_t *context = (ota_data_upgrade_ctx_t *)handle;
AUDIO_NULL_CHECK(TAG, context, return OTA_SERV_ERR_REASON_NULL_POINTER);
AUDIO_NULL_CHECK(TAG, context->r_stream, return OTA_SERV_ERR_REASON_NULL_POINTER);
AUDIO_NULL_CHECK(TAG, context->partition, return OTA_SERV_ERR_REASON_NULL_POINTER);
esp_err_t ret = ESP_OK;
if ((ret = esp_partition_erase_range(context->partition, 0, context->partition->size)) != ESP_OK) {
ESP_LOGE(TAG, "Erase [%s] partition failed, return value: %d", node->label, ret);
return OTA_SERV_ERR_REASON_PARTITION_WT_FAIL;
}
while ((r_size = audio_element_input(context->r_stream, context->read_buf, READER_BUF_LEN)) > 0) {
ESP_LOGI(TAG, "write_offset %d, r_size %d", context->write_offset, r_size);
if (esp_partition_write(context->partition, context->write_offset, context->read_buf, r_size) == ESP_OK) {
context->write_offset += r_size;
} else {
return OTA_SERV_ERR_REASON_PARTITION_WT_FAIL;
}
}
if (r_size == AEL_IO_OK || r_size == AEL_IO_DONE) {
ESP_LOGI(TAG, "partition %s upgrade successes", node->label);
return OTA_SERV_ERR_REASON_SUCCESS;
} else {
return OTA_SERV_ERR_REASON_STREAM_RD_FAIL;
}
}
static ota_service_err_reason_t ota_data_partition_finish(void *handle, ota_node_attr_t *node, ota_service_err_reason_t result)
{
ota_data_upgrade_ctx_t *context = (ota_data_upgrade_ctx_t *)handle;
AUDIO_NULL_CHECK(TAG, context->r_stream, return ESP_FAIL);
audio_element_process_deinit(context->r_stream);
audio_element_deinit(context->r_stream);
audio_free(handle);
return result;
}
void ota_data_get_default_proc(ota_upgrade_ops_t *ops)
{
ops->prepare = ota_data_partition_prepare;
ops->need_upgrade = NULL;
ops->execute_upgrade = ota_data_partition_exec_upgrade;
ops->finished_check = ota_data_partition_finish;
}
ota_service_err_reason_t ota_data_image_stream_read(void *handle, char *buf, int wanted_size)
{
ota_data_upgrade_ctx_t *context = (ota_data_upgrade_ctx_t *)handle;
if (context == NULL) {
ESP_LOGE(TAG, "run prepare first");
return OTA_SERV_ERR_REASON_NULL_POINTER;
}
AUDIO_NULL_CHECK(TAG, context->r_stream, return OTA_SERV_ERR_REASON_NULL_POINTER);
int r_size = 0;
do {
int ret = audio_element_input(context->r_stream, buf, wanted_size - r_size);
if (ret > 0) {
r_size += ret;
} else {
break;
}
} while (r_size < wanted_size);
if (r_size == wanted_size) {
return OTA_SERV_ERR_REASON_SUCCESS;
} else {
return OTA_SERV_ERR_REASON_STREAM_RD_FAIL;
}
}
ota_service_err_reason_t ota_data_partition_write(void *handle, char *buf, int size)
{
ota_data_upgrade_ctx_t *context = (ota_data_upgrade_ctx_t *)handle;
if (context == NULL) {
ESP_LOGE(TAG, "run prepare first");
return OTA_SERV_ERR_REASON_NULL_POINTER;
}
ESP_LOGI(TAG, "write_offset %d, size %d", context->write_offset, size);
if (esp_partition_write(context->partition, context->write_offset, buf, size) == ESP_OK) {
context->write_offset += size;
return OTA_SERV_ERR_REASON_SUCCESS;
} else {
return OTA_SERV_ERR_REASON_PARTITION_WT_FAIL;
}
}
int ota_get_version_number(char *version)
{
AUDIO_NULL_CHECK(TAG, version, return -1);
if (strlen(version) > 32) {
ESP_LOGE(TAG, "Invalid version");
return -1;
}
int ver_num = 0;
char *ver = audio_calloc(1, strlen(version) + 1);
AUDIO_NULL_CHECK(TAG, ver, return -1);
memcpy(ver, version, strlen(version));
char *p = strtok(ver, ".");
AUDIO_NULL_CHECK(TAG, p, goto _err_ver);
if (p[0] == 'v' || p[0] == 'V') {
p++;
int cnt = 2; // expect max version V255.255.255
while (p) {
for (int i = 0; i < strlen(p); i++) {
if (p[i] < '0' || p[i] > '9') {
goto _err_ver;
}
}
if (atoi(p) > 255) {
goto _err_ver;
}
ver_num |= (atoi(p) << (cnt * 8));
p = strtok(NULL, ".");
cnt--;
}
if (cnt != -1) {
goto _err_ver;
}
free(ver);
return ver_num;
} else {
goto _err_ver;
}
_err_ver:
ESP_LOGE(TAG, "Got invalid version: %s, the version should be (V0.0.0 - V255.255.255)", version);
free(ver);
return -1;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/ota_service/ota_proc_default.c
|
C
|
apache-2.0
| 13,163
|
/*
* 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/queue.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_log.h"
#include "audio_mem.h"
#include "ota_service.h"
typedef enum {
OTA_INIT,
OTA_IDLE,
OTA_START,
OTA_END,
OTA_DESTROY,
OTA_ERROR,
OTA_STATE_END
} ota_status_t;
typedef struct {
int state;
xQueueHandle srv_q;
ota_upgrade_ops_t *upgrade_list;
int list_len;
int result;
} ota_service_t;
typedef enum {
OTA_SERVICE_CMD_START,
OTA_SERVICE_CMD_DESTROY,
} ota_cmd_t;
typedef struct {
ota_upgrade_ops_t *list;
int len;
} ota_list_msg_t;
typedef struct {
int cmd;
void *pdata;
} ota_msg_t;
static const char *TAG = "OTA_SERVICE";
static void ota_service_cmd_send(void *que, int cmd, void *data, int dir)
{
ota_msg_t evt = { 0 };
evt.cmd = cmd;
evt.pdata = data;
if (dir) {
xQueueSendToFront(que, &evt, 0);
} else {
xQueueSend(que, &evt, 0);
}
}
static ota_service_err_reason_t ota_service_process(ota_upgrade_ops_t *upgrade_info)
{
ota_service_err_reason_t ret = OTA_SERV_ERR_REASON_UNKNOWN;
void *handle = NULL;
AUDIO_NULL_CHECK(TAG, upgrade_info, return OTA_SERV_ERR_REASON_NULL_POINTER);
AUDIO_NULL_CHECK(TAG, upgrade_info->prepare, return OTA_SERV_ERR_REASON_NULL_POINTER);
AUDIO_NULL_CHECK(TAG, upgrade_info->need_upgrade, return OTA_SERV_ERR_REASON_NULL_POINTER);
AUDIO_NULL_CHECK(TAG, upgrade_info->execute_upgrade, return OTA_SERV_ERR_REASON_NULL_POINTER);
ret = upgrade_info->prepare(&handle, &upgrade_info->node);
if (ret != OTA_SERV_ERR_REASON_SUCCESS) {
ESP_LOGE(TAG, "OTA prepared fail");
return ret;
}
ret = upgrade_info->need_upgrade(handle, &upgrade_info->node);
if (ret != OTA_SERV_ERR_REASON_SUCCESS) {
ESP_LOGE(TAG, "No need to upgrade");
return ret;
}
ret = upgrade_info->execute_upgrade(handle, &upgrade_info->node);
if (ret != OTA_SERV_ERR_REASON_SUCCESS) {
ESP_LOGE(TAG, "Fail to execute upgrade");
return ret;
}
AUDIO_CHECK(TAG, upgrade_info->finished_check != NULL, return OTA_SERV_ERR_REASON_NULL_POINTER, "finished_check should not be NULL");
return upgrade_info->finished_check(handle, &upgrade_info->node, ret);
}
static void ota_task(void *pvParameters)
{
periph_service_handle_t serv_handle = (periph_service_handle_t)pvParameters;
ota_service_t *ota = periph_service_get_data(serv_handle);
ota_msg_t msg = { 0 };
periph_service_event_t ser_evt = { 0 };
ota_result_t result_data = { 0 };
ota->state = OTA_IDLE;
while (true) {
switch (ota->state) {
case OTA_INIT:
case OTA_IDLE: {
ota->result = 0;
if (xQueueReceive(ota->srv_q, &msg, portMAX_DELAY) == pdTRUE) {
switch (msg.cmd) {
case OTA_SERVICE_CMD_START: {
if (ota->upgrade_list == NULL || ota->list_len == 0) {
ESP_LOGE(TAG, "Please set upgrade list first");
} else {
ota->state = OTA_START;
}
break;
}
case OTA_SERVICE_CMD_DESTROY: {
ota->state = OTA_DESTROY;
break;
}
default:
break;
}
}
break;
}
case OTA_START: {
ota_service_err_reason_t ret = OTA_SERV_ERR_REASON_UNKNOWN;
for (int i = 0; i < ota->list_len; i++) {
ota_upgrade_ops_t *cur_node = &ota->upgrade_list[i];
ret = ota_service_process(cur_node);
if (ret == OTA_SERV_ERR_REASON_SUCCESS) {
ota->result |= (0x01 << i);
}
ser_evt.type = OTA_SERV_EVENT_TYPE_RESULT;
ser_evt.source = serv_handle;
result_data.result = ret;
result_data.id = i;
ser_evt.data = (void *)&result_data;
ser_evt.len = ota->list_len;
periph_service_callback(serv_handle, &ser_evt);
if (ret != OTA_SERV_ERR_REASON_SUCCESS && cur_node->break_after_fail) {
ESP_LOGE(TAG, "upgrade_list[%d] OTA failed, break the update list", i);
break;
}
}
ota->state = OTA_END;
break;
}
case OTA_END: {
ESP_LOGW(TAG, "OTA_END!");
for (int i = 0; i < ota->list_len; i++) {
if (ota->result & (0x01 << i)) {
if (ota->upgrade_list[i].reboot_flag == true) {
ESP_LOGW(TAG, "restart!");
esp_restart();
}
}
}
memset(&ser_evt, 0, sizeof(periph_service_event_t));
ser_evt.type = OTA_SERV_EVENT_TYPE_FINISH;
periph_service_callback(serv_handle, &ser_evt);
ota->state = OTA_IDLE;
break;
}
case OTA_ERROR: {
ESP_LOGE(TAG, "OTA_ERROR");
ota->state = OTA_IDLE;
break;
}
case OTA_DESTROY: {
ESP_LOGE(TAG, "OTA_DESTROY");
break;
}
default:
ESP_LOGE(TAG, "Unkown OTA state %d", ota->state);
ota->state = OTA_ERROR;
break;
}
if (ota->state == OTA_DESTROY) {
break;
}
}
vQueueDelete(ota->srv_q);
if (ota->upgrade_list) {
audio_free(ota->upgrade_list);
}
audio_free(ota);
vTaskDelete(NULL);
}
static esp_err_t _ota_start(periph_service_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_ERR_INVALID_ARG);
ota_service_t *ota = periph_service_get_data(handle);
ota_service_cmd_send(ota->srv_q, OTA_SERVICE_CMD_START, NULL, 0);
return ESP_OK;
}
static esp_err_t _ota_destroy(periph_service_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_ERR_INVALID_ARG);
ota_service_t *ota = periph_service_get_data(handle);
ota_service_cmd_send(ota->srv_q, OTA_SERVICE_CMD_DESTROY, NULL, 0);
return ESP_OK;
}
esp_err_t ota_service_set_upgrade_param(periph_service_handle_t handle, ota_upgrade_ops_t *list, int list_len)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_ERR_INVALID_ARG);
AUDIO_NULL_CHECK(TAG, list, return ESP_ERR_INVALID_ARG);
AUDIO_CHECK(TAG, list_len > 0, return ESP_FAIL, "list len <= 0");
ota_service_t *ota = periph_service_get_data(handle);
ota->upgrade_list = audio_calloc(1, list_len * sizeof(ota_upgrade_ops_t));
AUDIO_NULL_CHECK(TAG, ota->upgrade_list, return ESP_FAIL);
memcpy(ota->upgrade_list, list, list_len * sizeof(ota_upgrade_ops_t));
ota->list_len = list_len;
return ESP_OK;
}
periph_service_handle_t ota_service_create(ota_service_config_t *config)
{
ota_service_t *ota = audio_calloc(1, sizeof(ota_service_t));
AUDIO_MEM_CHECK(TAG, ota, return NULL);
ota->srv_q = xQueueCreate(3, sizeof(ota_msg_t));
AUDIO_MEM_CHECK(TAG, ota->srv_q, {
audio_free(ota);
return NULL;
});
ota->state = OTA_INIT;
periph_service_config_t cfg = {
.task_stack = config->task_stack,
.task_prio = config->task_prio,
.task_core = config->task_core,
.task_func = ota_task,
.service_start = _ota_start,
.service_stop = NULL, /*Should not stop the upgrading process*/
.service_ioctl = NULL,
.service_destroy = _ota_destroy,
.service_name = "ota_serv",
.user_data = (void *)ota,
};
periph_service_handle_t periph_ota = periph_service_create(&cfg);
AUDIO_MEM_CHECK(TAG, periph_ota, {
vQueueDelete(ota->srv_q);
audio_free(ota);
return NULL;
});
periph_service_set_callback(periph_ota, config->evt_cb, config->cb_ctx);
return periph_ota;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/ota_service/ota_service.c
|
C
|
apache-2.0
| 9,631
|
# Edit following two lines to set component requirements (see docs)
set(COMPONENT_REQUIRES audio_sal nvs_flash)
set(COMPONENT_PRIV_REQUIRES )
set(COMPONENT_SRCS ./playlist.c
./playlist_operator/dram_list.c
./playlist_operator/flash_list.c
./playlist_operator/partition_list.c
./playlist_operator/sdcard_list.c
./sdcard_scan/sdcard_scan.c
)
set(COMPONENT_ADD_INCLUDEDIRS ./include)
register_component()
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/playlist/CMakeLists.txt
|
CMake
|
apache-2.0
| 538
|
#
# Main Makefile. This is basically the same as a component makefile.
COMPONENT_ADD_INCLUDEDIRS := include
COMPONENT_SRCDIRS := . ./playlist_operator ./sdcard_scan
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/playlist/component.mk
|
Makefile
|
apache-2.0
| 166
|
/*
* 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 _DRAM_LIST_H_
#define _DRAM_LIST_H_
#include "playlist.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Create a playlist in dram
*
* @param[out] handle The playlist handle from application layer
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t dram_list_create(playlist_operator_handle_t *handle);
/**
* @brief Save URL to dram playlist
*
* @param handle Playlist handle
* @param url URL to be saved
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t dram_list_save(playlist_operator_handle_t handle, const char *url);
/**
* @brief The following URLs in dram playlist
*
* @param handle Playlist handle
* @param step The offset of URL from current URL
* @param[out] url_buff A second rank pointer to get a address of URL
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t dram_list_next(playlist_operator_handle_t handle, int step, char **url_buff);
/**
* @brief The previous URLs in dram playlist
*
* @param handle Playlist handle
* @param step The offset of URL from current URL
* @param[out] url_buff A second rank pointer to get a address of URL
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t dram_list_prev(playlist_operator_handle_t handle, int step, char **url_buff);
/**
* @brief Judge whether the url exists in dram playlist
*
* @param handle Playlist handle
* @param url The url to be checked
*
* @return true existence
* false Non-existent
*/
bool dram_list_exist(playlist_operator_handle_t handle, const char *url);
/**
* @brief Reset dram playlist
*
* @param handle Playlist handle
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t dram_list_reset(playlist_operator_handle_t handle);
/**
* @brief The current URL in current playlist
*
* @param handle Playlist handle
* @param[out] url_buff A second rank pointer to get a address of URL
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t dram_list_current(playlist_operator_handle_t handle, char **url_buff);
/**
* @brief Choose a url by url id
*
* @param handle Playlist handle
* @param url_id The id of url in dram list
* @param[out] url_buff A second rank pointer to get a address of URL
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t dram_list_choose(playlist_operator_handle_t handle, int url_id, char **url_buff);
/**
* @brief Get URLs number in the dram playlist
*
* @param handle Playlist handle
*
* @return URLs number in dram playlist
* ESP_FAIL Fail to get number of urls
*/
int dram_list_get_url_num(playlist_operator_handle_t handle);
/**
* @brief Get current url id in the dram playlist
*
* @param handle Playlist handle
*
* @return Current url id in dram playlist
* ESP_FAIL Fail to get url id
*/
int dram_list_get_url_id(playlist_operator_handle_t handle);
/**
* @brief Show all the URLs in the dram playlist
*
* @param handle Playlist handle
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t dram_list_show(playlist_operator_handle_t handle);
/**
* @brief Remove corrsponding url in dram list
*
* @param handle Playlist handle
* @param url The url to be removed
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t dram_list_remove_by_url(playlist_operator_handle_t handle, const char *url);
/**
* @brief Remove url by id
*
* @param handle Playlist handle
* @param url_id The url id to be removed
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t dram_list_remove_by_url_id(playlist_operator_handle_t handle, uint16_t url_id);
/**
* @brief Destroy the dram playlist
*
* @param handle Playlist handle
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t dram_list_destroy(playlist_operator_handle_t handle);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/playlist/include/dram_list.h
|
C
|
apache-2.0
| 5,322
|
/*
* 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 _FLASH_LIST_H_
#define _FLASH_LIST_H_
#include "playlist.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Create a playlist in nvs flash
*
* @param[out] handle Playlist handle
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t flash_list_create(playlist_operator_handle_t *handle);
/**
* @brief Save URL to nvs flash list
*
* @param handle Playlist handle
* @param url URL to be saved
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t flash_list_save(playlist_operator_handle_t handle, const char *url);
/**
* @brief Show all the URLs in nvs flash list
*
* @param handle Playlist handle
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t flash_list_show(playlist_operator_handle_t handle);
/**
* @brief The following URLs in nvs flash playlist
*
* @param handle Playlist handle
* @param step The offset of URL from current URL
* @param[out] url_buff A second rank pointer to get a address of URL
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t flash_list_next(playlist_operator_handle_t handle, int step, char **url_buff);
/**
* @brief The previous URLs in nvs flash playlist
*
* @param handle Playlist handle
* @param step The offset of URL from current URL
* @param[out] url_buff A second rank pointer to get a address of URL
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t flash_list_prev(playlist_operator_handle_t handle, int step, char **url_buff);
/**
* @brief The current URL in nvs flash playlist
*
* @param handle Playlist handle
* @param[out] url_buff A second rank pointer to get a address of URL
*
* @return ESP_OK success
* @return ESP_FAIL failed
*/
esp_err_t flash_list_current(playlist_operator_handle_t handle, char **url_buff);
/**
* @brief Judge whether the url exists in flash playlist
*
* @param handle Playlist handle
* @param url The url to be checked
*
* @return true existence
* false Non-existent
*/
bool flash_list_exist(playlist_operator_handle_t handle, const char *url);
/**
* @brief Reset flash playlist
*
* @param handle Playlist handle
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t flash_list_reset(playlist_operator_handle_t handle);
/**
* @brief Choose a url by url id
*
* @param handle Playlist handle
* @param url_id The id of url in flash list
* @param[out] url_buff A second rank pointer to get a address of URL
*
* @return ESP_OK success
* @return ESP_FAIL failed
*/
esp_err_t flash_list_choose(playlist_operator_handle_t handle, int url_id, char **url_buff);
/**
* @brief Get URLs number in the flash playlist
*
* @param handle Playlist handle
*
* @return URLs number in flash playlist
* ESP_FAIL Fail to get number of urls
*/
int flash_list_get_url_num(playlist_operator_handle_t handle);
/**
* @brief Get current url id in the flash playlist
*
* @param handle Playlist handle
*
* @return Curernt url id in flash playlist
* ESP_FAIL Fail to get url id
*/
int flash_list_get_url_id(playlist_operator_handle_t handle);
/**
* @brief Destroy the nvs flash playlist
*
* @param handle Playlist handle
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t flash_list_destroy(playlist_operator_handle_t handle);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/playlist/include/flash_list.h
|
C
|
apache-2.0
| 4,789
|
/*
* 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 _PARTITION_LIST_H_
#define _PARTITION_LIST_H_
#include "playlist.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Create a playlist in flash partition by list id
*
* @param[out] handle The playlist handle from application layer
*
* @return ESP_OK success
* ESP_FAIL failed
*
* @note Please add 2 partitions to partition table whose subtype are 0x06 and 0x07 first
*/
esp_err_t partition_list_create(playlist_operator_handle_t *handle);
/**
* @brief Save URL to partition playlist
*
* @param handle Playlist handle
* @param url URL to be saved
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t partition_list_save(playlist_operator_handle_t handle, const char *url);
/**
* @brief The following URLs in partition playlist
*
* @param handle Playlist handle
* @param step The offset of URL from current URL
* @param[out] url_buff A second rank pointer to get a address of URL
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t partition_list_next(playlist_operator_handle_t handle, int step, char **url_buff);
/**
* @brief The previous URLs in partition playlist
*
* @param handle Playlist handle
* @param step The offset of URL from current URL
* @param[out] url_buff A second rank pointer to get a address of URL
*
* return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t partition_list_prev(playlist_operator_handle_t handle, int step, char **url_buff);
/**
* @brief Judge whether the url exists in partition playlist
*
* @param handle Playlist handle
* @param url The url to be checked
*
* @return true existence
* false Non-existent
*/
bool partition_list_exist(playlist_operator_handle_t handle, const char *url);
/**
* @brief Reset partition playlist
*
* @param handle Playlist handle
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t partition_list_reset(playlist_operator_handle_t handle);
/**
* @brief Get current URL in the partition playlist
*
* @param handle Playlist handle
* @param[out] url_buff A second rank pointer to get a address of URL
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t partition_list_current(playlist_operator_handle_t handle, char **url_buff);
/**
* @brief Choose a url by url id
*
* @param handle Playlist handle
* @param url_id The id of url in partition list
* @param[out] url_buff A second rank pointer to get a address of URL
*
* @return ESP_OK success
* @return ESP_FAIL failed
*/
esp_err_t partition_list_choose(playlist_operator_handle_t handle, int url_id, char **url_buff);
/**
* @brief Get URLs number in the partition playlist
*
* @param handle Playlist handle
*
* @return URLs number in partition playlist
* ESP_FAIL Fail to get number of urls
*/
int partition_list_get_url_num(playlist_operator_handle_t handle);
/**
* @brief Get curernt url id in the partition playlist
*
* @param handle Playlist handle
*
* @return Current url id in partition playlist
* ESP_FAIL Fail to get url id
*/
int partition_list_get_url_id(playlist_operator_handle_t handle);
/**
* @brief Show all the URLs in the partition playlist
*
* @param handle Playlist handle
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t partition_list_show(playlist_operator_handle_t handle);
/**
* @brief Destroy the partition playlist
*
* @param handle Playlist handle
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t partition_list_destroy(playlist_operator_handle_t handle);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/playlist/include/partition_list.h
|
C
|
apache-2.0
| 5,035
|
/*
* 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 _PLAY_LIST_H_
#define _PLAY_LIST_H_
#include "esp_log.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Type of playlist
*/
typedef enum {
PLAYLIST_UNKNOWN = -1, /*!< Unknown type */
PLAYLIST_SDCARD, /*!< Playlist in sdcard */
PLAYLIST_FLASH, /*!< Playlist in nvs */
PLAYLIST_DRAM, /*!< Playlist in ram */
PLAYLIST_PARTITION /*!< Playlist in partition */
} playlist_type_t;
/**
* @brief All types of Playlists' operation
*/
typedef struct {
esp_err_t (*show) (void *playlist); /*!< Show all the URLs in playlist */
esp_err_t (*save) (void *playlist, const char *url); /*!< Save URLs to playlist */
esp_err_t (*next) (void *playlist, int step, char **url_buff); /*!< Get next URL in playlist */
esp_err_t (*prev) (void *playlist, int step, char **url_buff); /*!< Get previous URL in playlist */
esp_err_t (*reset) (void *playlist); /*!< Reset the playlist */
esp_err_t (*choose) (void *playlist, int url_id, char **url_buff); /*!< Get url by url id */
esp_err_t (*current) (void *playlist, char **url_buff); /*!< Get current URL in playlist */
esp_err_t (*destroy) (void *playlist); /*!< Destroy playlist */
bool (*exist) (void *playlist, const char *url); /*!< Judge whether the url exists */
int (*get_url_num) (void *playlist); /*!< Get number of URLS in current playlist */
int (*get_url_id) (void *playlist); /*!< Get current url id in playlist */
playlist_type_t type; /*!< Type of playlist */
esp_err_t (*remove_by_url)(void *playlist, const char *url); /*!< Remove the corresponding url */
esp_err_t (*remove_by_id)(void *playlist, uint16_t url_id); /*!< Remove url by id */
} playlist_operation_t;
/**
* @brief Information of playlist manager node
*/
typedef struct {
void *playlist; /*!< Specific playlist's pointer */
esp_err_t (*get_operation)(playlist_operation_t *operation); /*!< Function pointer to get playlists' handle */
} playlist_operator_t;
typedef playlist_operator_t *playlist_operator_handle_t;
typedef struct playlist_handle *playlist_handle_t;
/**
* @brief Create a playlist manager handle
*
* @return playlist handle success
* NULL failed
*/
playlist_handle_t playlist_create(void);
/**
* @brief Create a playlist manager and add playlist handle to it
*
* @note The partition playlist can only be added once, or it will be overwrited by the newest partiiton playlist
* @note Different lists must use different IDs, because even if they are in different handles,
* list_id is the only indicator that distinguishes them.
*
* @param handle Playlist manager handle
* @param list_handle The playlist handle to be added
* @param list_id The playlist id to be registered
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t playlist_add(playlist_handle_t handle, playlist_operator_handle_t list_handle, uint8_t list_id);
/**
* @brief Playlist checkout by list id
*
* @param handle Playlist handle
* @param id Specified list id
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t playlist_checkout_by_id(playlist_handle_t handle, uint8_t id);
/**
* @brief Get number of playlists in the handle
*
* @param handle Playlist handle
*
* @return success Number of playlists in handle
* failed -1
*/
int playlist_get_list_num(playlist_handle_t handle);
/**
* @brief Get current playlist type
*
* @param handle Playlist handle
*
* @return success Type of current playlist
* failed -1
*/
playlist_type_t playlist_get_current_list_type(playlist_handle_t handle);
/**
* @brief Get current playlist id
*
* @param handle Playlist handle
*
* @return success Current playlist id
* failed -1
*/
int playlist_get_current_list_id(playlist_handle_t handle);
/**
* @brief Get current URL in current playlist
*
* @param handle Playlist handle
* @param[out] url_buff A second rank pointer to get a address of URL
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t playlist_get_current_list_url(playlist_handle_t handle, char **url_buff);
/**
* @brief Get number of URLs in current playlist
*
* @param handle Playlist handle
*
* @return Number of URLS in current playlsit
*/
int playlist_get_current_list_url_num(playlist_handle_t handle);
/**
* @brief Get current url id in current playlist
*
* @param handle Playlist handle
*
* @return Current url's id in current playlsit
*/
int playlist_get_current_list_url_id(playlist_handle_t handle);
/**
* @brief Save a URL to the current playlist
*
* @param handle Playlist handle
* @param url The URL to be saved ot sdcard
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t playlist_save(playlist_handle_t handle, const char *url);
/**
* @brief Next URl in current playlist
*
* @param handle Playlist handle
* @param step Next steps from current position
* @param[out] url_buff A second rank pointer to get a address of URL
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t playlist_next(playlist_handle_t handle, int step, char **url_buff);
/**
* @brief Previous URL in current playlist
*
* @param handle Playlist handle
* @param step Previous steps from current position
* @param[out] url_buff A second rank pointer to get a address of URL
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t playlist_prev(playlist_handle_t handle, int step, char **url_buff);
/**
* @brief Choose a url by url id
*
* @param handle Playlist handle
* @param url_id The id of url in current list
* @param[out] url_buff A second rank pointer to get a address of URL
*
* @return ESP_OK success
* @return ESP_FAIL failed
*/
esp_err_t playlist_choose(playlist_handle_t handle, int url_id, char **url_buff);
/**
* @brief Show URLs in current playlist
*
* @param handle Playlist handle
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t playlist_show(playlist_handle_t handle);
/**
* @brief Reset current playlist
*
* @param handle Playlist handle
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t playlist_reset(playlist_handle_t handle);
/**
* @brief Remove corresponding url
*
* @param handle Playlist handle
* @param url The url to be removed
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t playlist_remove_by_url(playlist_handle_t handle, const char *url);
/**
* @brief Remove url by url id
*
* @param handle Playlist handle
* @param url_id The id of url to be removed
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t playlist_remove_by_url_id(playlist_handle_t handle, uint16_t url_id);
/**
* @brief Judge whether the url exists in current playlist
*
* @param handle Playlist handle
* @param url The url to be checked
*
* @return true existence
* false Non-existent
*/
bool playlist_exist(playlist_handle_t handle, const char *url);
/**
* @brief Destroy all playlists in the handle
*
* @param handle Playlist handle
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t playlist_destroy(playlist_handle_t handle);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/playlist/include/playlist.h
|
C
|
apache-2.0
| 8,968
|
/*
* 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 _SDCARD_LIST_H_
#define _SDCARD_LIST_H_
#include "playlist.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Create a playlist in sdcard by list id
*
* @param[out] handle The playlist handle from application layer
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t sdcard_list_create(playlist_operator_handle_t *handle);
/**
* @brief Show all the URLs in sdcard playlist
*
* @param handle Playlist handle
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t sdcard_list_show(playlist_operator_handle_t handle);
/**
* @brief The following URLs in sdcard playlist
*
* @param handle Playlist handle
* @param step The offset of URL from current URL
* @param[out] url_buff A second rank pointer to get a address of URL
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t sdcard_list_next(playlist_operator_handle_t handle, int step, char **url_buff);
/**
* @brief The previous URLs in sdcard playlist
*
* @param handle Playlist handle
* @param step The offset of URL from current URL
* @param[out] url_buff A second rank pointer to get a address of URL
*
* return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t sdcard_list_prev(playlist_operator_handle_t handle, int step, char **url_buff);
/**
* @brief Judge whether the url exists in sdcard playlist
*
* @param handle Playlist handle
* @param url The url to be checked
*
* @return true existence
* false Non-existent
*/
bool sdcard_list_exist(playlist_operator_handle_t handle, const char *url);
/**
* @brief Reset sdcard playlist
*
* @param handle Playlist handle
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t sdcard_list_reset(playlist_operator_handle_t handle);
/**
* @brief Get current URL in sdcard playlist
*
* @param handle Playlist handle
* @param[out] url_buff A second rank pointer to get a address of URL
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t sdcard_list_current(playlist_operator_handle_t handle, char **url_buff);
/**
* @brief Choose a url by url id
*
* @param handle Playlist handle
* @param url_id The id of url in sdcard list
* @param[out] url_buff A second rank pointer to get a address of URL
*
* @return ESP_OK success
* @return ESP_FAIL failed
*/
esp_err_t sdcard_list_choose(playlist_operator_handle_t handle, int url_id, char **url_buff);
/**
* @brief Get URLs number in sdcard playlist
*
* @param handle Playlist handle
*
* @return URLs number in sdcard playlist
* ESP_FAIL Fail to get number of urls
*/
int sdcard_list_get_url_num(playlist_operator_handle_t handle);
/**
* @brief Get current url id in the sdcard playlist
*
* @param handle Playlist handle
*
* @return Current url id in partition playlist
* ESP_FAIL Fail to get url id
*/
int sdcard_list_get_url_id(playlist_operator_handle_t handle);
/**
* @brief Destroy sdcard playlist
*
* @param handle Playlist handle
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t sdcard_list_destroy(playlist_operator_handle_t handle);
/**
* @brief Save URL to sdcard playlist
*
* @param handle Playlist handle
* @param url URL to be saved
*
* @return ESP_OK success
* ESP_FAIL failed
*/
esp_err_t sdcard_list_save(playlist_operator_handle_t handle, const char *url);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/playlist/include/sdcard_list.h
|
C
|
apache-2.0
| 4,836
|
/*
* 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 _SDCARD_SCAN_H_
#define _SDCARD_SCAN_H_
#ifdef __cplusplus
extern "C" {
#endif
typedef void (*sdcard_scan_cb_t)(void *user_data, char *url);
/**
* @brief Scan files in SD card and use callback function to save files that meet filtering conditions.
*
* @param cb The callback function
* @param path The path to be scanned
* @param depth The depth of file scanning // .e.g. if you only want to save files in "/test" , depth = 0.
* // if you want to save files in "/test/scan_test/", depth = 1
* @param file_extension File extension of files that are supposed to be saved // .e.g. const char *[]{"mp3", "aac"}
* @param filter_num Number of filters
* @param user_data The data to be used by callback function
*
* @return ESP_OK success
* ESP_FAIL failed
*
* //example sdcard_scan(callback, "/sdcard", 5, const char *[]{"mp3", "aac"}, 2, user_data);
* Scan 5 levels folder in sdcard and save mp3 files and aac files.
*/
esp_err_t sdcard_scan(sdcard_scan_cb_t cb, const char *path, int depth, const char *file_extension[], int filter_num, void *user_data);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/playlist/include/sdcard_scan.h
|
C
|
apache-2.0
| 2,521
|
/*
* 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 "sys/queue.h"
#include "esp_log.h"
#include "audio_mem.h"
#include "audio_error.h"
#include "audio_mutex.h"
#include "playlist.h"
static const char *TAG = "PLAYLIST";
/**
* @brief Information of playlist
*/
typedef struct playlist_info {
playlist_operator_handle_t list_handle; /*!< Specific playlist's handle */
uint8_t list_id; /*!< List id*/
STAILQ_ENTRY(playlist_info) entries; /*!< List node */
} playlist_info_t;
/**
* @brief Handle of playlist
*/
struct playlist_handle {
uint8_t list_num; /*!< The number of all the playlists in the handle */
playlist_info_t *cur_playlist; /*!< Pointer of current playlist */
xSemaphoreHandle playlist_operate_lock; /*!< A semaphore of operations */
STAILQ_HEAD(list_info, playlist_info) playlist_info_list; /*!< List head of playlists */
};
playlist_handle_t playlist_create(void)
{
playlist_handle_t handle = (playlist_handle_t)audio_calloc(1, sizeof(struct playlist_handle));
AUDIO_NULL_CHECK(TAG, handle, return NULL);
handle->playlist_operate_lock = mutex_create();
AUDIO_NULL_CHECK(TAG, handle->playlist_operate_lock, {
audio_free(handle);
return NULL;
});
STAILQ_INIT(&handle->playlist_info_list);
return handle;
}
esp_err_t playlist_next(playlist_handle_t handle, int step, char **url_buff)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, handle->cur_playlist, return ESP_FAIL);
esp_err_t ret = ESP_OK;
mutex_lock(handle->playlist_operate_lock);
playlist_info_t *cur_list = handle->cur_playlist;
playlist_operator_handle_t cur_handle = cur_list->list_handle;
playlist_operation_t operation = {0};
cur_handle->get_operation(&operation);
ret = operation.next(cur_handle, step, url_buff);
mutex_unlock(handle->playlist_operate_lock);
return ret;
}
esp_err_t playlist_prev(playlist_handle_t handle, int step, char **url_buff)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, handle->cur_playlist, return ESP_FAIL);
esp_err_t ret = ESP_OK;
mutex_lock(handle->playlist_operate_lock);
playlist_info_t *cur_list = handle->cur_playlist;
playlist_operator_handle_t cur_handle = cur_list->list_handle;
playlist_operation_t operation = {0};
cur_handle->get_operation(&operation);
ret = operation.prev(cur_handle, step, url_buff);
mutex_unlock(handle->playlist_operate_lock);
return ret;
}
esp_err_t playlist_choose(playlist_handle_t handle, int url_id, char **url_buff)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, handle->cur_playlist, return ESP_FAIL);
esp_err_t ret = ESP_OK;
mutex_lock(handle->playlist_operate_lock);
playlist_info_t *cur_list = handle->cur_playlist;
playlist_operator_handle_t cur_handle = cur_list->list_handle;
playlist_operation_t operation = {0};
cur_handle->get_operation(&operation);
ret = operation.choose(cur_handle, url_id, url_buff);
mutex_unlock(handle->playlist_operate_lock);
return ret;
}
esp_err_t playlist_save(playlist_handle_t handle, const char *url)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, handle->cur_playlist, return ESP_FAIL);
esp_err_t ret = ESP_OK;
mutex_lock(handle->playlist_operate_lock);
playlist_info_t *cur_list = handle->cur_playlist;
playlist_operator_handle_t cur_handle = cur_list->list_handle;
playlist_operation_t operation = {0};
cur_handle->get_operation(&operation);
ret = operation.save(cur_handle, url);
mutex_unlock(handle->playlist_operate_lock);
return ret;
}
esp_err_t playlist_reset(playlist_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, handle->cur_playlist, return ESP_FAIL);
esp_err_t ret = ESP_OK;
mutex_lock(handle->playlist_operate_lock);
playlist_info_t *cur_list = handle->cur_playlist;
playlist_operator_handle_t cur_handle = cur_list->list_handle;
playlist_operation_t operation = {0};
cur_handle->get_operation(&operation);
ret = operation.reset(cur_handle);
mutex_unlock(handle->playlist_operate_lock);
return ret;
}
bool playlist_exist(playlist_handle_t handle, const char *url)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, handle->cur_playlist, return ESP_FAIL);
mutex_lock(handle->playlist_operate_lock);
playlist_info_t *cur_list = handle->cur_playlist;
playlist_operator_handle_t cur_handle = cur_list->list_handle;
playlist_operation_t operation = {0};
cur_handle->get_operation(&operation);
bool ret = operation.exist(cur_handle, url);
mutex_unlock(handle->playlist_operate_lock);
return ret;
}
esp_err_t playlist_show(playlist_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, handle->cur_playlist, return ESP_FAIL);
esp_err_t ret = ESP_OK;
mutex_lock(handle->playlist_operate_lock);
playlist_info_t *cur_list = handle->cur_playlist;
playlist_operator_handle_t cur_handle = cur_list->list_handle;
playlist_operation_t operation = {0};
cur_handle->get_operation(&operation);
ret = operation.show(cur_handle);
mutex_unlock(handle->playlist_operate_lock);
return ret;
}
esp_err_t playlist_remove_by_url(playlist_handle_t handle, const char *url)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, handle->cur_playlist, return ESP_FAIL);
esp_err_t ret = ESP_OK;
mutex_lock(handle->playlist_operate_lock);
playlist_info_t *cur_list = handle->cur_playlist;
playlist_operator_handle_t cur_handle = cur_list->list_handle;
playlist_operation_t operation = {0};
cur_handle->get_operation(&operation);
if (operation.remove_by_url) {
ret = operation.remove_by_url(cur_handle, url);
} else {
ESP_LOGE(TAG, "Remove by url only can be use in dram list now");
mutex_unlock(handle->playlist_operate_lock);
return ESP_ERR_NOT_SUPPORTED;
}
mutex_unlock(handle->playlist_operate_lock);
return ret;
}
esp_err_t playlist_remove_by_url_id(playlist_handle_t handle, uint16_t url_id)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, handle->cur_playlist, return ESP_FAIL);
esp_err_t ret = ESP_OK;
mutex_lock(handle->playlist_operate_lock);
playlist_info_t *cur_list = handle->cur_playlist;
playlist_operator_handle_t cur_handle = cur_list->list_handle;
playlist_operation_t operation = {0};
cur_handle->get_operation(&operation);
if (operation.remove_by_id) {
ret = operation.remove_by_id(cur_handle, url_id);
} else {
ESP_LOGE(TAG, "Remove by url id only can be use in dram list now");
mutex_unlock(handle->playlist_operate_lock);
return ESP_ERR_NOT_SUPPORTED;
}
mutex_unlock(handle->playlist_operate_lock);
return ret;
}
esp_err_t playlist_destroy(playlist_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
esp_err_t ret = ESP_OK;
mutex_lock(handle->playlist_operate_lock);
playlist_info_t *item, *tmp;
playlist_operation_t operation = {0};
playlist_operator_handle_t cur_handle = NULL;
STAILQ_FOREACH_SAFE(item, &handle->playlist_info_list, entries, tmp) {
cur_handle = item->list_handle;
ret |= cur_handle->get_operation(&operation);
ret |= operation.destroy(cur_handle);
STAILQ_REMOVE(&handle->playlist_info_list, item, playlist_info, entries);
audio_free(item);
}
mutex_unlock(handle->playlist_operate_lock);
mutex_destroy(handle->playlist_operate_lock);
audio_free(handle);
ESP_LOGW(TAG, "Handle of playlists has been destroyed");
return ret;
}
esp_err_t playlist_add(playlist_handle_t handle, playlist_operator_handle_t list_handle, uint8_t list_id)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, list_handle, return ESP_FAIL);
esp_err_t ret = ESP_OK;
mutex_lock(handle->playlist_operate_lock);
playlist_info_t *tmp = NULL;
STAILQ_FOREACH(tmp, &handle->playlist_info_list, entries) {
if (tmp->list_id == list_id) {
ESP_LOGE(TAG, "This id has been registered, id: %d", tmp->list_id);
mutex_unlock(handle->playlist_operate_lock);
return ESP_FAIL;
}
}
playlist_info_t *list_node = audio_calloc(1, sizeof(playlist_info_t));
AUDIO_NULL_CHECK(TAG, list_node, {
mutex_unlock(handle->playlist_operate_lock);
return ESP_FAIL;
});
list_node->list_handle = list_handle;
list_node->list_id = list_id;
STAILQ_INSERT_TAIL(&handle->playlist_info_list, list_node, entries);
handle->list_num ++;
if (NULL == handle->cur_playlist) {
ESP_LOGD(TAG, "Set the first node as current playlist");
handle->cur_playlist = list_node;
}
mutex_unlock(handle->playlist_operate_lock);
return ret;
}
esp_err_t playlist_checkout_by_id(playlist_handle_t handle, uint8_t id)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
mutex_lock(handle->playlist_operate_lock);
playlist_info_t *tmp = NULL;
STAILQ_FOREACH(tmp, &handle->playlist_info_list, entries) {
if (tmp->list_id == id) {
handle->cur_playlist = tmp;
mutex_unlock(handle->playlist_operate_lock);
ESP_LOGW(TAG, "checkout to another playlist, ID: %d, TYPE: %d", tmp->list_id, playlist_get_current_list_type(handle));
return ESP_OK;
}
}
ESP_LOGE(TAG, "Can not find id %d", id);
mutex_unlock(handle->playlist_operate_lock);
return ESP_FAIL;
}
int playlist_get_list_num(playlist_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return -1);
mutex_lock(handle->playlist_operate_lock);
int num = handle->list_num;
mutex_unlock(handle->playlist_operate_lock);
return num;
}
int playlist_get_current_list_id(playlist_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return -1);
AUDIO_NULL_CHECK(TAG, handle->cur_playlist, return -1);
mutex_lock(handle->playlist_operate_lock);
playlist_info_t *tmp = handle->cur_playlist;
mutex_unlock(handle->playlist_operate_lock);
return tmp->list_id;
}
playlist_type_t playlist_get_current_list_type(playlist_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return -1);
AUDIO_NULL_CHECK(TAG, handle->cur_playlist, return -1);
mutex_lock(handle->playlist_operate_lock);
playlist_info_t *cur_list = handle->cur_playlist;
playlist_operator_handle_t cur_handle = cur_list->list_handle;
playlist_operation_t operation = {0};
cur_handle->get_operation(&operation);
mutex_unlock(handle->playlist_operate_lock);
return operation.type;
}
esp_err_t playlist_get_current_list_url(playlist_handle_t handle, char **url_buff)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, handle->cur_playlist, return ESP_FAIL);
esp_err_t ret = ESP_OK;
mutex_lock(handle->playlist_operate_lock);
playlist_info_t *cur_list = handle->cur_playlist;
playlist_operator_handle_t cur_handle = cur_list->list_handle;
playlist_operation_t operation = {0};
cur_handle->get_operation(&operation);
ret = operation.current(cur_handle, url_buff);
mutex_unlock(handle->playlist_operate_lock);
return ret;
}
int playlist_get_current_list_url_num(playlist_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, handle->cur_playlist, return ESP_FAIL);
mutex_lock(handle->playlist_operate_lock);
playlist_info_t *cur_list = handle->cur_playlist;
playlist_operator_handle_t cur_handle = cur_list->list_handle;
playlist_operation_t operation = {0};
cur_handle->get_operation(&operation);
int ret = operation.get_url_num(cur_handle);
mutex_unlock(handle->playlist_operate_lock);
return ret;
}
int playlist_get_current_list_url_id(playlist_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, handle->cur_playlist, return ESP_FAIL);
mutex_lock(handle->playlist_operate_lock);
playlist_info_t *cur_list = handle->cur_playlist;
playlist_operator_handle_t cur_handle = cur_list->list_handle;
playlist_operation_t operation = {0};
cur_handle->get_operation(&operation);
int ret = operation.get_url_id(cur_handle);;
mutex_unlock(handle->playlist_operate_lock);
return ret;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/playlist/playlist.c
|
C
|
apache-2.0
| 13,965
|
/*
* 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 "sys/queue.h"
#include "audio_error.h"
#include "audio_mem.h"
#include "dram_list.h"
static const char *TAG = "DRAM_LIST";
/**
* @brief List node save URL
*/
typedef struct url_info {
char *url_name; /*!< URL string */
int url_id;
TAILQ_ENTRY(url_info) entries; /*!< list node */
} url_info_t;
/**
* @brief Dram list management unit
*/
typedef struct dram_list {
uint16_t url_num; /*!< Number of URLs in dram playlist */
url_info_t *cur_node; /*!< Current node of URL on dram list */
TAILQ_HEAD(info, url_info) url_info_list; /*!< List of URL nodes */
} dram_list_t;
esp_err_t dram_list_get_operation(playlist_operation_t *operation);
esp_err_t dram_list_create(playlist_operator_handle_t *handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
playlist_operator_handle_t dram_handle = (playlist_operator_handle_t )audio_calloc(1, sizeof(playlist_operator_t));
AUDIO_NULL_CHECK(TAG, dram_handle, return ESP_FAIL);
dram_list_t *dram_list = (dram_list_t *) audio_calloc(1, sizeof(dram_list_t));
AUDIO_NULL_CHECK(TAG, dram_list, {
audio_free(dram_handle);
return ESP_FAIL;
});
dram_handle->playlist = dram_list;
dram_handle->get_operation = dram_list_get_operation;
TAILQ_INIT(&dram_list->url_info_list);
*handle = dram_handle;
return ESP_OK;
}
esp_err_t dram_list_save(playlist_operator_handle_t handle, const char *url)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, url, return ESP_FAIL);
size_t url_len = strlen(url);
dram_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
url_info_t *list_node = (url_info_t *)audio_calloc(1, sizeof(url_info_t));
AUDIO_NULL_CHECK(TAG, list_node, return ESP_FAIL);
list_node->url_name = (char *)audio_calloc(1, url_len + 1);
list_node->url_id = playlist->url_num;
AUDIO_NULL_CHECK(TAG, list_node->url_name, {
audio_free(list_node);
list_node = NULL;
return ESP_FAIL;
});
#if defined(__GNUC__) && (__GNUC__ >= 6)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstringop-truncation"
strncpy(list_node->url_name, url, url_len); // causes compilation warning although the extra byte is accounted for in the calloc
#pragma GCC diagnostic pop
#endif
TAILQ_INSERT_TAIL(&playlist->url_info_list, list_node, entries);
if (NULL == playlist->cur_node) {
ESP_LOGD(TAG, "Set the first url as the default url");
playlist->cur_node = list_node;
}
playlist->url_num ++;
return ESP_OK;
}
esp_err_t dram_list_next(playlist_operator_handle_t handle, int step, char **url_buff)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, url_buff, return ESP_FAIL);
dram_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
if (playlist->url_num == 0) {
ESP_LOGE(TAG, "Please add urls to playlist first");
return ESP_FAIL;
}
if (step < 0) {
ESP_LOGE(TAG, "Number of steps should be larger than 0");
return ESP_FAIL;
}
url_info_t *tmp = playlist->cur_node;
for (int i = 0; i < step; i++) {
tmp = TAILQ_NEXT(playlist->cur_node, entries);
if (tmp == NULL) {
ESP_LOGD(TAG, "Already the last url of the playlist");
tmp = TAILQ_FIRST(&playlist->url_info_list);
}
playlist->cur_node = tmp;
}
*url_buff = tmp->url_name;
return ESP_OK;
}
esp_err_t dram_list_prev(playlist_operator_handle_t handle, int step, char **url_buff)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, url_buff, return ESP_FAIL);
dram_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
if (playlist->url_num == 0) {
ESP_LOGE(TAG, "Please add urls to playlist first");
return ESP_FAIL;
}
if (step < 0) {
ESP_LOGE(TAG, "Number of steps should be larger than 0");
return ESP_FAIL;
}
url_info_t *tmp = playlist->cur_node;
for (int i = 0; i < step; i++) {
tmp = TAILQ_PREV(playlist->cur_node, info, entries);
if (tmp == NULL) {
ESP_LOGD(TAG, "Already the first url of the playlist");
tmp = TAILQ_LAST(&playlist->url_info_list, info);
}
playlist->cur_node = tmp;
}
*url_buff = tmp->url_name;
return ESP_OK;
}
esp_err_t dram_list_current(playlist_operator_handle_t handle, char **url_buff)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, url_buff, return ESP_FAIL);
dram_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
if (playlist->url_num == 0) {
ESP_LOGE(TAG, "Please add urls to playlist first");
return ESP_FAIL;
}
url_info_t *cur_node = playlist->cur_node;
*url_buff = cur_node->url_name;
return ESP_OK;
}
esp_err_t dram_list_choose(playlist_operator_handle_t handle, int url_id, char **url_buff)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, url_buff, return ESP_FAIL);
dram_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
if (playlist->url_num == 0) {
ESP_LOGE(TAG, "Please add urls tp playlist first");
return ESP_FAIL;
}
if ((url_id < 0) || (url_id >= playlist->url_num)) {
ESP_LOGE(TAG, "Invalid url id to be choosen");
return ESP_FAIL;
}
// rewind pointer
playlist->cur_node = TAILQ_FIRST(&playlist->url_info_list);
return dram_list_next(handle, url_id, url_buff);
}
esp_err_t dram_list_show(playlist_operator_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
dram_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
url_info_t *item, *tmp;
TAILQ_FOREACH_SAFE(item, &playlist->url_info_list, entries, tmp) {
ESP_LOGI(TAG, "URL: %s", item->url_name);
}
return ESP_OK;
}
bool dram_list_exist(playlist_operator_handle_t handle, const char *url)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
dram_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
url_info_t *item, *tmp;
TAILQ_FOREACH_SAFE(item, &playlist->url_info_list, entries, tmp) {
if (strlen(url) != strlen(item->url_name)) {
continue;
}
if (strcmp(item->url_name, url) == 0) {
return true;
}
}
return false;
}
esp_err_t dram_list_reset(playlist_operator_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
dram_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
url_info_t *item, *tmp;
TAILQ_FOREACH_SAFE(item, &playlist->url_info_list, entries, tmp) {
audio_free(item->url_name);
item->url_name = NULL;
TAILQ_REMOVE(&playlist->url_info_list, item, entries);
audio_free(item);
item = NULL;
}
playlist->url_num = 0;
return ESP_OK;
}
int dram_list_get_url_num(playlist_operator_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
dram_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
return playlist->url_num;
}
int dram_list_get_url_id(playlist_operator_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
dram_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
if (playlist->url_num == 0) {
ESP_LOGE(TAG, "Please add urls to playlist first");
return ESP_FAIL;
}
url_info_t *cur_node = playlist->cur_node;
return cur_node->url_id;
}
esp_err_t dram_list_remove_by_url(playlist_operator_handle_t handle, const char *url)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
dram_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
bool _find_flag = false;
url_info_t *item, *tmp;
TAILQ_FOREACH_SAFE(item, &playlist->url_info_list, entries, tmp) {
if (strlen(url) != strlen(item->url_name)) {
continue;
}
if (strcmp(url, item->url_name) == 0) {
audio_free(item->url_name);
item->url_name = NULL;
TAILQ_REMOVE(&playlist->url_info_list, item, entries);
audio_free(item);
item = NULL;
playlist->url_num--;
_find_flag = true;
continue;
}
if (_find_flag) {
item->url_id--;
}
}
if (_find_flag) {
return ESP_OK;
} else {
ESP_LOGE(TAG, "Cannot find the url, fail to remove");
return ESP_ERR_NOT_FOUND;
}
}
esp_err_t dram_list_remove_by_url_id(playlist_operator_handle_t handle, uint16_t url_id)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
dram_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
bool _find_flag = false;
url_info_t *item, *tmp;
TAILQ_FOREACH_SAFE(item, &playlist->url_info_list, entries, tmp) {
if (item->url_id == url_id) {
audio_free(item->url_name);
item->url_name = NULL;
TAILQ_REMOVE(&playlist->url_info_list, item, entries);
audio_free(item);
item = NULL;
playlist->url_num--;
_find_flag = true;
continue;
}
if (_find_flag) {
item->url_id--;
}
}
if (_find_flag) {
return ESP_OK;
} else {
ESP_LOGE(TAG, "Cannot find the url id, fail to remove");
return ESP_ERR_NOT_FOUND;
}
}
esp_err_t dram_list_destroy(playlist_operator_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
dram_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
url_info_t *item, *tmp;
TAILQ_FOREACH_SAFE(item, &playlist->url_info_list, entries, tmp) {
audio_free(item->url_name);
item->url_name = NULL;
TAILQ_REMOVE(&playlist->url_info_list, item, entries);
audio_free(item);
item = NULL;
}
audio_free(playlist);
handle->playlist = NULL;
audio_free(handle);
return ESP_OK;
}
esp_err_t dram_list_get_operation(playlist_operation_t *operation)
{
AUDIO_NULL_CHECK(TAG, operation, return ESP_FAIL);
operation->show = (void *)dram_list_show;
operation->save = (void *)dram_list_save;
operation->next = (void *)dram_list_next;
operation->prev = (void *)dram_list_prev;
operation->reset = (void *)dram_list_reset;
operation->exist = (void *)dram_list_exist;
operation->current = (void *)dram_list_current;
operation->destroy = (void *)dram_list_destroy;
operation->choose = (void *)dram_list_choose;
operation->get_url_num = (void *)dram_list_get_url_num;
operation->get_url_id = (void *)dram_list_get_url_id;
operation->remove_by_url = (void *)dram_list_remove_by_url;
operation->remove_by_id = (void *)dram_list_remove_by_url_id;
operation->type = PLAYLIST_DRAM;
return ESP_OK;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/playlist/playlist_operator/dram_list.c
|
C
|
apache-2.0
| 12,586
|
/*
* 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 "audio_error.h"
#include "audio_mem.h"
#include "flash_list.h"
#include "nvs_flash.h"
#define DEFAULT_NVS_NAME_SPACE "NVS"
#define NVS_NAME_SPACE_MAX_LENGTH 16
#define NVS_FLASH_URL_MAX_LENGTH 2048
static const char *TAG = "FLASH_LIST";
/**
* @brief Nvs flash list management unit
*/
typedef struct flash_list {
char *name_space; /*!< nvs name space */
nvs_handle url_nvs_handle; /*!< nvs handle */
uint16_t url_num; /*!< number of URLs */
int16_t cur_url_id; /*!< current URL id */
char *cur_url; /*!< point to current URL */
} flash_list_t;
esp_err_t flash_list_get_operation(playlist_operation_t *operation);
static esp_err_t flash_list_choose_id(flash_list_t *playlist, int id, char **url_buff)
{
esp_err_t ret = ESP_OK;
if (playlist->cur_url) {
audio_free(playlist->cur_url);
}
playlist->cur_url = (char *)audio_calloc(1, NVS_FLASH_URL_MAX_LENGTH);
AUDIO_NULL_CHECK(TAG, playlist->cur_url, {
ESP_LOGE(TAG, "Allocate memory failed!");
return ESP_FAIL;
});
size_t len = NVS_FLASH_URL_MAX_LENGTH;
ret = nvs_get_str(playlist->url_nvs_handle, (const char *)&id, playlist->cur_url, &len);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Flash list choose url id failed");
return ESP_FAIL;
}
*url_buff = playlist->cur_url;
playlist->cur_url_id = id;
return ESP_OK;
}
esp_err_t flash_list_create(playlist_operator_handle_t *handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES) {
// NVS partition was truncated and needs to be erased
// Retry nvs_flash_init
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
static int list_id;
playlist_operator_handle_t flash_handle = (playlist_operator_handle_t )audio_calloc(1, sizeof(playlist_operator_t));
AUDIO_NULL_CHECK(TAG, flash_handle, return ESP_FAIL);
flash_list_t *flash_list = (flash_list_t *)audio_calloc(1, sizeof(flash_list_t));
AUDIO_NULL_CHECK(TAG, flash_list, {
audio_free(flash_handle);
return ESP_FAIL;
});
flash_handle->playlist = flash_list;
flash_handle->get_operation = flash_list_get_operation;
flash_list->name_space = audio_calloc(1, NVS_NAME_SPACE_MAX_LENGTH);
AUDIO_NULL_CHECK(TAG, flash_list, {
audio_free(flash_handle);
audio_free(flash_list);
return ESP_FAIL;
});
sprintf(flash_list->name_space, "%s%d", DEFAULT_NVS_NAME_SPACE, list_id++);
ret |= nvs_open(flash_list->name_space, NVS_READWRITE, &flash_list->url_nvs_handle);
if (ret != ESP_OK) {
audio_free(flash_handle);
audio_free(flash_list->name_space);
audio_free(flash_list);
ESP_LOGE(TAG, "Flash playlist open failed, please check");
}
*handle = flash_handle;
return ESP_OK;
}
esp_err_t flash_list_save(playlist_operator_handle_t handle, const char *url)
{
esp_err_t ret = ESP_OK;
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, url, return ESP_FAIL);
if (strlen(url) >= NVS_FLASH_URL_MAX_LENGTH - 1) {
ESP_LOGE(TAG, "The URL is too long to save, please change the NVS_FLASH_URL_MAX_LENGTH and retry");
return ESP_FAIL;
}
flash_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
ret |= nvs_set_str(playlist->url_nvs_handle, (const char *)&playlist->url_num, url);
ret |= nvs_commit(playlist->url_nvs_handle);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Flash save url failed, URL: %s, ret: %d", url, ret);
return ESP_FAIL;
}
playlist->url_num ++;
return ESP_OK;
}
esp_err_t flash_list_show(playlist_operator_handle_t handle)
{
esp_err_t ret = ESP_OK;
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
flash_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
size_t len = NVS_FLASH_URL_MAX_LENGTH;
char *out_str = audio_calloc(1, NVS_FLASH_URL_MAX_LENGTH);
for (int i = 0; i < playlist->url_num; i++) {
memset(out_str, 0, NVS_FLASH_URL_MAX_LENGTH);
len = NVS_FLASH_URL_MAX_LENGTH;
ret = nvs_get_str(playlist->url_nvs_handle, (const char *)&i, out_str, &len);
ESP_LOGI(TAG, "ID:%d URL: %s", i, out_str);
}
audio_free(out_str);
return ret;
}
esp_err_t flash_list_next(playlist_operator_handle_t handle, int step, char **url_buff)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, url_buff, return ESP_FAIL);
flash_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
if (playlist->url_num == 0) {
ESP_LOGE(TAG, "No url, please save urls to playlist first");
return ESP_FAIL;
}
if (step < 0) {
ESP_LOGE(TAG, "Steps should be larger than 0");
return ESP_FAIL;
}
int id = 0, total_step = 0;
total_step = playlist->cur_url_id + step;
id = total_step;
if (total_step >= playlist->url_num) {
id = total_step % playlist->url_num;
}
return flash_list_choose_id(playlist, id, url_buff);
}
esp_err_t flash_list_prev(playlist_operator_handle_t handle, int step, char **url_buff)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, url_buff, return ESP_FAIL);
flash_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
if (playlist->url_num == 0) {
ESP_LOGE(TAG, "No url, please save urls to playlist first");
return ESP_FAIL;
}
if (step < 0) {
ESP_LOGE(TAG, "Steps should be larger than 0");
return ESP_FAIL;
}
int id = 0, total_step = 0;
total_step = playlist->cur_url_id - step;
id = total_step;
if (total_step < 0) {
if (total_step % playlist->url_num == 0) {
id = 0;
} else {
id = playlist->url_num + total_step % playlist->url_num;
}
}
return flash_list_choose_id(playlist, id, url_buff);
}
esp_err_t flash_list_current(playlist_operator_handle_t handle, char **url_buff)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
flash_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
if (NULL == playlist || NULL == url_buff) {
ESP_LOGE(TAG, "Invalid parameters, line: %d, func:%s", __LINE__, __FUNCTION__);
return ESP_FAIL;
}
if (playlist->url_num == 0) {
ESP_LOGE(TAG, "No url, please save urls to playlist first");
return ESP_FAIL;
}
return flash_list_choose_id(playlist, playlist->cur_url_id, url_buff);
}
esp_err_t flash_list_choose(playlist_operator_handle_t handle, int url_id, char **url_buff)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, url_buff, return ESP_FAIL);
flash_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
if (playlist->url_num == 0) {
ESP_LOGE(TAG, "No url, please save urls to playlist first");
return ESP_FAIL;
}
if ((url_id < 0) || (url_id >= playlist->url_num)) {
ESP_LOGE(TAG, "Invalid url id to be choosen");
return ESP_FAIL;
}
return flash_list_choose_id(playlist, url_id, url_buff);
}
esp_err_t flash_list_reset(playlist_operator_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
flash_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
nvs_erase_all(playlist->url_nvs_handle);
if (playlist->cur_url) {
audio_free(playlist->cur_url);
playlist->cur_url = NULL;
}
playlist->cur_url_id = 0;
playlist->url_num = 0;
return ESP_OK;
}
bool flash_list_exist(playlist_operator_handle_t handle, const char *url)
{
esp_err_t ret = ESP_OK;
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
flash_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
size_t len = NVS_FLASH_URL_MAX_LENGTH;
char *out_str = audio_calloc(1, NVS_FLASH_URL_MAX_LENGTH);
for (int i = 0; i < playlist->url_num; i++) {
memset(out_str, 0, NVS_FLASH_URL_MAX_LENGTH);
len = NVS_FLASH_URL_MAX_LENGTH;
ret = nvs_get_str(playlist->url_nvs_handle, (const char *)&i, out_str, &len);
if (strlen(url) != strlen(out_str)) {
continue;
}
if (strcmp(url, out_str) == 0) {
audio_free(out_str);
return true;
}
}
audio_free(out_str);
return ret;
}
int flash_list_get_url_num(playlist_operator_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
flash_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
return playlist->url_num;
}
int flash_list_get_url_id(playlist_operator_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
flash_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
return playlist->cur_url_id;
}
esp_err_t flash_list_destroy(playlist_operator_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
flash_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
nvs_erase_all(playlist->url_nvs_handle);
nvs_close(playlist->url_nvs_handle);
audio_free(playlist->name_space);
playlist->name_space = NULL;
if (playlist->cur_url) {
audio_free(playlist->cur_url);
playlist->cur_url = NULL;
}
audio_free(playlist);
handle->playlist = NULL;
audio_free(handle);
return ESP_OK;
}
esp_err_t flash_list_get_operation(playlist_operation_t *operation)
{
AUDIO_NULL_CHECK(TAG, operation, return ESP_FAIL);
operation->show = (void *)flash_list_show;
operation->save = (void *)flash_list_save;
operation->next = (void *)flash_list_next;
operation->prev = (void *)flash_list_prev;
operation->reset = (void *)flash_list_reset;
operation->exist = (void *)flash_list_exist;
operation->current = (void *)flash_list_current;
operation->choose = (void *)flash_list_choose;
operation->destroy = (void *)flash_list_destroy;
operation->get_url_num = (void *)flash_list_get_url_num;
operation->get_url_id = (void *)flash_list_get_url_id;
operation->type = PLAYLIST_FLASH;
return ESP_OK;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/playlist/playlist_operator/flash_list.c
|
C
|
apache-2.0
| 11,798
|
/*
* 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 "esp_partition.h"
#include "audio_mem.h"
#include "audio_error.h"
#include "partition_list.h"
#define DEFAULT_PARTITION_TYPE ESP_PARTITION_TYPE_DATA
#define DEFAULT_PARTITION_URL_SUB_TYPE 0x06
#define DEFAULT_PARTITION_OFFSET_SUB_TYPE 0x07
#define PARTITION_LIST_URL_MAX_LENGTH 2048
static const char *TAG = "PARTITION_LIST";
/**
* @brief Partition list management unit
*/
typedef struct partition_list {
const esp_partition_t *url_part; /*!< URL partition handle */
const esp_partition_t *offset_part; /*!< offset partition handle */
uint16_t url_num; /*!< number of URLs */
uint16_t cur_url_id; /*!< current URL id */
uint32_t total_size_offset_part; /*!< size of partition to save URLs */
uint32_t total_size_url_part; /*!< size of partition to save offset */
char *cur_url; /*!< point to current URL */
} partition_list_t;
esp_err_t partition_list_get_operation(playlist_operation_t *operation);
static esp_err_t partition_list_choose_id(partition_list_t *playlist, int id, char **url_buff)
{
esp_err_t ret = ESP_OK;
uint32_t pos = 0;
uint16_t size = 0;
int offset = id * (sizeof(uint32_t) + sizeof(uint16_t));
ret |= esp_partition_read(playlist->offset_part, offset, &pos, sizeof(uint32_t));
ret |= esp_partition_read(playlist->offset_part, offset + sizeof(uint32_t), &size, sizeof(uint16_t));
if (playlist->cur_url) {
audio_free(playlist->cur_url);
}
playlist->cur_url = (char *)audio_calloc(1, size + 1);
AUDIO_NULL_CHECK(TAG, playlist->cur_url, {
ESP_LOGE(TAG, "Fail to allocate memory for url");
return ESP_FAIL;
});
ret |= esp_partition_read(playlist->url_part, pos, playlist->cur_url, size);
playlist->cur_url[size] = 0;
if (ret != ESP_OK) {
ESP_LOGE(TAG, "There is a mistake when choose id in partition playlist!");
return ESP_FAIL;
}
*url_buff = playlist->cur_url;
playlist->cur_url_id = id;
return ESP_OK;
}
esp_err_t partition_list_create(playlist_operator_handle_t *handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
playlist_operator_handle_t partition_handle = (playlist_operator_handle_t )audio_calloc(1, sizeof(playlist_operator_t));
AUDIO_NULL_CHECK(TAG, partition_handle, return ESP_FAIL);
partition_list_t *partition_list = audio_calloc(1, sizeof(partition_list_t));
AUDIO_NULL_CHECK(TAG, partition_list, {
audio_free(partition_handle);
});
partition_handle->playlist = partition_list;
partition_handle->get_operation = partition_list_get_operation;
esp_err_t ret = ESP_OK;
partition_list->url_part = esp_partition_find_first(DEFAULT_PARTITION_TYPE, DEFAULT_PARTITION_URL_SUB_TYPE, NULL);
partition_list->offset_part = esp_partition_find_first(DEFAULT_PARTITION_TYPE, DEFAULT_PARTITION_OFFSET_SUB_TYPE, NULL);
if (NULL == partition_list->url_part || NULL == partition_list->offset_part) {
ESP_LOGE(TAG, "Can not find the offset partition or url partition, please check the partition table");
audio_free(partition_handle);
audio_free(partition_list);
return ESP_FAIL;
}
const esp_partition_t *url_part = partition_list->url_part;
const esp_partition_t *offset_part = partition_list->offset_part;
ret |= esp_partition_erase_range(url_part, 0, url_part->size);
ret |= esp_partition_erase_range(offset_part, 0, url_part->size);
*handle = partition_handle;
return ret;
}
esp_err_t partition_list_save(playlist_operator_handle_t handle, const char *url)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, url, return ESP_FAIL);
partition_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
esp_err_t ret = ESP_OK;
uint16_t len = strlen(url);
ret |= esp_partition_write(playlist->offset_part, playlist->total_size_offset_part, &playlist->total_size_url_part, sizeof(uint32_t));
playlist->total_size_offset_part += sizeof(uint32_t);
ret |= esp_partition_write(playlist->offset_part, playlist->total_size_offset_part, &len, sizeof(uint16_t));
playlist->total_size_offset_part += sizeof(uint16_t);
ret |= esp_partition_write(playlist->url_part, playlist->total_size_url_part, url, len);
playlist->total_size_url_part += len;
if (ret != ESP_OK) {
playlist->total_size_offset_part -= (sizeof(uint32_t) + sizeof(uint16_t));
playlist->total_size_url_part -= len;
ESP_LOGE(TAG, "Failed to save URL to partition list ");
return ESP_FAIL;
}
playlist->url_num++;
return ESP_OK;
}
esp_err_t partition_list_next(playlist_operator_handle_t handle, int step, char **url_buff)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, url_buff, return ESP_FAIL);
partition_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
if (playlist->url_num == 0) {
ESP_LOGE(TAG, "No url, please save urls to playlist first");
return ESP_FAIL;
}
if (step < 0) {
ESP_LOGE(TAG, "Number of steps should be larger than 0");
return ESP_FAIL;
}
int id = 0, total_step = 0;
total_step = playlist->cur_url_id + step;
id = total_step;
if (total_step >= playlist->url_num) {
id = total_step % playlist->url_num;
}
return partition_list_choose_id(playlist, id, url_buff);
}
esp_err_t partition_list_prev(playlist_operator_handle_t handle, int step, char **url_buff)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, url_buff, return ESP_FAIL);
partition_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
if (playlist->url_num == 0) {
ESP_LOGE(TAG, "No url, please save urls to playlist first");
return ESP_FAIL;
}
if (step < 0) {
ESP_LOGE(TAG, "Number of steps should be larger than 0");
return ESP_FAIL;
}
int id = 0, total_step = 0;
total_step = playlist->cur_url_id - step;
id = total_step;
if (total_step < 0) {
if (total_step % playlist->url_num == 0) {
id = 0;
} else {
id = playlist->url_num + total_step % playlist->url_num;
}
}
return partition_list_choose_id(playlist, id, url_buff);
}
esp_err_t partition_list_current(playlist_operator_handle_t handle, char **url_buff)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, url_buff, return ESP_FAIL);
partition_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
if (playlist->url_num == 0) {
ESP_LOGE(TAG, "No url, please save urls to playlist first");
return ESP_FAIL;
}
return partition_list_choose_id(playlist, playlist->cur_url_id, url_buff);
}
esp_err_t partition_list_choose(playlist_operator_handle_t handle, int url_id, char **url_buff)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, url_buff, return ESP_FAIL);
partition_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
if (playlist->url_num == 0) {
ESP_LOGE(TAG, "No url, please save urls to playlist first");
return ESP_FAIL;
}
if ((url_id < 0) || (url_id >= playlist->url_num)) {
ESP_LOGE(TAG, "Invalid url id to be choosen");
return ESP_FAIL;
}
return partition_list_choose_id(playlist, url_id, url_buff);
}
esp_err_t partition_list_show(playlist_operator_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
partition_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
esp_err_t ret = ESP_OK;
uint32_t pos = 0, offset = 0;
uint16_t size = 0;
char *url = audio_calloc(1, PARTITION_LIST_URL_MAX_LENGTH);
ESP_LOGI(TAG, "ID URL");
for (int i = 0; i < playlist->url_num; i++) {
memset(url, 0, PARTITION_LIST_URL_MAX_LENGTH);
ret |= esp_partition_read(playlist->offset_part, offset, &pos, sizeof(uint32_t));
offset += sizeof(uint32_t);
ret |= esp_partition_read(playlist->offset_part, offset, &size, sizeof(uint16_t));
offset += sizeof(uint16_t);
ret |= esp_partition_read(playlist->url_part, pos, url, size);
ESP_LOGI(TAG, "%d %s", i, url);
}
audio_free(url);
return ret;
}
bool partition_list_exist(playlist_operator_handle_t handle, const char *url)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
partition_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
esp_err_t ret = ESP_OK;
uint32_t pos = 0, offset = 0;
uint16_t size = 0;
char *url_buff = audio_calloc(1, PARTITION_LIST_URL_MAX_LENGTH);
for (int i = 0; i < playlist->url_num; i++) {
memset(url_buff, 0, PARTITION_LIST_URL_MAX_LENGTH);
ret |= esp_partition_read(playlist->offset_part, offset, &pos, sizeof(uint32_t));
offset += sizeof(uint32_t);
ret |= esp_partition_read(playlist->offset_part, offset, &size, sizeof(uint16_t));
offset += sizeof(uint16_t);
ret |= esp_partition_read(playlist->url_part, pos, url_buff, size);
if (strlen(url) != strlen(url_buff)) {
continue;
}
if (strcmp(url, url_buff) == 0) {
audio_free(url_buff);
return true;
}
}
audio_free(url_buff);
return false;
}
esp_err_t partition_list_reset(playlist_operator_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
partition_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
esp_err_t ret = ESP_OK;
const esp_partition_t *url_part = playlist->url_part;
const esp_partition_t *offset_part = playlist->offset_part;
ret |= esp_partition_erase_range(url_part, 0, url_part->size);
ret |= esp_partition_erase_range(offset_part, 0, offset_part->size);
if (playlist->cur_url) {
audio_free(playlist->cur_url);
playlist->cur_url = NULL;
}
playlist->url_num = 0;
playlist->cur_url_id = 0;
playlist->total_size_offset_part = 0;
playlist->total_size_url_part = 0;
return ret;
}
int partition_list_get_url_num(playlist_operator_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
partition_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
return playlist->url_num;
}
int partition_list_get_url_id(playlist_operator_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
partition_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
return playlist->cur_url_id;
}
esp_err_t partition_list_destroy(playlist_operator_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
partition_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
esp_err_t ret = ESP_OK;
const esp_partition_t *url_part = playlist->url_part;
const esp_partition_t *offset_part = playlist->offset_part;
ret |= esp_partition_erase_range(url_part, 0, url_part->size);
ret |= esp_partition_erase_range(offset_part, 0, offset_part->size);
if (playlist->cur_url) {
audio_free(playlist->cur_url);
playlist->cur_url = NULL;
}
audio_free(playlist);
handle->playlist = NULL;
audio_free(handle);
return ret;
}
esp_err_t partition_list_get_operation(playlist_operation_t *operation)
{
AUDIO_NULL_CHECK(TAG, operation, return ESP_FAIL);
operation->show = (void *)partition_list_show;
operation->save = (void *)partition_list_save;
operation->next = (void *)partition_list_next;
operation->prev = (void *)partition_list_prev;
operation->reset = (void *)partition_list_reset;
operation->exist = (void *)partition_list_exist;
operation->choose = (void *)partition_list_choose;
operation->current = (void *)partition_list_current;
operation->destroy = (void *)partition_list_destroy;
operation->get_url_num = (void *)partition_list_get_url_num;
operation->get_url_id = (void *)partition_list_get_url_id;
operation->type = PLAYLIST_PARTITION;
return ESP_OK;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/playlist/playlist_operator/partition_list.c
|
C
|
apache-2.0
| 13,730
|
/*
* 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 <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include "audio_error.h"
#include "audio_mem.h"
#include "sdcard_list.h"
#define SDCARD_DEFAULT_DIR_NAME "/sdcard/__playlist"
#define SDCARD_DEFAULT_URL_FILE_NAME "/sdcard/__playlist/_playlist_url"
#define SDCARD_DEFAULT_OFFSET_FILE_NAME "/sdcard/__playlist/_offset"
#define SDCARD_URL_FILE_NAME_LENGTH (strlen(SDCARD_DEFAULT_URL_FILE_NAME) + 10)
#define SDCARD_OFFSET_FILE_NAME_LENGTH (strlen(SDCARD_DEFAULT_OFFSET_FILE_NAME) + 10)
#define SDCARD_LIST_URL_MAX_LENGTH (1024 * 2)
#define CHECK_ERROR(TAG, para, action) {\
if ((para) == false) {\
ESP_LOGE(TAG, "unexpect action in sdcard list, line: %d", __LINE__);\
action;\
}\
}
static const char *TAG = "PLAYLIST_SDCARD";
/**
* @brief Sdcard list management unit
*/
typedef struct sdcard_list {
char *save_file_name; /*!< Name of file to save URLs */
char *offset_file_name; /*!< Name of file to save offset */
FILE *save_file; /*!< File to save urls */
FILE *offset_file; /*!< File to save offset of urls */
char *cur_url; /*!< Point to current URL */
uint16_t url_num; /*!< Number of URLs */
uint16_t cur_url_id; /*!< Current url ID */
uint32_t total_size_save_file; /*!< Size of file to save URLs */
uint32_t total_size_offset_file; /*!< Size of file to save offset */
} sdcard_list_t;
esp_err_t sdcard_list_get_operation(playlist_operation_t *operation);
static esp_err_t save_url_to_sdcard(sdcard_list_t *playlist, const char *path)
{
if (playlist->save_file == NULL || playlist->offset_file == NULL) {
ESP_LOGE(TAG, "The file to save playlist failed to open");
return ESP_FAIL;
}
uint16_t len = strlen(path);
CHECK_ERROR(TAG, ((fseek(playlist->offset_file, playlist->total_size_offset_file, SEEK_SET)) == 0), return ESP_FAIL);
CHECK_ERROR(TAG, ((fseek(playlist->save_file, playlist->total_size_save_file, SEEK_SET)) == 0), return ESP_FAIL);
CHECK_ERROR(TAG, (fwrite(path, 1, len, playlist->save_file) == len), return ESP_FAIL);
CHECK_ERROR(TAG, (fwrite(&playlist->total_size_save_file, 1, sizeof(uint32_t), playlist->offset_file) == sizeof(uint32_t)), return ESP_FAIL);
CHECK_ERROR(TAG, (fwrite(&len, 1, sizeof(uint16_t), playlist->offset_file)) == sizeof(uint16_t), return ESP_FAIL);
CHECK_ERROR(TAG, (fsync(fileno(playlist->save_file)) == 0), return ESP_FAIL);
CHECK_ERROR(TAG, (fsync(fileno(playlist->offset_file)) == 0), return ESP_FAIL);
playlist->total_size_save_file += len;
playlist->total_size_offset_file += (sizeof(uint16_t) + sizeof(uint32_t));
playlist->url_num++;
return ESP_OK;
}
static esp_err_t sdcard_list_open(sdcard_list_t *playlist, uint8_t list_id)
{
playlist->save_file_name = audio_calloc(1, SDCARD_URL_FILE_NAME_LENGTH);
AUDIO_NULL_CHECK(TAG, playlist->save_file_name, return ESP_FAIL);
playlist->offset_file_name = audio_calloc(1, SDCARD_OFFSET_FILE_NAME_LENGTH);
AUDIO_NULL_CHECK(TAG, playlist->offset_file_name, {
audio_free(playlist->save_file_name);
return ESP_FAIL;
});
sprintf(playlist->save_file_name, "%s%d", SDCARD_DEFAULT_URL_FILE_NAME, list_id);
sprintf(playlist->offset_file_name, "%s%d", SDCARD_DEFAULT_OFFSET_FILE_NAME, list_id);
mkdir(SDCARD_DEFAULT_DIR_NAME, 0777);
playlist->save_file = fopen(playlist->save_file_name, "w+");
playlist->offset_file = fopen(playlist->offset_file_name, "w+");
if (playlist->save_file == NULL || NULL == playlist->offset_file) {
ESP_LOGE(TAG, "open file error, line: %d, have you mounted sdcard, set the long file name and UTF-8 encoding configuration ?", __LINE__);
audio_free(playlist->save_file_name);
audio_free(playlist->offset_file_name);
if (playlist->save_file) {
fclose(playlist->save_file);
}
if (playlist->offset_file) {
fclose(playlist->offset_file);
}
return ESP_FAIL;
}
return ESP_OK;
}
static esp_err_t sdcard_list_close(sdcard_list_t *playlist)
{
fclose(playlist->offset_file);
fclose(playlist->save_file);
playlist->offset_file = NULL;
playlist->save_file = NULL;
return ESP_OK;
}
static esp_err_t sdcard_list_choose_id(sdcard_list_t *playlist, int id, char **url_buff)
{
uint32_t pos = 0;
uint16_t size = 0;
int offset = id * (sizeof(uint32_t) + sizeof(uint16_t));
CHECK_ERROR(TAG, ((fseek(playlist->offset_file, offset, SEEK_SET)) == 0), return ESP_FAIL);
CHECK_ERROR(TAG, ((fread(&pos, 1, sizeof(uint32_t), playlist->offset_file)) == sizeof(uint32_t)), return ESP_FAIL);
CHECK_ERROR(TAG, ((fread(&size, 1, sizeof(uint16_t), playlist->offset_file)) == sizeof(uint16_t)), return ESP_FAIL);
if (playlist->cur_url) {
audio_free(playlist->cur_url);
}
playlist->cur_url = (char *)audio_calloc(1, size + 1);
AUDIO_NULL_CHECK(TAG, playlist->cur_url, {
ESP_LOGE(TAG, "Fail to allocate memory for url");
fclose(playlist->offset_file);
fclose(playlist->save_file);
return ESP_FAIL;
});
CHECK_ERROR(TAG, ((fseek(playlist->save_file, pos, SEEK_SET)) == 0), return ESP_FAIL);
CHECK_ERROR(TAG, ((fread(playlist->cur_url, 1, size, playlist->save_file)) == size), return ESP_FAIL);
playlist->cur_url[size] = 0;
playlist->cur_url_id = id;
*url_buff = playlist->cur_url;
return ESP_OK;
}
esp_err_t sdcard_list_create(playlist_operator_handle_t *handle)
{
esp_err_t ret = ESP_OK;
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
playlist_operator_handle_t sdcard_handle = (playlist_operator_handle_t )audio_calloc(1, sizeof(playlist_operator_t));
AUDIO_NULL_CHECK(TAG, sdcard_handle, return ESP_FAIL);
sdcard_list_t *sdcard_list = (sdcard_list_t *)audio_calloc(1, sizeof(sdcard_list_t));
AUDIO_NULL_CHECK(TAG, sdcard_list, {
audio_free(sdcard_handle);
return ESP_FAIL;
});
sdcard_handle->playlist = sdcard_list;
sdcard_handle->get_operation = sdcard_list_get_operation;
static int list_id;
ret |= sdcard_list_open(sdcard_list, list_id++);
if (ret != ESP_OK) {
audio_free(sdcard_handle);
audio_free(sdcard_list);
return ESP_FAIL;
}
*handle = sdcard_handle;
return ESP_OK;
}
esp_err_t sdcard_list_show(playlist_operator_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
sdcard_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
uint32_t pos = 0;
uint16_t size = 0;
char *url = audio_calloc(1, SDCARD_LIST_URL_MAX_LENGTH);
CHECK_ERROR(TAG, (fseek(playlist->save_file, 0, SEEK_SET) == 0), return ESP_FAIL);
CHECK_ERROR(TAG, (fseek(playlist->offset_file, 0, SEEK_SET) == 0), return ESP_FAIL);
ESP_LOGI(TAG, "ID URL");
for (int i = 0; i < playlist->url_num; i++) {
memset(url, 0, SDCARD_LIST_URL_MAX_LENGTH);
CHECK_ERROR(TAG, (fread(&pos, 1, sizeof(uint32_t), playlist->offset_file) == sizeof(uint32_t)), return ESP_FAIL);
CHECK_ERROR(TAG, (fread(&size, 1, sizeof(uint16_t), playlist->offset_file) == sizeof(uint16_t)), return ESP_FAIL);
CHECK_ERROR(TAG, (fseek(playlist->save_file, pos, SEEK_SET) == 0), return ESP_FAIL);
CHECK_ERROR(TAG, (fread(url, 1, size, playlist->save_file) == size), return ESP_FAIL);
ESP_LOGI(TAG, "%d %s", i, url);
}
audio_free(url);
return ESP_OK;
}
esp_err_t sdcard_list_next(playlist_operator_handle_t handle, int step, char **url_buff)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, url_buff, return ESP_FAIL);
sdcard_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
if (playlist->url_num == 0) {
ESP_LOGE(TAG, "No url, please save urls to playlist first");
return ESP_FAIL;
}
if (step < 0) {
ESP_LOGE(TAG, "Step should be larger than 0");
return ESP_FAIL;
}
int id = 0, total_step = 0;
total_step = playlist->cur_url_id + step;
id = total_step;
if (total_step >= playlist->url_num) {
id = total_step % playlist->url_num;
}
return sdcard_list_choose_id(playlist, id, url_buff);
}
esp_err_t sdcard_list_prev(playlist_operator_handle_t handle, int step, char **url_buff)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, url_buff, return ESP_FAIL);
sdcard_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
if (playlist->url_num == 0) {
ESP_LOGE(TAG, "No url, please save urls to playlist first");
return ESP_FAIL;
}
if (step < 0) {
ESP_LOGE(TAG, "Steps should be larger than 0");
return ESP_FAIL;
}
int id = 0, total_step = 0;
total_step = playlist->cur_url_id - step;
id = total_step;
if (total_step < 0) {
if (total_step % playlist->url_num == 0) {
id = 0;
} else {
id = playlist->url_num + total_step % playlist->url_num;
}
}
return sdcard_list_choose_id(playlist, id, url_buff);
}
esp_err_t sdcard_list_current(playlist_operator_handle_t handle, char **url_buff)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, url_buff, return ESP_FAIL);
sdcard_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
if (playlist->url_num == 0) {
ESP_LOGE(TAG, "No url, please save urls to playlist first");
return ESP_FAIL;
}
return sdcard_list_choose_id(playlist, playlist->cur_url_id, url_buff);
}
esp_err_t sdcard_list_choose(playlist_operator_handle_t handle, int url_id, char **url_buff)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, url_buff, return ESP_FAIL);
sdcard_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
if (playlist->url_num == 0) {
ESP_LOGE(TAG, "No url, please save urls to playlist first");
return ESP_FAIL;
}
if ((url_id < 0) || (url_id >= playlist->url_num)) {
ESP_LOGE(TAG, "Invalid url id to be choosen");
return ESP_FAIL;
}
return sdcard_list_choose_id(playlist, url_id, url_buff);
}
esp_err_t sdcard_list_save(playlist_operator_handle_t handle, const char *url)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, url, return ESP_FAIL);
sdcard_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
esp_err_t ret = ESP_OK;
uint16_t len = strlen(url);
if (len >= SDCARD_LIST_URL_MAX_LENGTH) {
ESP_LOGE(TAG, "The url length is greater than MAX LENTGTH, you should change the SDCARD_LIST_URL_MAX_LENGTH value");
return ESP_FAIL;
}
ret = save_url_to_sdcard(playlist, url);
return ret;
}
bool sdcard_list_exist(playlist_operator_handle_t handle, const char *url)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
sdcard_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
uint32_t pos = 0;
uint16_t size = 0;
char *url_buff = audio_calloc(1, SDCARD_LIST_URL_MAX_LENGTH);
CHECK_ERROR(TAG, (fseek(playlist->save_file, 0, SEEK_SET) == 0), return ESP_FAIL);
CHECK_ERROR(TAG, (fseek(playlist->offset_file, 0, SEEK_SET) == 0), return ESP_FAIL);
for (int i = 0; i < playlist->url_num; i++) {
memset(url_buff, 0, SDCARD_LIST_URL_MAX_LENGTH);
CHECK_ERROR(TAG, (fread(&pos, 1, sizeof(uint32_t), playlist->offset_file) == sizeof(uint32_t)), return ESP_FAIL);
CHECK_ERROR(TAG, (fread(&size, 1, sizeof(uint16_t), playlist->offset_file) == sizeof(uint16_t)), return ESP_FAIL);
CHECK_ERROR(TAG, (fseek(playlist->save_file, pos, SEEK_SET) == 0), return ESP_FAIL);
CHECK_ERROR(TAG, (fread(url_buff, 1, size, playlist->save_file) == size), return ESP_FAIL);
if (strlen(url_buff) != strlen(url)) {
continue;
}
if (strcmp(url, url_buff) == 0) {
audio_free(url_buff);
return true;
}
}
audio_free(url_buff);
return false;
}
esp_err_t sdcard_list_reset(playlist_operator_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
sdcard_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
/**
* ftruncate() function is not supported now, it won't affect the operation result.
*
CHECK_ERROR(TAG, (ftruncate(playlist->save_file, 0) == ESP_OK), return ESP_FAIL);
CHECK_ERROR(TAG, (ftruncate(playlist->offset_file, 0) == ESP_OK), return ESP_FAIL);
CHECK_ERROR(TAG, (fseek(playlist->save_file, 0, SEEK_SET) == 0), return ESP_FAIL);
CHECK_ERROR(TAG, (fseek(playlist->offset_file, 0, SEEK_SET) == 0), return ESP_FAIL);
*/
if (playlist->cur_url) {
audio_free(playlist->cur_url);
playlist->cur_url = NULL;
}
playlist->url_num = 0;
playlist->cur_url_id = 0;
playlist->total_size_offset_file = 0;
playlist->total_size_save_file = 0;
return ESP_OK;
}
int sdcard_list_get_url_num(playlist_operator_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
sdcard_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
return playlist->url_num;
}
int sdcard_list_get_url_id(playlist_operator_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
sdcard_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
return playlist->cur_url_id;
}
esp_err_t sdcard_list_destroy(playlist_operator_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
sdcard_list_t *playlist = handle->playlist;
AUDIO_NULL_CHECK(TAG, playlist, return ESP_FAIL);
sdcard_list_close(playlist);
remove(playlist->save_file_name);
remove(playlist->offset_file_name);
audio_free(playlist->save_file_name);
audio_free(playlist->offset_file_name);
if (playlist->cur_url) {
audio_free(playlist->cur_url);
playlist->cur_url = NULL;
}
audio_free(playlist);
handle->playlist = NULL;
audio_free(handle);
return ESP_OK;
}
esp_err_t sdcard_list_get_operation(playlist_operation_t *operation)
{
AUDIO_NULL_CHECK(TAG, operation, return ESP_FAIL);
operation->show = (void *)sdcard_list_show;
operation->save = (void *)sdcard_list_save;
operation->next = (void *)sdcard_list_next;
operation->prev = (void *)sdcard_list_prev;
operation->reset = (void *)sdcard_list_reset;
operation->exist = (void *)sdcard_list_exist;
operation->choose = (void *)sdcard_list_choose;
operation->current = (void *)sdcard_list_current;
operation->destroy = (void *)sdcard_list_destroy;
operation->get_url_num = (void *)sdcard_list_get_url_num;
operation->get_url_id = (void *)sdcard_list_get_url_id;
operation->type = PLAYLIST_SDCARD;
return ESP_OK;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/playlist/playlist_operator/sdcard_list.c
|
C
|
apache-2.0
| 16,544
|
/*
* 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 <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include "esp_log.h"
#include "audio_error.h"
#include "audio_mem.h"
#include "sdcard_scan.h"
#define SDCARD_FILE_PREV_NAME "file:/"
#define SDCARD_SCAN_URL_MAX_LENGTH (1024 * 2)
static const char *TAG = "SDCARD_SCAN";
static void scan_dir(sdcard_scan_cb_t save_url_cb, const char *path, int cur_depth, int depth, const char *file_extension[] , int filter_num, void *user_data)
{
if (cur_depth > depth) {
ESP_LOGD(TAG, "scan depth = %d, exit", cur_depth);
return;
}
char *file_url = audio_calloc(1, SDCARD_SCAN_URL_MAX_LENGTH);
AUDIO_NULL_CHECK(TAG, file_url, return);
DIR *dir = opendir(path);
if (dir == NULL) {
ESP_LOGE(TAG, "Open [%s] directory failed", path);
audio_free(file_url);
return;
}
struct dirent *file_info = NULL;
while (NULL != (file_info = readdir(dir))) {
if ((strlen(file_info->d_name) + strlen(path)) > (SDCARD_SCAN_URL_MAX_LENGTH - strlen(SDCARD_FILE_PREV_NAME))) {
ESP_LOGE(TAG, "The file name is too long, invalid url");
continue;
}
if (file_info->d_name[0] == '.') {
continue;
}
if (file_info->d_type == DT_DIR) {
if (file_info->d_name[0] == '_' && file_info->d_name[1] == '_') {
continue;
}
memset(file_url, 0, SDCARD_SCAN_URL_MAX_LENGTH);
sprintf(file_url, "%s/%s", path, file_info->d_name);
scan_dir(save_url_cb, file_url, cur_depth + 1, depth, file_extension, filter_num, user_data);
} else {
memset(file_url, 0, SDCARD_SCAN_URL_MAX_LENGTH);
sprintf(file_url, "%s%s/%s", SDCARD_FILE_PREV_NAME, path, file_info->d_name);
if (NULL == file_extension) {
save_url_cb(user_data, file_url);
continue;
}
char *detect = strrchr(file_info->d_name, '.');
if (NULL == detect) {
continue;
}
detect ++;
for (int i = 0; i < filter_num; i++) {
if (strcasecmp(detect, file_extension[i]) == 0) {
save_url_cb(user_data, file_url);
break;
}
}
}
}
audio_free(file_url);
closedir(dir);
}
esp_err_t sdcard_scan(sdcard_scan_cb_t cb, const char *path, int depth, const char *file_extension[], int filter_num, void *user_data)
{
AUDIO_NULL_CHECK(TAG, cb, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, path, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, file_extension, return ESP_FAIL);
if (depth < 0 || filter_num < 0) {
ESP_LOGE(TAG, "Invalid parameters, please check");
return ESP_FAIL;
}
scan_dir(cb, path, 0, depth, file_extension, filter_num, user_data);
return ESP_OK;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/playlist/sdcard_scan/sdcard_scan.c
|
C
|
apache-2.0
| 4,173
|
COMPONENT_ADD_LDFLAGS = -Wl,--whole-archive -l$(COMPONENT_NAME) -Wl,--no-whole-archive
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/playlist/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 "esp_peripherals.h"
#include "periph_sdcard.h"
#include "board.h"
#include "playlist.h"
#include "sdcard_list.h"
#include "dram_list.h"
#include "flash_list.h"
#include "partition_list.h"
#include "unity.h"
#include "sdcard_scan.h"
static const char *TAG = "TEST_PLAYLIST";
/**
* Usage case test
*/
static esp_err_t initialize_sdcard(esp_periph_set_handle_t *set_in)
{
// Initialize peripherals management
esp_err_t ret = ESP_OK;
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);
*set_in = set;
ret = audio_board_sdcard_init(set, SD_MODE_1_LINE);
return ret;
}
TEST_CASE("Create a playlist handle, add playlists to the handle and use it", "[playlist]")
{
esp_periph_set_handle_t set;
TEST_ASSERT_FALSE(initialize_sdcard(&set));
ESP_LOGI(TAG, "Create a handle to manage playlists");
playlist_handle_t handle = playlist_create();
TEST_ASSERT_NOT_NULL(handle);
ESP_LOGI(TAG, "Create specific playlist");
playlist_operator_handle_t sdcard_handle = NULL;
TEST_ASSERT_FALSE(sdcard_list_create(&sdcard_handle));
playlist_operator_handle_t flash_handle = NULL;
TEST_ASSERT_FALSE(flash_list_create(&flash_handle));
playlist_operator_handle_t partition_handle = NULL;
TEST_ASSERT_FALSE(partition_list_create(&partition_handle));
playlist_operator_handle_t dram_handle = NULL;
TEST_ASSERT_FALSE(dram_list_create(&dram_handle));
ESP_LOGI(TAG, "add a dram playlist and save a url to it");
TEST_ASSERT_FALSE(playlist_add(handle, dram_handle, 0));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to dram playlist"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "add a sdcard playlist and checkout to the playlist and then save a url to it");
TEST_ASSERT_FALSE(playlist_add(handle, sdcard_handle, 1));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 1));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to sdcard playlist"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "add a nvs flash playlist and checkout to the playlist and then save a url to it");
TEST_ASSERT_FALSE(playlist_add(handle, flash_handle, 2));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 2));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to flash playlist"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "add a partition playlist and checkout to the playlist and then save a url to it");
TEST_ASSERT_FALSE(playlist_add(handle, partition_handle, 3));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 3));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to partition list"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "get type and list id of current playlist");
TEST_ASSERT_NOT_EQUAL(-1, playlist_get_current_list_type(handle));
TEST_ASSERT_NOT_EQUAL(-1, playlist_get_current_list_id(handle));
ESP_LOGI(TAG, "basic operation of playlist, get next, previous, current URL in current playlist");
char *url = NULL;
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 0));
TEST_ASSERT_FALSE(playlist_get_current_list_url(handle, &url));
ESP_LOGI(TAG, "current URL: %s", url);
TEST_ASSERT_FALSE(playlist_next(handle, 2, &url));
ESP_LOGI(TAG, "operation: next, step = 2, url: %s", url);
TEST_ASSERT_FALSE(playlist_prev(handle, 1, &url));
ESP_LOGI(TAG, "operation: prev, step = 1, url: %s", url);
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 1));
TEST_ASSERT_FALSE(playlist_get_current_list_url(handle, &url));
ESP_LOGI(TAG, "current URL: %s", url);
TEST_ASSERT_FALSE(playlist_next(handle, 3, &url));
ESP_LOGI(TAG, "operation: next, step = 3, url: %s", url);
TEST_ASSERT_FALSE(playlist_prev(handle, 2, &url));
ESP_LOGI(TAG, "operation: prev, step = 2, url: %s", url);
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 2));
TEST_ASSERT_FALSE(playlist_get_current_list_url(handle, &url));
ESP_LOGI(TAG, "current URL: %s", url);
TEST_ASSERT_FALSE(playlist_next(handle, 1, &url));
ESP_LOGI(TAG, "operation: next, step = 1, url: %s", url);
TEST_ASSERT_FALSE(playlist_prev(handle, 1, &url));
ESP_LOGI(TAG, "operation: prev, step = 1, url: %s", url);
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 3));
TEST_ASSERT_FALSE(playlist_get_current_list_url(handle, &url));
ESP_LOGI(TAG, "current URL: %s", url);
TEST_ASSERT_FALSE(playlist_next(handle, 2, &url));
ESP_LOGI(TAG, "operation: next, step = 2, url: %s", url);
TEST_ASSERT_FALSE(playlist_prev(handle, 1, &url));
ESP_LOGI(TAG, "operation: prev, step = 1, url: %s", url);
ESP_LOGI(TAG, "destroy all playlists");
TEST_ASSERT_FALSE(playlist_destroy(handle));
handle = NULL;
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
}
TEST_CASE("Create different playlists and use choose function", "[playlist]")
{
esp_periph_set_handle_t set;
TEST_ASSERT_FALSE(initialize_sdcard(&set));
ESP_LOGI(TAG, "Create a handle to manage playlists");
playlist_handle_t handle = playlist_create();
TEST_ASSERT_NOT_NULL(handle);
ESP_LOGI(TAG, "Create specific playlist");
playlist_operator_handle_t sdcard_handle = NULL;
TEST_ASSERT_FALSE(sdcard_list_create(&sdcard_handle));
playlist_operator_handle_t flash_handle = NULL;
TEST_ASSERT_FALSE(flash_list_create(&flash_handle));
playlist_operator_handle_t partition_handle = NULL;
TEST_ASSERT_FALSE(partition_list_create(&partition_handle));
playlist_operator_handle_t dram_handle = NULL;
TEST_ASSERT_FALSE(dram_list_create(&dram_handle));
ESP_LOGI(TAG, "add a dram playlist and save urls to it");
TEST_ASSERT_FALSE(playlist_add(handle, dram_handle, 0));
TEST_ASSERT_FALSE(playlist_save(handle, "save url to dram playlist ID0"));
TEST_ASSERT_FALSE(playlist_save(handle, "save url to dram playlist ID1"));
TEST_ASSERT_FALSE(playlist_save(handle, "save url to dram playlist ID2"));
TEST_ASSERT_FALSE(playlist_save(handle, "save url to dram playlist ID3"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "add a sdcard playlist and checkout to the playlist and then save urls to it");
TEST_ASSERT_FALSE(playlist_add(handle, sdcard_handle, 1));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 1));
TEST_ASSERT_FALSE(playlist_save(handle, "save url to sdcard playlist ID0"));
TEST_ASSERT_FALSE(playlist_save(handle, "save url to sdcard playlist ID1"));
TEST_ASSERT_FALSE(playlist_save(handle, "save url to sdcard playlist ID2"));
TEST_ASSERT_FALSE(playlist_save(handle, "save url to sdcard playlist ID3"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "add a nvs flash playlist and checkout to the playlist and then save urls to it");
TEST_ASSERT_FALSE(playlist_add(handle, flash_handle, 2));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 2));
TEST_ASSERT_FALSE(playlist_save(handle, "save url to flash playlist ID0"));
TEST_ASSERT_FALSE(playlist_save(handle, "save url to flash playlist ID1"));
TEST_ASSERT_FALSE(playlist_save(handle, "save url to flash playlist ID2"));
TEST_ASSERT_FALSE(playlist_save(handle, "save url to flash playlist ID3"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "add a partition playlist and checkout to the playlist and then save urls to it");
TEST_ASSERT_FALSE(playlist_add(handle, partition_handle, 3));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 3));
TEST_ASSERT_FALSE(playlist_save(handle, "save url to partition playlist ID0"));
TEST_ASSERT_FALSE(playlist_save(handle, "save url to partition playlist ID1"));
TEST_ASSERT_FALSE(playlist_save(handle, "save url to partition playlist ID2"));
TEST_ASSERT_FALSE(playlist_save(handle, "save url to partition playlist ID3"));
TEST_ASSERT_FALSE(playlist_show(handle));
char *url = NULL;
ESP_LOGI(TAG, "Checkout to dram playlist and choose id in the list");
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 0));
for (int i = 0; i < playlist_get_current_list_url_num(handle); i++) {
playlist_choose(handle, i, &url);
ESP_LOGW(TAG, "Choose ID: %d, URL: %s", i, url);
}
ESP_LOGI(TAG, "Checkout to sdcard playlist and choose id in the list");
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 1));
for (int i = 0; i < playlist_get_current_list_url_num(handle); i++) {
playlist_choose(handle, i, &url);
ESP_LOGW(TAG, "Choose sdcard ID: %d, URL: %s", i, url);
}
ESP_LOGI(TAG, "Checkout to flash playlist and choose id in the list");
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 2));
for (int i = 0; i < playlist_get_current_list_url_num(handle); i++) {
playlist_choose(handle, i, &url);
ESP_LOGW(TAG, "Choose sdcard ID: %d, URL: %s", i, url);
}
ESP_LOGI(TAG, "Checkout to partition playlist and choose id in the list");
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 3));
for (int i = 0; i < playlist_get_current_list_url_num(handle); i++) {
playlist_choose(handle, i, &url);
ESP_LOGW(TAG, "Choose sdcard ID: %d, URL: %s", i, url);
}
ESP_LOGI(TAG, "Test finish, destroy all playlists");
TEST_ASSERT_FALSE(playlist_destroy(handle));
handle = NULL;
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
}
TEST_CASE("Add same type to a handle use different list id", "[playlist]")
{
esp_periph_set_handle_t set;
TEST_ASSERT_FALSE(initialize_sdcard(&set));
ESP_LOGI(TAG, "Create a handle to manage playlists");
playlist_handle_t handle = playlist_create();
TEST_ASSERT_NOT_NULL(handle);
ESP_LOGI(TAG, "Create specific playlist");
playlist_operator_handle_t sdcard_handle = NULL;
TEST_ASSERT_FALSE(sdcard_list_create(&sdcard_handle));
playlist_operator_handle_t sdcard_handle1 = NULL;
TEST_ASSERT_FALSE(sdcard_list_create(&sdcard_handle1));
playlist_operator_handle_t flash_handle = NULL;
TEST_ASSERT_FALSE(flash_list_create(&flash_handle));
playlist_operator_handle_t flash_handle1 = NULL;
TEST_ASSERT_FALSE(flash_list_create(&flash_handle1));
playlist_operator_handle_t partition_handle = NULL;
TEST_ASSERT_FALSE(partition_list_create(&partition_handle));
playlist_operator_handle_t partition_handle1 = NULL;
TEST_ASSERT_FALSE(partition_list_create(&partition_handle1));
playlist_operator_handle_t dram_handle = NULL;
TEST_ASSERT_FALSE(dram_list_create(&dram_handle));
playlist_operator_handle_t dram_handle1 = NULL;
TEST_ASSERT_FALSE(dram_list_create(&dram_handle1));
ESP_LOGI(TAG, "add two sdcard playlists to handle");
TEST_ASSERT_FALSE(playlist_add(handle, sdcard_handle, 0));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 0));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to sdcard playlist, id: 0"));
TEST_ASSERT_FALSE(playlist_show(handle));
TEST_ASSERT_FALSE(playlist_add(handle, sdcard_handle1, 1));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 1));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to sdcard playlist, id: 1"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "add two dram playlists to handle");
TEST_ASSERT_FALSE(playlist_add(handle, dram_handle, 2));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 2));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to dram playlist, id: 2"));
TEST_ASSERT_FALSE(playlist_show(handle));
TEST_ASSERT_FALSE(playlist_add(handle, dram_handle1, 3));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 3));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to dram playlist, id: 3"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "add two nvs flash playlists to handle");
TEST_ASSERT_FALSE(playlist_add(handle, flash_handle, 4));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 4));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to flash playlist, id: 4"));
TEST_ASSERT_FALSE(playlist_show(handle));
TEST_ASSERT_FALSE(playlist_add(handle, flash_handle1, 5));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 5));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to flash playlist, id: 5"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "add a partition playlist to handle");
// The partition playlist can only be added once, or it will be overwrited by the newest partition playlist
TEST_ASSERT_FALSE(playlist_add(handle, partition_handle, 6));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 6));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to partition list, id: 6"));
TEST_ASSERT_FALSE(playlist_show(handle));
TEST_ASSERT_FALSE(playlist_destroy(handle));
handle = NULL;
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
}
TEST_CASE("Create multiple handles and add playlists to them", "[playlist]")
{
esp_periph_set_handle_t set;
TEST_ASSERT_FALSE(initialize_sdcard(&set));
ESP_LOGI(TAG, "Create a handle to manage playlists, called handle0");
playlist_handle_t handle = playlist_create();
TEST_ASSERT_NOT_NULL(handle);
ESP_LOGI(TAG, "add a sdcard playlist to the handle 0");
playlist_operator_handle_t sdcard_handle = NULL;
TEST_ASSERT_FALSE(sdcard_list_create(&sdcard_handle));
TEST_ASSERT_FALSE(playlist_add(handle, sdcard_handle, 0));
TEST_ASSERT_FALSE(playlist_save(handle, "This a sdcard playlist in handle 0"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "add a dram playlist to the handle 0");
playlist_operator_handle_t dram_handle = NULL;
TEST_ASSERT_FALSE(dram_list_create(&dram_handle));
TEST_ASSERT_FALSE(playlist_add(handle, dram_handle, 1));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 1));
TEST_ASSERT_FALSE(playlist_save(handle, "This a dram playlist in handle 0"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "add a nvs flash playlist to the handle 0");
playlist_operator_handle_t flash_handle = NULL;
TEST_ASSERT_FALSE(flash_list_create(&flash_handle));
TEST_ASSERT_FALSE(playlist_add(handle, flash_handle, 2));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 2));
TEST_ASSERT_FALSE(playlist_save(handle, "This a flash playlist in handle 0"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "add a partition playlist to the handle 0");
playlist_operator_handle_t partition_handle = NULL;
TEST_ASSERT_FALSE(partition_list_create(&partition_handle));
TEST_ASSERT_FALSE(playlist_add(handle, partition_handle, 3));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 3));
TEST_ASSERT_FALSE(playlist_save(handle, "This a partition playlist in handle 0"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "create a new handle, called handle 1");
playlist_handle_t handle1 = playlist_create();
TEST_ASSERT_NOT_NULL(handle1);
ESP_LOGI(TAG, "add a sdcard playlist to the handle 1");
playlist_operator_handle_t sdcard_handle1 = NULL;
TEST_ASSERT_FALSE(sdcard_list_create(&sdcard_handle1));
TEST_ASSERT_FALSE(playlist_add(handle1, sdcard_handle1, 0));
TEST_ASSERT_FALSE(playlist_save(handle1, "This a sdcard playlist in handle 1"));
TEST_ASSERT_FALSE(playlist_show(handle1));
ESP_LOGI(TAG, "add a dram playlist to the handle 1");
playlist_operator_handle_t dram_handle1 = NULL;
TEST_ASSERT_FALSE(dram_list_create(&dram_handle1));
TEST_ASSERT_FALSE(playlist_add(handle1, dram_handle1, 1));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle1, 1));
TEST_ASSERT_FALSE(playlist_save(handle1, "This a dram playlist in handle 1"));
TEST_ASSERT_FALSE(playlist_show(handle1));
ESP_LOGI(TAG, "add a nvs flash playlist to the handle 1");
playlist_operator_handle_t flash_handle1 = NULL;
TEST_ASSERT_FALSE(flash_list_create(&flash_handle1));
TEST_ASSERT_FALSE(playlist_add(handle1, flash_handle1, 2));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle1, 2));
TEST_ASSERT_FALSE(playlist_save(handle1, "This a flash playlist in handle 1"));
TEST_ASSERT_FALSE(playlist_show(handle1));
// partition playlist can only use once, or it will be rewritten
TEST_ASSERT_FALSE(playlist_destroy(handle));
handle = NULL;
TEST_ASSERT_FALSE(playlist_destroy(handle1));
handle1 = NULL;
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
}
TEST_CASE("Create playlists and use them without playlist manager handle", "[playlist]")
{
ESP_LOGI(TAG, "Initialize sdcard");
esp_periph_set_handle_t set;
TEST_ASSERT_FALSE(initialize_sdcard(&set));
ESP_LOGI(TAG, "Create a sdcard playlist and use it");
playlist_operator_handle_t sdcard_handle = NULL;
TEST_ASSERT_FALSE(sdcard_list_create(&sdcard_handle));
TEST_ASSERT_FALSE(sdcard_list_save(sdcard_handle, "sdcard playlist test url 0"));
TEST_ASSERT_FALSE(sdcard_list_save(sdcard_handle, "sdcard playlist test url 1"));
TEST_ASSERT_FALSE(sdcard_list_save(sdcard_handle, "sdcard playlist test url 2"));
TEST_ASSERT_FALSE(sdcard_list_save(sdcard_handle, "sdcard playlist test url 3"));
TEST_ASSERT_FALSE(sdcard_list_show(sdcard_handle));
char *url = NULL;
ESP_LOGI(TAG, "current url number: %d", sdcard_list_get_url_num(sdcard_handle));
TEST_ASSERT_FALSE(sdcard_list_next(sdcard_handle, 1, &url));
ESP_LOGI(TAG, "operation: get next url, step: 1, url: %s", url);
TEST_ASSERT_FALSE( sdcard_list_next(sdcard_handle, 2, &url));
ESP_LOGI(TAG, "operation: get next url, step: 2, url: %s", url);
TEST_ASSERT_FALSE(sdcard_list_prev(sdcard_handle, 50, &url));
ESP_LOGI(TAG, "operation: get previous url, step: 50, url: %s", url);
TEST_ASSERT_FALSE(sdcard_list_current(sdcard_handle, &url));
ESP_LOGI(TAG, "operation: get current url, url: %s", url);
TEST_ASSERT_FALSE(sdcard_list_destroy(sdcard_handle));
sdcard_handle = NULL;
ESP_LOGI(TAG, "Create a flash playlist and use it");
playlist_operator_handle_t flash_handle = NULL;
TEST_ASSERT_FALSE(flash_list_create(&flash_handle));
TEST_ASSERT_FALSE(flash_list_save(flash_handle, "flash playlist test url 0"));
TEST_ASSERT_FALSE(flash_list_save(flash_handle, "flash playlist test url 1"));
TEST_ASSERT_FALSE(flash_list_save(flash_handle, "flash playlist test url 2"));
TEST_ASSERT_FALSE(flash_list_save(flash_handle, "flash playlist test url 3"));
TEST_ASSERT_FALSE(flash_list_show(flash_handle));
ESP_LOGI(TAG, "current url number: %d", flash_list_get_url_num(flash_handle));
TEST_ASSERT_FALSE(flash_list_next(flash_handle, 2, &url));
ESP_LOGI(TAG, "operation: get next url, step: 2, url: %s", url);
TEST_ASSERT_FALSE(flash_list_next(flash_handle, 3, &url));
ESP_LOGI(TAG, "operation: get next url, step: 3, url: %s", url);
TEST_ASSERT_FALSE(flash_list_prev(flash_handle, 1, &url));
ESP_LOGI(TAG, "operation: get previous url, step: 1, url: %s", url);
TEST_ASSERT_FALSE(flash_list_current(flash_handle, &url));
ESP_LOGI(TAG, "operation: get current url, url: %s", url);
TEST_ASSERT_FALSE(flash_list_destroy(flash_handle));
flash_handle = NULL;
ESP_LOGI(TAG, "Create a partition playlist and use it");
playlist_operator_handle_t partition_handle = NULL;
TEST_ASSERT_FALSE(partition_list_create(&partition_handle));
TEST_ASSERT_FALSE(partition_list_save(partition_handle, "partition playlist test url 0"));
TEST_ASSERT_FALSE(partition_list_save(partition_handle, "partition playlist test url 1"));
TEST_ASSERT_FALSE(partition_list_save(partition_handle, "partition playlist test url 2"));
TEST_ASSERT_FALSE(partition_list_save(partition_handle, "partition playlist test url 3"));
TEST_ASSERT_FALSE(partition_list_show(partition_handle));
ESP_LOGI(TAG, "current url number: %d", partition_list_get_url_num(partition_handle));
TEST_ASSERT_FALSE(partition_list_next(partition_handle, 5, &url));
ESP_LOGI(TAG, "operation: get next url, step: 5, url: %s", url);
TEST_ASSERT_FALSE(partition_list_next(partition_handle, 10, &url));
ESP_LOGI(TAG, "operation: get next url, step: 10, url: %s", url);
TEST_ASSERT_FALSE(partition_list_prev(partition_handle, 23, &url));
ESP_LOGI(TAG, "operation: get previous url, step: 23, url: %s", url);
TEST_ASSERT_FALSE(partition_list_current(partition_handle, &url));
ESP_LOGI(TAG, "operation: get current url, url: %s", url);
TEST_ASSERT_FALSE(partition_list_destroy(partition_handle));
partition_handle = NULL;
ESP_LOGI(TAG, "Create a dram playlist and use it");
playlist_operator_handle_t dram_handle = NULL;
TEST_ASSERT_FALSE(dram_list_create(&dram_handle));
TEST_ASSERT_FALSE(dram_list_save(dram_handle, "dram playlist test url 0"));
TEST_ASSERT_FALSE(dram_list_save(dram_handle, "dram playlist test url 1"));
TEST_ASSERT_FALSE(dram_list_save(dram_handle, "dram playlist test url 2"));
TEST_ASSERT_FALSE(dram_list_save(dram_handle, "dram playlist test url 3"));
TEST_ASSERT_FALSE(dram_list_show(dram_handle));
ESP_LOGI(TAG, "current url number: %d", dram_list_get_url_num(dram_handle));
TEST_ASSERT_FALSE(dram_list_next(dram_handle, 21, &url));
ESP_LOGI(TAG, "operation: get next url, step: 21, url: %s", url);
TEST_ASSERT_FALSE(dram_list_next(dram_handle, 12, &url));
ESP_LOGI(TAG, "operation: get next url, step: 12, url: %s", url);
TEST_ASSERT_FALSE(dram_list_prev(dram_handle, 2, &url));
ESP_LOGI(TAG, "operation: get previous url, step: 2, url: %s", url);
TEST_ASSERT_FALSE(dram_list_current(dram_handle, &url));
ESP_LOGI(TAG, "operation: get current url, url: %s", url);
TEST_ASSERT_FALSE(dram_list_destroy(dram_handle));
dram_handle = NULL;
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
}
static void scan_sdcard_cb(void *user_data, char *url)
{
playlist_handle_t handle = (playlist_handle_t)user_data;
playlist_save(handle, url);
}
TEST_CASE("Create a sdcard playlist and scan sdcard then save the specified url to the sdcard playlist", "[playlist]")
{
esp_periph_set_handle_t set;
TEST_ASSERT_FALSE(initialize_sdcard(&set));
playlist_handle_t handle = playlist_create();
TEST_ASSERT_NOT_NULL(handle);
ESP_LOGI(TAG, "create a sdcard playlist");
playlist_operator_handle_t sdcard_handle = NULL;
TEST_ASSERT_FALSE(sdcard_list_create(&sdcard_handle));
TEST_ASSERT_FALSE(playlist_add(handle, sdcard_handle, 0));
TEST_ASSERT_FALSE(sdcard_scan(scan_sdcard_cb, "/sdcard", 0, (const char *[]) {"mp3", "wav", "aac"}, 3, handle));
TEST_ASSERT_FALSE(playlist_show(handle));
TEST_ASSERT_FALSE(playlist_destroy(handle));
handle = NULL;
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
}
/**
* Abnormal operation and stress test
*/
TEST_CASE("Create a manager handle and use it without adding playlist", "[playlist]")
{
playlist_handle_t handle = playlist_create();
TEST_ASSERT_NOT_NULL(handle);
char *url = NULL;
TEST_ASSERT_TRUE(playlist_next(handle, 1, &url));
TEST_ASSERT_TRUE(playlist_prev(handle, 1, &url));
TEST_ASSERT_TRUE(playlist_get_current_list_url(handle, &url));
TEST_ASSERT_TRUE(playlist_show(handle));
TEST_ASSERT_TRUE(playlist_checkout_by_id(handle, 0));
TEST_ASSERT_TRUE(playlist_get_current_list_id(handle));
TEST_ASSERT_TRUE(playlist_get_current_list_type(handle));
TEST_ASSERT_FALSE(playlist_destroy(handle));
handle = NULL;
}
TEST_CASE("Create a playlist handle and add a sdcard playlist without initializing sdcard", "[playlist]")
{
// The sdcard hasn't been initialized, there's bound to be a failure here.
playlist_operator_handle_t sdcard_handle = NULL;
TEST_ASSERT_TRUE(sdcard_list_create(&sdcard_handle));
}
TEST_CASE("Create and destroy a playlist manager", "[playlist]")
{
playlist_handle_t handle = playlist_create();
TEST_ASSERT_NOT_NULL(handle);
TEST_ASSERT_FALSE(playlist_destroy(handle));
}
TEST_CASE("Create a playlist and then call function without save URLs", "[playlist]")
{
char *url = NULL;
esp_periph_set_handle_t set;
TEST_ASSERT_FALSE(initialize_sdcard(&set));
playlist_operator_handle_t sdcard_handle = NULL;
TEST_ASSERT_FALSE(sdcard_list_create(&sdcard_handle));
TEST_ASSERT_TRUE(sdcard_list_next(sdcard_handle, 1, &url));
TEST_ASSERT_TRUE(sdcard_list_prev(sdcard_handle, 1, &url));
TEST_ASSERT_TRUE(sdcard_list_current(sdcard_handle, &url));
TEST_ASSERT_FALSE(sdcard_list_destroy(sdcard_handle));
sdcard_handle = NULL;
playlist_operator_handle_t flash_handle = NULL;
TEST_ASSERT_FALSE(flash_list_create(&flash_handle));
TEST_ASSERT_TRUE(flash_list_next(flash_handle, 1, &url));
TEST_ASSERT_TRUE(flash_list_prev(flash_handle, 1, &url));
TEST_ASSERT_TRUE(flash_list_current(flash_handle, &url));
TEST_ASSERT_FALSE(flash_list_destroy(flash_handle));
flash_handle = NULL;
playlist_operator_handle_t partition_handle = NULL;
TEST_ASSERT_FALSE(partition_list_create(&partition_handle));
TEST_ASSERT_TRUE(partition_list_next(partition_handle, 1, &url));
TEST_ASSERT_TRUE(partition_list_prev(partition_handle, 1, &url));
TEST_ASSERT_TRUE(partition_list_current(partition_handle, &url));
TEST_ASSERT_FALSE(partition_list_destroy(partition_handle));
partition_handle = NULL;
playlist_operator_handle_t dram_handle = NULL;
TEST_ASSERT_FALSE(dram_list_create(&dram_handle));
TEST_ASSERT_TRUE(dram_list_next(dram_handle, 1, &url));
TEST_ASSERT_TRUE(dram_list_prev(dram_handle, 1, &url));
TEST_ASSERT_TRUE(dram_list_current(dram_handle, &url));
TEST_ASSERT_FALSE(dram_list_destroy(dram_handle));
dram_handle = NULL;
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
}
TEST_CASE("Register a existed ID to playlist manager", "[playlist]")
{
esp_periph_set_handle_t set;
TEST_ASSERT_FALSE(initialize_sdcard(&set));
playlist_handle_t handle = playlist_create();
TEST_ASSERT_NOT_NULL(handle);
playlist_operator_handle_t sdcard_handle = NULL;
TEST_ASSERT_FALSE(sdcard_list_create(&sdcard_handle));
TEST_ASSERT_FALSE(playlist_add(handle, sdcard_handle, 0));
// because of ID 0 had been registered, so there must be a failure
playlist_operator_handle_t flash_handle = NULL;
TEST_ASSERT_FALSE(flash_list_create(&flash_handle));
TEST_ASSERT_TRUE(playlist_add(handle, flash_handle, 0));
TEST_ASSERT_FALSE(flash_list_destroy(flash_handle));
TEST_ASSERT_FALSE(playlist_destroy(handle));
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
}
TEST_CASE("Checkout to a playlist id that is non-existed", "[playlist]")
{
playlist_handle_t handle = playlist_create();
TEST_ASSERT_NOT_NULL(handle);
playlist_operator_handle_t flash_handle = NULL;
TEST_ASSERT_FALSE(flash_list_create(&flash_handle));
TEST_ASSERT_FALSE(playlist_add(handle, flash_handle, 0));
ESP_LOGW(TAG, "Because of playlist ID 1 hadn't been registered, so there must be a failure");
TEST_ASSERT_TRUE(playlist_checkout_by_id(handle, 1));
TEST_ASSERT_FALSE(playlist_destroy(handle));
}
TEST_CASE("Get number of urls and current id in playlist", "[playlist]")
{
esp_periph_set_handle_t set;
TEST_ASSERT_FALSE(initialize_sdcard(&set));
ESP_LOGI(TAG, "Create a handle to manage playlists");
playlist_handle_t handle = playlist_create();
TEST_ASSERT_NOT_NULL(handle);
ESP_LOGI(TAG, "Create specific playlist");
playlist_operator_handle_t sdcard_handle = NULL;
TEST_ASSERT_FALSE(sdcard_list_create(&sdcard_handle));
playlist_operator_handle_t flash_handle = NULL;
TEST_ASSERT_FALSE(flash_list_create(&flash_handle));
playlist_operator_handle_t partition_handle = NULL;
TEST_ASSERT_FALSE(partition_list_create(&partition_handle));
playlist_operator_handle_t dram_handle = NULL;
TEST_ASSERT_FALSE(dram_list_create(&dram_handle));
ESP_LOGI(TAG, "add a dram playlist and save a url to it");
TEST_ASSERT_FALSE(playlist_add(handle, dram_handle, 0));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to dram playlist0"));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to dram playlist1"));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to dram playlist2"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "add a sdcard playlist and checkout to the playlist and then save a url to it");
TEST_ASSERT_FALSE(playlist_add(handle, sdcard_handle, 1));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 1));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to sdcard playlist0"));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to sdcard playlist1"));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to sdcard playlist2"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "add a nvs flash playlist and checkout to the playlist and then save a url to it");
TEST_ASSERT_FALSE(playlist_add(handle, flash_handle, 2));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 2));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to flash playlist0"));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to flash playlist1"));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to flash playlist2"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "add a partition playlist and checkout to the playlist and then save a url to it");
TEST_ASSERT_FALSE(playlist_add(handle, partition_handle, 3));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 3));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to partition playlist0"));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to partition playlist1"));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to partition playlist2"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "get type and list id of current playlist");
TEST_ASSERT_NOT_EQUAL(-1, playlist_get_current_list_type(handle));
TEST_ASSERT_NOT_EQUAL(-1, playlist_get_current_list_id(handle));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 0));
TEST_ASSERT_EQUAL(3, playlist_get_current_list_url_num(handle));
char *buff = NULL;
for (int i = 0; i < 2; i++) {
TEST_ASSERT_EQUAL(i, playlist_get_current_list_url_id(handle));
TEST_ASSERT_FALSE(playlist_next(handle, 1, &buff));
}
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 1));
TEST_ASSERT_EQUAL(3, playlist_get_current_list_url_num(handle));
for (int i = 0; i < 2; i++) {
TEST_ASSERT_EQUAL(i, playlist_get_current_list_url_id(handle));
TEST_ASSERT_FALSE(playlist_next(handle, 1, &buff));
}
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 2));
TEST_ASSERT_EQUAL(3, playlist_get_current_list_url_num(handle));
for (int i = 0; i < 2; i++) {
TEST_ASSERT_EQUAL(i, playlist_get_current_list_url_id(handle));
TEST_ASSERT_FALSE(playlist_next(handle, 1, &buff));
}
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 3));
TEST_ASSERT_EQUAL(3, playlist_get_current_list_url_num(handle));
for (int i = 0; i < 2; i++) {
TEST_ASSERT_EQUAL(i, playlist_get_current_list_url_id(handle));
TEST_ASSERT_FALSE(playlist_next(handle, 1, &buff));
}
ESP_LOGI(TAG, "destroy all playlists");
TEST_ASSERT_FALSE(playlist_destroy(handle));
handle = NULL;
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
}
TEST_CASE("Judge whether a url exists in playlist and reset playlist", "[playlist]")
{
esp_periph_set_handle_t set;
TEST_ASSERT_FALSE(initialize_sdcard(&set));
ESP_LOGI(TAG, "Create a handle to manage playlists");
playlist_handle_t handle = playlist_create();
TEST_ASSERT_NOT_NULL(handle);
ESP_LOGI(TAG, "Create specific playlist");
playlist_operator_handle_t sdcard_handle = NULL;
TEST_ASSERT_FALSE(sdcard_list_create(&sdcard_handle));
playlist_operator_handle_t flash_handle = NULL;
TEST_ASSERT_FALSE(flash_list_create(&flash_handle));
playlist_operator_handle_t partition_handle = NULL;
TEST_ASSERT_FALSE(partition_list_create(&partition_handle));
playlist_operator_handle_t dram_handle = NULL;
TEST_ASSERT_FALSE(dram_list_create(&dram_handle));
ESP_LOGI(TAG, "add a dram playlist and save a url to it");
TEST_ASSERT_FALSE(playlist_add(handle, dram_handle, 0));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to dram playlist0"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "add a sdcard playlist and checkout to the playlist and then save a url to it");
TEST_ASSERT_FALSE(playlist_add(handle, sdcard_handle, 1));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 1));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to sdcard playlist0"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "add a nvs flash playlist and checkout to the playlist and then save a url to it");
TEST_ASSERT_FALSE(playlist_add(handle, flash_handle, 2));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 2));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to flash playlist0"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "add a partition playlist and checkout to the playlist and then save a url to it");
TEST_ASSERT_FALSE(playlist_add(handle, partition_handle, 3));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 3));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to partition playlist0"));
TEST_ASSERT_FALSE(playlist_show(handle));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 0));
TEST_ASSERT_TRUE(playlist_exist(handle, "save a url to dram playlist0"));
TEST_ASSERT_FALSE(playlist_reset(handle));
TEST_ASSERT_EQUAL(0, playlist_get_current_list_url_num(handle));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to dram playlist0"));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to dram playlist1"));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to dram playlist2"));
TEST_ASSERT_FALSE(playlist_show(handle));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 1));
TEST_ASSERT_TRUE(playlist_exist(handle, "save a url to sdcard playlist0"));
TEST_ASSERT_FALSE(playlist_reset(handle));
TEST_ASSERT_EQUAL(0, playlist_get_current_list_url_num(handle));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to sdcard playlist0"));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to sdcard playlist1"));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to sdcard playlist2"));
TEST_ASSERT_FALSE(playlist_show(handle));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 2));
TEST_ASSERT_TRUE(playlist_exist(handle, "save a url to flash playlist0"));
TEST_ASSERT_FALSE(playlist_reset(handle));
TEST_ASSERT_EQUAL(0, playlist_get_current_list_url_num(handle));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to flash playlist0"));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to flash playlist1"));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to flash playlist2"));
TEST_ASSERT_FALSE(playlist_show(handle));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 3));
TEST_ASSERT_TRUE(playlist_exist(handle, "save a url to partition playlist0"));
TEST_ASSERT_FALSE(playlist_reset(handle));
TEST_ASSERT_EQUAL(0, playlist_get_current_list_url_num(handle));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to partition playlist0"));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to partition playlist1"));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to partition playlist2"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "destroy all playlists");
TEST_ASSERT_FALSE(playlist_destroy(handle));
handle = NULL;
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
}
TEST_CASE("Remove fuction test in dram list", "[playlist]")
{
esp_periph_set_handle_t set;
TEST_ASSERT_FALSE(initialize_sdcard(&set));
ESP_LOGI(TAG, "Create a handle to manage playlists");
playlist_handle_t handle = playlist_create();
TEST_ASSERT_NOT_NULL(handle);
ESP_LOGI(TAG, "Create specific playlist");
playlist_operator_handle_t sdcard_handle = NULL;
TEST_ASSERT_FALSE(sdcard_list_create(&sdcard_handle));
playlist_operator_handle_t flash_handle = NULL;
TEST_ASSERT_FALSE(flash_list_create(&flash_handle));
playlist_operator_handle_t partition_handle = NULL;
TEST_ASSERT_FALSE(partition_list_create(&partition_handle));
playlist_operator_handle_t dram_handle = NULL;
TEST_ASSERT_FALSE(dram_list_create(&dram_handle));
ESP_LOGI(TAG, "add a dram playlist and save a url to it");
TEST_ASSERT_FALSE(playlist_add(handle, dram_handle, 0));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to dram playlist0"));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to dram playlist1"));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to dram playlist2"));
ESP_LOGI(TAG, "add a sdcard playlist and checkout to the playlist and then save a url to it");
TEST_ASSERT_FALSE(playlist_add(handle, sdcard_handle, 1));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 1));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to sdcard playlist0"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "add a nvs flash playlist and checkout to the playlist and then save a url to it");
TEST_ASSERT_FALSE(playlist_add(handle, flash_handle, 2));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 2));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to flash playlist0"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "add a partition playlist and checkout to the playlist and then save a url to it");
TEST_ASSERT_FALSE(playlist_add(handle, partition_handle, 3));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 3));
TEST_ASSERT_FALSE(playlist_save(handle, "save a url to partition playlist0"));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "remove a url");
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 0));
TEST_ASSERT_FALSE(playlist_remove_by_url(handle, "save a url to dram playlist0"));
TEST_ASSERT_FALSE(playlist_remove_by_url_id(handle, 1));
TEST_ASSERT_EQUAL(1, playlist_get_current_list_url_num(handle));
TEST_ASSERT_FALSE(playlist_show(handle));
ESP_LOGI(TAG, "add urls again");
TEST_ASSERT_FALSE(playlist_save(handle, "save url after remove"));
TEST_ASSERT_EQUAL(2, playlist_get_current_list_url_num(handle));
TEST_ASSERT_FALSE(playlist_show(handle));
// We only support remove function in dram list, so the remove fuction will return
// ESP_ERR_NOT_SUPPORTED when checkout to other playlists.
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 1));
TEST_ASSERT_EQUAL(ESP_ERR_NOT_SUPPORTED, playlist_remove_by_url(handle, "save a url to sdcard playlist0"));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 2));
TEST_ASSERT_EQUAL(ESP_ERR_NOT_SUPPORTED, playlist_remove_by_url(handle, "save a url to flash playlist0"));
TEST_ASSERT_FALSE(playlist_checkout_by_id(handle, 3));
TEST_ASSERT_EQUAL(ESP_ERR_NOT_SUPPORTED, playlist_remove_by_url(handle, "save a url to partition playlist0"));
ESP_LOGI(TAG, "destroy all playlists");
TEST_ASSERT_FALSE(playlist_destroy(handle));
handle = NULL;
TEST_ASSERT_FALSE(esp_periph_set_destroy(set));
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/playlist/test/test_playlist.c
|
C
|
apache-2.0
| 41,005
|
set(COMPONENT_ADD_INCLUDEDIRS include)
# Edit following two lines to set component requirements (see docs)
set(COMPONENT_REQUIRES bootloader_support)
set(COMPONENT_PRIV_REQUIRES esp_actions esp_dispatcher audio_sal)
set(COMPONENT_SRCS ./tone_partition.c)
register_component()
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/tone_partition/CMakeLists.txt
|
CMake
|
apache-2.0
| 278
|
#
# "main" pseudo-component makefile.
#
# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.)
COMPONENT_ADD_INCLUDEDIRS := include
COMPONENT_SRCDIRS := .
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/tone_partition/component.mk
|
Makefile
|
apache-2.0
| 206
|
/*
* 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 __TONE_PARTITION_H__
#define __TONE_PARTITION_H__
#include "esp_err.h"
#include "esp_image_format.h"
#ifdef __cplusplus
extern "C" {
#endif
#define FLASH_TONE_HEADER (0x2053)
#define FLASH_TONE_TAIL (0xDFAC)
#define FLASH_TONE_MAGIC_WORD (0xF55F9876)
#define FLASH_TONE_PROJECT_NAME "ESP_TONE_BIN"
/**
* @brief The operation handle for tone partition
*/
typedef struct tone_partition_s * tone_partition_handle_t;
/**
* @brief The fone bin head
*/
#pragma pack(1)
typedef struct flash_tone_header
{
uint16_t header_tag; /*!< File header tag is 0x2053 */
uint16_t total_num; /*!< Number of all tones */
uint32_t format; /*!< The version of the bin file */
} flash_tone_header_t;
#pragma pack()
/**
* @brief The file information structure in tone partition
*/
#pragma pack(1)
typedef struct tone_file_info {
uint8_t file_tag; /*!< File tag is 0x28 */
uint8_t song_index; /*!< Song index represents the type of tone */
uint8_t file_type; /*!< The file type of the tone bin, usually the mp3 type. */
uint8_t song_ver; /*!< Song version, default is 0 */
uint32_t song_adr; /*!< The address of the bin file corresponding to each tone */
uint32_t song_len; /*!< The length of current tone */
uint32_t RFU[12]; /*!< Default 0 */
uint32_t info_crc; /*!< The crc value of current tone */
} tone_file_info_t;
#pragma pack()
typedef enum tone_format {
TONE_VERSION_0, // header + file table + files
TONE_VERSION_1, // header + desc + file table + files + crc + tail
} tone_format_t;
/**
* @brief Initial the tone partition.
*
* @param[in] handle Pointer to 'tone_partition_handle_t' structure
* @param[in] use_delegate Whether to use esp delegate to read flash
*
* @return
* - 'tone_partition_handle_t': Success
* - NULL: Fail
*/
tone_partition_handle_t tone_partition_init(const char *partition_label, bool use_delegate);
/**
* @brief Destroy the tone partition handle.
*
* @param[in] handle Pointer to 'tone_partition_handle_t' structure
*
* @return
* - ESP_OK: Success
* - others: Failed
*/
esp_err_t tone_partition_deinit(tone_partition_handle_t handle);
/**
* @brief Get the 'esp_app_desc_t' structure in 'flash_tone' partition.
*
* @param[in] handle Pointer to 'tone_partition_handle_t' structure
* @param[in] desc Pointer to 'esp_app_desc_t' structure
*
* @return
* - ESP_OK: Success
* - others: Failed
*/
esp_err_t tone_partition_get_app_desc(tone_partition_handle_t handle, esp_app_desc_t *desc);
/**
* @brief Get the 'tone_file_info_t' structure of the given file index.
*
* @param[in] handle Pointer to 'tone_partition_handle_t' structure
* @param[in] index Index of the file stored in tone partition
* @param[out] info File information read from tone partition
*
* @return
* - ESP_OK: Success
* - others: Failed
*/
esp_err_t tone_partition_get_file_info(tone_partition_handle_t handle, uint16_t index, tone_file_info_t *info);
/**
* @brief Get the 'tone_file_info_t' structure of the given file index.
*
* @param[in] handle Pointer to 'tone_partition_handle_t' structure
* @param[in] file File to read
* @param[in] offset Read offset from the beginning of the file.
* @param[in] dst Buffer to read
* @param[in] read_len Wanted length
*
* @return
* - ESP_OK: Success
* - others: Failed
*/
esp_err_t tone_partition_file_read(tone_partition_handle_t handle, tone_file_info_t *file, uint32_t offset, char *dst, int read_len);
#ifdef __cplusplus
}
#endif
#endif /* __TONE_PARTITION_H__ */
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/tone_partition/include/tone_partition.h
|
C
|
apache-2.0
| 4,946
|
/*
* 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 "audio_error.h"
#include "audio_mem.h"
#include "esp_delegate.h"
#include "esp_log.h"
#include "esp_partition.h"
#include "partition_action.h"
#include "tone_partition.h"
#define FLASH_TONE_FILE_TAG (0x28)
#define FLASH_TONE_FILE_INFO_BLOCK (64)
typedef struct tone_partition_s {
const esp_partition_t *partition;
flash_tone_header_t header;
const esp_partition_t *(*find)(esp_partition_type_t, esp_partition_subtype_t, const char *);
esp_err_t (*read)(const esp_partition_t *, size_t, void *, size_t);
} tone_partition_t;
static const char *TAG = "TONE_PARTITION";
static const esp_partition_t *partition_find_with_dispatcher(esp_partition_type_t type, esp_partition_subtype_t subtype, const char *label)
{
esp_dispatcher_handle_t dispatcher = esp_dispatcher_get_delegate_handle();
if (!dispatcher) {
return NULL;
}
partition_find_args_t config = {
.type = type,
.subtype = subtype,
.label = label,
};
action_arg_t arg = {
.data = &config,
.len = sizeof(partition_find_args_t),
};
action_result_t result = { 0 };
esp_dispatcher_execute_with_func(dispatcher, partition_find_action, NULL, &arg, &result);
return (const esp_partition_t *)result.data;
}
static esp_err_t partition_read_with_dispatcher(const esp_partition_t *partition, size_t src_offset, void *dst, size_t size)
{
esp_dispatcher_handle_t dispatcher = esp_dispatcher_get_delegate_handle();
if (!dispatcher) {
return ESP_FAIL;
}
partition_read_args_t read_arg = {
.partition = partition,
.src_offset = src_offset,
.dst = dst,
.size = size,
};
action_arg_t arg = {
.data = &read_arg,
.len = sizeof(partition_read_args_t),
};
action_result_t result = { 0 };
esp_dispatcher_execute_with_func(dispatcher, partition_read_action, NULL, &arg, &result);
return result.err;
}
esp_err_t tone_partition_get_file_info(tone_partition_handle_t handle, uint16_t index, tone_file_info_t *info)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, info, return ESP_FAIL);
if (handle->header.total_num < index) {
ESP_LOGE(TAG, "Wanted index out of range index[%d]", index);
return ESP_FAIL;
}
tone_file_info_t info_tmp = { 0 };
int start_adr = 0;
if (handle->header.format == TONE_VERSION_0) {
start_adr = sizeof(flash_tone_header_t) + FLASH_TONE_FILE_INFO_BLOCK * index;
} else if (handle->header.format == TONE_VERSION_1) {
start_adr = sizeof(flash_tone_header_t) + sizeof(esp_app_desc_t) + FLASH_TONE_FILE_INFO_BLOCK * index;
} else {
ESP_LOGE(TAG, "Tone format not support!");
return ESP_FAIL;
}
if (ESP_OK == handle->read(handle->partition, start_adr, &info_tmp, sizeof(info_tmp))) {
//TODO check crc
if (info_tmp.file_tag == FLASH_TONE_FILE_TAG) {
memcpy(info, &info_tmp, sizeof(info_tmp));
}
} else {
ESP_LOGE(TAG, "Get tone file tag error %x", info_tmp.file_tag);
return ESP_FAIL;
}
return ESP_OK;
}
esp_err_t tone_partition_file_read(tone_partition_handle_t handle, tone_file_info_t *file, uint32_t offset, char *dst, int read_len)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, file, return ESP_FAIL);
esp_err_t err = handle->read(handle->partition, file->song_adr + offset, dst, read_len);
if (ESP_OK != err) {
ESP_LOGE(TAG, "Tone file read error[0x%x]", err);
}
return err;
}
static esp_err_t tone_partition_get_tail(tone_partition_handle_t handle, uint16_t *tail)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
if (handle->header.format == TONE_VERSION_1) {
tone_file_info_t last_file = { 0 };
tone_partition_get_file_info(handle, handle->header.total_num - 1, &last_file);
int tail_addr = last_file.song_adr + last_file.song_len + ((4 - last_file.song_len % 4) % 4) + 4;
ESP_LOGD(TAG, "addr %X, len %X, tail %X", last_file.song_adr, last_file.song_len, tail_addr);
return handle->read(handle->partition, tail_addr, tail, sizeof(uint16_t));
} else {
*tail = 0;
ESP_LOGE(TAG, "No tail");
return ESP_FAIL;
}
}
esp_err_t tone_partition_get_app_desc(tone_partition_handle_t handle, esp_app_desc_t *desc)
{
if (handle != NULL && handle->header.format == TONE_VERSION_1) {
if (ESP_OK == handle->read(handle->partition, sizeof(flash_tone_header_t), desc, sizeof(esp_app_desc_t))) {
return ESP_OK;
}
}
ESP_LOGE(TAG, "Get desc failed");
return ESP_FAIL;
}
tone_partition_handle_t tone_partition_init(const char *partition_label, bool use_delegate)
{
AUDIO_NULL_CHECK(TAG, partition_label, return NULL);
tone_partition_t *tone = audio_calloc(1, sizeof(tone_partition_t));
AUDIO_NULL_CHECK(TAG, tone, return NULL);
if (use_delegate) {
tone->find = partition_find_with_dispatcher;
tone->read = partition_read_with_dispatcher;
} else {
tone->find = esp_partition_find_first;
tone->read = esp_partition_read;
}
tone->partition = tone->find(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_ANY, partition_label);
if (!tone->partition) {
ESP_LOGE(TAG, "Can not found tone[%s] partition", partition_label);
goto error;
}
if (ESP_OK != tone->read(tone->partition, 0, &tone->header, sizeof(flash_tone_header_t))) {
ESP_LOGE(TAG, "Read flash tone file header failed");
goto error;
}
if (tone->header.header_tag != FLASH_TONE_HEADER) {
ESP_LOGE(TAG, "Not flash tone partition");
goto error;
}
if (tone->header.format == TONE_VERSION_1) {
uint16_t tail = 0;
if (ESP_OK != tone_partition_get_tail(tone, &tail) || tail != FLASH_TONE_TAIL) {
ESP_LOGE(TAG, "Flash tone init failed at tail check %X", tail);
goto error;
}
}
ESP_LOGI(TAG, "tone partition format %d, total %d", tone->header.format, tone->header.total_num);
return (tone_partition_handle_t)tone;
error:
if (tone) {
free(tone);
}
return NULL;
}
esp_err_t tone_partition_deinit(tone_partition_handle_t handle)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
free(handle);
return ESP_OK;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/tone_partition/tone_partition.c
|
C
|
apache-2.0
| 7,657
|
set(COMPONENT_ADD_INCLUDEDIRS include)
set(COMPONENT_PRIV_INCLUDEDIRS inc)
# Edit following two lines to set component requirements (see docs)
set(COMPONENT_REQUIRES bt mbedtls nvs_flash)
set(COMPONENT_PRIV_REQUIRES audio_sal esp_dispatcher esp_actions)
list(APPEND COMPONENT_SRCS src/esp_wifi_setting.c
src/wifi_service.c
src/wifi_ssid_manager.c
smart_config/smart_config.c
blufi_config/blufi_config.c
blufi_config/blufi_security.c)
IF (CONFIG_IDF_TARGET STREQUAL "esp32c3")
register_component()
ELSE()
list(APPEND COMPONENT_SRCS airkiss_config/airkiss_config.c)
register_component()
target_link_libraries(${COMPONENT_TARGET} INTERFACE "-L${CMAKE_CURRENT_LIST_DIR}/airkiss_config")
target_link_libraries(${COMPONENT_TARGET} INTERFACE airkiss_aes)
ENDIF()
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/wifi_service/CMakeLists.txt
|
CMake
|
apache-2.0
| 879
|
/*
* 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 "esp_system.h"
#include "esp_wifi.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "audio_mem.h"
#include "lwip/err.h"
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include "lwip/netdb.h"
#include "lwip/dns.h"
#include "airkiss.h"
#include "airkiss_config.h"
#include "esp_wifi_setting.h"
#define AIRKISS_DEBUG_ON 0
#define AIRKISS_NOTIFY_TASK_PRIORITY 3
#define AIRKISS_NOTIFY_TASK_STACK_SIZE 4096
#define AIRKISS_DEFAULT_LAN_PORT 12476
#define AIRKISS_ACK_TASK_PRIORITY 2
#define AIRKISS_ACK_TASK_STACK_SIZE 4096
#define AIRKISS_ACK_PORT 10000
#define AIRKISS_CHANNEL_CHANGE_PERIOD 130
#define AIRKISS_MAX_CHANNEL_NUM 17
#define AIRKISS_MIN_RSSI -90
typedef struct {
bool ap_exist;
uint8_t primary_chan;
wifi_second_chan_t second_chan;
} airkiss_chan_t;
typedef struct {
airkiss_lan_pack_param_t lan_pack;
bool ssdp_notify_enable;
char *aes_key;
} airkiss_notify_para_t;
static esp_wifi_setting_handle_t air_setting_handle;
static const char *TAG = "AIRKISS";
static uint8_t s_sniffer_stop_flag = 1;
static int s_cur_chan_idx = AIRKISS_MAX_CHANNEL_NUM - 1;
static airkiss_context_t *ak_ctx;
static uint8_t ak_random_num = 0;
static esp_timer_handle_t channel_change_timer;
static TaskHandle_t air_answer_task_handle;
static airkiss_chan_t s_airkiss_chan_tab[AIRKISS_MAX_CHANNEL_NUM] = {
{false, 1, WIFI_SECOND_CHAN_ABOVE},
{false, 2, WIFI_SECOND_CHAN_ABOVE},
{false, 3, WIFI_SECOND_CHAN_ABOVE},
{false, 4, WIFI_SECOND_CHAN_ABOVE},
{false, 5, WIFI_SECOND_CHAN_ABOVE},
{false, 5, WIFI_SECOND_CHAN_BELOW},
{false, 6, WIFI_SECOND_CHAN_ABOVE},
{false, 6, WIFI_SECOND_CHAN_BELOW},
{false, 7, WIFI_SECOND_CHAN_ABOVE},
{false, 7, WIFI_SECOND_CHAN_BELOW},
{false, 8, WIFI_SECOND_CHAN_BELOW},
{false, 9, WIFI_SECOND_CHAN_BELOW},
{false, 10, WIFI_SECOND_CHAN_BELOW},
{false, 11, WIFI_SECOND_CHAN_BELOW},
{false, 12, WIFI_SECOND_CHAN_BELOW},
{false, 13, WIFI_SECOND_CHAN_BELOW},
{false, 14, WIFI_SECOND_CHAN_NONE},
};
const airkiss_config_t ak_conf = {
(airkiss_memset_fn) &memset,
(airkiss_memcpy_fn) &memcpy,
(airkiss_memcmp_fn) &memcmp,
(airkiss_printf_fn) &printf,
};
static int airkiss_get_errno(int fd)
{
int sock_errno = 0;
u32_t optlen = sizeof(sock_errno);
getsockopt(fd, SOL_SOCKET, SO_ERROR, &sock_errno, &optlen);
return sock_errno;
}
// send notify
static void airkiss_notify_task(void *pvParameters)
{
airkiss_lan_pack_param_t *lan_param = (airkiss_lan_pack_param_t *)pvParameters;
struct sockaddr_in local_addr;
struct sockaddr_in remote_addr;
struct sockaddr_in broad_addr;
struct timeval tv;
fd_set rfds, exfds;
socklen_t addr_len = sizeof(remote_addr);
int fd = -1;
int send_socket = -1;
uint16_t buf_len = 200;
uint16_t resp_len;
uint16_t recv_len;
uint16_t req_len;
uint8_t *buf = NULL;
uint8_t *req_buf = NULL;
int ret, err;
airkiss_lan_ret_t lan_ret;
buf = audio_malloc(buf_len);
if (buf == NULL) {
ESP_LOGE(TAG, "buf allocate fail");
goto _fail;
}
req_buf = audio_malloc(buf_len);
if (req_buf == NULL) {
ESP_LOGE(TAG, "lan buf allocate fail");
goto _fail;
}
memset(req_buf, 0, buf_len);
req_len = buf_len;
ret = airkiss_lan_pack(AIRKISS_LAN_SSDP_NOTIFY_CMD,
lan_param->appid , lan_param->deviceid, 0, 0, req_buf, &req_len, &ak_conf);
if (ret != AIRKISS_LAN_PAKE_READY) {
ESP_LOGE(TAG, "Pack lan packet error!");
goto _fail;
return;
}
do {
send_socket = socket(AF_INET, SOCK_DGRAM, 0);
if (send_socket == -1) {
ESP_LOGE(TAG, "failed to create sock!");
vTaskDelay(1000 / portTICK_RATE_MS);
}
} while (send_socket == -1);
memset(&broad_addr, 0, sizeof(broad_addr));
broad_addr.sin_family = AF_INET;
broad_addr.sin_addr.s_addr = INADDR_BROADCAST;
broad_addr.sin_port = htons(AIRKISS_DEFAULT_LAN_PORT);
broad_addr.sin_len = sizeof(broad_addr);
do {
fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); //IPPROTO_UDP
if (fd == -1) {
ESP_LOGE(TAG, "failed to create sock!");
vTaskDelay(1000 / portTICK_RATE_MS);
}
} while (fd == -1);
memset(&local_addr, 0, sizeof(local_addr));
local_addr.sin_family = AF_INET;
local_addr.sin_addr.s_addr = INADDR_ANY;
local_addr.sin_port = htons(AIRKISS_DEFAULT_LAN_PORT);
local_addr.sin_len = sizeof(local_addr);
ret = bind(fd, (const struct sockaddr *)&local_addr, sizeof(local_addr));
if (ret) {
err = airkiss_get_errno(fd);
ESP_LOGE(TAG, "airkiss bind local port ERROR! errno %d", err);
goto _out;
}
tv.tv_sec = 1;
tv.tv_usec = 0;
uint8_t re_sent_num = 10;
while (re_sent_num) {
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
FD_ZERO(&exfds);
FD_SET(fd, &exfds);
ret = select(fd + 1, &rfds, NULL, &exfds, &tv);
if (ret > 0) {
if (FD_ISSET(fd, &exfds) || !FD_ISSET(fd, &rfds)) {
ESP_LOGE(TAG, "Receive AIRKISS_LAN_SSDP_REQ select error!");
goto _out;
}
memset(buf, 0, buf_len);
recv_len = recvfrom(fd, buf, buf_len, 0,
(struct sockaddr *)&remote_addr, (socklen_t *)&addr_len);
lan_ret = airkiss_lan_recv(buf, recv_len, &ak_conf);
if (lan_ret == AIRKISS_LAN_SSDP_REQ) {
ESP_LOGD(TAG, "AIRKISS_LAN_SSDP_REQ");
memset(buf, 0, buf_len);
resp_len = buf_len;
lan_ret = airkiss_lan_pack(AIRKISS_LAN_SSDP_RESP_CMD,
lan_param->appid , lan_param->deviceid, 0, 0, buf, &resp_len, &ak_conf);
if (lan_ret != AIRKISS_LAN_PAKE_READY) {
ESP_LOGE(TAG, "Pack lan packet error! errno %d", lan_ret);
goto _out;
}
ret = sendto(fd, buf, resp_len, 0,
(struct sockaddr *)&remote_addr, sizeof(remote_addr));
if (ret < 0) {
err = airkiss_get_errno(fd);
if (err != ENOMEM && err != EAGAIN) {
ESP_LOGE(TAG, "send notify msg ERROR! errno %d", err);
goto _out;
}
} else {
ESP_LOGD(TAG, "send notify msg OK!");
re_sent_num --;
}
}
} else {
ret = sendto(send_socket, req_buf, req_len, 0,
(const struct sockaddr *)&broad_addr, sizeof(broad_addr));
if (ret < 0) {
err = airkiss_get_errno(fd);
if (err != ENOMEM && err != EAGAIN) {
ESP_LOGE(TAG, "send notify msg ERROR! errno %d", err);
goto _out;
}
} else {
ESP_LOGI(TAG, "send notify msg %d OK!", re_sent_num);
re_sent_num --;
}
}
}
_out:
close(fd);
close(send_socket);
_fail:
if (buf) {
audio_free(buf);
buf = NULL;
}
if (req_buf) {
audio_free(req_buf);
req_buf = NULL;
}
audio_free(lan_param->appid);
audio_free(lan_param->deviceid);
audio_free(lan_param);
vTaskDelete(NULL);
}
void airkiss_ssdp_notify(airkiss_lan_pack_param_t *lan_param)
{
if (lan_param == NULL) {
ESP_LOGE(TAG, "lan_param invalid");
return;
}
airkiss_lan_pack_param_t *pack = audio_malloc(sizeof(airkiss_lan_pack_param_t));
pack->appid = audio_strdup(lan_param->appid);
pack->deviceid = audio_strdup(lan_param->deviceid);
xTaskCreate(airkiss_notify_task, "airkiss_notify_task", AIRKISS_NOTIFY_TASK_STACK_SIZE, pack, AIRKISS_NOTIFY_TASK_PRIORITY, NULL);
}
static void airkiss_send_ack_task(void *pvParameters)
{
tcpip_adapter_ip_info_t local_ip;
struct sockaddr_in server_addr;
socklen_t sin_size = sizeof(server_addr);
int send_socket = 0;
uint8_t buf[7];
size_t sendlen;
int count = 1;
int ret, err;
bzero(&server_addr, sizeof(struct sockaddr_in));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_BROADCAST;
server_addr.sin_port = htons(AIRKISS_ACK_PORT);
buf[0] = (uint8_t)ak_random_num;
esp_wifi_get_mac(WIFI_IF_STA, &buf[1]);
vTaskDelay(200 / portTICK_RATE_MS);
while (1) {
/* Get local IP address of station */
ret = tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &local_ip);
if ((ESP_OK == ret) && (local_ip.ip.addr != INADDR_ANY)) {
/* Create UDP socket. */
send_socket = socket(AF_INET, SOCK_DGRAM, 0);
if (send_socket < 0) {
ESP_LOGE(TAG, "Create airkiss udp socket failed");
vTaskDelay(1000 / portTICK_RATE_MS);
continue;
}
while (1) {
/* Send airkiss ACK every 100ms. */
vTaskDelay(100 / portTICK_RATE_MS);
sendlen = sendto(send_socket, buf, 7, 0,
(struct sockaddr *) &server_addr, sin_size);
if (sendlen > 0) {
/* Totally send 30 airkiss ACKs. Then airkiss is successful. */
if (count++ >= 30) {
goto _out;
}
} else {
err = airkiss_get_errno(send_socket);
if (err == ENOMEM || err == EAGAIN) {
ESP_LOGD(TAG, "send failed, errno %d", err);
continue;
}
ESP_LOGE(TAG, "send failed, errno %d", err);
goto _out;
}
}
} else {
vTaskDelay((portTickType) (100 / portTICK_RATE_MS));
}
}
_out:
close(send_socket);
ESP_LOGI(TAG, "airkiss_send_ack_task exit");
air_answer_task_handle = NULL;
vTaskDelete(NULL);
}
//reply UDP to cell phone to notify that cell phone has connected to router
void airkiss_answer(void)
{
if (air_answer_task_handle) {
return;
}
xTaskCreate(airkiss_send_ack_task, "KISS_Send_task", AIRKISS_ACK_TASK_STACK_SIZE, NULL,
AIRKISS_ACK_TASK_PRIORITY, &air_answer_task_handle);
}
static int airkiss_get_next_channel_idx(void)
{
do {
if (s_cur_chan_idx >= AIRKISS_MAX_CHANNEL_NUM - 1) {
s_cur_chan_idx = 0;
} else {
s_cur_chan_idx++;
}
} while (s_airkiss_chan_tab[s_cur_chan_idx].ap_exist == false);
return s_cur_chan_idx;
}
//switch channel
static void channel_change_callback(void *timer_arg)
{
int chan_idx = 0;
if (s_sniffer_stop_flag == 1) {
return;
}
chan_idx = airkiss_get_next_channel_idx();
ESP_LOGD(TAG, "ch%d-%d", s_airkiss_chan_tab[chan_idx].primary_chan,
s_airkiss_chan_tab[chan_idx].second_chan);
esp_wifi_set_channel(s_airkiss_chan_tab[chan_idx].primary_chan,
s_airkiss_chan_tab[chan_idx].second_chan);
airkiss_change_channel(ak_ctx);
}
static void airkiss_finish(void)
{
airkiss_result_t result;
wifi_config_t wifi_config;
int err;
err = airkiss_get_result(ak_ctx, &result);
if (err == 0) {
ESP_LOGI(TAG,
"ssid = \"%s\", pwd = \"%s\", ssid_length = %d, pwd_length = %d, random = %x",
result.ssid, result.pwd, result.ssid_length, result.pwd_length,
result.random);
ak_random_num = result.random;
bzero(&wifi_config.sta, sizeof(wifi_sta_config_t));
memcpy(wifi_config.sta.ssid, result.ssid, result.ssid_length);
memcpy(wifi_config.sta.password, result.pwd, result.pwd_length);
if (air_setting_handle) {
esp_wifi_setting_info_notify(air_setting_handle, &wifi_config);
}
} else {
ESP_LOGI(TAG, "airkiss_get_result() failed !");
}
audio_free(ak_ctx);
ak_ctx = NULL;
}
static void wifi_promiscuous_rx(void *buf, wifi_promiscuous_pkt_type_t type)
{
wifi_promiscuous_pkt_t *pkt = (wifi_promiscuous_pkt_t *) buf;
uint8_t *payload;
uint16_t len;
int ret;
if (s_sniffer_stop_flag == 1 || buf == NULL) {
return;
}
payload = pkt->payload;
len = pkt->rx_ctrl.sig_len;
ret = airkiss_recv(ak_ctx, payload, len);
if (ret == AIRKISS_STATUS_CHANNEL_LOCKED) {
esp_timer_stop(channel_change_timer);
esp_timer_delete(channel_change_timer);
channel_change_timer = NULL;
ESP_LOGI(TAG, "AIRKISS_STATUS_CHANNEL_LOCKED");
} else if (ret == AIRKISS_STATUS_COMPLETE) {
esp_wifi_set_promiscuous(false);
s_sniffer_stop_flag = 1;
airkiss_finish();
ESP_LOGI(TAG, "AIRKISS_STATUS_COMPLETE");
} else {
//ESP_LOGI(TAG, "AIRKISS_STATUS: %d", ret);
}
}
static void airkiss_wifi_scan_ap(void)
{
wifi_scan_config_t *scan_config = NULL;
uint16_t ap_num = 0;
wifi_ap_record_t *ap_record = NULL;
scan_config = audio_calloc(1, sizeof(wifi_scan_config_t));
if (scan_config == NULL) {
ESP_LOGE(TAG, "scan config allocate fail");
return;
}
for (int scan_cnt = 0; scan_cnt < 2; scan_cnt++) {
bzero(scan_config, sizeof(wifi_scan_config_t));
scan_config->show_hidden = true;
esp_wifi_scan_start(scan_config, true);
esp_wifi_scan_get_ap_num(&ap_num);
if (ap_num) {
ap_record = audio_calloc(1, ap_num * sizeof(wifi_ap_record_t));
if (ap_record == NULL) {
ESP_LOGE(TAG, "ap record allocate fail");
continue;
}
esp_wifi_scan_get_ap_records(&ap_num, ap_record);
#if AIRKISS_DEBUG_ON
ESP_LOGI(TAG, "scan ap number: %d", ap_num);
for (int i = 0; i < ap_num; i++) {
ESP_LOGI(TAG, "scan ap: %s, "MACSTR", %u, %u, %d", ap_record[i].ssid,
MAC2STR(ap_record[i].bssid), ap_record[i].primary,
ap_record[i].second, ap_record[i].rssi);
}
#endif
for (int i = 0; i < AIRKISS_MAX_CHANNEL_NUM; i++) {
if (s_airkiss_chan_tab[i].ap_exist == true) {
continue;
}
for (int j = 0; j < ap_num; j++) {
if (ap_record[j].rssi < AIRKISS_MIN_RSSI) {
continue;
}
if (ap_record[j].primary == s_airkiss_chan_tab[i].primary_chan) {
s_airkiss_chan_tab[i].ap_exist = true;
}
}
}
audio_free(ap_record);
}
}
audio_free(scan_config);
}
static esp_err_t airkiss_start(esp_wifi_setting_handle_t handle)
{
int chan_idx = 0;
esp_err_t res = ESP_OK;
ESP_LOGI(TAG, "Start airkiss, Version:%s", airkiss_version());
ak_ctx = audio_calloc(1, sizeof(airkiss_context_t));
if (ak_ctx == NULL) {
ESP_LOGE(TAG, "Airkiss context allocate fail");
return ESP_FAIL;
}
res = airkiss_init(ak_ctx, &ak_conf);
if (res < 0) {
audio_free(ak_ctx);
ESP_LOGE(TAG, "Airkiss init failed!");
return ESP_FAIL;
}
airkiss_notify_para_t *para = esp_wifi_setting_get_data(handle);
if (para->ssdp_notify_enable && para->aes_key) {
airkiss_set_key(ak_ctx, (uint8_t *)para->aes_key, strlen(para->aes_key));
}
esp_wifi_disconnect();
airkiss_wifi_scan_ap();
chan_idx = airkiss_get_next_channel_idx();
esp_wifi_set_channel(s_airkiss_chan_tab[chan_idx].primary_chan,
s_airkiss_chan_tab[chan_idx].second_chan);
esp_timer_create_args_t create_args = {
.callback = &channel_change_callback,
.arg = NULL,
.name = "channel_change",
};
esp_timer_create(&create_args, &channel_change_timer);
esp_timer_start_periodic(channel_change_timer, AIRKISS_CHANNEL_CHANGE_PERIOD * 1000);
esp_wifi_set_promiscuous(false);
esp_wifi_set_promiscuous_rx_cb(wifi_promiscuous_rx);
esp_wifi_set_promiscuous(true);
s_sniffer_stop_flag = 0;
return res;
}
static esp_err_t airkiss_teardown(esp_wifi_setting_handle_t handle, wifi_config_t *arg)
{
airkiss_notify_para_t *para = esp_wifi_setting_get_data(handle);
airkiss_answer();
if (para->ssdp_notify_enable) {
airkiss_ssdp_notify(¶->lan_pack);
}
return ESP_OK;
}
static esp_err_t airkiss_stop(esp_wifi_setting_handle_t handle)
{
s_sniffer_stop_flag = 1;
if (channel_change_timer) {
esp_timer_stop(channel_change_timer);
esp_timer_delete(channel_change_timer);
channel_change_timer = NULL;
}
esp_wifi_set_promiscuous(false);
audio_free(ak_ctx);
ak_ctx = NULL;
return ESP_OK;
}
esp_wifi_setting_handle_t airkiss_config_create(airkiss_config_info_t *info)
{
air_setting_handle = esp_wifi_setting_create("airkiss_config");
AUDIO_MEM_CHECK(TAG, air_setting_handle, return NULL);
airkiss_notify_para_t *cfg = audio_calloc(1, sizeof(airkiss_notify_para_t));
AUDIO_MEM_CHECK(TAG, cfg, {
audio_free(air_setting_handle);
return NULL;
});
cfg->lan_pack.appid = info->lan_pack.appid;
cfg->lan_pack.deviceid = info->lan_pack.deviceid;
if (info->aes_key) {
cfg->aes_key = audio_strdup(info->aes_key);
}
cfg->ssdp_notify_enable = info->ssdp_notify_enable;
esp_wifi_setting_set_data(air_setting_handle, cfg);
esp_wifi_setting_register_function(air_setting_handle, airkiss_start, airkiss_stop, airkiss_teardown);
return air_setting_handle;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/wifi_service/airkiss_config/airkiss_config.c
|
C
|
apache-2.0
| 19,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.
*
*/
#include <string.h>
#include "audio_mem.h"
#include "esp_log.h"
#include "esp_wifi.h"
#include "blufi_config.h"
#include "blufi_security.h"
#include "esp_wifi_setting.h"
#include "audio_idf_version.h"
static esp_wifi_setting_handle_t bc_setting_handle;
typedef struct wifi_blufi_config {
uint8_t ble_server_if;
uint16_t ble_conn_id;
wifi_config_t sta_config;
bool sta_connected_flag;
bool ble_connected_flag;
void *user_data;
int user_data_length;
} wifi_blufi_config_t;
static const char *TAG = "BLUFI_CONFIG";
#ifdef CONFIG_BLUEDROID_ENABLED
#include "esp_bt.h"
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 3, 0))
#include "esp_blufi.h"
#else
#include "esp_blufi_api.h"
#endif
#include "esp_bt_defs.h"
#include "esp_gap_ble_api.h"
#include "esp_bt_device.h"
#include "esp_bt_main.h"
#include "esp_gap_bt_api.h"
#define WIFI_LIST_NUM (10)
static void wifi_ble_event_callback(esp_blufi_cb_event_t event, esp_blufi_cb_param_t *param);
static esp_err_t _ble_config_stop(esp_wifi_setting_handle_t self);
static esp_blufi_callbacks_t wifi_ble_callbacks = {
.event_cb = wifi_ble_event_callback,
.negotiate_data_handler = blufi_dh_negotiate_data_handler,
.encrypt_func = blufi_aes_encrypt,
.decrypt_func = blufi_aes_decrypt,
.checksum_func = blufi_crc_checksum,
};
static void wifi_ble_event_callback(esp_blufi_cb_event_t event, esp_blufi_cb_param_t *param)
{
/* actually, should post to blufi_task handle the procedure,
* now, as an audio_ble, we do it more simply */
esp_err_t ret = ESP_OK;
wifi_blufi_config_t *cfg = esp_wifi_setting_get_data(bc_setting_handle);
switch (event) {
case ESP_BLUFI_EVENT_INIT_FINISH:
ESP_LOGI(TAG, "BLUFI init finish");
break;
case ESP_BLUFI_EVENT_DEINIT_FINISH:
ESP_LOGI(TAG, "BLUFI deinit finish");
break;
case ESP_BLUFI_EVENT_BLE_CONNECT:
ESP_LOGI(TAG, "BLUFI ble connect");
cfg->ble_connected_flag = true;
cfg->ble_server_if = param->connect.server_if;
cfg->ble_conn_id = param->connect.conn_id;
break;
case ESP_BLUFI_EVENT_BLE_DISCONNECT:
cfg->ble_connected_flag = false;
ESP_LOGI(TAG, "BLUFI ble disconnect");
break;
case ESP_BLUFI_EVENT_SET_WIFI_OPMODE:
ESP_LOGI(TAG, "BLUFI Set WIFI opmode %d", param->wifi_mode.op_mode);
ESP_ERROR_CHECK( esp_wifi_set_mode(param->wifi_mode.op_mode) );
break;
case ESP_BLUFI_EVENT_REQ_CONNECT_TO_AP:
ESP_LOGI(TAG, "BLUFI request wifi connect to AP");
if (bc_setting_handle) {
esp_wifi_setting_info_notify(bc_setting_handle, &cfg->sta_config);
}
_ble_config_stop(NULL);
break;
case ESP_BLUFI_EVENT_REQ_DISCONNECT_FROM_AP:
ESP_LOGI(TAG, "BLUFI request wifi disconnect from AP");
esp_wifi_disconnect();
break;
case ESP_BLUFI_EVENT_GET_WIFI_STATUS: {
wifi_mode_t mode;
esp_blufi_extra_info_t info = {0};
esp_wifi_get_mode(&mode);
if (cfg->sta_connected_flag) {
memset(&info, 0, sizeof(esp_blufi_extra_info_t));
info.sta_ssid = cfg->sta_config.sta.ssid;
info.sta_ssid_len = strlen((char *)cfg->sta_config.sta.ssid);
esp_blufi_send_wifi_conn_report(mode, ESP_BLUFI_STA_CONN_SUCCESS, 0, &info);
} else {
esp_blufi_send_wifi_conn_report(mode, ESP_BLUFI_STA_CONN_FAIL, 0, NULL);
}
ESP_LOGI(TAG, "BLUFI get wifi status from AP");
break;
}
case ESP_BLUFI_EVENT_RECV_SLAVE_DISCONNECT_BLE:
ESP_LOGI(TAG, "BLUFI close a gatt connection");
esp_blufi_close(cfg->ble_server_if, cfg->ble_conn_id);
break;
case ESP_BLUFI_EVENT_DEAUTHENTICATE_STA:
/* TODO */
break;
case ESP_BLUFI_EVENT_RECV_STA_BSSID:
memcpy(cfg->sta_config.sta.bssid, param->sta_bssid.bssid, 6);
cfg->sta_config.sta.bssid_set = 1;
ESP_LOGI(TAG, "Recv STA BSSID %s", cfg->sta_config.sta.bssid);
break;
case ESP_BLUFI_EVENT_RECV_STA_SSID:
memcpy(cfg->sta_config.sta.ssid, param->sta_ssid.ssid, param->sta_ssid.ssid_len);
cfg->sta_config.sta.ssid[param->sta_ssid.ssid_len] = '\0';
ESP_LOGI(TAG, "Recv STA SSID ret %d %s", ret, cfg->sta_config.sta.ssid);
break;
case ESP_BLUFI_EVENT_RECV_STA_PASSWD:
memcpy(cfg->sta_config.sta.password, param->sta_passwd.passwd, param->sta_passwd.passwd_len);
cfg->sta_config.sta.password[param->sta_passwd.passwd_len] = '\0';
ESP_LOGI(TAG, "Recv STA PASSWORD %s", cfg->sta_config.sta.password);
break;
default:
ESP_LOGE(TAG, "Event %d is not supported", event);
break;
}
}
#endif
esp_err_t _ble_config_start(esp_wifi_setting_handle_t self)
{
#ifdef CONFIG_BLUEDROID_ENABLED
ESP_LOGI(TAG, "blufi_config_start");
ESP_LOGI(TAG, "BD ADDR: "ESP_BD_ADDR_STR"", ESP_BD_ADDR_HEX(esp_bt_dev_get_address()));
ESP_LOGI(TAG, "BLUFI VERSION %04x", esp_blufi_get_version());
blufi_security_init();
esp_blufi_register_callbacks(&wifi_ble_callbacks);
esp_blufi_profile_init();
#else
ESP_LOGW(TAG, "blufi config selected, but CONFIG_BLUEDROID_ENABLED not enabled");
#endif
return ESP_OK;
}
static esp_err_t _ble_config_stop(esp_wifi_setting_handle_t self)
{
return ESP_OK;
}
esp_wifi_setting_handle_t blufi_config_create(void *info)
{
bc_setting_handle = esp_wifi_setting_create("blufi_config");
AUDIO_MEM_CHECK(TAG, bc_setting_handle, return NULL);
wifi_blufi_config_t *cfg = audio_calloc(1, sizeof(wifi_blufi_config_t));
AUDIO_MEM_CHECK(TAG, cfg, {
audio_free(bc_setting_handle);
return NULL;
});
esp_wifi_setting_set_data(bc_setting_handle, cfg);
esp_wifi_setting_register_function(bc_setting_handle, _ble_config_start, _ble_config_stop, NULL);
return bc_setting_handle;
}
esp_err_t blufi_set_sta_connected_flag(esp_wifi_setting_handle_t handle, bool flag)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
wifi_blufi_config_t *blufi_cfg = esp_wifi_setting_get_data(handle);
blufi_cfg->sta_connected_flag = flag;
return ESP_OK;
}
esp_err_t blufi_set_customized_data(esp_wifi_setting_handle_t handle, char *data, int data_len)
{
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
AUDIO_NULL_CHECK(TAG, data, return ESP_FAIL);
wifi_blufi_config_t *blufi_cfg = esp_wifi_setting_get_data(handle);
blufi_cfg->user_data = audio_calloc(1, data_len + 1);
blufi_cfg->user_data_length = data_len;
AUDIO_MEM_CHECK(TAG, blufi_cfg->user_data, return ESP_FAIL);
memcpy(blufi_cfg->user_data, data, data_len);
ESP_LOGI(TAG, "Set blufi customized data: %s, length: %d", data, data_len);
return ESP_OK;
}
esp_err_t blufi_send_customized_data(esp_wifi_setting_handle_t handle)
{
#ifdef CONFIG_BLUEDROID_ENABLED
AUDIO_NULL_CHECK(TAG, handle, return ESP_FAIL);
wifi_blufi_config_t *blufi_cfg = esp_wifi_setting_get_data(handle);
if (blufi_cfg->ble_connected_flag == false) {
ESP_LOGE(TAG, "No Ble device connected, fail to send customized data");
return ESP_FAIL;
}
if (blufi_cfg->user_data && blufi_cfg->user_data_length) {
ESP_LOGI(TAG, "Send a string to peer: %s, data len: %d", (char *)blufi_cfg->user_data, blufi_cfg->user_data_length);
return esp_blufi_send_custom_data((uint8_t *)blufi_cfg->user_data, blufi_cfg->user_data_length);
} else {
ESP_LOGW(TAG, "Nothing to be sent, please set customer data first!");
return ESP_FAIL;
}
#else
ESP_LOGW(TAG, "blufi config selected, but CONFIG_BLUEDROID_ENABLED not enabled");
return ESP_FAIL;
#endif
}
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/wifi_service/blufi_config/blufi_config.c
|
C
|
apache-2.0
| 9,405
|
/*
* 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 "sdkconfig.h"
#ifdef CONFIG_BLUEDROID_ENABLED
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "esp_log.h"
#include "esp_system.h"
#include "audio_mem.h"
#include "mbedtls/aes.h"
#include "mbedtls/dhm.h"
#include "mbedtls/md5.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 (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
#ifdef CONFIG_IDF_TARGET_ESP32
#include "esp32/rom/crc.h"
#else
#include "esp32s2beta/rom/crc.h"
#endif // CONFIG_IDF_TARGET_ESP32
#else
#include "rom/crc.h"
#endif //(ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0))
#define BLUFI_SECURITY_TAG "BLUFI_SECURITY"
/*
The SEC_TYPE_xxx is for self-defined packet data type in the procedure of "BLUFI negotiate key"
If using other negotiation procedure to exchange (or generate) a key, users should redefine the type themselves.
*/
#define SEC_TYPE_DH_PARAM_LEN 0x00
#define SEC_TYPE_DH_PARAM_DATA 0x01
#define SEC_TYPE_DH_P 0x02
#define SEC_TYPE_DH_G 0x03
#define SEC_TYPE_DH_PUBLIC 0x04
struct blufi_security {
#define DH_SELF_PUB_KEY_LEN 128
#define DH_SELF_PUB_KEY_BIT_LEN (DH_SELF_PUB_KEY_LEN * 8)
uint8_t self_public_key[DH_SELF_PUB_KEY_LEN];
#define SHARE_KEY_LEN 128
#define SHARE_KEY_BIT_LEN (SHARE_KEY_LEN * 8)
uint8_t share_key[SHARE_KEY_LEN];
size_t share_len;
#define PSK_LEN 16
uint8_t psk[PSK_LEN];
uint8_t *dh_param;
int dh_param_len;
uint8_t iv[16];
mbedtls_dhm_context dhm;
mbedtls_aes_context aes;
};
static struct blufi_security *blufi_sec;
static int myrand (void *rng_state, unsigned char *output, size_t len)
{
size_t i;
for (i = 0; i < len; ++i) {
output[i] = esp_random();
}
return ESP_OK;
}
void blufi_dh_negotiate_data_handler(uint8_t *data, int len, uint8_t **output_data, int *output_len, bool *need_free)
{
int ret;
uint8_t type = data[0];
if (blufi_sec == NULL) {
ESP_LOGE(BLUFI_SECURITY_TAG, "BLUFI Security is not initialized");
return;
}
switch (type) {
case SEC_TYPE_DH_PARAM_LEN:
blufi_sec->dh_param_len = ((data[1] << 8) | data[2]);
if (blufi_sec->dh_param) {
audio_free(blufi_sec->dh_param);
blufi_sec->dh_param = NULL;
}
blufi_sec->dh_param = (uint8_t *)audio_calloc(1, blufi_sec->dh_param_len);
if (blufi_sec->dh_param == NULL) {
ESP_LOGE(BLUFI_SECURITY_TAG, "%s, Malloc failed", __func__);
return;
}
break;
case SEC_TYPE_DH_PARAM_DATA: {
if (blufi_sec->dh_param == NULL) {
ESP_LOGE(BLUFI_SECURITY_TAG, "%s, Blufi_sec->dh_param == NULL", __func__);
return;
}
uint8_t *param = blufi_sec->dh_param;
memcpy(blufi_sec->dh_param, &data[1], blufi_sec->dh_param_len);
ret = mbedtls_dhm_read_params(&blufi_sec->dhm, ¶m, ¶m[blufi_sec->dh_param_len]);
if (ret) {
ESP_LOGE(BLUFI_SECURITY_TAG, "%s Read param failed %d", __func__, ret);
return;
}
audio_free(blufi_sec->dh_param);
blufi_sec->dh_param = NULL;
ret = mbedtls_dhm_make_public(&blufi_sec->dhm, (int) mbedtls_mpi_size( &blufi_sec->dhm.P ), blufi_sec->self_public_key, blufi_sec->dhm.len, myrand, NULL);
if (ret) {
ESP_LOGE(BLUFI_SECURITY_TAG, "%s Make public failed %d", __func__, ret);
return;
}
mbedtls_dhm_calc_secret( &blufi_sec->dhm,
blufi_sec->share_key,
SHARE_KEY_BIT_LEN,
&blufi_sec->share_len,
NULL, NULL);
mbedtls_md5(blufi_sec->share_key, blufi_sec->share_len, blufi_sec->psk);
mbedtls_aes_setkey_enc(&blufi_sec->aes, blufi_sec->psk, 128);
/* Alloc output data */
*output_data = &blufi_sec->self_public_key[0];
*output_len = blufi_sec->dhm.len;
*need_free = false;
}
break;
case SEC_TYPE_DH_P:
break;
case SEC_TYPE_DH_G:
break;
case SEC_TYPE_DH_PUBLIC:
break;
}
}
int blufi_aes_encrypt(uint8_t iv8, uint8_t *crypt_data, int crypt_len)
{
int ret;
size_t iv_offset = 0;
uint8_t iv0[16];
memcpy(iv0, blufi_sec->iv, sizeof(blufi_sec->iv));
/* Set iv8 as the iv0[0] */
iv0[0] = iv8;
ret = mbedtls_aes_crypt_cfb128(&blufi_sec->aes, MBEDTLS_AES_ENCRYPT, crypt_len, &iv_offset, iv0, crypt_data, crypt_data);
if (ret) {
return ESP_FAIL;
}
return crypt_len;
}
int blufi_aes_decrypt(uint8_t iv8, uint8_t *crypt_data, int crypt_len)
{
int ret;
size_t iv_offset = 0;
uint8_t iv0[16];
memcpy(iv0, blufi_sec->iv, sizeof(blufi_sec->iv));
/* Set iv8 as the iv0[0] */
iv0[0] = iv8;
ret = mbedtls_aes_crypt_cfb128(&blufi_sec->aes, MBEDTLS_AES_DECRYPT, crypt_len, &iv_offset, iv0, crypt_data, crypt_data);
if (ret) {
return ESP_FAIL;
}
return crypt_len;
}
uint16_t blufi_crc_checksum(uint8_t iv8, uint8_t *data, int len)
{
/* This iv8 ignore, not used */
return crc16_be(0, data, len);
}
esp_err_t blufi_security_init(void)
{
blufi_sec = (struct blufi_security *)audio_calloc(1, sizeof(struct blufi_security));
if (blufi_sec == NULL) {
return ESP_FAIL;
}
mbedtls_dhm_init(&blufi_sec->dhm);
mbedtls_aes_init(&blufi_sec->aes);
memset(blufi_sec->iv, 0x0, 16);
return ESP_OK;
}
esp_err_t blufi_security_deinit(void)
{
if (blufi_sec == NULL) {
return ESP_FAIL;
}
if (blufi_sec->dh_param) {
audio_free(blufi_sec->dh_param);
blufi_sec->dh_param = NULL;
}
mbedtls_dhm_free(&blufi_sec->dhm);
mbedtls_aes_free(&blufi_sec->aes);
memset(blufi_sec, 0x0, sizeof(struct blufi_security));
audio_free(blufi_sec);
blufi_sec = NULL;
return ESP_OK;
}
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/wifi_service/blufi_config/blufi_security.c
|
C
|
apache-2.0
| 7,606
|
#
# Main Makefile. This is basically the same as a component makefile.
COMPONENT_ADD_INCLUDEDIRS := include
COMPONENT_PRIV_INCLUDEDIRS := inc
COMPONENT_SRCDIRS := src smart_config airkiss_config blufi_config
LIBS := airkiss_aes
COMPONENT_ADD_LDFLAGS += -lmain -L $(COMPONENT_PATH)/airkiss_config $(addprefix -l,$(LIBS))
ALL_LIB_FILES += $(patsubst %,$(COMPONENT_PATH)/airkiss_config/lib%.a,$(LIBS))
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/wifi_service/component.mk
|
Makefile
|
apache-2.0
| 401
|
/*
* airkiss.h
*
* Created on: 2015-1-26
* Author: peterfan
*/
#ifndef AIRKISS_H_
#define AIRKISS_H_
#ifdef __cplusplus
extern "C" {
#endif
/*
* 定义AIRKISS_ENABLE_CRYPT为1以启用AirKiss加密功能
*/
#ifndef AIRKISS_ENABLE_CRYPT
#define AIRKISS_ENABLE_CRYPT 1
#endif
typedef void* (*airkiss_memset_fn) (void* ptr, int value, unsigned int num);
typedef void* (*airkiss_memcpy_fn) (void* dst, const void* src, unsigned int num);
typedef int (*airkiss_memcmp_fn) (const void* ptr1, const void* ptr2, unsigned int num);
typedef int (*airkiss_printf_fn) (const char* format, ...);
/*
* 对AirKiss库进行配置,目前仅定义了一些回调函数
*/
typedef struct
{
/*
* 为尽量减少库文件体积,如下c标准库函数需要上层使用者提供
* 其中printf可以为NULL
*/
airkiss_memset_fn memset;
airkiss_memcpy_fn memcpy;
airkiss_memcmp_fn memcmp;
airkiss_printf_fn printf;
} airkiss_config_t;
/*
* AirKiss API工作需要的结构体,必须为全局变量或者通过malloc动态分配
*/
typedef struct
{
int dummyap[26];
int dummy[32];
} airkiss_context_t;
/*
* AirKiss解码成功后的结果
*/
typedef struct
{
char* pwd; /* wifi密码,以'\0'结尾 */
char* ssid; /* wifi ssid,以'\0'结尾 */
unsigned char pwd_length; /* wifi密码长度 */
unsigned char ssid_length; /* wifi ssid长度 */
unsigned char random; /* 随机值,根据AirKiss协议,当wifi连接成功后,需要通过udp向10000端口广播这个随机值,这样AirKiss发送端(微信客户端或者AirKissDebugger)就能知道AirKiss已配置成功 */
unsigned char reserved; /* 保留值 */
} airkiss_result_t;
/*
* airkiss_recv()正常情况下的返回值
*/
typedef enum
{
/* 解码正常,无需特殊处理,继续调用airkiss_recv()直到解码成功 */
AIRKISS_STATUS_CONTINUE = 0,
/* wifi信道已经锁定,上层应该立即停止切换信道 */
AIRKISS_STATUS_CHANNEL_LOCKED = 1,
/* 解码成功,可以调用airkiss_get_result()取得结果 */
AIRKISS_STATUS_COMPLETE = 2
} airkiss_status_t;
#if AIRKISS_ENABLE_CRYPT
/*
* 设置解密key,最长可以为128bit,若传入的key不足128bit,则默认用0填充
*
* 返回值
* < 0:出错,通常是参数错误
* 0:成功
*/
int airkiss_set_key(airkiss_context_t* context, const unsigned char* key, unsigned int length);
#endif
/*
* 获取AirKiss库版本信息
*/
const char* airkiss_version(void);
/*
* 初始化AirKiss库,如要复用context,可以多次调用
*
* 返回值
* < 0:出错,通常是参数错误
* 0:成功
*/
int airkiss_init(airkiss_context_t* context, const airkiss_config_t* config);
/*
* 开启WiFi Promiscuous Mode后,将收到的包传给airkiss_recv以进行解码
*
* 参数说明
* frame:802.11 frame mac header(must contain at least first 24 bytes)
* length:total frame length
*
* 返回值
* < 0:出错,通常是参数错误
* >= 0:成功,请参考airkiss_status_t
*/
int airkiss_recv(airkiss_context_t* context, const void* frame, unsigned short length);
/*
* 当airkiss_recv()返回AIRKISS_STATUS_COMPLETE后,调用此函数来获取AirKiss解码结果
*
* 返回值
* < 0:出错,解码状态还不是AIRKISS_STATUS_COMPLETE
* 0:成功
*/
int airkiss_get_result(airkiss_context_t* context, airkiss_result_t* result);
/*
* 上层切换信道以后,可以调用一下本接口清缓存,降低锁定错信道的概率,注意调用的逻辑是在airkiss_init之后
*
* 返回值
* < 0:出错,通常是参数错误
* 0:成功
*/
int airkiss_change_channel(airkiss_context_t* context);
/*
*
* 以上是实现智能配置网络的相关API,以下是微信内网发现相关API
*
*/
/*
* airkiss_lan_recv()的返回值
*/
typedef enum
{
/* 提供的数据缓冲区长度不足 */
AIRKISS_LAN_ERR_OVERFLOW = -5,
/* 当前版本不支持的指令类型 */
AIRKISS_LAN_ERR_CMD = -4,
/* 打包数据出错 */
AIRKISS_LAN_ERR_PAKE = -3,
/* 函数传递参数出错 */
AIRKISS_LAN_ERR_PARA = -2,
/* 报文数据错误 */
AIRKISS_LAN_ERR_PKG = -1,
/* 报文格式正确,但是不需要设备处理的数据包 */
AIRKISS_LAN_CONTINUE = 0,
/* 接收到发现设备请求数据包 */
AIRKISS_LAN_SSDP_REQ = 1,
/* 数据包打包完成 */
AIRKISS_LAN_PAKE_READY = 2
} airkiss_lan_ret_t;
typedef enum
{
AIRKISS_LAN_SSDP_REQ_CMD = 0x1,
AIRKISS_LAN_SSDP_RESP_CMD = 0x1001,
AIRKISS_LAN_SSDP_NOTIFY_CMD = 0x1002
} airkiss_lan_cmdid_t;
/*
* 设备进入内网发现模式后,将收到的包传给airkiss_lan_recv以进行解析
*
* 参数说明
* body:通过监听端口接收到的UDP报文
* length:total frame length
* config:AirKiss回调函数
*
* 返回值
* < 0:出错,请参考airkiss_lan_ret_t,通常是报文数据出错
* >= 0:成功,请参考airkiss_lan_ret_t
*/
int airkiss_lan_recv(const void* body, unsigned short length, const airkiss_config_t* config);
/*
* 设备要发送内网协议包时,调用本接口完成数据包打包
*
* 参数说明
* ak_lan_cmdid:要发送的数据包类型,查看airkiss_lan_cmdid_t
* appid:对应device_type
* deviceid:当前设备的ID
* _datain:要发送的数据内容
* inlength:要发送的数据内容长度
* _dataout:输出数据缓冲区
* outlength:传入时应赋值为输出数据缓冲区的大小,函数返回后会赋值为要发送的数据大小
* config:AirKiss回调函数
*
* 返回值
* < 0:出错,请参考airkiss_lan_ret_t,通常是报文数据出错
* >= 0:成功,请参考airkiss_lan_ret_t
*/
int airkiss_lan_pack(airkiss_lan_cmdid_t ak_lan_cmdid, void* appid, void* deviceid, void* _datain, unsigned short inlength, void* _dataout, unsigned short* outlength, const airkiss_config_t* config);
#ifdef __cplusplus
}
#endif
#endif /* AIRKISS_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/wifi_service/inc/airkiss.h
|
C
|
apache-2.0
| 5,986
|
/*
* 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 _BLUFI_SECURITY_H_
#define _BLUFI_SECURITY_H_
#include "esp_log.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief BLUFI negotiate data handler
*
* @param[in] data data from phone
* @param[in] len length of data from phone
* @param[in] output_data data to be sent to phone
* @param[in] output_len length of data to be sent to phone
*/
void blufi_dh_negotiate_data_handler(uint8_t *data, int len, uint8_t **output_data, int *output_len, bool *need_free);
/**
* @brief BLUFI encrypt the data after negotiating a share key
*
* @param[in] iv8 initial vector(8bit), normally, blufi core will input packet sequence number
* @param[in] crypt_data plain text and encrypted data, the encrypt function must support autochthonous encrypt
* @param[in] crypt_len length of plain text
*
* @return Nonnegative number is encrypted length, if error, return negative number;
*/
int blufi_aes_encrypt(uint8_t iv8, uint8_t *crypt_data, int crypt_len);
/**
* @brief BLUFI decrypt the data after negotiating a share key
*
* @param[in] iv8 initial vector(8bit), normally, blufi core will input packet sequence number
* @param[in] crypt_data encrypted data and plain text, the encrypt function must support autochthonous decrypt
* @param[in] crypt_len length of encrypted text
*
* @return Nonnegative number is decrypted length, if error, return negative number;
*/
int blufi_aes_decrypt(uint8_t iv8, uint8_t *crypt_data, int crypt_len);
/**
* @brief BLUFI CRC check sum function
*
* @param[in] iv8 initial vector(8bit), normally, blufi core will input packet sequence number
* @param[in] data data need to checksum
* @param[in] len length of data
*
* @return None
*/
uint16_t blufi_crc_checksum(uint8_t iv8, uint8_t *data, int len);
/**
* @brief Initialize and allocate the resource for BLUFI security
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t blufi_security_init(void);
/**
* @brief Uninitialize and free the resource for BLUFI security
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t blufi_security_deinit(void);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/wifi_service/inc/blufi_security.h
|
C
|
apache-2.0
| 3,465
|
/*
* 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 __AIRKISS_CONFIG_H__
#define __AIRKISS_CONFIG_H__
#include "esp_wifi_setting.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief airkiss lan data pack
*/
typedef struct {
void *appid; /*!< APP identifer data */
void *deviceid; /*!< Device identifer data */
} airkiss_lan_pack_param_t;
/**
* @brief airkiss configurations
*/
typedef struct {
airkiss_lan_pack_param_t lan_pack; /*!< User lan pack parameter */
bool ssdp_notify_enable; /*!< Notify enable flag */
char *aes_key; /*!< Airkiss aes key data */
} airkiss_config_info_t;
#define AIRKISS_CONFIG_INFO_DEFAULT() { \
.lan_pack = { \
.appid = NULL, \
.deviceid = NULL, \
}, \
.ssdp_notify_enable = true, \
.aes_key = NULL, \
}
/**
* brief Create airkiss setting handle instance
*
* @param info Configuration of the airkiss
*
* @return
* - NULL, Fail
* - Others, Success
*/
esp_wifi_setting_handle_t airkiss_config_create(airkiss_config_info_t *info);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/wifi_service/include/airkiss_config.h
|
C
|
apache-2.0
| 2,369
|
/*
* 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 __BLUFI_CONFIG_H_
#define __BLUFI_CONFIG_H_
#include "esp_wifi_setting.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Create blufi setting handle instance
*
* @param[in] info A pointer to void
*
* @return
* - NULL, Fail
* - Others, Success
*/
esp_wifi_setting_handle_t blufi_config_create(void *info);
/**
* @brief Set flag to judge whether the station has connected to the AP
*
* @param[in] handle Wifi setting handle
* @param[in] flag bool type of station connection state
*
* @return
* - NULL, Fail
* - Others, Success
*/
esp_err_t blufi_set_sta_connected_flag(esp_wifi_setting_handle_t handle, bool flag);
/**
* @brief Set customized data to be sent after configurate wifi successfully.
*
* @param[in] handle Wifi setting handle
* @param[in] data Customized data
* @param[in] data_len Customized data length
* @return
* - ESP_FAIL, Fail
* - ESP_OK, Success
*/
esp_err_t blufi_set_customized_data(esp_wifi_setting_handle_t handle, char *data, int data_len);
/**
* @brief Send customized data that be set before
*
* @param[in] handle Wifi setting handle
* @return
* - ESP_FAIL, Fail
* - ESP_OK, Success
*/
esp_err_t blufi_send_customized_data(esp_wifi_setting_handle_t handle);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/wifi_service/include/blufi_config.h
|
C
|
apache-2.0
| 2,585
|
/*
* 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 _ESP_WIFI_SETTING_H_
#define _ESP_WIFI_SETTING_H_
#include "audio_error.h"
#include "esp_wifi_types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct esp_wifi_setting *esp_wifi_setting_handle_t;
typedef esp_err_t (* wifi_setting_func)(esp_wifi_setting_handle_t handle);
typedef esp_err_t (* wifi_setting_teardown_func)(esp_wifi_setting_handle_t handle, wifi_config_t *info);
/**
* brief Create wifi setting handle instance
*
* @param tag Tag of the wifi setting handle
*
* @return
* - NULL, Fail
* - Others, Success
*/
esp_wifi_setting_handle_t esp_wifi_setting_create(const char *tag);
/**
* brief Destroy wifi setting handle instance
*
* @param handle The wifi setting handle instance
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_wifi_setting_destroy(esp_wifi_setting_handle_t handle);
/**
* @brief Register the wifi setting execute functions
*
* @param handle The wifi setting handle instance
* @param start The start wifi setting
* @param stop The stop
* @param teardown The destroy
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_wifi_setting_register_function(esp_wifi_setting_handle_t handle,
wifi_setting_func start,
wifi_setting_func stop,
wifi_setting_teardown_func teardown
);
/**
* @brief Register the notify execute handle
*
* @param handle The peripheral handle
* @param on_handle The notify execute handle
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_wifi_setting_regitster_notify_handle(esp_wifi_setting_handle_t handle, void *on_handle);
/**
* @brief Call this to notify the `wifi_config_t` to `on_handle`
*
* @param handle The wifi setting handle instance
* @param info The `wifi_config_t`
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_wifi_setting_info_notify(esp_wifi_setting_handle_t handle, wifi_config_t *info);
/**
* @brief Set the user data
*
* @note Make sure the `data` lifetime is sufficient,
* this function does not copy all data, it only stores the data pointer
*
* @param[in] handle The wifi setting handle instance
* @param data The user data
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_wifi_setting_set_data(esp_wifi_setting_handle_t handle, void *data);
/**
* @brief Get the user data stored on `handle`
*
* @param[in] handle The wifi setting handle instance
*
* @return user data pointer
*/
void *esp_wifi_setting_get_data(esp_wifi_setting_handle_t handle);
/**
* @brief Call this to execute `start` function of wifi setting instance
*
* @param handle The wifi setting handle instance
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_wifi_setting_start(esp_wifi_setting_handle_t handle);
/**
* @brief Call this to execute `stop` function of wifi setting instance
*
* @param handle The wifi setting handle instance
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_wifi_setting_stop(esp_wifi_setting_handle_t handle);
/**
* @brief Call this to execute `teardown` function of wifi setting instance
*
* @param handle The wifi setting handle instance
* @param info The `wifi_config_t`
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_wifi_setting_teardown(esp_wifi_setting_handle_t handle, wifi_config_t *info);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/wifi_service/include/esp_wifi_setting.h
|
C
|
apache-2.0
| 4,910
|
/*
* 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 _SMART_CONFIG_H_
#define _SMART_CONFIG_H_
#include "esp_wifi_setting.h"
#include "esp_smartconfig.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief esp smartconfig configuration
*/
typedef struct {
smartconfig_type_t type; /*!< Type of smartconfig */
} smart_config_info_t;
#define SMART_CONFIG_INFO_DEFAULT() { \
.type = SC_TYPE_ESPTOUCH, \
}
/**
* brief Create smartconfig setting handle instance
*
* @param info Configuration of the smartconfig
*
* @return
* - NULL, Fail
* - Others, Success
*/
esp_wifi_setting_handle_t smart_config_create(smart_config_info_t *info);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/wifi_service/include/smart_config.h
|
C
|
apache-2.0
| 1,907
|
/*
* 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 _CONNECTIVITY_SERVICE_H_
#define _CONNECTIVITY_SERVICE_H_
#include "periph_service.h"
#include "esp_wifi_setting.h"
#include "esp_wifi_types.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief WiFi STA service status
*/
typedef enum {
WIFI_SERV_EVENT_UNKNOWN,
WIFI_SERV_EVENT_CONNECTING,
WIFI_SERV_EVENT_CONNECTED,
WIFI_SERV_EVENT_DISCONNECTED,
WIFI_SERV_EVENT_SETTING_TIMEOUT,
WIFI_SERV_EVENT_SETTING_FAILED,
WIFI_SERV_EVENT_SETTING_FINISHED,
} wifi_service_event_t;
/**
* @brief WiFi STA disconnection reasons
*/
typedef enum {
WIFI_SERV_STA_UNKNOWN,
WIFI_SERV_STA_COM_ERROR,
WIFI_SERV_STA_AUTH_ERROR,
WIFI_SERV_STA_AP_NOT_FOUND,
WIFI_SERV_STA_BY_USER,
WIFI_SERV_STA_SET_INFO,
} wifi_service_disconnect_reason_t;
/**
* @brief WiFi service configurations
*/
typedef struct {
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 */
char *user_data; /*!< User data */
int setting_timeout_s; /*!< Timeout of setting WiFi */
int max_retry_time; /*!< Maximum times of reconnection */
int max_prov_retry_time; /*!< Maximum times of reconnection after wifi provision*/
uint8_t max_ssid_num; /*!< Maximum ssid that can be stored */
} wifi_service_config_t;
#define WIFI_SERVICE_DEFAULT_CONFIG() { \
.task_stack = 3*1024, \
.task_prio = 6, \
.task_core = 0, \
.extern_stack = true, \
.evt_cb = NULL, \
.cb_ctx = NULL, \
.user_data = NULL, \
.setting_timeout_s = 60, \
.max_retry_time = 5,\
.max_prov_retry_time = 3, \
.max_ssid_num = 5, \
}
/*
* @brief Create the WiFi service instance
*
* @param config Configuration of the WiFi service
*
* @return
* - NULL, Fail
* - Others, Success
*/
periph_service_handle_t wifi_service_create(wifi_service_config_t *config);
/*
* @brief Destroy the WiFi service instance
*
* @param handle The periph_service_handle_t instance
*
* @return
* - ESP_OK, Success
* - Others, Fail
*/
esp_err_t wifi_service_destroy(periph_service_handle_t handle);
/*
* @brief Rigster the WiFi setting handle instance to configurate wifi
*
* @param handle The periph_service_handle_t instance
* @param setting Specific WiFi setting handle instance
* @param out_index Get the `setting` index
*
* @return
* - ESP_OK, Success
* - Others, Fail
*/
esp_err_t wifi_service_register_setting_handle(periph_service_handle_t handle, esp_wifi_setting_handle_t setting, int *out_index);
/*
* @brief Start setting with given index.
*
* @param handle The periph_service_handle_t instance
* @param index Specific index will be start WiFi setting
* -`0`, selected all registed instance
* - Others, got from by `wifi_service_register_setting_handle`
*
* @return
* - ESP_OK, Success
* - Others, Fail
*/
esp_err_t wifi_service_setting_start(periph_service_handle_t handle, int index);
/*
* @brief Update ssid and password and connect to the ap.
* @Note It works only after the wifi service task runs up.
*
* @param handle The periph_service_handle_t instance
* @param info A pointer to wifi_config_t
*
* @return
* - ESP_OK, Success
* - Others, Fail
*/
esp_err_t wifi_service_update_sta_info(periph_service_handle_t handle, wifi_config_t *wifi_conf);
/*
* @brief Stop setting with given index
*
* @param handle The periph_service_handle_t instance
* @param index Specific index will be stop WiFi setting
* -`0`, selected all registed instance
* - Others, got from by `wifi_service_register_setting_handle`
*
* @return
* - ESP_OK, Success
* - Others, Fail
*/
esp_err_t wifi_service_setting_stop(periph_service_handle_t handle, int index);
/*
* @brief Connect wifi
*
* @param handle The periph_service_handle_t instance
*
* @return
* - ESP_OK, Success
* - Others, Fail
*/
esp_err_t wifi_service_connect(periph_service_handle_t handle);
/*
* @brief Disconnect wifi
*
* @param handle The periph_service_handle_t instance
*
* @return
* - ESP_OK, Success
* - Others, Fail
*/
esp_err_t wifi_service_disconnect(periph_service_handle_t handle);
/*
* @brief Set the WiFi ssid and password
* @Note The wifi ssid and password is set to connect only when there is no wifi information stored in flash
*
* @param handle The periph_service_handle_t instance
* @param info A pointer to wifi_config_t
*
* @return
* - ESP_OK, Success
* - Others, Fail
*/
esp_err_t wifi_service_set_sta_info(periph_service_handle_t handle, wifi_config_t *info);
/*
* @brief Get WiFi service state
*
* @param handle The periph_service_handle_t instance
*
* @return The state of service
*
*/
periph_service_state_t wifi_service_state_get(periph_service_handle_t handle);
/*
* @brief Get WiFi disconnect reason
*
* @param handle The periph_service_handle_t instance
*
* @return The reason of disconnect
*
*/
wifi_service_disconnect_reason_t wifi_service_disconnect_reason_get(periph_service_handle_t handle);
/*
* @brief Erase all the ssid information stored in ssid manager
*
* @param handle The periph_service_handle_t instance
*
* @return
* - ESP_OK, Success
* - Others, Fail
*/
esp_err_t wifi_service_erase_ssid_manager_info(periph_service_handle_t handle);
/*
* @brief Get the last wifi configure
*
* @param handle The periph_service_handle_t instance
* @param wifi_cfg A pointer to wifi_config_t
*
* @return
* - ESP_OK, Success
* - Others, Fail
*/
esp_err_t wifi_service_get_last_ssid_cfg(periph_service_handle_t handle, wifi_config_t* wifi_cfg);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/espressif_adf/esp-adf/components/wifi_service/include/wifi_service.h
|
C
|
apache-2.0
| 7,632
|