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
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #ifndef AOS_UNIT_TEST_H #define AOS_UNIT_TEST_H #include <stddef.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif #ifndef AOS_EXPORTX #define AOS_EXPORT(ret, fun, ...) #endif #ifndef AOS_COMPONENT_INIT #define AOS_COMPONENT_INIT(fun, ...) #endif #ifndef AOS_TESTCASE #define AOS_TESTCASE(fun, ...) #endif typedef void (*yunit_test_case_proc)(void); typedef struct { const char *name; yunit_test_case_proc test_proc; } yunit_test_case_t; #define YUNIT_TEST_CASE_NULL { 0 } typedef int (*yunit_test_suit_init)(void); typedef int (*yunit_test_suit_deinit)(void); typedef void (*yunit_test_case_setup)(void); typedef void (*yunit_test_case_teardown)(void); typedef struct { const char *name; yunit_test_suit_init init; yunit_test_suit_deinit deinit; yunit_test_case_setup setup; yunit_test_case_teardown teardown; yunit_test_case_t *test_case_array; } yunit_test_suite_t; #define YUNIT_TEST_SUITE_NULL { 0 } void *yunit_add_test_suite( const char *name, yunit_test_suit_init init, yunit_test_suit_deinit deinit, yunit_test_case_setup setup, yunit_test_case_teardown teardown); int yunit_add_test_case( void *test_suite, const char *name, yunit_test_case_proc proc); int yunit_add_test_suites(yunit_test_suite_t *test_suite_array); void *yunit_get_test_suite(const char *name); void *yunit_get_test_case(void *test_suite, const char *name); void yunit_test_init(void); void yunit_test_deinit(void); int yunit_test_run(void); int yunit_run_test_suite(void *test_suite); int yunit_run_test_case(void *test_suite, void *test_case); void yunit_test_print_result(void); enum { TEST_RESULT_SUCCESS = 0, TEST_RESULT_FAILURE, TEST_RESULT_FATAL }; void yunit_add_test_case_result( int result_type, const char *file, size_t line, const char *fmt, ...); #define YUNIT_FAIL(msg) \ yunit_add_test_case_result( \ TEST_RESULT_FAILURE, __FILE__, __LINE__, "%s", msg); #define YUNIT_FAIL_FATAL(msg) \ yunit_add_test_case_result( \ TEST_RESULT_FATAL, __FILE__, __LINE__, "%s", msg); #define YUNIT_ASSERT(expr) \ do { \ yunit_add_test_case_result( \ (expr) ? TEST_RESULT_SUCCESS : TEST_RESULT_FAILURE, \ __FILE__, __LINE__, "%s", #expr); \ } while (0); /* print msg if failure, else nothing */ #define YUNIT_ASSERT_MSG(expr, fmt, args...) \ do { \ yunit_add_test_case_result( \ (expr) ? TEST_RESULT_SUCCESS : TEST_RESULT_FAILURE, \ __FILE__, __LINE__, "expect (%s) but actual ("fmt")", #expr, ##args); \ } while (0); #define YUNIT_ASSERT_FETAL(expr) \ do { \ yunit_add_test_case_result( \ (expr) ? TEST_RESULT_SUCCESS : TEST_RESULT_FATAL, \ __FILE__, __LINE__, "%s", #expr); \ } while (0); #define YUNIT_ASSERT_TRUE(expr) YUNIT_ASSERT(expr) #define YUNIT_ASSERT_FALSE(expr) YUNIT_ASSERT(!(expr)) #define YUNIT_ASSERT_TRUE_FATAL(expr) YUNIT_ASSERT_FETAL(expr) #define YUNIT_ASSERT_EQUAL(expect, actual) \ do { \ int result = (expect == actual); \ yunit_add_test_case_result( \ result ? TEST_RESULT_SUCCESS : TEST_RESULT_FAILURE, \ __FILE__, __LINE__, \ "%s==%s", #expect, #actual); \ } while (0); #define YUNIT_ASSERT_EQUAL_FATAL(expect, actual) \ do { \ yunit_add_test_case_result( \ (expect == actual) ? TEST_RESULT_SUCCESS : TEST_RESULT_FATAL, \ __FILE__, __LINE__, "%s==%s", #expect, #actual); \ } while (0); #define YUNIT_ASSERT_STR_EQUAL(expect, actual) \ do { \ int result = strcmp((const char *)expect, (const char *)actual) == 0; \ yunit_add_test_case_result( \ result ? TEST_RESULT_SUCCESS : TEST_RESULT_FAILURE, \ __FILE__, __LINE__, \ result ? "%s(%s)==%s(%s)" : "expect %s(%s) but actual is %s(%s)", \ #expect, (const char *)expect, #actual, (const char *)actual); \ } while (0); #define YUNIT_ASSERT_STR_N_EQUAL(expect, actual, len) \ do { \ int result = strncmp((const char *)expect, (const char *)actual, len) == 0; \ yunit_add_test_case_result( \ result ? TEST_RESULT_SUCCESS : TEST_RESULT_FAILURE, \ __FILE__, __LINE__, \ result ? "%s(%s)==%s(%s) len=%d" \ : "expect %s(%s) but actual is %s(%s) len=%d", \ #expect, (const char *)expect, #actual, (const char *)actual, len); \ } while (0); #define YUNIT_ASSERT_PTR_NULL(p) YUNIT_ASSERT_PTR_EQUAL(p, NULL) #define YUNIT_ASSERT_PTR_NOT_NULL(p) YUNIT_ASSERT_PTR_NOT_EQUAL(p, NULL) #define YUNIT_ASSERT_PTR_EQUAL(expect, actual) \ do { \ int result = (expect == actual); \ yunit_add_test_case_result( \ result ? TEST_RESULT_SUCCESS : TEST_RESULT_FAILURE, \ __FILE__, __LINE__, \ result ? "%s(%p)==%s(%p)" : "expect %s(%p) but actual is %s(%p)", \ #expect, expect, #actual, actual); \ } while (0); #define YUNIT_ASSERT_PTR_NOT_EQUAL(expect, actual) \ do { \ int result = (expect != actual); \ yunit_add_test_case_result( \ result ? TEST_RESULT_SUCCESS : TEST_RESULT_FAILURE, \ __FILE__, __LINE__, \ result ? "%s(%p)!=%s(%p)" : "expect %s(%p) but actual is %s(%p)", \ #expect, expect, #actual, actual); \ } while (0); #define PRINT_TASK_INFO(task) \ printf("\t%-40s%-10d%-20d\n",\ task->task_name, \ (int)task->task_state, \ (int)task->stack_size*sizeof(cpu_stack_t)) #define PRINT_ALL_TASK_INFO() do { \ klist_t *taskhead = &g_kobj_list.task_head; \ klist_t *taskend = taskhead;\ klist_t *tmp;\ ktask_t *task; \ printf("\t--------------------------------------------------------------\n");\ printf("\t%-40s%-10s%-20s\n", "Name","State", "StackSize");\ printf("\t--------------------------------------------------------------\n");\ for (tmp = taskhead->next; tmp != taskend; tmp = tmp->next) { \ task = krhino_list_entry(tmp, ktask_t, task_stats_item);\ PRINT_TASK_INFO(task);\ }\ printf("\t--------------------------------------------------------------\n");\ }while(0) #ifdef __cplusplus } #endif #endif /* AOS_UNIT_TEST_H */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/include/yunit.h
C
apache-2.0
6,388
NAME := pwm_test $(NAME)_MBINS_TYPE := app $(NAME)_VERSION := 0.0.1 $(NAME)_SUMMARY := testcase for pwm $(NAME)_SOURCES += pwm_test.c $(NAME)_CFLAGS += -Wall -Werror
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/pwm/aos.mk
Makefile
apache-2.0
176
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdint.h> #include <string.h> #include <stdlib.h> #include "aos/kernel.h" #include "aos/hal/pwm.h" #include "pwm_test.h" #define PWM_TESTCASE_NUM 10 pwm_dev_t pwm_dev; pwm_config_t config; pwm_config_t testsace_config[PWM_TESTCASE_NUM] = {{.freq = 1000, .duty_cycle = 0.5f}, {.freq = 1000, .duty_cycle = 0.0f}, {.freq = 1000, .duty_cycle = 0.3f}, {.freq = 1000, .duty_cycle = 0.7f}, {.freq = 1000, .duty_cycle = 1.0f}, {.freq = 2000, .duty_cycle = 0.5f}, {.freq = 2000, .duty_cycle = 0.0f}, {.freq = 2000, .duty_cycle = 0.3f}, {.freq = 2000, .duty_cycle = 0.7f}, {.freq = 2000, .duty_cycle = 1.0f}}; void hal_pwm_test_init(void) { int i = 0; printf("*********** pwm test start ! ***********\n"); printf("enter the testcase you want to test: \n"); printf("for example: enter \"pwm_testcase1\" to test frequence 1000hz duty_cycle 50%%\n"); for (i = 0; i < PWM_TESTCASE_NUM; ++i) { printf("pwm_testcase%d [frequence:%dhz duty_cycle:%d%% ]\n",(i + 1) ,testsace_config[i].freq, (int)(testsace_config[i].duty_cycle * 100)); } } void hal_pwm_test_output(char *msg) { int ret = -1; int num = 0; num = atoi(msg); if (num > PWM_TESTCASE_NUM) { printf("testcase number error !\n"); return; } printf("pwm output frequence: %dhz duty_cycle: %d%%\n", testsace_config[num - 1].freq, (int)(testsace_config[num - 1].duty_cycle * 100)); hal_pwm_stop(&pwm_dev); pwm_dev.port = PORT_PWM_TEST; pwm_dev.config.freq = testsace_config[num - 1].freq; pwm_dev.config.duty_cycle = testsace_config[num - 1].duty_cycle; ret = hal_pwm_init(&pwm_dev); if (ret != 0) { printf("hal_pwm_init error !\n"); return; } hal_pwm_start(&pwm_dev); printf("please observe the output waveform through the oscilloscope to judge whether it is correct !\n"); } void hal_pwm_test_finalize(void) { int ret = -1; ret = hal_pwm_finalize(&pwm_dev); if (ret != 0) { printf("hal_pwm_finalize error !\n"); return; } printf("pwm test result: succeed !\n"); printf("*********** pwm test end ! ***********\n"); }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/pwm/pwm_test.c
C
apache-2.0
2,689
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #define PORT_PWM_TEST 0 void hal_pwm_test(void);
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/pwm/pwm_test.h
C
apache-2.0
115
src = Split(''' pwm_test.c ''') component = aos_component('pwm_test', src) component.add_cflags('-Wall') component.add_cflags('-Werror')
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/pwm/ucube.py
Python
apache-2.0
143
NAME := rng_test $(NAME)_MBINS_TYPE := app $(NAME)_VERSION := 0.0.1 $(NAME)_SUMMARY := testcase for rng $(NAME)_SOURCES += rng_test.c $(NAME)_CFLAGS += -Wall -Werror
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/rng/aos.mk
Makefile
apache-2.0
176
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdint.h> #include <string.h> #include "aos/kernel.h" #include "aos/hal/rng.h" #include "rng_test.h" #define RNG_TEST_TIMES 1000 random_dev_t rng_dev; uint32_t random_buf[RNG_TEST_TIMES]; void hal_rng_test(void) { int ret = -1; int i = 0; int j = 0; uint32_t data = 0; uint32_t repeat_cnt = 0; float repeat_rate = 0; printf("*********** rng test start ! ***********\n"); memset(random_buf, 0, sizeof(random_buf)); rng_dev.port = PORT_RNG_TEST; printf("step1: read random number %d times ! \n", (int)RNG_TEST_TIMES); for (i = 0; i < RNG_TEST_TIMES; i++) { ret = hal_random_num_read(rng_dev, &random_buf[i], sizeof(uint32_t)); if (ret != 0) { printf("hal_random_num_read error !\n"); return; } } for (i = 0; i < RNG_TEST_TIMES; ++i) { for (j = i; j < (RNG_TEST_TIMES - i - 1); ++j) { if (random_buf[j] > random_buf[j + 1]) { data = random_buf[j + 1]; random_buf[j + 1] = random_buf[j]; random_buf[j] = data; } } } for (i = 0; i < RNG_TEST_TIMES - 1; i++) { if (random_buf[j] == random_buf[j + 1]) { repeat_cnt++; } printf("%x\n", random_buf[i]); } printf("step2: check the number repetition rate !\n"); repeat_rate = (float)repeat_cnt / (float)RNG_TEST_TIMES; printf("repeat_rate is %f \n", repeat_rate); if (repeat_rate > 0.001f) { printf("hal_rtc_test failed !\n"); return; } printf("rng test result: succeed !\n"); printf("*********** rng test end ! ***********\n"); }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/rng/rng_test.c
C
apache-2.0
1,784
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #define PORT_RNG_TEST 0 void hal_rng_test(void);
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/rng/rng_test.h
C
apache-2.0
115
src = Split(''' rng_test.c ''') component = aos_component('rng_test', src) component.add_cflags('-Wall') component.add_cflags('-Werror')
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/rng/ucube.py
Python
apache-2.0
143
NAME := rtc_test $(NAME)_MBINS_TYPE := app $(NAME)_VERSION := 0.0.1 $(NAME)_SUMMARY := testcase for rtc $(NAME)_SOURCES += rtc_test.c $(NAME)_CFLAGS += -Wall -Werror
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/rtc/aos.mk
Makefile
apache-2.0
176
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdint.h> #include <string.h> #include "aos/kernel.h" #include "aos/hal/rtc.h" #include "rtc_test.h" #define RTC_DELAY_MS 2000 #define RTC_TOLERANCE_RANGE 0.01f static rtc_time_t rtc_time_r; static rtc_time_t rtc_time = {.sec = 45, .min = 30, .hr = 15, .weekday = 5, .date = 1, .month = 3, .year = 19}; static rtc_dev_t rtc_dev; void hal_rtc_test(void) { int ret = -1; printf("*********** rtc test start ! ***********\n"); memset(&rtc_time_r, 0, sizeof(rtc_time_t)); rtc_dev.port = PORT_RTC_TEST; rtc_dev.config.format = HAL_RTC_FORMAT_DEC; printf("step1: set rtc date to\n"); printf(" year: %d month: %d date: %d weekday: %d hr: %d min: %d sec: %d\n", rtc_time.year, rtc_time.month, rtc_time.date, rtc_time.weekday, rtc_time.hr, rtc_time.min, rtc_time.sec); ret = hal_rtc_init(&rtc_dev); if (ret != 0) { printf("hal_rtc_init error !\n"); return; } ret = hal_rtc_set_time(&rtc_dev, &rtc_time); if (ret != 0) { printf("hal_rtc_set_time error !\n"); return; } printf("step2: sleep %d ms !\n", RTC_DELAY_MS); aos_msleep(RTC_DELAY_MS * (1 + RTC_TOLERANCE_RANGE)); ret = hal_rtc_get_time(&rtc_dev, &rtc_time_r); if (ret != 0) { printf("hal_rtc_get_time error !\n"); return; } printf("step3: read rtc, current date is\n"); printf(" year: %d month: %d date: %d weekday: %d hr: %d min: %d sec: %d\n", rtc_time_r.year, rtc_time_r.month, rtc_time_r.date, rtc_time_r.weekday, rtc_time_r.hr, rtc_time_r.min, rtc_time_r.sec); if ((rtc_time_r.sec != rtc_time.sec + RTC_DELAY_MS / 1000) ||(rtc_time_r.min != rtc_time.min) ||(rtc_time_r.hr != rtc_time.hr) ||(rtc_time_r.weekday != rtc_time.weekday) ||(rtc_time_r.date != rtc_time.date) ||(rtc_time_r.month != rtc_time.month) ||(rtc_time_r.year != rtc_time.year)) { printf("rtc value error !\n"); return; } ret = hal_rtc_finalize(&rtc_dev); if (ret != 0) { printf("hal_rtc_finalize error !\n"); return; } printf("rtc test result: succeed !\n"); printf("*********** rtc test end ! ***********\n"); }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/rtc/rtc_test.c
C
apache-2.0
2,340
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #define PORT_RTC_TEST 0 void hal_rtc_test(void);
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/rtc/rtc_test.h
C
apache-2.0
115
src = Split(''' rtc_test.c ''') component = aos_component('rtc_test', src) component.add_cflags('-Wall') component.add_cflags('-Werror')
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/rtc/ucube.py
Python
apache-2.0
143
NAME := spi_test $(NAME)_MBINS_TYPE := app $(NAME)_VERSION := 0.0.1 $(NAME)_SUMMARY := testcase for spi $(NAME)_SOURCES += spi_test.c $(NAME)_CFLAGS += -Wall -Werror
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/spi/aos.mk
Makefile
apache-2.0
176
#ifndef __SPI_FLASH_H #define __SPI_FLASH_H #include "stm32f10x.h" #define SPI_FLASH_SPI SPI1 #define SPI_FLASH_SPI_CLK RCC_APB2Periph_SPI1 #define SPI_FLASH_SPI_SCK_PIN GPIO_Pin_5 /* PA.05 */ #define SPI_FLASH_SPI_SCK_GPIO_PORT GPIOA /* GPIOA */ #define SPI_FLASH_SPI_SCK_GPIO_CLK RCC_APB2Periph_GPIOA #define SPI_FLASH_SPI_MISO_PIN GPIO_Pin_6 /* PA.06 */ #define SPI_FLASH_SPI_MISO_GPIO_PORT GPIOA /* GPIOA */ #define SPI_FLASH_SPI_MISO_GPIO_CLK RCC_APB2Periph_GPIOA #define SPI_FLASH_SPI_MOSI_PIN GPIO_Pin_7 /* PA.07 */ #define SPI_FLASH_SPI_MOSI_GPIO_PORT GPIOA /* GPIOA */ #define SPI_FLASH_SPI_MOSI_GPIO_CLK RCC_APB2Periph_GPIOA #define SPI_FLASH_CS_PIN GPIO_Pin_4 /* PC.04 */ #define SPI_FLASH_CS_GPIO_PORT GPIOA /* GPIOC */ #define SPI_FLASH_CS_GPIO_CLK RCC_APB2Periph_GPIOA #define SPI_FLASH_CS_LOW() GPIO_ResetBits(GPIOA, GPIO_Pin_4) #define SPI_FLASH_CS_HIGH() GPIO_SetBits(GPIOA, GPIO_Pin_4) void SPI_FLASH_Init(void); void SPI_FLASH_SectorErase(u32 SectorAddr); void SPI_FLASH_BulkErase(void); void SPI_FLASH_PageWrite(u8* pBuffer, u32 WriteAddr, u16 NumByteToWrite); void SPI_FLASH_BufferWrite(u8* pBuffer, u32 WriteAddr, u16 NumByteToWrite); void SPI_FLASH_BufferRead(u8* pBuffer, u32 ReadAddr, u16 NumByteToRead); u32 SPI_FLASH_ReadID(void); u32 SPI_FLASH_ReadDeviceID(void); void SPI_FLASH_StartReadSequence(u32 ReadAddr); void SPI_Flash_PowerDown(void); void SPI_Flash_WAKEUP(void); u8 SPI_FLASH_ReadByte(void); u8 SPI_FLASH_SendByte(u8 byte); u16 SPI_FLASH_SendHalfWord(u16 HalfWord); void SPI_FLASH_WriteEnable(void); void SPI_FLASH_WaitForWriteEnd(void); #endif /* __SPI_FLASH_H */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/spi/spi_flash.h
C
apache-2.0
2,055
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdint.h> #include <string.h> #include <stdlib.h> #include "aos/kernel.h" #include "aos/hal/spi.h" #include "spi_test.h" #include "board.h" #include "stm32f4xx_hal.h" /* Private define ------------------------------------------------------------*/ #define W25X_WriteEnable 0x06 #define W25X_WriteDisable 0x04 #define W25X_ReadStatusReg 0x05 #define W25X_WriteStatusReg 0x01 #define W25X_ReadData 0x03 #define W25X_FastReadData 0x0B #define W25X_FastReadDual 0x3B #define W25X_PageProgram 0x02 #define W25X_BlockErase 0xD8 #define W25X_SectorErase 0x20 #define W25X_ChipErase 0xC7 #define W25X_PowerDown 0xB9 #define W25X_ReleasePowerDown 0xAB #define W25X_DeviceID 0xAB #define W25X_ManufactDeviceID 0x90 #define W25X_JedecDeviceID 0x9F #define WIP_Flag 0x01 /* Write In Progress (WIP) flag */ #define Dummy_Byte 0xFF #define TEST_DATA_BYTES 128 static spi_dev_t spi_dev; static uint8_t write_buf[TEST_DATA_BYTES]; static uint8_t read_buf[TEST_DATA_BYTES]; static int32_t flash_spi_init(void); static int32_t flash_spi_read(void *buf, uint32_t bytes); static int32_t flash_spi_write(void *buf, uint32_t bytes); static int32_t flash_spi_erase(void); SPI_HandleTypeDef hspi1; /* SPI1 init function */ static void MX_SPI1_Init(void) { /* SPI1 parameter configuration*/ hspi1.Instance = SPI1; hspi1.Init.Mode = SPI_MODE_MASTER; hspi1.Init.Direction = SPI_DIRECTION_2LINES; hspi1.Init.DataSize = SPI_DATASIZE_8BIT; hspi1.Init.CLKPolarity = SPI_POLARITY_LOW; hspi1.Init.CLKPhase = SPI_PHASE_2EDGE; hspi1.Init.NSS = SPI_NSS_SOFT; hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16; hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB; hspi1.Init.TIMode = SPI_TIMODE_DISABLE; hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; hspi1.Init.CRCPolynomial = 10; if (HAL_SPI_Init(&hspi1) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } } uint8_t flash_spi_read_device_id(void) { uint8_t data = 0; uint8_t data_r = 0; int ret = -1; /* Select the FLASH: Chip Select low */ //SPI_FLASH_CS_LOW(); /* Send "RDID " instruction */ data = W25X_DeviceID; ret = HAL_SPI_Transmit(&hspi1, &data, 1, 100); printf("ret %d\n", ret); data = Dummy_Byte; HAL_SPI_TransmitReceive(&hspi1, &data, &data_r, 1, 1000); HAL_SPI_TransmitReceive(&hspi1, &data, &data_r, 1, 1000); HAL_SPI_TransmitReceive(&hspi1, &data, &data_r, 1, 1000); HAL_SPI_TransmitReceive(&hspi1, &data, &data_r, 1, 1000); while (HAL_SPI_GetState(&hspi1) != HAL_SPI_STATE_READY) { } /* Read a byte from the FLASH */ data = Dummy_Byte; ret = HAL_SPI_TransmitReceive(&hspi1, &data, &data_r, 1, 1000); printf("ret %d\n", ret); /* Deselect the FLASH: Chip Select high */ //SPI_FLASH_CS_HIGH(); return data_r; } uint32_t flash_spi_read_id(void) { uint32_t data1 = 0; uint32_t data2 = 0; uint32_t data3 = 0; uint32_t data4 = 0; uint8_t data = 0; uint8_t data_r = 0; int ret = -1; /* Select the FLASH: Chip Select low */ //SPI_FLASH_CS_LOW(); /* Send "RDID " instruction */ data = 0x90; HAL_SPI_TransmitReceive(&hspi1, &data, &data_r, 1, 1000); data = 0x00; HAL_SPI_TransmitReceive(&hspi1, &data, &data_r, 1, 1000); data = 0x00; HAL_SPI_TransmitReceive(&hspi1, &data, &data_r, 1, 1000); data = 0x00; HAL_SPI_TransmitReceive(&hspi1, &data, &data_r, 1, 1000); data = 0xFF; HAL_SPI_TransmitReceive(&hspi1, &data, &data1, 1, 1000); data = 0xFF; HAL_SPI_TransmitReceive(&hspi1, &data, &data2, 1, 1000); data4 = (data1 << 8) | data2; return data4; } #if 0 uint8_t flash_spi_read_device_id(void) { uint8_t data = 0; int ret = -1; /* Select the FLASH: Chip Select low */ //SPI_FLASH_CS_LOW(); /* Send "RDID " instruction */ data = W25X_DeviceID; ret = hal_spi_send(&spi_dev, &data, 1, AOS_WAIT_FOREVER); printf("ret %d\n", ret); data = Dummy_Byte; hal_spi_send(&spi_dev, &data, 1, AOS_WAIT_FOREVER); hal_spi_send(&spi_dev, &data, 1, AOS_WAIT_FOREVER); hal_spi_send(&spi_dev, &data, 1, AOS_WAIT_FOREVER); hal_spi_send(&spi_dev, &data, 1, AOS_WAIT_FOREVER); /* Read a byte from the FLASH */ hal_spi_recv(&spi_dev, &data, 1, AOS_WAIT_FOREVER); /* Deselect the FLASH: Chip Select high */ //SPI_FLASH_CS_HIGH(); return data; } #endif /* a spi interface rtc(ds1307) must be connetted to the mcu before testing */ void hal_spi_test(void) { int ret = -1; int i = 0; printf("*********** spi test start ! ***********\n"); memset(read_buf, 0, sizeof(read_buf)); //ret = flash_spi_init(); //if (ret != 0) { // printf("flash_spi_init error ! test failed !\n"); // return; //} MX_SPI1_Init(); //uint8_t data = flash_spi_read_device_id(); //printf("flash_spi_read_device_id: %x\n", data); uint32_t data32 = flash_spi_read_id(); printf("flash_spi_read_id: %x\n", data32); return; ret = flash_spi_erase(); if (ret != 0) { printf("flash_spi_erase error ! test failed !\n"); return; } for (i = 0; i < TEST_DATA_BYTES; i++) { write_buf[i] = i; } ret = flash_spi_write(write_buf, TEST_DATA_BYTES); if (ret != 0) { printf("flash_spi_write error ! test failed !\n"); return; } ret = flash_spi_read(read_buf, TEST_DATA_BYTES); if (ret != 0) { printf("flash_spi_read error ! test failed !\n"); return; } for (i = 0; i < TEST_DATA_BYTES; i++) { if (write_buf[i] != read_buf[i]) { printf("error ! read data diff with write data ! test failed !\n"); return; } } ret = hal_spi_finalize(&spi_dev); if (ret != 0) { printf("hal_spi_finalize error ! test failed !\n"); return; } printf("spi test result: succeed !\n"); printf("*********** spi test end ! ***********\n"); } int32_t flash_spi_init(void) { int ret = -1; spi_dev.port = PORT_SPI_1; spi_dev.config.mode = HAL_SPI_MODE_MASTER; spi_dev.config.freq = 15000000; ret = hal_spi_init(&spi_dev); if (ret != 0) { printf("hal_spi_init error !\n"); } return ret; } int32_t flash_spi_read(void *buf, uint32_t bytes) { int ret = -1; return ret; } int32_t flash_spi_write(void *buf, uint32_t bytes) { int ret = -1; return ret; } int32_t flash_spi_erase(void) { int ret = -1; return ret; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/spi/spi_test.c
C
apache-2.0
6,821
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #define PORT_SPI_TEST 1 void hal_spi_test(void);
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/spi/spi_test.h
C
apache-2.0
115
src = Split(''' spi_test.c ''') component = aos_component('spi_test', src) component.add_cflags('-Wall') component.add_cflags('-Werror')
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/spi/ucube.py
Python
apache-2.0
143
NAME := timer_test $(NAME)_MBINS_TYPE := app $(NAME)_VERSION := 0.0.1 $(NAME)_SUMMARY := testcase for timer $(NAME)_SOURCES += timer_test.c $(NAME)_CFLAGS += -Wall -Werror
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/timer/aos.mk
Makefile
apache-2.0
182
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdint.h> #include <stdio.h> #include <string.h> #include "aos/kernel.h" #include "aos/hal/timer.h" #include "timer_test.h" #define TIMER_PERIOD_US_TEST1 100000 #define TIMER_PERIOD_US_TEST2 200000 #define TIMER_PERIOD_TOLERANCE_RANGE 0.01f static timer_dev_t timer_dev; static aos_sem_t timer_test_sem; static char *msg = "AliOS Things"; static int success_flag = 1; static uint64_t systime_cur = 0; static uint64_t systime_pre = 0; static uint64_t period_us_cur = 0; void timer_handler(void *arg); int error_flag = 0; uint64_t period_us_calc = 0; void hal_timer_test(void) { int ret = -1; printf("*********** timer test start ! ***********\n"); timer_dev.port = PORT_TIMER_TEST; timer_dev.config.period = TIMER_PERIOD_US_TEST1; timer_dev.config.reload_mode = TIMER_RELOAD_AUTO; timer_dev.config.cb = &timer_handler; timer_dev.config.arg = msg; ret = aos_sem_new(&timer_test_sem, 0); if (ret != 0) { success_flag = 0; printf("sem new error ! test failed\n"); return; } printf("step1: set timer period to %d us, and check the period !\n", timer_dev.config.period); ret = hal_timer_init(&timer_dev); if (ret != 0) { success_flag = 0; printf("hal_timer_init error ! test failed\n"); return; } period_us_cur = timer_dev.config.period; ret = hal_timer_start(&timer_dev); if (ret != 0) { success_flag = 0; printf("hal_timer_start error ! test failed\n"); return; } aos_sem_wait(&timer_test_sem, AOS_WAIT_FOREVER); ret = hal_timer_finalize(&timer_dev); if (ret != 0) { success_flag = 0; printf("hal_timer_finalize error ! test failed\n"); return; } printf("error_flag %d\n", error_flag); printf("period_us_calc %d\n", (int)period_us_calc); if (success_flag == 1) { printf("timer test result: 【success】 !\n"); } else { printf("timer test result: 【failed】 !\n"); } printf("*********** timer test end ! ***********\n"); } void timer_handler(void *arg) { static int count = 0; int ret = -1; timer_config_t timer_conf; systime_pre = systime_cur; systime_cur = aos_now_ms(); if (count > 0) { period_us_calc = (systime_cur - systime_pre) * 1000; if ((period_us_calc < (uint64_t)(period_us_cur * (1.0f - TIMER_PERIOD_TOLERANCE_RANGE))) || (period_us_calc > (uint64_t)(period_us_cur * (1.0f + TIMER_PERIOD_TOLERANCE_RANGE)))) { success_flag = 0; error_flag = 1; //printf("timer period error ! test failed\n"); aos_sem_signal(&timer_test_sem); } } #if (TIMER_ARG_ENABLE == 1) if (strcmp(msg, arg) != 0) { success_flag = 0; //printf("timer_handler arg error ! test failed\n"); error_flag = 2; aos_sem_signal(&timer_test_sem); } #endif if (count == 3) { timer_conf.period = TIMER_PERIOD_US_TEST2; timer_conf.reload_mode = TIMER_RELOAD_AUTO; timer_conf.cb = &timer_handler; timer_conf.arg = msg; //printf("step2: set timer period to %d us, and check the period !\n", timer_conf.period); hal_timer_stop(&timer_dev); ret = hal_timer_para_chg(&timer_dev, timer_conf); if (ret != 0) { success_flag = 0; error_flag = 3; //printf("hal_timer_para_chg error ! test failed\n"); aos_sem_signal(&timer_test_sem); } hal_timer_start(&timer_dev); period_us_cur = timer_conf.period; } if (count == 5) { aos_sem_signal(&timer_test_sem); } count++; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/timer/timer_test.c
C
apache-2.0
3,775
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #define PORT_TIMER_TEST 1 void hal_timer_test(void);
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/timer/timer_test.h
C
apache-2.0
119
src = Split(''' flash_test.c ''') component = aos_component('flash_test', src) component.add_cflags('-Wall') component.add_cflags('-Werror')
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/timer/ucube.py
Python
apache-2.0
147
NAME := uart_test $(NAME)_MBINS_TYPE := app $(NAME)_VERSION := 0.0.1 $(NAME)_SUMMARY := testcase for uart $(NAME)_SOURCES += uart_test.c ymodem.c $(NAME)_CFLAGS += -Wall -Werror
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/uart/aos.mk
Makefile
apache-2.0
188
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdint.h> #include <string.h> #include "aos/kernel.h" #include "aos/hal/uart.h" #include "uart_test.h" #include "ymodem.h" uart_dev_t uart_dev; void hal_uart_test(void) { int32_t ret = -1; printf("*********** uart test start ! ***********\n"); printf("send file from the PC by ymodem protocol !\n"); ret = SerialDownload(); if (ret > 0) { printf("uart test result: succeed !\n"); } else { printf("uart test result: failed !\n"); } printf("*********** uart test end ! ***********\n"); }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/uart/uart_test.c
C
apache-2.0
637
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #define PORT_UART_TEST 0 void hal_uart_test(void);
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/uart/uart_test.h
C
apache-2.0
117
src = Split(''' uart_test.c ''') component = aos_component('uart_test', src) component.add_cflags('-Wall') component.add_cflags('-Werror')
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/uart/ucube.py
Python
apache-2.0
145
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ /* Includes ------------------------------------------------------------------*/ #include "ymodem.h" void Int2Str(uint8_t *str, int32_t intnum); void Int2Str(uint8_t *str, int32_t intnum); uint8_t FileName[256]; void Int2Str(uint8_t *str, int32_t intnum); uint8_t tab_1024[1024] = {0}; int32_t SerialDownload(void) { char Number[10] = " "; int32_t Size = 0; hal_partition_t partition = 0; printf("Waiting for the file to be sent ... (press 'a' to abort)\r\n"); Size = Ymodem_Receive( &tab_1024[0], partition ); if (Size > 0) { printf("\n\n\r Successfully!\n\r\r\n Name: %s", FileName); Int2Str((uint8_t *)Number, Size); printf("\n\r Size: %s Bytes\r\n", Number); } else if (Size == -1) { printf("\n\n\rImage size is higher than memory!\n\r"); } else if (Size == -2) { printf("\n\n\rVerification failed!\r\n"); } else if (Size == -3) { printf("\r\n\nAborted.\r\n"); } else { printf("\n\rReceive failed!\r\n"); } return Size; } extern uart_dev_t uart_0; /** * @brief Receive byte from sender * @param c: Character * @param timeout: Timeout * @retval 0: Byte received * -1: Timeout */ static int32_t Receive_Byte (uint8_t *c, uint32_t timeout) { if (hal_uart_recv_II(&uart_0, c, 1, NULL, timeout ) != 0) { return -1; } else { return 0; } } /** * @brief Send a byte * @param c: Character * @retval 0: Byte sent */ static uint32_t Send_Byte (uint8_t c) { hal_uart_send(&uart_0, &c, 1 ,HAL_WAIT_FOREVER); return 0; } uint16_t UpdateCRC16_ymodem(uint16_t crcIn, uint8_t byte) { uint32_t crc = crcIn; uint32_t in = byte | 0x100; do { crc <<= 1; in <<= 1; if (in & 0x100) { ++crc; } if (crc & 0x10000) { crc ^= 0x1021; } } while (!(in & 0x10000)); return crc & 0xffffu; } void CRC16_Init_ymodem( CRC16_Context *inContext ) { inContext->crc = 0; } void CRC16_Update_ymodem( CRC16_Context *inContext, const void *inSrc, size_t inLen ) { const uint8_t *src = (const uint8_t *) inSrc; const uint8_t *srcEnd = src + inLen; while ( src < srcEnd ) { inContext->crc = UpdateCRC16_ymodem(inContext->crc, *src++); } } void CRC16_Final_ymodem( CRC16_Context *inContext, uint16_t *outResult ) { inContext->crc = UpdateCRC16_ymodem(inContext->crc, 0); inContext->crc = UpdateCRC16_ymodem(inContext->crc, 0); *outResult = inContext->crc & 0xffffu; } void Int2Str(uint8_t *str, int32_t intnum) { uint32_t i, Div = 1000000000, j = 0, Status = 0; for (i = 0; i < 10; i++) { str[j++] = (intnum / Div) + 48; intnum = intnum % Div; Div /= 10; if ((str[j - 1] == '0') & (Status == 0)) { j = 0; } else { Status++; } } } uint32_t Str2Int(uint8_t *inputstr, int32_t *intnum) { uint32_t i = 0, res = 0; uint32_t val = 0; if (inputstr[0] == '0' && (inputstr[1] == 'x' || inputstr[1] == 'X')) { if (inputstr[2] == '\0') { return 0; } for (i = 2; i < 11; i++) { if (inputstr[i] == '\0') { *intnum = val; /* return 1; */ res = 1; break; } if (ISVALIDHEX(inputstr[i])) { val = (val << 4) + CONVERTHEX(inputstr[i]); } else { /* Return 0, Invalid input */ res = 0; break; } } /* Over 8 digit hex --invalid */ if (i >= 11) { res = 0; } } else { /* max 10-digit decimal input */ for (i = 0; i < 11; i++) { if (inputstr[i] == '\0') { *intnum = val; /* return 1 */ res = 1; break; } else if ((inputstr[i] == 'k' || inputstr[i] == 'K') && (i > 0)) { val = val << 10; *intnum = val; res = 1; break; } else if ((inputstr[i] == 'm' || inputstr[i] == 'M') && (i > 0)) { val = val << 20; *intnum = val; res = 1; break; } else if (ISVALIDDEC(inputstr[i])) { val = val * 10 + CONVERTDEC(inputstr[i]); } else { /* return 0, Invalid input */ res = 0; break; } } /* Over 10 digit decimal --invalid */ if (i >= 11) { res = 0; } } return res; } /** * @brief Receive a packet from sender * @param data * @param length * @param timeout * 0: end of transmission * -1: abort by sender * >0: packet length * @retval 0: normally return * -1: timeout or packet error * 1: abort by user */ static int32_t Receive_Packet (uint8_t *data, int32_t *length, uint32_t timeout) { uint16_t i, packet_size; uint8_t c; *length = 0; if (Receive_Byte(&c, timeout) != 0) { return -1; } switch (c) { case SOH: packet_size = PACKET_SIZE; break; case STX: packet_size = PACKET_1K_SIZE; break; case EOT: return 0; case CA: if ((Receive_Byte(&c, timeout) == 0) && (c == CA)) { *length = -1; return 0; } else { return -1; } case ABORT1: case ABORT2: return 1; default: return -1; } *data = c; for (i = 1; i < (packet_size + PACKET_OVERHEAD); i ++) { if (Receive_Byte(data + i, timeout) != 0) { return -1; } } if (data[PACKET_SEQNO_INDEX] != ((data[PACKET_SEQNO_COMP_INDEX] ^ 0xff) & 0xff)) { return -1; } *length = packet_size; return 0; } /** * @brief Receive a file using the ymodem protocol. * @param buf: Address of the first byte. * @retval The size of the file. */ int32_t Ymodem_Receive (uint8_t *buf, hal_partition_t partition) { uint8_t packet_data[PACKET_1K_SIZE + PACKET_OVERHEAD], file_size[FILE_SIZE_LENGTH], *file_ptr, *buf_ptr; int32_t i, packet_length, session_done, file_done, packets_received, errors, session_begin, remain_size=0, size = 0; uint32_t ramsource; uint32_t maxRecvSize; uint32_t flashdestination; #ifdef CONFIG_MX108 if(partition == HAL_PARTITION_APPLICATION) { flashdestination = hal_flash_get_info(partition)->partition_start_addr / 16; } else #endif { flashdestination = 0; } //yangjia maxRecvSize = hal_flash_get_info(partition)->partition_length; maxRecvSize = 1024*1024*1024; for (session_done = 0, errors = 0, session_begin = 0; ;) { for (packets_received = 0, file_done = 0, buf_ptr = buf; ;) { switch (Receive_Packet(packet_data, &packet_length, NAK_TIMEOUT)) { case 0: errors = 0; switch (packet_length) { /* Abort by sender */ case - 1: Send_Byte(ACK); return 0; /* End of transmission */ case 0: Send_Byte(ACK); file_done = 1; break; /* Normal packet */ default: if ((packet_data[PACKET_SEQNO_INDEX] & 0xff) != (packets_received & 0xff)) { Send_Byte(NAK); } else { if (packets_received == 0) { /* Filename packet */ if (packet_data[PACKET_HEADER] != 0) { /* Filename packet has valid data */ for (i = 0, file_ptr = packet_data + PACKET_HEADER; (*file_ptr != 0) && (i < FILE_NAME_LENGTH);) { FileName[i++] = *file_ptr++; } FileName[i++] = '\0'; for (i = 0, file_ptr ++; (*file_ptr != ' ') && (i < FILE_SIZE_LENGTH);) { file_size[i++] = *file_ptr++; } file_size[i++] = '\0'; Str2Int(file_size, &size); remain_size = size; /* Test the size of the image to be sent */ /* Image size is greater than Flash size */ if (size > (maxRecvSize + 1)) { /* End session */ Send_Byte(CA); Send_Byte(CA); Send_Byte(CA); Send_Byte(CA); return -1; } /* erase user application area */ //yangjia hal_flash_erase(partition, 0, hal_flash_get_info(partition)->partition_length); Send_Byte(ACK); Send_Byte(CRC16); } /* Filename packet is empty, end session */ else { Send_Byte(ACK); file_done = 1; session_done = 1; break; } } /* Data packet */ else { memcpy(buf_ptr, packet_data + PACKET_HEADER, packet_length); ramsource = (uint32_t)buf; if( remain_size < packet_length) packet_length = remain_size; remain_size -= packet_length; /* Write received data in Flash */ Send_Byte(ACK); #if 0 if(hal_flash_write(partition, &flashdestination, ramsource, packet_length) == 0) { Send_Byte(ACK); } else /* An error occurred while writing to Flash memory */ { /* End session */ Send_Byte(CA); Send_Byte(CA); return -2; } #endif } packets_received ++; session_begin = 1; } } break; case 1: Send_Byte(CA); Send_Byte(CA); return -3; default: if (session_begin > 0) { errors ++; } if (errors > MAX_ERRORS) { Send_Byte(CA); Send_Byte(CA); return 0; } Send_Byte(CRC16); break; } if (file_done != 0) { break; } } if (session_done != 0) { break; } } return (int32_t)size; } /** * @brief check response using the ymodem protocol * @param buf: Address of the first byte * @retval The size of the file */ int32_t Ymodem_CheckResponse(uint8_t c) { return 0; } /** * @brief Prepare the first block * @param timeout * 0: end of transmission * @retval None */ void Ymodem_PrepareIntialPacket(uint8_t *data, const uint8_t* fileName, uint32_t *length) { uint16_t i, j; uint8_t file_ptr[10]; /* Make first three packet */ data[0] = SOH; data[1] = 0x00; data[2] = 0xff; /* Filename packet has valid data */ for (i = 0; (fileName[i] != '\0') && (i < FILE_NAME_LENGTH);i++) { data[i + PACKET_HEADER] = fileName[i]; } data[i + PACKET_HEADER] = 0x00; Int2Str (file_ptr, *length); for (j =0, i = i + PACKET_HEADER + 1; file_ptr[j] != '\0' ; ) { data[i++] = file_ptr[j++]; } for (j = i; j < PACKET_SIZE + PACKET_HEADER; j++) { data[j] = 0; } } /** * @brief Prepare the data packet * @param timeout * 0: end of transmission * @retval None */ void Ymodem_PreparePacket(hal_partition_t partition, uint32_t flashdestination, uint8_t *data, uint8_t pktNo, uint32_t sizeBlk) { uint16_t i, size, packetSize; /* Make first three packet */ packetSize = sizeBlk >= PACKET_1K_SIZE ? PACKET_1K_SIZE : PACKET_SIZE; size = sizeBlk < packetSize ? sizeBlk :packetSize; if (packetSize == PACKET_1K_SIZE) { data[0] = STX; } else { data[0] = SOH; } data[1] = pktNo; data[2] = (~pktNo); //yangjia hal_flash_read( partition, &flashdestination, data + PACKET_HEADER, size ); if ( size <= packetSize) { for (i = size + PACKET_HEADER; i < packetSize + PACKET_HEADER; i++) { data[i] = 0x1A; /* EOF (0x1A) or 0x00 */ } } } /** * @brief Cal CRC16 for YModem Packet * @param data * @param length * @retval None */ uint16_t Cal_CRC16(const uint8_t* data, uint32_t size) { CRC16_Context contex; uint16_t ret; CRC16_Init_ymodem( &contex ); CRC16_Update_ymodem( &contex, data, size ); CRC16_Final_ymodem( &contex, &ret ); return ret; } /** * @brief Cal Check sum for YModem Packet * @param data * @param length * @retval None */ uint8_t CalChecksum(const uint8_t* data, uint32_t size) { uint32_t sum = 0; const uint8_t* dataEnd = data+size; while(data < dataEnd ) sum += *data++; return (sum & 0xffu); } /** * @brief Transmit a data packet using the ymodem protocol * @param data * @param length * @retval None */ void Ymodem_SendPacket(uint8_t *data, uint16_t length) { uint16_t i; i = 0; while (i < length) { Send_Byte(data[i]); i++; } } /** * @brief Transmit a file using the ymodem protocol * @param buf: Address of the first byte * @retval The size of the file */ uint8_t Ymodem_Transmit (hal_partition_t partition, const uint8_t* sendFileName) { uint8_t packet_data[PACKET_1K_SIZE + PACKET_OVERHEAD]; uint8_t filename[FILE_NAME_LENGTH]; uint8_t tempCheckSum; uint32_t buf_ptr; uint16_t tempCRC; uint16_t blkNumber; uint8_t receivedC[2], CRC16_F = 0, i; uint32_t errors, ackReceived, size = 0, pktSize; uint32_t flashdestination; uint32_t sizeFile; #ifdef CONFIG_MX108 if(partition == HAL_PARTITION_APPLICATION) { //yangjia flashdestination = hal_flash_get_info(partition)->partition_start_addr / 16; //yangjia sizeFile = hal_flash_get_info(partition)->partition_length / 16 * 15; } else #endif { flashdestination = 0; //yangjia sizeFile = hal_flash_get_info(partition)->partition_length; } errors = 0; ackReceived = 0; for (i = 0; i < (FILE_NAME_LENGTH - 1); i++) { filename[i] = sendFileName[i]; } CRC16_F = 1; /* Prepare first block */ Ymodem_PrepareIntialPacket(&packet_data[0], filename, &sizeFile); do { /* Send Packet */ Ymodem_SendPacket(packet_data, PACKET_SIZE + PACKET_HEADER); /* Send CRC or Check Sum based on CRC16_F */ if (CRC16_F) { tempCRC = Cal_CRC16(&packet_data[3], PACKET_SIZE); Send_Byte(tempCRC >> 8); Send_Byte(tempCRC & 0xFF); } else { tempCheckSum = CalChecksum (&packet_data[3], PACKET_SIZE); Send_Byte(tempCheckSum); } /* Wait for Ack and 'C' */ if (Receive_Byte(&receivedC[0], 1000) == 0) { if (receivedC[0] == ACK) { /* Packet transferred correctly */ ackReceived = 1; } } else { errors++; } }while (!ackReceived && (errors < 0x0A)); if (errors >= 0x0A) { return errors; } buf_ptr = flashdestination; size = sizeFile; blkNumber = 0x01; /* Here 1024 bytes package is used to send the packets */ Receive_Byte(&receivedC[0], 1000); /* Resend packet if NAK for a count of 10 else end of communication */ while (size) { /* Prepare next packet */ //Ymodem_PreparePacket(buf_ptr, &packet_data[0], blkNumber, size); Ymodem_PreparePacket(partition, buf_ptr, &packet_data[0], blkNumber, size); ackReceived = 0; receivedC[0]= 0; errors = 0; do { /* Send next packet */ if (size >= PACKET_1K_SIZE) { pktSize = PACKET_1K_SIZE; } else { pktSize = PACKET_SIZE; } Ymodem_SendPacket(packet_data, pktSize + PACKET_HEADER); /* Send CRC or Check Sum based on CRC16_F */ /* Send CRC or Check Sum based on CRC16_F */ if (CRC16_F) { tempCRC = Cal_CRC16(&packet_data[3], pktSize); Send_Byte(tempCRC >> 8); Send_Byte(tempCRC & 0xFF); } else { tempCheckSum = CalChecksum (&packet_data[3], pktSize); Send_Byte(tempCheckSum); } /* Wait for Ack */ if ((Receive_Byte(&receivedC[0], 1000) == 0) && (receivedC[0] == ACK)) { ackReceived = 1; if (size > pktSize) { buf_ptr += pktSize; size -= pktSize; blkNumber++; } else { buf_ptr += pktSize; size = 0; } } else { errors++; } }while(!ackReceived && (errors < 0x0A)); /* Resend packet if NAK for a count of 10 else end of communication */ if (errors >= 0x0A) { return errors; } } ackReceived = 0; receivedC[0] = 0x00; errors = 0; do { Send_Byte(EOT); /* Send (EOT); */ /* Wait for Ack */ if ((Receive_Byte(&receivedC[0], 1000) == 0) && receivedC[0] == ACK) { ackReceived = 1; } else { errors++; } }while (!ackReceived && (errors < 0x0A)); if (errors >= 0x0A) { return errors; } /* Last packet preparation */ ackReceived = 0; receivedC[0] = 0x00; errors = 0; packet_data[0] = SOH; packet_data[1] = 0; packet_data [2] = 0xFF; for (i = PACKET_HEADER; i < (PACKET_SIZE + PACKET_HEADER); i++) { packet_data [i] = 0x00; } do { /* Send Packet */ Ymodem_SendPacket(packet_data, PACKET_SIZE + PACKET_HEADER); /* Send CRC or Check Sum based on CRC16_F */ tempCRC = Cal_CRC16(&packet_data[3], PACKET_SIZE); Send_Byte(tempCRC >> 8); Send_Byte(tempCRC & 0xFF); /* Wait for Ack and 'C' */ if (Receive_Byte(&receivedC[0], 1000) == 0) { if (receivedC[0] == ACK) { /* Packet transferred correctly */ ackReceived = 1; } } else { errors++; } }while (!ackReceived && (errors < 0x0A)); /* Resend packet if NAK for a count of 10 else end of communication */ if (errors >= 0x0A) { return errors; } do { Send_Byte(EOT); /* Send (EOT); */ /* Wait for Ack */ if ((Receive_Byte(&receivedC[0], 10) == 0) && receivedC[0] == ACK) { ackReceived = 1; } else { errors++; } }while (!ackReceived && (errors < 0x0A)); if (errors >= 0x0A) { return errors; } return 0; /* file transmitted successfully */ }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/uart/ymodem.c
C
apache-2.0
19,712
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __YMODEM_H_ #define __YMODEM_H_ #include <stdio.h> #include <string.h> #include <stdint.h> #include "aos/hal/uart.h" #include "aos/hal/flash.h" /* Includes ------------------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ #define PACKET_SEQNO_INDEX (1) #define PACKET_SEQNO_COMP_INDEX (2) #define PACKET_HEADER (3) #define PACKET_TRAILER (2) #define PACKET_OVERHEAD (PACKET_HEADER + PACKET_TRAILER) #define PACKET_SIZE (128) #define PACKET_1K_SIZE (1024) #define FILE_NAME_LENGTH (256) #define FILE_SIZE_LENGTH (16) #define SOH (0x01) /* start of 128-byte data packet */ #define STX (0x02) /* start of 1024-byte data packet */ #define EOT (0x04) /* end of transmission */ #define ACK (0x06) /* acknowledge */ #define NAK (0x15) /* negative acknowledge */ #define CA (0x18) /* two of these in succession aborts transfer */ #define CRC16 (0x43) /* 'C' == 0x43, request 16-bit CRC */ #define ABORT1 (0x41) /* 'A' == 0x41, abort by user */ #define ABORT2 (0x61) /* 'a' == 0x61, abort by user */ #define NAK_TIMEOUT (1000) #define MAX_ERRORS (20) typedef struct { uint8_t crc; } CRC8_Context; typedef struct { uint16_t crc; } CRC16_Context; /* Private define ------------------------------------------------------------*/ #define IS_AF(c) ((c >= 'A') && (c <= 'F')) #define IS_af(c) ((c >= 'a') && (c <= 'f')) #define IS_09(c) ((c >= '0') && (c <= '9')) #define ISVALIDHEX(c) IS_AF(c) || IS_af(c) || IS_09(c) #define ISVALIDDEC(c) IS_09(c) #define CONVERTDEC(c) (c - '0') #define CONVERTHEX_alpha(c) (IS_AF(c) ? (c - 'A'+10) : (c - 'a'+10)) #define CONVERTHEX(c) (IS_09(c) ? (c - '0') : CONVERTHEX_alpha(c)) /* Exported functions ------------------------------------------------------- */ int32_t Ymodem_Receive (uint8_t *buf, hal_partition_t partition); uint8_t Ymodem_Transmit (hal_partition_t partition, const uint8_t* sendFileName); int32_t SerialDownload(void); #endif /* __YMODEM_H_ */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/uart/ymodem.h
C
apache-2.0
2,665
src = Split(''' hal_test.c ''') component = aos_component('hal_test', src) component.add_cflags('-Wall') component.add_cflags('-Werror')
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/ucube.py
Python
apache-2.0
143
NAME := wdg_test $(NAME)_MBINS_TYPE := app $(NAME)_VERSION := 0.0.1 $(NAME)_SUMMARY := testcase for wdg $(NAME)_SOURCES += wdg_test.c $(NAME)_CFLAGS += -Wall -Werror
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/wdg/aos.mk
Makefile
apache-2.0
176
src = Split(''' flash_test.c ''') component = aos_component('flash_test', src) component.add_cflags('-Wall') component.add_cflags('-Werror')
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/wdg/ucube.py
Python
apache-2.0
147
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdint.h> #include <string.h> #include "aos/kernel.h" #include "aos/hal/wdg.h" #include "aos/hal/flash.h" #include "wdg_test.h" /* if WGD_TIMEOUT_MS is 1000, WGD_TIMEOUT_TOLERANCE_RANGE is 0.3f, wdg test will be OK if the real timeout in the range [700, 1300] */ #define WGD_TIMEOUT_MS 1000 #define WGD_TIMEOUT_TOLERANCE_RANGE 0.2f static wdg_dev_t wdg_dev; static hal_logic_partition_t *partition_info = NULL; static int success_flag = 0; static void wdg_timeout_test(void); static void wdg_normal_test(void); static uint16_t read_wdg_flag(void); static void write_wdg_flag(uint16_t value); static void clear_wdg_flag(void); void hal_wdg_test(void) { int ret = -1; uint16_t wdg_flag = 0; printf("*********** wdg test begin ! ***********\n"); /* init the wdg */ wdg_dev.port = PORT_WDG_TEST; wdg_dev.config.timeout = WGD_TIMEOUT_MS; ret = hal_wdg_init(&wdg_dev); if (ret != 0) { printf("hal_wdg_init error !\n"); return; } partition_info = hal_flash_get_info(PARTITION_WDG_TEST); if (partition_info == NULL) { printf("wdg_flag get error !\n"); } /* get the wdg flag */ wdg_flag = read_wdg_flag(); switch(wdg_flag) { case 0xF000: printf("wdg_normal_test failed !\n"); success_flag = 0; break; case 0xFF00: printf("wdg_timeout_test failed !\n"); success_flag = 0; break; case 0xFFF0: printf("wdg_normal_test begin !\n"); wdg_normal_test(); wdg_flag = read_wdg_flag(); if (wdg_flag == 0x0000) { success_flag = 1; } else { printf("wdg_normal_test failed !\n"); success_flag = 0; } break; case 0xFFFF: printf("wdg_timeout_test begin !\n"); wdg_timeout_test(); printf("wdg_timeout_test failed !\n"); success_flag = 0; break; default: printf("wdg flag error !\n"); success_flag = 0; break; } ret = hal_wdg_finalize(&wdg_dev); if (ret != 0) { printf("hal_wdg_finalize error !\n"); } if (success_flag == 0) { printf("wdg test result: failed !\n"); } else { printf("wdg test result: succeed !\n"); } clear_wdg_flag(); printf("*********** wdg test end ! ***********\n"); } void wdg_timeout_test(void) { write_wdg_flag(0xFFF0); hal_wdg_reload(&wdg_dev); /* delay timeout to make cpu restart */ aos_msleep(WGD_TIMEOUT_MS * (1 + WGD_TIMEOUT_TOLERANCE_RANGE)); /* this code will not be executed because wdg timeout and cpu restart */ write_wdg_flag(0xFF00); } void wdg_normal_test(void) { write_wdg_flag(0xF000); hal_wdg_reload(&wdg_dev); /* delay no timeout */ aos_msleep(WGD_TIMEOUT_MS * (1 - WGD_TIMEOUT_TOLERANCE_RANGE)); /* this code must be executed because sleep time is shorter than timeout */ write_wdg_flag(0x0000); } uint16_t read_wdg_flag(void) { int ret = -1; uint16_t value = 0; uint32_t offset = 0; offset = 0; ret = hal_flash_read(PARTITION_WDG_TEST, &offset, &value, sizeof(uint16_t)); if (ret != 0) { printf("hal_flash_read error ! test failed\n"); return 0; } return value; } void write_wdg_flag(uint16_t value) { int ret = -1; uint32_t offset = 0; offset = 0; ret = hal_flash_write(PARTITION_WDG_TEST, &offset, &value, sizeof(uint16_t)); if (ret != 0) { printf("hal_flash_write error ! test failed\n"); } } void clear_wdg_flag(void) { int ret = -1; ret = hal_flash_erase(PARTITION_WDG_TEST, 0, partition_info->partition_length); if (ret != 0) { printf("hal_flash_erase error ! test failed\n"); } }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/wdg/wdg_test.c
C
apache-2.0
3,985
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #define PORT_WDG_TEST 0 #define PARTITION_WDG_TEST HAL_PARTITION_OTA_TEMP void rtc_test_init(void);
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/wdg/wdg_test.h
C
apache-2.0
166
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdarg.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "aos/kernel.h" #include "ulog/ulog.h" #include "yunit.h" #define TAG "yunit" typedef struct yunit_test_case_node_s { struct yunit_test_case_node_s *next; const char *name; yunit_test_case_proc test_proc; } yunit_test_case_node_t; typedef struct yunit_test_suite_node_s { struct yunit_test_suite_node_s *next; const char *name; yunit_test_suit_init init; yunit_test_suit_deinit deinit; yunit_test_case_setup setup; yunit_test_case_teardown teardown; yunit_test_case_node_t test_case_list_header; } yunit_test_suite_node_t; #define TEST_RESULT_MESSAGE_LENGTH 64 typedef struct yunit_test_case_result_s { struct yunit_test_case_result_s *next; const char *file; size_t line; char msg[TEST_RESULT_MESSAGE_LENGTH]; } yunit_test_case_result_t; typedef struct { yunit_test_suite_node_t test_suite_list_header; int all_test_cases_count; int failed_test_cases_count; int fatal_test_cases_count; yunit_test_case_result_t failed_test_case_result; } yunit_test_context_t; static int yunit_run_test_case_list( yunit_test_suite_node_t *suite, yunit_test_case_node_t *test_case_list_header); yunit_test_context_t g_test_context; void yunit_test_init(void) { memset(&g_test_context, 0, sizeof(yunit_test_context_t)); } void yunit_test_deinit(void) { yunit_test_suite_node_t *test_suite_node = g_test_context.test_suite_list_header.next; while (test_suite_node != NULL) { yunit_test_case_node_t *test_case_node = test_suite_node->test_case_list_header.next; while (test_case_node != NULL) { yunit_test_case_node_t *test_case_node_next = test_case_node->next; aos_free(test_case_node); test_case_node = test_case_node_next; } yunit_test_suite_node_t *test_suite_node_next = test_suite_node->next; aos_free(test_suite_node); test_suite_node = test_suite_node_next; } yunit_test_case_result_t *test_case_result = g_test_context.failed_test_case_result.next; while (test_case_result != NULL) { yunit_test_case_result_t *test_case_result_next = test_case_result->next; aos_free(test_case_result); test_case_result = test_case_result_next; } } void *yunit_add_test_suite( const char *name, yunit_test_suit_init init, yunit_test_suit_deinit deinit, yunit_test_case_setup setup, yunit_test_case_teardown teardown) { yunit_test_suite_node_t *node = aos_malloc(sizeof(yunit_test_suite_node_t)); if (node == NULL) { printf("%s\n", "out of memory"); return NULL; } memset(node, 0, sizeof(yunit_test_suite_node_t)); node->next = NULL; node->name = name; node->init = init; node->deinit = deinit; node->setup = setup; node->teardown = teardown; yunit_test_suite_node_t *prev = &g_test_context.test_suite_list_header; while (prev->next != NULL) { prev = prev->next; } prev->next = node; return node; } int yunit_add_test_case(void *test_suite, const char *name, yunit_test_case_proc proc) { yunit_test_suite_node_t *test_suite_node = test_suite; yunit_test_case_node_t *prev = &test_suite_node->test_case_list_header; while (prev->next != NULL) { prev = prev->next; } yunit_test_case_node_t *node = aos_malloc(sizeof(yunit_test_case_node_t)); memset(node,0,sizeof(yunit_test_case_node_t)); if (node == NULL) { printf("%s\n", "out of memory"); return -1; } node->name = name; node->test_proc = proc; prev->next = node; return 0; } int yunit_add_test_suites(yunit_test_suite_t *test_suit_array) { int i = 0; while (test_suit_array[i].name != NULL) { yunit_test_suite_t *test_suite = &test_suit_array[i++]; void *test_suite_node = yunit_add_test_suite( test_suite->name, test_suite->init, test_suite->deinit, test_suite->setup, test_suite->teardown); if (test_suite_node == NULL) { return -1; } int j = 0; yunit_test_case_t *test_case_array = test_suite->test_case_array; while (test_case_array[j].name != NULL) { yunit_test_case_t *test_case = &test_case_array[j++]; int ret = yunit_add_test_case( test_suite_node, test_case->name, test_case->test_proc); if (ret == -1) { return ret; } } } return 0; } void *yunit_get_test_suite(const char *name) { yunit_test_suite_node_t *node = g_test_context.test_suite_list_header.next; while (node != NULL) { if (strcmp(node->name, name) == 0) { return node; } node = node->next; } return NULL; } void *yunit_get_test_case(void *test_suite, const char *name) { yunit_test_suite_node_t *test_suite_node = test_suite; yunit_test_case_node_t *node = test_suite_node->test_case_list_header.next; while (node != NULL) { if (strcmp(node->name, name) == 0) { return node; } node = node->next; } return NULL; } int yunit_test_run(void) { int ret = 0; yunit_test_suite_node_t* test_suite = g_test_context.test_suite_list_header.next; while (test_suite != NULL) { ret = yunit_run_test_suite(test_suite); if (ret != 0) { return ret; } test_suite = test_suite->next; } return ret; } int yunit_run_test_suite(void *test_suite) { int ret = 0; yunit_test_suite_node_t *node = test_suite; printf("run test suites %s\n", node->name); if (node->init != NULL) { node->init(); } ret = yunit_run_test_case_list(node, &node->test_case_list_header); if (node->deinit != NULL) { node->deinit(); } if (ret != 0) { LOGE(TAG, "run test suite %s error: ret = %d", node->name, ret); return ret; } return 0; } static int _run_test_case(void *test_suite, void *test_case) { yunit_test_suite_node_t *test_suite_node = test_suite; yunit_test_case_node_t *test_case_node = test_case; int cnt1 = g_test_context.failed_test_cases_count + g_test_context.fatal_test_cases_count; int cnt2; long long now = aos_now_ms(); int delta; if (test_suite_node->setup != NULL) { test_suite_node->setup(); } fprintf(stderr, "run test case %s\n", test_case_node->name); test_case_node->test_proc(); if (test_suite_node->teardown != NULL) { test_suite_node->teardown(); } cnt2 = g_test_context.failed_test_cases_count + g_test_context.fatal_test_cases_count; delta = aos_now_ms() - now; fprintf(stderr, "test case %s finished %d failed %d ms\n", test_case_node->name, cnt2-cnt1, delta); return 0; } int yunit_run_test_case(void *test_suite, void *test_case) { int ret = 0; yunit_test_suite_node_t *tnode = test_suite; yunit_test_case_node_t *tcase = test_case; printf("run test suites %s\n", tnode->name); if (tnode->init != NULL) { tnode->init(); } ret = _run_test_case(tnode, tcase); if (tnode->deinit != NULL) { tnode->deinit(); } if (ret != 0) { LOGE(TAG, "run test suite %s error: ret = %d", tnode->name, ret); return ret; } return 0; } int yunit_run_test_case_list(yunit_test_suite_node_t *test_suite, yunit_test_case_node_t *test_case_list_header) { int ret = 0; yunit_test_case_node_t *node = test_case_list_header->next; while (node != NULL) { ret = _run_test_case(test_suite, node); if (ret != 0) { return ret; } node = node->next; } return ret; } void yunit_add_test_case_result(int type, const char *file, size_t line, const char *fmt, ...) { g_test_context.all_test_cases_count++; if (type == TEST_RESULT_SUCCESS) { return; } if (type == TEST_RESULT_FAILURE) { g_test_context.failed_test_cases_count++; } else if (type == TEST_RESULT_FATAL) { g_test_context.fatal_test_cases_count++; } else { } yunit_test_case_result_t *result = aos_malloc(sizeof(yunit_test_case_result_t)); if (result == NULL) { printf("%s\n", "out of memory"); return; } memset(result, 0, sizeof(yunit_test_case_result_t)); va_list args; va_start(args, fmt); vsnprintf(result->msg, TEST_RESULT_MESSAGE_LENGTH, fmt, args); va_end(args); result->file = file; result->line = line; yunit_test_case_result_t *prev = &g_test_context.failed_test_case_result; while (prev != NULL && prev->next != NULL) { prev = prev->next; } prev->next = result; } void yunit_test_print_result(void) { printf("\n--------------------------------\n"); printf("%d test cases, %d failed\n\n", g_test_context.all_test_cases_count, g_test_context.failed_test_cases_count + g_test_context.fatal_test_cases_count); yunit_test_case_result_t *result = g_test_context.failed_test_case_result.next; while (result != NULL) { printf("failed at %s(#%d) %s\n", result->file, result->line, result->msg); result = result->next; } printf("\n--------------------------------\n"); }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/yunit.c
C
apache-2.0
9,923
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdbool.h> #include <string.h> #include <k_api.h> #include "aos/hal/timer.h" #include "board.h" #include "timer_api.h" gtimer_t local_timer; int32_t hal_timer_init(timer_dev_t *tim) { int32_t ret = -1; if(tim == NULL) return -1; memset(&local_timer, 0, sizeof(local_timer)); switch(tim->port) { case MICO_TIMER_2: case MICO_TIMER_3: gtimer_init(&local_timer, tim->port); ret = 0; break; default: printf("ERROR: Please USE Tmer2 and Timer3\n\r"); break; } return 0; } int32_t hal_timer_start(timer_dev_t *tim) { if(tim == NULL) return -1; if(tim->config.reload_mode == TIMER_RELOAD_MANU){ gtimer_start_one_shout(&local_timer, tim->config.period, tim->config.cb, (uint32_t)tim->config.arg); }else if(tim->config.reload_mode == TIMER_RELOAD_AUTO){ gtimer_start_periodical(&local_timer, tim->config.period, tim->config.cb, (uint32_t)tim->config.arg); }else{ printf("ERROR: Reload mode Set ERROR\n\r"); return -1; } return 0; } void hal_timer_stop(timer_dev_t *tim) { if (tim != NULL){ gtimer_stop(&local_timer); } } int32_t hal_timer_finalize(timer_dev_t *tim) { if(tim == NULL) return -1; gtimer_deinit(&local_timer); return 0; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_timer.c
C
apache-2.0
1,293
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdbool.h> #include <string.h> #include <k_api.h> #include "ulog/ulog.h" #include "aos/hal/uart.h" #include "aos/hal/timer.h" #include "board.h" #include "diag.h" #include "platform_stdlib.h" #define TAG "hw" #define us2tick(us) \ ((us * RHINO_CONFIG_TICKS_PER_SECOND + 999999) / 1000000) uart_dev_t uart_0; uart_dev_t uart_1; extern int sys_reset(); void hal_reboot(void) { sys_reset(); } #if 0 static void _timer_cb(void *timer, void *arg) { timer_dev_t *tmr = arg; tmr->config.cb(tmr->config.arg); } int32_t hal_timer_init(timer_dev_t *tim) { if (tim->config.reload_mode == TIMER_RELOAD_AUTO) { krhino_timer_dyn_create((ktimer_t **)&tim->priv, "hwtmr", _timer_cb, us2tick(tim->config.period), us2tick(tim->config.period), tim, 0); } else { krhino_timer_dyn_create((ktimer_t **)&tim->priv, "hwtmr", _timer_cb, us2tick(tim->config.period), 0, tim, 0); } return 0; } int32_t hal_timer_start(timer_dev_t *tmr) { return krhino_timer_start(tmr->priv); } void hal_timer_stop(timer_dev_t *tmr) { krhino_timer_stop(tmr->priv); krhino_timer_dyn_del(tmr->priv); tmr->priv = NULL; } #endif void hw_start_hal(void) { printf("start hal-----------\n"); uart_0.port = MICO_UART_1; uart_0.config.baud_rate = 115200; uart_0.config.data_width = DATA_WIDTH_8BIT; uart_0.config.parity = NO_PARITY; uart_0.config.stop_bits = STOP_BITS_1; uart_0.config.flow_control = FLOW_CONTROL_DISABLED; hal_uart_init(&uart_0); printf("hal init successed\n\r"); }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hw.c
C
apache-2.0
1,742
/* * Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #include <stdio.h> #include <k_api.h> #include <stdint.h> #include <stdbool.h> #include "board.h" #include "aos/hal/i2c.h" #include "i2c_api.h" #include "pinmap.h" /*I2C pin location: * I2C0: * - S0: PA_25(SCL)/PA_26(SDA). * - S1: PB_5(SCL)/PB_6(SDA). */ typedef enum{ I2C_NUM_0 = 0, /*!< I2C port 0 */ I2C_NUM_1 , /*!< I2C port 1 */ I2C_NUM_MAX } i2c_port_t; i2c_t i2c_pa = {0}; i2c_t i2c_pb = {0}; typedef struct i2c_resource { i2c_t * dev; PinName scl_io; PinName sda_io; } i2c_resource_t; static i2c_resource_t g_dev[I2C_NUM_MAX] = { {&i2c_pa,PA_25,PA_26}, {&i2c_pb,PB_5,PB_6} }; int32_t hal_i2c_init(i2c_dev_t *i2c) { int32_t ret = 0; if(NULL == i2c || (MICO_I2C_1 != i2c->port && MICO_I2C_2 != i2c->port)) { return (-1); } i2c_resource_t * resource = &g_dev[i2c->port]; #ifdef I2C_MASTER_DEVICE i2c_init(resource->dev, resource->sda_io ,resource->scl_io); i2c_frequency(resource->dev,i2c->config.freq); #else //I2C_SLAVE_DEVICE i2c_init(resource->dev, resource->sda_io ,resource->scl_io); i2c_frequency(resource->dev,i2c->config.freq); i2c_slave_address(resource->dev, 0, i2c->config.dev_addr, 0xFF); i2c_slave_mode(resource->dev, 1); #endif return ret; } int32_t hal_i2c_master_send(i2c_dev_t *i2c, uint16_t dev_addr, const uint8_t *data,uint16_t size, uint32_t timeout) { int32_t ret = 0; uint16_t len; (void)timeout; if(NULL == i2c || (NULL == data) ||(MICO_I2C_1 != i2c->port && MICO_I2C_2 != i2c->port)) { return (-1); } i2c_resource_t * resource = &g_dev[i2c->port]; len = (uint16_t)i2c_write(resource->dev, dev_addr, data, size , 1); if(len != size){ return -1; } return ret; } int32_t hal_i2c_master_recv(i2c_dev_t *i2c, uint16_t dev_addr, uint8_t *data,uint16_t size, uint32_t timeout) { int32_t ret = 0; uint16_t len; (void)timeout; if(NULL == i2c || (NULL == data) || (MICO_I2C_1 != i2c->port && MICO_I2C_2 != i2c->port)) { return (-1); } i2c_resource_t * resource = &g_dev[i2c->port]; len = i2c_read(resource->dev, dev_addr, data, size, 1); if(len != size){ return -1; } return ret; } int32_t hal_i2c_slave_send(i2c_dev_t *i2c, const uint8_t *data, uint16_t size, uint32_t timeout) { int32_t ret = 0; (void)timeout; if(NULL == i2c || (NULL == data) || (MICO_I2C_1 != i2c->port && MICO_I2C_2 != i2c->port)) { return (-1); } i2c_resource_t * resource = &g_dev[i2c->port]; i2c_slave_write(resource->dev,data,size); return ret; } int32_t hal_i2c_slave_recv(i2c_dev_t *i2c, uint8_t *data, uint16_t size, uint32_t timeout) { int32_t ret = 0; (void)timeout; if(NULL == i2c || (NULL == data) || (MICO_I2C_1 != i2c->port && MICO_I2C_2 != i2c->port)) { return (-1); } i2c_resource_t * resource = &g_dev[i2c->port]; i2c_slave_read(resource->dev, data, size) ; return ret; } int32_t hal_i2c_mem_write(i2c_dev_t *i2c, uint16_t dev_addr, uint16_t mem_addr, uint16_t mem_addr_size, const uint8_t *data, uint16_t size, uint32_t timeout) { int32_t ret = 0; return ret; } int32_t hal_i2c_mem_read(i2c_dev_t *i2c, uint16_t dev_addr, uint16_t mem_addr, uint16_t mem_addr_size, uint8_t *data, uint16_t size, uint32_t timeout) { int32_t ret = 0; return ret; } int32_t hal_i2c_finalize(i2c_dev_t *i2c) { int32_t ret = 0; return ret; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/i2c.c
C
apache-2.0
3,640
#include "ota/ota_service.h" #include <platform/platform_stdlib.h> #include <osdep_service.h> #include <rtl8721d_ota.h> #include <flash_api.h> #include <device_lock.h> #include "aos/hal/flash.h" #include "aos/kernel.h" #include <ameba_soc.h> static u32 alinknewImg2Addr = 0xFFFFFFFF; char *HeadBuffer = NULL; #define OTA_HEADER_BUF_SIZE 1024 int alink_size = 0; //u8 alink_signature[9] = {0}; //extern const update_file_img_id OtaImgId[2]; uint32_t alink_ota_target_index = OTA_INDEX_2; update_ota_target_hdr OtaTargetHdr; update_dw_info DownloadInfo[MAX_IMG_NUM]; static int aliota_total_len = 0, aliota_flag = 1, aliota_count = 0; static uint32_t aliota_address; static int aliota_RemainBytes[2] = {0}; static int aliota_ota_exit = 0; static int aliota_ota_flag = 1; static unsigned long aliota_tick1, aliota_tick2; static u32 aliota_OtaFg = 0; static u32 aliota_SigCnt = 0; static int aliota_end_sig = 0; static int aliota_flash_write_done = 0; static int boot_part = HAL_PARTITION_OTA_TEMP; hal_logic_partition_t *partition_info = NULL; #ifndef OTA2_DEFAULT_ADDR #define OTA2_DEFAULT_ADDR (0x08106000) #endif int check_ota_index() { uint32_t ota_index = -1; /* check OTA index we should update */ if (ota_get_cur_index() == OTA_INDEX_1) { ota_index = OTA_INDEX_2; printf("OTA2 address space will be upgraded\n"); } else { ota_index = OTA_INDEX_1; printf("OTA1 address space will be upgraded\n"); } return ota_index; } bool prepare_ota_address(u32 ota_target_index, u32 * new_addr) { update_file_img_hdr *OTAHdr = NULL; uint32_t OTALen = 0; uint32_t ota_addr; if (ota_target_index == OTA_INDEX_2) ota_addr = LS_IMG2_OTA2_ADDR; else if (ota_target_index == OTA_INDEX_1) ota_addr = LS_IMG2_OTA1_ADDR; printf("ota_addr = %x\n", ota_addr); if((ota_addr%4096) != 0) { printf("\n\r[%s] ota addr in sys data space not 4k aligned 0x%x", __FUNCTION__, ota_addr); goto error; } *new_addr = ota_addr; if(*new_addr == 0xFFFFFFFF) { printf("\n\r[%s] update address is invalid \n", __FUNCTION__); goto error; } printf("OTA update address: 0x%x\n", *new_addr); return TRUE; error: return FALSE; } bool rtl8721d_ota_prepare() { alink_size = 0; aliota_total_len = 0, aliota_flag = 1, aliota_count = 0; aliota_address = 0; aliota_RemainBytes[0] = 0; aliota_RemainBytes[1] = 0; aliota_ota_exit = 0; aliota_ota_flag = 1; aliota_tick1 = 0, aliota_tick2 = 0; aliota_OtaFg = 0; aliota_SigCnt = 0; aliota_end_sig = 0; aliota_flash_write_done = 0; memset((u8 *)&OtaTargetHdr, 0, sizeof(update_ota_target_hdr)); //uint32_t part = HAL_PARTITION_OTA_TEMP; alink_ota_target_index = check_ota_index(); if(prepare_ota_address(alink_ota_target_index, &alinknewImg2Addr) != TRUE){ printf("\n get OTA address failed\n"); return FALSE; } if(alink_ota_target_index == OTA_INDEX_1) { boot_part = HAL_PARTITION_APPLICATION; //alinknewImg2Addr = LS_IMG2_OTA1_ADDR; }else if(alink_ota_target_index == OTA_INDEX_2) { boot_part = HAL_PARTITION_OTA_TEMP; //alinknewImg2Addr = LS_IMG2_OTA2_ADDR; }else { printf("flash INDEX failed\n"); return FALSE; } partition_info = hal_flash_get_info(boot_part); if(partition_info == NULL) { printf("hal_flash_get_info failed\n"); return FALSE; } /*-------------------erase flash space for new firmware--------------*/ erase_ota_target_flash(alinknewImg2Addr, partition_info->partition_length); //DBG_INFO_MSG_OFF(_DBG_SPI_FLASH_); HeadBuffer = rtw_malloc(OTA_HEADER_BUF_SIZE); if (HeadBuffer == NULL) { printf("malloc headbuffer failed\n"); return FALSE; } return TRUE; } static int rtl8721d_ota_init(void *something) { printf("rtl8721d_ota_init\n"); uint32_t offset = *(uint32_t*)something; if(offset==0) { /* prepare to os update */ if (rtl8721d_ota_prepare() != TRUE) { return -1; } } return 0; } static int rtl8721d_ota_write_ota_cb(int* off_set, char *buffer, int len) { char *buf; update_file_hdr OtaFileHdr; uint32_t i; int len_temp; unsigned int buf_offset = 0;; unsigned int copy_len =0; if (aliota_ota_flag) { aliota_tick1 = rtw_get_current_time(); aliota_ota_flag = 0; } /*-----read firmware header from server*/ //buf = HeadBuffer + aliota_total_len; aliota_total_len += len; if (aliota_total_len < 32) {//reach until get at least 8+24 bytes(one image) if(HeadBuffer != NULL) { buf = HeadBuffer+aliota_count; memcpy(buf, buffer, len); aliota_count += len; printf("copy head len:%d \n",len); } return 0; } else if ((aliota_total_len >= 32) && aliota_total_len <= OTA_HEADER_BUF_SIZE) { if (aliota_flag == 1) { buf = HeadBuffer;// TODO :consider add protection to HeadBuffer memcpy((u8*)(&(OtaTargetHdr.FileHdr)), buf, sizeof(update_file_hdr));//get FileHdr info(hdr num) if (aliota_total_len < (8+OtaTargetHdr.FileHdr.HdrNum*24))//copy to buf and return to get more data { buf = HeadBuffer; memcpy(buf+aliota_count, buffer, len); aliota_count += len; return 0; } //get enough data and start processing buf = HeadBuffer; memcpy(buf+aliota_count, buffer, aliota_total_len - aliota_count); if (!get_ota_tartget_header(buf, aliota_total_len, &OtaTargetHdr, alink_ota_target_index)) { printf("\n\rget OTA header failed\n"); goto update_ota_exit; } /*Image size should not bigger than OTA_SIZE_MAX */ if(partition_info != NULL) { uint32_t imglen = 0; for (i=0; i< OtaTargetHdr.ValidImgCnt; i++) { imglen += OtaTargetHdr.FileImgHdr[i].ImgLen; if (OtaTargetHdr.FileImgHdr[i].FlashAddr != alinknewImg2Addr) printf("\n\rOTA address not match\n"); } if(imglen > partition_info->partition_length){ printf("\n\r[%s] illegal new image length 0x%x", __FUNCTION__, imglen); goto update_ota_exit; } } #if 0 //skip OTF MASK in AmebaD /*the upgrade space should be masked, because the encrypt firmware is used for checksum calculation*/ OTF_Mask(1, (alinknewImg2Addr - SPI_FLASH_BASE), NewImg2BlkSize, 1); #endif /* get OTA image and Write New Image to flash, skip the signature, not write signature first for power down protection*/ memset((u8 *)DownloadInfo, 0, MAX_IMG_NUM*sizeof(update_dw_info)); for(i = 0; i < OtaTargetHdr.ValidImgCnt; i++) { DownloadInfo[i].ImgId = OTA_IMAG; DownloadInfo[i].FlashAddr = OtaTargetHdr.FileImgHdr[i].FlashAddr - SPI_FLASH_BASE + 8; //aliota_address DownloadInfo[i].ImageLen = OtaTargetHdr.FileImgHdr[i].ImgLen - 8; /*skip the signature*/ DownloadInfo[i].ImgOffset = OtaTargetHdr.FileImgHdr[i].Offset; aliota_RemainBytes[i] = DownloadInfo[i].ImageLen; printf("FlashAddr=%x,ImgLen=%x,ImgOff=%x\n",DownloadInfo[i].FlashAddr,DownloadInfo[i].ImageLen,DownloadInfo[i].ImgOffset); } aliota_flag = 0; if (HeadBuffer != NULL) { rtw_free(HeadBuffer); } } } /*skip the signature*/ for (i=0; i < OtaTargetHdr.ValidImgCnt; i++){ u8 * signature; signature = &(OtaTargetHdr.Sign[i][0]); /*download the new firmware from server*/ if(aliota_RemainBytes[i] > 0) { if(aliota_total_len > DownloadInfo[i].ImgOffset) { if(!aliota_OtaFg) { u32 Cnt = 0; /*reach the the desired image, the first packet process*/ aliota_OtaFg = 1; Cnt = aliota_total_len -DownloadInfo[i].ImgOffset; if(Cnt < 8) { aliota_SigCnt = Cnt; } else { aliota_SigCnt = 8; } memcpy(signature, buffer + len -Cnt, aliota_SigCnt); if((aliota_SigCnt < 8) || (Cnt -8 == 0)) { return 0; } copy_len = Cnt -8; buf_offset = len - Cnt +8; goto WRITETOFLASH; } else { /*normal packet process*/ if(aliota_SigCnt < 8) { if(len < (8 -aliota_SigCnt)) { memcpy(signature + aliota_SigCnt, buffer, len); aliota_SigCnt += len; return 0; } else { memcpy(signature + aliota_SigCnt, buffer, (8 -aliota_SigCnt)); aliota_end_sig = 8 -aliota_SigCnt; len_temp = len; len_temp -= (8 -aliota_SigCnt) ; aliota_SigCnt = 8; if(!len_temp) { return 0; } copy_len = len_temp; len_temp = aliota_RemainBytes[i] -len_temp; if (len_temp <= 0) { copy_len = aliota_RemainBytes[i]; } buf_offset = aliota_end_sig; goto WRITETOFLASH; //return 0; } } copy_len = len; len_temp = aliota_RemainBytes[i] -len; if(len_temp <= 0) { copy_len = aliota_RemainBytes[i]; } buf_offset = 0; goto WRITETOFLASH; } WRITETOFLASH: device_mutex_lock(RT_DEV_LOCK_FLASH); if(ota_writestream_user(DownloadInfo[i].FlashAddr + alink_size, copy_len, buffer+buf_offset) < 0){ printf("Write sector failed\r\n"); device_mutex_unlock(RT_DEV_LOCK_FLASH); goto update_ota_exit; } device_mutex_unlock(RT_DEV_LOCK_FLASH); alink_size += copy_len; aliota_RemainBytes[i] -= copy_len; aliota_tick2 = rtw_get_current_time(); if (aliota_tick2 - aliota_tick1 > 2000) { printf("Download OTA file: %d B, RemainBytes = %d\n", (alink_size), aliota_RemainBytes[i]); aliota_ota_flag = 1; } if (aliota_RemainBytes[i] <= 0) { printf("file size=%x\n",alink_size); aliota_OtaFg = 0;//clear flags when image[i] all writen to flash alink_size = 0; aliota_SigCnt = 0; aliota_end_sig = 0; aliota_flash_write_done = 1; }else{ return 0; } } } } return 0; update_ota_exit: if (HeadBuffer != NULL) { rtw_free(HeadBuffer); } aliota_ota_exit = 1; printf("Update task exit"); return -1; } static int rtl8721d_ota_finish_cb(void *something) { //printf("size = %d, OtaTargetHdr.FileImgHdr.ImgLen = %d\n", alink_size, OtaTargetHdr.FileImgHdr[].ImgLen); //printf("buffer signature is: = %s", (u8 *)(&(OtaTargetHdr.Sign[0][0]))); /*------------- verify checksum and update signature-----------------*/ if (aliota_flash_write_done){ if(verify_ota_checksum( &OtaTargetHdr)){ int ret = 0; ota_boot_param_t *param = (ota_boot_param_t *)something; if (param == NULL) { return -1; } printf("checksum check ok upg_flag:0x%x \n", param->upg_flag); if (param->upg_flag == OTA_RAW) { int offset = 0x00; int param_part = HAL_PARTITION_PARAMETER_1; hal_logic_partition_t *part_info = hal_flash_get_info(boot_part); param->src_adr = part_info->partition_start_addr; ota_boot_param_t param_r; offset = 0x00; hal_flash_erase(param_part, offset, sizeof(ota_boot_param_t)); offset = 0x00; hal_flash_write(param_part, (uint32_t*)&offset, param, sizeof(ota_boot_param_t)); offset = 0x00; memset(&param_r, 0, sizeof(ota_boot_param_t)); hal_flash_read(param_part, (uint32_t*)&offset, &param_r, sizeof(ota_boot_param_t)); if(memcmp(param, &param_r, sizeof(ota_boot_param_t)) != 0) { return -1; } printf("OTA finish dst:0x%08x src:0x%08x len:0x%08x upg_flag:0x%x \r\n", param_r.dst_adr, param_r.src_adr, param_r.len, param_r.upg_flag); } if(!change_ota_signature(&OtaTargetHdr, alink_ota_target_index)) { printf("\n%s: change signature failed\n"); return -1; } #if 0 //reset board { WDG_InitTypeDef WDG_InitStruct; u32 CountProcess; u32 DivFacProcess; aos_msleep(100); #if defined(CONFIG_MBED_API_EN) && CONFIG_MBED_API_EN rtc_backup_timeinfo(); #endif WDG_Scalar(50, &CountProcess, &DivFacProcess); WDG_InitStruct.CountProcess = CountProcess; WDG_InitStruct.DivFacProcess = DivFacProcess; WDG_Init(&WDG_InitStruct); WDG_Cmd(ENABLE); return 0; } #endif }else { printf("checksum check fail\n"); return -1; } }else{ printf("flash write incomplete\n"); return -1; } } static int rtl8721d_ota_read_ota_cb(int* off_set, char* out_buf, int out_buf_len) { //ota_readstream_user(off_set, out_buf_len, out_buf); return hal_flash_read(boot_part, (uint32_t*)off_set, out_buf, out_buf_len); } static int rtl8721d_ota_rollback(void *something) { int offset = 0x00; int param_part = HAL_PARTITION_PARAMETER_1; ota_boot_param_t param_w, param_r; memset(&param_w, 0, sizeof(ota_boot_param_t)); hal_flash_read(param_part, (uint32_t*)&offset, &param_w, sizeof(ota_boot_param_t)); if((param_w.boot_count != 0) && (param_w.boot_count != 0xff)) { param_w.boot_count = 0; /*Clear bootcount to avoid rollback*/ printf("clear bootcount.\n"); offset = 0x00; hal_flash_erase(param_part, offset, sizeof(ota_boot_param_t)); offset = 0x00; hal_flash_write(param_part, (uint32_t*)&offset, &param_w, sizeof(ota_boot_param_t)); offset = 0x00; memset(&param_r, 0, sizeof(ota_boot_param_t)); hal_flash_read(param_part, (uint32_t*)&offset, &param_r, sizeof(ota_boot_param_t)); if(memcmp(&param_w, &param_r, sizeof(ota_boot_param_t)) != 0) { printf("rollback clear failed\n"); return -1; } } return 0; } const char *rtl8721d_ota_get_version(unsigned char dev_type) { if(dev_type){ return "v1.0.0-20180101-1000"; }else{ return SYSINFO_APP_VERSION; } } ota_hal_module_t ota_hal_module = { .init = rtl8721d_ota_init, .write = rtl8721d_ota_write_ota_cb, .read = rtl8721d_ota_read_ota_cb, .boot = rtl8721d_ota_finish_cb, .rollback = rtl8721d_ota_rollback, .version = rtl8721d_ota_get_version, };
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/ota.c
C
apache-2.0
13,950
#include <stdint.h> #include "pwmout_api.h" #include "aos/hal/pwm.h" static pwmout_t PWM[18]; u32 port2pin[18][2]={ {0, PA_12}, {1, PA_13}, {2, PA_23}, {3, PA_24}, {4, PA_25}, {5, PA_26}, {6, PA_28}, {7, PA_30}, {8, PB_4}, {9, PB_5}, {10, PB_18}, {11, PB_19}, {12, PB_20}, {13, PB_21}, {14, PB_22}, {15, PB_23}, {16, PB_24}, {17, PB_25}, //this channel also can be PB_7 }; extern void pwmout_init(pwmout_t* obj, PinName pin); extern void pwmout_free(pwmout_t* obj); extern void pwmout_write(pwmout_t* obj, float percent); extern float pwmout_read(pwmout_t* obj); extern void pwmout_period_us(pwmout_t* obj, int us); extern void pwmout_start(pwmout_t* obj); extern void pwmout_stop(pwmout_t* obj); /** * Initialises a PWM pin * * * @param[in] pwm the PWM device * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_pwm_init(pwm_dev_t *pwm) { int period_us; period_us = 1000000/pwm->config.freq; pwm->priv = &(PWM[pwm->port]); pwmout_init( pwm->priv , port2pin[pwm->port][1]); pwmout_period_us(pwm->priv , period_us); pwmout_write(pwm->priv , pwm->config.duty_cycle); return 0; } /** * Starts Pulse-Width Modulation signal output on a PWM pin * * @param[in] pwm the PWM device * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_pwm_start(pwm_dev_t *pwm) { pwmout_start(pwm->priv); return 0; } /** * Stops output on a PWM pin * * @param[in] pwm the PWM device * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_pwm_stop(pwm_dev_t *pwm) { pwmout_stop(pwm->priv); return 0; } /** * change the para of pwm * * @param[in] pwm the PWM device * @param[in] para the para of pwm * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_pwm_para_chg(pwm_dev_t *pwm, pwm_config_t para) { int period_us; period_us = 1000000/para.freq; pwmout_period_us(pwm->priv, period_us); pwmout_write(pwm->priv, para.duty_cycle); return 0; } /** * De-initialises an PWM interface, Turns off an PWM hardware interface * * @param[in] pwm the interface which should be de-initialised * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_pwm_finalize(pwm_dev_t *pwm) { pwmout_free(pwm->priv); return 0; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/pwm.c
C
apache-2.0
2,459
/* * Copyright (C) 2018 Alibaba Group Holding Limited */ /* DESCRIPTION This library provides the support for the STM32L496G-DISCOVERY CPU power state control. CPU power management: provides low-level interface for setting CPU C-states. provides low-level interface for setting CPU P-states. */ #include <k_api.h> #include "ameba_soc.h" #if (AOS_COMP_PWRMGMT > 0) #include <cpu_pwr.h> #include <cpu_pwr_hal_lib.h> #include <pwrmgmt_debug.h> #include <cpu_tickless.h> #include "pwrmgmt_api.h" /* forward declarations */ extern one_shot_timer_t rtc_one_shot; /* wakeup source for C3,C4 */ extern uint64_t expeted_sleep_ms; static cpu_pwr_t cpu_pwr_node_core_0; KM4SLEEP_ParamDef sleep_param; /* psm dd hook info */ PSM_DD_HOOK_INFO gPsmDdHookInfo[PMU_MAX]; extern uint32_t sleep_type; /* 0 is power gate, 1 is clock gate */ static u32 system_can_yield = 1; /* default is can */ static uint32_t deepwakelock = DEFAULT_DEEP_WAKELOCK; void sleep_ex_cg(uint32_t sleep_duration) { if (deepwakelock == 0) { sleep_param.dlps_enable = ENABLE; sleep_param.sleep_time = 0; } else { sleep_param.dlps_enable = DISABLE; sleep_param.sleep_time = sleep_duration; } sleep_param.sleep_type = sleep_type; IPCM0_DEV->IPCx_USR[IPC_INT_CHAN_SHELL_SWITCH] = 0x00000000; InterruptDis(UART_LOG_IRQ); if (sleep_type == SLEEP_PG) { SOCPS_SleepPG(); } else { SOCPS_SleepCG(); } } /** * board_cpu_c_state_set - program CPU into Cx idle state * * RUN Context: could be called from ISR context or task context. * * SMP Consider: STM32L496G-DISCOVERY do not support SMP, so only UP is enough. * * @return PWR_OK or PWR_ERR when failed. */ static pwr_status_t board_cpu_c_state_set(uint32_t cpuCState, int master) { switch (cpuCState) { case CPU_CSTATE_C0: if (master) { /* * do something needed when CPU waked up from C1 or higher * Cx state. */ } break; case CPU_CSTATE_C1: if ((uint32_t)expeted_sleep_ms < 3) { return PWR_OK; } /* put CPU into C1 state, for ARM we can call WFI instruction to put CPU into C1 state. */ PWR_DBG(DBG_DBG, "enter C1\n"); sleep_ex_cg((uint32_t)expeted_sleep_ms); PWR_DBG(DBG_DBG, "exit C1\n"); break; default: PWR_DBG(DBG_ERR, "invalid C state: C%d\n", cpuCState); break; } return PWR_OK; } /** * board_cpu_pwr_init() is called by HAL lib to * init board powr manage configure. * * RUN Context: could be called from task context only, ISR context is not * supported. * * SMP Consider: STM32L496G-DISCOVERY do not support SMP, so only UP is enough. * * @return PWR_OK or PWR_ERR when failed. */ pwr_status_t board_cpu_pwr_init(void) { cpu_pwr_t *pCpuNode = NULL; pwr_status_t retVal = PWR_OK; uint32_t cpuIndex = 0; /* 0 for UP */ pCpuNode = &cpu_pwr_node_core_0; retVal = cpu_pwr_node_init_static("core", 0, pCpuNode); if (retVal != PWR_OK) { return PWR_ERR; } /* record this node */ retVal = cpu_pwr_node_record(pCpuNode, cpuIndex); if (retVal == PWR_ERR) { return PWR_ERR; } /* * According reference manual of STM32L496G-DISCOVERY * * C0 - RUN, Power supplies are on,all clocks are on. * C1 - Sleep mode, CPU clock off, all peripherals including * Cortex®-M4 core peripherals such as NVIC, SysTick, etc. can run * and wake up the CPU when an interrupt or an event occurs. */ retVal = cpu_pwr_c_method_set(cpuIndex, board_cpu_c_state_set); if (retVal == PWR_ERR) { return PWR_ERR; } /* save support C status bitset : C0,C1 */ cpu_pwr_c_state_capability_set(cpuIndex, CPU_STATE_BIT(CPU_CSTATE_C0) | CPU_STATE_BIT(CPU_CSTATE_C1) ); if (retVal == PWR_ERR) { return PWR_ERR; } /* * According reference manual of STM32L496G-DISCOVERY, * the wakeup latency of Cx is: * resume from C1 (Low Power mode) : immediate */ cpu_pwr_c_state_latency_save(cpuIndex, CPU_CSTATE_C0, 0); cpu_pwr_c_state_latency_save(cpuIndex, CPU_CSTATE_C1, 0); tickless_one_shot_timer_save(CPU_CSTATE_C1, &rtc_one_shot); /* Tell the CPU PWR MGMT module which C state is supported with tickless function through tickless_c_states_add(c_state_x). */ tickless_c_states_add(CPU_STATE_BIT(CPU_CSTATE_C0) | CPU_STATE_BIT(CPU_CSTATE_C1) ); #if RHINO_CONFIG_CPU_PWR_SHOW cpu_pwr_info_show(); cpu_pwr_state_show(); #endif return retVal; } uint32_t pmu_yield_os_check(void) { return system_can_yield; } uint32_t pmu_yield_os_set(int value) { system_can_yield = value; } uint32_t pmu_set_sysactive_time(uint32_t timeout) { pwrmgmt_cpu_active_msec_set(timeout); } void pmu_release_wakelock(uint32_t nDeviceId) { nDeviceId = nDeviceId + 17; pwrmgmt_cpu_lowpower_resume(nDeviceId); } void pmu_acquire_wakelock(uint32_t nDeviceId) { nDeviceId = nDeviceId + 17; pwrmgmt_cpu_lowpower_suspend(nDeviceId); } void pmu_exec_wakeup_hook_funs(u32 nDeviceIdMax) { PSM_DD_HOOK_INFO *pPsmDdHookInfo = NULL; u32 nDeviceIdOffset = 0; for( nDeviceIdOffset = 0; nDeviceIdOffset < nDeviceIdMax; nDeviceIdOffset++) { pPsmDdHookInfo = &gPsmDdHookInfo[nDeviceIdOffset]; /*if this device register and sleep_hook_fun not NULL*/ if(pPsmDdHookInfo && pPsmDdHookInfo->wakeup_hook_fun) { pPsmDdHookInfo->wakeup_hook_fun(0, pPsmDdHookInfo->wakeup_param_ptr); } } } u32 pmu_exec_sleep_hook_funs(void) { PSM_DD_HOOK_INFO *pPsmDdHookInfo = NULL; u32 nDeviceIdOffset = 0; u32 ret = TRUE; for( nDeviceIdOffset = 0; nDeviceIdOffset < PMU_MAX; nDeviceIdOffset++) { pPsmDdHookInfo = &gPsmDdHookInfo[nDeviceIdOffset]; /*if this device register and sleep_hook_fun not NULL*/ if(pPsmDdHookInfo && pPsmDdHookInfo->sleep_hook_fun) { ret = pPsmDdHookInfo->sleep_hook_fun(0, pPsmDdHookInfo->sleep_param_ptr); if (ret == FALSE) { break; } } } return nDeviceIdOffset; } void pmu_register_sleep_callback(u32 nDeviceId, PSM_HOOK_FUN sleep_hook_fun, void* sleep_param_ptr, PSM_HOOK_FUN wakeup_hook_fun, void* wakeup_param_ptr) { PSM_DD_HOOK_INFO *pPsmDdHookInfo = NULL; assert_param(nDeviceId < PMU_MAX); assert_param((sleep_hook_fun != NULL) || (wakeup_hook_fun != NULL)); pPsmDdHookInfo = &gPsmDdHookInfo[nDeviceId]; pPsmDdHookInfo->nDeviceId = nDeviceId; pPsmDdHookInfo->sleep_hook_fun = sleep_hook_fun; pPsmDdHookInfo->sleep_param_ptr = sleep_param_ptr; pPsmDdHookInfo->wakeup_hook_fun = wakeup_hook_fun; pPsmDdHookInfo->wakeup_param_ptr = wakeup_param_ptr; } void pmu_unregister_sleep_callback(u32 nDeviceId) { PSM_DD_HOOK_INFO *pPsmDdHookInfo = NULL; assert_param(nDeviceId < PMU_MAX); pPsmDdHookInfo = &gPsmDdHookInfo[nDeviceId]; _memset(pPsmDdHookInfo, 0x00, sizeof(PSM_DD_HOOK_INFO)); } void pmu_acquire_deepwakelock(uint32_t nDeviceId) { deepwakelock |= BIT(nDeviceId); } void pmu_release_deepwakelock(uint32_t nDeviceId) { deepwakelock &= ~BIT(nDeviceId); } #else uint32_t pmu_yield_os_check(void) { return 1; } void pmu_release_wakelock(uint32_t nDeviceId) { } void pmu_acquire_wakelock(uint32_t nDeviceId) { } uint32_t pmu_set_sysactive_time(uint32_t timeout) { return 0; } void pmu_register_sleep_callback(u32 nDeviceId, PSM_HOOK_FUN sleep_hook_fun, void* sleep_param_ptr, PSM_HOOK_FUN wakeup_hook_fun, void* wakeup_param_ptr) { } void pmu_unregister_sleep_callback(u32 nDeviceId){ } #endif /* AOS_COMP_PWRMGMT */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/pwrmgmt_hal/board_cpu_pwr.c
C
apache-2.0
7,878
/* * Copyright (C) 2018 Alibaba Group Holding Limited */ /* * This file supplied RTC one-shot start/stop services for CPU tickless * module, verifyied on STM32L496-DISCOVERY with C3/C4 mode. * C3: stop mode. * C4: standby mode. */ #include <k_api.h> #if (AOS_COMP_PWRMGMT > 0) #include <stdint.h> #include <stdbool.h> #include <cpu_tickless.h> #include "ameba_soc.h" #define TIMER_FREQ 32768 int cpu_pwr_ready_status_get(void); uint32_t pmu_set_sysactive_time(uint32_t timeout); static pwr_status_t rtc_init(void); static uint32_t rtc_one_shot_max_seconds(void); static pwr_status_t rtc_one_shot_start(uint64_t planUs); static pwr_status_t rtc_one_shot_stop(uint64_t *pPassedUs); uint64_t expeted_sleep_ms = 0; one_shot_timer_t rtc_one_shot = { rtc_init, rtc_one_shot_max_seconds, rtc_one_shot_start, rtc_one_shot_stop, }; static uint32_t timer_counter_start = 0; static pwr_status_t rtc_init(void) { SYSTIMER_Init(); return PWR_OK; } static pwr_status_t rtc_one_shot_start(uint64_t planUs) { expeted_sleep_ms = planUs / 1000; timer_counter_start = SYSTIMER_TickGet(); return PWR_OK; } static pwr_status_t rtc_one_shot_stop(uint64_t *pPassedUs) { uint32_t timer_counter_end = SYSTIMER_TickGet(); if (timer_counter_end >= timer_counter_start) { *pPassedUs = (timer_counter_end - timer_counter_start) * (uint64_t)1000000 / TIMER_FREQ; } else { *pPassedUs = (0xffffffff + timer_counter_end - timer_counter_start) * (uint64_t)1000000 / TIMER_FREQ; } // pmu_set_sysactive_time(2 + (*pPassedUs) / 1000); return PWR_OK; } static uint32_t rtc_one_shot_max_seconds(void) { if (cpu_pwr_ready_status_get() == 1) { return (0xffffffff / TIMER_FREQ); } else { return 0; } } #endif /* AOS_COMP_PWRMGMT */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/pwrmgmt_hal/board_cpu_pwr_rtc.c
C
apache-2.0
1,822
/* * Copyright (C) 2018 Alibaba Group Holding Limited */ /* DESCRIPTION This file provides two fundtions systick_suspend()/systick_resume() which is used by cpu tickless module to suspend/resume system tick interrupt. Differrent board may has different way to suspend/resume system tick interrupt, please reference your board/soc user manual to find the detail for how to implement these two functions. */ #include <k_api.h> #if (AOS_COMP_PWRMGMT > 0) #include "ameba_soc.h" #define NVIC_SYSTICK_CTRL_REG (*((volatile uint32_t *) 0xe000e010)) void systick_suspend(void) { pmu_yield_os_set(0); NVIC_SYSTICK_CTRL_REG &= ~(SysTick_CTRL_ENABLE_Msk | SysTick_CTRL_TICKINT_Msk); } void systick_resume(void) { NVIC_SYSTICK_CTRL_REG |= (SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk); pmu_yield_os_set(1); } #endif /* AOS_COMP_PWRMGMT */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/pwrmgmt_hal/board_cpu_pwr_systick.c
C
apache-2.0
862
#if (AOS_COMP_PWRMGMT > 0) #include <hal/wifi.h> #include "pwrmgmt_api.h" #include <cpu_pwr.h> #define SET_BIT(off) ((uint32_t)1 << (off)) uint32_t sleep_type = SLEEP_CG; /* 0 is power gate, 1 is clock gate */ static sys_time_t cpu_pwr_active_exit_tick = 0; static uint32_t cpu_suspend_lock = 0; int cpu_pwr_ready_status_get(void) { if (cpu_pwr_is_suspend() == 1) { return 0; } if(krhino_sys_tick_get() < cpu_pwr_active_exit_tick) { return 0; } return 1; } int pwrmgmt_cpu_active_msec_set(uint32_t active_time) { tick_t active_tick = 0; sys_time_t current_active_exit_tick = 0; if (active_time == 0) { return 0; } active_tick = krhino_ms_to_ticks(active_time); /* if active time is less than 1 tick */ if (active_tick == 0) { active_tick = 1; } current_active_exit_tick = krhino_sys_tick_get() + active_tick; if (current_active_exit_tick > cpu_pwr_active_exit_tick) { cpu_pwr_active_exit_tick = current_active_exit_tick; } return 0; } uint32_t pwrmgmt_sleep_type_set(uint32_t type) { sleep_type = type; return 0; } int pwrmgmt_wifi_powersave_suspend(uint32_t suspend_module) { hal_wifi_module_t *module = NULL; module = hal_wifi_get_default_module(); hal_wifi_exit_powersave(module); } int pwrmgmt_wifi_powersave_resume(uint32_t resume_module) { hal_wifi_module_t *module = NULL; module = hal_wifi_get_default_module(); hal_wifi_enter_powersave(module, WIFI_CONFIG_RECEIVE_DTIM); } int pwrmgmt_cpu_lowpower_suspend(uint32_t suspend_module) { if (cpu_suspend_lock == 0) { cpu_pwr_suspend(); } cpu_suspend_lock |= SET_BIT(suspend_module); } int pwrmgmt_cpu_lowpower_resume(uint32_t resume_module) { cpu_suspend_lock &= ~SET_BIT(resume_module); if (cpu_suspend_lock == 0) { cpu_pwr_resume(); } } int pwrmgmt_cpu_minisleep_msec_set(uint32_t time_ms) { cpu_pwr_minisleep_msec_set(time_ms); return 0; } uint32_t pwrmgmt_cpu_minisleep_msec_get(void) { return cpu_pwr_minisleep_msec_get(); } #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/pwrmgmt_hal/pwrmgmt_api.c
C
apache-2.0
2,117
#if (AOS_COMP_PWRMGMT > 0) #include "pwrmgmt.h" #endif #include "ameba_soc.h" int pwrmgmt_cpu_active_msec_set(uint32_t active_time); uint32_t pwrmgmt_sleep_type_set(uint32_t type); int pwrmgmt_cpu_lowpower_suspend(uint32_t suspend_module); int pwrmgmt_cpu_lowpower_resume(uint32_t resume_module); int pwrmgmt_cpu_minisleep_msec_set(uint32_t time_ms); uint32_t pwrmgmt_cpu_minisleep_msec_get(void); int pwrmgmt_wifi_powersave_resume(uint32_t resume_module); int pwrmgmt_wifi_powersave_suspend(uint32_t suspend_module); void pmu_unregister_sleep_callback(u32 nDeviceId); void pmu_register_sleep_callback(u32 nDeviceId, PSM_HOOK_FUN sleep_hook_fun, void* sleep_param_ptr, PSM_HOOK_FUN wakeup_hook_fun, void* wakeup_param_ptr); void pmu_acquire_deepwakelock(uint32_t nDeviceId); void pmu_release_deepwakelock(uint32_t nDeviceId);
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/pwrmgmt_hal/pwrmgmt_api.h
C
apache-2.0
860
#include "ameba_soc.h" #include "k_api.h" #include "board.h" #include "device.h" #include "aos/hal/rtc.h" #include <time.h> #include "rtc_api.h" static struct tm rtc_timeinfo; static int rtc_en = 0; const static u8 dim[12] = { 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; /** * @brief This function is used to tell a year is a leap year or not. * @param year: The year need to be told. * @retval value: * - 1: This year is leap year. * - 0: This year is not leap year. */ static inline bool is_leap_year(unsigned int year) { u32 full_year = year + 1900; return (!(full_year % 4) && (full_year % 100)) || !(full_year % 400); } /** * @brief This function tells how many days in a month of a year. * @param year: Specified year * @param month: Specified month * @retval value: Number of days in the month. */ static u8 days_in_month (u8 month, u8 year) { u8 ret = dim[month]; if (ret == 0) ret = is_leap_year (year) ? 29 : 28; return ret; } /** * @brief This function is used to calculate month and day of month according to year and day of the year. * @param year: years since 1900. * @param yday: day of the year. * @param mon: pointer to the variable which stores month, the value can be 0-11 * @param mday: pointer to the variable which stores day of month, the value can be 1-31 * @retval value: none */ static void rtc_calculate_mday(int year, int yday, int* mon, int* mday) { int t_mon = -1, t_yday = yday + 1; while(t_yday > 0){ t_mon ++; t_yday -= days_in_month(t_mon, year); } *mon = t_mon; *mday = t_yday + days_in_month(t_mon, year); } /** * @brief This function is used to calculate day of week according to date. * @param year: years since 1900. * @param mon: which month of the year * @param mday: pointer to the variable which store day of month * @param wday: pointer to the variable which store day of week, the value can be 0-6, and 0 means Sunday * @retval value: none */ static void rtc_calculate_wday(int year, int mon, int mday, int* wday) { int t_year = year + 1900, t_mon = mon + 1; if(t_mon == 1 || t_mon == 2){ t_year --; t_mon += 12; } int c = t_year / 100; int y = t_year % 100; int week = (c / 4) - 2 * c + (y + y / 4) + (26 * (t_mon + 1) / 10) + mday -1; while(week < 0){ week += 7; } week %= 7; *wday = week; } static u32 get_yday(rtc_time_t *time) { int days = time->date; for(int i = 0; i < time->month-1; i++){ days += dim[i]; } } /** * @brief This function is used to restore rtc_timeinfo global variable whose value is lost after system reset. * @param none * @retval value: none */ static void rtc_restore_timeinfo(rtc_dev_t *rtc) { u32 value, days_in_year, format; if(rtc->config.format == HAL_RTC_FORMAT_DEC) format = RTC_Format_BIN; else if(rtc->config.format == HAL_RTC_FORMAT_BCD) format = RTC_Format_BCD; RTC_TimeTypeDef RTC_TimeStruct; RTC_GetTime(format, &RTC_TimeStruct); rtc_timeinfo.tm_sec = RTC_TimeStruct.RTC_Seconds; rtc_timeinfo.tm_min = RTC_TimeStruct.RTC_Minutes; rtc_timeinfo.tm_hour = RTC_TimeStruct.RTC_Hours; rtc_timeinfo.tm_yday = RTC_TimeStruct.RTC_Days; value = BKUP_Read(0); rtc_timeinfo.tm_year = (value & BIT_RTC_BACKUP) >> 8; days_in_year = (is_leap_year(rtc_timeinfo.tm_year) ? 366 : 365); if(rtc_timeinfo.tm_yday > days_in_year - 1){ rtc_timeinfo.tm_year ++; rtc_timeinfo.tm_yday -= days_in_year; /* over one year, update days in RTC_TR */ RTC_TimeStruct.RTC_Days = rtc_timeinfo.tm_yday; RTC_SetTime(format, &RTC_TimeStruct); } rtc_calculate_mday(rtc_timeinfo.tm_year, rtc_timeinfo.tm_yday, &rtc_timeinfo.tm_mon, &rtc_timeinfo.tm_mday); rtc_calculate_wday(rtc_timeinfo.tm_year, rtc_timeinfo.tm_mon, rtc_timeinfo.tm_mday, &rtc_timeinfo.tm_wday); } /** * @brief Initializes the RTC device, include clock, RTC registers and function. * @param none * @retval none */ /** * This function will initialize the on board CPU real time clock * * * @param[in] rtc rtc device * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_rtc_init(rtc_dev_t *rtc) { RTC_InitTypeDef RTC_InitStruct; RCC_PeriphClockSource_RTC(0); RTC_StructInit(&RTC_InitStruct); RTC_InitStruct.RTC_HourFormat = RTC_HourFormat_24; RTC_Init(&RTC_InitStruct); /* 32760 need add need add 15 cycles (256Hz) every 4 min*/ //RTC_SmoothCalibConfig(RTC_CalibSign_Positive, 15, // RTC_CalibPeriod_4MIN, RTC_Calib_Enable); rtc_en = 1; return 0; } /** * This function will return the value of time read from the on board CPU real time clock. * * @param[in] rtc rtc device * @param[out] time pointer to a time structure * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_rtc_get_time(rtc_dev_t *rtc, rtc_time_t *time) { int format; struct tm tm_temp; RTC_TimeTypeDef RTC_TimeStruct; u32 delta_days = 0; if(BKUP_Read(0) & BIT_RTC_RESTORE){ rtc_restore_timeinfo(rtc); BKUP_Clear(0, BIT_RTC_RESTORE); } _memcpy((void*)&tm_temp, (void*)&rtc_timeinfo, sizeof(struct tm)); if(rtc->config.format == HAL_RTC_FORMAT_DEC) format = RTC_Format_BIN; else if(rtc->config.format == HAL_RTC_FORMAT_BCD) format = RTC_Format_BCD; /*hour, min, sec get from RTC*/ RTC_GetTime(format, &RTC_TimeStruct); tm_temp.tm_sec = RTC_TimeStruct.RTC_Seconds; tm_temp.tm_min = RTC_TimeStruct.RTC_Minutes; tm_temp.tm_hour = RTC_TimeStruct.RTC_Hours; /* calculate how many days later from last time update rtc_timeinfo */ delta_days = RTC_TimeStruct.RTC_Days - tm_temp.tm_yday; /* calculate wday, mday, yday, mon, year*/ tm_temp.tm_wday += delta_days; if(tm_temp.tm_wday >= 7){ tm_temp.tm_wday = tm_temp.tm_wday % 7; } tm_temp.tm_yday += delta_days; tm_temp.tm_mday += delta_days; while(tm_temp.tm_mday > days_in_month(tm_temp.tm_mon, tm_temp.tm_year)){ tm_temp.tm_mday -= days_in_month(tm_temp.tm_mon, tm_temp.tm_year); tm_temp.tm_mon++; if(tm_temp.tm_mon >= 12){ tm_temp.tm_mon -= 12; tm_temp.tm_yday -= is_leap_year(tm_temp.tm_year) ? 366 : 365; tm_temp.tm_year ++; /* over one year, update days in RTC_TR */ RTC_TimeStruct.RTC_Days = tm_temp.tm_yday; RTC_SetTime(RTC_Format_BIN, &RTC_TimeStruct); /* update rtc_timeinfo */ _memcpy((void*)&rtc_timeinfo, (void*)&tm_temp, sizeof(struct tm)); } } time->sec = tm_temp.tm_sec; time->min = tm_temp.tm_min; time->hr = tm_temp.tm_hour; time->weekday = tm_temp.tm_wday; time->date = tm_temp.tm_mday; time->month = tm_temp.tm_mon; time->year = tm_temp.tm_year; return 0; } /** * This function will set MCU RTC time to a new value. * * @param[in] rtc rtc device * @param[out] time pointer to a time structure * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_rtc_set_time(rtc_dev_t *rtc, const rtc_time_t *time) { struct tm timeinfo; int format; timeinfo.tm_sec = time->sec; timeinfo.tm_min = time->min ; timeinfo.tm_hour= time->hr; timeinfo.tm_wday= time->weekday; timeinfo.tm_mday= time->date; timeinfo.tm_mon =time->month; timeinfo.tm_year= time->year; timeinfo.tm_yday = get_yday((rtc_time_t *)time); RTC_TimeTypeDef RTC_TimeStruct; /*set time in RTC */ RTC_TimeStruct.RTC_H12_PMAM = RTC_H12_AM; RTC_TimeStruct.RTC_Days = timeinfo.tm_yday; RTC_TimeStruct.RTC_Hours = timeinfo.tm_hour; RTC_TimeStruct.RTC_Minutes = timeinfo.tm_min; RTC_TimeStruct.RTC_Seconds = timeinfo.tm_sec; if(rtc->config.format == HAL_RTC_FORMAT_DEC) format = RTC_Format_BIN; else if(rtc->config.format == HAL_RTC_FORMAT_BCD) format = RTC_Format_BCD; RTC_SetTime(format, &RTC_TimeStruct); /* Set rtc_timeinfo*/ _memcpy((void*)&rtc_timeinfo, (void*)&timeinfo, sizeof(struct tm)); return 0; } /** * De-initialises an RTC interface, Turns off an RTC hardware interface * * @param[in] RTC the interface which should be de-initialised * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_rtc_finalize(rtc_dev_t *rtc) { rtc_en = 0; return 0; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/rtc.c
C
apache-2.0
8,392
#include <errno.h> #include <stdint.h> #include <aos/hal/sd.h> int32_t hal_sd_init(sd_dev_t *sd) { return -1; } int32_t hal_sd_blks_read(sd_dev_t *sd, uint8_t *data, uint32_t blk_addr, uint32_t blks, uint32_t timeout) { return -1; } int32_t hal_sd_blks_write(sd_dev_t *sd, uint8_t *data, uint32_t blk_addr, uint32_t blks, uint32_t timeout) { return -1; } int32_t hal_sd_erase(sd_dev_t *sd, uint32_t blk_start_addr, uint32_t blk_end_addr) { return -1; } int32_t hal_sd_stat_get(sd_dev_t *sd, hal_sd_stat *stat) { return -1; } int32_t hal_sd_info_get(sd_dev_t *sd, hal_sd_info_t *info) { return -1; } int32_t hal_sd_finalize(sd_dev_t *sd) { return -1; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/sd.c
C
apache-2.0
739
#include "ameba_soc.h" #include "k_api.h" #include "board.h" #include "device.h" #include "gpio_api.h" #include "aos/hal/uart.h" #include "device.h" #include "serial_api.h" #include "gpio_api.h" #include "diag.h" #define RX_BUFFER_LENGTH 128 typedef struct { u8 id; PinName tx; PinName rx; PinName rts; PinName cts; } uart_s; typedef struct { u32 length; u8 *rxbuffer; } uart_buffer; static uart_buffer uart_rxbuffer[5]; /*the pin used for uart, you can change the pin as pinmux table, 0 means not use*/ static uart_s uart_obj[5] = { { 2, PA_7, PA_8, 0, 0 }, // log uart { 0, PA_18, PA_19, PA_16, PA_17 }, // km4 uart { 1, PA_2, PA_4, PA_0, PB_31 }, // bt uart { 3, PA_12, PA_13, PA_14, PA_15 }, // km0 uart { 3, PB_1, PB_2, 0, 0 } }; #define UART_TX PB_1 #define UART_RX PB_2 // serial_t uart_obj_t; #define EVENT_RX_READY ((uint32_t)1 << 0) #if (RHINO_CONFIG_CPU_NUM > 1) static aos_spinlock_t uart0_lock = { KRHINO_SPINLOCK_FREE_VAL, }; #else static aos_spinlock_t uart0_lock; #endif static aos_event_t uart0_event; static uint8_t uart0_rx_buf[RX_BUFFER_LENGTH]; static size_t uart0_rx_buf_head = 0; static size_t uart0_rx_buf_tail = 0; #define uart0_rx_buf_count() ((RX_BUFFER_LENGTH + uart0_rx_buf_head - uart0_rx_buf_tail) & (RX_BUFFER_LENGTH - 1)) #define uart0_rx_buf_space() (RX_BUFFER_LENGTH - 1 - uart0_rx_buf_count()) size_t uart0_rx_buffer_produce(const void *buf, size_t count) { size_t c = 0; size_t old_count; aos_irqsave_t flags; flags = aos_spin_lock_irqsave(&uart0_lock); old_count = uart0_rx_buf_count(); while (c < count && uart0_rx_buf_space() > 0) { uart0_rx_buf[uart0_rx_buf_head++] = ((const uint8_t *)buf)[c++]; uart0_rx_buf_head &= RX_BUFFER_LENGTH - 1; } if (old_count == 0 && c > 0) aos_event_set(&uart0_event, EVENT_RX_READY, AOS_EVENT_OR); aos_spin_unlock_irqrestore(&uart0_lock, flags); return c; } static size_t uart0_rx_buffer_consume(void *buf, size_t count) { size_t c = 0; aos_irqsave_t flags; flags = aos_spin_lock_irqsave(&uart0_lock); while (c < count && uart0_rx_buf_count() > 0) { ((uint8_t *)buf)[c++] = uart0_rx_buf[uart0_rx_buf_tail++]; uart0_rx_buf_tail &= RX_BUFFER_LENGTH - 1; } if (uart0_rx_buf_count() == 0) aos_event_set(&uart0_event, ~EVENT_RX_READY, AOS_EVENT_AND); aos_spin_unlock_irqrestore(&uart0_lock, flags); return c; } int g_uart_init = 0; static int32_t uart_irq(void *data) { volatile u8 reg_iir; /* register */ u8 int_id; u32 reg_val; uint8_t rx_char; UART_TypeDef *uart_dev; uart_dev_t *uart = (uart_dev_t *)data; u8 num = uart_obj[uart->port].id; uart_dev = UART_DEV_TABLE[num].UARTx; reg_iir = UART_IntStatus(uart_dev); if ((reg_iir & RUART_IIR_INT_PEND) != 0) { /* No pending IRQ */ return 0; } int_id = (reg_iir & RUART_IIR_INT_ID) >> 1; switch (int_id) { case RUART_RECEIVER_DATA_AVAILABLE: case RUART_TIME_OUT_INDICATION: { if (UART_Readable(uart_dev)) { if (uart_rxbuffer[uart->port].length < RX_BUFFER_LENGTH) { UART_CharGet(uart_dev, (uart_rxbuffer[uart->port].rxbuffer + uart_rxbuffer[uart->port].length)); uart_rxbuffer[uart->port].length++; if (uart_rxbuffer[uart->port].length == RX_BUFFER_LENGTH) uart_rxbuffer[uart->port].length--; } else { /*DBG_8195A("UART BUFFER SIZE OVERFLOW!!!!!!!\n");*/ } } } break; case RUART_RECEIVE_LINE_STATUS: reg_val = (UART_LineStatusGet(uart_dev)); DBG_8195A("data_uart_irq: LSR %08x interrupt\n", reg_val); break; default: DBG_8195A("data_uart_irq: Unknown interrupt type %d\n", int_id); break; } return 0; } /** * Initialises a UART interface * * * @param[in] uart the interface which should be initialised * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_uart_init(uart_dev_t *uart) { if (uart->port != 0) { u8 num = uart_obj[uart->port].id; UART_InitTypeDef UARTStruct; UART_TypeDef *uart_dev; uart_dev = UART_DEV_TABLE[num].UARTx; uart_rxbuffer[uart->port].length = 0; uart_rxbuffer[uart->port].rxbuffer = aos_malloc(RX_BUFFER_LENGTH); /*set pin*/ if (uart_obj[uart->port].tx) { Pinmux_Config(uart_obj[uart->port].tx, PINMUX_FUNCTION_UART); PAD_PullCtrl(uart_obj[uart->port].tx, GPIO_PuPd_UP); } if (uart_obj[uart->port].rx) { Pinmux_Config(uart_obj[uart->port].rx, PINMUX_FUNCTION_UART); PAD_PullCtrl(uart_obj[uart->port].rx, GPIO_PuPd_UP); } if (uart->config.flow_control == FLOW_CONTROL_CTS) { if (uart_obj[uart->port].cts) { Pinmux_Config(uart_obj[uart->port].cts, PINMUX_FUNCTION_UART_RTSCTS); } } else if (uart->config.flow_control == FLOW_CONTROL_RTS) { if (uart_obj[uart->port].rts) { Pinmux_Config(uart_obj[uart->port].rts, PINMUX_FUNCTION_UART_RTSCTS); } } else if (uart->config.flow_control == FLOW_CONTROL_CTS_RTS) { if (uart_obj[uart->port].cts) { Pinmux_Config(uart_obj[uart->port].cts, PINMUX_FUNCTION_UART_RTSCTS); } if (uart_obj[uart->port].rts) { Pinmux_Config(uart_obj[uart->port].rts, PINMUX_FUNCTION_UART_RTSCTS); } } UART_StructInit(&UARTStruct); if (uart->config.data_width == DATA_WIDTH_7BIT) UARTStruct.WordLen = RUART_WLS_7BITS; else if (uart->config.data_width == DATA_WIDTH_8BIT) UARTStruct.WordLen = RUART_WLS_8BITS; else DBG_8195A("UNSUPPORTED DATA LENGTH\n"); if (uart->config.stop_bits == STOP_BITS_1) UARTStruct.StopBit = RUART_STOP_BIT_1; else if (uart->config.stop_bits == STOP_BITS_2) UARTStruct.StopBit = RUART_STOP_BIT_2; else DBG_8195A("UNSUPPORTED STOP BIT\n"); if (uart->config.parity == NO_PARITY) { UARTStruct.Parity = RUART_PARITY_DISABLE; } else if (uart->config.parity == ODD_PARITY) { UARTStruct.Parity = RUART_PARITY_ENABLE; UARTStruct.ParityType = RUART_ODD_PARITY; } else if (uart->config.parity == EVEN_PARITY) { UARTStruct.Parity = RUART_PARITY_ENABLE; UARTStruct.ParityType = RUART_EVEN_PARITY; } else { DBG_8195A("UNSUPPORTED PARITY TYPE\n"); } if (uart->config.flow_control == FLOW_CONTROL_DISABLED) { UARTStruct.FlowControl = DISABLE; } else { UARTStruct.FlowControl = ENABLE; } UART_Init(uart_dev, &UARTStruct); UART_SetBaud(uart_dev, uart->config.baud_rate); InterruptRegister((IRQ_FUN)uart_irq, UART_DEV_TABLE[num].IrqNum, (uint32_t)uart, 5); InterruptEn(UART_DEV_TABLE[num].IrqNum, 5); UART_INTConfig(uart_dev, RUART_IER_ERBI | RUART_IER_ETOI | RUART_IER_ELSI, ENABLE); UART_RxCmd(uart_dev, ENABLE); return 0; } else { /* serial_init(&uart_obj_t, UART_TX, UART_RX); serial_baud(&uart_obj_t, 115200); serial_format(&uart_obj_t, 8, ParityNone, 1); serial_irq_handler(&uart_obj_t, uart_irq, (uint32_t)&uart_obj_t); serial_irq_set(&uart_obj_t, RxIrq, 1);*/ g_uart_init = 1; aos_event_new(&uart0_event, 0); #ifdef AMEBAD_TODO LOGUART_SetBaud_FromFlash(); #endif shell_init_rom(0, 0); shell_init_ram(); ipc_table_init(); /* Register Log Uart Callback function */ extern VOID shell_uart_irq_rom(VOID *Data); InterruptRegister((IRQ_FUN)shell_uart_irq_rom, UART_LOG_IRQ, (u32)NULL, 10); InterruptEn(UART_LOG_IRQ_LP, 10); return 0; } } /** * Transmit data on a UART interface * * @param[in] uart the UART interface * @param[in] data pointer to the start of data * @param[in] size number of bytes to transmit * @param[in] timeout timeout in milisecond, set this value to HAL_WAIT_FOREVER * if you want to wait forever * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_uart_send(uart_dev_t *uart, const void *data, uint32_t size, uint32_t timeout) { u8 num = uart_obj[uart->port].id; UART_TypeDef *uart_dev; uart_dev = UART_DEV_TABLE[num].UARTx; UART_SendDataTO(uart_dev, (uint8_t *)data, size, 1000); return 0; } /** * Receive data on a UART interface * * @param[in] uart the UART interface * @param[out] data pointer to the buffer which will store incoming data * @param[in] expect_size number of bytes to receive * @param[out] recv_size number of bytes received * @param[in] timeout timeout in milisecond, set this value to HAL_WAIT_FOREVER * if you want to wait forever * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_uart_recv_II(uart_dev_t *uart, void *data, uint32_t expect_size, uint32_t *recv_size, uint32_t timeout) { if (uart->port != 0) { u8 num = uart_obj[uart->port].id; UART_TypeDef *uart_dev; uart_dev = UART_DEV_TABLE[num].UARTx; if ((uart_rxbuffer[uart->port].length) <= expect_size) { _memcpy(data, uart_rxbuffer[uart->port].rxbuffer, uart_rxbuffer[uart->port].length); *recv_size = uart_rxbuffer[uart->port].length; uart_rxbuffer[uart->port].length = 0; } else { _memcpy(data, uart_rxbuffer[uart->port].rxbuffer, expect_size); _memcpy(uart_rxbuffer[uart->port].rxbuffer, uart_rxbuffer[uart->port].rxbuffer + expect_size, uart_rxbuffer[uart->port].length - expect_size); *recv_size = expect_size; uart_rxbuffer[uart->port].length -= expect_size; } return 0; } else { uint32_t c = 0; if (data == NULL || expect_size == 0) { return -1; } while (1) { aos_status_t r; uint32_t val; c += uart0_rx_buffer_consume(&((uint8_t *)data)[c], expect_size - c); if (c > 0) break; if (timeout == 0) break; r = aos_event_get(&uart0_event, EVENT_RX_READY, AOS_EVENT_OR, &val, timeout); if (r) break; } if (recv_size) { *recv_size = c; } return c > 0 ? 0 : -1; } } int32_t hal_uart_any(uart_dev_t *uart) { return uart_rxbuffer[uart->port].length; } /** * Deinitialises a UART interface * * @param[in] uart the interface which should be deinitialised * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_uart_finalize(uart_dev_t *uart) { if (uart->port != 0) { u8 num = uart_obj[uart->port].id; UART_DeInit(UART_DEV_TABLE[num].UARTx); InterruptDis(UART_DEV_TABLE[num].IrqNum); InterruptUnRegister(UART_DEV_TABLE[num].IrqNum); aos_free(uart_rxbuffer[uart->port].rxbuffer); return 0; } else { if (g_uart_init == 0) { return 0; } uart0_rx_buf_head = 0; uart0_rx_buf_tail = 0; aos_event_free(&uart0_event); g_uart_init = 0; return 0; } } int hal_uart_rx_sem_take(int uart_id, int timeout) { uint32_t val; if (uart_id != 0) return -EINVAL; return aos_event_get(&uart0_event, EVENT_RX_READY, AOS_EVENT_OR, &val, timeout); } int hal_uart_rx_sem_give(int uart_id) { if (uart_id != 0) return -EINVAL; aos_event_set(&uart0_event, EVENT_RX_READY, AOS_EVENT_OR); return 0; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/uart.c
C
apache-2.0
12,125
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "aos/hal/wdg.h" #include "wdt_api.h" #include "sys_api.h" #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif static bool is_enable_handler = FALSE; void watchdog_irq_handler(uint32_t callback_id) { printf("watchdog_irq_handler, callback_id: %d\n", callback_id); sys_reset( ) ; } void watchdog_irq_set(void) { if(FALSE == is_enable_handler) { watchdog_irq_init(watchdog_irq_handler, 0); is_enable_handler = TRUE; } printf("watchdog_irq_set: is_enable_handler =%d\n", is_enable_handler); return; } int32_t hal_wdg_init(wdg_dev_t *wdg) { uint32_t msecs = wdg->config.timeout; printf("hal_wdg_init, set timeout:%d ms\n", msecs); watchdog_init(msecs); watchdog_irq_set(); watchdog_start(); return 0; } void hal_wdg_reload(wdg_dev_t *wdg) { WDG_TypeDef* WDG = ((WDG_TypeDef *) 0x48002800); u32 temp = WDG->VENDOR; temp |= WDG_BIT_CLEAR; WDG->VENDOR = temp; watchdog_refresh(); } int32_t hal_wdg_finalize(wdg_dev_t *wdg) { watchdog_stop(); return 0; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/wdg.c
C
apache-2.0
1,092
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "aos/hal/wifi.h" #include <platform/platform_stdlib.h> #include <wifi/wifi_conf.h> #include <wifi/wifi_util.h> #include <wifi/wifi_ind.h> #include <lwip_netconf.h> #include <osdep_service.h> #include <uservice/uservice.h> #include <uservice/eventid.h> #include <devicevfs/devicevfs.h> #include <lwip/inet.h> #if CONFIG_LWIP_LAYER extern struct netif xnetif[NET_IF_NUM]; #endif monitor_data_cb_t g_promisc_data_callback = NULL; monitor_data_cb_t g_mgnt_filter_callback = NULL; wifi_promiscuous_cb_t g_promisc_user_callback = NULL; static aos_sem_t scan_sem; int haas200_wifi_channel_list[64]; int haas200_wifi_channel_list_num = 0; int haas200_wifi_init(netdev_t *dev) { int ret; #if CONFIG_LWIP_LAYER LwIP_Init(); #endif wifi_on(RTW_MODE_STA); wifi_disable_powersave(); ret = aos_sem_new(&scan_sem, 0); if (ret != 0) return -1; return 0; } int haas200_wifi_deinit(netdev_t *dev) { return wifi_off(); } int haas200_wifi_set_mode(netdev_t *dev, wifi_mode_t mode) { return wifi_set_mode(mode); } int haas200_wifi_get_mode(netdev_t *dev, wifi_mode_t *devode) { return wext_get_mode(WLAN0_NAME, (int *)devode); } int haas200_wifi_install_event_cb(netdev_t *dev, wifi_event_func *evt_cb) { return 0; } int haas200_wifi_cancel_connect(netdev_t *dev) { int ret = wifi_disconnect(); if (ret < 0) { printf("\n\rERROR: Operation failed!"); return ret; } return ret; } int haas200_wifi_set_mac_addr(netdev_t *dev, const uint8_t *devac) { return wifi_set_mac_address((char *)devac); } int haas200_wifi_get_mac_addr(netdev_t *dev, uint8_t *devac) { char buf[32]; uint32_t mac[ETH_ALEN]; int i = 0; wifi_get_mac_address(buf); sscanf(buf, "%02x:%02x:%02x:%02x:%02x:%02x", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]); for (i = 0; i < ETH_ALEN; i++) devac[i] = mac[i] & 0xFF; return 0; } int haas200_wifi_set_lpm(netdev_t *dev, wifi_lpm_mode_t mode) { wext_set_powersave_mode(mode); return 0; } int haas200_wifi_get_lpm(netdev_t *dev, wifi_lpm_mode_t *mode) { wext_get_powersave_mode(mode); return 0; } int haas200_wifi_notify_ip_state2drv(netdev_t *dev, wifi_ip_stat_t *out_net_para, wifi_mode_t wifi_type) { ip4_addr_t ipaddr; ip4_addr_t netmask; ip4_addr_t gw; if (!out_net_para) { printf("%s: invalid argument!\n", __func__); return -1; } if (wifi_type == RTW_MODE_STA) { inet_aton(out_net_para->ip, &ipaddr); inet_aton(out_net_para->mask, &netmask); inet_aton(out_net_para->gate, &gw); netif_set_addr(&xnetif[0], &ipaddr, &netmask, &gw); return 0; } return -1; } static void print_scan_result(rtw_scan_result_t *record) { printf("%s\t ", (record->bss_type == RTW_BSS_TYPE_ADHOC) ? "Adhoc" : "Infra"); printf(MAC_FMT, MAC_ARG(record->BSSID.octet)); printf(" %d\t ", record->signal_strength); printf(" %d\t ", record->channel); printf(" %d\t ", record->wps_type); printf("%s\t\t ", (record->security == RTW_SECURITY_OPEN) ? "Open" : (record->security == RTW_SECURITY_WEP_PSK) ? "WEP" : (record->security == RTW_SECURITY_WPA_TKIP_PSK) ? "WPA TKIP" : (record->security == RTW_SECURITY_WPA_AES_PSK) ? "WPA AES" : (record->security == RTW_SECURITY_WPA_MIXED_PSK) ? "WPA Mixed" : (record->security == RTW_SECURITY_WPA2_AES_PSK) ? "WPA2 AES" : (record->security == RTW_SECURITY_WPA2_TKIP_PSK) ? "WPA2 TKIP" : (record->security == RTW_SECURITY_WPA2_MIXED_PSK) ? "WPA2 Mixed" : (record->security == RTW_SECURITY_WPA_WPA2_TKIP_PSK) ? "WPA/WPA2 TKIP" : (record->security == RTW_SECURITY_WPA_WPA2_AES_PSK) ? "WPA/WPA2 AES" : (record->security == RTW_SECURITY_WPA_WPA2_MIXED_PSK) ? "WPA/WPA2 Mixed" : #ifdef CONFIG_SAE_SUPPORT (record->security == RTW_SECURITY_WPA3_AES_PSK) ? "WP3-SAE AES" : #endif "Unknown"); printf(" %s ", record->SSID.val); printf("\r\n"); } static int scan_result_handler(rtw_scan_handler_result_t *malloced_scan_result) { static int ApNum = 0; if (malloced_scan_result->scan_complete != RTW_TRUE) { rtw_scan_result_t *record = &malloced_scan_result->ap_details; record->SSID.val[record->SSID.len] = 0; /* Ensure the SSID is null terminated */ printf("%d\t ", ++ApNum); print_scan_result(record); if (malloced_scan_result->user_data) rtw_memcpy((void *)((char *)malloced_scan_result->user_data + (ApNum - 1) * sizeof(rtw_scan_result_t)), (char *)record, sizeof(rtw_scan_result_t)); } else { int i = 0; static wifi_scan_result_t result = { 0 }; if (ApNum == 0) goto end; result.ap_list = (ap_list_t *)malloc(ApNum * sizeof(ap_list_t)); if (result.ap_list == NULL) { printf("ERROR: malloc failed!\n"); goto end; } for (i = 0; i < ApNum; i++) { rtw_scan_result_t *res = malloced_scan_result->user_data + i * sizeof(rtw_scan_result_t); rtw_memcpy((result.ap_list + i)->ssid, res->SSID.val, res->SSID.len); rtw_memcpy((result.ap_list + i)->bssid, res->BSSID.octet, 6); (result.ap_list + i)->ap_power = res->signal_strength; (result.ap_list + i)->channel = res->channel; (result.ap_list + i)->sec_type = res->security; } result.ap_num = ApNum; end: ApNum = 0; event_publish(EVENT_WIFI_SCAN_DONE, &result); if (malloced_scan_result->user_data) rtw_free(malloced_scan_result->user_data); } return 0; } int haas200_wifi_start_scan(netdev_t *dev, wifi_scan_config_t *config, bool block) { char *scan_buf; scan_buf = rtw_malloc(65 * sizeof(rtw_scan_result_t)); if (!scan_buf) { printf("ERROR: malloc failed!\n"); return -1; } rtw_memset(scan_buf, 0, 65 * sizeof(rtw_scan_result_t)); if (wifi_scan_networks((rtw_scan_result_handler_t)scan_result_handler, scan_buf) != 0) { printf("ERROR: wifi scan failed!\n"); return -1; } return 0; } /*find ap with "ssid" from scan list*/ static int _find_ap_from_scan_buf(char *buf, int buflen, char *target_ssid, void *user_data) { rtw_wifi_setting_t *pwifi = (rtw_wifi_setting_t *)user_data; int plen = 0; while (plen < buflen) { u8 len, ssid_len, security_mode; char *ssid; // len offset = 0 len = (int)*(buf + plen); // check end if (len == 0) break; // ssid offset = 14 ssid_len = len - 14; ssid = buf + plen + 14; if ((ssid_len == strlen(target_ssid)) && (!memcmp(ssid, target_ssid, ssid_len))) { // DBG_8195A("find a ap \r\n"); strncpy((char *)pwifi->ssid, target_ssid, 33); // channel offset = 13 pwifi->channel = *(buf + plen + 13); // security_mode offset = 11 security_mode = (u8)*(buf + plen + 11); switch (security_mode) { case IW_ENCODE_ALG_NONE: pwifi->security_type = SECURITY_TYPE_NONE; break; case IW_ENCODE_ALG_WEP: pwifi->security_type = SECURITY_TYPE_WEP; break; case IW_ENCODE_ALG_CCMP: pwifi->security_type = SECURITY_TYPE_WPA2_AES; break; } if (IW_ENCODE_ALG_WEP != security_mode) break; } plen += len; } return 0; } /*get ap security mode from scan list*/ static int _get_ap_security_mode(IN char *ssid, OUT rtw_security_t *security_mode, OUT u8 *channel) { rtw_wifi_setting_t wifi; u32 scan_buflen = 1000; memset(&wifi, 0, sizeof(wifi)); if (wifi_scan_networks_with_ssid(_find_ap_from_scan_buf, (void *)&wifi, scan_buflen, ssid, strlen(ssid)) != RTW_SUCCESS) { printf("ERROR: wifi scan failed!\n"); return 0; } if (strcmp(wifi.ssid, ssid) == 0) { // printf("Wifi scanned !\n"); *security_mode = wifi.security_type; *channel = wifi.channel; return 1; } return 0; } rtw_security_t haas200_security_type_to_rtw(wifi_sec_type_t sec_type) { rtw_security_t security_type = RTW_SECURITY_UNKNOWN; switch (sec_type) { case SECURITY_TYPE_NONE: security_type = RTW_SECURITY_OPEN; break; case SECURITY_TYPE_WEP: security_type = RTW_SECURITY_WEP_PSK; break; case SECURITY_TYPE_WPA_TKIP: security_type = RTW_SECURITY_WPA_TKIP_PSK; break; case SECURITY_TYPE_WPA_AES: security_type = RTW_SECURITY_WPA_AES_PSK; break; case SECURITY_TYPE_WPA2_TKIP: security_type = RTW_SECURITY_WPA2_TKIP_PSK; break; case SECURITY_TYPE_WPA2_AES: security_type = RTW_SECURITY_WPA2_AES_PSK; break; case SECURITY_TYPE_WPA2_MIXED: security_type = RTW_SECURITY_WPA2_MIXED_PSK; break; case SECURITY_TYPE_AUTO: security_type = RTW_SECURITY_WPA2_AES_PSK; break; } return security_type; } int haas200_wifi_connect(netdev_t *dev, wifi_config_t *config) { int ret = -1; int key_id = -1; uint8_t ssid[MAX_SSID_SIZE + 1] = { 0 }; uint8_t password[MAX_PASSWD_SIZE + 1] = { 0 }; uint32_t ssid_len, passwd_len; uint8_t channel; uint8_t pscan_config = (PSCAN_ENABLE | PSCAN_FAST_SURVEY); rtw_security_t security_type = RTW_SECURITY_UNKNOWN; char empty_bssid[ETH_ALEN] = { 0 }, assoc_by_bssid = 0; if (!config) return -1; if (config->mode != RTW_MODE_STA) return -1; #if CONFIG_AUTO_RECONNECT wifi_set_autoreconnect(0); #endif ssid_len = strlen(config->ssid); passwd_len = strlen(config->password); channel = config->sta_config.channel; rtw_memcpy(ssid, config->ssid, ssid_len); if (passwd_len == 0) { security_type = RTW_SECURITY_OPEN; } else { rtw_memcpy(password, config->password, passwd_len); security_type = haas200_security_type_to_rtw(config->sta_config.sec_type); } if (!rtw_memcmp(config->sta_config.bssid, empty_bssid, ETH_ALEN)) assoc_by_bssid = 1; if (wifi_set_pscan_chan(&channel, &pscan_config, 1) < 0) { printf("ERROR: Set channel pscan failed!\n"); return -1; } if (security_type == RTW_SECURITY_WEP_PSK || security_type == RTW_SECURITY_WEP_SHARED) key_id = 0; if (assoc_by_bssid) { ret = wifi_connect_bssid(config->sta_config.bssid, ssid, security_type, password, ETH_ALEN, ssid_len, passwd_len, key_id, NULL); } else { ret = wifi_connect(ssid, security_type, password, ssid_len, passwd_len, key_id, NULL); } if (ret != 0) { if (ret == RTW_INVALID_KEY) printf("\n\rERROR:Invalid Key\n"); printf("\n\rERROR: Can't connect to AP,ret:%d\n", ret); return ret; } printf("Wifi Connect Successed\n"); event_publish(EVENT_WIFI_CONNECTED, &xnetif[0]); return 0; } int haas200_wifi_disconnect(netdev_t *dev) { char essid[MAX_SSID_SIZE + 1]; int ret = 0, timeout = 20; if (wext_get_ssid(WLAN0_NAME, (unsigned char *)essid) < 0) { printf("\n\rnot connected yet"); return ret; } ret = wifi_disconnect(); if (ret < 0) { printf("\n\rERROR: Operation failed!\n"); return ret; } while (1) { if (wext_get_ssid(WLAN0_NAME, (unsigned char *)essid) < 0) break; if (timeout == 0) { printf("\n\rERROR: Deassoc timeout!\n"); ret = -1; break; } aos_msleep(1); timeout--; } #if CONFIG_LWIP_LAYER LwIP_ReleaseIP(WLAN0_IDX); #endif event_publish(EVENT_WIFI_DISCONNECTED, NULL); return ret; } int haas200_wifi_sta_get_link_status(netdev_t *dev, wifi_ap_record_t *ap_info) { rtw_wifi_setting_t setting; int rssi; wifi_get_setting(WLAN0_NAME, &setting); wifi_get_rssi(&rssi); ap_info->link_status = setting.mode; rtw_memcpy(ap_info->ssid, setting.ssid, strlen(setting.ssid)); ap_info->channel = setting.channel; ap_info->rssi = (int8_t)rssi; ap_info->encryptmode = setting.security_type; switch (setting.security_type) { case RTW_SECURITY_OPEN: ap_info->authmode = WIFI_AUTH_OPEN; break; case RTW_SECURITY_WEP_PSK: case RTW_SECURITY_WEP_SHARED: ap_info->authmode = WIFI_AUTH_WEP; break; case RTW_SECURITY_WPA_TKIP_PSK: case RTW_SECURITY_WPA_AES_PSK: ap_info->authmode = WIFI_AUTH_WPA_PSK; break; case RTW_SECURITY_WPA2_AES_PSK: case RTW_SECURITY_WPA2_TKIP_PSK: case RTW_SECURITY_WPA2_MIXED_PSK: ap_info->authmode = WIFI_AUTH_WPA2_PSK; break; case RTW_SECURITY_WPA_WPA2_MIXED_PSK: ap_info->authmode = WIFI_AUTH_MAX; break; default: printf("unknow security mode!\n"); break; } return 0; } int haas200_wifi_ap_get_sta_list(netdev_t *dev, wifi_sta_list_t *sta) { return wifi_get_associated_client_list(sta, sizeof(sta)); } // callback for promisc packets, like rtk_start_parse_packet in SC, wf, 1021 static void wifi_promisc_rx_cb(unsigned char *buf, unsigned int len, void *user_data) { wifi_link_info_t link_info; wifi_promiscuous_pkt_t *p_buf = NULL; link_info.rssi = ((ieee80211_frame_info_t *)user_data)->rssi; if (g_promisc_data_callback) g_promisc_data_callback(buf, len, &link_info); if (g_promisc_user_callback) { p_buf = aos_malloc(sizeof(wifi_promiscuous_pkt_t) + len); memcpy(p_buf->payload, buf, len); p_buf->rx_ctrl.sig_len = len; p_buf->rx_ctrl.rssi = ((ieee80211_frame_info_t *)user_data)->rssi; g_promisc_user_callback(p_buf, 0); aos_free(p_buf); } } int haas200_wifi_start_monitor(netdev_t *dev, wifi_promiscuous_cb_t cb) { #if CONFIG_AUTO_RECONNECT wifi_set_autoreconnect(RTW_AUTORECONNECT_DISABLE); #endif wifi_init_packet_filter(); wifi_enter_promisc_mode(); wifi_set_promisc(RTW_PROMISC_ENABLE_2, wifi_promisc_rx_cb, 0); g_promisc_user_callback = cb; return 0; } int haas200_wifi_stop_monitor(netdev_t *dev) { g_promisc_data_callback = NULL; wifi_set_promisc(RTW_PROMISC_DISABLE, NULL, 0); return 0; } int haas200_wifi_send_80211_raw_frame(netdev_t *dev, void *buffer, uint16_t len) { int ret = -2; len = len - 4; /* remove fcs */ ret = wext_send_mgnt(WLAN0_NAME, (char *)buffer, len, 1); return ret; } int haas200_wifi_get_channel(netdev_t *dev, int *channel) { return wifi_get_channel(channel); } int haas200_wifi_set_channel(netdev_t *dev, int channel) { return wifi_set_channel(channel); } static int specified_scan_result_handler(char *buf, int buflen, char *target_ssid, void *user_data) { ap_list_t *ap_list = (ap_list_t *)user_data; int cmp_rssi = -120; int plen = 0; while (plen < buflen) { int len, rssi, ssid_len, security_mode, i; char *ssid, *mac, exchange = 0; /* len offset = 0 */ len = (int)*(buf + plen); /* check end */ if (len == 0) break; /* mac */ mac = buf + plen + 1; /* rssi */ rssi = *(int *)(buf + plen + 7); if (rssi > cmp_rssi) { cmp_rssi = rssi; exchange = 1; strncpy(ap_list->bssid, mac, 6); ap_list->ap_power = rssi; } /* ssid offset = 14 */ ssid_len = len - 14; ssid = buf + plen + 14; if ((ssid_len == strlen(target_ssid)) && (!memcmp(ssid, target_ssid, ssid_len)) && exchange) { strncpy((char *)ap_list->ssid, target_ssid, 33); /* channel offset = 13 */ ap_list->channel = *(buf + plen + 13); /* security_mode offset = 11 */ security_mode = (u8)*(buf + plen + 11); switch (security_mode) { case IW_ENCODE_ALG_NONE: ap_list->sec_type = SECURITY_TYPE_NONE; break; case IW_ENCODE_ALG_WEP: ap_list->sec_type = SECURITY_TYPE_WEP; break; case IW_ENCODE_ALG_CCMP: ap_list->sec_type = SECURITY_TYPE_WPA2_AES; break; } } plen += len; } aos_sem_signal((aos_sem_t *)&scan_sem); return 0; } int haas200_wifi_start_specified_scan(netdev_t *dev, ap_list_t *ap_list, int ap_num) { static wifi_scan_result_t result = { 0 }; int i, scan_buf_len = 500; uint8_t *pscan_config = NULL; uint8_t *channel_list = NULL; if (!ap_num || !ap_list) { printf("ERROR: error params\n"); return -1; } if (result.ap_list == NULL) result.ap_list = (ap_list_t *)malloc(ap_num * sizeof(ap_list_t)); if (!result.ap_list) { printf("ERROR: malloc for ap list failed!\n"); return -1; } if (haas200_wifi_channel_list && haas200_wifi_channel_list_num > 0) { channel_list = (uint8_t *)malloc(haas200_wifi_channel_list_num); if (!channel_list) { printf("ERROR: malloc for channel list failed!\n"); return -1; } pscan_config = (uint8_t *)malloc(haas200_wifi_channel_list_num); if (!pscan_config) { printf("ERROR: malloc for pscan config failed!\n"); return -1; } for (int i = 0; i < haas200_wifi_channel_list_num; i++) { *(channel_list + i) = (uint8_t)haas200_wifi_channel_list[i]; *(pscan_config + i) = PSCAN_ENABLE; } if (wifi_set_pscan_chan(channel_list, pscan_config, haas200_wifi_channel_list_num) < 0) { printf("ERROR: set channel pscan failed!"); return -1; } } result.ap_num = ap_num; for (i = 0; i < ap_num; i++) { ap_list_t ap = *(ap_list + i); if (wifi_scan_networks_with_ssid(specified_scan_result_handler, &ap, scan_buf_len, ap.ssid, strlen(ap.ssid)) != 0) { printf("ERROR: wifi scan failed\n\r"); return -1; } aos_sem_wait((aos_sem_t *)&scan_sem, AOS_WAIT_FOREVER); *(ap_list + i) = ap; *(result.ap_list + i) = ap; } end: event_publish(EVENT_WIFI_SCAN_DONE, &result); return 0; } int haas200_wifi_register_monitor_cb(netdev_t *dev, monitor_data_cb_t fn) { if (!fn) return -1; g_promisc_data_callback = fn; return 0; } int haas200_wifi_start_mgnt_monitor(netdev_t *dev) { wifi_set_indicate_mgnt(2); return 0; } int haas200_wifi_stop_mgnt_monitor(netdev_t *dev) { g_mgnt_filter_callback = NULL; wifi_set_indicate_mgnt(0); return 0; } static void wifi_rx_mgnt_hdl(u8 *buf, int len, int flags, void *user_data) { wifi_link_info_t link_info; /* only deal with Probe Request*/ if (g_mgnt_filter_callback && buf[0] == 0x40) g_mgnt_filter_callback((u8 *)buf, len, &link_info); } int haas200_wifi_register_mgnt_monitor_cb(netdev_t *dev, monitor_data_cb_t fn) { if (!fn) return -1; g_mgnt_filter_callback = fn; wifi_reg_event_handler(WIFI_EVENT_RX_MGNT, (rtw_event_handler_t)wifi_rx_mgnt_hdl, NULL); return 0; } int haas200_wifi_set_channellist(netdev_t *dev, wifi_channel_list_t *channellist) { memset(&haas200_wifi_channel_list, 0, 64 * sizeof(int)); memcpy(&haas200_wifi_channel_list, channellist->channel_list, channellist->channel_num * sizeof(int)); haas200_wifi_channel_list_num = channellist->channel_num; return 0; } int haas200_wifi_get_channellist(netdev_t *dev, wifi_channel_list_t *channellist) { channellist->channel_list = &haas200_wifi_channel_list; channellist->channel_num = haas200_wifi_channel_list_num; return 0; } static wifi_driver_t haas200_wifi_driver = { /** driver info */ .base.os = "rtos", .base.type = "solo", .base.partner = "AliOS Things Team", .base.app_net = "rtsp+rtp+rtcp", .base.project = "HAAS200", .base.cloud = "aliyun", /** common APIs */ .init = haas200_wifi_init, .deinit = haas200_wifi_deinit, .set_mode = haas200_wifi_set_mode, .get_mode = haas200_wifi_get_mode, .install_event_cb = haas200_wifi_install_event_cb, /** conf APIs */ .set_mac_addr = haas200_wifi_set_mac_addr, .get_mac_addr = haas200_wifi_get_mac_addr, .set_lpm = haas200_wifi_set_lpm, .get_lpm = haas200_wifi_get_lpm, .notify_ip_state2drv = haas200_wifi_notify_ip_state2drv, /** connection APIs */ .start_scan = haas200_wifi_start_scan, .start_specified_scan = haas200_wifi_start_specified_scan, .connect = haas200_wifi_connect, .cancel_connect = haas200_wifi_cancel_connect, .disconnect = haas200_wifi_disconnect, .sta_get_link_status = haas200_wifi_sta_get_link_status, .ap_get_sta_list = haas200_wifi_ap_get_sta_list, /** promiscuous APIs */ .start_monitor = haas200_wifi_start_monitor, .stop_monitor = haas200_wifi_stop_monitor, .send_80211_raw_frame = haas200_wifi_send_80211_raw_frame, .set_channel = haas200_wifi_set_channel, .get_channel = haas200_wifi_get_channel, .register_monitor_cb = haas200_wifi_register_monitor_cb, .start_mgnt_monitor = haas200_wifi_start_mgnt_monitor, .stop_mgnt_monitor = haas200_wifi_stop_mgnt_monitor, .register_mgnt_monitor_cb = haas200_wifi_register_mgnt_monitor_cb, .set_smartcfg = NULL, .set_channellist = haas200_wifi_set_channellist, .get_channellist = haas200_wifi_get_channellist, }; int haas200_wifi_register(void) { vfs_wifi_dev_register(&haas200_wifi_driver, 0); return 0; } VFS_DRIVER_ENTRY(haas200_wifi_register);
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/wifi_port.c
C
apache-2.0
22,280
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <drivers/u_ld.h> #include <vfsdev/wifi_dev.h> #include <uservice/uservice.h> #include <uservice/eventid.h> #include <aos/hal/wifi.h> #if LWIP_ETHERNETIF && !LWIP_SUPPORT #include <lwip/def.h> #include <lwip/netdb.h> #endif #include "aos/vfs.h" #include "fcntl.h" #include "plat_types.h" #include "bwifi_interface.h" #include "bes_sniffer.h" typedef enum { SCAN_NORMAL, SCAN_SPECIFIED } scan_type_t; static struct { uint8_t wifi_started:1; uint8_t resetting:1; uint8_t sta_connected:1; uint8_t sta_got_ip:1; uint8_t sap_started:1; uint8_t sap_connected:1; uint8_t smart_config:1; uint8_t zero_config:1; struct { int ap_num; ap_list_t ap_list[3]; } scan_req; struct { uint8_t bssid[6]; wifi_ip_stat_t ip_stat; } network; netdev_t* dev; } wifi_status; static monitor_data_cb_t promisc_cb; static monitor_data_cb_t mgnt_frame_cb; struct netif *wifi_get_netif(netdev_t *dev, wifi_mode_t mode) { #if LWIP_ETHERNETIF && !LWIP_SUPPORT if (mode == WIFI_MODE_STA) return bwifi_get_netif(WIFI_IF_STATION); else if (mode == WIFI_MODE_AP) return bwifi_get_netif(WIFI_IF_SOFTAP); #endif return NULL; } static void on_wifi_connect(WIFI_USER_EVT_ID event_id, void *arg) { printf("%s event_id:%d\n", __func__, event_id); if (event_id == WIFI_USER_EVT_CONN_INTER_STATE) { BWIFI_CONNECT_INTER_STATE state = *(BWIFI_CONNECT_INTER_STATE *)arg; int event; switch (state) { case INTER_STATE_AUTHENTICATING: event = EVENT_WIFI_AUTHENTICATING; break; case INTER_STATE_AUTH_REJECT: event = EVENT_WIFI_AUTH_REJECT; break; case INTER_STATE_AUTH_TIMEOUT: event = EVENT_WIFI_AUTH_TIMEOUT; break; case INTER_STATE_ASSOCIATING: event = EVENT_WIFI_ASSOCIATING; break; case INTER_STATE_ASSOC_REJECT: event = EVENT_WIFI_ASSOC_REJECT; break; case INTER_STATE_ASSOC_TIMEOUT: event = EVENT_WIFI_ASSOC_TIMEOUT; break; case INTER_STATE_ASSOCIATED: event = EVENT_WIFI_ASSOCIATED; break; case INTER_STATE_4WAY_HANDSHAKE: event = EVENT_WIFI_4WAY_HANDSHAKE; break; case INTER_STATE_HANDSHAKE_FAIL: event = EVENT_WIFI_HANDSHAKE_FAILED; break; case INTER_STATE_GROUP_HANDSHAKE: event = EVENT_WIFI_GROUP_HANDSHAKE; break; default: /* Unhandled intermediate states */ return; } #if 0 if (m->ev_cb && m->ev_cb->stat_chg) { m->ev_cb->stat_chg(m, event, NULL); } #endif event_publish(event, NULL); } else if (event_id == WIFI_USER_EVT_CONNECTED) { uint8_t *bssid = (uint8_t *)arg; wifi_status.sta_connected = 1; memcpy(wifi_status.network.bssid, bssid, 6); #if 0 if (m->ev_cb && m->ev_cb->stat_chg) { m->ev_cb->stat_chg(m, NOTIFY_WIFI_CONNECTED, NULL); } #endif event_publish(EVENT_WIFI_CONNECTED, wifi_get_netif(wifi_status.dev, WIFI_MODE_STA)); #if LWIP_SUPPORT } else if (event_id == WIFI_USER_EVT_GOT_IP) { struct ip_info *ip = (struct ip_info *)arg; wifi_status.sta_got_ip = 1; snprintf(wifi_status.network.ip_stat.ip, sizeof(wifi_status.network.ip_stat.ip), "%s", inet_ntoa(ip->ip)); snprintf(wifi_status.network.ip_stat.mask, sizeof(wifi_status.network.ip_stat.mask), "%s", inet_ntoa(ip->netmask)); snprintf(wifi_status.network.ip_stat.gate, sizeof(wifi_status.network.ip_stat.gate), "%s", inet_ntoa(ip->gw)); #if 0 if (m->ev_cb && m->ev_cb->ip_got) { m->ev_cb->ip_got(m, &wifi_status.network.ip_stat, NULL); } if (m->ev_cb && m->ev_cb->para_chg) { memcpy(info.bssid, wifi_status.network.bssid, 6); m->ev_cb->para_chg(m, &info, NULL, 0, NULL); } #endif #endif } } static void on_wifi_disconnect(WIFI_USER_EVT_ID event_id, void *arg) { printf("%s event_id:%d\n", __func__, event_id); if (event_id == WIFI_USER_EVT_DISCONNECTED) { uint8_t reason = *(uint8_t *)arg; wifi_status.sta_connected = 0; wifi_status.sta_got_ip = 0; printf("wifi disconnected (reason=%d, locally_generated=%d)\n", reason & 0x7F, (reason & BIT(7)) >> 7); #if 0 if (m->ev_cb && m->ev_cb->stat_chg) { m->ev_cb->stat_chg(m, NOTIFY_WIFI_DISCONNECTED, &reason); } #endif event_publish(EVENT_WIFI_DISCONNECTED, &reason); } } static void on_fatal_error(WIFI_USER_EVT_ID event_id, void *arg) { printf("%s event_id:%d\n", __func__, event_id); if (event_id == WIFI_USER_EVT_FATAL_ERROR) { uint8 rst_flag = ((BWIFI_FATAL_ERROR_RESET_T *)arg)->rst_flag; uint16 error = ((BWIFI_FATAL_ERROR_RESET_T *)arg)->error_cause; BWIFI_LMAC_STATUS_DUMP_T dump_info = ((BWIFI_FATAL_ERROR_RESET_T *)arg)->dump_info; char str_buf[300]; size_t nbytes; ssize_t written_bytes; const char *pfile = "/data/wifi_reset_reports"; int fd; if (rst_flag == 1) { wifi_status.resetting = 1; printf("Bottom layer crashed, wifi card will be reset...\n"); #if 0 if (m->ev_cb && m->ev_cb->fatal_err) { m->ev_cb->fatal_err(m, NULL); } #endif nbytes = snprintf(str_buf, sizeof(str_buf), "errorCode=0x%04x\ndumpInfo=0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x", error, dump_info.pac_rxc_rx_buf_in_ptr, dump_info.pac_rxc_rx_buf_out_ptr, dump_info.scheduler_events, dump_info.lmac_pc0, dump_info.lmac_pc1, dump_info.lmac_lr, dump_info.lmac_sp, dump_info.pac_ntd_status_peek, dump_info.pac_txc_status, dump_info.QUEUE_0_CONTROL, dump_info.QUEUE_1_CONTROL, dump_info.QUEUE_2_CONTROL, dump_info.QUEUE_3_CONTROL, dump_info.wlan_sw_override_1, dump_info.tsq_in_prog, dump_info.tsq_in_cmpl); if (nbytes <= 0) { printf("snprintf fail, return %d", nbytes); return; } aos_vfs_init(); fd = aos_open(pfile, O_CREAT | O_RDWR); if (fd < 0) { printf("Failed to open file %s (%d)\n", pfile, fd); return; } written_bytes = aos_write(fd, str_buf, nbytes); if (written_bytes < 0) { printf("Failed to write file %s\n", pfile); } else if (written_bytes != nbytes) { printf("Incompletely write file %s, nbytes:%d, written_bytes:%d\n", pfile, nbytes, written_bytes); } aos_close(fd); } else if (rst_flag == 2) { wifi_status.resetting = 0; printf("wifi card is completely reset !!!\n"); #if 0 if (m->ev_cb && m->ev_cb->fatal_err) { m->ev_cb->fatal_err(m, NULL); } #endif } } } static int haas1000_wifi_init(netdev_t *dev) { static int inited; int ret; if (inited) return 0; ret = bwifi_init(); if (ret) { printf("bwifi init fail\n"); return -1; } /* Register event callbacks */ bwifi_reg_user_evt_handler(WIFI_USER_EVT_CONN_INTER_STATE, on_wifi_connect); bwifi_reg_user_evt_handler(WIFI_USER_EVT_CONNECTED, on_wifi_connect); bwifi_reg_user_evt_handler(WIFI_USER_EVT_GOT_IP, on_wifi_connect); bwifi_reg_user_evt_handler(WIFI_USER_EVT_DISCONNECTED, on_wifi_disconnect); bwifi_reg_user_evt_handler(WIFI_USER_EVT_FATAL_ERROR, on_fatal_error); inited = 1; wifi_status.wifi_started = 1; wifi_status.dev = dev; printf("wifi init success!!\n"); return 0; }; static int haas1000_wifi_deinit(netdev_t *dev) { return 0; } static int haas1000_wifi_get_mac_addr(netdev_t *dev, uint8_t *mac) { if (!mac) {printf("%s: invalid argument!\n", __func__); return -1;} bwifi_get_own_mac(mac); return 0; }; static int haas1000_wifi_set_mac_addr(netdev_t *dev, const uint8_t *mac) { printf("WiFi HAL %s not implemeted yet!\n", __func__); return -1; }; static void wifi_connect_task(void *arg) { int ret = 0; wifi_config_t *init_para = (wifi_config_t*)arg; if (!init_para) return; ret = bwifi_connect_to_ssid(init_para->ssid, init_para->password, 0, 0, NULL); if (ret) { printf("wifi connect to %s fail:%d\n", init_para->ssid, ret); #if 0 if (m->ev_cb && m->ev_cb->connect_fail) { m->ev_cb->connect_fail(m, ret, NULL); } #endif } aos_free(init_para); //aos_task_exit(0); osThreadExitPub(); } __SRAMDATA osThreadDef(wifi_connect_task, osPriorityNormal, 1, (4096), "wifi_connect"); static int haas1000_wifi_connect(netdev_t *dev, wifi_config_t* config) { if (!config) { printf("%s: invalid argument!\n", __func__); return -1; } if (WARN_ON(!wifi_status.wifi_started || wifi_status.resetting)) return -1; if (config->mode == WIFI_MODE_STA) { wifi_config_t *init_config_ptr = aos_malloc(sizeof(wifi_config_t)); if (!init_config_ptr) { printf("Failed to alloc init para for wifi_connect_task\n"); return -1; } strcpy(init_config_ptr->ssid, config->ssid); strcpy(init_config_ptr->password, config->password); //if (aos_task_new("wifi_connect", wifi_connect_task, init_para_ptr, 4096)) { if (osThreadCreate(osThread(wifi_connect_task), init_config_ptr) == NULL) { printf("Failed to create wifi_connect_task\n"); aos_free(init_config_ptr); return -1; } } else if (config->mode == WIFI_MODE_AP) { /* TODO */ } return 0; } static int haas1000_wifi_notify_ip_state2drv(netdev_t *dev, wifi_ip_stat_t *in_net_para, wifi_mode_t mode) { #if LWIP_ETHERNETIF && !LWIP_SUPPORT struct ip_info ip; if (!in_net_para) { printf("%s: invalid argument!\n", __func__); return -1; } if (mode == WIFI_MODE_STA&& wifi_status.sta_connected) { memcpy(&wifi_status.network.ip_stat, in_net_para, sizeof(wifi_ip_stat_t)); printf("set ip: %s\n", in_net_para->ip); printf("set mask: %s\n", in_net_para->mask); printf("set gw: %s\n", in_net_para->gate); inet_aton(in_net_para->ip, &ip.ip); inet_aton(in_net_para->mask, &ip.netmask); inet_aton(in_net_para->gate, &ip.gw); return bwifi_set_ip_addr(WIFI_IF_STATION, &ip); } #endif return -1; } static int get_ip_stat(netdev_t *dev, wifi_ip_stat_t *out_net_para, wifi_mode_t mode) { #if LWIP_SUPPORT if (!out_net_para) { printf("%s: invalid argument!\n", __func__); return -1; } if (mode == WIFI_MODE_STA&& wifi_status.sta_got_ip) { memcpy(out_net_para, &wifi_status.network.ip_stat, sizeof(wifi_ip_stat_t)); return 0; } #endif return -1; } static int haas1000_wifi_sta_get_link_status(netdev_t *dev, wifi_ap_record_t *out_stat) { if (!out_stat) { printf("%s: invalid argument!\n", __func__); return -1; } if (wifi_status.sta_connected) { out_stat->link_status = WIFI_STATUS_LINK_UP; out_stat->rssi = bwifi_get_current_rssi(); bwifi_get_current_ssid(out_stat->ssid); bwifi_get_current_bssid(out_stat->bssid); out_stat->channel = bwifi_get_current_channel(); } else { out_stat->link_status = WIFI_STATUS_LINK_DOWN; } return 0; } static int find_index_by_value(int value, int *array, int size) { int i; for( i=0; i<size; i++ ) { if( array[i] == value ) break; } return i; } static int wifi_scan(netdev_t *dev, wifi_scan_config_t* config, bool block, scan_type_t t) { int i, ret; struct bwifi_ssid *scan_ssid, *prev_scan_ssid; struct bwifi_scan_config scan_config; struct bwifi_bss_info *scan_result; static wifi_scan_result_t result = {0}; int index = 0, a_size = 0; int scan_chs[] = {1, 6, 11, 2, 3, 4, 5, 7, 8, 9, 10, 12, 13, 0}; if (WARN_ON(!wifi_status.wifi_started || wifi_status.resetting)) return -1; if (t == SCAN_SPECIFIED) { prev_scan_ssid = NULL; a_size = sizeof(scan_chs)/sizeof(scan_chs[0]) - 1; for (i = 0; i < wifi_status.scan_req.ap_num; i++) { index = find_index_by_value(wifi_status.scan_req.ap_list[i].channel, scan_chs, a_size); if( index < a_size && index > i) { scan_chs[index] = scan_chs[i]; scan_chs[i] = wifi_status.scan_req.ap_list[i].channel; } printf("Scan for specific SSID %s\n", wifi_status.scan_req.ap_list[i].ssid); scan_ssid = (struct bwifi_ssid *)aos_malloc(sizeof(struct bwifi_ssid)); if (!scan_ssid) { printf("Failed to malloc scan ssid struct\n"); break; } memcpy(scan_ssid->ssid, wifi_status.scan_req.ap_list[i].ssid, sizeof(scan_ssid->ssid)); scan_ssid->next = NULL; if (prev_scan_ssid) prev_scan_ssid->next = scan_ssid; else scan_config.ssids = scan_ssid; prev_scan_ssid = scan_ssid; } scan_config.channels = scan_chs; ret = bwifi_config_scan(&scan_config); scan_ssid = scan_config.ssids; while (scan_ssid) { prev_scan_ssid = scan_ssid; scan_ssid = scan_ssid->next; aos_free(prev_scan_ssid); } } else { ret = bwifi_scan(); } if (ret <= 0) { printf("wifi scan fail\n"); return -1; } scan_result = (struct bwifi_bss_info *)aos_malloc(ret * sizeof(struct bwifi_bss_info)); if (!scan_result) { printf("Failed to malloc scan result buffer\n"); goto end; } ret = bwifi_get_scan_result(scan_result, ret); result.ap_num = ret; if (result.ap_list == NULL) { result.ap_list = aos_malloc(ret * sizeof(ap_list_t)); } else { result.ap_list = aos_realloc(result.ap_list, ret * sizeof(ap_list_t)); } if (!result.ap_list) { printf("Failed to malloc the returned ap list\n"); result.ap_num = 0; goto end; } for (i = 0; i < ret; i++) { struct bwifi_bss_info *r = scan_result + i; ap_list_t *res = result.ap_list + i; memcpy(res->ssid, r->ssid, sizeof(res->ssid)); res->ap_power = r->rssi; memcpy(res->bssid, r->bssid, sizeof(res->bssid)); } end: event_publish(EVENT_WIFI_SCAN_DONE, &result); if (scan_result) aos_free(scan_result); return 0; } static int haas1000_wifi_start_scan(netdev_t *dev, wifi_scan_config_t* config, bool block) { return wifi_scan(dev, config, block, SCAN_NORMAL); } static int haas1000_wifi_start_specified_scan(netdev_t *dev, ap_list_t *ap_list, int ap_num) { int i = 0; if (ap_num > 3) ap_num = 3; wifi_status.scan_req.ap_num = ap_num; while (i < ap_num) { wifi_status.scan_req.ap_list[i] = *(ap_list + i); i++; } int ret = wifi_scan(dev, NULL, false, SCAN_SPECIFIED); printf("haas start scan:%d", ret); return ret; } static int disconnect_station(netdev_t *dev) { if (wifi_status.wifi_started && wifi_status.sta_connected && !wifi_status.resetting) return bwifi_disconnect(); return 0; } static int disconnect_soft_ap(netdev_t *dev) { return 0; } static int haas1000_wifi_disconnect(netdev_t *dev) { int ret = 0; ret = disconnect_station(dev); if (wifi_status.sap_started) ret += disconnect_soft_ap(dev); return ret; } static int haas1000_wifi_cancel_connect(netdev_t *dev) { if (wifi_status.wifi_started && !wifi_status.sta_connected && !wifi_status.resetting) return bwifi_disconnect(); return -1; } static int haas1000_wifi_set_channel(netdev_t *dev, int ch) { if (WARN_ON(!wifi_status.wifi_started || wifi_status.sta_connected)) return -1; return bes_sniffer_set_channel((u8)ch); } static int haas1000_wifi_get_channel(netdev_t *dev, int* ch) { if(ch != NULL) { *ch = bwifi_get_current_channel(); return 0; } return -1; } /* Wi-Fi Smart Config */ static int wifi_sniffer_handler(unsigned short data_len, void *data) { uint8_t *frame = (uint8_t *)data; if (data == NULL) { printf("%s ldpc:%d\n", __func__, data_len); return 0; } printf("%s data:%p, len:%d\n", __func__, data, data_len); #if 0 printf(" %02x %02x %02x %02x\n", frame[0], frame[1], frame[2], frame[3]); printf(" %02x %02x %02x %02x %02x %02x\n", frame[4], frame[5], frame[6], frame[7], frame[8], frame[9]); printf(" %02x %02x %02x %02x %02x %02x\n", frame[10], frame[11], frame[12], frame[13], frame[14], frame[15]); printf(" %02x %02x %02x %02x %02x %02x\n", frame[16], frame[17], frame[18], frame[19], frame[20], frame[21]); printf(" %02x %02x\n", frame[22], frame[23]); #endif if (wifi_status.smart_config && promisc_cb) promisc_cb(frame, data_len, NULL); else if (wifi_status.zero_config && mgnt_frame_cb) { uint8_t type = frame[0] & 0xFC; if (type == PROBE_REQ) { printf("%s: probe request received!\n", __func__); mgnt_frame_cb(frame, data_len, NULL); } } return 0; } static int haas1000_wifi_start_monitor(netdev_t *dev) { if (WARN_ON(!wifi_status.wifi_started || wifi_status.sta_connected)) return -1; if (bes_sniffer_start(wifi_sniffer_handler) || bes_sniffer_set_filter(0,1,1,0,0,0,0)) return -2; wifi_status.smart_config = 1; return 0; } static int haas1000_wifi_stop_monitor(netdev_t *dev) { wifi_status.smart_config = 0; return bes_sniffer_stop(); } static void haas1000_wifi_register_monitor_cb(netdev_t *dev, monitor_data_cb_t fn) { promisc_cb = fn; } /* Wi-Fi Zero Config */ static int haas1000_wifi_start_mgnt_monitor(netdev_t *dev) { if (WARN_ON(!wifi_status.sta_connected || wifi_status.resetting)) return -1; if (bes_sniffer_start(wifi_sniffer_handler) || bes_sniffer_set_filter(1,0,0,0,0,0,0)) return -2; wifi_status.zero_config = 1; return 0; } static int haas1000_wifi_stop_mgnt_monitor(netdev_t *dev) { wifi_status.zero_config = 0; return bes_sniffer_stop(); } static void haas1000_wifi_register_mgnt_monitor_cb(netdev_t *dev, monitor_data_cb_t fn) { mgnt_frame_cb = fn; } static int haas1000_wifi_send_80211_raw_frame(netdev_t *dev, uint8_t *buf, int len) { if (WARN_ON(!wifi_status.sta_connected || wifi_status.resetting)) return -1; return bes_sniffer_send_mgmt_frame(bwifi_get_current_channel(), buf, len); } static int start_ap(netdev_t *dev, const char *ssid, const char *passwd, int interval, int hide) { #ifdef __AP_MODE__ BWIFI_SEC_TYPE_T sec; printf("start_ap ssid:%s, pwd:%s, beacon_int:%d, hidden:%d\n", ssid, passwd, interval, hide); if (!passwd || !strlen(passwd)) sec = SECURITY_NONE; else sec = SECURITY_WPA2; if (bwifi_set_softap_config(ssid, 0, hide, sec, passwd)) { printf("Softap %s config failed\n", ssid); return -1; } if (bwifi_softap_start()) { printf("Softap %s start failed\n", ssid); return -2; } printf("Softap %s start success!!\n", ssid); wifi_status.sap_started = 1; if (m->ev_cb && m->ev_cb->stat_chg) { m->ev_cb->stat_chg(m, NOTIFY_AP_UP, NULL); } #endif return 0; } static int stop_ap(netdev_t *dev) { #ifdef __AP_MODE__ printf("stop_ap\n"); bwifi_softap_stop(); wifi_status.sap_started = 0; if (m->ev_cb && m->ev_cb->stat_chg) { m->ev_cb->stat_chg(m, NOTIFY_AP_DOWN, NULL); } #endif return 0; } static wifi_driver_t haas1000_wifi_driver = { /** driver info */ .base.os = "rtos", .base.type = "solo", .base.partner = "AliOS Things Team", .base.app_net = "rtsp+rtp+rtcp", .base.project = "HAAS100", .base.cloud = "aliyun", /** common APIs */ .init = haas1000_wifi_init, .deinit = haas1000_wifi_deinit, // .set_mode = haas1000_wifi_set_mode, // .get_mode = haas1000_wifi_get_mode, /** conf APIs */ .set_mac_addr = haas1000_wifi_set_mac_addr, .get_mac_addr = haas1000_wifi_get_mac_addr, // .set_lpm = haas1000_wifi_set_lpm, // .get_lpm = haas1000_wifi_get_lpm, .notify_ip_state2drv = haas1000_wifi_notify_ip_state2drv, /** connection APIs */ .start_scan = haas1000_wifi_start_scan, .start_specified_scan = haas1000_wifi_start_specified_scan, .connect = haas1000_wifi_connect, .cancel_connect = haas1000_wifi_cancel_connect, .disconnect = haas1000_wifi_disconnect, .sta_get_link_status = haas1000_wifi_sta_get_link_status, // .ap_get_sta_list = haas1000_wifi_ap_get_sta_list, /** promiscuous APIs */ .start_monitor = haas1000_wifi_start_monitor, .stop_monitor = haas1000_wifi_stop_monitor, .send_80211_raw_frame = haas1000_wifi_send_80211_raw_frame, .set_channel = haas1000_wifi_set_channel, .get_channel = haas1000_wifi_get_channel, .register_monitor_cb = haas1000_wifi_register_monitor_cb, .start_mgnt_monitor = haas1000_wifi_start_mgnt_monitor, .stop_mgnt_monitor = haas1000_wifi_stop_mgnt_monitor, .register_mgnt_monitor_cb = haas1000_wifi_register_mgnt_monitor_cb, .set_smartcfg = NULL, }; int haas1000_wifi_register(void) { vfs_wifi_dev_register(&haas1000_wifi_driver, 0); } VFS_DRIVER_ENTRY(haas1000_wifi_register)
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/wifi_port_ref.c
C
apache-2.0
23,129
#include <errno.h> #include <stddef.h> #include <zephyr.h> #include <misc/util.h> #include <misc/byteorder.h> #include <string.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_HCI_DRIVER) #include <bluetooth/bluetooth.h> #include <bluetooth/hci.h> #include <bluetooth/hci_driver.h> #include <common/log.h> #include "aos/hal/uart.h" #include "hci_if.h" #if 0 #ifdef BT_DBG #undef BT_DBG #define BT_DBG(f, ...) printf(f"\n", ##__VA_ARGS__) #endif #ifdef BT_INFO #undef BT_INFO #define BT_INFO(f, ...) printf(f"\n", ##__VA_ARGS__) #endif #ifdef BT_WARN #undef BT_WARN #define BT_WARN(f, ...) printf(f"\n", ##__VA_ARGS__) #endif #ifdef BT_ERR #undef BT_ERR #define BT_ERR(f, ...) printf(f"\n", ##__VA_ARGS__) #endif #endif #define H4_NONE 0x00 #define H4_CMD 0x01 #define H4_ACL 0x02 #define H4_SCO 0x03 #define H4_EVT 0x04 #define HCI_SEND_BUF_SIZE BT_BUF_RX_SIZE static struct { uint8_t type; struct net_buf *buf; struct k_fifo fifo; struct k_sem send_sem; uint8_t send_buf[HCI_SEND_BUF_SIZE]; } tx; static struct { struct net_buf *buf; struct k_fifo fifo; uint16_t remaining; uint16_t discard; bool have_hdr; bool discardable; uint8_t hdr_len; uint8_t type; union { struct bt_hci_evt_hdr evt; struct bt_hci_acl_hdr acl; uint8_t hdr[4]; }; } rx; bool hci_if_open_flag; struct k_sem hci_if_open_sem; static inline void copy_hdr(struct net_buf *buf) { net_buf_add_mem(buf, rx.hdr, rx.hdr_len); } static void reset_rx(void) { rx.type = H4_NONE; rx.remaining = 0; rx.have_hdr = false; rx.hdr_len = 0; rx.discardable = false; } static int get_evt_hdr(uint8_t *data, uint16_t len) { struct bt_hci_evt_hdr *hdr = &rx.evt; rx.hdr_len = sizeof(struct bt_hci_evt_hdr); memcpy((uint8_t *)hdr, data, rx.hdr_len); if (rx.evt.evt == BT_HCI_EVT_LE_META_EVENT) { memcpy((uint8_t *)hdr + rx.hdr_len, data + rx.hdr_len, 1); rx.hdr_len++; } if (rx.evt.evt == BT_HCI_EVT_LE_META_EVENT && rx.hdr[sizeof(*hdr)] == BT_HCI_EVT_LE_ADVERTISING_REPORT) { BT_DBG("Marking adv report as discardable"); rx.discardable = true; } rx.remaining = hdr->len - (rx.hdr_len - sizeof(*hdr)); BT_DBG("Got event header. Payload %u bytes", hdr->len); rx.have_hdr = true; return rx.hdr_len; } static int get_acl_hdr(uint8_t *data, uint16_t len) { struct bt_hci_acl_hdr *hdr = &rx.acl; rx.hdr_len = sizeof(struct bt_hci_acl_hdr); memcpy((uint8_t *)hdr, data, rx.hdr_len); rx.remaining = sys_le16_to_cpu(hdr->len); BT_DBG("Got ACL header. Payload %u bytes", rx.remaining); rx.have_hdr = true; return rx.hdr_len; } static struct net_buf *get_rx(int timeout) { BT_DBG("type 0x%02x, evt 0x%02x", rx.type, rx.evt.evt); if (rx.type == H4_EVT && (rx.evt.evt == BT_HCI_EVT_CMD_COMPLETE || rx.evt.evt == BT_HCI_EVT_CMD_STATUS)) { return bt_buf_get_cmd_complete(timeout); } return bt_buf_get_rx(BT_BUF_EVT, timeout); } static int h4_receive(uint8_t *data, uint16_t len) { uint8_t *pdata = data; uint16_t length = len; bool prio; struct net_buf *buf; BT_DBG("%s", bt_hex(data, len)); if (NULL == pdata) { BT_ERR("Receive no data"); return -EINVAL; } rx.type = *pdata; pdata++; length--; switch (rx.type) { case H4_EVT: pdata += get_evt_hdr(pdata, length); break; case H4_ACL: pdata += get_acl_hdr(pdata, length); break; default: BT_ERR("Unknown H:4 type 0x%02x", rx.type); rx.type = H4_NONE; return -EINVAL; } if (!rx.buf) { rx.buf = get_rx(K_NO_WAIT); if (!rx.buf) { if (rx.discardable) { BT_WARN("Discarding event 0x%02x", rx.evt.evt); rx.discard = rx.remaining; reset_rx(); return 0; } BT_WARN("Failed to allocate, deferring to rx_thread"); return -ENOMEM; } copy_hdr(rx.buf); } net_buf_add_mem(rx.buf, pdata, rx.remaining); prio = (rx.type == H4_EVT && bt_hci_evt_is_prio(rx.evt.evt)); buf = rx.buf; rx.buf = NULL; if (rx.type == H4_EVT) { bt_buf_set_type(buf, BT_BUF_EVT); } else { bt_buf_set_type(buf, BT_BUF_ACL_IN); } reset_rx(); if (prio) { BT_DBG("Calling bt_recv_prio(%p)", buf); bt_recv_prio(buf); } else { BT_DBG("Calling bt_recv(%p)", buf); bt_recv(buf); } return 0; } static bool hci_tp_tx_callback(void) { BT_DBG("hci send complete callback"); memset(tx.send_buf, 0, HCI_SEND_BUF_SIZE); k_sem_give(&tx.send_sem); } static inline void process_tx(void) { int bytes; int32_t ret; if (!tx.buf) { tx.buf = net_buf_get(&tx.fifo, K_NO_WAIT); if (!tx.buf) { BT_ERR("TX interrupt but no pending buffer!"); return; } } if (!tx.type) { switch (bt_buf_get_type(tx.buf)) { case BT_BUF_ACL_OUT: tx.type = H4_ACL; break; case BT_BUF_CMD: tx.type = H4_CMD; break; default: BT_ERR("Unknown buffer type"); goto done; } } BT_DBG("write type %d, data %s", tx.type, bt_hex(tx.buf->data, tx.buf->len)); bytes = tx.buf->len; memcpy(tx.send_buf, &tx.type, 1); memcpy(tx.send_buf + 1, tx.buf->data, bytes); ret = hci_tp_send(tx.send_buf, bytes + 1, hci_tp_tx_callback); if (ret != true) { BT_ERR("Failed to send data"); } net_buf_pull(tx.buf, bytes); if (tx.buf->len) { return; } done: tx.type = H4_NONE; net_buf_unref(tx.buf); tx.buf = net_buf_get(&tx.fifo, K_NO_WAIT); } static int h4_send(struct net_buf *buf) { int ret; ret = k_sem_take(&tx.send_sem, K_FOREVER); if (ret == 0) { BT_DBG("buf %p type %u len %u", buf, bt_buf_get_type(buf), buf->len); net_buf_put(&tx.fifo, buf); process_tx(); } else { BT_ERR("Take tx.send_sem error! ret = 0x%x", ret); } return ret; } #if 1 static bool hci_if_callback(T_HCI_IF_EVT evt, bool status, uint8_t *p_buf, uint32_t len) { if (evt == HCI_IF_EVT_OPENED) { if (status == true) { BT_DBG("hci_if_open success"); } else { BT_DBG("hci_if_open fail"); } hci_if_open_flag = status; k_sem_give(&hci_if_open_sem); } else if (evt == HCI_IF_EVT_DATA_IND) { BT_DBG("hci indicate to host"); h4_receive(p_buf, len); } else { BT_ERR("Other event enter hci_if_callback! evt = 0x%x, status = 0x%x", evt, status); } } #endif static int h4_open(void) { int ret; hci_if_open_flag = false; ret = k_sem_init(&hci_if_open_sem, 0, 1); if (ret != 0) { BT_ERR("Init hci_if_open_sem error! ret = 0x%x", ret); return ret; } hci_if_open(hci_if_callback); ret = k_sem_take(&hci_if_open_sem, K_FOREVER); if (ret == 0) { if (hci_if_open_flag == true) { memset(tx.send_buf, 0, HCI_SEND_BUF_SIZE); k_fifo_init(&tx.fifo); ret = k_sem_init(&tx.send_sem, 1, 1); if (ret != 0) { BT_ERR("Init tx.send_sem error! ret = 0x%x", ret); } } else { ret = 1; } } else { BT_ERR("Take hci_if_open_sem error! ret = 0x%x", ret); } k_sem_delete(&hci_if_open_sem); return ret; } static struct bt_hci_driver drv = { .name = "H:4", .bus = BT_HCI_DRIVER_BUS_UART, .open = h4_open, .send = h4_send, }; int hci_driver_init() { BT_INFO(""); bt_hci_driver_register(&drv); return 0; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hci_driver/hci_driver.c
C
apache-2.0
7,993
import sys, hashlib, os import struct # changed by yanxiaoyong.yxy # https://blog.csdn.net/qq_43192819/article/details/108981008 # https://blog.csdn.net/whatday/article/details/107769032 def MD5(input): md5 = hashlib.md5() md5.update(input) return bytes.fromhex(md5.hexdigest()) #return md5.hexdigest().decode('hex') input_bin = sys.argv[1] ota_bin = sys.argv[3] version = int(sys.argv[2], 16) b = struct.pack('<L', version) filelen = os.path.getsize(input_bin) sum = 0 i=0 with open(input_bin, 'rb') as file: ota_md5_bytes = MD5(file.read()) output = open(ota_bin, 'wb') output.write(b) b = struct.pack('<L', 0x01) output.write(b) #output.write("OTA1") output.write("OTA1".encode()) b = struct.pack('<L', 0x18) output.write(b) input = open(input_bin, 'rb') for i in range(filelen): data = input.read(1) sum += struct.unpack("B", data)[0] input.close b = struct.pack('<L', sum) #CRC output.write(b) b = struct.pack('<L', filelen) output.write(b) b = struct.pack('<L', 0x20) output.write(b) b = struct.pack('<L', 0) output.write(b) input = open(input_bin, 'rb') output.write(input.read()) input.close() output.close()
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/ota.py
Python
apache-2.0
1,150
# Date : 2019/03/08 # Author : Snow Yang # Mail : yangsw@mxchip.com import os import sys image_file = sys.argv[1] size = os.path.getsize(image_file) pad_size = (((size - 1) >> 12) + 1) << 12 open(image_file, 'ab').write(b'\xFF'*(pad_size - size))
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/pad.py
Python
apache-2.0
256
#!/bin/bash ################ # Library ################ Usage() { echo "Usage: $0 [Image Name]" } ################ # Main ################ if [ "$#" -lt 1 ]; then Usage exit 1 fi # Get Parameters IMAGE_FILENAME=$1 filesize=$(stat -c "%s" $IMAGE_FILENAME) newsize=$((((($filesize - 1) >> 12) + 1) << 12)) padcount=$(($newsize - $filesize)) for (( i=$padcount; i > 0; i-- )) do echo -n -e "\xFF" >> $IMAGE_FILENAME done
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/pad.sh
Shell
apache-2.0
436
# Date : 2019/03/08 # Author : Snow Yang # Mail : yangsw@mxchip.com import re import os import sys from struct import pack image_file = sys.argv[1] section_start_name = sys.argv[2] symbol_list_file = sys.argv[3] size = os.path.getsize(image_file) addr = int('0x'+re.search(r"\n(\w+) (\w+) "+section_start_name, open(symbol_list_file).read()).group(1), 16) header = b'81958711' + pack('<L', size) + pack('<L', addr) + b'\xFF'*16 open(image_file.replace('.bin', '_prepend.bin'), 'wb').write(header + open(image_file, 'rb').read())
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/prepend_header.py
Python
apache-2.0
540
#!/bin/bash ################ # Library ################ Usage() { echo "Usage: $0 [Image Name] [Start Symbol Name] [Symbols List File]" } # Parameter: # value, width, dest function MakeFixedWidthHeaderString() { local __value=$1 local __width=$2 local __dest=$3 local __reorder=$4 local __header_raw local __header_raw_reorder local __header_array if [[ "$__dest" ]]; then __header_raw=$(printf "%0""$__width""x" $__value) # echo $__header_raw if [ "$__reorder" -eq 1 ]; then # 20000680 to 80060020 for (( i=$__width; i > 0; i-=2 )) do __header_raw_reorder+=$(echo ${__header_raw:(i-2):2}) done else __header_raw_reorder=$__header_raw fi #echo $__header_raw_reorder __header_array=($(echo $__header_raw_reorder | sed 's/\(.\)/\1 /g')) for (( i=0; i < $__width; i+=2)) do eval $__dest+='\\x'"${__header_array[$i]}${__header_array[$i+1]}" done fi } ################ # Main ################ if [ "$#" -lt 3 ]; then Usage exit 1 fi # Get Parameters IMAGE_FILENAME=$1 IMAGE_SECTION_START_NAME=$2 SYMBOL_LIST=$3 # Constant Variables PATTERN_1=0x99999696 PATTERN_2=0x3FCC66FC RSVD=0xFFFFFFFFFFFFFFFF IMG2SIGN=0x3831393538373131 IMAGE_LEN=$(du -b $IMAGE_FILENAME | cut -f 1) IMAGE_ADDR="0x$(grep $IMAGE_SECTION_START_NAME $SYMBOL_LIST | awk '{print $1}')" IMAGE_FILENAME_PREPEND="${IMAGE_FILENAME%.*}"'_prepend.'"${IMAGE_FILENAME##*.}" IMAGE_FILENAME_NEW=$(basename $IMAGE_FILENAME) HEADER_FINAL='' if [ "$IMAGE_FILENAME_NEW" == "ram_1.bin" ]; then MakeFixedWidthHeaderString $PATTERN_1 8 HEADER_FINAL 0 MakeFixedWidthHeaderString $PATTERN_2 8 HEADER_FINAL 0 elif [ "$IMAGE_FILENAME_NEW" == "xip_boot.bin" ]; then MakeFixedWidthHeaderString $PATTERN_1 8 HEADER_FINAL 0 MakeFixedWidthHeaderString $PATTERN_2 8 HEADER_FINAL 0 else MakeFixedWidthHeaderString $IMG2SIGN 16 HEADER_FINAL 0 fi MakeFixedWidthHeaderString $IMAGE_LEN 8 HEADER_FINAL 1 MakeFixedWidthHeaderString $IMAGE_ADDR 8 HEADER_FINAL 1 MakeFixedWidthHeaderString $RSVD 16 HEADER_FINAL 0 MakeFixedWidthHeaderString $RSVD 16 HEADER_FINAL 0 # echo $HEADER_FINAL echo -n -e $HEADER_FINAL | cat - $IMAGE_FILENAME > $IMAGE_FILENAME_PREPEND
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/prepend_header.sh
Shell
apache-2.0
2,395
#!/usr/bin/env python import os, sys, re, time, json from flash_program_ll import burn_bin_files try: import serial from serial.tools import miniterm except: print("\nNot found pyserial, please install it by: \nsudo python%d -m pip install pyserial" % (sys.version_info.major)) sys.exit(-1) #force to ymodem_burn.bin def get_bin_file(): """ get binary file from sys.argv --bin=/xxx/yyy/zzz.bin """ bin_files = [] pattern = re.compile(r'--(.*)=(.*)') for arg in sys.argv[1:]: if arg.startswith("--"): match = pattern.match(arg) if match: key = match.group(1) value = match.group(2) if key == 'bin': bin_files.append(value) return bin_files def read_json(json_file): data = None if os.path.isfile(json_file): with open(json_file, 'r') as f: data = json.load(f) return data def write_json(json_file, data): with open(json_file, 'w') as f: f.write(json.dumps(data, indent=4, separators=(',', ': '))) def get_config(): """ get configuration from .config_burn file, if it is not existed, generate default configuration of chip_rtl8721d """ configs = {} config_file = os.path.join(os.getcwd(), '.config_burn') if os.path.isfile(config_file): configs = read_json(config_file) if not configs: configs = {} if 'chip_rtl8721d' not in configs: configs['chip_rtl8721d'] = {} if 'serialport' not in configs['chip_rtl8721d']: configs['chip_rtl8721d']['serialport'] = "" if 'baudrate' not in configs['chip_rtl8721d']: configs['chip_rtl8721d']['baudrate'] = "115200" if 'binfile' not in configs['chip_rtl8721d']: configs['chip_rtl8721d']['binfile'] = [] return configs['chip_rtl8721d'] def save_config(config): """ save configuration to .config_burn file, only update chip_rtl8721d portion """ if config: configs = {} config_file = os.path.join(os.getcwd(), '.config_burn') if os.path.isfile(config_file): configs = read_json(config_file) if not configs: configs = {} configs['chip_rtl8721d'] = config write_json(config_file, configs) def check_uart(portnum, baudrate): serialport = serial.Serial() serialport.port = portnum serialport.baudrate = baudrate serialport.parity = "N" serialport.bytesize = 8 serialport.stopbits = 1 serialport.timeout = 1 try: serialport.open() except Exception as e: print("check_uart open serialport: %s error " % portnum) return False serialport.close() return True def main(): # step 1: get binary file needsave = False myconfig = get_config() bin_files = get_bin_file() if bin_files: myconfig["binfile"] = bin_files needsave = True if not myconfig["binfile"]: print("no specified binary file") return print("binary file is %s" % myconfig["binfile"]) # step 2: get serial port if not myconfig["serialport"]: myconfig["serialport"] = miniterm.ask_for_port() if not myconfig["serialport"]: print("no specified serial port") return else: needsave = True while check_uart(myconfig["serialport"], myconfig['baudrate']) == False: myconfig["serialport"] = miniterm.ask_for_port() print("serial port is %s" % myconfig["serialport"]) print("the settings were restored in the file %s" % os.path.join(os.getcwd(), '.config_burn')) # step 3: burn binary file into flash bin_files = [] for bin_file in myconfig["binfile"]: filename = bin_file address = "0" if "#" in bin_file: filename = bin_file.split("#", 1)[0] address = bin_file.split("#", 1)[1] if address == "0" or address == "0x0" or address == "0x00": bin_files.append((os.path.join(os.getcwd(), 'binary/ymodem_burn_xz.bin'), address)) else: bin_files.append((filename, address)) print("bin_files is ", bin_files) burn_bin_files(myconfig["serialport"], myconfig['baudrate'], bin_files) if needsave: save_config(myconfig) if __name__ == "__main__": main()
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/release/aos_burn_tool/flash_program.py
Python
apache-2.0
4,348
#!/usr/bin/env python import os, sys, re, time from ymodem import YModem try: import serial from serial.tools import miniterm except: print("\nNot found pyserial, please install it by: \nsudo python%d -m pip install pyserial" % (sys.version_info.major)) sys.exit(-1) def match_and_send(serialport, pattern, command, timeout): """ receive serial data, and check it with pattern """ pattern = re.compile(pattern) start = time.time() while (time.time() - start) < timeout: #line = serialport.readline() #timeout dont work for 'readline', so using 'read_until' instead line = serialport.read_until(b'\n') if len(line) == 0: continue match = pattern.search(line) if match: if command: serialport.write(command) print(line.decode('UTF-8',errors='ignore')) sys.stdout.flush() return match print(line.decode('UTF-8',errors='ignore')) sys.stdout.flush() return None def send_and_match(serialport, command, pattern, timeout): """ receive serial data, and check it with pattern """ if command: serialport.write(command) if pattern == b'': #only send sys.stdout.flush() return None pattern = re.compile(pattern) start = time.time() while (time.time() - start) < timeout: #line = serialport.readline() #timeout dont work for 'readline', so using 'read_until' instead line = serialport.read_until(b'\n') if len(line) == 0: continue print(line.decode('UTF-8',errors='ignore')) sys.stdout.flush() match = pattern.search(line) if match: return match return None #burn file in 2_boot def burn_bin_file(serialport, filename, address): if not os.path.exists(filename): print("[ScriptPrint] File \"%s\" is not existed." % filename) return False #get address if address == "0" or address == "0x0" or address == "0x00": # get flash address match = send_and_match(serialport, b'5', b'Backup part addr:([0-9a-fxA-F]*)', 5) if not match: print("[ScriptPrint] Can not get flash address") return False address = match.group(1) else: send_and_match(serialport, b'6', b'', 0) address = address.encode() # set flash address match = send_and_match(serialport, address + b'\r\n', b'CCCC', 30) if not match: print("[ScriptPrint] Can not enter ymodem mode") return False # send binary file def sender_getc(size): return serialport.read(size) or None def sender_putc(data, timeout=15): return serialport.write(data) sender = YModem(sender_getc, sender_putc) sent = sender.send_file(filename) return True def burn_bin_files(portnum, baudrate, bin_files): # open serial port serialport = serial.Serial() serialport.port = portnum serialport.baudrate = baudrate serialport.parity = "N" serialport.bytesize = 8 serialport.stopbits = 1 serialport.timeout = 1 try: serialport.open() except Exception as e: raise Exception("[ScriptPrint] Failed to open serial port: %s!" % portnum) print("[ScriptPrint] Try to reboot...") # 重启单板并确保进入2nd-boot for i in range(10): match = send_and_match(serialport, b'\n', b'\(ash', 2) if match: # 如果在cli模式,通过reboot重启系统 print("[ScriptPrint] Reboot from CLI") send_and_match(serialport, b'reboot\n', b'', 0) match = match_and_send(serialport, b'2ndboot cli menu', b'w', 5) if match: print("[ScriptPrint] check if in boot") match = send_and_match(serialport, b'\n', b'aos boot', 2) if match: # 进入boot模式,退出 break match = send_and_match(serialport, b'\n', b'aos boot', 2) if match: # 如果在boot模式,通过2重启系统 print("[ScriptPrint] Reboot from 2nd-boot") send_and_match(serialport, b'2\n', b'', 0) match = match_and_send(serialport, b'2ndboot cli menu', b'w', 5) if match: print("[ScriptPrint] check if in boot") match = send_and_match(serialport, b'\n', b'aos boot', 2) if match: # 进入boot模式,退出 break match = match_and_send(serialport, b'2ndboot cli menu', b'w', 2) if match: print("[ScriptPrint] check if in boot") match = send_and_match(serialport, b'\n', b'aos boot', 2) if match: # 进入boot模式,退出 break else: # 一些solution需要先退出命令行模式回到CLI print("[ScriptPrint] change to CLI mode") send_and_match(serialport, b'\n\x03', b'', 0) #ctrl-C, ETX, 本文结束 send_and_match(serialport, b'\n\x04', b'', 0) #ctrl-D, EOT, 传输结束 time.sleep(1) if i >= 9 : print("[ScriptPrint] reboot fail") print("[ScriptPrint] Please connect the serial port of the board to the PC, then reset the board"); # close serial port serialport.close() return False # boot中下载文件 print("[ScriptPrint] Downloading files...") for bin_file in bin_files: if not burn_bin_file(serialport, bin_file[0], bin_file[1]): print("[ScriptPrint] Download file %s failed." % bin_file[0]) serialport.close() return False # switch partition print("[ScriptPrint] Swap AB partition") send_and_match(serialport, b'3\n', b'', 0) time.sleep(0.5) send_and_match(serialport, b'4\n', b'', 0) time.sleep(0.5) send_and_match(serialport, b'3\n', b'', 0) time.sleep(0.5) send_and_match(serialport, b'2\n', b'', 0) time.sleep(0.1) # workaround retry issue in 2nd boot match = send_and_match(serialport, b'\n'*16, b'ota update complete',100) if match: print("[ScriptPrint] Burn \"%s\" success." % bin_files) # close serial port serialport.close() if match: return True else: return False def main(): length = len(sys.argv) if (length < 5) or (length % 2 == 0): print("Usage demo: ./flash_program_ll.py COM6 1500000 sendfile flash_addr\n") return 1 serialport = sys.argv[1] baudrate = sys.argv[2] bin_files = [] for i in range(3, length, 2): filename = sys.argv[i] address = sys.argv[i + 1] bin_files.append((filename, address)) ret = burn_bin_files(serialport, baudrate, bin_files) sys.exit(ret) if __name__ == "__main__": main()
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/release/aos_burn_tool/flash_program_ll.py
Python
apache-2.0
6,932
#! /usr/bin/env python # -*- coding: utf-8 -*- """ MIT License Copyright (c) 2018 Alex Woo Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import print_function import os, sys, math, time, string, struct # ymodem data header byte SOH = b'\x01' STX = b'\x02' EOT = b'\x04' ACK = b'\x06' NAK = b'\x15' CAN = b'\x18' CRC = b'C' class SendTask(object): def __init__(self): self._task_name = "" self._task_size = 0 self._task_packets = 0 self._last_valid_packets_size = 0 self._sent_packets = 0 self._missing_sent_packets = 0 self._valid_sent_packets = 0 self._valid_sent_bytes = 0 def inc_sent_packets(self): self._sent_packets += 1 def inc_missing_sent_packets(self): self._missing_sent_packets += 1 def inc_valid_sent_packets(self): self._valid_sent_packets += 1 def add_valid_sent_bytes(self, this_valid_sent_bytes): self._valid_sent_bytes += this_valid_sent_bytes def get_valid_sent_packets(self): return self._valid_sent_packets def get_valid_sent_bytes(self): return self._valid_sent_bytes def set_task_name(self, data_name): self._task_name = data_name def set_task_size(self, data_size): self._task_size = data_size self._task_packets = math.ceil(data_size / 128) self._last_valid_packets_size = data_size % 128 class ReceiveTask(object): def __init__(self): self._task_name = "" self._task_size = 0 self._task_packets = 0 self._last_valid_packets_size = 0 self._received_packets = 0 self._missing_received_packets = 0 self._valid_received_packets = 0 self._valid_received_bytes = 0 def inc_received_packets(self): self._received_packets += 1 def inc_missing_received_packets(self): self._missing_received_packets += 1 def inc_valid_received_packets(self): self._valid_received_packets += 1 def add_valid_received_bytes(self, this_valid_received_bytes): self._valid_received_bytes += this_valid_received_bytes def get_task_packets(self): return self._task_packets def get_last_valid_packet_size(self): return self._last_valid_packets_size def get_valid_received_packets(self): return self._valid_received_packets def get_valid_received_bytes(self): return self._valid_received_bytes def set_task_name(self, data_name): self._task_name = data_name def set_task_size(self, data_size): self._task_size = data_size self._task_packets = math.ceil(data_size / 128) self._last_valid_packets_size = data_size % 128 def get_task_name(self): return self._task_name def get_task_size(self): return self._task_size class YModem(object): def __init__(self, getc, putc, header_pad=b'\x00', data_pad=b'\x1a'): self.getc = getc self.putc = putc self.st = SendTask() self.rt = ReceiveTask() self.header_pad = header_pad self.data_pad = data_pad def abort(self, count=2): for _ in range(count): self.putc(CAN) def send_file(self, file_path, retry=20, callback=None): try: file_stream = open(file_path, 'rb') file_name = os.path.basename(file_path) file_size = os.path.getsize(file_path) file_sent = self.send(file_stream, file_name, file_size, retry, callback) except IOError as e: print(str(e)) finally: file_stream.close() print("File: " + file_name) print("Size: " + str(file_sent) + "Bytes") return file_sent def wait_for_next(self, ch, timeout=60): cancel_count = 0 tic = time.time() while True: c = self.getc(1) if c: if c == ch: print("<<< " + hex(ord(ch))) break elif c == CAN: if cancel_count == 2: return -1 else: cancel_count += 1 else: print("Expected " + hex(ord(ch)) + ", but got " + hex(ord(c))) if (time.time() - tic) >= timeout: return -2 return 0 def send(self, data_stream, data_name, data_size, retry=20, callback=None): packet_size = 128 # [<<< CRC] self.wait_for_next(CRC) # [first packet >>>] header = self._make_edge_packet_header() if len(data_name) > 100: data_name = data_name[:100] self.st.set_task_name(data_name) data_name += bytes.decode(self.header_pad) data_size = str(data_size) if len(data_size) > 20: raise Exception("Data volume is too large!") self.st.set_task_size(int(data_size)) data_size += bytes.decode(self.header_pad) data = data_name + data_size data = data.ljust(128, bytes.decode(self.header_pad)) checksum = self._make_send_checksum(data) data_for_send = header + data.encode() + checksum ''' print("2checksum=") print(data_for_send.hex()) print("2len %d\r\n" % len(data_for_send)) ''' self.putc(data_for_send) self.st.inc_sent_packets() # data_in_hexstring = "".join("%02x" % b for b in data_for_send) print("Packet 0 >>>") # [<<< ACK] # [<<< CRC] self.wait_for_next(ACK) self.wait_for_next(CRC) # [data packet >>>] # [<<< ACK] error_count = 0 sequence = 1 sequence_int = 1 print("file size: " + str(self.st._task_packets/8) + " KB") while True: data = data_stream.read(packet_size) if not data: print('\nEOF') break extracted_data_bytes = len(data) if extracted_data_bytes <= 128: packet_size = 128 header = self._make_data_packet_header(packet_size, sequence) data = data.ljust(packet_size, self.data_pad) checksum = self._make_send_checksum(data) data_for_send = header + data + checksum ''' print("3checksum=") print(data_for_send.hex()) print("3len= %d\r\n" % len(data_for_send)) ''' # data_in_hexstring = "".join("%02x" % b for b in data_for_send) while True: self.putc(data_for_send) self.st.inc_sent_packets() print("\rPacket " + str(sequence_int) + " / " + str(self.st._task_packets) + " >>> ", end='') c = self.getc(1) if c == ACK: print("<<< ACK", end='') self.st.inc_valid_sent_packets() self.st.add_valid_sent_bytes(extracted_data_bytes) error_count = 0 break else: error_count += 1 self.st.inc_missing_sent_packets() print("RETRY " + str(error_count)) if error_count > retry: self.abort() print('send error: NAK received %d , aborting' % retry) return -2 sequence = (sequence + 1) % 0x100 sequence_int = sequence_int + 1 # [EOT >>>] # [<<< NAK] # [EOT >>>] # [<<< ACK] # workaround retry issue in 2nd boot for i in range(20): self.putc(EOT) print(">>> EOT") if self.wait_for_next(NAK, 0.5) != -2: break print("to receive NAK timeout. retry...") self.putc(EOT) print(">>> EOT") self.wait_for_next(ACK) # [<<< CRC] self.wait_for_next(CRC) # [Final packet >>>] header = self._make_edge_packet_header() if sys.version_info.major == 2: data = bytes.decode("").ljust(128, bytes.decode(self.header_pad)) else: data = "".ljust(128, bytes.decode(self.header_pad)) checksum = self._make_send_checksum(data) data_for_send = header + data.encode() + checksum ''' print("1checksum=") print(data_for_send.hex()) print("3len=%d\r\n" % len(data_for_send)) ''' self.putc(data_for_send) self.st.inc_sent_packets() print("Packet End >>>") self.wait_for_next(ACK) return self.st.get_valid_sent_bytes() def wait_for_header(self): cancel_count = 0 while True: c = self.getc(1) if c: if c == SOH or c == STX: return c elif c == CAN: if cancel_count == 2: return -1 else: cancel_count += 1 else: print("Expected 0x01(SOH)/0x02(STX)/0x18(CAN), but got " + hex(ord(c))) def wait_for_eot(self): eot_count = 0 while True: c = self.getc(1) if c: if c == EOT: eot_count += 1 if eot_count == 1: print("EOT >>>") self.putc(NAK) print("<<< NAK") elif eot_count == 2: print("EOT >>>") self.putc(ACK) print("<<< ACK") self.putc(CRC) print("<<< CRC") break else: print("Expected 0x04(EOT), but got " + hex(ord(c))) def recv_file(self, root_path, callback=None): while True: self.putc(CRC) print("<<< CRC") c = self.getc(1) if c: if c == SOH: packet_size = 128 break elif c == STX: packet_size = 1024 break else: print("Expected 0x01(SOH)/0x02(STX)/0x18(CAN), but got " + hex(ord(c))) IS_FIRST_PACKET = True FIRST_PACKET_RECEIVED = False WAIT_FOR_EOT = False WAIT_FOR_END_PACKET = False sequence = 0 sequence_int = 0 while True: if WAIT_FOR_EOT: self.wait_for_eot() WAIT_FOR_EOT = False WAIT_FOR_END_PACKET = True sequence = 0 sequence_int = 0 else: if IS_FIRST_PACKET: IS_FIRST_PACKET = False else: c = self.wait_for_header() if c == SOH: packet_size = 128 elif c == STX: packet_size = 1024 else: return c seq = self.getc(1) if seq is None: seq_oc = None else: seq = ord(seq) c = self.getc(1) if c is not None: seq_oc = 0xFF - ord(c) data = self.getc(packet_size + 2) if not (seq == seq_oc == sequence): continue else: valid, _ = self._verify_recv_checksum(data) if valid: # first packet # [<<< ACK] # [<<< CRC] if seq == 0 and not FIRST_PACKET_RECEIVED and not WAIT_FOR_END_PACKET: print("Packet 0 >>>") self.putc(ACK) print("<<< ACK") self.putc(CRC) print("<<< CRC") file_name_bytes, data_size_bytes = (data[:-2]).rstrip(self.header_pad).split(self.header_pad) file_name = bytes.decode(file_name_bytes) data_size = bytes.decode(data_size_bytes) print("TASK: " + file_name + " " + data_size + "Bytes") self.rt.set_task_name(file_name) self.rt.set_task_size(int(data_size)) file_stream = open(os.path.join(root_path, file_name), 'wb+') FIRST_PACKET_RECEIVED = True sequence = (sequence + 1) % 0x100 sequence_int = sequence_int + 1 # data packet # [data packet >>>] # [<<< ACK] elif not WAIT_FOR_END_PACKET: self.rt.inc_valid_received_packets() print("\rPacket " + str(sequence_int) + " >>> ", end='') valid_data = data[:-2] # last data packet if self.rt.get_valid_received_packets() == self.rt.get_task_packets(): valid_data = valid_data[:self.rt.get_last_valid_packet_size()] WAIT_FOR_EOT = True self.rt.add_valid_received_bytes(len(valid_data)) file_stream.write(valid_data) self.putc(ACK) print("<<< ACK", end='') sequence = (sequence + 1) % 0x100 sequence_int = sequence_int + 1 # final packet # [<<< ACK] else: print("Packet End >>>") self.putc(ACK) print("<<< ACK") break file_stream.close() print("File: " + self.rt.get_task_name()) print("Size: " + str(self.rt.get_task_size()) + "Bytes") return self.rt.get_valid_received_bytes() # Header byte def _make_edge_packet_header(self): _bytes = [ord(SOH), 0, 0xff] return bytearray(_bytes) def _make_data_packet_header(self, packet_size, sequence): assert packet_size in (128, 1024), packet_size _bytes = [] if packet_size == 128: _bytes.append(ord(SOH)) elif packet_size == 1024: _bytes.append(ord(STX)) _bytes.extend([sequence, 0xff - sequence]) return bytearray(_bytes) # Make check code def _make_send_checksum(self, data): _bytes = [] crc = self.calc_crc(data) _bytes.extend([crc >> 8, crc & 0xff]) return bytearray(_bytes) def _verify_recv_checksum(self, data): _checksum = bytearray(data[-2:]) their_sum = (_checksum[0] << 8) + _checksum[1] data = data[:-2] our_sum = self.calc_crc(data) valid = bool(their_sum == our_sum) return valid, data # For CRC algorithm crctable = [ 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0, ] # CRC algorithm: CCITT-0 def calc_crc(self, data, crc=0): if sys.version_info.major == 2: ba = struct.unpack("@%dB" % len(data), data) else: if isinstance(data, str): ba = bytearray(data, 'utf-8') else: ba = bytearray(data) for char in ba: crctbl_idx = ((crc >> 8) ^ char) & 0xff crc = ((crc << 8) ^ self.crctable[crctbl_idx]) & 0xffff return crc & 0xffff
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/release/aos_burn_tool/ymodem.py
Python
apache-2.0
19,170
#! /usr/bin/env python import os import platform import argparse import sys import shutil print(sys.argv) parser = argparse.ArgumentParser() parser.add_argument('--target', dest='target', action='store') args = parser.parse_args() mypath = os.path.dirname(sys.argv[0]) os.chdir(mypath) print(os.getcwd()) target = args.target cur_os = platform.system() arch = platform.architecture() path = '' magic = '0xefefefef' if cur_os == 'Linux': if '64bit' in arch: path = 'linux64' else: path = 'linux32' elif cur_os == 'Darwin': path = 'osx' elif cur_os == 'Windows': path = 'win32' if path: path = os.path.join("tools", path, "xz") # dm relative, clean. target_path = os.path.join("../..", "prebuild/data/app") cmd_str = "rm -rf \"%s\"" % (target_path) if os.path.exists(target_path): os.system(cmd_str) target_path = os.path.join("../..", "prebuild/data/dylib") cmd_str = "rm -rf \"%s\"" % (target_path) if os.path.exists(target_path): os.system(cmd_str) # dm relative, copy target_path = os.path.join("../..", "prebuild/data") source_path = os.path.join(os.path.dirname(target),"../aos_sdk/app") cmd_str = "cp -rf \"%s\" \"%s\"" % (source_path, target_path) if os.path.exists(source_path) and os.path.exists(target_path): os.system(cmd_str) target_path = os.path.join("../..", "prebuild/data") source_path = os.path.join(os.path.dirname(target),"../aos_sdk/dylib") cmd_str = "cp -rf \"%s\" \"%s\"" % (source_path, target_path) if os.path.exists(source_path) and os.path.exists(target_path): os.system(cmd_str) hw_module = 0 cmd_str = "python genbin.py %d \"%s\"" % (hw_module, target) os.system(cmd_str) bin_path = os.path.join("..", "write_flash_gui", "ota_bin") shutil.copy(os.path.join(bin_path, "ota_rtos.bin"), os.path.join(bin_path, "ota_rtos_ota_all.bin")) shutil.copy(os.path.join(bin_path, "ota_rtos.bin"), os.path.join(bin_path, "ota_rtos_ota_xz.bin")) cmd_str = "dd if=stupid.bin of=%s bs=1 count=8 conv=notrunc" % (os.path.join(bin_path, "ota_rtos_ota_all.bin")) os.system(cmd_str) cmd_str = "\"%s\" -f --lzma2=dict=32KiB --check=crc32 -k %s" % (os.path.abspath(path), os.path.join(bin_path, "ota_rtos_ota_xz.bin")) os.system(cmd_str) cmd_str = "python ota_gen_md5_bin.py \"%s\" -m %s" % (os.path.join(bin_path, "ota_rtos_ota_all.bin"), magic) os.system(cmd_str) cmd_str = "python ota_gen_md5_bin.py \"%s\" -m %s" % (os.path.join(bin_path, "ota_rtos_ota_xz.bin.xz"), magic) os.system(cmd_str) print("run external script success")
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/release/auto_build_tool/build_bin.py
Python
apache-2.0
2,500
#!/usr/bin/python # -*- coding: utf-8 -*- #本文件用于适配python3.x版本,在3.7.3版本下测试通过。其他版本未测试。 #修改本文件的目的是解决3.x版本下,使用aos make命令编译固件时发生的两个错误 #第一个错误是“missing parentheses in call to 'print'” #第二个错误是“module ‘string’ has no attribute 'find'" #花生,2020年10月6日 import os import sys #import struct import time #import yaml import string import subprocess #from time import strftime,gmtime import os,os.path import zipfile import platform import shutil import glob osstr = platform.system() def pack_dir(zip_dir,zip_file): filelist = [] if os.path.isfile(zip_dir): filelist.append(zip_dir) else : filelist = os.listdir(zip_dir) zf = zipfile.ZipFile(zip_file, "w", zipfile.zlib.DEFLATED) print('zip file') for file in filelist: #print arcname print(zip_dir + '/' + file) zf.write(file) zf.close() flag = sys.argv[1] f_cfg = open('haas_genbin_config.yaml') output_dir = sys.argv[2] cfg_dict = {} print("%s" % output_dir) dict1_name_list = [] dict2_name_list = [] num_of_first_items = -1 num_of_second_items = -1 is_list = False file_num = -1 sign_file_tmp = [] while True: line = f_cfg.readline() if not line: break arry_parm = line.split('-', 1 ) if len(arry_parm) == 2: is_list = True else : arry_parm = line.split(':', 1 ) is_list = False para_key = '' para_val = '' if len(arry_parm) == 2: para_key = arry_parm[0] para_val = arry_parm[1] if para_key[0:1].isspace() == False: num_of_first_items = num_of_first_items + 1 if para_val != '\r\n' and para_val != '\n': #花生,2020年10月6日17:32:39,下面的语句,原版本是print "format wrong",要想在3.x版本支持,需要加括号。 #否则会提示"missing parentheses in call to print"错误。下面若干个print也是相同处理方式 break dict1_name_list.append(para_key); cfg_dict[dict1_name_list[num_of_first_items]] = {} if dict1_name_list[num_of_first_items] == 'SIGN_FILE_LIST': cfg_dict[dict1_name_list[num_of_first_items]] = [] else: cfg_tmp = cfg_dict[dict1_name_list[num_of_first_items]] if dict1_name_list[num_of_first_items] == 'SIGN_FILE_LIST': if is_list == True and para_val.strip()[-1:] == ':': file_num = file_num + 1 cfg_tmp.append({}) continue if para_key.strip() == 'SWITCH': cfg_tmp[file_num][para_key.strip()] = para_val.strip() continue # print para_key.strip() # print para_val.strip()[1:-1] cfg_tmp[file_num][para_key.strip()] = para_val.strip()[1:-1] continue if para_val == '\r\n' or para_val == '\n': is_list = True num_of_second_items = num_of_second_items + 1 dict2_name_list.append(para_key[2:]) cfg_tmp[dict2_name_list[num_of_second_items]] = [] #print cfg_dict continue if is_list == True & para_key[:3].isspace() == True : if para_val[0].isspace() == True: cfg_tmp[dict2_name_list[num_of_second_items]].append(para_val.strip()[1:-1]) #print cfg_dict continue #花生,2020年10月6日17:30:53,str在原版本是string,在2.x版本中是可以的,但是3.x版本中,string没有find属性 if str.find(para_key,'SWITCH') != -1: cfg_tmp[para_key[2:]] = para_val.strip() continue cfg_tmp[para_key[2:]] = para_val.strip()[1:-1] #print cfg_tmp #print cfg_dict f_cfg.close() # BES_KEY dict_bes_key = cfg_dict['BES_KEY'] in_key_dir = dict_bes_key['IN_KEY_DIR'] out_key_dir = dict_bes_key['OUT_KEY_DIR'] pub_key_name = dict_bes_key['PUB_KEY_NAME'] pri_key_name = dict_bes_key['PRI_KEY_NAME'] out_key_name = dict_bes_key['OUT_KEY_NAME'] extract_dir = dict_bes_key['EXTRACT_DIR'] extract_cmd = dict_bes_key['EXTRACT_CMD'] key_dir = dict_bes_key['KEY_DIR'] sign_cmd = dict_bes_key['SIGN_CMD'] sign_dir = dict_bes_key['SIGN_DIR'] sign_file_dir = dict_bes_key['SIGN_FILE_DIR'] binary_dir = dict_bes_key['BINARY_DIR'] rtos_res_file_name = dict_bes_key['RTOS_RES_FILE_NAME'] rtos_file_name = dict_bes_key['RTOS_FILE_NAME'] release_file_dir = dict_bes_key['RELEASE_BIN_DIR'] pack_file_name = dict_bes_key['PACK_FILE_NAME'] ota_bin_dir = dict_bes_key['OTA_BIN_DIR'] gui_bin_dir = dict_bes_key['GUI_BIN_DIR'] download_tools_dir = dict_bes_key['DLOWNLOAD_TOOLS_DIR'] gui_tools_dir = dict_bes_key['GUI_TOOLS_DIR'] log_swich = dict_bes_key['LOG_SWITCH'] chmod_swich = dict_bes_key['CHMOD_SWITCH'] extract_switch = dict_bes_key['EXTRACT_SWITCH'] pub_otp_switch = dict_bes_key['PUB_OTP_SWITCH'] sign_file_switch = dict_bes_key['SIGN_FILE_SWITCH'] pack_switch = dict_bes_key['PACK_SWITCH'] dld_cfg_dir = dict_bes_key['GUI_CFG_YAML_DIR'] dld_cfg_file = dict_bes_key['GUI_CFG_YAML_FILE'] pro_dld_cfg_file = dict_bes_key['PRO_CFG_YAML_FILE'] # PUB_OTP dict_pub_otp = cfg_dict['PUB_OTP'] outkey_dir = dict_pub_otp['OUTKEY_DIR'] outkey_file_name = dict_pub_otp['OUTKEY_FILE_NAME'] pub_otp_name = dict_pub_otp['PUB_OTP_FILE_NAME'] #print cfg_dict # chmod sign_dir if chmod_swich == 'ON' and (osstr =="Linux"): cmd_list = [] cmd_list.append('chmod') cmd_list.append('777') cur_dir = os.getcwd() #花生,2020年10月6日17:32:39,下面的语句,原版本是print cur_dir,要想在3.x版本支持,需要加括号。 #否则会提示"missing parentheses in call to print"错误。下面若干个print也是相同处理方式 print (cur_dir) cmd_list.append(cur_dir + '/' + sign_dir) if log_swich == "ON": print(cmd_list) child = subprocess.Popen(cmd_list) is_fst = True while True: status = child.poll() if status == 0: break if status == 1: break if str(status) == 'None' and is_fst: print('Start chmod sign dir...') is_fst = False print("chmod sign dir done.\n") #make littlefs if False: os.system("echo \"Start make littlefs\"") #print val flag = sys.argv[1] if flag == '1': cmd_list = ['./s700_genfs.sh'] if osstr == "Windows": cmd_list = ['.\\s700_genfs.bat'] else: cmd_list = ['./haas1000_genfs.sh'] if osstr == "Windows": cmd_list = ['.\\haas1000_genfs.bat'] child = subprocess.Popen(cmd_list) while True: status = child.poll() if status != None: break; print("genfs done. ") size = os.path.getsize("../../prebuild/littlefs.bin") print("Littlefs code size:%d"%size) if size<4882432: time.sleep(5) os.system("echo \"Make littlefs done\"") # extract pub_key if extract_switch == 'ON': cmd_list = [] cmd_list = extract_cmd cur_dir = os.getcwd() #花生,2020年10月6日17:32:39,下面的语句,原版本是print cur_dir,要想在3.x版本支持,需要加括号。 #否则会提示"missing parentheses in call to print"错误。下面若干个print也是相同处理方式 print (cur_dir) if osstr == "Windows": cmd_list = [] cmd_list.append(cur_dir + '/' + sign_dir + '/' + 'bes_sign.bat') cmd_list.append(cur_dir + '/' + sign_dir + '/' + in_key_dir + '/' + pub_key_name) cmd_list.append(cur_dir + '/' + sign_dir + '/' + out_key_dir + '/' + out_key_name) print(os.getcwd()) if log_swich == 'ON': print(cmd_list) os.chdir(cur_dir + '/' + sign_dir + '/' + extract_dir) print(os.getcwd()) child = subprocess.Popen(cmd_list) is_fst = True while True: status = child.poll() if status == 0: break if status == 1: break if str(status) == 'None' and is_fst: print('Start extract the public key in C code format...') is_fst = False os.chdir(cur_dir) print("Extract the public key done.\n") # makedir release_bin ota_bin download_tools if True: isExists=os.path.exists(release_file_dir) if isExists == False: os.makedirs(release_file_dir) isExists = os.path.exists(ota_bin_dir) if isExists == False: os.makedirs(ota_bin_dir) isExists = os.path.exists(gui_bin_dir) if isExists == False: os.makedirs(gui_bin_dir) isExists = os.path.exists(download_tools_dir) if isExists == False: os.makedirs(download_tools_dir) isExists = os.path.exists(gui_tools_dir) if isExists == False: os.makedirs(gui_tools_dir) # Make pub_otp if pub_otp_switch == "ON": cmd_list = [] #./best_sign -k key/OutKey.bin key/pub_flash2.bin cur_dir = os.getcwd() if osstr == "Windows": sign_cmd = sign_cmd + '.exe' cmd_list.append(sign_dir + '/' + sign_cmd) cmd_list.append('-k') cmd_list.append(sign_dir + '/' + outkey_dir + '/' + outkey_file_name) cmd_list.append(release_file_dir + '/' + pub_otp_name) if log_swich == "ON": print(cmd_list) child = subprocess.Popen(cmd_list) is_fst = True while True: status = child.poll() if status == 0: break if status == 1: break if str(status) == 'None' and is_fst: print('Start make %s...'%(pub_otp_name)) is_fst = False print("Make %s done.\n"%(pub_otp_name)) cmd_cp_list = [] cmd_cp_list.append('cp') cmd_cp_list.append(release_file_dir + '/' + pub_otp_name) cmd_cp_list.append(ota_bin_dir + '/') if log_swich == "ON": print(cmd_cp_list) shutil.copy(release_file_dir + '/' + pub_otp_name, ota_bin_dir + '/') # child = subprocess.Popen(cmd_cp_list) cmd_cp_list2 = [] cmd_cp_list2.append('cp') cmd_cp_list2.append(release_file_dir + '/' + pub_otp_name) cmd_cp_list2.append(gui_bin_dir + '/') if log_swich == "ON": print(cmd_cp_list2) shutil.copy(release_file_dir + '/' + pub_otp_name, gui_bin_dir + '/') # child = subprocess.Popen(cmd_cp_list2) is_fst = True while True: status = child.poll() if status == 0: break if status == 1: break if str(status) == 'None' and is_fst: print('Cp %s from dir release_bin to dir ota_bin...' % (pub_otp_name)) is_fst = False print("Cp %s done.\n" % (pub_otp_name)) # cp prebuild/*.bin release_bin/ if True: if (osstr =="Linux"): os.system('chmod 777 ' + release_file_dir + '/') path = sign_file_dir file_list = os.listdir(path) for i in range(len(file_list)): res_file_path = sign_file_dir + '/' + file_list[i] des_path = release_file_dir + '/' cmd_str = 'cp -f ' + res_file_path + ' ' + des_path if log_swich == "ON": print(cmd_str) if os.path.isfile(res_file_path): shutil.copy(res_file_path, des_path) # os.system(cmd_str) # cp out/helloworld_demo@haas1000/binary/helloworld_demo@haas1000.bin release_bin if True: res_file_path = binary_dir + '/' + rtos_res_file_name if not glob.glob(res_file_path): res_file_path = os.path.join(output_dir, "binary", rtos_res_file_name) res_file_path = sys.argv[2] des_path = release_file_dir + '/' + rtos_file_name cmd_str = 'cp ' + res_file_path + ' ' + des_path if log_swich == "ON": print(cmd_str) print(glob.glob(res_file_path)[0]) shutil.copy(glob.glob(res_file_path)[0], des_path) # mv release_bin/helloworld_demo@haas1000.bin release_bin/ota_rtos.bin ''' if True: res_file_path = release_file_dir + '/' + rtos_res_file_name des_file_path = release_file_dir + '/' + rtos_file_name cmd_str = 'mv ' + res_file_path + ' ' + des_file_path if log_swich == "ON": print(cmd_str) os.system(cmd_str) ''' # cp ../write_flash_gui/dld_cfg to ../write_flash_gui/ if False: res_file_path = dld_cfg_dir + '/' + pro_dld_cfg_file des_path = gui_tools_dir + '/' cmd_str = 'cp -f ' + res_file_path + ' ' + des_path if log_swich == "ON": print(cmd_str) shutil.copy(res_file_path, des_path) #os.system(cmd_str) # mv ../write_flash_gui/dld_cfg/haas1000_dld_cfg_*.yaml to ../write_flash_gui/haas1000_dld_cfg.yaml if False: res_file_path = gui_tools_dir + '/' + pro_dld_cfg_file des_file_path = gui_tools_dir + '/' + dld_cfg_file cmd_str = 'cp -f ' + res_file_path + ' ' + des_file_path if log_swich == "ON": print(cmd_str) if (not os.path.isfile(des_file_path)) or (pro_dld_cfg_file != dld_cfg_file): shutil.copy(res_file_path, des_path) #os.system(cmd_str) # sign release_bin/*.bin --- according to configuration(bes_sign_cfg.yaml) if sign_file_switch == "ON": #./ best_sign key/pri.pem before_sign/noapp_test.bin dict_sign_file = cfg_dict['SIGN_FILE_LIST'] print (dict_sign_file) list_items_file = dict_sign_file file_itme_len = len(list_items_file) #print "file_itme_len %d " % file_itme_len for index in range(file_itme_len): sign_file_cmd_str = [] file_item = {} #print "list_items_file[index] %s" %list_items_file[index] file_item = list_items_file[index] tmp_file_item = file_item; if tmp_file_item: print(str(file_item)) sign_file_name = tmp_file_item['FILE_NAME'] sign_switch = tmp_file_item['SWITCH'] #print "sign_file_name %s" % sign_file_name #print "sign_switch %s" % sign_switch if sign_switch and sign_file_name: cmd_list = [] #os.system('chmod 777 ' + release_file_dir + '/' + sign_file_name) cmd_list.append(sign_dir + '/' + sign_cmd) cmd_list.append(sign_dir + '/' + in_key_dir + '/' + pri_key_name) cmd_list.append(release_file_dir + '/' + sign_file_name) if log_swich == "ON": print(cmd_list) child = subprocess.Popen(cmd_list) is_fst = True while True: status = child.poll() if status == 0: break if status == 1: break if str(status) == 'None' and is_fst: print('Start sign file...') is_fst = False print("Sign file done.\n") # mv release_bin/programmer2001.bin write_flash_tool/tools/ # changed by yanxiaoyong.yxy from True to False if False: res_file_path = release_file_dir + '/' + 'programmer2001.bin' des_file_path = download_tools_dir + '/' cmd_str = 'cp -f ' + res_file_path + ' ' + des_file_path if log_swich == "ON": print(cmd_str) shutil.copy(res_file_path, des_path) #os.system(cmd_str) res_file_path = download_tools_dir + '/' + 'programmer2001.bin' des_file_path = gui_tools_dir + '/' cmd_str = 'cp -f ' + res_file_path + ' ' + des_file_path if log_swich == "ON": print(cmd_str) shutil.copy(res_file_path, des_path) #os.system(cmd_str) # cp release_bin/*.bin ota_bin if True: path = release_file_dir file_list = os.listdir(path) for i in range(len(file_list)): res_file_path = release_file_dir + '/' + file_list[i] des_path = ota_bin_dir + '/' cmd_str = 'cp -f ' + res_file_path + ' ' + des_path if log_swich == "ON": print(cmd_str) shutil.copy(res_file_path, des_path) #os.system(cmd_str) des_path = gui_bin_dir + '/' cmd_str = 'cp -f ' + res_file_path + ' ' + des_path if log_swich == "ON": print(cmd_str) shutil.copy(res_file_path, des_path) #os.system(cmd_str) print('all files done.') if pack_switch == 'ON': print('Pack files start...') res_dir = cur_dir + '/' + sign_dir + '/' + sign_file_dir + '/*.bin' dst_dir = release_file_dir + '/' os.system('cp "' + res_dir + '" "' + dst_dir + '"') cur_dir = os.getcwd() to_pack_dir = os.getcwd() + '/' + release_file_dir os.chdir(to_pack_dir) changed_dir = os.getcwd() to_pack_file_name = pack_file_name pack_dir(changed_dir,to_pack_file_name) os.chdir(cur_dir) print('Pack files done.')
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/release/auto_build_tool/genbin.py
Python
apache-2.0
17,060
#! /usr/bin/env python3 import os, sys, re, struct, platform, getopt, subprocess from sys import platform as _platform import array,hashlib,struct def update_crc16(crcin, byte): crc = crcin calculen = byte | 0x100 crc <<= 1 calculen <<= 1 if calculen & 0x100 > 0: crc += 1 if crc & 0x10000 > 0: crc ^= 0x1021 while((calculen & 0x10000) == 0): crc <<= 1 calculen <<= 1 if calculen & 0x100 > 0: crc += 1 if crc & 0x10000 > 0: crc ^= 0x1021 return crc & 0xFFFF def crc16_calculate(data, len): crc = 0 for i in range(0, len): crc = update_crc16(crc, data[i]) crc = update_crc16(crc, 0) crc = update_crc16(crc, 0) return crc & 0xFFFF def hashcalculate(type, indata): if type == "md5": hashmethod = hashlib.md5() elif type == "sha256": hashmethod = hashlib.sha256() else: print("don't support other hash type") return 0 hashmethod.update(indata) value = hashmethod.digest() return value def print_usage(): print("") print("Usage: Merge a bin file into an exist bin file, create one if target is not exist") print(sys.argv[0]) print("Optional Usage:") print(" [-o] <target binary file>") print(" [-m] <image magic type>") print(" [-h | --help] Display usage") print(" [<input binary file>]") sys.stdout.flush() def main(): try: opts, args = getopt.getopt(sys.argv[1:], 'o:m:h') except getopt.GetoptError as err: print(str(err)) print_usage() sys.exit(2) if not len(args) == 3: print_usage() sys.exit(2) else: INPUT_FILE = args[0] if not os.path.exists(INPUT_FILE): print("Please input a binary file") sys.exit(2) for opt, arg in opts: if opt == "-o": OUTPUT_FILE = arg elif opt == "-m": magic_str = arg elif opt == "-h": print_usage() sys.exit() try: with open(INPUT_FILE, 'rb') as hfin: imagedata = hfin.read() #print("filelen = " + str(len(imagedata))) except FileNotFoundError: print(INPUT_FILE + " is not exist!") sys.exit(2) except: print("read " + INPUT_FILE + " failed!") sys.exit(2) image_alignment = 0xffffffff imagedata += struct.pack('<I', image_alignment) image_info_magic = 0xefefefef image_valid_len = len(imagedata) image_md5 = hashcalculate("md5", imagedata) image_num = 0x01 image_res = 0x00 image_crc16 = crc16_calculate(bytearray(imagedata), image_valid_len) newimagedata = imagedata[0:image_valid_len] newimagedata += struct.pack('<I', image_info_magic) newimagedata += struct.pack('<I', image_valid_len) newimagedata += image_md5 newimagedata += struct.pack('B', image_num) newimagedata += struct.pack('B', image_res) newimagedata += struct.pack('<H', image_crc16) OUTPUT_FILE = INPUT_FILE+".md5" try: with open(OUTPUT_FILE, 'wb') as imagefout: imagefout.write(newimagedata) except FileNotFoundError: print("output file path error!") sys.exit(2) except: print("output write error!") sys.exit(2) os.remove(INPUT_FILE) os.rename(OUTPUT_FILE,INPUT_FILE) if __name__ == "__main__": try: main() except KeyboardInterrupt: pass
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/release/auto_build_tool/ota_gen_md5_bin.py
Python
apache-2.0
3,481
#!/bin/sh export PATH=${PATH}:$5 ota_offset=$1 #dir=/home/cwhaiyi/pcshare/rualxw/AliOS-Things/platform/mcu/rtl8710bn platform_dir=$2/platform/mcu/rtl8710bn if [ ! -d "${platform_dir}/Debug/Exe" ]; then mkdir -p ${platform_dir}/Debug/Exe fi BIN_DIR=${platform_dir}/Debug/Exe app=`echo $3 | tr '/' '.'` outputplatform=$app@$4 outputdir=$2/out/${outputplatform}/binary if [ "${ota_offset}" = "0x0800B000" ]; then outputname=${outputplatform}.2boot else outputname=${outputplatform} fi OS=`uname -s` PICK=${platform_dir}/tools/pick PAD=${platform_dir}/tools/padding CHKSUM=${platform_dir}/tools/checksum OTA=${platform_dir}/tools/ota echo ${platform_dir} echo "" echo -n "install dependent software packages ..." if [ "$OS" = "Darwin" ]; then if [ "`which gawk`" = "" ];then sudo easy_install gawk > /dev/null fi else #Some Linux version if [ "`which apt-get`" != "" ]; then if [ "`which gawk`" = "" ];then sudo sudo apt-get -y install gawk > /dev/null fi fi fi find ${BIN_DIR}/ -name "*.axf" | xargs rm -rf find ${BIN_DIR}/ -name "*.map" | xargs rm -rf rm -f ${outputdir}/${outputname}.bin cp ${outputdir}/${outputname}.elf ${BIN_DIR}/${outputname}.axf arm-ali-aoseabi-nm ${BIN_DIR}/${outputname}.axf | sort > ${BIN_DIR}/${outputname}.nmap arm-ali-aoseabi-objcopy -j .ram_image2.entry -j .ram_image2.data -j .ram_image2.text -j .ram_image2.bss -j .ram_image2.skb.bss -j .ram_heap.data -Obinary ${BIN_DIR}/${outputname}.axf ${BIN_DIR}/ram_2.r.bin arm-ali-aoseabi-objcopy -j .xip_image2.text -Obinary ${BIN_DIR}/${outputname}.axf ${BIN_DIR}/xip_image2.bin arm-ali-aoseabi-objcopy -j .ram_rdp.text -Obinary ${BIN_DIR}/${outputname}.axf ${BIN_DIR}/rdp.bin if [ ! -f "${BIN_DIR}/bin/boot_all.bin" ]; then cp ${platform_dir}/bin/boot_all.bin ${BIN_DIR}/boot_all.bin fi chmod 777 ${BIN_DIR}/boot_all.bin chmod +rx ${PICK} ${CHKSUM} ${PAD} ${OTA} ${PICK} 0x`grep __ram_image2_text_start__ ${BIN_DIR}/${outputname}.nmap | gawk '{print $1}'` 0x`grep __ram_image2_text_end__ ${BIN_DIR}/${outputname}.nmap | gawk '{print $1}'` ${BIN_DIR}/ram_2.r.bin ${BIN_DIR}/ram_2.bin raw ${PICK} 0x`grep __ram_image2_text_start__ ${BIN_DIR}/${outputname}.nmap | gawk '{print $1}'` 0x`grep __ram_image2_text_end__ ${BIN_DIR}/${outputname}.nmap | gawk '{print $1}'` ${BIN_DIR}/ram_2.bin ${BIN_DIR}/ram_2.p.bin ${PICK} 0x`grep __xip_image2_start__ ${BIN_DIR}/${outputname}.nmap | gawk '{print $1}'` 0x`grep __xip_image2_start__ ${BIN_DIR}/${outputname}.nmap | gawk '{print $1}'` ${BIN_DIR}/xip_image2.bin ${BIN_DIR}/xip_image2.p.bin IMAGE2_OTA1=image2_2boot.bin IMAGE2_OTA2=image2_app.bin OTA_ALL=ota_all.bin #2boot bin if [ "${ota_offset}" = "0x0800B000" ]; then cat ${BIN_DIR}/xip_image2.p.bin > ${BIN_DIR}/${IMAGE2_OTA1} chmod 777 ${BIN_DIR}/${IMAGE2_OTA1} cat ${BIN_DIR}/ram_2.p.bin >> ${BIN_DIR}/${IMAGE2_OTA1} ${CHKSUM} ${BIN_DIR}/${IMAGE2_OTA1} || true rm ${BIN_DIR}/xip_image2.p.bin ${BIN_DIR}/ram_2.p.bin cp ${platform_dir}/bin/boot_all.bin ${outputdir}/boot_all.bin cp ${BIN_DIR}/${IMAGE2_OTA1} ${outputdir}/${IMAGE2_OTA1} else cat ${BIN_DIR}/xip_image2.p.bin > ${BIN_DIR}/${IMAGE2_OTA2} chmod 777 ${BIN_DIR}/${IMAGE2_OTA2} cat ${BIN_DIR}/ram_2.p.bin >> ${BIN_DIR}/${IMAGE2_OTA2} ${CHKSUM} ${BIN_DIR}/${IMAGE2_OTA2} || true rm ${BIN_DIR}/xip_image2.p.bin ${BIN_DIR}/ram_2.p.bin cp ${BIN_DIR}/${IMAGE2_OTA2} ${outputdir}/${IMAGE2_OTA2} fi #rm -f ${BIN_DIR}/ram_2.bin ${BIN_DIR}/ram_2.p.bin ${BIN_DIR}/ram_2.r.bin ${BIN_DIR}/xip_image2.bin ${BIN_DIR}/xip_image2.p.bin
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/script/manipulate_image.sh
Shell
apache-2.0
3,496
cd /D %2\platform\mcu\rtl8710bn\ ::echo %1 %2 %3 %4 > tmp3.txt set rootdir=%2 set amebazdir=%2\platform\mcu\rtl8710bn set tooldir=%2\platform\mcu\rtl8710bn\tools set libdir=%2\platform\mcu\rtl8710bn\lib set bindir=%2\platform\mcu\rtl8710bn\Debug\Exe set ota_bin_ver=0x%date:~0,4%%date:~5,2%%date:~8,2% set ota_offset=%1 set outputplatform=%3@%4 set outputdir=%2\out\%outputplatform%\binary ::echo %outputdir% >tmp2.txt ::echo %outputname% >tmp4.txt ::echo input1=%1 >tmp.txt ::echo input2=%2 >>tmp.txt ::echo ota_bin_ver=%ota_bin_ver% >>tmp.txt IF NOT EXIST %bindir% MD %bindir% if "%ota_offset%"=="0x0800B000" ( copy %outputdir%\%outputplatform%.2boot.elf %bindir%\application.axf ) else ( copy %outputdir%\%outputplatform%.elf %bindir%\application.axf ) del Debug\Exe\*.map Debug\Exe\*.asm %tooldir%\nm ./Debug/Exe/application.axf | %tooldir%\sort > ./Debug/Exe/application.map %tooldir%\objdump -d ./Debug/Exe/application.axf > ./Debug/Exe/application.asm if "%ota_offset%"=="0x0800B000" ( copy %bindir%\application.map %bindir%\application.2boot.map copy %bindir%\application.asm %bindir%\application.2boot.asm ) else ( copy %bindir%\application.map %bindir%\application.app.map copy %bindir%\application.asm %bindir%\application.app.asm ) for /f "delims=" %%i in ('cmd /c "%tooldir%\grep __ram_image2_text_start__ ./Debug/Exe/application.map | %tooldir%\gawk '{print $1}'"') do set ram2_start=0x%%i for /f "delims=" %%i in ('cmd /c "%tooldir%\grep __ram_image2_text_end__ ./Debug/Exe/application.map | %tooldir%\gawk '{print $1}'"') do set ram2_end=0x%%i for /f "delims=" %%i in ('cmd /c "%tooldir%\grep __xip_image2_start__ ./Debug/Exe/application.map | %tooldir%\gawk '{print $1}'"') do set xip_image2_start=0x%%i for /f "delims=" %%i in ('cmd /c "%tooldir%\grep __xip_image2_end__ ./Debug/Exe/application.map | %tooldir%\gawk '{print $1}'"') do set xip_image2_end=0x%%i %tooldir%\objcopy -j .ram_image2.entry -j .ram_image2.data -j .ram_image2.text -j .ram_image2.bss -j .ram_image2.skb.bss -j .ram_heap.data -Obinary ./Debug/Exe/application.axf ./Debug/Exe/ram_2.r.bin %tooldir%\objcopy -j .xip_image2.text -Obinary ./Debug/Exe/application.axf ./Debug/Exe/xip_image2.bin %tooldir%\objcopy -j .ram_rdp.text -Obinary ./Debug/Exe/application.axf ./Debug/Exe/rdp.bin :: remove bss sections %tooldir%\pick %ram2_start% %ram2_end% %bindir%\ram_2.r.bin %bindir%\ram_2.bin raw del %bindir%\ram_2.r.bin :: add header %tooldir%\pick %ram2_start% %ram2_end% %bindir%\ram_2.bin %bindir%\ram_2.p.bin ::%tooldir%\pick %xip_image2_start% %xip_image2_end% Debug\Exe\xip_image2.bin Debug\Exe\xip_image2.p.bin %tooldir%\pick 0 0 %bindir%\xip_image2.bin %bindir%\xip_image2.p.bin :: get ota_idx and ota_offset from image2.icf ::setlocal enabledelayedexpansion ::findstr /rg "__ICFEDIT_region_XIP_OTA1_start__" image2.icf>test.txt ::for /f "tokens=1,2,3,4,5*" %%i in ('findstr /rg "symbol" test.txt') do ( :: set "var=%%m" :: set "ota_offset=!var:~0,10!" ::) ::setlocal disabledelayedexpansion if "%ota_offset%"=="0x0800B000" ( set ota_idx=1 ) else ( set ota_idx=2 ) ::del test.txt ::echo ota_idx=%ota_idx% >tmp.txt ::echo ota_offset=%ota_offset% >>tmp.txt :: aggregate image2_all.bin and add checksum if "%ota_idx%"=="2" ( copy /b %bindir%\xip_image2.p.bin+%bindir%\ram_2.p.bin %bindir%\image2_app.bin %tooldir%\checksum %bindir%\image2_app.bin ) else ( copy /b %bindir%\xip_image2.p.bin+%bindir%\ram_2.p.bin %bindir%\image2_2boot.bin %tooldir%\checksum %bindir%\image2_2boot.bin ) del Debug\Exe\ram_2.bin del Debug\Exe\ram_2.p.bin del Debug\Exe\xip_image2.bin del Debug\Exe\xip_image2.p.bin :: force update boot_all.bin :: del Debug\Exe\boot_all.bin :: check boot_all.bin exist, copy default if not exist Debug\Exe\boot_all.bin ( copy %amebazdir%\bin\boot_all.bin %bindir%\boot_all.bin ) if "%ota_idx%"=="2" ( copy %bindir%\image2_app.bin %outputdir%\image2_app.bin copy %bindir%\ota_all.bin %outputdir%\ota_all.bin ) else ( copy %bindir%\boot_all.bin %outputdir%\boot_all.bin copy %bindir%\image2_2boot.bin %outputdir%\image2_2boot.bin ) :: board generator ::%tooldir%\..\gen_board_img2.bat %ram2_start% %ram2_end% exit
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/script/postbuild_img2.bat
Batchfile
apache-2.0
4,194
Dim WshShell Set WshShell = WScript.CreateObject("WScript.Shell") WshShell.Run "cmd /c "+WScript.Arguments.Item(1)+"postbuild_img2.bat "+WScript.Arguments.Item(0)+" "+WScript.Arguments.Item(1), 0
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/script/postbuild_img2.vbs
VBScript
apache-2.0
198
#define UTS_VERSION "2017/12/20-10:58:56" #define RTL8195AFW_COMPILE_TIME "2017/12/20-10:58:56" #define RTL8195AFW_COMPILE_DATE "2017/12/20" #define RTL8195AFW_COMPILE_BY "Jeanne" #define RTL8195AFW_COMPILE_HOST "Jeanne-PC" #define RTL8195AFW_COMPILE_DOMAIN #define RTL8195AFW_COMPILER "IAR compiler"
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/build_info.h
C
apache-2.0
308
/* Includes ------------------------------------------------------------------*/ #include "lwip/mem.h" #include "lwip/memp.h" #include "lwip/dhcp.h" #include "lwip/dns.h" #include "lwip/tcpip.h" #include "ethernetif.h" #include "main.h" #include "lwip_netconf.h" #if CONFIG_WLAN #include "wifi_ind.h" #endif #if defined(STM32F2XX) #include "stm322xg_eval_lcd.h" #elif defined(STM32F4XX) #include "stm324xg_eval_lcd.h" #endif #include <platform/platform_stdlib.h> #include "osdep_service.h" /*Static IP ADDRESS*/ #ifndef IP_ADDR0 #define IP_ADDR0 192 #define IP_ADDR1 168 #define IP_ADDR2 1 #define IP_ADDR3 80 #endif /*NETMASK*/ #ifndef NETMASK_ADDR0 #define NETMASK_ADDR0 255 #define NETMASK_ADDR1 255 #define NETMASK_ADDR2 255 #define NETMASK_ADDR3 0 #endif /*Gateway Address*/ #ifndef GW_ADDR0 #define GW_ADDR0 192 #define GW_ADDR1 168 #define GW_ADDR2 1 #define GW_ADDR3 1 #endif /*Static IP ADDRESS*/ #ifndef AP_IP_ADDR0 #define AP_IP_ADDR0 192 #define AP_IP_ADDR1 168 #define AP_IP_ADDR2 43 #define AP_IP_ADDR3 1 #endif /*NETMASK*/ #ifndef AP_NETMASK_ADDR0 #define AP_NETMASK_ADDR0 255 #define AP_NETMASK_ADDR1 255 #define AP_NETMASK_ADDR2 255 #define AP_NETMASK_ADDR3 0 #endif /*Gateway Address*/ #ifndef AP_GW_ADDR0 #define AP_GW_ADDR0 192 #define AP_GW_ADDR1 168 #define AP_GW_ADDR2 43 #define AP_GW_ADDR3 1 #endif /*Static IP ADDRESS FOR ETHERNET*/ #ifndef ETH_IP_ADDR0 #define ETH_IP_ADDR0 192 #define ETH_IP_ADDR1 168 #define ETH_IP_ADDR2 0 #define ETH_IP_ADDR3 80 #endif /*NETMASK FOR ETHERNET*/ #ifndef ETH_NETMASK_ADDR0 #define ETH_NETMASK_ADDR0 255 #define ETH_NETMASK_ADDR1 255 #define ETH_NETMASK_ADDR2 255 #define ETH_NETMASK_ADDR3 0 #endif /*Gateway address for ethernet*/ #ifndef ETH_GW_ADDR0 #define ETH_GW_ADDR0 192 #define ETH_GW_ADDR1 168 #define ETH_GW_ADDR2 0 #define ETH_GW_ADDR3 1 #endif /* Private define ------------------------------------------------------------*/ #define MAX_DHCP_TRIES 10 /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ struct netif xnetif[NET_IF_NUM]; /* network interface structure */ /* Private functions ---------------------------------------------------------*/ /** * @brief Initializes the lwIP stack * @param None * @retval None */ #if CONFIG_WLAN extern int error_flag; extern rtw_mode_t wifi_mode; #endif int lwip_init_done = 0; void LwIP_Init(void) { ip_addr_t ipaddr; ip_addr_t netmask; ip_addr_t gw; int8_t idx = 0; /* Create tcp_ip stack thread */ tcpip_init( NULL, NULL ); /* - netif_add(struct netif *netif, struct ip_addr *ipaddr, struct ip_addr *netmask, struct ip_addr *gw, void *state, err_t (* init)(struct netif *netif), err_t (* input)(struct pbuf *p, struct netif *netif)) Adds your network interface to the netif_list. Allocate a struct netif and pass a pointer to this structure as the first argument. Give pointers to cleared ip_addr structures when using DHCP, or fill them with sane numbers otherwise. The state pointer may be NULL. The init function pointer must point to a initialization function for your ethernet netif interface. The following code illustrates it's use.*/ //printf("NET_IF_NUM:%d\n\r",NET_IF_NUM); for(idx=0;idx<NET_IF_NUM;idx++){ if(idx==0){ IP4_ADDR((&ipaddr), IP_ADDR0, IP_ADDR1, IP_ADDR2, IP_ADDR3); IP4_ADDR((&netmask), NETMASK_ADDR0, NETMASK_ADDR1 , NETMASK_ADDR2, NETMASK_ADDR3); IP4_ADDR((&gw), GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3); } else{ IP4_ADDR((&ipaddr), AP_IP_ADDR0, AP_IP_ADDR1, AP_IP_ADDR2, AP_IP_ADDR3); IP4_ADDR((&netmask), AP_NETMASK_ADDR0, AP_NETMASK_ADDR1 , AP_NETMASK_ADDR2, AP_NETMASK_ADDR3); IP4_ADDR((&gw), AP_GW_ADDR0, AP_GW_ADDR1, AP_GW_ADDR2, AP_GW_ADDR3); } #if CONFIG_ETHERNET if(idx == NET_IF_NUM - 1) { IP4_ADDR(&ipaddr, ETH_IP_ADDR0, ETH_IP_ADDR1, ETH_IP_ADDR2, ETH_IP_ADDR3); IP4_ADDR(&netmask, ETH_NETMASK_ADDR0, ETH_NETMASK_ADDR1 , ETH_NETMASK_ADDR2, ETH_NETMASK_ADDR3); IP4_ADDR(&gw, ETH_GW_ADDR0, ETH_GW_ADDR1, ETH_GW_ADDR2, ETH_GW_ADDR3); } #endif xnetif[idx].name[0] = 'r'; xnetif[idx].name[1] = '0'+idx; #if CONFIG_ETHERNET if(idx == NET_IF_NUM - 1) netif_add(&xnetif[idx], &ipaddr, &netmask, &gw, NULL, &ethernetif_mii_init, &tcpip_input); else netif_add(&xnetif[idx], &ipaddr, &netmask, &gw, NULL, &ethernetif_init, &tcpip_input); #else netif_add(&xnetif[idx], &ipaddr, &netmask, &gw, NULL, &ethernetif_init, &tcpip_input); #endif printf("interface %d is initialized\n", idx); } /* Registers the default network interface. */ netif_set_default(&xnetif[0]); /*move these operations to wifi_on/wifi_off*/ #if 0 /* When the netif is fully configured this function must be called.*/ for(idx = 0;idx < NET_IF_NUM;idx++) netif_set_up(&xnetif[idx]); #endif lwip_init_done = 1; } /** * @brief LwIP_DHCP_Process_Handle * @param None * @retval None */ uint8_t LwIP_DHCP(uint8_t idx, uint8_t dhcp_state) { ip_addr_t ipaddr; ip_addr_t netmask; ip_addr_t gw; uint32_t IPaddress; uint8_t iptab[4]; uint8_t DHCP_state; int mscnt = 0; struct netif *pnetif = NULL; DHCP_state = dhcp_state; #if !CONFIG_ETHERNET if(idx > 1) idx = 1; #endif pnetif = &xnetif[idx]; struct dhcp *dhcp = netif_dhcp_data(pnetif); if(DHCP_state == 0){ pnetif->ip_addr.addr = 0; pnetif->netmask.addr = 0; pnetif->gw.addr = 0; } for (;;) { //printf("\n\r ========DHCP_state:%d============\n\r",DHCP_state); switch (DHCP_state) { case DHCP_START: { #if CONFIG_WLAN wifi_unreg_event_handler(WIFI_EVENT_BEACON_AFTER_DHCP, wifi_rx_beacon_hdl); #endif dhcp_start(pnetif); IPaddress = 0; DHCP_state = DHCP_WAIT_ADDRESS; dhcp = netif_dhcp_data(pnetif); } break; case DHCP_WAIT_ADDRESS: { /* If DHCP stopped by wifi_disconn_hdl*/ if(dhcp->state == 0) { printf("\n\rLwIP_DHCP: dhcp stop."); return DHCP_STOP; } /* Read the new IP address */ IPaddress = pnetif->ip_addr.addr; if (IPaddress!=0) { DHCP_state = DHCP_ADDRESS_ASSIGNED; #if CONFIG_WLAN wifi_reg_event_handler(WIFI_EVENT_BEACON_AFTER_DHCP, wifi_rx_beacon_hdl, NULL); #endif /* Stop DHCP */ // dhcp_stop(pnetif); /* can not stop, need to renew, Robbie*/ iptab[0] = (uint8_t)(IPaddress >> 24); iptab[1] = (uint8_t)(IPaddress >> 16); iptab[2] = (uint8_t)(IPaddress >> 8); iptab[3] = (uint8_t)(IPaddress); printf("\n\rInterface %d IP address : %d.%d.%d.%d", idx, iptab[3], iptab[2], iptab[1], iptab[0]); #if CONFIG_WLAN error_flag = RTW_NO_ERROR; #endif return DHCP_ADDRESS_ASSIGNED; } else { /* DHCP timeout */ if (dhcp->tries > MAX_DHCP_TRIES) { DHCP_state = DHCP_TIMEOUT; /* Stop DHCP */ dhcp_stop(pnetif); /* Static address used */ IP4_ADDR(&ipaddr, IP_ADDR0 ,IP_ADDR1 , IP_ADDR2 , IP_ADDR3 ); IP4_ADDR(&netmask, NETMASK_ADDR0, NETMASK_ADDR1, NETMASK_ADDR2, NETMASK_ADDR3); IP4_ADDR(&gw, GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3); netif_set_addr(pnetif, &ipaddr , &netmask, &gw); iptab[0] = IP_ADDR3; iptab[1] = IP_ADDR2; iptab[2] = IP_ADDR1; iptab[3] = IP_ADDR0; printf("\n\rInterface %d DHCP timeout",idx); printf("\n\rStatic IP address : %d.%d.%d.%d", iptab[3], iptab[2], iptab[1], iptab[0]); #if CONFIG_WLAN error_flag = RTW_DHCP_FAIL; #endif #if CONFIG_ETHERNET if(idx == NET_IF_NUM -1) // This is the ethernet interface, set it up for static ip address netif_set_up(pnetif); #endif return DHCP_TIMEOUT; }else { //sys_msleep(DHCP_FINE_TIMER_MSECS); rtw_msleep_os(DHCP_FINE_TIMER_MSECS); dhcp_fine_tmr(); mscnt += DHCP_FINE_TIMER_MSECS; if (mscnt >= DHCP_COARSE_TIMER_SECS*1000) { dhcp_coarse_tmr(); mscnt = 0; } } } } break; case DHCP_RELEASE_IP: #if CONFIG_WLAN wifi_unreg_event_handler(WIFI_EVENT_BEACON_AFTER_DHCP, wifi_rx_beacon_hdl); #endif printf("\n\rLwIP_DHCP: Release ip"); dhcp_release(pnetif); return DHCP_RELEASE_IP; case DHCP_STOP: #if CONFIG_WLAN wifi_unreg_event_handler(WIFI_EVENT_BEACON_AFTER_DHCP, wifi_rx_beacon_hdl); #endif printf("\n\rLwIP_DHCP: dhcp stop."); dhcp_stop(pnetif); printf("\n\rLwIP_DHCP: dhcp stop.end"); return DHCP_STOP; default: break; } } } void LwIP_ReleaseIP(uint8_t idx) { ip_addr_t ipaddr; ip_addr_t netmask; ip_addr_t gw; struct netif *pnetif = &xnetif[idx]; IP4_ADDR(&ipaddr, 0, 0, 0, 0); IP4_ADDR(&netmask, 255, 255, 255, 0); IP4_ADDR(&gw, 0, 0, 0, 0); netif_set_addr(pnetif, &ipaddr , &netmask, &gw); } uint8_t* LwIP_GetMAC(struct netif *pnetif) { return (uint8_t *) (pnetif->hwaddr); } uint8_t* LwIP_GetIP(struct netif *pnetif) { return (uint8_t *) &(pnetif->ip_addr); } uint8_t* LwIP_GetGW(struct netif *pnetif) { return (uint8_t *) &(pnetif->gw); } uint8_t* LwIP_GetMASK(struct netif *pnetif) { return (uint8_t *) &(pnetif->netmask); } uint8_t* LwIP_GetBC(struct netif *pnetif) { return NULL; } #if LWIP_DNS void LwIP_GetDNS(ip_addr_t* dns) { return; } void LwIP_SetDNS(ip_addr_t* dns) { //dns_setserver(0, (const ip_addr_t *)dns); return; } #endif void LwIP_UseStaticIP(struct netif *pnetif) { ip_addr_t ipaddr; ip_addr_t netmask; ip_addr_t gw; /* Static address used */ if(pnetif->name[1] == '0'){ #if CONFIG_WLAN if(wifi_mode == RTW_MODE_STA){ IP4_ADDR(&ipaddr, IP_ADDR0 ,IP_ADDR1 , IP_ADDR2 , IP_ADDR3 ); IP4_ADDR(&netmask, NETMASK_ADDR0, NETMASK_ADDR1, NETMASK_ADDR2, NETMASK_ADDR3); IP4_ADDR(&gw, GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3); } else if(wifi_mode == RTW_MODE_AP){ IP4_ADDR(&ipaddr, AP_IP_ADDR0, AP_IP_ADDR1, AP_IP_ADDR2, AP_IP_ADDR3); IP4_ADDR(&netmask, AP_NETMASK_ADDR0, AP_NETMASK_ADDR1 , AP_NETMASK_ADDR2, AP_NETMASK_ADDR3); IP4_ADDR(&gw, AP_GW_ADDR0, AP_GW_ADDR1, AP_GW_ADDR2, AP_GW_ADDR3); } #endif }else{ IP4_ADDR(&ipaddr, AP_IP_ADDR0, AP_IP_ADDR1, AP_IP_ADDR2, AP_IP_ADDR3); IP4_ADDR(&netmask, AP_NETMASK_ADDR0, AP_NETMASK_ADDR1 , AP_NETMASK_ADDR2, AP_NETMASK_ADDR3); IP4_ADDR(&gw, AP_GW_ADDR0, AP_GW_ADDR1, AP_GW_ADDR2, AP_GW_ADDR3); } netif_set_addr(pnetif, &ipaddr , &netmask, &gw); } #if LWIP_AUTOIP #include <lwip/autoip.h> void LwIP_AUTOIP(struct netif *pnetif) { uint8_t *ip = LwIP_GetIP(pnetif); autoip_start(pnetif); while((pnetif->autoip->state == AUTOIP_STATE_PROBING) || (pnetif->autoip->state == AUTOIP_STATE_ANNOUNCING)) { rtw_msleep_os(1000); } if(*((uint32_t *) ip) == 0) { ip_addr_t ipaddr; ip_addr_t netmask; ip_addr_t gw; printf("AUTOIP timeout\n"); /* Static address used */ IP4_ADDR(&ipaddr, IP_ADDR0 ,IP_ADDR1 , IP_ADDR2 , IP_ADDR3 ); IP4_ADDR(&netmask, NETMASK_ADDR0, NETMASK_ADDR1, NETMASK_ADDR2, NETMASK_ADDR3); IP4_ADDR(&gw, GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3); netif_set_addr(pnetif, &ipaddr , &netmask, &gw); printf("Static IP address : %d.%d.%d.%d\n", ip[0], ip[1], ip[2], ip[3]); } else { printf("\nLink-local address: %d.%d.%d.%d\n", ip[0], ip[1], ip[2], ip[3]); } } #endif #if LWIP_IPV6 /* Get IPv6 address with lwip 1.5.0 */ void LwIP_AUTOIP_IPv6(struct netif *pnetif) { uint8_t *ipv6 = (uint8_t *) &(pnetif->ip6_addr[0].addr[0]); netif_create_ip6_linklocal_address(pnetif, 1); printf("\nIPv6 link-local address: %02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x\n", ipv6[0], ipv6[1], ipv6[2], ipv6[3], ipv6[4], ipv6[5], ipv6[6], ipv6[7], ipv6[8], ipv6[9], ipv6[10], ipv6[11], ipv6[12], ipv6[13], ipv6[14], ipv6[15]); } #endif uint32_t LWIP_Get_Dynamic_Sleep_Interval() { #ifdef DYNAMIC_TICKLESS_SLEEP_INTERVAL return DYNAMIC_TICKLESS_SLEEP_INTERVAL; #else return 0; #endif }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/lwip_netconf.c
C
apache-2.0
11,906
/****************************************************************************** * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. * ******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __NETCONF_H #define __NETCONF_H #ifdef __cplusplus extern "C" { #endif #include "lwip/tcpip.h" /* Includes ------------------------------------------------------------------*/ #include <platform/platform_stdlib.h> #include "platform_opts.h" #include "autoconf.h" // macros /* Give default value if not defined */ #ifndef NET_IF_NUM #ifdef CONFIG_CONCURRENT_MODE #define NET_IF_NUM ((CONFIG_ETHERNET) + (CONFIG_WLAN) + 1) #else #define NET_IF_NUM ((CONFIG_ETHERNET) + (CONFIG_WLAN)) #endif // end of CONFIG_CONCURRENT_MODE #endif // end of NET_IF_NUM /* Private typedef -----------------------------------------------------------*/ typedef enum { DHCP_START=0, DHCP_WAIT_ADDRESS, DHCP_ADDRESS_ASSIGNED, DHCP_RELEASE_IP, DHCP_STOP, DHCP_TIMEOUT } DHCP_State_TypeDef; /* Extern functions ------------------------------------------------------------*/ void wifi_rx_beacon_hdl( char* buf, int buf_len, int flags, void* userdata); /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ void LwIP_Init(void); uint8_t LwIP_DHCP(uint8_t idx, uint8_t dhcp_state); void LwIP_ReleaseIP(uint8_t idx); unsigned char* LwIP_GetMAC(struct netif *pnetif); unsigned char* LwIP_GetIP(struct netif *pnetif); unsigned char* LwIP_GetGW(struct netif *pnetif); uint8_t* LwIP_GetMASK(struct netif *pnetif); uint8_t* LwIP_GetBC(struct netif *pnetif); #if LWIP_DNS void LwIP_GetDNS(ip_addr_t* dns); void LwIP_SetDNS(ip_addr_t* dns); #endif void LwIP_UseStaticIP(struct netif *pnetif); #if LWIP_AUTOIP void LwIP_AUTOIP(struct netif *pnetif); #endif #if LWIP_IPV6 void LwIP_AUTOIP_IPv6(struct netif *pnetif); #endif uint32_t LWIP_Get_Dynamic_Sleep_Interval(); #ifdef __cplusplus } #endif #endif /* __NETCONF_H */ /******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/lwip_netconf.h
C
apache-2.0
2,561
/****************************************************************************** * Copyright (c) 2013-2016 Realtek Semiconductor Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ #ifndef __LIST_H #define __LIST_H #if defined ( __CC_ARM ) #ifndef inline #define inline __inline #endif #endif /* This file is from Linux Kernel (include/linux/list.h) * and modified by simply removing hardware prefetching of list items. * Here by copyright, credits attributed to wherever they belong. * Kulesh Shanmugasundaram (kulesh [squiggly] isis.poly.edu) */ /* * Simple doubly linked list implementation. * * Some of the internal functions ("__xxx") are useful when * manipulating whole lists rather than single entries, as * sometimes we already know the next/prev entries and we can * generate better code by using them directly rather than * using the generic single-entry routines. */ struct list_head { struct list_head *next, *prev; }; #define LIST_HEAD_INIT(name) { &(name), &(name) } #define LIST_HEAD(name) \ struct list_head name = LIST_HEAD_INIT(name) #define INIT_LIST_HEAD(ptr) do { \ (ptr)->next = (ptr); (ptr)->prev = (ptr); \ } while (0) /* * Insert a new entry between two known consecutive entries. * * This is only for internal list manipulation where we know * the prev/next entries already! */ static inline void __list_add(struct list_head *newitem, struct list_head *prev, struct list_head *next) { next->prev = newitem; newitem->next = next; newitem->prev = prev; prev->next = newitem; } /** * list_add - add a new entry * @new: new entry to be added * @head: list head to add it after * * Insert a new entry after the specified head. * This is good for implementing stacks. */ static inline void list_add(struct list_head *newitem, struct list_head *head) { __list_add(newitem, head, head->next); } /** * list_add_tail - add a new entry * @new: new entry to be added * @head: list head to add it before * * Insert a new entry before the specified head. * This is useful for implementing queues. */ static inline void list_add_tail(struct list_head *newitem, struct list_head *head) { __list_add(newitem, head->prev, head); } /* * Delete a list entry by making the prev/next entries * point to each other. * * This is only for internal list manipulation where we know * the prev/next entries already! */ static inline void __list_del(struct list_head *prev, struct list_head *next) { next->prev = prev; prev->next = next; } /** * list_del - deletes entry from list. * @entry: the element to delete from the list. * Note: list_empty on entry does not return true after this, the entry is in an undefined state. */ static inline void list_del(struct list_head *entry) { __list_del(entry->prev, entry->next); entry->next = (struct list_head *) 0; entry->prev = (struct list_head *) 0; } /** * list_del_init - deletes entry from list and reinitialize it. * @entry: the element to delete from the list. */ static inline void list_del_init(struct list_head *entry) { __list_del(entry->prev, entry->next); INIT_LIST_HEAD(entry); } /** * list_move - delete from one list and add as another's head * @list: the entry to move * @head: the head that will precede our entry */ static inline void list_move(struct list_head *list, struct list_head *head) { __list_del(list->prev, list->next); list_add(list, head); } /** * list_move_tail - delete from one list and add as another's tail * @list: the entry to move * @head: the head that will follow our entry */ static inline void list_move_tail(struct list_head *list, struct list_head *head) { __list_del(list->prev, list->next); list_add_tail(list, head); } /** * list_empty - tests whether a list is empty * @head: the list to test. */ static inline int list_empty(struct list_head *head) { return head->next == head; } static inline void __list_splice(struct list_head *list, struct list_head *head) { struct list_head *first = list->next; struct list_head *last = list->prev; struct list_head *at = head->next; first->prev = head; head->next = first; last->next = at; at->prev = last; } /** * list_splice - join two lists * @list: the new list to add. * @head: the place to add it in the first list. */ static inline void list_splice(struct list_head *list, struct list_head *head) { if (!list_empty(list)) __list_splice(list, head); } /** * list_splice_init - join two lists and reinitialise the emptied list. * @list: the new list to add. * @head: the place to add it in the first list. * * The list at @list is reinitialised */ static inline void list_splice_init(struct list_head *list, struct list_head *head) { if (!list_empty(list)) { __list_splice(list, head); INIT_LIST_HEAD(list); } } /** * list_entry - get the struct for this entry * @ptr: the &struct list_head pointer. * @type: the type of the struct this is embedded in. * @member: the name of the list_struct within the struct. */ #define list_entry(ptr, type, member) \ ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member))) /** * list_first_entry - get the first element from a list * @ptr: the list head to take the element from. * @type: the type of the struct this is embedded in. * @member: the name of the list_head within the struct. * * Note, that list is expected to be not empty. */ #define list_first_entry(ptr, type, member) \ list_entry((ptr)->next, type, member) /** * list_for_each - iterate over a list * @pos: the &struct list_head to use as a loop counter. * @head: the head for your list. */ #define list_for_each(pos, head) \ for (pos = (head)->next; pos != (head); \ pos = pos->next) /** * list_for_each_prev - iterate over a list backwards * @pos: the &struct list_head to use as a loop counter. * @head: the head for your list. */ #define list_for_each_prev(pos, head) \ for (pos = (head)->prev; pos != (head); \ pos = pos->prev) /** * list_for_each_safe - iterate over a list safe against removal of list entry * @pos: the &struct list_head to use as a loop counter. * @n: another &struct list_head to use as temporary storage * @head: the head for your list. */ #define list_for_each_safe(pos, n, head) \ for (pos = (head)->next, n = pos->next; pos != (head); \ pos = n, n = pos->next) /** * list_for_each_entry - iterate over list of given type * @pos: the type * to use as a loop counter. * @head: the head for your list. * @member: the name of the list_struct within the struct. */ #define list_for_each_entry(pos, head, member, type) \ for (pos = list_entry((head)->next, type, member); \ &pos->member != (head); \ pos = list_entry(pos->member.next, type, member)) /** * list_for_each_entry_safe - iterate over list of given type safe against removal of list entry * @pos: the type * to use as a loop counter. * @n: another type * to use as temporary storage * @head: the head for your list. * @member: the name of the list_struct within the struct. */ #define list_for_each_entry_safe(pos, n, head, member, type) \ for (pos = list_entry((head)->next, type, member), \ n = list_entry(pos->member.next, type, member); \ &pos->member != (head); \ pos = n, n = list_entry(n->member.next, type, member)) #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/platform/dlist.h
C
apache-2.0
8,003
/****************************************************************************** * Copyright (c) 2013-2016 Realtek Semiconductor Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ #ifndef __PLATFORM_STDLIB_H__ #define __PLATFORM_STDLIB_H__ #ifdef __cplusplus extern "C" { #endif #if defined(CONFIG_PLATFORM_8195A)+\ defined(CONFIG_PLATFORM_8711B)+\ defined(CONFIG_PLATFORM_8721D)+\ defined(CONFIG_PLATFORM_8195BHP)+\ defined(USE_STM322xG_EVAL)+\ defined(USE_STM324xG_EVAL)+\ defined(CONFIG_PLATFOMR_CUSTOMER_RTOS)+\ defined(STM32F10X_XL) > 1 #error "Cannot define two or more platform at one time" #endif #if defined(CONFIG_PLATFORM_8195A) #include "platform_stdlib_rtl8195a.h" #elif defined (CONFIG_PLATFORM_8711B) #include "platform_stdlib_rtl8711b.h" #elif defined (CONFIG_PLATFORM_8721D) #include "platform_stdlib_rtl8721d.h" #elif defined(CONFIG_PLATFORM_8195BHP) #include "platform_stdlib_rtl8195bhp.h" #elif defined(USE_STM322xG_EVAL) || defined(USE_STM324xG_EVAL) || defined(STM32F10X_XL) #include "platform_stdlib_stm32.h" #elif defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) #include "platform_stdlib_customer.h" #elif defined (CONFIG_PLATFORM_8710C) #include "platform_stdlib_rtl8710c.h" #else #error "Undefined Platform stdlib" #endif #if (CONFIG_PLATFORM_AMEBA_X == 0) #ifndef CONFIG_PLATFOMR_CUSTOMER_RTOS #include "basic_types.h" #endif #endif #ifdef __cplusplus } #endif #endif //__PLATFORM_STDLIB_H__
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/platform/platform_stdlib.h
C
apache-2.0
2,039
#ifndef PLATFORM_STDLIB_8721D_H #define PLATFORM_STDLIB_8721D_H #define CONFIG_PLATFORM_AMEBA_X 1 #if defined (__IARSTDLIB__) #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stdarg.h> /* va_list */ #include "diag.h" #define strsep(str, delim) _strsep(str, delim) #else #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> /* va_list */ #include "diag.h" #include "strproc.h" #include "memproc.h" #include "basic_types.h" #include "rtl8721d.h" #include "rtl8721d_ram_libc.h" #ifndef STD_PRINTF #undef printf #undef vsnprintf #undef sprintf #undef snprintf #undef sscanf #endif #undef memchr #undef memcmp #undef memcpy #undef memset #undef memmove #undef strcmp #undef strcpy #undef strlen #undef strncmp #undef strncpy #undef strsep #undef strtok #undef strcat #undef strchr #undef strncat #undef strstr #undef atol #undef atoi #undef strpbrk #undef strtoul #undef strtol #undef rand #ifndef STD_PRINTF #define printf _rtl_printf #define sprintf _rtl_sprintf #define snprintf _rtl_snprintf // NULL function #define vsnprintf _rtl_vsnprintf #define sscanf _rtl_sscanf //if use sscanf in std libc.a, please delete _strtol_r symbol in rlx8721d_rom_symbol_acut.ld #endif #define memchr _memchr #define memcmp _memcmp #define memcpy _memcpy //memcpy_gdma(dst, src, sz) #define memmove _memmove #define memset _memset #define strchr(s, c) _strchr(s, c) // for B-cut ROM #define strcmp(str1, str2) _strcmp(str1, str2) #define strcpy _strcpy #define strlen _strlen #define strsep(str, delim) _strsep(str, delim) #define strstr(str1, str2) _strstr(str1, str2) // NULL function #define strtok(str, delim) _strtok(str, delim)//_strsep(str, delim) #define strcat _strcat #define strncmp(str1, str2, cnt) _strncmp(str1, str2, cnt) #define strncpy(dest, src, count) _strncpy(dest, src, count) #define strncat _strncat #define strtoul(str, endp, base) _strtoul(str, endp, base) #define strtol(str, endp, base) _strtol(str, endp, base) #define atol(str) _strtol(str,NULL,10) #define atoi(str) _stratoi(str) #define strpbrk(cs, ct) _strpbrk(cs, ct) // for B-cut ROM #define rand Rand #define srand //extern int _sscanf_patch(const char *buf, const char *fmt, ...); //#define sscanf _sscanf_patch #endif // defined (__IARSTDLIB__) extern void *pvPortMalloc( size_t xWantedSize ); extern void vPortFree( void *pv ); #define malloc pvPortMalloc #define free vPortFree #define realloc pvPortReAlloc #define calloc rtw_calloc #endif // PLATFORM_STDLIB_8721D_H
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/platform/platform_stdlib_rtl8721d.h
C
apache-2.0
2,742
/* this is the c lib patch, It can help when the clib provided by IAR does not work well. How to use this: 1.You must include platform_stdlib.h in you source file。 2.There is a macro USE_CLIB_PATCH in platform_stdlib.h should be opened. If there is some problems using this patch, You'd better check if you code runs into these functions: DiagSscanfPatch DiagStrtokPatch DiagStrstrPatch DiagSnPrintfPatch DiagPrintfPatch DiagSPrintfPatch DiagPrintfPatch DiagSPrintfPatch DiagSnPrintfPatch DiagStrstrPatch DiagStrtokPatch */ #ifndef CONFIG_PLATFORM_8711B #include <stdarg.h> #define DiagPutChar HalSerialPutcRtl8195a #define IN #define NULL 0 typedef unsigned int size_t; typedef unsigned int SIZE_T; typedef unsigned long long u64; typedef unsigned int u32; typedef unsigned short int u16; typedef unsigned char u8; typedef signed long long s64; typedef signed int s32; typedef signed short int s16; typedef unsigned char bool; #define in_range(c, lo, up) ((u8)c >= lo && (u8)c <= up) #define isprint(c) in_range(c, 0x20, 0x7f) #define isdigit(c) in_range(c, '0', '9') #define isxdigit(c) (isdigit(c) || in_range(c, 'a', 'f') || in_range(c, 'A', 'F')) #define islower(c) in_range(c, 'a', 'z') #define isspace(c) (c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v' || c == ',') #define ULLONG_MAX (~0ULL) #define USHRT_MAX ((u16)(~0U)) #define KSTRTOX_OVERFLOW (1U << 31) #define SHRT_MAX ((s16)(USHRT_MAX>>1)) static inline char _tolower(const char c) { return c | 0x20; } extern s64 div_s64_rem(s64 dividend, s32 divisor, s32 *remainder); extern s64 div_s64(s64 dividend, s32 divisor); extern inline char _tolower(const char c); extern u64 div_u64_rem(u64 dividend, u32 divisor, u32 *remainder); extern u64 div_u64(u64 dividend, u32 divisor); extern unsigned int _parse_integer(const char *s, unsigned int base, unsigned long long *p); extern const char *_parse_integer_fixup_radix(const char *s, unsigned int *base); extern char *skip_spaces(const char *str); extern int skip_atoi(const char **s); extern void HalSerialPutcRtl8195a(u8 c); static unsigned long long simple_strtoull_patch(const char *cp, char **endp, unsigned int base) { unsigned long long result; unsigned int rv; cp = _parse_integer_fixup_radix(cp, &base); rv = _parse_integer(cp, base, &result); return result; } static long long simple_strtoll_patch(const char *cp, char **endp, unsigned int base) { if(*cp == '-') return -simple_strtoull_patch(cp + 1, endp, base); return simple_strtoull_patch(cp, endp, base); } static unsigned long simple_strtoul_patch(const char *cp, char **endp, unsigned int base) { return simple_strtoull_patch(cp, endp, base); } static long simple_strtol_patch(const char *cp, char **endp, unsigned int base) { if(*cp == '-') return -simple_strtoul_patch(cp + 1, endp, base); return simple_strtoul_patch(cp, endp, base); } static int judge_digit_width(const char *str) { int width = 0; while(isdigit(*str)) { width++; str++; } return width; } static int _vsscanf_patch(const char *buf, const char *fmt, va_list args) { const char *str = buf; char *next; char digit; int num = 0; int i =0; u8 qualifier; unsigned int base; union { long long s; unsigned long long u; } val; s16 field_width; bool is_sign; char str_store[20] = {0}; while(*fmt) { /* skip any white space in format */ /* white space in format matchs any amount of * white space, including none, in the input. */ if(isspace(*fmt)) { fmt = skip_spaces(++fmt); str = skip_spaces(str); } /* anything that is not a conversion must match exactly */ if(*fmt != '%' && *fmt) { if(*fmt++ != *str++) { break; } continue; } if(!*fmt) { break; } ++fmt; /* skip this conversion. * advance both strings to next white space */ if(*fmt == '*') { if(!*str) { break; } while(!isspace(*fmt) && *fmt != '%' && *fmt) fmt++; while(!isspace(*str) && *str) str++; continue; } /* get field width */ field_width = -1; if(isdigit(*fmt)) { field_width = skip_atoi(&fmt); if(field_width <= 0) { break; } } /* get conversion qualifier */ qualifier = -1; if(*fmt == 'h' || _tolower(*fmt) == 'l' || _tolower(*fmt) == 'z') { qualifier = *fmt++; if(qualifier == *fmt) { if(qualifier == 'h') { qualifier = 'H'; fmt++; } else if(qualifier == 'l') { qualifier = 'L'; fmt++; } } } if(!*fmt) { break; } if(*fmt == 'n') { /* return number of characters read so far */ *va_arg(args, int *) = str - buf; ++fmt; continue; } if(!*str) { break; } base = 10; is_sign = 0; switch(*fmt++) { case 'c': { char *s = (char *)va_arg(args, char*); if(field_width == -1) field_width = 1; do { *s++ = *str++; } while(--field_width > 0 && *str); num++; } continue; case 's': { char *s = (char *)va_arg(args, char *); if(field_width == -1) field_width = SHRT_MAX; /* first, skip leading white space in buffer */ str = skip_spaces(str); /* now copy until next white space */ while(*str && !isspace(*str) && field_width--) { *s++ = *str++; } *s = '\0'; num++; } continue; case 'o': base = 8; break; case 'x': case 'X': base = 16; break; case 'i': base = 0; case 'd': is_sign = 1; case 'u': break; case '%': /* looking for '%' in str */ if(*str++ != '%') { return num; } continue; default: /* invalid format; stop here */ return num; } /* have some sort of integer conversion. * first, skip white space in buffer. */ str = skip_spaces(str); digit = *str; if(is_sign && digit == '-') digit = *(str + 1); if(!digit || (base == 16 && !isxdigit(digit)) || (base == 10 && !isdigit(digit)) || (base == 8 && (!isdigit(digit) || digit > '7')) || (base == 0 && !isdigit(digit))) { break; } //here problem ******************************************* //troy add ,fix support %2d, but not support %d if(field_width <= 0) { field_width = judge_digit_width(str); } /////troy add, fix str passed inwidth wrong for(i = 0; i<field_width ; i++) str_store[i] = str[i]; next = (char*)str + field_width; if(is_sign) { val.s = qualifier != 'L' ? simple_strtol_patch(str_store, &next, base) : simple_strtoll_patch(str_store, &next, base); } else { val.u = qualifier != 'L' ? simple_strtoul_patch(str_store, &next, base) : simple_strtoull_patch(str_store, &next, base); } ////troy add for(i = 0; i<20 ; i++) str_store[i] = 0; //判断转换的字符串的宽度是否大于 %2d if(field_width > 0 && next - str > field_width) { if(base == 0) _parse_integer_fixup_radix(str, &base); while(next - str > field_width) { if(is_sign) { val.s = div_s64(val.s, base); } else { val.u = div_u64(val.u, base); } --next; } } switch(qualifier) { case 'H': /* that's 'hh' in format */ if(is_sign) *va_arg(args, signed char *) = val.s; else *va_arg(args, unsigned char *) = val.u; break; case 'h': if(is_sign) *va_arg(args, short *) = val.s; else *va_arg(args, unsigned short *) = val.u; break; case 'l': if(is_sign) *va_arg(args, long *) = val.s; else *va_arg(args, unsigned long *) = val.u; break; case 'L': if(is_sign) *va_arg(args, long long *) = val.s; else *va_arg(args, unsigned long long *) = val.u; break; case 'Z': case 'z': *va_arg(args, size_t *) = val.u; break; default: if(is_sign) *va_arg(args, int *) = val.s; else *va_arg(args, unsigned int *) = val.u; break; } num++; if(!next) { break; } str = next; } return num; } int DiagSscanfPatch(const char *buf, const char *fmt, ...) { va_list args; int i; va_start(args, fmt); i = _vsscanf_patch(buf, fmt, args); va_end(args); return i; } /*********************************************************/ char* DiagStrtokPatch(char *str, const char* delim) { static char* _buffer; if(str != NULL) _buffer = str; if(_buffer[0] == '\0') return NULL; char *ret = _buffer, *b; const char *d; for(b = _buffer; *b !='\0'; b++) { for(d = delim; *d != '\0'; d++) { if(*b == *d) { *b = '\0'; _buffer = b+1; // skip the beginning delimiters if(b == ret) { ret++; continue; } return ret; } } } return ret; } /*********************************************************/ char *DiagStrstrPatch(char *string, char *substring) { register char *a, *b; /* First scan quickly through the two strings looking for a * single-character match. When it's found, then compare the * rest of the substring. */ b = substring; if(*b == 0) { return string; } for(; *string != 0; string += 1) { if(*string != *b) { continue; } a = string; while(1) { if(*b == 0) { return string; } if(*a++ != *b++) { break; } } b = substring; } return (char *) 0; } /*********************************************************/ int DiagSnPrintfPatch(char *buf, size_t size, const char *fmt, ...) { va_list ap; char *p, *s, *buf_end = NULL; const int *dp = ((const int *)&fmt)+1; if(buf == NULL) return 0; va_start(ap, fmt); s = buf; buf_end = size? (buf + size):(char*)~0; for(; *fmt != '\0'; ++fmt) { if(*fmt != '%') { *s++ = *fmt; if(s >= buf_end) { goto Exit; } continue; } if(*++fmt == 's') { for(p = (char *)*dp++; *p != '\0'; p++) { *s++ = *p; if(s >= buf_end) { goto Exit; } } } else { /* Length of item is bounded */ char tmp[20], *q = tmp; int alt = 0; int shift = 0;// = 12; const long *lpforchk = (const long *)dp; if((*lpforchk) < 0x10) { shift = 0; } else if(((*lpforchk) >= 0x10) && ((*lpforchk) < 0x100)) { shift = 4; } else if(((*lpforchk) >= 0x100) && ((*lpforchk) < 0x1000)) { shift = 8; } else if(((*lpforchk) >= 0x1000) && ((*lpforchk) < 0x10000)) { shift = 12; } else if(((*lpforchk) >= 0x10000) && ((*lpforchk) < 0x100000)) { shift = 16; } else if(((*lpforchk) >= 0x100000) && ((*lpforchk) < 0x1000000)) { shift = 20; } else if(((*lpforchk) >= 0x1000000) && ((*lpforchk) < 0x10000000)) { shift = 24; } else if((*lpforchk) >= 0x10000000) { shift = 28; } else { shift = 28; } if((*fmt >= '0') && (*fmt <= '9')) { int width; unsigned char fch = *fmt; for(width=0; (fch>='0') && (fch<='9'); fch=*++fmt) { width = width * 10 + fch - '0'; } shift=(width-1)*4; } /* * Before each format q points to tmp buffer * After each format q points past end of item */ if((*fmt == 'x')||(*fmt == 'X') || (*fmt == 'p') || (*fmt == 'P')) { /* With x86 gcc, sizeof(long) == sizeof(int) */ const long *lp = (const long *)dp; long h = *lp++; int hex_count = 0; unsigned long h_back = h; int ncase = (*fmt & 0x20); dp = (const int *)lp; if((*fmt == 'p') || (*fmt == 'P')) alt=1; if(alt) { *q++ = '0'; *q++ = 'X' | ncase; } while(h_back) { hex_count += (h_back & 0xF) ? 1 : 0; h_back = h_back >> 4; } if(shift < (hex_count - 1)*4) shift = (hex_count - 1)*4; for(; shift >= 0; shift -= 4) *q++ = "0123456789ABCDEF"[(h >> shift) & 0xF] | ncase; } else if(*fmt == 'd') { int i = *dp++; char *r; int digit_space = 0; if(i < 0) { *q++ = '-'; i = -i; digit_space++; } p = q; /* save beginning of digits */ do { *q++ = '0' + (i % 10); i /= 10; digit_space++; } while(i); for(; shift >= 0; shift -= 4) { if(digit_space-- > 0) { ; //do nothing } else { *q++ = '0'; } } /* reverse digits, stop in middle */ r = q; /* don't alter q */ while(--r > p) { i = *r; *r = *p; *p++ = i; } } else if(*fmt == 'c') *q++ = *dp++; else *q++ = *fmt; /* now output the saved string */ for(p = tmp; p < q; ++p) { *s++ = *p; if(s >= buf_end) { goto Exit; } } } } Exit: if(buf) *s = '\0'; va_end(ap); return(s-buf); } /*********************************************************/ static int VSprintfPatch(char *buf, const char *fmt, const int *dp) { char *p, *s; s = buf; for(; *fmt != '\0'; ++fmt) { if(*fmt != '%') { if(buf) { *s++ = *fmt; } else { DiagPutChar(*fmt); } continue; } if(*++fmt == 's') { for(p = (char *)*dp++; *p != '\0'; p++) { if(buf) { *s++ = *p; } else { DiagPutChar(*p); } } } else { /* Length of item is bounded */ char tmp[20], *q = tmp; int alt = 0; int shift = 0;// = 12; const long *lpforchk = (const long *)dp; if((*lpforchk) < 0x10) { shift = 0; } else if(((*lpforchk) >= 0x10) && ((*lpforchk) < 0x100)) { shift = 4; } else if(((*lpforchk) >= 0x100) && ((*lpforchk) < 0x1000)) { shift = 8; } else if(((*lpforchk) >= 0x1000) && ((*lpforchk) < 0x10000)) { shift = 12; } else if(((*lpforchk) >= 0x10000) && ((*lpforchk) < 0x100000)) { shift = 16; } else if(((*lpforchk) >= 0x100000) && ((*lpforchk) < 0x1000000)) { shift = 20; } else if(((*lpforchk) >= 0x1000000) && ((*lpforchk) < 0x10000000)) { shift = 24; } else if((*lpforchk) >= 0x10000000) { shift = 28; } else { shift = 28; } #if 1 //wei patch for %02x if((*fmt >= '0') && (*fmt <= '9')) { int width; unsigned char fch = *fmt; for(width=0; (fch>='0') && (fch<='9'); fch=*++fmt) { width = width * 10 + fch - '0'; } shift=(width-1)*4; } #endif /* * Before each format q points to tmp buffer * After each format q points past end of item */ if((*fmt == 'x')||(*fmt == 'X') || (*fmt == 'p') || (*fmt == 'P')) { /* With x86 gcc, sizeof(long) == sizeof(int) */ const long *lp = (const long *)dp; long h = *lp++; int hex_count = 0; unsigned long h_back = h; int ncase = (*fmt & 0x20); dp = (const int *)lp; if((*fmt == 'p') || (*fmt == 'P')) alt=1; if(alt) { *q++ = '0'; *q++ = 'X' | ncase; } //hback 是实际得到的数据,hex_count是统计数据的HEX字符个数 while(h_back) { hex_count += (h_back & 0xF) ? 1 : 0; h_back = h_back >> 4; } //这里修复 example: 字符有4个,但是用了%02x导致字符被截断的情况 if(shift < (hex_count - 1)*4) shift = (hex_count - 1)*4; //printf("(%d,%d)", hex_count, shift); for(; shift >= 0; shift -= 4) { *q++ = "0123456789ABCDEF"[(h >> shift) & 0xF] | ncase; } } else if(*fmt == 'd') { int i = *dp++; char *r; int digit_space = 0; if(i < 0) { *q++ = '-'; i = -i; digit_space++; } p = q; /* save beginning of digits */ do { *q++ = '0' + (i % 10); i /= 10; digit_space++; } while(i); //这里修复 example:用了%08d后,在数字前面没有0的情况 for(; shift >= 0; shift -= 4) { if(digit_space-- > 0) { ; //do nothing } else { *q++ = '0'; } } /* reverse digits, stop in middle */ r = q; /* don't alter q */ while(--r > p) { i = *r; *r = *p; *p++ = i; } } else if(*fmt == 'c') *q++ = *dp++; else *q++ = *fmt; /* now output the saved string */ for(p = tmp; p < q; ++p) { if(buf) { *s++ = *p; } else { DiagPutChar(*p); } if((*p) == '\n') { DiagPutChar('\r'); } } } } if(buf) *s = '\0'; return (s - buf); } u32 DiagPrintfPatch( IN const char *fmt, ... ) { (void)VSprintfPatch(0, fmt, ((const int *)&fmt)+1); return 1; } u32 DiagSPrintfPatch( IN u8 *buf, IN const char *fmt, ... ) { (void)VSprintfPatch((char*)buf, fmt, ((const int *)&fmt)+1); return 1; } #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/platform/stdlib_patch.c
C
apache-2.0
16,376
/* * SSL/TLS interface definition * Copyright (c) 2004-2013, Jouni Malinen <j@w1.fi> * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #ifndef TLS_H #define TLS_H struct tls_connection; struct tls_random { const u8 *client_random; size_t client_random_len; const u8 *server_random; size_t server_random_len; }; enum tls_event { TLS_CERT_CHAIN_SUCCESS, TLS_CERT_CHAIN_FAILURE, TLS_PEER_CERTIFICATE, TLS_ALERT }; /* * Note: These are used as identifier with external programs and as such, the * values must not be changed. */ enum tls_fail_reason { TLS_FAIL_UNSPECIFIED = 0, TLS_FAIL_UNTRUSTED = 1, TLS_FAIL_REVOKED = 2, TLS_FAIL_NOT_YET_VALID = 3, TLS_FAIL_EXPIRED = 4, TLS_FAIL_SUBJECT_MISMATCH = 5, TLS_FAIL_ALTSUBJECT_MISMATCH = 6, TLS_FAIL_BAD_CERTIFICATE = 7, TLS_FAIL_SERVER_CHAIN_PROBE = 8, TLS_FAIL_DOMAIN_SUFFIX_MISMATCH = 9, TLS_FAIL_DOMAIN_MISMATCH = 10, }; #define TLS_MAX_ALT_SUBJECT 10 union tls_event_data { struct { int depth; const char *subject; enum tls_fail_reason reason; const char *reason_txt; const struct wpabuf *cert; } cert_fail; struct { int depth; const char *subject; const struct wpabuf *cert; const u8 *hash; size_t hash_len; const char *altsubject[TLS_MAX_ALT_SUBJECT]; int num_altsubject; } peer_cert; struct { int is_local; const char *type; const char *description; } alert; }; struct tls_config { const char *opensc_engine_path; const char *pkcs11_engine_path; const char *pkcs11_module_path; int fips_mode; int cert_in_cb; const char *openssl_ciphers; unsigned int tls_session_lifetime; void (*event_cb)(void *ctx, enum tls_event ev, union tls_event_data *data); void *cb_ctx; }; #define TLS_CONN_ALLOW_SIGN_RSA_MD5 BIT(0) #define TLS_CONN_DISABLE_TIME_CHECKS BIT(1) #define TLS_CONN_DISABLE_SESSION_TICKET BIT(2) #define TLS_CONN_REQUEST_OCSP BIT(3) #define TLS_CONN_REQUIRE_OCSP BIT(4) #define TLS_CONN_DISABLE_TLSv1_1 BIT(5) #define TLS_CONN_DISABLE_TLSv1_2 BIT(6) #define TLS_CONN_EAP_FAST BIT(7) #define TLS_CONN_DISABLE_TLSv1_0 BIT(8) /** * struct tls_connection_params - Parameters for TLS connection * @ca_cert: File or reference name for CA X.509 certificate in PEM or DER * format * @ca_cert_blob: ca_cert as inlined data or %NULL if not used * @ca_cert_blob_len: ca_cert_blob length * @ca_path: Path to CA certificates (OpenSSL specific) * @subject_match: String to match in the subject of the peer certificate or * %NULL to allow all subjects * @altsubject_match: String to match in the alternative subject of the peer * certificate or %NULL to allow all alternative subjects * @suffix_match: String to suffix match in the dNSName or CN of the peer * certificate or %NULL to allow all domain names. This may allow subdomains an * wildcard certificates. Each domain name label must have a full match. * @domain_match: String to match in the dNSName or CN of the peer * certificate or %NULL to allow all domain names. This requires a full, * case-insensitive match. * @client_cert: File or reference name for client X.509 certificate in PEM or * DER format * @client_cert_blob: client_cert as inlined data or %NULL if not used * @client_cert_blob_len: client_cert_blob length * @private_key: File or reference name for client private key in PEM or DER * format (traditional format (RSA PRIVATE KEY) or PKCS#8 (PRIVATE KEY) * @private_key_blob: private_key as inlined data or %NULL if not used * @private_key_blob_len: private_key_blob length * @private_key_passwd: Passphrase for decrypted private key, %NULL if no * passphrase is used. * @dh_file: File name for DH/DSA data in PEM format, or %NULL if not used * @dh_blob: dh_file as inlined data or %NULL if not used * @dh_blob_len: dh_blob length * @engine: 1 = use engine (e.g., a smartcard) for private key operations * (this is OpenSSL specific for now) * @engine_id: engine id string (this is OpenSSL specific for now) * @ppin: pointer to the pin variable in the configuration * (this is OpenSSL specific for now) * @key_id: the private key's id when using engine (this is OpenSSL * specific for now) * @cert_id: the certificate's id when using engine * @ca_cert_id: the CA certificate's id when using engine * @openssl_ciphers: OpenSSL cipher configuration * @flags: Parameter options (TLS_CONN_*) * @ocsp_stapling_response: DER encoded file with cached OCSP stapling response * or %NULL if OCSP is not enabled * * TLS connection parameters to be configured with tls_connection_set_params() * and tls_global_set_params(). * * Certificates and private key can be configured either as a reference name * (file path or reference to certificate store) or by providing the same data * as a pointer to the data in memory. Only one option will be used for each * field. */ struct tls_connection_params { const char *ca_cert; const u8 *ca_cert_blob; size_t ca_cert_blob_len; const char *ca_path; const char *subject_match; const char *altsubject_match; const char *suffix_match; const char *domain_match; const char *client_cert; const u8 *client_cert_blob; size_t client_cert_blob_len; const char *private_key; const u8 *private_key_blob; size_t private_key_blob_len; const char *private_key_passwd; const char *dh_file; const u8 *dh_blob; size_t dh_blob_len; /* OpenSSL specific variables */ int engine; const char *engine_id; const char *pin; const char *key_id; const char *cert_id; const char *ca_cert_id; const char *openssl_ciphers; unsigned int flags; const char *ocsp_stapling_response; }; /** * tls_init - Initialize TLS library * @conf: Configuration data for TLS library * Returns: Context data to be used as tls_ctx in calls to other functions, * or %NULL on failure. * * Called once during program startup and once for each RSN pre-authentication * session. In other words, there can be two concurrent TLS contexts. If global * library initialization is needed (i.e., one that is shared between both * authentication types), the TLS library wrapper should maintain a reference * counter and do global initialization only when moving from 0 to 1 reference. */ //ssl_context * tls_init(const struct tls_config *conf); void * tls_init(const struct tls_config *conf); /** * tls_deinit - Deinitialize TLS library * @tls_ctx: TLS context data from tls_init() * * Called once during program shutdown and once for each RSN pre-authentication * session. If global library deinitialization is needed (i.e., one that is * shared between both authentication types), the TLS library wrapper should * maintain a reference counter and do global deinitialization only when moving * from 1 to 0 references. */ void tls_deinit(void *tls_ctx); /** * tls_get_errors - Process pending errors * @tls_ctx: TLS context data from tls_init() * Returns: Number of found error, 0 if no errors detected. * * Process all pending TLS errors. */ int tls_get_errors(void *tls_ctx); /** * tls_connection_init - Initialize a new TLS connection * @tls_ctx: TLS context data from tls_init() * Returns: Connection context data, conn for other function calls */ struct tls_connection * tls_connection_init(void *tls_ctx); /** * tls_connection_deinit - Free TLS connection data * @tls_ctx: TLS context data from tls_init() * @conn: Connection context data from tls_connection_init() * * Release all resources allocated for TLS connection. */ void tls_connection_deinit(void *tls_ctx, struct tls_connection *conn); /** * tls_connection_established - Has the TLS connection been completed? * @tls_ctx: TLS context data from tls_init() * @conn: Connection context data from tls_connection_init() * Returns: 1 if TLS connection has been completed, 0 if not. */ int tls_connection_established(void *tls_ctx, struct tls_connection *conn); /** * tls_connection_shutdown - Shutdown TLS connection * @tls_ctx: TLS context data from tls_init() * @conn: Connection context data from tls_connection_init() * Returns: 0 on success, -1 on failure * * Shutdown current TLS connection without releasing all resources. New * connection can be started by using the same conn without having to call * tls_connection_init() or setting certificates etc. again. The new * connection should try to use session resumption. */ int tls_connection_shutdown(void *tls_ctx, struct tls_connection *conn); enum { TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN = -4, TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED = -3, TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED = -2 }; /** * tls_connection_set_params - Set TLS connection parameters * @tls_ctx: TLS context data from tls_init() * @conn: Connection context data from tls_connection_init() * @params: Connection parameters * Returns: 0 on success, -1 on failure, * TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED (-2) on error causing PKCS#11 engine * failure, or * TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED (-3) on failure to verify the * PKCS#11 engine private key, or * TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN (-4) on PIN error causing PKCS#11 engine * failure. */ int __must_check tls_connection_set_params(void *tls_ctx, struct tls_connection *conn, const struct tls_connection_params *params); /** * tls_global_set_params - Set TLS parameters for all TLS connection * @tls_ctx: TLS context data from tls_init() * @params: Global TLS parameters * Returns: 0 on success, -1 on failure, * TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED (-2) on error causing PKCS#11 engine * failure, or * TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED (-3) on failure to verify the * PKCS#11 engine private key, or * TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN (-4) on PIN error causing PKCS#11 engine * failure. */ int __must_check tls_global_set_params( void *tls_ctx, const struct tls_connection_params *params); /** * tls_global_set_verify - Set global certificate verification options * @tls_ctx: TLS context data from tls_init() * @check_crl: 0 = do not verify CRLs, 1 = verify CRL for the user certificate, * 2 = verify CRL for all certificates * Returns: 0 on success, -1 on failure */ int __must_check tls_global_set_verify(void *tls_ctx, int check_crl); /** * tls_connection_set_verify - Set certificate verification options * @tls_ctx: TLS context data from tls_init() * @conn: Connection context data from tls_connection_init() * @verify_peer: 1 = verify peer certificate * @flags: Connection flags (TLS_CONN_*) * @session_ctx: Session caching context or %NULL to use default * @session_ctx_len: Length of @session_ctx in bytes. * Returns: 0 on success, -1 on failure */ int __must_check tls_connection_set_verify(void *tls_ctx, struct tls_connection *conn, int verify_peer, unsigned int flags, const u8 *session_ctx, size_t session_ctx_len); /** * tls_connection_get_random - Get random data from TLS connection * @tls_ctx: TLS context data from tls_init() * @conn: Connection context data from tls_connection_init() * @data: Structure of client/server random data (filled on success) * Returns: 0 on success, -1 on failure */ int __must_check tls_connection_get_random(void *tls_ctx, struct tls_connection *conn, struct tls_random *data); /** * tls_connection_prf - Use TLS-PRF to derive keying material * @tls_ctx: TLS context data from tls_init() * @conn: Connection context data from tls_connection_init() * @label: Label (e.g., description of the key) for PRF * @server_random_first: seed is 0 = client_random|server_random, * 1 = server_random|client_random * @skip_keyblock: Skip TLS key block from the beginning of PRF output * @out: Buffer for output data from TLS-PRF * @out_len: Length of the output buffer * Returns: 0 on success, -1 on failure * * tls_connection_prf() is required so that further keying material can be * derived from the master secret. Example implementation of this function is in * tls_prf_sha1_md5() when it is called with seed set to * client_random|server_random (or server_random|client_random). For TLSv1.2 and * newer, a different PRF is needed, though. */ int __must_check tls_connection_prf(void *tls_ctx, struct tls_connection *conn, const char *label, int server_random_first, int skip_keyblock, u8 *out, size_t out_len); /** * tls_connection_handshake - Process TLS handshake (client side) * @tls_ctx: TLS context data from tls_init() * @conn: Connection context data from tls_connection_init() * @in_data: Input data from TLS server * @appl_data: Pointer to application data pointer, or %NULL if dropped * Returns: Output data, %NULL on failure * * The caller is responsible for freeing the returned output data. If the final * handshake message includes application data, this is decrypted and * appl_data (if not %NULL) is set to point this data. The caller is * responsible for freeing appl_data. * * This function is used during TLS handshake. The first call is done with * in_data == %NULL and the library is expected to return ClientHello packet. * This packet is then send to the server and a response from server is given * to TLS library by calling this function again with in_data pointing to the * TLS message from the server. * * If the TLS handshake fails, this function may return %NULL. However, if the * TLS library has a TLS alert to send out, that should be returned as the * output data. In this case, tls_connection_get_failed() must return failure * (> 0). * * tls_connection_established() should return 1 once the TLS handshake has been * completed successfully. */ struct wpabuf * tls_connection_handshake(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data, struct wpabuf **appl_data); struct wpabuf * tls_connection_handshake2(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data, struct wpabuf **appl_data, int *more_data_needed); /** * tls_connection_server_handshake - Process TLS handshake (server side) * @tls_ctx: TLS context data from tls_init() * @conn: Connection context data from tls_connection_init() * @in_data: Input data from TLS peer * @appl_data: Pointer to application data pointer, or %NULL if dropped * Returns: Output data, %NULL on failure * * The caller is responsible for freeing the returned output data. */ struct wpabuf * tls_connection_server_handshake(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data, struct wpabuf **appl_data); /** * tls_connection_encrypt - Encrypt data into TLS tunnel * @tls_ctx: TLS context data from tls_init() * @conn: Connection context data from tls_connection_init() * @in_data: Plaintext data to be encrypted * Returns: Encrypted TLS data or %NULL on failure * * This function is used after TLS handshake has been completed successfully to * send data in the encrypted tunnel. The caller is responsible for freeing the * returned output data. */ struct wpabuf * tls_connection_encrypt(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data); /** * tls_connection_decrypt - Decrypt data from TLS tunnel * @tls_ctx: TLS context data from tls_init() * @conn: Connection context data from tls_connection_init() * @in_data: Encrypted TLS data * Returns: Decrypted TLS data or %NULL on failure * * This function is used after TLS handshake has been completed successfully to * receive data from the encrypted tunnel. The caller is responsible for * freeing the returned output data. */ struct wpabuf * tls_connection_decrypt(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data); struct wpabuf * tls_connection_decrypt2(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data, int *more_data_needed); /** * tls_connection_resumed - Was session resumption used * @tls_ctx: TLS context data from tls_init() * @conn: Connection context data from tls_connection_init() * Returns: 1 if current session used session resumption, 0 if not */ int tls_connection_resumed(void *tls_ctx, struct tls_connection *conn); enum { TLS_CIPHER_NONE, TLS_CIPHER_RC4_SHA /* 0x0005 */, TLS_CIPHER_AES128_SHA /* 0x002f */, TLS_CIPHER_RSA_DHE_AES128_SHA /* 0x0031 */, TLS_CIPHER_ANON_DH_AES128_SHA /* 0x0034 */ }; /** * tls_connection_set_cipher_list - Configure acceptable cipher suites * @tls_ctx: TLS context data from tls_init() * @conn: Connection context data from tls_connection_init() * @ciphers: Zero (TLS_CIPHER_NONE) terminated list of allowed ciphers * (TLS_CIPHER_*). * Returns: 0 on success, -1 on failure */ int __must_check tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn, u8 *ciphers); /** * tls_get_version - Get the current TLS version number * @tls_ctx: TLS context data from tls_init() * @conn: Connection context data from tls_connection_init() * @buf: Buffer for returning the TLS version number * @buflen: buf size * Returns: 0 on success, -1 on failure * * Get the currently used TLS version number. */ int __must_check tls_get_version(void *tls_ctx, struct tls_connection *conn, char *buf, size_t buflen); /** * tls_get_cipher - Get current cipher name * @tls_ctx: TLS context data from tls_init() * @conn: Connection context data from tls_connection_init() * @buf: Buffer for the cipher name * @buflen: buf size * Returns: 0 on success, -1 on failure * * Get the name of the currently used cipher. */ int __must_check tls_get_cipher(void *tls_ctx, struct tls_connection *conn, char *buf, size_t buflen); /** * tls_connection_enable_workaround - Enable TLS workaround options * @tls_ctx: TLS context data from tls_init() * @conn: Connection context data from tls_connection_init() * Returns: 0 on success, -1 on failure * * This function is used to enable connection-specific workaround options for * buffer SSL/TLS implementations. */ int __must_check tls_connection_enable_workaround(void *tls_ctx, struct tls_connection *conn); /** * tls_connection_client_hello_ext - Set TLS extension for ClientHello * @tls_ctx: TLS context data from tls_init() * @conn: Connection context data from tls_connection_init() * @ext_type: Extension type * @data: Extension payload (%NULL to remove extension) * @data_len: Extension payload length * Returns: 0 on success, -1 on failure */ int __must_check tls_connection_client_hello_ext(void *tls_ctx, struct tls_connection *conn, int ext_type, const u8 *data, size_t data_len); /** * tls_connection_get_failed - Get connection failure status * @tls_ctx: TLS context data from tls_init() * @conn: Connection context data from tls_connection_init() * * Returns >0 if connection has failed, 0 if not. */ int tls_connection_get_failed(void *tls_ctx, struct tls_connection *conn); /** * tls_connection_get_read_alerts - Get connection read alert status * @tls_ctx: TLS context data from tls_init() * @conn: Connection context data from tls_connection_init() * Returns: Number of times a fatal read (remote end reported error) has * happened during this connection. */ int tls_connection_get_read_alerts(void *tls_ctx, struct tls_connection *conn); /** * tls_connection_get_write_alerts - Get connection write alert status * @tls_ctx: TLS context data from tls_init() * @conn: Connection context data from tls_connection_init() * Returns: Number of times a fatal write (locally detected error) has happened * during this connection. */ int tls_connection_get_write_alerts(void *tls_ctx, struct tls_connection *conn); typedef int (*tls_session_ticket_cb) (void *ctx, const u8 *ticket, size_t len, const u8 *client_random, const u8 *server_random, u8 *master_secret); int __must_check tls_connection_set_session_ticket_cb( void *tls_ctx, struct tls_connection *conn, tls_session_ticket_cb cb, void *ctx); void tls_connection_set_log_cb(struct tls_connection *conn, void (*log_cb)(void *ctx, const char *msg), void *ctx); #define TLS_BREAK_VERIFY_DATA BIT(0) #define TLS_BREAK_SRV_KEY_X_HASH BIT(1) #define TLS_BREAK_SRV_KEY_X_SIGNATURE BIT(2) #define TLS_DHE_PRIME_511B BIT(3) #define TLS_DHE_PRIME_767B BIT(4) #define TLS_DHE_PRIME_15 BIT(5) #define TLS_DHE_PRIME_58B BIT(6) #define TLS_DHE_NON_PRIME BIT(7) void tls_connection_set_test_flags(struct tls_connection *conn, u32 flags); int tls_get_library_version(char *buf, size_t buf_len); void tls_connection_set_success_data(struct tls_connection *conn, struct wpabuf *data); void tls_connection_set_success_data_resumed(struct tls_connection *conn); const struct wpabuf * tls_connection_get_success_data(struct tls_connection *conn); void tls_connection_remove_session(struct tls_connection *conn); #endif /* TLS_H */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/rtw_wpa_supplicant/src/crypto/tls.h
C
apache-2.0
20,916
/* * SSL/TLS interface functions for PolarSSL * Copyright (c) 2004-2009, Jouni Malinen <j@w1.fi> * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #include "utils/includes.h" #include "utils/common.h" #include "tls.h" #define DEBUG_LEVEL 0 // For debug: 5 extern int max_buf_bio_size; int ErrorCnt = 0; struct tls_connection { // buffer BIO info (ptr, offset, len) struct buf_BIO *buf_in; struct buf_BIO *buf_out; u8 client_random[32]; u8 server_random[32]; int (*tls_prf)(const unsigned char *, size_t, const char *, const unsigned char *, size_t, unsigned char *, size_t); }; // buffer BIO info (ptr, len, len left), might improve the performance if using circular buffer struct buf_BIO{ unsigned char *ptr; int len; int len_left; }; /* used to test the buffer I/O read write functions int test_BIO(struct tls_connection * conn){ // test char * a = "abcdefg"; printf("p: %d %d\n", conn->buf_out->len, conn->buf_out->len_left); buf_write(conn->buf_out, a, 8); printf("buf: %s\n", conn->buf_out->ptr); char b[5]; char c[4]; buf_read(conn->buf_out, b, 4); printf("buf: %s\n", conn->buf_out->ptr); b[4] = '\0'; printf("%s\n", b); buf_read(conn->buf_out, c, 2); printf("buf: %s\n", conn->buf_out->ptr); c[3] = '\0'; printf("%s\n", c); buf_write(conn->buf_out, a, 8); char d[10]; buf_read(conn->buf_out, d, 10); d[1] = 'x'; printf("%s\n", d); } */ static volatile size_t min_heap_size = 0; static int my_random(void *p_rng, unsigned char *output, size_t output_len) { /* To avoid gcc warnings */ ( void ) p_rng; rtw_get_random_bytes(output, output_len); return 0; } void my_debug(void *ctx, int level, const char *str) { /* To avoid gcc warnings */ ( void ) ctx; if(level <= DEBUG_LEVEL) { printf("\n\r%s", str); } } #if CONFIG_USE_POLARSSL #include <polarssl/ssl.h> #include <polarssl/memory.h> void* eap_my_malloc(size_t size) { void *ptr = pvPortMalloc(size); size_t current_heap_size = xPortGetFreeHeapSize(); if((current_heap_size < min_heap_size) || (min_heap_size == 0)) min_heap_size = current_heap_size; return ptr; } int buf_init(struct tls_connection * conn){ conn->buf_in = (struct buf_BIO *)os_zalloc(sizeof(struct buf_BIO)); if(conn->buf_in == NULL){ return -1; } conn->buf_in->ptr = (unsigned char *)os_zalloc(max_buf_bio_size); if(conn->buf_in->ptr == NULL){ return -1; } conn->buf_out = (struct buf_BIO *)os_zalloc(sizeof(struct buf_BIO)); if(conn->buf_out == NULL){ return -1; } conn->buf_out->ptr = (unsigned char *)os_zalloc(max_buf_bio_size); if(conn->buf_out->ptr == NULL){ return -1; } conn->buf_in->len = 0; conn->buf_out->len = 0; conn->buf_in->len_left = max_buf_bio_size; conn->buf_out->len_left = max_buf_bio_size; return 1; } int buf_read(void *ctx, unsigned char *buf, size_t len){ struct buf_BIO *bio = ctx; size_t read_len = len; wpa_printf(MSG_DEBUG, "TLS: buffer read size: %d", len); if(bio->len == 0){ return 0; } if(bio->len < read_len) read_len = bio->len; os_memcpy(buf, bio->ptr, read_len); bio->len -= read_len; bio->len_left += read_len; os_memset(bio->ptr, 0, read_len); os_memmove(bio->ptr, bio->ptr + read_len, bio->len); //wpa_printf(MSG_INFO, "TLS: buffer read finish"); return read_len; } int buf_write(void *ctx, const unsigned char * buf, size_t len){ struct buf_BIO *bio = ctx; wpa_printf(MSG_DEBUG, "TLS: buffer write size: %d", len); if(bio->len_left < len){ wpa_printf(MSG_INFO, "TLS: failed to write buffer due to size not enough, required size: %d", len); return -1; } os_memcpy(bio->ptr + bio->len, buf, len); bio->len += len; bio->len_left -= len; //wpa_printf(MSG_INFO, "TLS: buffer write finish"); return len; } void buf_clear(void *ctx, int isIn){ struct buf_BIO *bio = ctx; if(isIn == 1) wpa_printf(MSG_DEBUG, "TLS: clear input buffer, len: %d", bio->len); else wpa_printf(MSG_DEBUG, "TLS: clear output buffer, len: %d", bio->len); os_memset(bio->ptr, 0, max_buf_bio_size); bio->len = 0; bio->len_left = max_buf_bio_size; } void * tls_init(const struct tls_config *conf) { ssl_context *ssl; int ret = -1; memory_set_own(eap_my_malloc, vPortFree); ssl = os_zalloc(sizeof(*ssl)); if(ssl == NULL) return NULL; if((ret = ssl_init(ssl)) != 0){ wpa_printf(MSG_INFO, "TLS: ssl_init() failed, ret: %d", ret); return NULL; } return ssl; } void tls_deinit(void *ssl_ctx) { if(ssl_ctx != NULL){ ssl_free(ssl_ctx); os_free(ssl_ctx, 0); ssl_ctx = NULL; } } int tls_get_errors(void *tls_ctx) { wpa_printf(MSG_DEBUG, "TLS: tls_get_errors"); return ErrorCnt; } struct tls_connection * tls_connection_init(void *tls_ctx) { ssl_context *ssl = tls_ctx; struct tls_connection *conn; conn = os_zalloc(sizeof(*conn)); if(conn == NULL) return NULL; conn->tls_prf = NULL; // init buf in conn if(buf_init(conn) < 0){ wpa_printf(MSG_INFO, "TLS: buf_new() failed"); tls_connection_deinit(tls_ctx, conn); return NULL; } //test_BIO(conn); ssl_set_endpoint(ssl, SSL_IS_CLIENT); ssl_set_authmode(ssl, SSL_VERIFY_NONE); ssl_set_rng(ssl, my_random, NULL); ssl_set_bio(ssl, buf_read, conn->buf_in, buf_write, conn->buf_out); ssl_set_dbg(ssl, my_debug, NULL); #if defined(POLARSSL_DEBUG_C) debug_set_threshold(DEBUG_LEVEL); #endif ErrorCnt = 0; return conn; } void tls_connection_deinit(void *tls_ctx, struct tls_connection *conn) { wpa_printf(MSG_DEBUG, "TLS: tls_connection_deinit start"); if(conn != NULL){ os_free(conn->buf_in->ptr, 0); os_free(conn->buf_out->ptr, 0); os_free(conn->buf_in, 0); os_free(conn->buf_out, 0); os_free(conn, 0); conn = NULL; } ErrorCnt = 0; } int tls_connection_established(void *tls_ctx, struct tls_connection *conn) { ssl_context *ssl = tls_ctx; if(ssl->state == SSL_HANDSHAKE_OVER){ wpa_printf(MSG_DEBUG, "TLS: Check conn established.. true"); return 1; } else{ wpa_printf(MSG_DEBUG, "TLS: Check conn established.. false"); return 0; } } int tls_connection_shutdown(void *tls_ctx, struct tls_connection *conn) { if(conn == NULL) return -1; tls_connection_deinit(tls_ctx, conn); return -1; } int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn, const struct tls_connection_params *params) { wpa_printf(MSG_DEBUG, "TLS: tls_connection_set_params"); //return -1; return 0; } int tls_global_set_params(void *tls_ctx, const struct tls_connection_params *params) { wpa_printf(MSG_DEBUG, "TLS: tls_global_set_params"); return -1; } int tls_global_set_verify(void *tls_ctx, int check_crl) { wpa_printf(MSG_DEBUG, "TLS: tls_global_set_verify"); return -1; } int tls_connection_set_verify(void *tls_ctx, struct tls_connection *conn, int verify_peer, unsigned int flags, const u8 *session_ctx, size_t session_ctx_len) { wpa_printf(MSG_DEBUG, "TLS: tls_connection_set_verify"); return -1; } int tls_connection_get_random(void *tls_ctx, struct tls_connection *conn, struct tls_random *keys) { ssl_context *ssl = tls_ctx; if(ssl == NULL || conn == NULL || keys == NULL) return -1; os_memset(keys, 0, sizeof(*keys)); keys->client_random = conn->client_random; keys->client_random_len = 32; keys->server_random = conn->server_random; keys->server_random_len = 32; return 0; } // return 0: success int tls_connection_prf(void *tls_ctx, struct tls_connection *conn, const char *label, int server_random_first, int skip_keyblock, u8 *out, size_t out_len) { //wpa_printf(MSG_DEBUG, "TLS: tls_connection_prf"); ssl_context *ssl = tls_ctx; ssl_session *session = ssl->session; int ret = 1; unsigned char *rnd; rnd = (unsigned char *)os_zalloc(64); if(!rnd){ wpa_printf(MSG_INFO, "TLS: rnd buf alloc failed"); return ret; } os_memcpy(rnd, conn->client_random, 32); os_memcpy(rnd + 32, conn->server_random, 32); // dump_buf(conn->client_random, 32); // dump_buf(conn->server_random, 32); // dump_buf(session->master, 48); if(conn->tls_prf != NULL) ret = conn->tls_prf( session->master, 48, label, rnd, 64, out, out_len ); os_free(rnd, 0); return ret; } struct wpabuf * tls_connection_handshake(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data, struct wpabuf **appl_data) { ssl_context *ssl = tls_ctx; struct wpabuf * out_data; int size; int ret = 0; // clear input and output buffer buf_clear(conn->buf_out, 0); buf_clear(conn->buf_in, 1); // write input data to input buffer if(in_data && wpabuf_len(in_data) > 0 && buf_write(conn->buf_in, wpabuf_head(in_data), wpabuf_len(in_data)) < 0){ return NULL; } while( ssl->state != SSL_HANDSHAKE_OVER ) { wpa_printf(MSG_INFO, "TLS: connection handshake, state: %d", ssl->state); //printf("\nTLS: connection handshake, state: %d\n", ssl->state); ret = ssl_handshake_step( ssl ); // keep the client random & server random for eap further use if(ssl->state == SSL_CLIENT_CERTIFICATE){ os_memcpy(conn->client_random, ssl->handshake->randbytes, 32); os_memcpy(conn->server_random, ssl->handshake->randbytes + 32, 32); } // free memory since server cert has been verified else if(ssl->state == SSL_SERVER_KEY_EXCHANGE){ eap_server_cert_free(); } // free memory since client cert has been set else if(ssl->state == SSL_CLIENT_CHANGE_CIPHER_SPEC){ eap_client_cert_free(); } // keep the tls_prf function pointer else if(ssl->state == SSL_SERVER_CHANGE_CIPHER_SPEC) conn->tls_prf = ssl->handshake->tls_prf; // time to send data out or read data in if(ret != 0){ // need to read more data if(ret == POLARSSL_ERR_SSL_CONN_EOF) break; // handshake got error else{ //wpa_printf(MSG_INFO, "TLS: connection handshake failed, ret: %d", ret); printf("\nTLS: connection handshake failed, ret: %d\n", ret); ErrorCnt = 1; return NULL; } } } // store output buffer to out_data size = conn->buf_out->len; out_data = wpabuf_alloc(size); if(out_data == NULL){ wpa_printf(MSG_INFO, "SSL: Failed to allocate memory for " "handshake output (%d bytes)", size); return NULL; } buf_read(conn->buf_out, out_data->buf, size); wpabuf_put(out_data, size); //dump_buf(out_data->buf, size); // clear input and output buffer buf_clear(conn->buf_out, 0); buf_clear(conn->buf_in, 1); return out_data; } struct wpabuf * tls_connection_server_handshake(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data, struct wpabuf **appl_data) { wpa_printf(MSG_DEBUG, "TLS: tls_connection_server_handshake"); return NULL; } struct wpabuf * tls_connection_encrypt(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data) { wpa_printf(MSG_DEBUG, "TLS: tls_connection_encrypt"); ssl_context *ssl = tls_ctx; struct wpabuf * out_data; int size; int res; if(conn == NULL) return NULL; res = ssl_write(ssl, wpabuf_head(in_data), wpabuf_len(in_data)); if(res < 0){ wpa_printf(MSG_INFO, "TLS: tls_connection_encrypt failed - ssl_write"); return NULL; } /* Read encrypted data to be sent to the server */ size = wpabuf_len(in_data) + 300; out_data = wpabuf_alloc(size); if(out_data == NULL){ wpa_printf(MSG_INFO, "TLS: Failed to allocate memory for " "encrypted output (%d bytes)", size); return NULL; } res = buf_read(conn->buf_out, out_data->buf, size); if(res < 0){ wpa_printf(MSG_INFO, "TLS: tls_connection_decrypt failed - buf_read"); wpabuf_free(out_data); return NULL; } wpabuf_put(out_data, res); // clear input and output buffer buf_clear(conn->buf_out, 0); buf_clear(conn->buf_in, 1); return out_data; } struct wpabuf * tls_connection_decrypt(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data) { wpa_printf(MSG_DEBUG, "TLS: tls_connection_decrypt"); ssl_context *ssl = tls_ctx; struct wpabuf * out_data; int size; int res; // write input data to input buffer if(in_data && wpabuf_len(in_data) > 0 && buf_write(conn->buf_in, wpabuf_head(in_data), wpabuf_len(in_data)) < 0){ wpa_printf(MSG_INFO, "TLS: tls_connection_decrypt failed - buf_write"); return NULL; } /* Read decrypted data for further processing */ /* * refer to tls_openssl.c * * Even though we try to disable TLS compression, it is possible that * this cannot be done with all TLS libraries. Add extra buffer space * to handle the possibility of the decrypted data being longer than * input data. */ size = (wpabuf_len(in_data) + 500) * 3; out_data = wpabuf_alloc(size); if(out_data == NULL){ wpa_printf(MSG_INFO, "TLS: Failed to allocate memory for " "decrypted output (%d bytes)", size); return NULL; } res = ssl_read(ssl, out_data->buf, size); if(res < 0){ wpa_printf(MSG_INFO, "TLS: tls_connection_decrypt failed - ssl_read"); wpabuf_free(out_data); return NULL; } wpabuf_put(out_data, res); //dump_buf(out_data->buf, size); // clear input and output buffer buf_clear(conn->buf_out, 0); buf_clear(conn->buf_in, 1); return out_data; } #elif CONFIG_USE_MBEDTLS /* CONFIG_USE_POLARSSL */ #include <mbedtls/ssl.h> #include <mbedtls/net.h> #include <mbedtls/ssl_internal.h> #include <mbedtls/debug.h> struct buf_BIO *conn_buf_out, *conn_buf_in; int buf_init(struct tls_connection * conn){ conn->buf_in = (struct buf_BIO *)os_zalloc(sizeof(struct buf_BIO)); if(conn->buf_in == NULL){ return -1; } conn->buf_in->ptr = (unsigned char *)os_zalloc(max_buf_bio_size); if(conn->buf_in->ptr == NULL){ return -1; } conn->buf_out = (struct buf_BIO *)os_zalloc(sizeof(struct buf_BIO)); if(conn->buf_out == NULL){ return -1; } conn->buf_out->ptr = (unsigned char *)os_zalloc(max_buf_bio_size); if(conn->buf_out->ptr == NULL){ return -1; } conn->buf_in->len = 0; conn->buf_out->len = 0; conn->buf_in->len_left = max_buf_bio_size; conn->buf_out->len_left = max_buf_bio_size; conn_buf_out = conn->buf_out; conn_buf_in = conn->buf_in; return 1; } int buf_read_store(void *ctx, unsigned char *buf, size_t len){ struct buf_BIO *bio = ctx; size_t read_len = len; wpa_printf(MSG_DEBUG, "TLS: buffer read size: %d", len); if(bio->len == 0){ return 0; } if((size_t)bio->len < read_len) read_len = bio->len; os_memcpy(buf, bio->ptr, read_len); bio->len -= read_len; bio->len_left += read_len; os_memset(bio->ptr, 0, read_len); os_memmove(bio->ptr, bio->ptr + read_len, bio->len); //wpa_printf(MSG_INFO, "TLS: buffer read finish"); return read_len; } int buf_write_store(void *ctx, const unsigned char * buf, size_t len){ struct buf_BIO *bio = ctx; wpa_printf(MSG_DEBUG, "TLS: buffer write size: %d", len); if((size_t)bio->len_left < len){ wpa_printf(MSG_INFO, "TLS: failed to write buffer due to size not enough, required size: %d", len); return -1; } os_memcpy(bio->ptr + bio->len, buf, len); bio->len += len; bio->len_left -= len; //wpa_printf(MSG_INFO, "TLS: buffer write finish"); return len; } int buf_read(void *ctx, unsigned char *buf, size_t len) { /* To avoid gcc warnins */ ( void ) ctx; struct buf_BIO *bio = conn_buf_in; size_t read_len = len; wpa_printf(MSG_DEBUG, "TLS: buffer read size: %d", len); if(bio->len == 0){ return 0; } if((size_t)bio->len < read_len) read_len = bio->len; os_memcpy(buf, bio->ptr, read_len); bio->len -= read_len; bio->len_left += read_len; os_memset(bio->ptr, 0, read_len); os_memmove(bio->ptr, bio->ptr + read_len, bio->len); //wpa_printf(MSG_INFO, "TLS: buffer read finish"); return read_len; } int buf_write(void *ctx, const unsigned char * buf, size_t len) { /* To avoid gcc warnins */ ( void ) ctx; struct buf_BIO *bio = conn_buf_out; wpa_printf(MSG_DEBUG, "TLS: buffer write size: %d", len); if((size_t)bio->len_left < len){ wpa_printf(MSG_INFO, "TLS: failed to write buffer due to size not enough, required size: %d", len); return -1; } os_memcpy(bio->ptr + bio->len, buf, len); bio->len += len; bio->len_left -= len; //wpa_printf(MSG_INFO, "TLS: buffer write finish"); return len; } void buf_clear(void *ctx, int isIn){ struct buf_BIO *bio = ctx; if(isIn == 1) wpa_printf(MSG_DEBUG, "TLS: clear input buffer, len: %d", bio->len); else wpa_printf(MSG_DEBUG, "TLS: clear output buffer, len: %d", bio->len); os_memset(bio->ptr, 0, max_buf_bio_size); bio->len = 0; bio->len_left = max_buf_bio_size; } static void* my_calloc(size_t nelements, size_t elementSize) { size_t size; void *ptr = NULL; size = nelements * elementSize; ptr = pvPortMalloc(size); if(ptr) memset(ptr, 0, size); return ptr; } struct eap_tls{ void *ssl; void *conf; void *fd; }; extern int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ),void (*free_func)( void * ) ); void * tls_init(const struct tls_config *conf) { /* To avoid gcc warnings */ ( void ) conf; struct eap_tls *tls_context; mbedtls_platform_set_calloc_free(my_calloc, vPortFree); tls_context = os_zalloc(sizeof(struct eap_tls)); tls_context->ssl = os_zalloc(sizeof(mbedtls_ssl_context)); tls_context->conf = os_zalloc(sizeof(mbedtls_ssl_config)); tls_context->fd = os_zalloc(sizeof(mbedtls_net_context)); if((tls_context == NULL)||(tls_context->ssl == NULL)||(tls_context->conf == NULL)||(tls_context->fd == NULL)) return NULL; mbedtls_net_init(tls_context->fd); mbedtls_ssl_init(tls_context->ssl); mbedtls_ssl_config_init(tls_context->conf); return tls_context; } void tls_deinit(void *ssl_ctx) { if(ssl_ctx != NULL){ struct eap_tls *tls_context = (struct eap_tls *) ssl_ctx; mbedtls_net_free(tls_context->fd); mbedtls_ssl_free(tls_context->ssl); mbedtls_ssl_config_free(tls_context->conf); os_free(ssl_ctx, 0); ssl_ctx = NULL; } } int tls_get_errors(void *tls_ctx) { /* To avoid gcc warnings */ ( void ) tls_ctx; wpa_printf(MSG_DEBUG, "TLS: tls_get_errors"); return ErrorCnt; } struct tls_connection * tls_connection_init(void *tls_ctx) { volatile int ret; struct eap_tls *tls_context = (struct eap_tls *) tls_ctx; struct tls_connection *conn; conn = os_zalloc(sizeof(*conn)); if(conn == NULL) return NULL; conn->tls_prf = NULL; // init buf in conn if(buf_init(conn) < 0){ wpa_printf(MSG_INFO, "TLS: buf_new() failed"); tls_connection_deinit(tls_ctx, conn); return NULL; } //test_BIO(conn); mbedtls_ssl_set_bio(tls_context->ssl, tls_context->fd, buf_write, buf_read, NULL); if((ret = mbedtls_ssl_config_defaults(tls_context->conf, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT)) != 0) { wpa_printf(MSG_INFO, "TLS: mbedtls_ssl_config_defaults() failed"); return NULL; } mbedtls_ssl_conf_authmode(tls_context->conf, MBEDTLS_SSL_VERIFY_NONE); mbedtls_ssl_conf_rng(tls_context->conf, my_random, NULL); if((ret = mbedtls_ssl_setup(tls_context->ssl, tls_context->conf)) != 0) { wpa_printf(MSG_INFO, "TLS: mbedtls_ssl_setup() failed"); return NULL; } #if defined(MBEDTLS_DEBUG_C) mbedtls_debug_set_threshold(DEBUG_LEVEL); #endif ErrorCnt = 0; return conn; } void tls_connection_deinit(void *tls_ctx, struct tls_connection *conn) { /* To avoid gcc warnings */ ( void ) tls_ctx; wpa_printf(MSG_DEBUG, "TLS: tls_connection_deinit start"); if(conn != NULL){ os_free(conn->buf_in->ptr, 0); os_free(conn->buf_out->ptr, 0); os_free(conn->buf_in, 0); os_free(conn->buf_out, 0); os_free(conn, 0); conn = NULL; } ErrorCnt = 0; } int tls_connection_established(void *tls_ctx, struct tls_connection *conn) { /* To avoid gcc warnings */ ( void ) conn; mbedtls_ssl_context *ssl = ((struct eap_tls *)tls_ctx)->ssl; if(ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER){ wpa_printf(MSG_DEBUG, "TLS: Check conn established.. true"); return 1; } else{ wpa_printf(MSG_DEBUG, "TLS: Check conn established.. false"); return 0; } } int tls_connection_shutdown(void *tls_ctx, struct tls_connection *conn) { if(conn == NULL) return -1; tls_connection_deinit(tls_ctx, conn); return -1; } int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn, const struct tls_connection_params *params) { /* To avoid gcc warnings */ ( void ) tls_ctx; ( void ) conn; ( void ) params; wpa_printf(MSG_DEBUG, "TLS: tls_connection_set_params"); //return -1; return 0; } int tls_global_set_params(void *tls_ctx, const struct tls_connection_params *params) { /* To avoid gcc warnings */ ( void ) params; ( void ) tls_ctx; wpa_printf(MSG_DEBUG, "TLS: tls_global_set_params"); return -1; } int tls_global_set_verify(void *tls_ctx, int check_crl) { /* To avoid gcc warnings */ ( void ) tls_ctx; ( void ) check_crl; wpa_printf(MSG_DEBUG, "TLS: tls_global_set_verify"); return -1; } int tls_connection_set_verify(void *tls_ctx, struct tls_connection *conn, int verify_peer, unsigned int flags, const u8 *session_ctx, size_t session_ctx_len) { /* To avoid gcc warnings */ ( void ) tls_ctx; ( void ) conn; ( void ) verify_peer; ( void ) flags; ( void ) session_ctx; ( void ) session_ctx_len; wpa_printf(MSG_DEBUG, "TLS: tls_connection_set_verify"); return -1; } int tls_connection_get_random(void *tls_ctx, struct tls_connection *conn, struct tls_random *keys) { mbedtls_ssl_context *ssl = ((struct eap_tls *)tls_ctx)->ssl; if(ssl == NULL || conn == NULL || keys == NULL) return -1; os_memset(keys, 0, sizeof(*keys)); keys->client_random = conn->client_random; keys->client_random_len = 32; keys->server_random = conn->server_random; keys->server_random_len = 32; return 0; } // return 0: success int tls_connection_prf(void *tls_ctx, struct tls_connection *conn, const char *label, int server_random_first, int skip_keyblock, u8 *out, size_t out_len) { /* To avoid gcc warnings */ ( void ) server_random_first; ( void ) skip_keyblock; //wpa_printf(MSG_DEBUG, "TLS: tls_connection_prf"); mbedtls_ssl_context *ssl = (( struct eap_tls *)tls_ctx)->ssl; mbedtls_ssl_session *session = ssl->session; int ret = 1; unsigned char *rnd; rnd = (unsigned char *)os_zalloc(64); if(!rnd){ wpa_printf(MSG_INFO, "TLS: rnd buf alloc failed"); return ret; } os_memcpy(rnd, conn->client_random, 32); os_memcpy(rnd + 32, conn->server_random, 32); // dump_buf(conn->client_random, 32); // dump_buf(conn->server_random, 32); // dump_buf(session->master, 48); if(conn->tls_prf != NULL) ret = conn->tls_prf( session->master, 48, label, rnd, 64, out, out_len ); os_free(rnd, 0); return ret; } extern void eap_server_cert_free(void); extern void eap_client_cert_free(void); struct wpabuf * tls_connection_handshake(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data, struct wpabuf **appl_data) { /* To avoid gcc warnings */ ( void ) appl_data; mbedtls_ssl_context *ssl = ((struct eap_tls*)tls_ctx)->ssl; struct wpabuf * out_data; int size; int ret = 0; // clear input and output buffer buf_clear(conn->buf_out, 0); buf_clear(conn->buf_in, 1); // write input data to input buffer if(in_data && wpabuf_len(in_data) > 0 && buf_write_store(conn_buf_in, wpabuf_head(in_data), wpabuf_len(in_data)) < 0){ return NULL; } while( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) { wpa_printf(MSG_INFO, "TLS: connection handshake, state: %d", ssl->state); //printf("\nTLS: connection handshake, state: %d\n", ssl->state); ret = mbedtls_ssl_handshake_step( ssl ); // keep the client random & server random for eap further use if(ssl->state == MBEDTLS_SSL_CLIENT_CERTIFICATE){ os_memcpy(conn->client_random, ssl->handshake->randbytes, 32); os_memcpy(conn->server_random, ssl->handshake->randbytes + 32, 32); } // free memory since server cert has been verified else if(ssl->state == MBEDTLS_SSL_SERVER_KEY_EXCHANGE){ eap_server_cert_free(); } // free memory since client cert has been set else if(ssl->state == MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC){ eap_client_cert_free(); } // keep the tls_prf function pointer else if(ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC) conn->tls_prf = ssl->handshake->tls_prf; // time to send data out or read data in if(ret != 0){ // need to read more data if(ret == MBEDTLS_ERR_SSL_CONN_EOF) break; // handshake got error else{ //wpa_printf(MSG_INFO, "TLS: connection handshake failed, ret: %d", ret); printf("\nTLS: connection handshake failed, ret: %d\n", ret); ErrorCnt = 1; return NULL; } } } // store output buffer to out_data size = conn_buf_out->len; out_data = wpabuf_alloc(size); if(out_data == NULL){ wpa_printf(MSG_INFO, "SSL: Failed to allocate memory for " "handshake output (%d bytes)", size); return NULL; } buf_read_store(conn_buf_out, out_data->buf, size); wpabuf_put(out_data, size); //dump_buf(out_data->buf, size); // clear input and output buffer buf_clear(conn->buf_out, 0); buf_clear(conn->buf_in, 1); return out_data; } struct wpabuf * tls_connection_server_handshake(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data, struct wpabuf **appl_data) { /* To avoid gcc warnings */ ( void ) conn; ( void ) tls_ctx; ( void ) in_data; ( void ) appl_data; wpa_printf(MSG_DEBUG, "TLS: tls_connection_server_handshake"); return NULL; } struct wpabuf * tls_connection_encrypt(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data) { wpa_printf(MSG_DEBUG, "TLS: tls_connection_encrypt"); mbedtls_ssl_context *ssl = ((struct eap_tls *) tls_ctx)->ssl; struct wpabuf * out_data; int size; int res; if(conn == NULL) return NULL; res = mbedtls_ssl_write(ssl, wpabuf_head(in_data), wpabuf_len(in_data)); if(res < 0){ wpa_printf(MSG_INFO, "TLS: tls_connection_encrypt failed - ssl_write"); return NULL; } /* Read encrypted data to be sent to the server */ size = wpabuf_len(in_data) + 300; out_data = wpabuf_alloc(size); if(out_data == NULL){ wpa_printf(MSG_INFO, "TLS: Failed to allocate memory for " "encrypted output (%d bytes)", size); return NULL; } res = buf_read_store(conn_buf_out, out_data->buf, size); if(res < 0){ wpa_printf(MSG_INFO, "TLS: tls_connection_decrypt failed - buf_read"); wpabuf_free(out_data); return NULL; } wpabuf_put(out_data, res); // clear input and output buffer buf_clear(conn->buf_out, 0); buf_clear(conn->buf_in, 1); return out_data; } struct wpabuf * tls_connection_decrypt(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data) { wpa_printf(MSG_DEBUG, "TLS: tls_connection_decrypt"); mbedtls_ssl_context *ssl = ((struct eap_tls *)tls_ctx)->ssl; struct wpabuf * out_data; int size; int res; // write input data to input buffer if(in_data && wpabuf_len(in_data) > 0 && buf_write_store(conn_buf_in, wpabuf_head(in_data), wpabuf_len(in_data)) < 0){ wpa_printf(MSG_INFO, "TLS: tls_connection_decrypt failed - buf_write"); return NULL; } /* Read decrypted data for further processing */ /* * refer to tls_openssl.c * * Even though we try to disable TLS compression, it is possible that * this cannot be done with all TLS libraries. Add extra buffer space * to handle the possibility of the decrypted data being longer than * input data. */ size = (wpabuf_len(in_data) + 500) * 3; out_data = wpabuf_alloc(size); if(out_data == NULL){ wpa_printf(MSG_INFO, "TLS: Failed to allocate memory for " "decrypted output (%d bytes)", size); return NULL; } res = mbedtls_ssl_read(ssl, out_data->buf, size); if(res < 0){ wpa_printf(MSG_INFO, "TLS: tls_connection_decrypt failed - ssl_read"); wpabuf_free(out_data); return NULL; } wpabuf_put(out_data, res); //dump_buf(out_data->buf, size); // clear input and output buffer buf_clear(conn->buf_out, 0); buf_clear(conn->buf_in, 1); return out_data; } #endif /*CONFIG_USE_POLARSSL*/ int tls_connection_resumed(void *tls_ctx, struct tls_connection *conn) { /* To avoid gcc warnings */ ( void ) conn; ( void ) tls_ctx; wpa_printf(MSG_DEBUG, "TLS: tls_connection_resumed"); return 0; } int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn, u8 *ciphers) { /* To avoid gcc warnings */ ( void ) conn; ( void ) tls_ctx; ( void ) ciphers; wpa_printf(MSG_DEBUG, "TLS: tls_connection_set_cipher_list"); return -1; } int tls_get_version(void *ssl_ctx, struct tls_connection *conn, char *buf, size_t buflen) { /* To avoid gcc warnings */ ( void ) conn; ( void ) ssl_ctx; ( void ) buf; ( void ) buflen; wpa_printf(MSG_DEBUG, "TLS: tls_get_version"); return -1; } int tls_get_cipher(void *tls_ctx, struct tls_connection *conn, char *buf, size_t buflen) { /* To avoid gcc warnings */ ( void ) conn; ( void ) tls_ctx; ( void ) buf; ( void ) buflen; wpa_printf(MSG_DEBUG, "TLS: tls_get_cipher"); return -1; } int tls_connection_enable_workaround(void *tls_ctx, struct tls_connection *conn) { /* To avoid gcc warnings */ ( void ) conn; ( void ) tls_ctx; wpa_printf(MSG_DEBUG, "TLS: tls_connection_enable_workaround"); return -1; } int tls_connection_client_hello_ext(void *tls_ctx, struct tls_connection *conn, int ext_type, const u8 *data, size_t data_len) { /* To avoid gcc warnings */ ( void ) conn; ( void ) tls_ctx; ( void ) ext_type; ( void ) data; ( void ) data_len; wpa_printf(MSG_DEBUG, "TLS: tls_connection_client_hello_ext"); return -1; } int tls_connection_get_failed(void *tls_ctx, struct tls_connection *conn) { /* To avoid gcc warnings */ ( void ) conn; ( void ) tls_ctx; wpa_printf(MSG_DEBUG, "TLS: tls_connection_get_failed"); return 0; } int tls_connection_get_read_alerts(void *tls_ctx, struct tls_connection *conn) { /* To avoid gcc warnings */ ( void ) conn; ( void ) tls_ctx; wpa_printf(MSG_DEBUG, "TLS: tls_connection_get_read_alerts"); return 0; } int tls_connection_get_write_alerts(void *tls_ctx, struct tls_connection *conn) { /* To avoid gcc warnings */ ( void ) conn; ( void ) tls_ctx; wpa_printf(MSG_DEBUG, "TLS: tls_connection_get_write_alerts"); return 0; } int tls_get_library_version(char *buf, size_t buf_len) { wpa_printf(MSG_DEBUG, "TLS: tls_get_library_version"); return os_snprintf(buf, buf_len, "none"); } void tls_connection_set_success_data(struct tls_connection *conn, struct wpabuf *data) { /* To avoid gcc warnings */ ( void ) conn; ( void ) data; wpa_printf(MSG_DEBUG, "TLS: tls_connection_set_success_data"); } void tls_connection_set_success_data_resumed(struct tls_connection *conn) { /* To avoid gcc warnings */ ( void ) conn; wpa_printf(MSG_DEBUG, "TLS: tls_connection_set_success_data_resumed"); } const struct wpabuf * tls_connection_get_success_data(struct tls_connection *conn) { /* To avoid gcc warnings */ ( void ) conn; wpa_printf(MSG_DEBUG, "TLS: tls_connection_get_success_data"); return NULL; } void tls_connection_remove_session(struct tls_connection *conn) { /* To avoid gcc warnings */ ( void ) conn; wpa_printf(MSG_DEBUG, "TLS: tls_connection_get_success_data"); }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/rtw_wpa_supplicant/src/crypto/tls_polarssl.c
C
apache-2.0
31,215
/* * wpa_supplicant/hostapd / common helper functions, etc. * Copyright (c) 2002-2007, Jouni Malinen <j@w1.fi> * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #ifndef COMMON_H #define COMMON_H #include "utils/os.h" #define TO_TEST_WPS 0 #define ETH_ALEN 6 #if defined(__linux__) || defined(__GLIBC__) #include <endian.h> #include <byteswap.h> #endif /* __linux__ */ #if defined(PLATFORM_FREERTOS) //#include "little_endian.h" //#include "basic_types.h" #endif /* PLATFORM_FREERTOS */ #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || \ defined(__OpenBSD__) #include <sys/types.h> #include <sys/endian.h> #define __BYTE_ORDER _BYTE_ORDER #define __LITTLE_ENDIAN _LITTLE_ENDIAN #define __BIG_ENDIAN _BIG_ENDIAN #ifdef __OpenBSD__ #define bswap_16 swap16 #define bswap_32 swap32 #define bswap_64 swap64 #else /* __OpenBSD__ */ #define bswap_16 bswap16 #define bswap_32 bswap32 #define bswap_64 bswap64 #endif /* __OpenBSD__ */ #endif /* defined(__FreeBSD__) || defined(__NetBSD__) || * defined(__DragonFly__) || defined(__OpenBSD__) */ #ifdef __APPLE__ #include <sys/types.h> #include <machine/endian.h> #define __BYTE_ORDER _BYTE_ORDER #define __LITTLE_ENDIAN _LITTLE_ENDIAN #define __BIG_ENDIAN _BIG_ENDIAN static inline unsigned short bswap_16(unsigned short v) { return ((v & 0xff) << 8) | (v >> 8); } static inline unsigned int bswap_32(unsigned int v) { return ((v & 0xff) << 24) | ((v & 0xff00) << 8) | ((v & 0xff0000) >> 8) | (v >> 24); } #endif /* __APPLE__ */ #ifdef CONFIG_TI_COMPILER #define __BIG_ENDIAN 4321 #define __LITTLE_ENDIAN 1234 #ifdef __big_endian__ #define __BYTE_ORDER __BIG_ENDIAN #else #define __BYTE_ORDER __LITTLE_ENDIAN #endif #endif /* CONFIG_TI_COMPILER */ #ifdef CONFIG_NATIVE_WINDOWS #include <winsock.h> typedef int socklen_t; #ifndef MSG_DONTWAIT #define MSG_DONTWAIT 0 /* not supported */ #endif #endif /* CONFIG_NATIVE_WINDOWS */ #ifdef _MSC_VER #define inline __inline #undef vsnprintf #define vsnprintf _vsnprintf #undef close #define close closesocket #endif /* _MSC_VER */ /* Define platform specific integer types */ #ifdef _MSC_VER typedef UINT64 u64; typedef UINT32 u32; typedef UINT16 u16; typedef UINT8 u8; typedef INT64 s64; typedef INT32 s32; typedef INT16 s16; typedef INT8 s8; #define WPA_TYPES_DEFINED #endif /* _MSC_VER */ #ifdef __vxworks typedef unsigned long long u64; typedef UINT32 u32; typedef UINT16 u16; typedef UINT8 u8; typedef long long s64; typedef INT32 s32; typedef INT16 s16; typedef INT8 s8; #define WPA_TYPES_DEFINED #endif /* __vxworks */ #ifdef CONFIG_TI_COMPILER #ifdef _LLONG_AVAILABLE typedef unsigned long long u64; #else /* * TODO: 64-bit variable not available. Using long as a workaround to test the * build, but this will likely not work for all operations. */ typedef unsigned long u64; #endif typedef unsigned int u32; typedef unsigned short u16; typedef unsigned char u8; #define WPA_TYPES_DEFINED #endif /* CONFIG_TI_COMPILER */ #ifndef WPA_TYPES_DEFINED #ifdef CONFIG_USE_INTTYPES_H #include <inttypes.h> #else //#include <stdint.h> #endif #if 0 typedef uint64_t u64; typedef uint32_t u32; typedef uint16_t u16; typedef uint8_t u8; typedef int64_t s64; typedef int32_t s32; typedef int16_t s16; typedef int8_t s8; #endif #define WPA_TYPES_DEFINED #endif /* !WPA_TYPES_DEFINED */ /* Define platform specific byte swapping macros */ #if defined(__CYGWIN__) || defined(CONFIG_NATIVE_WINDOWS) static inline unsigned short wpa_swap_16(unsigned short v) { return ((v & 0xff) << 8) | (v >> 8); } static inline unsigned int wpa_swap_32(unsigned int v) { return ((v & 0xff) << 24) | ((v & 0xff00) << 8) | ((v & 0xff0000) >> 8) | (v >> 24); } #define le_to_host16(n) (n) #define host_to_le16(n) (n) #define be_to_host16(n) wpa_swap_16(n) #define host_to_be16(n) wpa_swap_16(n) #define le_to_host32(n) (n) #define be_to_host32(n) wpa_swap_32(n) #define host_to_be32(n) wpa_swap_32(n) #define WPA_BYTE_SWAP_DEFINED #endif /* __CYGWIN__ || CONFIG_NATIVE_WINDOWS */ #ifndef WPA_BYTE_SWAP_DEFINED #if 0 #ifndef __BYTE_ORDER #ifndef __LITTLE_ENDIAN #ifndef __BIG_ENDIAN #define __LITTLE_ENDIAN 1234 #define __BIG_ENDIAN 4321 #if defined(sparc) #define __BYTE_ORDER __BIG_ENDIAN #endif #endif /* __BIG_ENDIAN */ #endif /* __LITTLE_ENDIAN */ #endif /* __BYTE_ORDER */ #else #ifndef __LITTLE_ENDIAN #define __LITTLE_ENDIAN 1234 #endif #ifndef __BIG_ENDIAN #define __BIG_ENDIAN 4321 #endif #ifndef __BYTE_ORDER #define __BYTE_ORDER __LITTLE_ENDIAN #endif #endif #if __BYTE_ORDER == __LITTLE_ENDIAN #define le_to_host16(n) ((__force u16) (le16) (n)) #define host_to_le16(n) ((__force le16) (u16) (n)) #define be_to_host16(n) bswap_16((__force u16) (be16) (n)) #define host_to_be16(n) ((__force be16) bswap_16((n))) #define le_to_host32(n) ((__force u32) (le32) (n)) #define host_to_le32(n) ((__force le32) (u32) (n)) #define be_to_host32(n) bswap_32((__force u32) (be32) (n)) #define host_to_be32(n) ((__force be32) bswap_32((n))) #define le_to_host64(n) ((__force u64) (le64) (n)) #define host_to_le64(n) ((__force le64) (u64) (n)) #define be_to_host64(n) bswap_64((__force u64) (be64) (n)) #define host_to_be64(n) ((__force be64) bswap_64((n))) #elif __BYTE_ORDER == __BIG_ENDIAN #define le_to_host16(n) bswap_16(n) #define host_to_le16(n) bswap_16(n) #define be_to_host16(n) (n) #define host_to_be16(n) (n) #define le_to_host32(n) bswap_32(n) #define be_to_host32(n) (n) #define host_to_be32(n) (n) #define le_to_host64(n) bswap_64(n) #define host_to_le64(n) bswap_64(n) #define be_to_host64(n) (n) #define host_to_be64(n) (n) #ifndef WORDS_BIGENDIAN #define WORDS_BIGENDIAN #endif #else //#error Could not determine CPU byte order #endif #define WPA_BYTE_SWAP_DEFINED #endif /* !WPA_BYTE_SWAP_DEFINED */ /* Macros for handling unaligned memory accesses */ #define WPA_GET_BE16(a) ((u16) (((a)[0] << 8) | (a)[1])) #define WPA_PUT_BE16(a, val) \ do { \ (a)[0] = ((u16) (val)) >> 8; \ (a)[1] = ((u16) (val)) & 0xff; \ } while (0) #define WPA_GET_LE16(a) ((u16) (((a)[1] << 8) | (a)[0])) #define WPA_PUT_LE16(a, val) \ do { \ (a)[1] = ((u16) (val)) >> 8; \ (a)[0] = ((u16) (val)) & 0xff; \ } while (0) #define WPA_GET_BE24(a) ((((u32) (a)[0]) << 16) | (((u32) (a)[1]) << 8) | \ ((u32) (a)[2])) #define WPA_PUT_BE24(a, val) \ do { \ (a)[0] = (u8) ((((u32) (val)) >> 16) & 0xff); \ (a)[1] = (u8) ((((u32) (val)) >> 8) & 0xff); \ (a)[2] = (u8) (((u32) (val)) & 0xff); \ } while (0) #define WPA_GET_BE32(a) ((((u32) (a)[0]) << 24) | (((u32) (a)[1]) << 16) | \ (((u32) (a)[2]) << 8) | ((u32) (a)[3])) #define WPA_PUT_BE32(a, val) \ do { \ (a)[0] = (u8) ((((u32) (val)) >> 24) & 0xff); \ (a)[1] = (u8) ((((u32) (val)) >> 16) & 0xff); \ (a)[2] = (u8) ((((u32) (val)) >> 8) & 0xff); \ (a)[3] = (u8) (((u32) (val)) & 0xff); \ } while (0) #define WPA_GET_LE32(a) ((((u32) (a)[3]) << 24) | (((u32) (a)[2]) << 16) | \ (((u32) (a)[1]) << 8) | ((u32) (a)[0])) #define WPA_PUT_LE32(a, val) \ do { \ (a)[3] = (u8) ((((u32) (val)) >> 24) & 0xff); \ (a)[2] = (u8) ((((u32) (val)) >> 16) & 0xff); \ (a)[1] = (u8) ((((u32) (val)) >> 8) & 0xff); \ (a)[0] = (u8) (((u32) (val)) & 0xff); \ } while (0) #define WPA_GET_BE64(a) ((((u64) (a)[0]) << 56) | (((u64) (a)[1]) << 48) | \ (((u64) (a)[2]) << 40) | (((u64) (a)[3]) << 32) | \ (((u64) (a)[4]) << 24) | (((u64) (a)[5]) << 16) | \ (((u64) (a)[6]) << 8) | ((u64) (a)[7])) #define WPA_PUT_BE64(a, val) \ do { \ (a)[0] = (u8) (((u64) (val)) >> 56); \ (a)[1] = (u8) (((u64) (val)) >> 48); \ (a)[2] = (u8) (((u64) (val)) >> 40); \ (a)[3] = (u8) (((u64) (val)) >> 32); \ (a)[4] = (u8) (((u64) (val)) >> 24); \ (a)[5] = (u8) (((u64) (val)) >> 16); \ (a)[6] = (u8) (((u64) (val)) >> 8); \ (a)[7] = (u8) (((u64) (val)) & 0xff); \ } while (0) #define WPA_GET_LE64(a) ((((u64) (a)[7]) << 56) | (((u64) (a)[6]) << 48) | \ (((u64) (a)[5]) << 40) | (((u64) (a)[4]) << 32) | \ (((u64) (a)[3]) << 24) | (((u64) (a)[2]) << 16) | \ (((u64) (a)[1]) << 8) | ((u64) (a)[0])) #ifndef ETH_ALEN #define ETH_ALEN 6 #endif #ifndef IFNAMSIZ #define IFNAMSIZ 16 #endif #ifndef ETH_P_ALL #define ETH_P_ALL 0x0003 #endif #ifndef ETH_P_80211_ENCAP #define ETH_P_80211_ENCAP 0x890d /* TDLS comes under this category */ #endif #ifndef ETH_P_PAE #define ETH_P_PAE 0x888E /* Port Access Entity (IEEE 802.1X) */ #endif /* ETH_P_PAE */ #ifndef ETH_P_EAPOL #define ETH_P_EAPOL ETH_P_PAE #endif /* ETH_P_EAPOL */ #ifndef ETH_P_RSN_PREAUTH #define ETH_P_RSN_PREAUTH 0x88c7 #endif /* ETH_P_RSN_PREAUTH */ #ifndef ETH_P_RRB #define ETH_P_RRB 0x890D #endif /* ETH_P_RRB */ #if 0 //#ifdef __GNUC__ #define PRINTF_FORMAT(a,b) __attribute__ ((format (printf, (a), (b)))) #define STRUCT_PACKED __attribute__ ((packed)) #else #define PRINTF_FORMAT(a,b) #define STRUCT_PACKED #endif #ifdef CONFIG_ANSI_C_EXTRA #if !defined(_MSC_VER) || _MSC_VER < 1400 /* snprintf - used in number of places; sprintf() is _not_ a good replacement * due to possible buffer overflow; see, e.g., * http://www.ijs.si/software/snprintf/ for portable implementation of * snprintf. */ int snprintf(char *str, size_t size, const char *format, ...); /* vsnprintf - only used for wpa_msg() in wpa_supplicant.c */ int vsnprintf(char *str, size_t size, const char *format, va_list ap); #endif /* !defined(_MSC_VER) || _MSC_VER < 1400 */ /* getopt - only used in main.c */ int getopt(int argc, char *const argv[], const char *optstring); extern char *optarg; extern int optind; #ifndef CONFIG_NO_SOCKLEN_T_TYPEDEF #ifndef __socklen_t_defined typedef int socklen_t; #endif #endif /* inline - define as __inline or just define it to be empty, if needed */ #ifdef CONFIG_NO_INLINE #define inline #else #define inline __inline #endif #ifndef __func__ #define __func__ "__func__ not defined" #endif #ifndef bswap_16 #define bswap_16(a) ((((u16) (a) << 8) & 0xff00) | (((u16) (a) >> 8) & 0xff)) #endif #ifndef bswap_32 #define bswap_32(a) ((((u32) (a) << 24) & 0xff000000) | \ (((u32) (a) << 8) & 0xff0000) | \ (((u32) (a) >> 8) & 0xff00) | \ (((u32) (a) >> 24) & 0xff)) #endif #ifndef MSG_DONTWAIT #define MSG_DONTWAIT 0 #endif #ifdef _WIN32_WCE void perror(const char *s); #endif /* _WIN32_WCE */ #endif /* CONFIG_ANSI_C_EXTRA */ #ifndef MAC2STR #define MAC2STR(a) (a)[0], (a)[1], (a)[2], (a)[3], (a)[4], (a)[5] #define MACSTR "%02x:%02x:%02x:%02x:%02x:%02x" /* * Compact form for string representation of MAC address * To be used, e.g., for constructing dbus paths for P2P Devices */ #define COMPACT_MACSTR "%02x%02x%02x%02x%02x%02x" #endif #ifndef BIT #define BIT(x) (1 << (x)) #endif /* * Definitions for sparse validation * (http://kernel.org/pub/linux/kernel/people/josh/sparse/) */ #ifdef __CHECKER__ #define __force __attribute__((force)) #define __bitwise __attribute__((bitwise)) #else #define __force #define __bitwise #endif typedef u16 __bitwise be16; typedef u16 __bitwise le16; typedef u32 __bitwise be32; typedef u32 __bitwise le32; typedef u64 __bitwise be64; typedef u64 __bitwise le64; #ifndef __must_check #if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) #define __must_check __attribute__((__warn_unused_result__)) #else #define __must_check #endif /* __GNUC__ */ #endif /* __must_check */ //int hwaddr_aton(const char *txt, u8 *addr); int hwaddr_compact_aton(const char *txt, u8 *addr); int hwaddr_aton2(const char *txt, u8 *addr); int hex2byte(const char *hex); int hexstr2bin(const char *hex, u8 *buf, size_t len); void inc_byte_array(u8 *counter, size_t len); void wpa_get_ntp_timestamp(u8 *buf); //int wpa_snprintf_hex(char *buf, size_t buf_size, const u8 *data, size_t len); int wpa_snprintf_hex_uppercase(char *buf, size_t buf_size, const u8 *data, size_t len); #ifdef CONFIG_NATIVE_WINDOWS void wpa_unicode2ascii_inplace(TCHAR *str); TCHAR * wpa_strdup_tchar(const char *str); #else /* CONFIG_NATIVE_WINDOWS */ #define wpa_unicode2ascii_inplace(s) do { } while (0) #define wpa_strdup_tchar(s) strdup((s)) #endif /* CONFIG_NATIVE_WINDOWS */ void printf_encode(char *txt, size_t maxlen, const u8 *data, size_t len); size_t printf_decode(u8 *buf, size_t maxlen, const char *str); const char * wpa_ssid_txt(const u8 *ssid, size_t ssid_len); char * wpa_config_parse_string(const char *value, size_t *len); int is_hex(const u8 *data, size_t len); size_t merge_byte_arrays(u8 *res, size_t res_len, const u8 *src1, size_t src1_len, const u8 *src2, size_t src2_len); static inline int is_zero_ether_addr(const u8 *a) { return !(a[0] | a[1] | a[2] | a[3] | a[4] | a[5]); } static inline int is_broadcast_ether_addr(const u8 *a) { return (a[0] & a[1] & a[2] & a[3] & a[4] & a[5]) == 0xff; } #define broadcast_ether_addr (const u8 *) "\xff\xff\xff\xff\xff\xff" #include "wpa_debug.h" char * dup_binstr(const void *src, size_t len); struct wpa_freq_range_list { struct wpa_freq_range { unsigned int min; unsigned int max; } *range; unsigned int num; }; int freq_range_list_parse(struct wpa_freq_range_list *res, const char *value); int freq_range_list_includes(const struct wpa_freq_range_list *list, unsigned int freq); char * freq_range_list_str(const struct wpa_freq_range_list *list); int int_array_len(const int *a); void int_array_concat(int **res, const int *a); void int_array_sort_unique(int *a); void int_array_add_unique(int **res, int a); #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) void str_clear_free(char *str); void bin_clear_free(void *bin, size_t len); int random_mac_addr(u8 *addr); int random_mac_addr_keep_oui(u8 *addr); const char * cstr_token(const char *str, const char *delim, const char **last); char * str_token(char *str, const char *delim, char **context); size_t utf8_escape(const char *inp, size_t in_size, char *outp, size_t out_size); size_t utf8_unescape(const char *inp, size_t in_size, char *outp, size_t out_size); int is_ctrl_char(char c); #ifndef bswap_16 #define bswap_16(a) ((((u16) (a) << 8) & 0xff00) | (((u16) (a) >> 8) & 0xff)) #endif /* * gcc 4.4 ends up generating strict-aliasing warnings about some very common * networking socket uses that do not really result in a real problem and * cannot be easily avoided with union-based type-punning due to struct * definitions including another struct in system header files. To avoid having * to fully disable strict-aliasing warnings, provide a mechanism to hide the * typecast from aliasing for now. A cleaner solution will hopefully be found * in the future to handle these cases. */ void * __hide_aliasing_typecast(void *foo); #define aliasing_hide_typecast(a,t) (t *) __hide_aliasing_typecast((a)) #ifdef CONFIG_VALGRIND #include <valgrind/memcheck.h> #define WPA_MEM_DEFINED(ptr, len) VALGRIND_MAKE_MEM_DEFINED((ptr), (len)) #else /* CONFIG_VALGRIND */ #define WPA_MEM_DEFINED(ptr, len) do { } while (0) #endif /* CONFIG_VALGRIND */ #endif /* COMMON_H */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/rtw_wpa_supplicant/src/utils/common.h
C
apache-2.0
15,176
#ifndef INCLUDES_H #define INCLUDES_H #define CONFIG_NO_STDOUT_DEBUG #ifndef CONFIG_NO_STDOUT_DEBUG /* Event messages with fixed prefix */ /** Authentication completed successfully and data connection enabled */ #define WPA_EVENT_CONNECTED "CTRL-EVENT-CONNECTED " /** Disconnected, data connection is not available */ #define WPA_EVENT_DISCONNECTED "CTRL-EVENT-DISCONNECTED " /** Association rejected during connection attempt */ #define WPA_EVENT_ASSOC_REJECT "CTRL-EVENT-ASSOC-REJECT " /** Authentication rejected during connection attempt */ #define WPA_EVENT_AUTH_REJECT "CTRL-EVENT-AUTH-REJECT " /** wpa_supplicant is exiting */ #define WPA_EVENT_TERMINATING "CTRL-EVENT-TERMINATING " /** Password change was completed successfully */ #define WPA_EVENT_PASSWORD_CHANGED "CTRL-EVENT-PASSWORD-CHANGED " /** EAP-Request/Notification received */ #define WPA_EVENT_EAP_NOTIFICATION "CTRL-EVENT-EAP-NOTIFICATION " /** EAP authentication started (EAP-Request/Identity received) */ #define WPA_EVENT_EAP_STARTED "CTRL-EVENT-EAP-STARTED " /** EAP method proposed by the server */ #define WPA_EVENT_EAP_PROPOSED_METHOD "CTRL-EVENT-EAP-PROPOSED-METHOD " /** EAP method selected */ #define WPA_EVENT_EAP_METHOD "CTRL-EVENT-EAP-METHOD " /** EAP peer certificate from TLS */ #define WPA_EVENT_EAP_PEER_CERT "CTRL-EVENT-EAP-PEER-CERT " /** EAP peer certificate alternative subject name component from TLS */ #define WPA_EVENT_EAP_PEER_ALT "CTRL-EVENT-EAP-PEER-ALT " /** EAP TLS certificate chain validation error */ #define WPA_EVENT_EAP_TLS_CERT_ERROR "CTRL-EVENT-EAP-TLS-CERT-ERROR " /** EAP status */ #define WPA_EVENT_EAP_STATUS "CTRL-EVENT-EAP-STATUS " /** EAP authentication completed successfully */ #define WPA_EVENT_EAP_SUCCESS "CTRL-EVENT-EAP-SUCCESS " /** EAP authentication failed (EAP-Failure received) */ #define WPA_EVENT_EAP_FAILURE "CTRL-EVENT-EAP-FAILURE " /** Network block temporarily disabled (e.g., due to authentication failure) */ #define WPA_EVENT_TEMP_DISABLED "CTRL-EVENT-SSID-TEMP-DISABLED " /** Temporarily disabled network block re-enabled */ #define WPA_EVENT_REENABLED "CTRL-EVENT-SSID-REENABLED " /** New scan started */ #define WPA_EVENT_SCAN_STARTED "CTRL-EVENT-SCAN-STARTED " /** New scan results available */ #define WPA_EVENT_SCAN_RESULTS "CTRL-EVENT-SCAN-RESULTS " /** Scan command failed */ #define WPA_EVENT_SCAN_FAILED "CTRL-EVENT-SCAN-FAILED " /** wpa_supplicant state change */ #define WPA_EVENT_STATE_CHANGE "CTRL-EVENT-STATE-CHANGE " /** A new BSS entry was added (followed by BSS entry id and BSSID) */ #define WPA_EVENT_BSS_ADDED "CTRL-EVENT-BSS-ADDED " /** A BSS entry was removed (followed by BSS entry id and BSSID) */ #define WPA_EVENT_BSS_REMOVED "CTRL-EVENT-BSS-REMOVED " /** No suitable network was found */ #define WPA_EVENT_NETWORK_NOT_FOUND "CTRL-EVENT-NETWORK-NOT-FOUND " /** Change in the signal level was reported by the driver */ #define WPA_EVENT_SIGNAL_CHANGE "CTRL-EVENT-SIGNAL-CHANGE " /** Regulatory domain channel */ #define WPA_EVENT_REGDOM_CHANGE "CTRL-EVENT-REGDOM-CHANGE " /** RSN IBSS 4-way handshakes completed with specified peer */ #define IBSS_RSN_COMPLETED "IBSS-RSN-COMPLETED " /** Notification of frequency conflict due to a concurrent operation. * * The indicated network is disabled and needs to be re-enabled before it can * be used again. */ #define WPA_EVENT_FREQ_CONFLICT "CTRL-EVENT-FREQ-CONFLICT " /** Frequency ranges that the driver recommends to avoid */ #define WPA_EVENT_AVOID_FREQ "CTRL-EVENT-AVOID-FREQ " /** WPS overlap detected in PBC mode */ #define WPS_EVENT_OVERLAP "WPS-OVERLAP-DETECTED " /** Available WPS AP with active PBC found in scan results */ #define WPS_EVENT_AP_AVAILABLE_PBC "WPS-AP-AVAILABLE-PBC " /** Available WPS AP with our address as authorized in scan results */ #define WPS_EVENT_AP_AVAILABLE_AUTH "WPS-AP-AVAILABLE-AUTH " /** Available WPS AP with recently selected PIN registrar found in scan results */ #define WPS_EVENT_AP_AVAILABLE_PIN "WPS-AP-AVAILABLE-PIN " /** Available WPS AP found in scan results */ #define WPS_EVENT_AP_AVAILABLE "WPS-AP-AVAILABLE " /** A new credential received */ #define WPS_EVENT_CRED_RECEIVED "WPS-CRED-RECEIVED " /** M2D received */ #define WPS_EVENT_M2D "WPS-M2D " /** WPS registration failed after M2/M2D */ #define WPS_EVENT_FAIL "WPS-FAIL " /** WPS registration completed successfully */ #define WPS_EVENT_SUCCESS "WPS-SUCCESS " /** WPS enrollment attempt timed out and was terminated */ #define WPS_EVENT_TIMEOUT "WPS-TIMEOUT " /* PBC mode was activated */ #define WPS_EVENT_ACTIVE "WPS-PBC-ACTIVE " /* PBC mode was disabled */ #define WPS_EVENT_DISABLE "WPS-PBC-DISABLE " #define WPS_EVENT_ENROLLEE_SEEN "WPS-ENROLLEE-SEEN " #define WPS_EVENT_OPEN_NETWORK "WPS-OPEN-NETWORK " /* WPS ER events */ #define WPS_EVENT_ER_AP_ADD "WPS-ER-AP-ADD " #define WPS_EVENT_ER_AP_REMOVE "WPS-ER-AP-REMOVE " #define WPS_EVENT_ER_ENROLLEE_ADD "WPS-ER-ENROLLEE-ADD " #define WPS_EVENT_ER_ENROLLEE_REMOVE "WPS-ER-ENROLLEE-REMOVE " #define WPS_EVENT_ER_AP_SETTINGS "WPS-ER-AP-SETTINGS " #define WPS_EVENT_ER_SET_SEL_REG "WPS-ER-AP-SET-SEL-REG " #endif /* CONFIG_NO_STDOUT_DEBUG */ //#define DBG_871X(...) vTaskDelay(100) //DBG_871X_LEVEL(_drv_always_, "no beacon for a long time, disconnect or roaming\n"); //#define DBG_871X(...) DBG_871X_LEVEL(_drv_always_,...) #endif /* INCLUDES_H */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/rtw_wpa_supplicant/src/utils/includes.h
C
apache-2.0
5,336
/* * OS specific functions * Copyright (c) 2005-2009, Jouni Malinen <j@w1.fi> * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #ifndef OS_H #define OS_H //#include "basic_types.h" #include <autoconf.h> #include "osdep_service.h" #include "alios/wrapper.h" #include "utils/rom/rom_wps_os.h" typedef void* xqueue_handle_t; typedef long os_time_t; typedef _timer os_timer; /** * os_sleep - Sleep (sec, usec) * @sec: Number of seconds to sleep * @usec: Number of microseconds to sleep */ void os_sleep(os_time_t sec, os_time_t usec); struct os_time { os_time_t sec; os_time_t usec; }; struct os_reltime { os_time_t sec; os_time_t usec; }; /** * os_get_time - Get current time (sec, usec) * @t: Pointer to buffer for the time * Returns: 0 on success, -1 on failure */ int os_get_time(struct os_time *t); int os_get_reltime(struct os_reltime *t); /* Helper macros for handling struct os_time */ /* (&timeout->time, &tmp->time) */ #define os_time_before(a, b) \ ((a)->sec < (b)->sec || \ ((a)->sec == (b)->sec && (a)->usec < (b)->usec)) #define os_time_sub(a, b, res) do { \ (res)->sec = (a)->sec - (b)->sec; \ (res)->usec = (a)->usec - (b)->usec; \ if ((res)->usec < 0) { \ (res)->sec--; \ (res)->usec += 1000000; \ } \ } while (0) /** * os_mktime - Convert broken-down time into seconds since 1970-01-01 * @year: Four digit year * @month: Month (1 .. 12) * @day: Day of month (1 .. 31) * @hour: Hour (0 .. 23) * @min: Minute (0 .. 59) * @sec: Second (0 .. 60) * @t: Buffer for returning calendar time representation (seconds since * 1970-01-01 00:00:00) * Returns: 0 on success, -1 on failure * * Note: The result is in seconds from Epoch, i.e., in UTC, not in local time * which is used by POSIX mktime(). */ int os_mktime(int year, int month, int day, int hour, int min, int sec, os_time_t *t); struct os_tm { int sec; /* 0..59 or 60 for leap seconds */ int min; /* 0..59 */ int hour; /* 0..23 */ int day; /* 1..31 */ int month; /* 1..12 */ int year; /* Four digit year */ }; int os_gmtime(os_time_t t, struct os_tm *tm); /* Helpers for handling struct os_time */ /* Helpers for handling struct os_reltime */ static inline int os_reltime_before(struct os_reltime *a, struct os_reltime *b) { return os_time_before(a,b); } static inline void os_reltime_sub(struct os_reltime *a, struct os_reltime *b, struct os_reltime *res) { os_time_sub(a,b,res); } static inline void os_reltime_age(struct os_reltime *start, struct os_reltime *age) { struct os_reltime now; os_get_time((struct os_time *)&now); os_reltime_sub(&now, start, age); } static inline int os_reltime_expired(struct os_reltime *now, struct os_reltime *ts, os_time_t timeout_secs) { struct os_reltime age; os_reltime_sub(now, ts, &age); return (age.sec > timeout_secs) || (age.sec == timeout_secs && age.usec > 0); } /** * os_daemonize - Run in the background (detach from the controlling terminal) * @pid_file: File name to write the process ID to or %NULL to skip this * Returns: 0 on success, -1 on failure */ int os_daemonize(const char *pid_file); /** * os_daemonize_terminate - Stop running in the background (remove pid file) * @pid_file: File name to write the process ID to or %NULL to skip this */ void os_daemonize_terminate(const char *pid_file); /** * os_get_random - Get cryptographically strong pseudo random data * @buf: Buffer for pseudo random data * @len: Length of the buffer * Returns: 0 on success, -1 on failure */ int os_get_random(unsigned char *buf, size_t len); /** * os_random - Get pseudo random value (not necessarily very strong) * Returns: Pseudo random value */ unsigned long os_random(void); /** * os_rel2abs_path - Get an absolute path for a file * @rel_path: Relative path to a file * Returns: Absolute path for the file or %NULL on failure * * This function tries to convert a relative path of a file to an absolute path * in order for the file to be found even if current working directory has * changed. The returned value is allocated and caller is responsible for * freeing it. It is acceptable to just return the same path in an allocated * buffer, e.g., return strdup(rel_path). This function is only used to find * configuration files when os_daemonize() may have changed the current working * directory and relative path would be pointing to a different location. */ char * os_rel2abs_path(const char *rel_path); /** * os_program_init - Program initialization (called at start) * Returns: 0 on success, -1 on failure * * This function is called when a programs starts. If there are any OS specific * processing that is needed, it can be placed here. It is also acceptable to * just return 0 if not special processing is needed. */ int os_program_init(void); /** * os_program_deinit - Program deinitialization (called just before exit) * * This function is called just before a program exists. If there are any OS * specific processing, e.g., freeing resourced allocated in os_program_init(), * it should be done here. It is also acceptable for this function to do * nothing. */ void os_program_deinit(void); /** * os_setenv - Set environment variable * @name: Name of the variable * @value: Value to set to the variable * @overwrite: Whether existing variable should be overwritten * Returns: 0 on success, -1 on error * * This function is only used for wpa_cli action scripts. OS wrapper does not * need to implement this if such functionality is not needed. */ int os_setenv(const char *name, const char *value, int overwrite); /** * os_unsetenv - Delete environent variable * @name: Name of the variable * Returns: 0 on success, -1 on error * * This function is only used for wpa_cli action scripts. OS wrapper does not * need to implement this if such functionality is not needed. */ int os_unsetenv(const char *name); /** * os_readfile - Read a file to an allocated memory buffer * @name: Name of the file to read * @len: For returning the length of the allocated buffer * Returns: Pointer to the allocated buffer or %NULL on failure * * This function allocates memory and reads the given file to this buffer. Both * binary and text files can be read with this function. The caller is * responsible for freeing the returned buffer with os_free(). */ char * os_readfile(const char *name, size_t *len); //#if 0 /** * os_zalloc - Allocate and zero memory * @size: Number of bytes to allocate * Returns: Pointer to allocated and zeroed memory or %NULL on failure * * Caller is responsible for freeing the returned buffer with os_free(). */ void * os_zalloc(size_t size); /** * os_calloc - Allocate and zero memory for an array * @nmemb: Number of members in the array * @size: Number of bytes in each member * Returns: Pointer to allocated and zeroed memory or %NULL on failure * * This function can be used as a wrapper for os_zalloc(nmemb * size) when an * allocation is used for an array. The main benefit over os_zalloc() is in * having an extra check to catch integer overflows in multiplication. * * Caller is responsible for freeing the returned buffer with os_free(). */ static inline void * os_calloc(size_t nmemb, size_t size) { if (size && nmemb > (~(size_t) 0) / size) return NULL; return os_zalloc(nmemb * size); } //#endif static inline int os_memcmp_const(const void *a, const void *b, size_t len) { const u8 *aa = a; const u8 *bb = b; size_t i; u8 res; for (res = 0, i = 0; i < len; i++) res |= aa[i] ^ bb[i]; return res; } /* * The following functions are wrapper for standard ANSI C or POSIX functions. * By default, they are just defined to use the standard function name and no * os_*.c implementation is needed for them. This avoids extra function calls * by allowing the C pre-processor take care of the function name mapping. * * If the target system uses a C library that does not provide these functions, * build_config.h can be used to define the wrappers to use a different * function name. This can be done on function-by-function basis since the * defines here are only used if build_config.h does not define the os_* name. * If needed, os_*.c file can be used to implement the functions that are not * included in the C library on the target system. Alternatively, * OS_NO_C_LIB_DEFINES can be defined to skip all defines here in which case * these functions need to be implemented in os_*.c file for the target system. */ #ifdef OS_NO_C_LIB_DEFINES /** * os_malloc - Allocate dynamic memory * @size: Size of the buffer to allocate * Returns: Allocated buffer or %NULL on failure * * Caller is responsible for freeing the returned buffer with os_free(). */ void * os_malloc(size_t size); /** * os_realloc - Re-allocate dynamic memory * @ptr: Old buffer from os_malloc() or os_realloc() * @size: Size of the new buffer * Returns: Allocated buffer or %NULL on failure * * Caller is responsible for freeing the returned buffer with os_free(). * If re-allocation fails, %NULL is returned and the original buffer (ptr) is * not freed and caller is still responsible for freeing it. */ void * os_realloc(void *ptr, size_t size); /** * os_free - Free dynamic memory * @ptr: Old buffer from os_malloc() or os_realloc(); can be %NULL */ void os_free(void *ptr); /** * os_memcpy - Copy memory area * @dest: Destination * @src: Source * @n: Number of bytes to copy * Returns: dest * * The memory areas src and dst must not overlap. os_memmove() can be used with * overlapping memory. */ void * os_memcpy(void *dest, const void *src, size_t n); /** * os_memmove - Copy memory area * @dest: Destination * @src: Source * @n: Number of bytes to copy * Returns: dest * * The memory areas src and dst may overlap. */ void *os_memmove(void *dest, const void *src, size_t n); /** * os_memset - Fill memory with a constant byte * @s: Memory area to be filled * @c: Constant byte * @n: Number of bytes started from s to fill with c * Returns: s */ void *os_memset(void *s, int c, size_t n); /** * os_memcmp - Compare memory areas * @s1: First buffer * @s2: Second buffer * @n: Maximum numbers of octets to compare * Returns: An integer less than, equal to, or greater than zero if s1 is * found to be less than, to match, or be greater than s2. Only first n * characters will be compared. */ int os_memcmp(const void *s1, const void *s2, size_t n); /** * os_strdup - Duplicate a string * @s: Source string * Returns: Allocated buffer with the string copied into it or %NULL on failure * * Caller is responsible for freeing the returned buffer with os_free(). */ char *os_strdup(const char *s); /** * os_strlen - Calculate the length of a string * @s: '\0' terminated string * Returns: Number of characters in s (not counting the '\0' terminator) */ size_t os_strlen(const char *s); /** * os_strcasecmp - Compare two strings ignoring case * @s1: First string * @s2: Second string * Returns: An integer less than, equal to, or greater than zero if s1 is * found to be less than, to match, or be greatred than s2 */ int os_strcasecmp(const char *s1, const char *s2); /** * os_strncasecmp - Compare two strings ignoring case * @s1: First string * @s2: Second string * @n: Maximum numbers of characters to compare * Returns: An integer less than, equal to, or greater than zero if s1 is * found to be less than, to match, or be greater than s2. Only first n * characters will be compared. */ int os_strncasecmp(const char *s1, const char *s2, size_t n); /** * os_strchr - Locate the first occurrence of a character in string * @s: String * @c: Character to search for * Returns: Pointer to the matched character or %NULL if not found */ char *os_strchr(const char *s, int c); /** * os_strrchr - Locate the last occurrence of a character in string * @s: String * @c: Character to search for * Returns: Pointer to the matched character or %NULL if not found */ char *os_strrchr(const char *s, int c); /** * os_strcmp - Compare two strings * @s1: First string * @s2: Second string * Returns: An integer less than, equal to, or greater than zero if s1 is * found to be less than, to match, or be greatred than s2 */ int os_strcmp(const char *s1, const char *s2); /** * os_strncmp - Compare two strings * @s1: First string * @s2: Second string * @n: Maximum numbers of characters to compare * Returns: An integer less than, equal to, or greater than zero if s1 is * found to be less than, to match, or be greater than s2. Only first n * characters will be compared. */ int os_strncmp(const char *s1, const char *s2, size_t n); /** * os_strncpy - Copy a string * @dest: Destination * @src: Source * @n: Maximum number of characters to copy * Returns: dest */ char *os_strncpy(char *dest, const char *src, size_t n); /** * os_strstr - Locate a substring * @haystack: String (haystack) to search from * @needle: Needle to search from haystack * Returns: Pointer to the beginning of the substring or %NULL if not found */ char *os_strstr(const char *haystack, const char *needle); /** * os_snprintf - Print to a memory buffer * @str: Memory buffer to print into * @size: Maximum length of the str buffer * @format: printf format * Returns: Number of characters printed (not including trailing '\0'). * * If the output buffer is truncated, number of characters which would have * been written is returned. Since some C libraries return -1 in such a case, * the caller must be prepared on that value, too, to indicate truncation. * * Note: Some C library implementations of snprintf() may not guarantee null * termination in case the output is truncated. The OS wrapper function of * os_snprintf() should provide this guarantee, i.e., to null terminate the * output buffer if a C library version of the function is used and if that * function does not guarantee null termination. * * If the target system does not include snprintf(), see, e.g., * http://www.ijs.si/software/snprintf/ for an example of a portable * implementation of snprintf. */ int os_snprintf(char *str, size_t size, const char *format, ...); #else /* OS_NO_C_LIB_DEFINES */ #if !defined(CONFIG_PLATFORM_8195A) && !defined(CONFIG_PLATFORM_8711B) && !defined(CONFIG_PLATFORM_8721D) #ifdef CONFIG_MEM_MONITOR u8* os_malloc(u32 sz); void os_mfree(u8 *pbuf, u32 sz); #ifndef os_free #define os_free(p, sz) os_mfree(((u8*)(p)), (sz)) #endif #else #ifndef os_malloc #define os_malloc(sz) _rtw_malloc(sz) #endif #ifndef os_free #define os_free(p, sz) _rtw_mfree(((u8*)(p)), (sz)) #endif #endif #endif extern void *os_zalloc(size_t size); extern char *os_strdup(const char *string_copy_from); #ifndef os_sleep #define os_sleep(s, us) rtw_mdelay_os((s)*1000 + (us)/1000) #endif #ifndef os_memcpy #define os_memcpy(d, s, n) rtw_memcpy((void*)(d), ((void*)(s)), (n)) #endif #ifndef os_memmove #define os_memmove(d, s, n) memmove((d), (s), (n)) #endif #ifndef os_memset #define os_memset(pbuf, c, sz) rtw_memset(pbuf, c, sz) #endif #ifndef os_memcmp #define os_memcmp(s1, s2, n) rtw_memcmp(((void*)(s1)), ((void*)(s2)), (n)) #endif #ifndef os_memcmp_p2p #define os_memcmp_p2p(s1, s2, n) memcmp((s1), (s2), (n)) #endif #ifndef os_get_random_bytes #define os_get_random_bytes(d,sz) rtw_get_random_bytes(((void*)(d)), (sz)) #endif #ifndef os_strlen #define os_strlen(s) strlen(s) #endif #ifndef os_strcasecmp #ifdef _MSC_VER #define os_strcasecmp(s1, s2) _stricmp((s1), (s2)) #else #define os_strcasecmp(s1, s2) strcasecmp((s1), (s2)) #endif #endif #ifndef os_strncasecmp #ifdef _MSC_VER #define os_strncasecmp(s1, s2, n) _strnicmp((s1), (s2), (n)) #else #define os_strncasecmp(s1, s2, n) strncasecmp((s1), (s2), (n)) #endif #endif #ifndef os_init_timer #define os_init_timer(t, p, f, x, n) rtw_init_timer((t), (p), (f), (x), (n)) #endif #ifndef os_set_timer #define os_set_timer(t, d) rtw_set_timer((t), (d)) #endif #ifndef os_cancel_timer #define os_cancel_timer(t) rtw_cancel_timer(t) #endif #ifndef os_del_timer #define os_del_timer(t) rtw_del_timer(t) #endif #ifndef os_atoi #define os_atoi(s) rtw_atoi(s) #endif #ifndef os_strchr #define os_strchr(s, c) strchr((s), (c)) #endif #ifndef os_strcmp #define os_strcmp(s1, s2) strcmp((s1), (s2)) #endif #ifndef os_strncmp #define os_strncmp(s1, s2, n) strncmp((s1), (s2), (n)) #endif #ifndef os_strncpy #define os_strncpy(d, s, n) strncpy((d), (s), (n)) #endif #ifndef os_strrchr #define os_strrchr(s, c) strrchr((s), (c)) #endif #ifndef os_strstr #define os_strstr(h, n) strstr((h), (n)) #endif #ifndef os_snprintf #ifdef _MSC_VER #define os_snprintf _snprintf #else #define os_snprintf snprintf #endif #endif #endif /* OS_NO_C_LIB_DEFINES */ static inline void * os_realloc_array(void *ptr, size_t nmemb, size_t size) { if (size && nmemb > (~(size_t) 0) / size) return NULL; return os_realloc(ptr, nmemb * size, nmemb * size); } void *os_xqueue_create(unsigned long uxQueueLength, unsigned long uxItemSize) ; int os_xqueue_receive(xqueue_handle_t xQueue, void * const pvBuffer, unsigned long xSecsToWait); void os_xqueue_delete(xqueue_handle_t xQueue ); int os_xqueue_send(xqueue_handle_t xQueue, const void * const pvItemToQueue, unsigned long xSecsToWait); #endif /* OS_H */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/rtw_wpa_supplicant/src/utils/os.h
C
apache-2.0
17,467
/* * OS specific functions * Copyright (c) 2005-2009, Jouni Malinen <j@w1.fi> * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #ifndef ROM_WPS_OS_H #define ROM_WPS_OS_H #if defined(CONFIG_PLATFORM_8195A) || defined(CONFIG_PLATFORM_8711B) || defined(CONFIG_PLATFORM_8721D) #include <rom_wlan_ram_map.h> extern struct _rom_wlan_ram_map rom_wlan_ram_map; #define os_malloc(sz) rom_wlan_ram_map.rtw_malloc(sz) #define os_free(p, sz) rom_wlan_ram_map.rtw_mfree(((u8*)(p)), (sz)) #endif extern u8 *WPS_realloc(u8 *old_buf, u32 old_sz, u32 new_sz); #define os_realloc(p, os, ns) WPS_realloc(((u8*)(p)),(os),(ns)) #endif /* ROM_WPS_OS_H */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/rtw_wpa_supplicant/src/utils/rom/rom_wps_os.h
C
apache-2.0
702
/* * Universally Unique IDentifier (UUID) * Copyright (c) 2008, Jouni Malinen <j@w1.fi> * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #ifndef UUID_H #define UUID_H #include <platform/platform_stdlib.h> #define UUID_LEN 16 int uuid_str2bin(const char *str, u8 *bin); static int uuid_bin2str(const u8 *bin, char *str, size_t max_len) { int len; len = os_snprintf(str, max_len, "%02x%02x%02x%02x-%02x%02x-%02x%02x-" "%02x%02x-%02x%02x%02x%02x%02x%02x", bin[0], bin[1], bin[2], bin[3], bin[4], bin[5], bin[6], bin[7], bin[8], bin[9], bin[10], bin[11], bin[12], bin[13], bin[14], bin[15]); if (len < 0 || (size_t) len >= max_len) return -1; return 0; } int is_nil_uuid(const u8 *uuid); #endif /* UUID_H */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/rtw_wpa_supplicant/src/utils/uuid.h
C
apache-2.0
803
/* * wpa_supplicant/hostapd / Debug prints * Copyright (c) 2002-2007, Jouni Malinen <j@w1.fi> * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #ifndef WPA_DEBUG_H #define WPA_DEBUG_H #include "utils/wpabuf.h" /* Debugging function - conditional printf and hex dump. Driver wrappers can * use these for debugging purposes. */ enum { MSG_EXCESSIVE, MSG_MSGDUMP, MSG_DEBUG, MSG_INFO, MSG_ALWAYS, MSG_WARNING, MSG_ERROR }; #define wpa_debug_print_timestamp() do { } while (0) #define wpa_hexdump(l,t,b,le) do { } while (0) #define wpa_hexdump_buf_key(l,t,b) do { } while (0) #define wpa_hexdump_ascii_key(l,t,b,le) do { } while (0) #define wpa_debug_open_file(p) do { } while (0) #define wpa_debug_close_file() do { } while (0) #define wpa_dbg(args...) do { } while (0) #define wpa_msg_ctrl(args...) do { } while (0) #define wpa_msg_register_cb(f) do { } while (0) #define wpa_msg_register_ifname_cb(f) do { } while (0) static inline int wpa_debug_reopen_file(void) { return 0; } #define wprintf(fmt, arg...) printf("[%d] "fmt, rtw_get_current_time(),##arg) #ifdef CONFIG_NO_STDOUT_DEBUG #define wpa_printf(args...) do { } while (0) #define wpa_hexdump_buf(l,t,b) do { } while (0) #define wpa_hexdump_key(l,t,b,le) do { } while (0) #define wpa_hexdump_ascii(l,t,b,le) do { } while (0) #define wpa_msg(args...) do { } while (0) #else //void wpa_printf(int level, const char *fmt, ...); #define wpa_printf(level, fmt, arg...) \ do {\ if (level >= MSG_INFO) {\ {\ printf("\r\n%d:", rtw_get_current_time());\ printf(fmt, ##arg);\ printf("\n\r");\ } \ }\ }while(0) #define wpa_msg(ctx,level,fmt,arg...) wpa_printf((level),(fmt), ##arg) void wpa_hexdump_key(int level, const char *title, const void *buf, size_t len); void wpa_hexdump_buf(int level, const char *title, const struct wpabuf *buf); void wpa_hexdump_ascii(int level, const char *title, const void *buf, size_t len); #ifdef EAPOL_TEST #define WPA_ASSERT(a) \ do { \ if (!(a)) { \ printf("WPA_ASSERT FAILED '" #a "' " \ "%s %s:%d\n", \ __FUNCTION__, __FILE__, __LINE__); \ exit(1); \ } \ } while (0) #else #define WPA_ASSERT(a) do { } while (0) #endif #endif //CONFIG_NO_STDOUT_DEBUG #endif /* WPA_DEBUG_H */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/rtw_wpa_supplicant/src/utils/wpa_debug.h
C
apache-2.0
2,397
/* * Dynamic data buffer * Copyright (c) 2007-2012, Jouni Malinen <j@w1.fi> * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #ifndef WPABUF_H #define WPABUF_H /* wpabuf::buf is a pointer to external data */ #define WPABUF_FLAG_EXT_DATA BIT(0) /* * Internal data structure for wpabuf. Please do not touch this directly from * elsewhere. This is only defined in header file to allow inline functions * from this file to access data. */ struct wpabuf { size_t size; /* total size of the allocated buffer (i.e allocated buffer size)*/ size_t used; /* length of data in the buffer (i.e data length) */ u8 *buf; /* pointer to the head of the buffer (i.e buffer address) */ unsigned int flags; /* optionally followed by the allocated buffer */ }; int wpabuf_resize(struct wpabuf **buf, size_t add_len); struct wpabuf * wpabuf_alloc(size_t len); struct wpabuf * wpabuf_alloc_ext_data(u8 *data, size_t len); struct wpabuf * wpabuf_alloc_copy(const void *data, size_t len); struct wpabuf * wpabuf_dup(const struct wpabuf *src); void wpabuf_free(struct wpabuf *buf); void * wpabuf_put(struct wpabuf *buf, size_t len); struct wpabuf * wpabuf_concat(struct wpabuf *a, struct wpabuf *b); struct wpabuf * wpabuf_zeropad(struct wpabuf *buf, size_t len); void wpabuf_printf(struct wpabuf *buf, char *fmt, ...) PRINTF_FORMAT(2, 3); /** * wpabuf_size - Get the currently allocated size of a wpabuf buffer * @buf: wpabuf buffer * Returns: Currently allocated size of the buffer */ static inline size_t wpabuf_size(const struct wpabuf *buf) { return buf->size; } /** * wpabuf_len - Get the current length of a wpabuf buffer data * @buf: wpabuf buffer * Returns: Currently used length of the buffer */ static inline size_t wpabuf_len(const struct wpabuf *buf) { return buf->used; } /** * wpabuf_tailroom - Get size of available tail room in the end of the buffer * @buf: wpabuf buffer * Returns: Tail room (in bytes) of available space in the end of the buffer */ static inline size_t wpabuf_tailroom(const struct wpabuf *buf) { return buf->size - buf->used; } /** * wpabuf_head - Get pointer to the head of the buffer data * @buf: wpabuf buffer * Returns: Pointer to the head of the buffer data */ static inline const void *wpabuf_head(const struct wpabuf *buf) { return buf->buf; } static inline const u8 *wpabuf_head_u8(const struct wpabuf *buf) { return wpabuf_head(buf); } /** * wpabuf_mhead - Get modifiable pointer to the head of the buffer data * @buf: wpabuf buffer * Returns: Pointer to the head of the buffer data */ static inline void *wpabuf_mhead(struct wpabuf *buf) { return buf->buf; } static inline u8 *wpabuf_mhead_u8(struct wpabuf *buf) { return wpabuf_mhead(buf); } static inline void wpabuf_put_u8(struct wpabuf *buf, u8 data) { u8 *pos = NULL; if ( buf == NULL) return; pos = wpabuf_put(buf, 1); *pos = data; } static inline void wpabuf_put_le16(struct wpabuf *buf, u16 data) { u8 *pos = NULL; if ( buf == NULL) return; pos = wpabuf_put(buf, 2); WPA_PUT_LE16(pos, data); } static inline void wpabuf_put_le32(struct wpabuf *buf, u32 data) { u8 *pos = NULL; if ( buf == NULL) return; pos = wpabuf_put(buf, 4); WPA_PUT_LE32(pos, data); } static inline void wpabuf_put_be16(struct wpabuf *buf, u16 data) { u8 *pos = NULL; if ( buf == NULL) return; pos = wpabuf_put(buf, 2); WPA_PUT_BE16(pos, data); } static inline void wpabuf_put_be24(struct wpabuf *buf, u32 data) { u8 *pos = NULL; if ( buf == NULL) return; pos = wpabuf_put(buf, 3); WPA_PUT_BE24(pos, data); } static inline void wpabuf_put_be32(struct wpabuf *buf, u32 data) { u8 *pos = NULL; if ( buf == NULL) return; pos = wpabuf_put(buf, 4); WPA_PUT_BE32(pos, data); } // encr >> 16 B 64 - 16 = 48 static inline void wpabuf_put_data(struct wpabuf *buf, const void *data, size_t len) { if ( buf == NULL) return; if (data) os_memcpy(wpabuf_put(buf, len), data, len); } static inline void wpabuf_put_buf(struct wpabuf *dst, const struct wpabuf *src) { if ( dst == NULL) return; wpabuf_put_data(dst, wpabuf_head(src), wpabuf_len(src)); } static inline void wpabuf_set(struct wpabuf *buf, const void *data, size_t len) { if ( buf == NULL) return; buf->buf = (u8 *) data; buf->flags = WPABUF_FLAG_EXT_DATA; buf->size = buf->used = len; } static inline void wpabuf_put_str(struct wpabuf *dst, const char *str) { if ( dst == NULL) return; wpabuf_put_data(dst, str, os_strlen(str)); } #endif /* WPABUF_H */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/rtw_wpa_supplicant/src/utils/wpabuf.h
C
apache-2.0
4,553
/* * Wi-Fi Protected Setup - message definitions * Copyright (c) 2008, Jouni Malinen <j@w1.fi> * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #ifndef WPS_DEFS_H #define WPS_DEFS_H #ifdef CONFIG_WPS2 #define WPS_VERSION 0x20 #else /* CONFIG_WPS2 */ #define WPS_VERSION 0x10 #endif /* CONFIG_WPS2 */ /* Diffie-Hellman 1536-bit MODP Group; RFC 3526, Group 5 */ #define WPS_DH_GROUP (5) #define WPS_UUID_LEN (16) #define WPS_NONCE_LEN (16) #define WPS_AUTHENTICATOR_LEN (8) #define WPS_AUTHKEY_LEN (32) #define WPS_KEYWRAPKEY_LEN (16) #define WPS_EMSK_LEN (32) #define WPS_PSK_LEN (16) #define WPS_SECRET_NONCE_LEN (16) #define WPS_HASH_LEN (32) #define WPS_KWA_LEN (8) #define WPS_MGMTAUTHKEY_LEN (32) #define WPS_MGMTENCKEY_LEN (16) #define WPS_MGMT_KEY_ID_LEN (16) #define WPS_OOB_DEVICE_PASSWORD_MIN_LEN (16) #define WPS_OOB_DEVICE_PASSWORD_LEN (32) #define WPS_OOB_PUBKEY_HASH_LEN (20) /* Attribute Types */ enum wps_attribute { ATTR_AP_CHANNEL = 0x1001, ATTR_ASSOC_STATE = 0x1002, ATTR_AUTH_TYPE = 0x1003, ATTR_AUTH_TYPE_FLAGS = 0x1004, ATTR_AUTHENTICATOR = 0x1005, ATTR_CONFIG_METHODS = 0x1008, ATTR_CONFIG_ERROR = 0x1009, ATTR_CONFIRM_URL4 = 0x100a, ATTR_CONFIRM_URL6 = 0x100b, ATTR_CONN_TYPE = 0x100c, ATTR_CONN_TYPE_FLAGS = 0x100d, ATTR_CRED = 0x100e, ATTR_ENCR_TYPE = 0x100f, ATTR_ENCR_TYPE_FLAGS = 0x1010, ATTR_DEV_NAME = 0x1011, ATTR_DEV_PASSWORD_ID = 0x1012, ATTR_E_HASH1 = 0x1014, ATTR_E_HASH2 = 0x1015, ATTR_E_SNONCE1 = 0x1016, ATTR_E_SNONCE2 = 0x1017, ATTR_ENCR_SETTINGS = 0x1018, ATTR_ENROLLEE_NONCE = 0x101a, ATTR_FEATURE_ID = 0x101b, ATTR_IDENTITY = 0x101c, ATTR_IDENTITY_PROOF = 0x101d, ATTR_KEY_WRAP_AUTH = 0x101e, ATTR_KEY_ID = 0x101f, ATTR_MAC_ADDR = 0x1020, ATTR_MANUFACTURER = 0x1021, ATTR_MSG_TYPE = 0x1022, ATTR_MODEL_NAME = 0x1023, ATTR_MODEL_NUMBER = 0x1024, ATTR_NETWORK_INDEX = 0x1026, ATTR_NETWORK_KEY = 0x1027, ATTR_NETWORK_KEY_INDEX = 0x1028, ATTR_NEW_DEVICE_NAME = 0x1029, ATTR_NEW_PASSWORD = 0x102a, ATTR_OOB_DEVICE_PASSWORD = 0x102c, ATTR_OS_VERSION = 0x102d, ATTR_POWER_LEVEL = 0x102f, ATTR_PSK_CURRENT = 0x1030, ATTR_PSK_MAX = 0x1031, ATTR_PUBLIC_KEY = 0x1032, ATTR_RADIO_ENABLE = 0x1033, ATTR_REBOOT = 0x1034, ATTR_REGISTRAR_CURRENT = 0x1035, ATTR_REGISTRAR_ESTABLISHED = 0x1036, ATTR_REGISTRAR_LIST = 0x1037, ATTR_REGISTRAR_MAX = 0x1038, ATTR_REGISTRAR_NONCE = 0x1039, ATTR_REQUEST_TYPE = 0x103a, ATTR_RESPONSE_TYPE = 0x103b, ATTR_RF_BANDS = 0x103c, ATTR_R_HASH1 = 0x103d, ATTR_R_HASH2 = 0x103e, ATTR_R_SNONCE1 = 0x103f, ATTR_R_SNONCE2 = 0x1040, ATTR_SELECTED_REGISTRAR = 0x1041, ATTR_SERIAL_NUMBER = 0x1042, ATTR_WPS_STATE = 0x1044, ATTR_SSID = 0x1045, ATTR_TOTAL_NETWORKS = 0x1046, ATTR_UUID_E = 0x1047, ATTR_UUID_R = 0x1048, ATTR_VENDOR_EXT = 0x1049, ATTR_VERSION = 0x104a, ATTR_X509_CERT_REQ = 0x104b, ATTR_X509_CERT = 0x104c, ATTR_EAP_IDENTITY = 0x104d, ATTR_MSG_COUNTER = 0x104e, ATTR_PUBKEY_HASH = 0x104f, ATTR_REKEY_KEY = 0x1050, ATTR_KEY_LIFETIME = 0x1051, ATTR_PERMITTED_CFG_METHODS = 0x1052, ATTR_SELECTED_REGISTRAR_CONFIG_METHODS = 0x1053, ATTR_PRIMARY_DEV_TYPE = 0x1054, ATTR_SECONDARY_DEV_TYPE_LIST = 0x1055, ATTR_PORTABLE_DEV = 0x1056, ATTR_AP_SETUP_LOCKED = 0x1057, ATTR_APPLICATION_EXT = 0x1058, ATTR_EAP_TYPE = 0x1059, ATTR_IV = 0x1060, ATTR_KEY_PROVIDED_AUTO = 0x1061, ATTR_802_1X_ENABLED = 0x1062, ATTR_APPSESSIONKEY = 0x1063, ATTR_WEPTRANSMITKEY = 0x1064, ATTR_REQUESTED_DEV_TYPE = 0x106a, ATTR_EXTENSIBILITY_TEST = 0x10fa /* _NOT_ defined in the spec */ }; #define WPS_VENDOR_ID_WFA 14122 /* WFA Vendor Extension subelements */ enum { WFA_ELEM_VERSION2 = 0x00, WFA_ELEM_AUTHORIZEDMACS = 0x01, WFA_ELEM_NETWORK_KEY_SHAREABLE = 0x02, WFA_ELEM_REQUEST_TO_ENROLL = 0x03, WFA_ELEM_SETTINGS_DELAY_TIME = 0x04 }; /* Device Password ID */ enum wps_dev_password_id { DEV_PW_DEFAULT = 0x0000, DEV_PW_USER_SPECIFIED = 0x0001, DEV_PW_MACHINE_SPECIFIED = 0x0002, DEV_PW_REKEY = 0x0003, DEV_PW_PUSHBUTTON = 0x0004, DEV_PW_REGISTRAR_SPECIFIED = 0x0005 }; /* Message Type */ enum wps_msg_type { WPS_START = 0x00, WPS_Beacon = 0x01, WPS_ProbeRequest = 0x02, WPS_ProbeResponse = 0x03, WPS_M1 = 0x04, WPS_M2 = 0x05, WPS_M2D = 0x06, WPS_M3 = 0x07, WPS_M4 = 0x08, WPS_M5 = 0x09, WPS_M6 = 0x0a, WPS_M7 = 0x0b, WPS_M8 = 0x0c, WPS_WSC_ACK = 0x0d, WPS_WSC_NACK = 0x0e, WPS_WSC_DONE = 0x0f }; /* Authentication Type Flags */ #define WPS_AUTH_OPEN 0x0001 #define WPS_AUTH_WPAPSK 0x0002 #define WPS_AUTH_SHARED 0x0004 #define WPS_AUTH_WPA 0x0008 #define WPS_AUTH_WPA2 0x0010 #define WPS_AUTH_WPA2PSK 0x0020 #define WPS_AUTH_TYPES (WPS_AUTH_OPEN | WPS_AUTH_WPAPSK | WPS_AUTH_SHARED | \ WPS_AUTH_WPA | WPS_AUTH_WPA2 | WPS_AUTH_WPA2PSK) /* Encryption Type Flags */ #define WPS_ENCR_NONE 0x0001 #define WPS_ENCR_WEP 0x0002 #define WPS_ENCR_TKIP 0x0004 #define WPS_ENCR_AES 0x0008 #define WPS_ENCR_TYPES (WPS_ENCR_NONE | WPS_ENCR_WEP | WPS_ENCR_TKIP | \ WPS_ENCR_AES) /* Configuration Error */ enum wps_config_error { WPS_CFG_NO_ERROR = 0, WPS_CFG_OOB_IFACE_READ_ERROR = 1, WPS_CFG_DECRYPTION_CRC_FAILURE = 2, WPS_CFG_24_CHAN_NOT_SUPPORTED = 3, WPS_CFG_50_CHAN_NOT_SUPPORTED = 4, WPS_CFG_SIGNAL_TOO_WEAK = 5, WPS_CFG_NETWORK_AUTH_FAILURE = 6, WPS_CFG_NETWORK_ASSOC_FAILURE = 7, WPS_CFG_NO_DHCP_RESPONSE = 8, WPS_CFG_FAILED_DHCP_CONFIG = 9, WPS_CFG_IP_ADDR_CONFLICT = 10, WPS_CFG_NO_CONN_TO_REGISTRAR = 11, WPS_CFG_MULTIPLE_PBC_DETECTED = 12, WPS_CFG_ROGUE_SUSPECTED = 13, WPS_CFG_DEVICE_BUSY = 14, WPS_CFG_SETUP_LOCKED = 15, WPS_CFG_MSG_TIMEOUT = 16, WPS_CFG_REG_SESS_TIMEOUT = 17, WPS_CFG_DEV_PASSWORD_AUTH_FAILURE = 18 }; /* RF Bands */ #define WPS_RF_24GHZ (0x01) #define WPS_RF_50GHZ (0x02) /* Config Methods */ #define WPS_CONFIG_USBA (0x0001) #define WPS_CONFIG_ETHERNET (0x0002) #define WPS_CONFIG_LABEL (0x0004) #define WPS_CONFIG_DISPLAY (0x0008) #define WPS_CONFIG_EXT_NFC_TOKEN (0x0010) #define WPS_CONFIG_INT_NFC_TOKEN (0x0020) #define WPS_CONFIG_NFC_INTERFACE (0x0040) #define WPS_CONFIG_PUSHBUTTON (0x0080) #define WPS_CONFIG_KEYPAD (0x0100) #ifdef CONFIG_WPS2 #define WPS_CONFIG_VIRT_PUSHBUTTON (0x0280) #define WPS_CONFIG_PHY_PUSHBUTTON (0x0480) #define WPS_CONFIG_VIRT_DISPLAY (0x2008) #define WPS_CONFIG_PHY_DISPLAY (0x4008) #endif /* CONFIG_WPS2 */ /* Connection Type Flags */ #define WPS_CONN_ESS (0x01) #define WPS_CONN_IBSS (0x02) /* Wi-Fi Protected Setup State */ enum wps_state { WPS_STATE_NOT_CONFIGURED = 1, WPS_STATE_CONFIGURED = 2 }; /* Association State */ enum wps_assoc_state { WPS_ASSOC_NOT_ASSOC = 0, WPS_ASSOC_CONN_SUCCESS = 1, WPS_ASSOC_CFG_FAILURE = 2, WPS_ASSOC_FAILURE = 3, WPS_ASSOC_IP_FAILURE = 4 }; #define WPS_DEV_OUI_WFA (0x0050f204) enum wps_dev_categ { WPS_DEV_COMPUTER = 1, WPS_DEV_INPUT = 2, WPS_DEV_PRINTER = 3, WPS_DEV_CAMERA = 4, WPS_DEV_STORAGE = 5, WPS_DEV_NETWORK_INFRA = 6, WPS_DEV_DISPLAY = 7, WPS_DEV_MULTIMEDIA = 8, WPS_DEV_GAMING = 9, WPS_DEV_PHONE = 10 }; enum wps_dev_subcateg { WPS_DEV_COMPUTER_PC = 1, WPS_DEV_COMPUTER_SERVER = 2, WPS_DEV_COMPUTER_MEDIA_CENTER = 3, WPS_DEV_PRINTER_PRINTER = 1, WPS_DEV_PRINTER_SCANNER = 2, WPS_DEV_CAMERA_DIGITAL_STILL_CAMERA = 1, WPS_DEV_STORAGE_NAS = 1, WPS_DEV_NETWORK_INFRA_AP = 1, WPS_DEV_NETWORK_INFRA_ROUTER = 2, WPS_DEV_NETWORK_INFRA_SWITCH = 3, WPS_DEV_DISPLAY_TV = 1, WPS_DEV_DISPLAY_PICTURE_FRAME = 2, WPS_DEV_DISPLAY_PROJECTOR = 3, WPS_DEV_MULTIMEDIA_DAR = 1, WPS_DEV_MULTIMEDIA_PVR = 2, WPS_DEV_MULTIMEDIA_MCX = 3, WPS_DEV_GAMING_XBOX = 1, WPS_DEV_GAMING_XBOX360 = 2, WPS_DEV_GAMING_PLAYSTATION = 3, WPS_DEV_PHONE_WINDOWS_MOBILE = 1 }; /* Request Type */ enum wps_request_type { WPS_REQ_ENROLLEE_INFO = 0, WPS_REQ_ENROLLEE = 1, WPS_REQ_REGISTRAR = 2, WPS_REQ_WLAN_MANAGER_REGISTRAR = 3 }; /* Response Type */ enum wps_response_type { WPS_RESP_ENROLLEE_INFO = 0, WPS_RESP_ENROLLEE = 1, WPS_RESP_REGISTRAR = 2, WPS_RESP_AP = 3 }; /* Walk Time for push button configuration (in seconds) */ #define WPS_PBC_WALK_TIME (120) #define WPS_MAX_AUTHORIZED_MACS (5) #endif /* WPS_DEFS_H */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/rtw_wpa_supplicant/src/wps/wps_defs.h
C
apache-2.0
8,546
#if !defined(CONFIG_MBED_ENABLED) #include "main.h" #include <lwip_netconf.h> #include <lwip/netif.h> #endif #include <stdio.h> #include <string.h> #include <stdlib.h> #include <osdep_service.h> #include "utils/os.h" #include "wifi/wifi_conf.h" #include <platform/platform_stdlib.h> #define WLAN0_NAME "wlan0" #ifndef ENABLE #define ENABLE (1) #endif #ifndef DISABLE #define DISABLE (0) #endif u8 eap_phase = 0; u8 eap_method = 0; // eap config arguments char *eap_target_ssid = NULL; char *eap_identity = NULL; char *eap_password = NULL; // if set eap_ca_cert and defined(EAP_SSL_VERIFY_SERVER), client will verify server's cert const unsigned char *eap_ca_cert = NULL; // if set eap_client_cert, eap_client_key, and defined(EAP_SSL_VERIFY_CLIENT), client will send its cert to server const unsigned char *eap_client_cert = NULL; const unsigned char *eap_client_key = NULL; char *eap_client_key_pwd = NULL; void eap_eapol_recvd_hdl(char *buf, int buf_len, int flags, void* handler_user_data); void eap_eapol_start_hdl(char *buf, int buf_len, int flags, void* handler_user_data); int connect_by_open_system(char *target_ssid); void set_eap_phase(unsigned char is_trigger_eap){ eap_phase = is_trigger_eap; } int get_eap_phase(void){ return eap_phase; } int get_eap_method(void){ return eap_method; } #if !defined(CONFIG_MBED_ENABLED) void reset_config(void){ eap_target_ssid = NULL; eap_identity = NULL; eap_password = NULL; eap_ca_cert = NULL; eap_client_cert = NULL; eap_client_key = NULL; eap_client_key_pwd = NULL; } void judge_station_disconnect(void) { int mode = 0; unsigned char ssid[33]; wext_get_mode(WLAN0_NAME, &mode); switch(mode) { case IW_MODE_MASTER: //In AP mode wifi_off(); rtw_msleep_os(20); wifi_on(RTW_MODE_STA); break; case IW_MODE_INFRA: //In STA mode if(wext_get_ssid(WLAN0_NAME, ssid) > 0) wifi_disconnect(); } } extern void eap_peer_unregister_methods(void); extern void eap_sm_deinit(void); void eap_disconnected_hdl(char *buf, int buf_len, int flags, void* handler_user_data){ /* To avoid gcc warnings */ ( void ) buf; ( void ) buf_len; ( void ) flags; ( void ) handler_user_data; // printf("disconnected\n"); #if (RTL8192E_SUPPORT == 0)//devin_li rtl8192es_temp_mask wifi_unreg_event_handler(WIFI_EVENT_EAPOL_RECVD, eap_eapol_recvd_hdl); wifi_unreg_event_handler(WIFI_EVENT_DISCONNECT, eap_disconnected_hdl); eap_peer_unregister_methods(); eap_sm_deinit(); //reset_config(); #endif } /* void eap_config(void){ eap_target_ssid = "Test_eap"; eap_identity = "guest2"; eap_password = "test2"; eap_client_cert = \ "-----BEGIN CERTIFICATE-----\r\n" \ "MIIC9zCCAd8CAQMwDQYJKoZIhvcNAQEEBQAwgZMxCzAJBgNVBAYTAkZSMQ8wDQYD\r\n" \ "VQQIEwZSYWRpdXMxEjAQBgNVBAcTCVNvbWV3aGVyZTEVMBMGA1UEChMMRXhhbXBs\r\n" \ "ZSBJbmMuMSAwHgYJKoZIhvcNAQkBFhFhZG1pbkBleGFtcGxlLmNvbTEmMCQGA1UE\r\n" \ "AxMdRXhhbXBsZSBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcNMTYwMzE1MDgwNzEx\r\n" \ "WhcNMTcwMzE1MDgwNzExWjBzMQswCQYDVQQGEwJGUjEPMA0GA1UECBMGUmFkaXVz\r\n" \ "MRUwEwYDVQQKEwxFeGFtcGxlIEluYy4xGjAYBgNVBAMUEXVzZXIyQGV4YW1wbGUu\r\n" \ "Y29tMSAwHgYJKoZIhvcNAQkBFhF1c2VyMkBleGFtcGxlLmNvbTCBnzANBgkqhkiG\r\n" \ "9w0BAQEFAAOBjQAwgYkCgYEAqESlV4OYfBcIgZ+Cs8mWpiBjhvKoa0/kIe7saqhC\r\n" \ "e5q4snox0jdkUpLcc4vOs3vQ7ZGnimqTltA9oF6XNUzTWW4vlJTKEfrCWK085l7c\r\n" \ "DHFvHavH3E6vuP71lI7jq4PLXbo2TvZK+uBul4ozjzVWihaZBtz8eLHq446h/D/p\r\n" \ "kzkCAwEAATANBgkqhkiG9w0BAQQFAAOCAQEAAfhVAIkNdeeUNJud720uUHVnIcxz\r\n" \ "GXWI+Svi1qchuTEnRNhLwXmnE+A0WWSHyfdR6FvzdT3xtz3K50iOif8jY2gCGkSK\r\n" \ "8RjKr97228SwbrGO9y9+dYIjH1uz9cBpoVKcpzdsWpKObrDPDYyReHSWo99jM2+O\r\n" \ "vfJxnBw4PLiBj7Q0/dpd6o4JXyp7Cxa0mB4/+cZqjCzzuKfuK3WP7j6laMCV6mg4\r\n" \ "wRZ528IdwDqB7OOqsDm1PVQM8vzny9PM6ikWUCRTVNQJN8RDLkrHR3FRjy15YLdt\r\n" \ "yOfDqVnT/z0wGBaxnNziSJjqPGHPpRi4bJFGXwXOhtknKmciKzfj9/npoQ==\r\n" \ "-----END CERTIFICATE-----\r\n"; eap_client_key = \ "-----BEGIN RSA PRIVATE KEY-----\r\n" \ "MIICXQIBAAKBgQCoRKVXg5h8FwiBn4KzyZamIGOG8qhrT+Qh7uxqqEJ7mriyejHS\r\n" \ "N2RSktxzi86ze9DtkaeKapOW0D2gXpc1TNNZbi+UlMoR+sJYrTzmXtwMcW8dq8fc\r\n" \ "Tq+4/vWUjuOrg8tdujZO9kr64G6XijOPNVaKFpkG3Px4serjjqH8P+mTOQIDAQAB\r\n" \ "AoGARI+LyweshssfxSkIKVc3EcNaqi6PHwJzUrw2ChM624AkR1xwllXJg7ehKVdK\r\n" \ "xmjprRLO8CASuL1qjsBb3fTKnBl+sIVxIFS0AI4Y3ri8VUKbangvSsI7pCzAFry7\r\n" \ "p1gmy9WWRV2ZEa+dV8xcrjb3bloT7hcdeLehgBCvExJIQM0CQQDXlSAKdW3AhYyj\r\n" \ "1A+pfyBSGxJbpSwNyyWgwHIHHjxendxmdUbrc8EbAu1eNKbP58TLgdCZsKcMonAv\r\n" \ "MY1Y2/nnAkEAx9CrUaCU8pJqXTRypM5JtexLKnYMJhpnA9uUILBQOq4Oe0eruyF5\r\n" \ "SaSxhyJYXY491ahWYPF0PTb3jkUhoN+l3wJBAJZthjgGDJlEFwjSFkOtYz4nib3N\r\n" \ "GVpeoFj1MBvrazCScpJDz0LIOLzCZCNSFfwIu3dNk+NKMqZMSn+D0h9pD40CQQC5\r\n" \ "K9n4NXaTLbjAU2CC9mE85JPr76XmkcUxwAWQHZTcLH1jJdIyAx1hb+zNLLjzSmRn\r\n" \ "Yi9ae6ibKhtUjyBQ87HFAkA2Bb3z7NUx+AA2g2HZocFZFShBxylACyQkl8FAFZtf\r\n" \ "osudmKdFQHyAWuBMex4tpz/OLTqJ1ecL1JQeC7OvlpEX\r\n" \ "-----END RSA PRIVATE KEY-----\r\n"; eap_ca_cert = \ "-----BEGIN CERTIFICATE-----\r\n" \ "MIIEpzCCA4+gAwIBAgIJAPvZaozpdfjkMA0GCSqGSIb3DQEBCwUAMIGTMQswCQYD\r\n" \ "VQQGEwJGUjEPMA0GA1UECBMGUmFkaXVzMRIwEAYDVQQHEwlTb21ld2hlcmUxFTAT\r\n" \ "BgNVBAoTDEV4YW1wbGUgSW5jLjEgMB4GCSqGSIb3DQEJARYRYWRtaW5AZXhhbXBs\r\n" \ "ZS5jb20xJjAkBgNVBAMTHUV4YW1wbGUgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MB4X\r\n" \ "DTE2MDMxNDExMjU0OVoXDTE2MDQxMzExMjU0OVowgZMxCzAJBgNVBAYTAkZSMQ8w\r\n" \ "DQYDVQQIEwZSYWRpdXMxEjAQBgNVBAcTCVNvbWV3aGVyZTEVMBMGA1UEChMMRXhh\r\n" \ "bXBsZSBJbmMuMSAwHgYJKoZIhvcNAQkBFhFhZG1pbkBleGFtcGxlLmNvbTEmMCQG\r\n" \ "A1UEAxMdRXhhbXBsZSBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0GCSqGSIb3\r\n" \ "DQEBAQUAA4IBDwAwggEKAoIBAQC9pireu0aCDLNfMaGv3vId7RXjUhQwSK0jV2Oc\r\n" \ "SyvlKWH3P/N+5kLrP2iL6SCzyETVDXZ0vOsAMjcBF0zHp16prXV0d51cTUqeWBb0\r\n" \ "I5UnGxleIuuOfSg8zLUJoBWZPqLv++eZ5WgOKHt7SXocjvg7TU5t/TMB0Y8OCz3H\r\n" \ "CW2vJ/XKMgMA9HDUu4g57cJu88i1JPRpyFaz/HIQBc7+UNb9z+q09uTZKWTmEMqi\r\n" \ "E2U0EEIs7EtbxnOze1/8C4XNlmztrEdwvu6UEBU/TFkUoh9M646NkkBK7wP9n9pv\r\n" \ "T0nPQRJiiCrICzVqUtlEi9lIKpbBSMbQ0KzrGF7lGTgm4rz9AgMBAAGjgfswgfgw\r\n" \ "HQYDVR0OBBYEFIVyecka74kvOKIW0BjlTc/B+a2NMIHIBgNVHSMEgcAwgb2AFIVy\r\n" \ "ecka74kvOKIW0BjlTc/B+a2NoYGZpIGWMIGTMQswCQYDVQQGEwJGUjEPMA0GA1UE\r\n" \ "CBMGUmFkaXVzMRIwEAYDVQQHEwlTb21ld2hlcmUxFTATBgNVBAoTDEV4YW1wbGUg\r\n" \ "SW5jLjEgMB4GCSqGSIb3DQEJARYRYWRtaW5AZXhhbXBsZS5jb20xJjAkBgNVBAMT\r\n" \ "HUV4YW1wbGUgQ2VydGlmaWNhdGUgQXV0aG9yaXR5ggkA+9lqjOl1+OQwDAYDVR0T\r\n" \ "BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAZYHM26sxbKOckVqJJ1QY0U2QFlGP\r\n" \ "1GYd8v27znxdnRmSonDvv3GjFfhwoyDk0JUuxkK/33ikCxihrgoO/EQTY9BV2OpW\r\n" \ "qkB1PDtb3i5ZRNvfjmW0pVA4p+GmdTGaEE5pTlcVnorzVrUeFKaZakb+IDFYzmeF\r\n" \ "xp8B3Bb5wvinDligLOaJnSlgS8QeeIab9HZfaVTTuPmVK6zE6D54Y0dJPnykvDdE\r\n" \ "cGN0FC+migfilFjJgkDJ0r78nwes55L8zjoofiZuO03rrHww6ARc3v1jYzAufddk\r\n" \ "QTiZHgjlMQb2XXMmXLn8kBgoDnqkXFNe8j0h8uxIJSrjOoIyn1h1wvX5/w==\r\n" \ "-----END CERTIFICATE-----\r\n"; } */ int eap_start(char *method) { /* To avoid gcc warnings */ ( void ) method; #ifdef CONFIG_ENABLE_EAP int ret = -1; //unsigned long tick1 = xTaskGetTickCount(); //unsigned long tick2; if(rltk_wlan_running(WLAN1_IDX)){ printf("\n\rNot support con-current mode!\n\r"); return -1; } judge_station_disconnect(); #if CONFIG_ENABLE_PEAP if(strcmp(method,"peap") == 0){ ret = set_eap_peap_method(); } #endif #if CONFIG_ENABLE_TLS if(strcmp(method,"tls") == 0){ ret = set_eap_tls_method(); } #endif #if CONFIG_ENABLE_TTLS if(strcmp(method,"ttls") == 0){ ret = set_eap_ttls_method(); } #endif if(ret == -1){ printf("\r\neap method %s not supported\r\n", method); return -1; } eap_method = get_eap_ctx_method(); printf("\n==================== %s_start ====================\n", method); //eap_config(); set_eap_phase(ENABLE); wifi_reg_event_handler(WIFI_EVENT_EAPOL_START, eap_eapol_start_hdl, NULL); wifi_reg_event_handler(WIFI_EVENT_EAPOL_RECVD, eap_eapol_recvd_hdl, NULL); ret = connect_by_open_system(eap_target_ssid); #if CONFIG_LWIP_LAYER /* Start DHCPClient */ if(ret == 0) LwIP_DHCP(0, DHCP_START); #endif wifi_unreg_event_handler(WIFI_EVENT_EAPOL_START, eap_eapol_start_hdl); // for re-authentication when session timeout wifi_reg_event_handler(WIFI_EVENT_DISCONNECT, eap_disconnected_hdl, NULL); //wifi_unreg_event_handler(WIFI_EVENT_EAPOL_RECVD, eap_eapol_recvd_hdl); set_eap_phase(DISABLE); // eap failed, disconnect if(ret != 0){ judge_station_disconnect(); eap_disconnected_hdl(NULL, 0, 0, NULL); rtw_msleep_os(200); //wait handler done printf("\r\nERROR: connect to AP by %s failed\n", method); } eap_sm_deinit(); printf("\n==================== %s_finish ====================\n", method); //tick2 = xTaskGetTickCount(); //printf("\r\nConnected after %dms.\n", (tick2-tick1)); return ret; #else return -1; #endif } int connect_by_open_system(char *target_ssid) { int retry_count = 0, ret; if (target_ssid != NULL) { while (1) { rtw_msleep_os(500); //wait scan complete. ret = wifi_connect(target_ssid, RTW_SECURITY_OPEN, NULL, strlen(target_ssid), 0, 0, NULL); if (ret == RTW_SUCCESS) { //printf("\r\n[EAP]Associate with AP success\n"); break; } if (retry_count == 0) { //printf("\r\n[EAP]Associate with AP failed %d\n", ret); return -1; } retry_count --; printf("Retry connection...\n"); judge_station_disconnect(); set_eap_phase(ENABLE); } } else { printf("\r\n[EAP]Target SSID is NULL\n"); return -1; } return 0; } void eap_autoreconnect_thread(void *method) { eap_start((char*)method); //vTaskDelete(NULL); aos_task_exit(0); } #endif void eap_autoreconnect_hdl(u8 method_id) { /* To avoid gcc warnings */ ( void ) method_id; #ifdef CONFIG_ENABLE_EAP char *method; switch(method_id){ case 25: // EAP_TYPE_PEAP method = "peap"; break; case 13: // EAP_TYPE_TLS method = "tls"; break; case 21: // EAP_TYPE_TTLS method = "ttls"; break; default: printf("invalid eap method\n"); return; } //if(xTaskCreate(eap_autoreconnect_thread, ((const char*)"eap_autoreconnect_thread"), 1024, (void*) method, tskIDLE_PRIORITY + 1, NULL) != pdPASS) // printf("\n\r%s xTaskCreate failed\n", __FUNCTION__); aos_task_new("eap_autoreconnect_thread", eap_autoreconnect_thread, method, 1024); #endif } //#if CONFIG_MBED_ENABLED // copy from ssl_client_ext.c #if CONFIG_USE_POLARSSL #include <polarssl/ssl.h> #include <polarssl/memory.h> int max_buf_bio_size = SSL_BUFFER_LEN; #if ENABLE_EAP_SSL_VERIFY_CLIENT static x509_crt* _cli_crt = NULL; static pk_context* _clikey_rsa = NULL; #endif #if ENABLE_EAP_SSL_VERIFY_SERVER static x509_crt* _ca_crt = NULL; static int eap_verify(void *data, x509_crt *crt, int depth, int *flags) { //char buf[1024]; ((void) data); printf("\nVerify requested for (Depth %d):\n", depth); //x509_crt_info(buf, sizeof(buf) - 1, "", crt); //printf("%s", buf); if(((*flags) & BADCERT_EXPIRED) != 0) printf("server certificate has expired\n"); if(((*flags) & BADCERT_REVOKED) != 0) printf(" ! server certificate has been revoked\n"); if(((*flags) & BADCERT_CN_MISMATCH) != 0) printf(" ! CN mismatch\n"); if(((*flags) & BADCERT_NOT_TRUSTED) != 0) printf(" ! self-signed or not signed by a trusted CA\n"); if(((*flags) & BADCRL_NOT_TRUSTED) != 0) printf(" ! CRL not trusted\n"); if(((*flags) & BADCRL_EXPIRED) != 0) printf(" ! CRL expired\n"); if(((*flags) & BADCERT_OTHER) != 0) printf(" ! other (unknown) flag\n"); if((*flags) == 0) printf(" Certificate verified without error flags\n"); return(0); } #endif int eap_cert_init(void) { #if ENABLE_EAP_SSL_VERIFY_CLIENT if(eap_client_cert != NULL && eap_client_key != NULL){ _cli_crt = polarssl_malloc(sizeof(x509_crt)); if(_cli_crt) x509_crt_init(_cli_crt); else return -1; _clikey_rsa = polarssl_malloc(sizeof(pk_context)); if(_clikey_rsa) pk_init(_clikey_rsa); else return -1; } #endif #if ENABLE_EAP_SSL_VERIFY_SERVER if(eap_ca_cert != NULL){ _ca_crt = polarssl_malloc(sizeof(x509_crt)); if(_ca_crt) x509_crt_init(_ca_crt); else return -1; } #endif return 0; } void eap_client_cert_free(void) { #if ENABLE_EAP_SSL_VERIFY_CLIENT if(eap_client_cert != NULL && eap_client_key != NULL){ if(_cli_crt) { x509_crt_free(_cli_crt); polarssl_free(_cli_crt); _cli_crt = NULL; } if(_clikey_rsa) { pk_free(_clikey_rsa); polarssl_free(_clikey_rsa); _clikey_rsa = NULL; } } #endif } void eap_server_cert_free(void) { #if ENABLE_EAP_SSL_VERIFY_SERVER if(eap_ca_cert != NULL){ if(_ca_crt) { x509_crt_free(_ca_crt); polarssl_free(_ca_crt); _ca_crt = NULL; } } #endif } int eap_cert_setup(ssl_context *ssl) { #if ENABLE_EAP_SSL_VERIFY_CLIENT if(eap_client_cert != NULL && eap_client_key != NULL){ if(x509_crt_parse(_cli_crt, eap_client_cert, strlen(eap_client_cert)) != 0) return -1; if(pk_parse_key(_clikey_rsa, eap_client_key, strlen(eap_client_key), eap_client_key_pwd, strlen(eap_client_key_pwd)) != 0) return -1; ssl_set_own_cert(ssl, _cli_crt, _clikey_rsa); } #endif #if ENABLE_EAP_SSL_VERIFY_SERVER if(eap_ca_cert != NULL){ if(x509_crt_parse(_ca_crt, eap_ca_cert, strlen(eap_ca_cert)) != 0) return -1; ssl_set_ca_chain(ssl, _ca_crt, NULL, NULL); ssl_set_authmode(ssl, SSL_VERIFY_REQUIRED); ssl_set_verify(ssl, eap_verify, NULL); } #endif return 0; } #elif CONFIG_USE_MBEDTLS #include <mbedtls/config.h> #include <mbedtls/platform.h> #include <mbedtls/ssl.h> #include <mbedtls/ssl_internal.h> int max_buf_bio_size = MBEDTLS_SSL_IN_BUFFER_LEN; struct eap_tls{ void *ssl; void *conf; void *fd; }; #if (defined(ENABLE_EAP_SSL_VERIFY_CLIENT) && ENABLE_EAP_SSL_VERIFY_CLIENT) static mbedtls_x509_crt* _cli_crt = NULL; static mbedtls_pk_context* _clikey_rsa = NULL; #endif #if (defined(ENABLE_EAP_SSL_VERIFY_SERVER) && ENABLE_EAP_SSL_VERIFY_SERVER) static mbedtls_x509_crt* _ca_crt = NULL; static int eap_verify(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags) { //char buf[1024]; ((void) data); printf("\nVerify requested for (Depth %d):\n", depth); //mbedtls_x509_crt_info(buf, sizeof(buf) - 1, "", crt); //printf("%s", buf); if(((*flags) & MBEDTLS_X509_BADCERT_EXPIRED) != 0) printf("server certificate has expired\n"); if(((*flags) & MBEDTLS_X509_BADCERT_REVOKED) != 0) printf(" ! server certificate has been revoked\n"); if(((*flags) & MBEDTLS_X509_BADCERT_CN_MISMATCH) != 0) printf(" ! CN mismatch\n"); if(((*flags) & MBEDTLS_X509_BADCERT_NOT_TRUSTED) != 0) printf(" ! self-signed or not signed by a trusted CA\n"); if(((*flags) & MBEDTLS_X509_BADCRL_NOT_TRUSTED) != 0) printf(" ! CRL not trusted\n"); if(((*flags) & MBEDTLS_X509_BADCRL_EXPIRED) != 0) printf(" ! CRL expired\n"); if(((*flags) & MBEDTLS_X509_BADCERT_OTHER) != 0) printf(" ! other (unknown) flag\n"); if((*flags) == 0) printf(" Certificate verified without error flags\n"); return(0); } #endif int eap_cert_init(void) { #if (defined(ENABLE_EAP_SSL_VERIFY_CLIENT) && ENABLE_EAP_SSL_VERIFY_CLIENT) if(eap_client_cert != NULL && eap_client_key != NULL){ _cli_crt = mbedtls_calloc(1, sizeof(mbedtls_x509_crt)); if(_cli_crt) mbedtls_x509_crt_init(_cli_crt); else return -1; _clikey_rsa = mbedtls_calloc(1, sizeof(mbedtls_pk_context)); if(_clikey_rsa) mbedtls_pk_init(_clikey_rsa); else return -1; } #endif #if (defined(ENABLE_EAP_SSL_VERIFY_SERVER) && ENABLE_EAP_SSL_VERIFY_SERVER) if(eap_ca_cert != NULL){ _ca_crt = mbedtls_calloc(1, sizeof(mbedtls_x509_crt)); if(_ca_crt) mbedtls_x509_crt_init(_ca_crt); else return -1; } #endif return 0; } void eap_client_cert_free(void) { #if (defined(ENABLE_EAP_SSL_VERIFY_CLIENT) && ENABLE_EAP_SSL_VERIFY_CLIENT) if(eap_client_cert != NULL && eap_client_key != NULL){ if(_cli_crt) { mbedtls_x509_crt_free(_cli_crt); mbedtls_free(_cli_crt); _cli_crt = NULL; } if(_clikey_rsa) { mbedtls_pk_free(_clikey_rsa); mbedtls_free(_clikey_rsa); _clikey_rsa = NULL; } } #endif } void eap_server_cert_free(void) { #if (defined(ENABLE_EAP_SSL_VERIFY_SERVER) && ENABLE_EAP_SSL_VERIFY_SERVER) if(eap_ca_cert != NULL){ if(_ca_crt) { mbedtls_x509_crt_free(_ca_crt); mbedtls_free(_ca_crt); _ca_crt = NULL; } } #endif } int eap_cert_setup(struct eap_tls *tls_context) { /* To avoid gcc warnings */ ( void ) tls_context; #if (defined(ENABLE_EAP_SSL_VERIFY_CLIENT) && ENABLE_EAP_SSL_VERIFY_CLIENT) if(eap_client_cert != NULL && eap_client_key != NULL){ if(mbedtls_x509_crt_parse(_cli_crt, eap_client_cert, strlen(eap_client_cert)+1) != 0) return -1; if(mbedtls_pk_parse_key(_clikey_rsa, eap_client_key, strlen(eap_client_key)+1, eap_client_key_pwd, strlen(eap_client_key_pwd)+1) != 0) return -1; mbedtls_ssl_conf_own_cert(tls_context->conf, _cli_crt, _clikey_rsa); } #endif #if (defined(ENABLE_EAP_SSL_VERIFY_SERVER) && ENABLE_EAP_SSL_VERIFY_SERVER) if(eap_ca_cert != NULL){ if(mbedtls_x509_crt_parse(_ca_crt, eap_ca_cert, strlen(eap_ca_cert)+1) != 0) return -1; mbedtls_ssl_conf_ca_chain(tls_context->conf, _ca_crt, NULL); mbedtls_ssl_conf_authmode(tls_context->conf, MBEDTLS_SSL_VERIFY_REQUIRED); mbedtls_ssl_conf_verify(tls_context->conf, eap_verify, NULL); } #endif return 0; } #endif /*CONFIG_USE_MBEDTLS*/ //#endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/rtw_wpa_supplicant/wpa_supplicant/wifi_eap_config.c
C
apache-2.0
17,248
#include "FreeRTOS.h" #include "task.h" #include "utils/os.h" #include <lwip/netif.h> #include <wifi/wifi_conf.h> #include "wps/wps_defs.h" #if CONFIG_ENABLE_P2P enum p2p_wps_method { WPS_NOT_READY, WPS_PIN_DISPLAY, WPS_PIN_KEYPAD, WPS_PBC }; /*NETMASK*/ #define P2P_NETMASK_ADDR0 255 #define P2P_NETMASK_ADDR1 255 #define P2P_NETMASK_ADDR2 255 #define P2P_NETMASK_ADDR3 0 /*Gateway Address*/ #define P2P_GW_ADDR0 192 #define P2P_GW_ADDR1 168 #define P2P_GW_ADDR2 42 #define P2P_GW_ADDR3 1 #define P2P_GO_NEGO_RESULT_SIZE 376//256 xqueue_handle_t queue_for_p2p_nego; extern void dhcps_init(struct netif * pnetif); static int hex2num(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; } /** * hwaddr_aton - Convert ASCII string to MAC address (colon-delimited format) * @txt: MAC address as a string (e.g., "00:11:22:33:44:55") * @addr: Buffer for the MAC address (ETH_ALEN = 6 bytes) * Returns: 0 on success, -1 on failure (e.g., string not a MAC address) */ int hwaddr_aton(const char *txt, u8 *addr) { int i; for (i = 0; i < 6; i++) { int a, b; a = hex2num(*txt++); if (a < 0) return -1; b = hex2num(*txt++); if (b < 0) return -1; *addr++ = (a << 4) | b; if (i < 5 && *txt++ != ':') return -1; } return 0; } int wifi_start_p2p_go(char *ssid, char *passphrase, u8 channel) { extern struct netif xnetif[NET_IF_NUM]; struct netif * pnetif = &xnetif[0]; struct ip_addr ipaddr; struct ip_addr netmask; struct ip_addr gw; #if LWIP_VERSION_MAJOR >= 2 IP4_ADDR(ip_2_ip4(&ipaddr), P2P_GW_ADDR0, P2P_GW_ADDR1, P2P_GW_ADDR2, P2P_GW_ADDR3); IP4_ADDR(ip_2_ip4(&netmask), P2P_NETMASK_ADDR0, P2P_NETMASK_ADDR1 , P2P_NETMASK_ADDR2, P2P_NETMASK_ADDR3); IP4_ADDR(ip_2_ip4(&gw), P2P_GW_ADDR0, P2P_GW_ADDR1, P2P_GW_ADDR2, P2P_GW_ADDR3); netif_set_addr(pnetif, ip_2_ip4(&ipaddr), ip_2_ip4(&netmask),ip_2_ip4(&gw)); #else IP4_ADDR(&ipaddr, P2P_GW_ADDR0, P2P_GW_ADDR1, P2P_GW_ADDR2, P2P_GW_ADDR3); IP4_ADDR(&netmask, P2P_NETMASK_ADDR0, P2P_NETMASK_ADDR1 , P2P_NETMASK_ADDR2, P2P_NETMASK_ADDR3); IP4_ADDR(&gw, P2P_GW_ADDR0, P2P_GW_ADDR1, P2P_GW_ADDR2, P2P_GW_ADDR3); netif_set_addr(pnetif, &ipaddr, &netmask,&gw); #endif // start ap if(wifi_start_ap(ssid, RTW_SECURITY_WPA2_AES_PSK, passphrase, strlen(ssid), strlen(passphrase), channel ) != RTW_SUCCESS) { printf("\n\rERROR: Operation failed!"); return -1; } netif_set_default(pnetif); // start dhcp server dhcps_init(pnetif); return 0; } void app_callback(char *msg) { //From Application } void cmd_wifi_p2p_start(int argc, char **argv) { extern struct netif xnetif[NET_IF_NUM]; int listen_ch = 1; int op_ch = 5; int go_intent = 1; #if 1 u32 r = 0; os_get_random((u8 *) &r, sizeof(r)); go_intent = r%15+1; /*1-15*/ os_get_random((u8 *) &r, sizeof(r)); listen_ch = 1 + (r % 3) * 5; os_get_random((u8 *) &r, sizeof(r)); op_ch = 1 + (r % 3) * 5; #endif wifi_off(); os_sleep(0, 20000); wifi_on(RTW_MODE_P2P); wifi_p2p_init(xnetif[0].hwaddr, go_intent, listen_ch, op_ch); } int cmd_wifi_p2p_auto_go_start(int argc, char **argv) { u8 *passphrase = "12345678"; u8 channel = 6; // 1, 6, 11 const char *ssid_in = "DIRECT-34-Ameba"; const char *dev_name = "Ameba1234"; // max strlen 32 const char *manufacturer = "by customer"; // max strlen 64 const char *model_name = "customer"; // max strlen 32 const char *model_number = "v2.0"; // max strlen 32 const char *serial_number = "9"; // max strlen 32 const u8 pri_dev_type[8] = {0x00,0x0A,0x00,0x50,0xF2,0x04,0x00,0x01}; // category ID:0x00,0x0A; sub category ID:0x00,0x01 u8 res[P2P_GO_NEGO_RESULT_SIZE]; u16 config_methods = WPS_CONFIG_DISPLAY | WPS_CONFIG_KEYPAD | WPS_CONFIG_PUSHBUTTON; if(!is_wifi_p2p_initialized()) return -1; wifi_p2p_set_dev_name(dev_name); wifi_p2p_set_manufacturer(manufacturer); wifi_p2p_set_model_name(model_name); wifi_p2p_set_model_number(model_number); wifi_p2p_set_serial_number(serial_number); wifi_p2p_set_pri_dev_type(pri_dev_type); wifi_p2p_set_ssid(ssid_in); wifi_p2p_set_config_methods(config_methods); wifi_p2p_init_auto_go_params(res, passphrase, channel); wifi_p2p_start_auto_go(res); return 0; } void cmd_wifi_p2p_stop(int argc, char **argv) { wifi_p2p_deinit(); wifi_off(); } void cmd_p2p_listen(int argc, char **argv) { u32 timeout = 0; if(argc == 2){ timeout = os_atoi((u8*)argv[1]); printf("\r\n%s(): timeout=%d\n", __func__, timeout); if(timeout > 3600) timeout = 3600; } wifi_cmd_p2p_listen(timeout); } void cmd_p2p_find(int argc, char **argv) { wifi_cmd_p2p_find(); } void cmd_p2p_peers(int argc, char **argv) { wifi_cmd_p2p_peers(); } void cmd_p2p_info(int argc, char **argv) { wifi_cmd_p2p_info(); } void cmd_p2p_disconnect(int argc, char **argv) { wifi_cmd_p2p_disconnect(); } void cmd_p2p_connect(int argc, char **argv) { enum p2p_wps_method config_method = WPS_PBC; char *pin = NULL; u8 dest[ETH_ALEN] = {0x44, 0x6d, 0x57, 0xd7, 0xce, 0x41}; u8 res[P2P_GO_NEGO_RESULT_SIZE]; int ret = 0, result = 0; #if 1 if((argc != 2) && (argc != 3) && (argc != 4)) { printf("\n\rUsage: p2p_connect DEST_ADDR [pbc|pin] [pin code]\n"); printf("\n\rExample: p2p_connect 00:e0:4c:87:00:15 pin 12345678\n"); return; } if (hwaddr_aton(argv[1], dest)){ printf("\r\nP2P_CONNECT: dest address is not correct!\n"); return; } //printf("\r\nDEST: %2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x\n", dest[0], dest[1], dest[2], dest[3], dest[4], dest[5]); config_method = WPS_PBC; if(argc == 3) { if(os_strncmp(argv[2], "pbc", 3) == 0) config_method = WPS_PBC; else if(os_strncmp(argv[2], "pin", 3) == 0){ config_method = WPS_PIN_DISPLAY; }else{ printf("\n\rUnknown config method!\n"); printf("\n\rUsage: p2p_connect DEST_ADDR [pbc|pin] \n"); printf("\n\rExample: p2p_connect 00:e0:4c:87:00:15 pin\n"); return; } } else if(argc == 4) { if(os_strncmp(argv[2], "pin", 3) == 0){ config_method = WPS_PIN_KEYPAD; pin = argv[3]; }else{ printf("\n\rUnknown config method!\n"); printf("\n\rUsage: p2p_connect DEST_ADDR [pbc|pin] [pin code]\n"); printf("\n\rExample: p2p_connect 00:e0:4c:87:00:15 pin 12345678\n"); return; } } #else //For test u8 dest1[ETH_ALEN] = {0xea, 0x92, 0xa4, 0x9b, 0x61, 0xd6}; //NEXUS 4 //u8 dest1[ETH_ALEN] = {0x0e, 0x37, 0xdc, 0xfc, 0xc4, 0x12}; //HUAWEI U9508_c001 //u8 dest1[ETH_ALEN] = {0x42, 0xcb, 0xa8, 0xd3, 0x2c, 0x50}; //HUAWEI G610-T00 os_memcpy(dest, dest1, ETH_ALEN); config_method = WPS_PBC; #endif if (queue_for_p2p_nego!= NULL) { os_xqueue_delete(queue_for_p2p_nego); queue_for_p2p_nego = NULL; } queue_for_p2p_nego = os_xqueue_create(1, P2P_GO_NEGO_RESULT_SIZE); if(queue_for_p2p_nego != NULL) { ret = wifi_cmd_p2p_connect(dest, config_method, pin); if(ret == 0) result = os_xqueue_receive(queue_for_p2p_nego, res, 15); os_xqueue_delete(queue_for_p2p_nego); queue_for_p2p_nego = NULL; if((ret == 0) && (result == 0)) wifi_p2p_start_wps(res); } } #endif //CONFIG_ENABLE_P2P
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/rtw_wpa_supplicant/wpa_supplicant/wifi_p2p_config.c
C
apache-2.0
7,146
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "FreeRTOS.h" #include "task.h" #include "main.h" #include "queue.h" #include "utils/os.h" #include <lwip_netconf.h> #include <lwip/netif.h> #include "wifi/wifi_conf.h" #include "wps/wps_defs.h" #include <platform/platform_stdlib.h> #include "wifi_wps_config.h" // The maximum number of WPS credentials. The value should be in range of 1~10. int wps_max_cred_count = 10; /* * @brief struct wps_credential - WPS Credential */ struct dev_credential { u8 ssid[32]; /**< SSID */ size_t ssid_len; /**< Length of SSID */ u16 auth_type; /**< Authentication Type (WPS_AUTH_OPEN, .. flags) */ u16 encr_type; /**< Encryption Type (WPS_ENCR_NONE, .. flags) */ u8 key_idx; /**< Key index */ u8 key[65]; /**< Key */ size_t key_len; /**< Key length in octets */ u8 mac_addr[6]; /**< MAC address of the Credential receiver */ const u8 *cred_attr; /**< Unparsed Credential attribute data (used only in cred_cb()). This may be NULL, if not used. */ size_t cred_attr_len; /**< Length of cred_attr in octets */ u16 ap_channel; /**< AP channel */ }; typedef struct { char *target_ssid; unsigned char *target_bssid; u16 config_method; _sema scan_sema; int isoverlap; int isoverlap_5G; } internal_wps_scan_handler_arg_t; #define WLAN0_NAME "wlan0" #ifndef ENABLE #define ENABLE (1) #endif #ifndef DISABLE #define DISABLE (0) #endif #define STACKSIZE 512 //static xSemaphoreHandle wps_reconnect_semaphore; //static struct _WIFI_NETWORK wifi_get_from_certificate = {0}; #define WPS_AUTH_TYPE_OPEN (0x0001) #define WPS_AUTH_TYPE_WPA_PERSONAL (0x0002) #define WPS_AUTH_TYPE_SHARED (0x0004) #define WPS_AUTH_TYPE_WPA_ENTERPRISE (0x0008) #define WPS_AUTH_TYPE_WPA2_PERSONAL (0x0010) #define WPS_AUTH_TYPE_WPA2_ENTERPRISE (0x0020) #define WPS_ENCR_TYPE_NONE (0x0001) #define WPS_ENCR_TYPE_WEP (0x0002) #define WPS_ENCR_TYPE_TKIP (0x0004) #define WPS_ENCR_TYPE_AES (0x0008) #define SCAN_BUFFER_LENGTH (4096) #if defined(CONFIG_ENABLE_P2P) && CONFIG_ENABLE_P2P extern void _wifi_p2p_wps_success(const u8 *peer_addr, int registrar); extern void _wifi_p2p_wps_failed(); #endif #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP extern u32 _wps_registrar_process_msg(void *priv, u32 op_code, const void *pmsg); extern void * _wps_registrar_get_msg(void *priv, u32 *op_code); extern void * _wps_registrar_init(void *priv, const void* pcfg); extern void _wps_registrar_deinit(void *priv); extern void *_wps_registrar_alloc(); extern int _wps_registrar_add_pin(void *priv, const u8 *addr, const u8 *uuid, const u8 *pin, size_t pin_len, int timeout); extern int _wps_registrar_button_pushed(void *priv, const u8 *p2p_dev_addr); extern int _wps_registrar_wps_cancel(void *priv); extern void _wpas_wsc_ap_send_eap_reqidentity(void *priv, u8 *rx_buf); extern void _wpas_wsc_ap_check_eap_rspidentity(void *priv, u8 *rx_buf); extern void _wpas_wsc_registrar_send_eap_fail(void *priv); extern void _wpas_wsc_registrar_handle_recvd(void *priv, u8 *rx_buf); extern void * _eap_wsc_server_process_hdl(void *priv, void* req, u8 id); extern void _eap_wsc_server_reset(void *priv); #endif extern void wpas_wsc_sta_wps_start_hdl(char *buf, int buf_len, int flags, void *userdata); extern void wpas_wsc_wps_finish_hdl(char *buf, int buf_len, int flags, void *userdata); extern void wpas_wsc_server_wps_finish_hdl(char *buf, int buf_len, int flags, void *userdata); extern void wpas_wsc_eapol_recvd_hdl(char *buf, int buf_len, int flags, void *userdata); void wifi_p2p_wps_success(const u8 *peer_addr, int registrar) { /* To avoid gcc warnnings */ ( void ) peer_addr; ( void ) registrar; #if CONFIG_ENABLE_P2P _wifi_p2p_wps_success(peer_addr, registrar); #endif } void wifi_p2p_wps_failed(void) { #if CONFIG_ENABLE_P2P _wifi_p2p_wps_failed(); #endif } void * wps_registrar_init(void *priv, void *pcfg) { /* To avoid gcc warnnings */ ( void ) priv; ( void ) pcfg; #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP return _wps_registrar_init(priv, pcfg); #else return NULL; #endif } void wps_registrar_deinit(void *priv) { /* To avoid gcc warnnings */ ( void ) priv; #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP _wps_registrar_deinit(priv); #endif } void *wps_registrar_alloc(void) { #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP return _wps_registrar_alloc(); #else return NULL; #endif } u32 wps_registrar_process_msg(void *priv, u32 op_code, const void *pmsg) { /* To avoid gcc warnnings */ ( void ) priv; ( void ) op_code; ( void ) pmsg; #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP return _wps_registrar_process_msg(priv, op_code, pmsg); #else return 0; #endif } void * wps_registrar_get_msg(void *priv, u32 *op_code) { /* To avoid gcc warnnings */ ( void ) priv; ( void ) op_code; #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP return _wps_registrar_get_msg(priv, op_code); #else return NULL; #endif } int wps_registrar_add_pin(void *priv, const u8 *addr, const u8 *uuid, const u8 *pin, size_t pin_len, int timeout) { /* To avoid gcc warnnings */ ( void ) priv; ( void ) addr; ( void ) uuid; ( void ) pin; ( void ) pin_len; ( void ) timeout; #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP return _wps_registrar_add_pin(priv, NULL,NULL,pin,pin_len,0); #else return 0; #endif } int wps_registrar_button_pushed(void *priv, const u8 *p2p_dev_addr) { /* To avoid gcc warnnings */ ( void ) priv; ( void ) p2p_dev_addr; #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP return _wps_registrar_button_pushed(priv, p2p_dev_addr); #else return 0; #endif } int wps_registrar_wps_cancel(void *priv) { /* To avoid gcc warnnings */ ( void ) priv; #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP return _wps_registrar_wps_cancel(priv); #else return 0; #endif } void wpas_wsc_ap_send_eap_reqidentity(void *priv, u8 *rx_buf) { /* To avoid gcc warnnings */ ( void ) priv; ( void ) rx_buf; #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP _wpas_wsc_ap_send_eap_reqidentity(priv, rx_buf); #endif } void wpas_wsc_ap_check_eap_rspidentity(void *priv, u8 *rx_buf) { /* To avoid gcc warnnings */ ( void ) priv; ( void ) rx_buf; #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP _wpas_wsc_ap_check_eap_rspidentity(priv, rx_buf); #endif } void wpas_wsc_registrar_send_eap_fail(void *priv) { /* To avoid gcc warnnings */ ( void ) priv; #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP _wpas_wsc_registrar_send_eap_fail(priv); #endif } void wpas_wsc_registrar_handle_recvd(void *priv, u8 *rx_buf) { /* To avoid gcc warnnings */ ( void ) priv; ( void ) rx_buf; #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP _wpas_wsc_registrar_handle_recvd(priv, rx_buf); #endif } void * eap_wsc_server_process_hdl(void *priv, void* req, u8 id) { /* To avoid gcc warnnings */ ( void ) priv; ( void ) req; ( void ) id; #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP return _eap_wsc_server_process_hdl(priv, req, id); #else return NULL; #endif } void eap_wsc_server_reset(void *priv) { /* To avoid gcc warnnings */ ( void ) priv; #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP _eap_wsc_server_reset(priv); #endif } #if CONFIG_ENABLE_WPS xqueue_handle_t queue_for_credential; char wps_pin_code[32]; u16 config_method; u8 wps_password_id; #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP static TaskHandle_t ap_wps_task = NULL; #endif static unsigned char wps_stop_notified = 0; void wps_check_and_show_connection_info(void) { rtw_wifi_setting_t setting; #if CONFIG_LWIP_LAYER /* Start DHCP Client */ LwIP_DHCP(0, DHCP_START); #endif wifi_get_setting(WLAN0_NAME, &setting); wifi_show_setting(WLAN0_NAME, &setting); #if defined(CONFIG_INIC_CMD_RSP) && CONFIG_INIC_CMD_RSP inic_c2h_wifi_info("ATWW", RTW_SUCCESS); #endif } static void wps_config_wifi_setting(rtw_network_info_t *wifi, struct dev_credential *dev_cred) { printf("\r\nwps_config_wifi_setting\n"); //memcpy((void *)wifi->ssid, (void *)dev_cred->ssid, dev_cred->ssid_len); strcpy((char*)wifi->ssid.val, (char*)&dev_cred->ssid[0]); printf("\r\nwps_wifi.ssid = %s\n", wifi->ssid.val); wifi->ssid.len = dev_cred->ssid_len; printf("\r\nwps_wifi.ssid_len = %d\n", wifi->ssid.len); if(dev_cred->auth_type & (WPS_AUTH_TYPE_WPA2_PERSONAL | WPS_AUTH_TYPE_WPA2_ENTERPRISE)) { if((dev_cred->encr_type & WPS_ENCR_TYPE_AES) && (dev_cred->encr_type & WPS_ENCR_TYPE_TKIP)) { printf("\r\nsecurity_type = RTW_SECURITY_WPA2_MIXED_PSK\n"); wifi->security_type = RTW_SECURITY_WPA2_MIXED_PSK; } else if(dev_cred->encr_type & WPS_ENCR_TYPE_AES) { printf("\r\nsecurity_type = RTW_SECURITY_WPA2_AES_PSK\n"); wifi->security_type = RTW_SECURITY_WPA2_AES_PSK; } else if(dev_cred->encr_type & WPS_ENCR_TYPE_TKIP) { printf("\r\nsecurity_type = RTW_SECURITY_WPA2_TKIP_PSK\n"); wifi->security_type = RTW_SECURITY_WPA2_TKIP_PSK; } } else if(dev_cred->auth_type & (WPS_AUTH_TYPE_WPA_PERSONAL | WPS_AUTH_TYPE_WPA_ENTERPRISE)) { if((dev_cred->encr_type & WPS_ENCR_TYPE_AES) && (dev_cred->encr_type & WPS_ENCR_TYPE_TKIP)) { printf("\r\nsecurity_type = RTW_SECURITY_WPA_MIXED_PSK\n"); wifi->security_type = RTW_SECURITY_WPA_MIXED_PSK; } else if(dev_cred->encr_type & WPS_ENCR_TYPE_AES) { printf("\r\nsecurity_type = RTW_SECURITY_WPA_AES_PSK\n"); wifi->security_type = RTW_SECURITY_WPA_AES_PSK; } else if(dev_cred->encr_type & WPS_ENCR_TYPE_TKIP) { printf("\r\nsecurity_type = RTW_SECURITY_WPA_TKIP_PSK\n"); wifi->security_type = RTW_SECURITY_WPA_TKIP_PSK; } } else if(dev_cred->auth_type & (WPS_AUTH_TYPE_OPEN | WPS_AUTH_TYPE_SHARED)) { if(dev_cred->encr_type & WPS_ENCR_TYPE_WEP) { printf("\r\nsecurity_type = RTW_SECURITY_WEP_PSK\n"); wifi->security_type = RTW_SECURITY_WEP_PSK; wifi->key_id = dev_cred->key_idx - 1; } else { printf("\r\nsecurity_type = RTW_SECURITY_OPEN\n"); wifi->security_type = RTW_SECURITY_OPEN; } } printf("\r\nwps_wifi.security_type = %d\n", wifi->security_type); //memcpy(wifi->password, dev_cred->key, dev_cred->key_len); wifi->password = dev_cred->key; printf("\r\nwps_wifi.password = %s\n", wifi->password); wifi->password_len = dev_cred->key_len; printf("\r\nwps_wifi.password_len = %d", wifi->password_len); //xSemaphoreGive(wps_reconnect_semaphore); //printf("\r\nrelease wps_reconnect_semaphore"); } static int wps_connect_to_AP_by_certificate(rtw_network_info_t *wifi) { int retry_count = WPS_CONNECT_RETRY_COUNT, ret; printf("\r\n=============== wifi_certificate_info ===============\n"); printf("\r\nwps_wifi.ssid = %s\n", wifi->ssid.val); printf("\r\nsecurity_type = %d\n", wifi->security_type); printf("\r\nwps_wifi.password = %s\n", wifi->password); printf("\r\nssid_len = %d\n", wifi->ssid.len); printf("\r\npassword_len = %d\n", wifi->password_len); while (1) { ret = wifi_connect((char*)wifi->ssid.val, wifi->security_type, (char*)wifi->password, wifi->ssid.len, wifi->password_len, wifi->key_id, NULL); if (ret == RTW_SUCCESS) { if(retry_count == WPS_CONNECT_RETRY_COUNT) rtw_msleep_os(1000); //When start wps with OPEN AP, AP will send a disassociate frame after STA connected, need reconnect here. if(RTW_SUCCESS == wifi_is_connected_to_ap( )){ //printf("\r\n[WPS]Ready to tranceive!!\n"); wps_check_and_show_connection_info(); break; } } if (retry_count == 0) { printf("\r\n[WPS]Join bss failed\n"); ret = -1; break; } retry_count --; rtw_msleep_os(WPS_CONNECT_RETRY_INTERVAL); } return ret; } static int wps_connect_to_AP_by_open_system(char *target_ssid) { int retry_count = 3, ret; if (target_ssid != NULL) { rtw_msleep_os(500); //wait scan complete. while (1) { ret = wifi_connect(target_ssid, RTW_SECURITY_OPEN, NULL, strlen(target_ssid), 0, 0, NULL); if (ret == RTW_SUCCESS) { //wps_check_and_show_connection_info(); break; } if (retry_count == 0) { printf("\r\n[WPS]Join bss failed\n"); return -1; } retry_count --; } // } else { printf("\r\n[WPS]Target SSID is NULL\n"); } return 0; } static int wps_connect_to_AP_by_open_system_with_bssid(char *target_ssid, unsigned char *target_bssid) { int retry_count = 3, ret; if ((target_ssid != NULL)&&(target_bssid != NULL)) { rtw_msleep_os(500); //wait scan complete. while (1) { ret = wifi_connect_bssid(target_bssid, target_ssid, RTW_SECURITY_OPEN, NULL, ETH_ALEN, strlen(target_ssid), 0, 0, NULL); if (ret == RTW_SUCCESS) { //wps_check_and_show_connection_info(); break; } if (retry_count == 0) { printf("\r\n[WPS]Join bss failed\n"); return -1; } retry_count --; } } else { printf("\r\n[WPS]Target SSID or BSSID is NULL\n"); } return 0; } static void process_wps_scan_result( rtw_scan_result_t* record, void * user_data ) { u8 zero_mac[ETH_ALEN] = {0}; internal_wps_scan_handler_arg_t *wps_arg = (internal_wps_scan_handler_arg_t *)user_data; if ((record->wps_type != 0xff) && (record->channel != 0) && (memcmp(&record->BSSID, zero_mac, 6) != 0) && (!(record->security & WEP_ENABLED))) { // ignore hidden ssid if(record->SSID.len == 0) { return; } else { int i; u8 is_hidden_ssid = 1; for(i = 0; i < record->SSID.len; i ++) { if(record->SSID.val[i] != 0) { is_hidden_ssid = 0; break; } } if(is_hidden_ssid) return; } if (wps_arg->config_method == WPS_CONFIG_PUSHBUTTON) { if (record->wps_type == 0x04) { wps_password_id = record->wps_type; if (record->channel > 14) { if (++wps_arg->isoverlap_5G == 0) { memcpy(&wps_arg->target_ssid[0], record->SSID.val, record->SSID.len); memcpy(wps_arg->target_bssid, record->BSSID.octet, ETH_ALEN); wps_arg->target_ssid[record->SSID.len] = '\0'; printf("\r\n[pbc]Record first triger wps 5G AP = %s, %02x:%02x:%02x:%02x:%02x:%02x\n",\ wps_arg->target_ssid,wps_arg->target_bssid[0],wps_arg->target_bssid[1],wps_arg->target_bssid[2],\ wps_arg->target_bssid[3],wps_arg->target_bssid[4],wps_arg->target_bssid[5]); } } else { if ((++wps_arg->isoverlap == 0) && (wps_arg->isoverlap_5G == -1)) { memcpy(&wps_arg->target_ssid[0], record->SSID.val, record->SSID.len); memcpy(wps_arg->target_bssid, record->BSSID.octet, ETH_ALEN); wps_arg->target_ssid[record->SSID.len] = '\0'; printf("\r\n[pbc]Record first triger wps AP = %s, %02x:%02x:%02x:%02x:%02x:%02x\n",\ wps_arg->target_ssid,wps_arg->target_bssid[0],wps_arg->target_bssid[1],wps_arg->target_bssid[2],\ wps_arg->target_bssid[3],wps_arg->target_bssid[4],wps_arg->target_bssid[5]); } } } } else if (wps_arg->config_method == WPS_CONFIG_DISPLAY || wps_arg->config_method == WPS_CONFIG_KEYPAD) { if (record->wps_type == 0x00) { wps_arg->isoverlap = 0; wps_password_id = record->wps_type; memcpy(&wps_arg->target_ssid[0], record->SSID.val, record->SSID.len); memcpy(wps_arg->target_bssid, record->BSSID.octet, ETH_ALEN); wps_arg->target_ssid[record->SSID.len] = '\0'; printf("\r\n[pin]find out first triger wps AP = %s, %02x:%02x:%02x:%02x:%02x:%02x\n",\ wps_arg->target_ssid,wps_arg->target_bssid[0],wps_arg->target_bssid[1],wps_arg->target_bssid[2],\ wps_arg->target_bssid[3],wps_arg->target_bssid[4],wps_arg->target_bssid[5]); } } } } #ifndef CONFIG_ENABLE_WPS_DISCOVERY #define CONFIG_ENABLE_WPS_DISCOVERY 0 #endif #if CONFIG_ENABLE_WPS_DISCOVERY #define DISCOVERED_SSIDS_NUM 10 static char *discovered_ssids[DISCOVERED_SSIDS_NUM]; static char discovery_ssid[64]; static void reset_discovery_phase(void) { memset(discovered_ssids, 0, sizeof(discovered_ssids)); memset(discovery_ssid, 0, sizeof(discovery_ssid)); } static void reset_discovery_ssid(void) { memset(discovery_ssid, 0, sizeof(discovery_ssid)); } static void clean_discovered_ssids(void) { int i; for(i = 0; i < DISCOVERED_SSIDS_NUM; i ++) { if(discovered_ssids[i]) { free(discovered_ssids[i]); discovered_ssids[i] = NULL; } } } static void update_discovered_ssids(char *ssid) { int i; for(i = 0; i < DISCOVERED_SSIDS_NUM; i ++) { if(discovered_ssids[i] != NULL) { if(strcmp(discovered_ssids[i], ssid) == 0) break; } else { if(strlen(discovery_ssid) == 0) { discovered_ssids[i] = malloc(strlen(ssid) + 1); strcpy(discovered_ssids[i], ssid); strcpy(discovery_ssid, ssid); break; } } } } static int start_discovery_phase(u16 wps_config) { struct dev_credential *dev_cred; rtw_network_info_t wifi = {0}; int ret = 0; if(strlen(discovery_ssid) == 0) { //clean_discovered_ssids(); return -1; } printf("\ndiscovery_ssid=%s\n", discovery_ssid); if (queue_for_credential != NULL) { os_xqueue_delete(queue_for_credential); queue_for_credential = NULL; } queue_for_credential = os_xqueue_create(wps_max_cred_count, sizeof(struct dev_credential)); if(!queue_for_credential) return -1; wifi_reg_event_handler(WIFI_EVENT_STA_WPS_START, wpas_wsc_sta_wps_start_hdl, NULL); wifi_reg_event_handler(WIFI_EVENT_WPS_FINISH, wpas_wsc_wps_finish_hdl, NULL); wifi_reg_event_handler(WIFI_EVENT_EAPOL_RECVD, wpas_wsc_eapol_recvd_hdl, NULL); wpas_wps_enrollee_init_probe_ie(wps_config); wpas_wps_enrollee_init_assoc_ie(); wifi_set_wps_phase(ENABLE); if(wps_stop_notified) { ret = -1; goto exit; } ret = wps_connect_to_AP_by_open_system(discovery_ssid); if(ret < 0){ goto exit; } dev_cred = (struct dev_credential *)os_zalloc(sizeof(struct dev_credential) * wps_max_cred_count); if(!dev_cred){ printf("\n\rWPS: dev_credential allocate fail\n"); goto exit; } for(int i=0; i< wps_max_cred_count; i++){ os_xqueue_receive(queue_for_credential, &dev_cred[i], 20); // ssid == 0: no more credential if(dev_cred[i].ssid[0] == 0) break; } // choose first credential as default if (dev_cred[0].ssid[0] != 0 && dev_cred[0].ssid_len <= 32) { wps_config_wifi_setting(&wifi, &dev_cred[0]); wifi_set_wps_phase(DISABLE); #if defined(CONFIG_WIFI_IND_USE_THREAD) && CONFIG_WIFI_IND_USE_THREAD vTaskDelay(10); //Wait WIFI_DISCONNECT_EVENT and WIFI_EVENT_WPS_FINISH to be processed which sent by OnDeauth #endif ret = wps_connect_to_AP_by_certificate(&wifi); os_free(dev_cred,0); goto exit1; } else { ret = -1; } os_free(dev_cred,0); exit: wifi_set_wps_phase(DISABLE); exit1: if (queue_for_credential != NULL) { os_xqueue_delete(queue_for_credential); queue_for_credential = NULL; } wifi_unreg_event_handler(WIFI_EVENT_STA_WPS_START, wpas_wsc_sta_wps_start_hdl); wifi_unreg_event_handler(WIFI_EVENT_WPS_FINISH, wpas_wsc_wps_finish_hdl); wifi_unreg_event_handler(WIFI_EVENT_EAPOL_RECVD, wpas_wsc_eapol_recvd_hdl); wpas_wps_deinit(); vTaskDelay(10); return ret; } #endif /* CONFIG_ENABLE_WPS_DISCOVERY */ static rtw_result_t wps_scan_result_handler( rtw_scan_handler_result_t* malloced_scan_result ) { internal_wps_scan_handler_arg_t *wps_arg = (internal_wps_scan_handler_arg_t *)malloced_scan_result->user_data; if (malloced_scan_result->scan_complete != RTW_TRUE) { rtw_scan_result_t* record = &malloced_scan_result->ap_details; record->SSID.val[record->SSID.len] = 0; /* Ensure the SSID is null terminated */ process_wps_scan_result(record, malloced_scan_result->user_data); #if CONFIG_ENABLE_WPS_DISCOVERY if(((wps_arg->config_method == WPS_CONFIG_DISPLAY) || (wps_arg->config_method == WPS_CONFIG_KEYPAD)) && (record->wps_type == 0x07)) { update_discovered_ssids(record->SSID.val); } #endif } else { printf("\r\nWPS scan done!\r\n"); rtw_up_sema(&wps_arg->scan_sema); } return RTW_SUCCESS; } extern void wifi_scan_each_report_hdl( char* buf, int buf_len, int flags, void* userdata); extern void wifi_scan_done_hdl( char* buf, int buf_len, int flags, void* userdata); static int wps_find_out_triger_wps_AP(char *target_ssid, unsigned char *target_bssid, u16 config_method) { int isoverlap = -1; internal_wps_scan_handler_arg_t wps_arg = {0}; wps_password_id = 0xFF; wps_arg.isoverlap = -1; wps_arg.isoverlap_5G = -1; wps_arg.config_method = config_method; wps_arg.target_ssid = target_ssid; wps_arg.target_bssid = target_bssid; rtw_init_sema(&wps_arg.scan_sema, 0); if(wps_arg.scan_sema == NULL) return RTW_ERROR; if(wifi_scan_networks(wps_scan_result_handler, &wps_arg ) != RTW_SUCCESS){ printf("\n\rERROR: wifi scan failed"); goto exit; } if(rtw_down_timeout_sema(&wps_arg.scan_sema, SCAN_LONGEST_WAIT_TIME) == RTW_FALSE){ printf("\r\nWPS scan done early!\r\n"); } wifi_unreg_event_handler(WIFI_EVENT_SCAN_RESULT_REPORT, wifi_scan_each_report_hdl); wifi_unreg_event_handler(WIFI_EVENT_SCAN_DONE, wifi_scan_done_hdl); exit: rtw_free_sema(&wps_arg.scan_sema); if((wps_arg.isoverlap >= 0) && (wps_arg.isoverlap_5G >= 0)) isoverlap = wps_arg.isoverlap + wps_arg.isoverlap_5G; else if(wps_arg.isoverlap_5G >= 0) isoverlap = wps_arg.isoverlap_5G; else if(wps_arg.isoverlap >= 0) isoverlap = wps_arg.isoverlap; return isoverlap; } static u8 wps_scan_cred_ssid(struct dev_credential *dev_cred) { u8 ssid_found = 0; scan_buf_arg scan_buf; scan_buf.buf_len = 1000; scan_buf.buf = malloc(scan_buf.buf_len); if(scan_buf.buf) { memset(scan_buf.buf, 0, scan_buf.buf_len); *((int *) scan_buf.buf) = dev_cred->ssid_len; memcpy(scan_buf.buf + sizeof(int), dev_cred->ssid, dev_cred->ssid_len); if(wifi_scan(RTW_SCAN_TYPE_ACTIVE, RTW_BSS_TYPE_ANY, &scan_buf) > 0) { uint8_t *pos = (uint8_t *) scan_buf.buf; while(pos <= ((uint8_t *) scan_buf.buf + scan_buf.buf_len)) { uint8_t len = *pos; uint8_t ssid_len = len - 14; uint8_t *ssid = pos + 14; uint8_t ssid_len_p2p = len - 15; uint8_t *ssid_p2p = pos + 15; if((len <= 0) || ((pos + len) > ((uint8_t *) scan_buf.buf + scan_buf.buf_len))) break; if(((ssid_len == dev_cred->ssid_len) && (memcmp(ssid, dev_cred->ssid, dev_cred->ssid_len) == 0)) || ((ssid_len_p2p == dev_cred->ssid_len) && (memcmp(ssid_p2p, dev_cred->ssid, dev_cred->ssid_len) == 0))) { ssid_found = 1; break; } pos += len; } } free(scan_buf.buf); } else { // if cannot scan, suppose it can be found ssid_found = 1; } return ssid_found; } static void wps_filter_cred_by_scan(struct dev_credential *dev_cred, int cred_cnt) { u8 ssid_found_count = 0; u8 *ssid_found_flags = (u8 *) malloc(cred_cnt); if(ssid_found_flags) { int i, times; for(times = 0; times < (WPS_CONNECT_RETRY_COUNT + 1); times ++) { memset(ssid_found_flags, 0, cred_cnt); ssid_found_count = 0; for(i = 0; i < cred_cnt; i ++) { ssid_found_flags[i] = wps_scan_cred_ssid(&dev_cred[i]); ssid_found_count += ssid_found_flags[i]; } if(ssid_found_count) break; else rtw_msleep_os(WPS_CONNECT_RETRY_INTERVAL); } for(i = 0; i < cred_cnt; i ++) { if(ssid_found_flags[i] == 0) memset(&dev_cred[i], 0, sizeof(struct dev_credential)); } free(ssid_found_flags); } } int wps_start(u16 wps_config, char *pin, u8 channel, char *ssid) { struct dev_credential *dev_cred; rtw_network_info_t wifi = {0}; char target_ssid[64]; unsigned char target_bssid[ETH_ALEN]; int is_overlap = -1; u32 start_time = rtw_get_current_time(); int ret = 0; // for multiple credentials int cred_cnt = 0; int select_index = 0; u32 select_security = 0; uint8_t pscan_config = PSCAN_ENABLE | PSCAN_FAST_SURVEY; if(wps_max_cred_count < 1 || wps_max_cred_count > 10){ printf("\n\rWPS: wps_max_cred_count should be in range 1~10\n"); return -1; } memset(target_ssid, 0, 64); memset(target_bssid, 0, ETH_ALEN); wps_stop_notified = 0; if((wps_config != WPS_CONFIG_PUSHBUTTON) && (wps_config != WPS_CONFIG_DISPLAY) && (wps_config != WPS_CONFIG_KEYPAD)){ printf("\n\rWPS: Wps method(%d) is wrong. Not triger WPS.\n", wps_config); return -1; } config_method = wps_config; if(wps_config == WPS_CONFIG_DISPLAY || wps_config == WPS_CONFIG_KEYPAD) { if(pin) strcpy(wps_pin_code, pin); else{ printf("\n\rWPS: PIN is NULL. Not triger WPS.\n"); return -1; } } if(!ssid) { #if CONFIG_ENABLE_WPS_DISCOVERY reset_discovery_phase(); #endif while (1) { unsigned int current_time = rtw_get_current_time(); if ((rtw_systime_to_sec(current_time - start_time) < 120) && !wps_stop_notified) { #if CONFIG_ENABLE_WPS_DISCOVERY reset_discovery_ssid(); #endif wpas_wps_enrollee_init_probe_ie(wps_config); is_overlap = wps_find_out_triger_wps_AP(&target_ssid[0], &target_bssid[0], wps_config); if ((is_overlap == 0) || (is_overlap > 0)) break; #if CONFIG_ENABLE_WPS_DISCOVERY if((wps_config == WPS_CONFIG_DISPLAY) || (wps_config == WPS_CONFIG_KEYPAD)) { if(start_discovery_phase(wps_config) == 0) { clean_discovered_ssids(); return 0; } } #endif } else { printf("\r\nWPS: WPS Walking Time Out\n"); return -2; } } #if CONFIG_ENABLE_WPS_DISCOVERY clean_discovered_ssids(); #endif if (is_overlap > 0) { printf("\r\nWPS: WPS session overlap. Not triger WPS.\n"); return -2; } }else{ rtw_memcpy(target_ssid, ssid, strlen(ssid)); if(channel !=0) { channel &= 0xff; ret = wifi_set_pscan_chan((uint8_t *)&channel, &pscan_config, 1); if(ret < 0) return -1; } } if (queue_for_credential != NULL) { os_xqueue_delete(queue_for_credential); queue_for_credential = NULL; } queue_for_credential = os_xqueue_create(wps_max_cred_count, sizeof(struct dev_credential)); if(!queue_for_credential) return -1; wifi_reg_event_handler(WIFI_EVENT_STA_WPS_START, wpas_wsc_sta_wps_start_hdl, NULL); wifi_reg_event_handler(WIFI_EVENT_WPS_FINISH, wpas_wsc_wps_finish_hdl, NULL); wifi_reg_event_handler(WIFI_EVENT_EAPOL_RECVD, wpas_wsc_eapol_recvd_hdl, NULL); wpas_wps_enrollee_init_probe_ie(wps_config); wpas_wps_enrollee_init_assoc_ie(); wifi_set_wps_phase(ENABLE); if(ssid) /*for the customers who scan themself use wps_start to connect directly*/ ret = wps_connect_to_AP_by_open_system(target_ssid); else /*for wifi mesh AP, should use bssid to choose the right AP*/ ret = wps_connect_to_AP_by_open_system_with_bssid(target_ssid,target_bssid); if(ret < 0){ printf("\n\rWPS: WPS Fail!!\n"); goto exit; } dev_cred = (struct dev_credential *)os_zalloc(sizeof(struct dev_credential) * wps_max_cred_count); if(!dev_cred){ printf("\n\rWPS: dev_credential allocate fail\n"); goto exit; } for(int i=0; i< wps_max_cred_count; i++){ os_xqueue_receive(queue_for_credential, &dev_cred[i], 120); // ssid == 0: no more credential if(dev_cred[i].ssid[0] == 0) break; else cred_cnt++; } // filter 5G rf_band cred if(cred_cnt > 1) wps_filter_cred_by_scan(dev_cred, cred_cnt); // check got credentials and select the most secure one to connect for(int cur_index = 0; cur_index < cred_cnt; cur_index++){ u32 cur_security = 0; //printf("\r\nWPS: check %d th cred\n", cur_index+1); if(dev_cred[cur_index].ssid_len == 0) continue; if(dev_cred[cur_index].auth_type & (WPS_AUTH_TYPE_WPA2_PERSONAL | WPS_AUTH_TYPE_WPA2_ENTERPRISE)) { if((dev_cred[cur_index].encr_type & WPS_ENCR_TYPE_AES) && (dev_cred[cur_index].encr_type & WPS_ENCR_TYPE_TKIP)) cur_security = RTW_SECURITY_WPA2_MIXED_PSK; else if(dev_cred[cur_index].encr_type & WPS_ENCR_TYPE_AES) cur_security = RTW_SECURITY_WPA2_AES_PSK; else if(dev_cred[cur_index].encr_type & WPS_ENCR_TYPE_TKIP) cur_security = RTW_SECURITY_WPA2_TKIP_PSK; } else if(dev_cred[cur_index].auth_type & (WPS_AUTH_TYPE_WPA_PERSONAL | WPS_AUTH_TYPE_WPA_ENTERPRISE)) { if((dev_cred[cur_index].encr_type & WPS_ENCR_TYPE_AES) && (dev_cred[cur_index].encr_type & WPS_ENCR_TYPE_TKIP)) cur_security = RTW_SECURITY_WPA_MIXED_PSK; else if(dev_cred[cur_index].encr_type & WPS_ENCR_TYPE_AES) cur_security = RTW_SECURITY_WPA_AES_PSK; else if(dev_cred[cur_index].encr_type & WPS_ENCR_TYPE_TKIP) cur_security = RTW_SECURITY_WPA_TKIP_PSK; } else if(dev_cred[cur_index].auth_type & (WPS_AUTH_TYPE_OPEN | WPS_AUTH_TYPE_SHARED)) { if(dev_cred[cur_index].encr_type & WPS_ENCR_TYPE_WEP) cur_security = RTW_SECURITY_WEP_PSK; else cur_security = RTW_SECURITY_OPEN; } //printf("\r\nWPS: cur_security: %d\n", cur_security); if(cur_security >= select_security){ //printf("\r\nWPS: update index to %d of security type %d\n", cur_index, cur_security); select_security = cur_security; select_index = cur_index; } } // choose first credential as default if (dev_cred[select_index].ssid[0] != 0 && dev_cred[select_index].ssid_len <= 32) { wps_config_wifi_setting(&wifi, &dev_cred[select_index]); wifi_set_wps_phase(DISABLE); #if defined(CONFIG_WIFI_IND_USE_THREAD) && CONFIG_WIFI_IND_USE_THREAD vTaskDelay(10); //Wait WIFI_DISCONNECT_EVENT and WIFI_EVENT_WPS_FINISH to be processed which sent by OnDeauth #endif #ifdef CONFIG_SAE_SUPPORT if(wext_get_support_wpa3()==1) { wext_set_support_wpa3(DISABLE); ret = wps_connect_to_AP_by_certificate(&wifi); wext_set_support_wpa3(ENABLE); } else #endif { ret = wps_connect_to_AP_by_certificate(&wifi); } os_free(dev_cred,0); goto exit1; } else { printf("\n\rWPS: WPS FAIL!!!\n"); printf("\n\rWPS: WPS FAIL!!!\n"); printf("\n\rWPS: WPS FAIL!!!\n"); ret = -1; } os_free(dev_cred,0); exit: wifi_set_wps_phase(DISABLE); exit1: if (queue_for_credential != NULL) { os_xqueue_delete(queue_for_credential); queue_for_credential = NULL; } wifi_unreg_event_handler(WIFI_EVENT_STA_WPS_START, wpas_wsc_sta_wps_start_hdl); wifi_unreg_event_handler(WIFI_EVENT_WPS_FINISH, wpas_wsc_wps_finish_hdl); wifi_unreg_event_handler(WIFI_EVENT_EAPOL_RECVD, wpas_wsc_eapol_recvd_hdl); wpas_wps_deinit(); return ret; } void wps_stop(void) { wps_stop_notified = 1; wpas_wsc_wps_finish_hdl(NULL, 0, 0, NULL); } #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP static int ap_wps_start(u16 wps_config, char *pin) { u8 authorized_mac[ETH_ALEN]; int ret = 0; u32 pin_val = 0; if (queue_for_credential != NULL) { os_xqueue_delete(queue_for_credential); queue_for_credential = NULL; } queue_for_credential = os_xqueue_create(1, sizeof(authorized_mac)); if(!queue_for_credential) return -1; wifi_reg_event_handler(WIFI_EVENT_STA_WPS_START, wpas_wsc_sta_wps_start_hdl, NULL); wifi_reg_event_handler(WIFI_EVENT_WPS_FINISH, wpas_wsc_server_wps_finish_hdl, NULL); wifi_reg_event_handler(WIFI_EVENT_EAPOL_RECVD, wpas_wsc_eapol_recvd_hdl, NULL); wifi_set_wps_phase(ENABLE); if(wps_config == WPS_CONFIG_KEYPAD) { pin_val = atoi(pin); if (!wps_pin_valid(pin_val)) { printf("\n\rWPS-AP: Enter pin code is unvalid."); goto exit; } ret = wpas_wps_registrar_add_pin((unsigned char const*)pin, strlen(pin)); } else if(wps_config == WPS_CONFIG_DISPLAY) ret = wpas_wps_registrar_add_pin((unsigned char const*)pin, strlen(pin)); else ret = wpas_wps_registrar_button_pushed(); if(ret<0) goto exit; printf("\n\rWPS-AP: wait for STA connect!\n"); os_xqueue_receive(queue_for_credential, authorized_mac, 120); //max wait 2min if(!wpas_wps_registrar_check_done()) { ret = -1; wpas_wps_registrar_wps_cancel(); } exit: wifi_set_wps_phase(0); os_xqueue_delete(queue_for_credential); queue_for_credential = NULL; printf("\n\rWPS-AP: Finished!\n"); wifi_unreg_event_handler(WIFI_EVENT_STA_WPS_START, wpas_wsc_sta_wps_start_hdl); wifi_unreg_event_handler(WIFI_EVENT_WPS_FINISH, wpas_wsc_server_wps_finish_hdl); wifi_unreg_event_handler(WIFI_EVENT_EAPOL_RECVD, wpas_wsc_eapol_recvd_hdl); return ret; } static void wifi_start_ap_wps_thread_hdl( void *param) { ap_wps_start(config_method, wps_pin_code); //Not support WPS_CONFIG_KEYPAD ap_wps_task = NULL; vTaskDelete(NULL); } void wifi_start_ap_wps_thread(u16 config_methods, char *pin) { if((config_methods != WPS_CONFIG_PUSHBUTTON) && (config_methods != WPS_CONFIG_DISPLAY) && (config_methods != WPS_CONFIG_KEYPAD)){ printf("\n\rWPS-AP: Wps method(%d) is wrong. Not triger WPS.\n", config_methods); return; } config_method = config_methods; if(config_methods == WPS_CONFIG_DISPLAY || config_methods == WPS_CONFIG_KEYPAD) { if(pin) strcpy(wps_pin_code, pin); else{ printf("\n\rWPS-AP: PIN is NULL. Not triger WPS.\n"); return; } } if(ap_wps_task != NULL){ //push item to wait queue to finish last ap_wps task printf("\n\rWPS-AP: Wait for last ap_wps task exiting...\n"); if(queue_for_credential) os_xqueue_send(queue_for_credential, NULL, 0); while(ap_wps_task != NULL) vTaskDelay(1); vTaskDelay(20); printf("\n\rLast ap_wps task completed.\n"); } if(xTaskCreate(wifi_start_ap_wps_thread_hdl, ((const char*)"ap_wps"), 256, NULL, tskIDLE_PRIORITY + 3, &ap_wps_task) != pdPASS) printf("\n\r%s xTaskCreate(ap_wps thread) failed", __FUNCTION__); } #endif //CONFIG_ENABLE_WPS_AP void wps_judge_staion_disconnect(void) { int mode = 0; unsigned char ssid[33]; wext_get_mode(WLAN0_NAME, &mode); switch(mode) { case IW_MODE_MASTER: //In AP mode // rltk_wlan_deinit(); // rltk_wlan_init(0,RTW_MODE_STA); // rltk_wlan_start(0); //modified by Chris Yang for iNIC wifi_off(); vTaskDelay(20); wifi_on(RTW_MODE_STA); break; case IW_MODE_INFRA: //In STA mode if(wext_get_ssid(WLAN0_NAME, ssid) > 0) wifi_disconnect(); } } void cmd_wps(int argc, char **argv) { int ret = -1; (void) ret; wps_judge_staion_disconnect(); if((argc == 2 || argc == 3 ) && (argv[1] != NULL)){ if(strcmp(argv[1],"pin") == 0){ unsigned int pin_val = 0; /* start pin */ if(argc == 2){ char device_pin[10]; pin_val = wps_generate_pin(); snprintf(device_pin, sizeof(device_pin), "%08d", pin_val); /* Display PIN 3 times to prevent to be overwritten by logs from other tasks */ printf("\n\rWPS: Start WPS PIN Display. PIN: [%s]\n\r", device_pin); printf("\n\rWPS: Start WPS PIN Display. PIN: [%s]\n\r", device_pin); printf("\n\rWPS: Start WPS PIN Display. PIN: [%s]\n\r", device_pin); ret = wps_start(WPS_CONFIG_DISPLAY, (char*)device_pin, 0, NULL); }else{ pin_val = atoi(argv[2]); if (!wps_pin_valid(pin_val)) { printf("\n\rWPS: Device pin code is invalid. Not triger WPS.\n"); goto exit; } printf("\n\rWPS: Start WPS PIN Keypad.\n\r"); ret = wps_start(WPS_CONFIG_KEYPAD, argv[2], 0, NULL); } }else if(strcmp(argv[1],"pbc") == 0){ /* start pbc */ printf("\n\rWPS: Start WPS PBC.\n\r"); ret = wps_start(WPS_CONFIG_PUSHBUTTON, NULL, 0, NULL); }else{ printf("\n\rWPS: Wps Method is wrong. Not triger WPS.\n"); goto exit; } } exit: #if defined(CONFIG_INIC_CMD_RSP) && CONFIG_INIC_CMD_RSP if(ret != 0) inic_c2h_msg("ATWW", ret, NULL, 0); #endif return; } #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP /* cmd_ap_wps for AP WSC setting. command style: cmd_ap_wps pbc or cmd_ap_wps pin 12345678 */ void cmd_ap_wps(int argc, char **argv) { int mode = 0; if(rltk_wlan_running(WLAN1_IDX)){ printf("\n\rNot support con-current softAP WSC!\n\r"); return; } wext_get_mode(WLAN0_NAME, &mode); if(mode != IW_MODE_MASTER){ printf("\n\rOnly valid for IW_MODE_MASTER!\n\r"); return; } if((argc == 2 || argc == 3) && (argv[1] != NULL)) { if (strcmp(argv[1],"pin") == 0 ) { unsigned int pin_val = 0; if(argc == 3){ pin_val = atoi(argv[2]); if (!wps_pin_valid(pin_val)) { printf("\n\rWPS-AP: Device pin code is invalid. Not trigger WPS.\n\r"); return; } printf("\n\rWPS-AP: Start AP WPS PIN Keypad.\n"); wifi_start_ap_wps_thread(WPS_CONFIG_KEYPAD, argv[2]); }else{ char device_pin[10]; pin_val = wps_generate_pin(); snprintf(device_pin, sizeof(device_pin), "%08d", pin_val); printf("\n\rWPS: Start WPS PIN Display. PIN: %s\n\r", device_pin); wifi_start_ap_wps_thread(WPS_CONFIG_DISPLAY, (char*)device_pin); } }else if (strcmp(argv[1],"pbc") == 0) { printf("\n\rWPS-AP: Start AP WPS PBC\n"); wifi_start_ap_wps_thread(WPS_CONFIG_PUSHBUTTON, NULL); }else{ printf("\n\rWPS-AP Usage:\"wifi_ap_wps pin [pin_code]\" or \"wifi_ap_wps pbc\"\n"); return; } } else { printf("\n\rWPS-AP Usage:\"wifi_ap_wps pin [pin_code]\" or \"wifi_ap_wps pbc\"\n"); } return; } #endif //CONFIG_ENABLE_P2P #endif //CONFIG_ENABLE_WPS
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/rtw_wpa_supplicant/wpa_supplicant/wifi_wps_config.c
C
apache-2.0
36,636
/** ****************************************************************************** * @file wifi_wps_config.h * @author * @version * @brief This file provides user interfaces for WPS functionality. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ /** @addtogroup wpsp2p WPS/P2P * @ingroup wlan * @brief WPS/P2P functions * @{ */ /** * @brief Start WPS enrollee process. * @warning Before invoking this function, the Wi-Fi should be enabled by using @ref wifi_on(). * @param[in] wps_config: WPS configure method. Options are: WPS_CONFIG_DISPLAY, WPS_CONFIG_KEYPAD, and WPS_CONFIG_PUSHBUTTON. * @param[in] pin: PIN number. Can be set to NULL if using WPS_CONFIG_PUSHBUTTON. * @param[in] channel: Channel. Currently un-used, can be set to 0. * @param[in] ssid: Target network SSID. Can be set to NULL if no target network specified. * @return 0 on success. * @note Please make sure CONFIG_ENABLE_WPS is enabled in platform_opts.h.\n * You can reference @ref cmd_wps() to know how to choose input parameters. */ int wps_start(u16 wps_config, char *pin, u8 channel, char *ssid); /** * @brief Command to start WPS enrollee process for commonly use. Can refer to ATWW in atcmd_wifi.c. * @warning Before invoking this function, the Wi-Fi should be enabled by using @ref wifi_on(). * @param[in] argc: Command line argument. Argument count. * @param[in] argv: Command line argument. Argument vector. * @return 0 on success. * @note Command style for example: * - cmd_wps pbc * - cmd_wps pin * - cmd_wps pin 12345678 * @note Please make sure CONFIG_ENABLE_WPS is enabled in platform_opts.h. */ void cmd_wps(int argc, char **argv); /** * @brief Start a WPS registrar thread. * @warning Before invoking this function, the Wi-Fi should be in SoftAP mode. * @param[in] config_methods: WPS configure method. Options are: WPS_CONFIG_DISPLAY, WPS_CONFIG_KEYPAD, and WPS_CONFIG_PUSHBUTTON. * @param[in] pin: PIN number. Can be set to NULL. * @return None * @note Please make sure CONFIG_ENABLE_WPS and CONFIG_ENABLE_WPS_AP are enabled in platform_opts.h.\n * You can reference @ref cmd_ap_wps() to know how to choose input parameters. */ void wifi_start_ap_wps_thread(u16 config_methods, char *pin); /** * @brief Command to start WPS registrar process for commonly use. Can refer to ATWw in atcmd_wifi.c. * @warning Before invoking this function, the Wi-Fi should be in SoftAP mode. * @param[in] argc: Command line argument. Argument count. * @param[in] argv: Command line argument. Argument vector. * @return 0 on success * @note Command style for example: * - cmd_ap_wps pbc * - cmd_ap_wps pin * - cmd_ap_wps pin 12345678 * @note Please make sure CONFIG_ENABLE_WPS and CONFIG_ENABLE_WPS_AP are enabled in platform_opts.h. */ void cmd_ap_wps(int argc, char **argv); /* extern function declaration */ extern int wpas_wps_enrollee_init_probe_ie(u16 config_methods); extern int wpas_wps_enrollee_init_assoc_ie(void); extern void wpas_wps_deinit(void); extern unsigned int wps_generate_pin(void); extern unsigned int wps_pin_valid(unsigned int pin); /*\@}*/
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/rtw_wpa_supplicant/wpa_supplicant/wifi_wps_config.h
C
apache-2.0
3,526
//----------------------------------------------------------------------------// //#include <flash/stm32_flash.h> #if !defined(CONFIG_MBED_ENABLED) && !defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //#include "main.h" #include <lwip_netconf.h> #include <lwip/sockets.h> #include <dhcp/dhcps.h> #include "lwip/tcpip.h" #endif #include <platform/platform_stdlib.h> #include <wifi/wifi_conf.h> #include <wifi/wifi_util.h> #include <wifi/wifi_ind.h> #include <osdep_service.h> #include <device_lock.h> #include "aos/hal/wifi.h" #include <uservice/uservice.h> #include <uservice/eventid.h> #if CONFIG_EXAMPLE_WLAN_FAST_CONNECT || (defined(CONFIG_JD_SMART) && CONFIG_JD_SMART) #include "wlan_fast_connect/example_wlan_fast_connect.h" #if defined(CONFIG_FAST_DHCP) && CONFIG_FAST_DHCP #include "flash_api.h" #include "device_lock.h" #endif #endif #if (defined(CONFIG_EXAMPLE_UART_ATCMD) && CONFIG_EXAMPLE_UART_ATCMD) || (defined(CONFIG_EXAMPLE_SPI_ATCMD) && CONFIG_EXAMPLE_SPI_ATCMD) #include "at_cmd/atcmd_wifi.h" #endif #if CONFIG_INIC_EN extern int inic_start(void); extern int inic_stop(void); #endif extern u8 rtw_get_band_type(void); /****************************************************** * Constants ******************************************************/ #define SCAN_USE_SEMAPHORE 0 #define RTW_JOIN_TIMEOUT 20000 #define JOIN_ASSOCIATED (uint32_t)(1 << 0) #define JOIN_AUTHENTICATED (uint32_t)(1 << 1) #define JOIN_LINK_READY (uint32_t)(1 << 2) #define JOIN_SECURITY_COMPLETE (uint32_t)(1 << 3) #define JOIN_COMPLETE (uint32_t)(1 << 4) #define JOIN_NO_NETWORKS (uint32_t)(1 << 5) #define JOIN_WRONG_SECURITY (uint32_t)(1 << 6) #define JOIN_HANDSHAKE_DONE (uint32_t)(1 << 7) #define JOIN_SIMPLE_CONFIG (uint32_t)(1 << 8) #define JOIN_AIRKISS (uint32_t)(1 << 9) #define JOIN_CONNECTING (uint32_t)(1 << 10) /****************************************************** * Type Definitions ******************************************************/ /****************************************************** * Variables Declarations ******************************************************/ #if !defined(CONFIG_MBED_ENABLED) extern struct netif xnetif[NET_IF_NUM]; #endif /****************************************************** * Variables Definitions ******************************************************/ static internal_scan_handler_t scan_result_handler_ptr = {0, 0, 0, RTW_FALSE, 0, 0, 0, 0, 0}; static internal_join_result_t* join_user_data; static unsigned char ap_bssid[6]; #if CONFIG_WIFI_IND_USE_THREAD static void* disconnect_sema = NULL; #endif #if defined(CONFIG_MBED_ENABLED) rtw_mode_t wifi_mode = RTW_MODE_STA; #endif extern rtw_mode_t wifi_mode; int error_flag = RTW_UNKNOWN; uint32_t rtw_join_status; #if ATCMD_VER == ATVER_2 extern unsigned char dhcp_mode_sta; #endif /* The flag to check if wifi init is completed */ static int _wifi_is_on = 0; rtw_mode_t wifi_mode = RTW_MODE_STA; void* param_indicator; struct task_struct wifi_autoreconnect_task; /****************************************************** * Variables Definitions ******************************************************/ #ifndef WLAN0_NAME #define WLAN0_NAME "wlan0" #endif #ifndef WLAN1_NAME #define WLAN1_NAME "wlan1" #endif /* Give default value if not defined */ #ifndef NET_IF_NUM #ifdef CONFIG_CONCURRENT_MODE #define NET_IF_NUM 2 #else #define NET_IF_NUM 1 #endif #endif /*Static IP ADDRESS*/ #ifndef IP_ADDR0 #define IP_ADDR0 192 #define IP_ADDR1 168 #define IP_ADDR2 1 #define IP_ADDR3 80 #endif /*NETMASK*/ #ifndef NETMASK_ADDR0 #define NETMASK_ADDR0 255 #define NETMASK_ADDR1 255 #define NETMASK_ADDR2 255 #define NETMASK_ADDR3 0 #endif /*Gateway Address*/ #ifndef GW_ADDR0 #define GW_ADDR0 192 #define GW_ADDR1 168 #define GW_ADDR2 1 #define GW_ADDR3 1 #endif /*Static IP ADDRESS*/ #ifndef AP_IP_ADDR0 #define AP_IP_ADDR0 192 #define AP_IP_ADDR1 168 #define AP_IP_ADDR2 43 #define AP_IP_ADDR3 1 #endif /*NETMASK*/ #ifndef AP_NETMASK_ADDR0 #define AP_NETMASK_ADDR0 255 #define AP_NETMASK_ADDR1 255 #define AP_NETMASK_ADDR2 255 #define AP_NETMASK_ADDR3 0 #endif /*Gateway Address*/ #ifndef AP_GW_ADDR0 #define AP_GW_ADDR0 192 #define AP_GW_ADDR1 168 #define AP_GW_ADDR2 43 #define AP_GW_ADDR3 1 #endif #if defined(CONFIG_AUTO_RECONNECT) && CONFIG_AUTO_RECONNECT #ifndef AUTO_RECONNECT_COUNT #define AUTO_RECONNECT_COUNT 8 #endif #ifndef AUTO_RECONNECT_INTERVAL #define AUTO_RECONNECT_INTERVAL 5 // in sec #endif #endif /****************************************************** * Function Definitions ******************************************************/ #if CONFIG_WLAN extern unsigned char is_promisc_enabled(void); extern int promisc_set(rtw_rcr_level_t enabled, void (*callback)(unsigned char*, unsigned int, void*), unsigned char len_used); extern unsigned char _is_promisc_enabled(void); extern int wext_get_drv_ability(const char *ifname, __u32 *ability); extern void rltk_wlan_btcoex_set_bt_state(unsigned char state); extern int wext_close_lps_rf(const char *ifname); extern int rltk_wlan_reinit_drv_sw(const char *ifname, rtw_mode_t mode); extern int rltk_set_mode_prehandle(rtw_mode_t curr_mode, rtw_mode_t next_mode, const char *ifname); extern int rltk_set_mode_posthandle(rtw_mode_t curr_mode, rtw_mode_t next_mode, const char *ifname); #ifdef CONFIG_PMKSA_CACHING extern int wifi_set_pmk_cache_enable(unsigned char value); #endif extern void rltk_wlan_enable_scan_with_ssid_by_extended_security(BOOL enable); //----------------------------------------------------------------------------// static int wifi_connect_local(rtw_network_info_t *pWifi) { int ret = 0; if(is_promisc_enabled()) promisc_set(0, NULL, 0); #ifndef LOW_POWER_WIFI_CONNECT /* lock 4s to forbid suspend under linking */ rtw_wakelock_timeout(4 *1000); #endif if(!pWifi) return -1; switch(pWifi->security_type){ case RTW_SECURITY_OPEN: ret = wext_set_key_ext(WLAN0_NAME, IW_ENCODE_ALG_NONE, NULL, 0, 0, 0, 0, NULL, 0); break; case RTW_SECURITY_WEP_PSK: case RTW_SECURITY_WEP_SHARED: ret = wext_set_auth_param(WLAN0_NAME, IW_AUTH_80211_AUTH_ALG, IW_AUTH_ALG_SHARED_KEY); if(ret == 0) ret = wext_set_key_ext(WLAN0_NAME, IW_ENCODE_ALG_WEP, NULL, pWifi->key_id, 1 /* set tx key */, 0, 0, pWifi->password, pWifi->password_len); break; case RTW_SECURITY_WPA_TKIP_PSK: case RTW_SECURITY_WPA2_TKIP_PSK: case RTW_SECURITY_WPA_MIXED_PSK: case RTW_SECURITY_WPA_WPA2_TKIP_PSK: ret = wext_set_auth_param(WLAN0_NAME, IW_AUTH_80211_AUTH_ALG, IW_AUTH_ALG_OPEN_SYSTEM); if(ret == 0) ret = wext_set_key_ext(WLAN0_NAME, IW_ENCODE_ALG_TKIP, NULL, 0, 0, 0, 0, NULL, 0); if(ret == 0) ret = wext_set_passphrase(WLAN0_NAME, pWifi->password, pWifi->password_len); break; case RTW_SECURITY_WPA_AES_PSK: case RTW_SECURITY_WPA2_AES_PSK: case RTW_SECURITY_WPA2_MIXED_PSK: case RTW_SECURITY_WPA_WPA2_AES_PSK: case RTW_SECURITY_WPA_WPA2_MIXED_PSK: #ifdef CONFIG_SAE_SUPPORT case RTW_SECURITY_WPA3_AES_PSK: #endif ret = wext_set_auth_param(WLAN0_NAME, IW_AUTH_80211_AUTH_ALG, IW_AUTH_ALG_OPEN_SYSTEM); if(ret == 0) ret = wext_set_key_ext(WLAN0_NAME, IW_ENCODE_ALG_CCMP, NULL, 0, 0, 0, 0, NULL, 0); if(ret == 0) ret = wext_set_passphrase(WLAN0_NAME, pWifi->password, pWifi->password_len); break; default: ret = -1; RTW_API_INFO("\n\rWIFICONF: security type(0x%x) is not supported.\n\r", pWifi->security_type); break; } if(ret == 0) ret = wext_set_ssid(WLAN0_NAME, pWifi->ssid.val, pWifi->ssid.len); return ret; } static int wifi_connect_bssid_local(rtw_network_info_t *pWifi) { int ret = 0; u8 bssid[12] = {0}; if(is_promisc_enabled()) promisc_set(0, NULL, 0); /* lock 4s to forbid suspend under linking */ rtw_wakelock_timeout(4 *1000); if(!pWifi) return -1; switch(pWifi->security_type){ case RTW_SECURITY_OPEN: ret = wext_set_key_ext(WLAN0_NAME, IW_ENCODE_ALG_NONE, NULL, 0, 0, 0, 0, NULL, 0); break; case RTW_SECURITY_WEP_PSK: case RTW_SECURITY_WEP_SHARED: ret = wext_set_auth_param(WLAN0_NAME, IW_AUTH_80211_AUTH_ALG, IW_AUTH_ALG_SHARED_KEY); if(ret == 0) ret = wext_set_key_ext(WLAN0_NAME, IW_ENCODE_ALG_WEP, NULL, pWifi->key_id, 1 /* set tx key */, 0, 0, pWifi->password, pWifi->password_len); break; case RTW_SECURITY_WPA_TKIP_PSK: case RTW_SECURITY_WPA2_TKIP_PSK: case RTW_SECURITY_WPA_MIXED_PSK: case RTW_SECURITY_WPA_WPA2_TKIP_PSK: ret = wext_set_auth_param(WLAN0_NAME, IW_AUTH_80211_AUTH_ALG, IW_AUTH_ALG_OPEN_SYSTEM); if(ret == 0) ret = wext_set_key_ext(WLAN0_NAME, IW_ENCODE_ALG_TKIP, NULL, 0, 0, 0, 0, NULL, 0); if(ret == 0) ret = wext_set_passphrase(WLAN0_NAME, pWifi->password, pWifi->password_len); break; case RTW_SECURITY_WPA_AES_PSK: case RTW_SECURITY_WPA2_AES_PSK: case RTW_SECURITY_WPA2_MIXED_PSK: case RTW_SECURITY_WPA_WPA2_AES_PSK: case RTW_SECURITY_WPA_WPA2_MIXED_PSK: #ifdef CONFIG_SAE_SUPPORT case RTW_SECURITY_WPA3_AES_PSK: #endif ret = wext_set_auth_param(WLAN0_NAME, IW_AUTH_80211_AUTH_ALG, IW_AUTH_ALG_OPEN_SYSTEM); if(ret == 0) ret = wext_set_key_ext(WLAN0_NAME, IW_ENCODE_ALG_CCMP, NULL, 0, 0, 0, 0, NULL, 0); if(ret == 0) ret = wext_set_passphrase(WLAN0_NAME, pWifi->password, pWifi->password_len); break; default: ret = -1; RTW_API_INFO("\n\rWIFICONF: security type(0x%x) is not supported.\n\r", pWifi->security_type); break; } if(ret == 0){ memcpy(bssid, pWifi->bssid.octet, ETH_ALEN); if(pWifi->ssid.len){ bssid[ETH_ALEN] = '#'; bssid[ETH_ALEN + 1] = '@'; memcpy(bssid + ETH_ALEN + 2, &pWifi, sizeof(pWifi)); } ret = wext_set_bssid(WLAN0_NAME, bssid); } return ret; } void wifi_rx_beacon_hdl( char* buf, int buf_len, int flags, void* userdata) { /* To avoid gcc warnings */ ( void ) buf; ( void ) buf_len; ( void ) flags; ( void ) userdata; //RTW_API_INFO("Beacon!\n"); } static void wifi_no_network_hdl(char* buf, int buf_len, int flags, void* userdata) { /* To avoid gcc warnings */ ( void ) buf; ( void ) buf_len; ( void ) flags; ( void ) userdata; if(join_user_data!=NULL) rtw_join_status = JOIN_NO_NETWORKS | JOIN_CONNECTING; } static void wifi_connected_hdl( char* buf, int buf_len, int flags, void* userdata) { /* To avoid gcc warnings */ ( void ) buf_len; ( void ) flags; ( void ) userdata; rtw_memcpy(ap_bssid, buf, ETH_ALEN); #ifdef CONFIG_ENABLE_EAP if(get_eap_phase()){ rtw_join_status = JOIN_COMPLETE | JOIN_SECURITY_COMPLETE | JOIN_ASSOCIATED | JOIN_AUTHENTICATED | JOIN_LINK_READY | JOIN_CONNECTING; return; } #endif /* CONFIG_ENABLE_EAP */ if((join_user_data!=NULL)&&((join_user_data->network_info.security_type == RTW_SECURITY_OPEN) || (join_user_data->network_info.security_type == RTW_SECURITY_WEP_PSK) || (join_user_data->network_info.security_type == RTW_SECURITY_WEP_SHARED))){ rtw_join_status = JOIN_COMPLETE | JOIN_SECURITY_COMPLETE | JOIN_ASSOCIATED | JOIN_AUTHENTICATED | JOIN_LINK_READY | JOIN_CONNECTING; rtw_up_sema(&join_user_data->join_sema); }else if((join_user_data!=NULL)&&((join_user_data->network_info.security_type == RTW_SECURITY_WPA2_AES_PSK) )){ rtw_join_status = JOIN_COMPLETE | JOIN_SECURITY_COMPLETE | JOIN_ASSOCIATED | JOIN_AUTHENTICATED | JOIN_LINK_READY | JOIN_CONNECTING; } } static void wifi_handshake_done_hdl( char* buf, int buf_len, int flags, void* userdata) { /* To avoid gcc warnings */ ( void ) buf; ( void ) buf_len; ( void ) flags; ( void ) userdata; rtw_join_status = JOIN_COMPLETE | JOIN_SECURITY_COMPLETE | JOIN_ASSOCIATED | JOIN_AUTHENTICATED | JOIN_LINK_READY|JOIN_HANDSHAKE_DONE | JOIN_CONNECTING; if(join_user_data != NULL) rtw_up_sema(&join_user_data->join_sema); } extern void dhcp_stop(struct netif *netif); static void wifi_disconn_hdl( char* buf, int buf_len, int flags, void* userdata) { /* To avoid gcc warnings */ ( void ) buf_len; ( void ) flags; ( void ) userdata; #define REASON_4WAY_HNDSHK_TIMEOUT 15 u16 disconn_reason; if (buf != NULL){ /* buf detail: mac addr + disconn_reason, buf_len = ETH_ALEN+2*/ disconn_reason =*(u16*)(buf+6); } if(join_user_data != NULL){ if(join_user_data->network_info.security_type == RTW_SECURITY_OPEN){ if(rtw_join_status & JOIN_NO_NETWORKS) error_flag = RTW_NONE_NETWORK; }else if(join_user_data->network_info.security_type == RTW_SECURITY_WEP_PSK){ if(rtw_join_status & JOIN_NO_NETWORKS) error_flag = RTW_NONE_NETWORK; else if(rtw_join_status == 0) error_flag = RTW_CONNECT_FAIL; }else if(join_user_data->network_info.security_type == RTW_SECURITY_WPA2_AES_PSK){ if(rtw_join_status & JOIN_NO_NETWORKS) error_flag = RTW_NONE_NETWORK; else if(rtw_join_status == 0) error_flag = RTW_CONNECT_FAIL; else if(rtw_join_status == (JOIN_COMPLETE | JOIN_SECURITY_COMPLETE | JOIN_ASSOCIATED | JOIN_AUTHENTICATED | JOIN_LINK_READY | JOIN_CONNECTING)) { if(disconn_reason == REASON_4WAY_HNDSHK_TIMEOUT) error_flag = RTW_4WAY_HANDSHAKE_TIMEOUT; else error_flag = RTW_WRONG_PASSWORD; } } }else{ if(error_flag == RTW_NO_ERROR) //wifi_disconn_hdl will be dispatched one more time after join_user_data = NULL add by frankie error_flag = RTW_UNKNOWN; } #if CONFIG_LWIP_LAYER #if defined(CONFIG_MBED_ENABLED) || defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO #else dhcp_stop(&xnetif[0]); #endif #endif if(join_user_data != NULL) rtw_up_sema(&join_user_data->join_sema); //RTW_API_INFO("\r\nWiFi Disconnect. Error flag is %d.\n", error_flag); // Need to use sema to make sure wifi_disconn_hdl invoked before setting join_user_data when connecting to another AP #if CONFIG_WIFI_IND_USE_THREAD if(disconnect_sema != NULL){ rtw_up_sema(&disconnect_sema); } #endif event_publish(EVENT_WIFI_DISCONNECTED, &disconn_reason); } #if CONFIG_EXAMPLE_WLAN_FAST_CONNECT || (defined(CONFIG_JD_SMART) && CONFIG_JD_SMART) #define WLAN0_NAME "wlan0" struct wlan_fast_reconnect wifi_data_to_flash; #if defined(CONFIG_FAST_DHCP) && CONFIG_FAST_DHCP u8 is_the_same_ap = 0; #endif void restore_wifi_info_to_flash(void) { u32 channel = 0; u8 index = 0; u8 *ifname[1] = {(u8*)WLAN0_NAME}; rtw_wifi_setting_t setting; //struct security_priv *psecuritypriv = &padapter->securitypriv; //WLAN_BSSID_EX *pcur_bss = pmlmepriv->cur_network.network; rtw_memset(&wifi_data_to_flash,0,sizeof(struct wlan_fast_reconnect)); if(p_write_reconnect_ptr){ if(wifi_get_setting((const char*)ifname[0],&setting) || setting.mode == RTW_MODE_AP){ RTW_API_INFO("\r\n %s():wifi_get_setting fail or ap mode", __func__); return; } channel = setting.channel; #if defined(CONFIG_FAST_DHCP) && CONFIG_FAST_DHCP flash_t flash; struct wlan_fast_reconnect data; device_mutex_lock(RT_DEV_LOCK_FLASH); flash_stream_read(&flash, FAST_RECONNECT_DATA, sizeof(struct wlan_fast_reconnect), (uint8_t *)&data); device_mutex_unlock(RT_DEV_LOCK_FLASH); if(strncmp((const char*)data.psk_essid,(const char*)setting.ssid,strlen((char const*)setting.ssid)) == 0){ is_the_same_ap = 1; }else{ is_the_same_ap = 0; } #endif rtw_memset(psk_essid[index], 0, sizeof(psk_essid[index])); strncpy((char*)psk_essid[index], (char const*)setting.ssid, strlen((char const*)setting.ssid)); switch(setting.security_type){ case RTW_SECURITY_OPEN: rtw_memset(psk_passphrase[index], 0, sizeof(psk_passphrase[index])); rtw_memset(wpa_global_PSK[index], 0, sizeof(wpa_global_PSK[index])); wifi_data_to_flash.security_type = RTW_SECURITY_OPEN; break; case RTW_SECURITY_WEP_PSK: channel |= (setting.key_idx) << 28; rtw_memset(psk_passphrase[index], 0, sizeof(psk_passphrase[index])); rtw_memset(wpa_global_PSK[index], 0, sizeof(wpa_global_PSK[index])); rtw_memcpy(psk_passphrase[index], setting.password, sizeof(psk_passphrase[index])); wifi_data_to_flash.security_type = RTW_SECURITY_WEP_PSK; break; case RTW_SECURITY_WPA_TKIP_PSK: wifi_data_to_flash.security_type = RTW_SECURITY_WPA_TKIP_PSK; break; case RTW_SECURITY_WPA2_AES_PSK: wifi_data_to_flash.security_type = RTW_SECURITY_WPA2_AES_PSK; break; #ifdef CONFIG_SAE_SUPPORT case RTW_SECURITY_WPA3_AES_PSK: wifi_data_to_flash.security_type = RTW_SECURITY_WPA3_AES_PSK; break; #endif default: break; } memcpy(wifi_data_to_flash.psk_essid, psk_essid[index], sizeof(wifi_data_to_flash.psk_essid)); if (strlen((char const*)psk_passphrase64) == 64) { memcpy(wifi_data_to_flash.psk_passphrase, psk_passphrase64, sizeof(wifi_data_to_flash.psk_passphrase)); } else { memcpy(wifi_data_to_flash.psk_passphrase, psk_passphrase[index], sizeof(wifi_data_to_flash.psk_passphrase)); } //For avoiding 13Bytes password of WEP ascii replacing WPA that will cause four-way handshaking failed because of not generating global_psk. if(setting.security_type == RTW_SECURITY_WEP_PSK) rtw_memset(psk_passphrase[index], 0, sizeof(psk_passphrase[index])); memcpy(wifi_data_to_flash.wpa_global_PSK, wpa_global_PSK[index], sizeof(wifi_data_to_flash.wpa_global_PSK)); memcpy(&(wifi_data_to_flash.channel), &channel, 4); #if !defined(CONFIG_FAST_DHCP) || (CONFIG_FAST_DHCP == 0) || CONFIG_EXAMPLE_WIFI_ROAMING_PLUS //for wifi_roaming in FIT_APs, there is no DHCP needed, but we want to store FIT AP channels into flash for specific scan //call callback function in user program p_write_reconnect_ptr((u8 *)&wifi_data_to_flash, sizeof(struct wlan_fast_reconnect)); #endif } } #endif //----------------------------------------------------------------------------// int wifi_connect( char *ssid, rtw_security_t security_type, char *password, int ssid_len, int password_len, int key_id, void *semaphore) { _sema join_semaphore; rtw_result_t result = RTW_SUCCESS; u8 wep_hex = 0; u8 wep_pwd[14] = {0}; if(rtw_join_status & JOIN_CONNECTING){ if(wifi_disconnect() < 0){ RTW_API_INFO("\nwifi_disconnect Operation failed!"); return RTW_ERROR; } while(rtw_join_status & JOIN_CONNECTING){ rtw_msleep_os(1); } } if(rtw_join_status & JOIN_SIMPLE_CONFIG || rtw_join_status & JOIN_AIRKISS){ return RTW_BUSY; } error_flag = RTW_UNKNOWN ;//clear for last connect status rtw_memset(ap_bssid, 0, ETH_ALEN); if ( ( ( ( password_len > RTW_MAX_PSK_LEN ) || ( password_len < RTW_MIN_PSK_LEN ) ) && ( ( security_type == RTW_SECURITY_WPA_TKIP_PSK ) || ( security_type == RTW_SECURITY_WPA_AES_PSK ) || ( security_type == RTW_SECURITY_WPA_MIXED_PSK ) || ( security_type == RTW_SECURITY_WPA2_AES_PSK ) || ( security_type == RTW_SECURITY_WPA2_TKIP_PSK ) || ( security_type == RTW_SECURITY_WPA2_MIXED_PSK )|| ( security_type == RTW_SECURITY_WPA_WPA2_TKIP_PSK)|| ( security_type == RTW_SECURITY_WPA_WPA2_AES_PSK)|| ( security_type == RTW_SECURITY_WPA_WPA2_MIXED_PSK) #ifdef CONFIG_SAE_SUPPORT ||( security_type == RTW_SECURITY_WPA3_AES_PSK) #endif ) ) ) { error_flag = RTW_WRONG_PASSWORD; return RTW_INVALID_KEY; } if ((security_type == RTW_SECURITY_WEP_PSK)|| (security_type ==RTW_SECURITY_WEP_SHARED)) { if ((password_len != 5) && (password_len != 13) && (password_len != 10)&& (password_len != 26)) { error_flag = RTW_WRONG_PASSWORD; return RTW_INVALID_KEY; } else { if(password_len == 10) { u32 p[5] = {0}; u8 i = 0; sscanf((const char*)password, "%02x%02x%02x%02x%02x", &p[0], &p[1], &p[2], &p[3], &p[4]); for(i=0; i< 5; i++) wep_pwd[i] = (u8)p[i]; wep_pwd[5] = '\0'; password_len = 5; wep_hex = 1; } else if (password_len == 26) { u32 p[13] = {0}; u8 i = 0; sscanf((const char*)password, "%02x%02x%02x%02x%02x%02x%02x"\ "%02x%02x%02x%02x%02x%02x", &p[0], &p[1], &p[2], &p[3], &p[4],\ &p[5], &p[6], &p[7], &p[8], &p[9], &p[10], &p[11], &p[12]); for(i=0; i< 13; i++) wep_pwd[i] = (u8)p[i]; wep_pwd[13] = '\0'; password_len = 13; wep_hex = 1; } } } internal_join_result_t *join_result = (internal_join_result_t *)rtw_zmalloc(sizeof(internal_join_result_t)); if(!join_result) { return RTW_NOMEM; } join_result->network_info.ssid.len = ssid_len > 32 ? 32 : ssid_len; rtw_memcpy(join_result->network_info.ssid.val, ssid, join_result->network_info.ssid.len); join_result->network_info.password_len = password_len; if(password_len) { /* add \0 to the end */ join_result->network_info.password = rtw_zmalloc(password_len + 1); if(!join_result->network_info.password) { result =(rtw_result_t) RTW_NOMEM; goto error; } if (0 == wep_hex) rtw_memcpy(join_result->network_info.password, password, password_len); else rtw_memcpy(join_result->network_info.password, wep_pwd, password_len); } join_result->network_info.security_type = security_type; join_result->network_info.key_id = key_id; if(semaphore == NULL) { rtw_init_sema( &join_result->join_sema, 0 ); if(!join_result->join_sema){ result =(rtw_result_t) RTW_NORESOURCE; goto error; } join_semaphore = join_result->join_sema; } else { join_result->join_sema = semaphore; } wifi_reg_event_handler(WIFI_EVENT_NO_NETWORK,wifi_no_network_hdl,NULL); wifi_reg_event_handler(WIFI_EVENT_CONNECT, wifi_connected_hdl, NULL); wifi_reg_event_handler(WIFI_EVENT_DISCONNECT, wifi_disconn_hdl, NULL); wifi_reg_event_handler(WIFI_EVENT_FOURWAY_HANDSHAKE_DONE, wifi_handshake_done_hdl, NULL); // if is connected to ap, would trigger disconn_hdl but need to make sure it is invoked before setting join_user_data #if CONFIG_WIFI_IND_USE_THREAD if(wifi_is_connected_to_ap() == RTW_SUCCESS){ rtw_init_sema( &disconnect_sema, 0 ); } #endif rtw_join_status = JOIN_CONNECTING; result = wifi_connect_local(&join_result->network_info); if(result != 0) goto error; #if CONFIG_WIFI_IND_USE_THREAD if(disconnect_sema != NULL){ rtw_down_timeout_sema(&disconnect_sema, 50); rtw_free_sema( &disconnect_sema); } #endif join_user_data = join_result; if(semaphore == NULL) { // for eap connection, timeout should be longer (default value in wpa_supplicant: 60s) #ifdef CONFIG_ENABLE_EAP if(get_eap_phase()){ if(rtw_down_timeout_sema( &join_result->join_sema, 60000 ) == RTW_FALSE) { RTW_API_INFO("RTW API: Join bss timeout\r\n"); if(password_len) { rtw_free(join_result->network_info.password); } result = RTW_TIMEOUT; goto error; } else { if(wifi_is_connected_to_ap( ) != RTW_SUCCESS) { result = RTW_ERROR; goto error; } } } else #endif if(rtw_down_timeout_sema( &join_result->join_sema, RTW_JOIN_TIMEOUT ) == RTW_FALSE) { RTW_API_INFO("RTW API: Join bss timeout\r\n"); if(password_len) { rtw_free(join_result->network_info.password); } result = RTW_TIMEOUT; goto error; } else { if(join_result->network_info.password_len) { rtw_free(join_result->network_info.password); } if(wifi_is_connected_to_ap( ) != RTW_SUCCESS) { result = RTW_ERROR; goto error; } } } result = RTW_SUCCESS; #if CONFIG_LWIP_LAYER #if defined(CONFIG_MBED_ENABLED) || defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO #else netif_set_link_up(&xnetif[0]); #endif #endif #if CONFIG_EXAMPLE_WLAN_FAST_CONNECT || (defined(CONFIG_JD_SMART) && CONFIG_JD_SMART) restore_wifi_info_to_flash(); #endif error: if(semaphore == NULL){ rtw_free_sema( &join_semaphore); } join_user_data = NULL; rtw_free((u8*)join_result); wifi_unreg_event_handler(WIFI_EVENT_CONNECT, wifi_connected_hdl); wifi_unreg_event_handler(WIFI_EVENT_NO_NETWORK,wifi_no_network_hdl); wifi_unreg_event_handler(WIFI_EVENT_FOURWAY_HANDSHAKE_DONE, wifi_handshake_done_hdl); rtw_join_status &= ~JOIN_CONNECTING; return result; } int wifi_connect_bssid( unsigned char bssid[ETH_ALEN], char *ssid, rtw_security_t security_type, char *password, int bssid_len, int ssid_len, int password_len, int key_id, void *semaphore) { _sema join_semaphore; rtw_result_t result = RTW_SUCCESS; u8 wep_hex = 0; u8 wep_pwd[14] = {0}; if(rtw_join_status & JOIN_CONNECTING){ if(wifi_disconnect() < 0){ RTW_API_INFO("\nwifi_disconnect Operation failed!"); return RTW_ERROR; } while(rtw_join_status & JOIN_CONNECTING){ rtw_mdelay_os(1); } } if(rtw_join_status & JOIN_SIMPLE_CONFIG || rtw_join_status & JOIN_AIRKISS){ return RTW_BUSY; } error_flag = RTW_UNKNOWN;//clear for last connect status rtw_memset(ap_bssid, 0, ETH_ALEN); internal_join_result_t *join_result = (internal_join_result_t *)rtw_zmalloc(sizeof(internal_join_result_t)); if(!join_result) { return RTW_NOMEM; } if(ssid_len && ssid){ join_result->network_info.ssid.len = ssid_len > 32 ? 32 : ssid_len; rtw_memcpy(join_result->network_info.ssid.val, ssid, join_result->network_info.ssid.len); } rtw_memcpy(join_result->network_info.bssid.octet, bssid, bssid_len); if ( ( ( ( password_len > RTW_MAX_PSK_LEN ) || ( password_len < RTW_MIN_PSK_LEN ) ) && ( ( security_type == RTW_SECURITY_WPA_TKIP_PSK ) || ( security_type == RTW_SECURITY_WPA_AES_PSK ) || ( security_type == RTW_SECURITY_WPA_MIXED_PSK ) || ( security_type == RTW_SECURITY_WPA2_AES_PSK ) || ( security_type == RTW_SECURITY_WPA2_TKIP_PSK ) || ( security_type == RTW_SECURITY_WPA2_MIXED_PSK ) || ( security_type == RTW_SECURITY_WPA_WPA2_TKIP_PSK)|| ( security_type == RTW_SECURITY_WPA_WPA2_AES_PSK)|| ( security_type == RTW_SECURITY_WPA_WPA2_MIXED_PSK) #ifdef CONFIG_SAE_SUPPORT ||( security_type == RTW_SECURITY_WPA3_AES_PSK) #endif ) ) ) { return RTW_INVALID_KEY; } if ((security_type == RTW_SECURITY_WEP_PSK)|| (security_type ==RTW_SECURITY_WEP_SHARED)) { if ((password_len != 5) && (password_len != 13) && (password_len != 10)&& (password_len != 26)) { return RTW_INVALID_KEY; } else { if(password_len == 10) { u32 p[5] = {0}; u8 i = 0; sscanf((const char*)password, "%02x%02x%02x%02x%02x", &p[0], &p[1], &p[2], &p[3], &p[4]); for(i=0; i< 5; i++) wep_pwd[i] = (u8)p[i]; wep_pwd[5] = '\0'; password_len = 5; wep_hex = 1; } else if (password_len == 26) { u32 p[13] = {0}; u8 i = 0; sscanf((const char*)password, "%02x%02x%02x%02x%02x%02x%02x"\ "%02x%02x%02x%02x%02x%02x", &p[0], &p[1], &p[2], &p[3], &p[4],\ &p[5], &p[6], &p[7], &p[8], &p[9], &p[10], &p[11], &p[12]); for(i=0; i< 13; i++) wep_pwd[i] = (u8)p[i]; wep_pwd[13] = '\0'; password_len = 13; wep_hex = 1; } } } join_result->network_info.password_len = password_len; if(password_len) { /* add \0 to the end */ join_result->network_info.password = rtw_zmalloc(password_len + 1); if(!join_result->network_info.password) { return RTW_NOMEM; } if (0 == wep_hex) rtw_memcpy(join_result->network_info.password, password, password_len); else rtw_memcpy(join_result->network_info.password, wep_pwd, password_len); } join_result->network_info.security_type = security_type; join_result->network_info.key_id = key_id; if(semaphore == NULL) { rtw_init_sema( &join_result->join_sema, 0 ); if(!join_result->join_sema){ return RTW_NORESOURCE; } join_semaphore = join_result->join_sema; } else { join_result->join_sema = semaphore; } wifi_reg_event_handler(WIFI_EVENT_NO_NETWORK,wifi_no_network_hdl,NULL); wifi_reg_event_handler(WIFI_EVENT_CONNECT, wifi_connected_hdl, NULL); wifi_reg_event_handler(WIFI_EVENT_DISCONNECT, wifi_disconn_hdl, NULL); wifi_reg_event_handler(WIFI_EVENT_FOURWAY_HANDSHAKE_DONE, wifi_handshake_done_hdl, NULL); rtw_join_status = JOIN_CONNECTING; wifi_connect_bssid_local(&join_result->network_info); join_user_data = join_result; if(semaphore == NULL) { if(rtw_down_timeout_sema( &join_result->join_sema, RTW_JOIN_TIMEOUT ) == RTW_FALSE) { RTW_API_INFO("RTW API: Join bss timeout\r\n"); if(password_len) { rtw_free(join_result->network_info.password); } rtw_free((u8*)join_result); rtw_free_sema( &join_semaphore); result = RTW_TIMEOUT; goto error; } else { rtw_free_sema( &join_semaphore ); if(join_result->network_info.password_len) { rtw_free(join_result->network_info.password); } rtw_free((u8*)join_result); if( wifi_is_connected_to_ap( ) != RTW_SUCCESS) { result = RTW_ERROR; goto error; } } } result = RTW_SUCCESS; #if CONFIG_LWIP_LAYER #if defined(CONFIG_MBED_ENABLED) || defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO #else netif_set_link_up(&xnetif[0]); #endif #endif #if CONFIG_EXAMPLE_WLAN_FAST_CONNECT || (defined(CONFIG_JD_SMART) && CONFIG_JD_SMART) restore_wifi_info_to_flash(); #endif error: join_user_data = NULL; wifi_unreg_event_handler(WIFI_EVENT_CONNECT, wifi_connected_hdl); wifi_unreg_event_handler(WIFI_EVENT_NO_NETWORK,wifi_no_network_hdl); wifi_unreg_event_handler(WIFI_EVENT_FOURWAY_HANDSHAKE_DONE, wifi_handshake_done_hdl); rtw_join_status &= ~JOIN_CONNECTING; return result; } int wifi_disconnect(void) { int ret = 0; //set MAC address last byte to 1 since driver will filter the mac with all 0x00 or 0xff //add extra 2 zero byte for check of #@ in wext_set_bssid() const __u8 null_bssid[ETH_ALEN + 2] = {0, 0, 0, 0, 0, 1, 0, 0}; if (wext_set_bssid(WLAN0_NAME, null_bssid) < 0){ RTW_API_INFO("\n\rWEXT: Failed to set bogus BSSID to disconnect"); ret = -1; } return ret; } //----------------------------------------------------------------------------// int wifi_is_connected_to_ap( void ) { return rltk_wlan_is_connected_to_ap(); } //----------------------------------------------------------------------------// int wifi_is_up(rtw_interface_t interface) { switch (interface) { case RTW_AP_INTERFACE: switch (wifi_mode) { case RTW_MODE_STA_AP: return (rltk_wlan_running(WLAN1_IDX) && _wifi_is_on); case RTW_MODE_STA: return 0; default: return (rltk_wlan_running(WLAN0_IDX) && _wifi_is_on); } case RTW_STA_INTERFACE: switch (wifi_mode) { case RTW_MODE_AP: return 0; default: return (rltk_wlan_running(WLAN0_IDX) && _wifi_is_on); } default: return 0; } } int wifi_is_ready_to_transceive(rtw_interface_t interface) { switch ( interface ) { case RTW_AP_INTERFACE: return ( wifi_is_up(interface) == RTW_TRUE ) ? RTW_SUCCESS : RTW_ERROR; case RTW_STA_INTERFACE: switch ( error_flag) { case RTW_NO_ERROR: return RTW_SUCCESS; default: return RTW_ERROR; } default: return RTW_ERROR; } } //----------------------------------------------------------------------------// int wifi_set_mac_address(char * mac) { char buf[13+17+1]; rtw_memset(buf, 0, sizeof(buf)); snprintf(buf, 13+17, "write_mac %s", mac); return wext_private_command(WLAN0_NAME, buf, 0); } int wifi_get_mac_address(char * mac) { int ret = 0; char buf[32]; rtw_memset(buf, 0, sizeof(buf)); rtw_memcpy(buf, "read_mac", 8); ret = wext_private_command_with_retval(WLAN0_NAME, buf, buf, 32); strcpy(mac, buf); return ret; } //----------------------------------------------------------------------------// int wifi_enable_powersave(void) { return wext_enable_powersave(WLAN0_NAME, 1, 1); } int wifi_resume_powersave(void) { return wext_resume_powersave(WLAN0_NAME); } int wifi_disable_powersave(void) { return wext_disable_powersave(WLAN0_NAME); } void wifi_btcoex_set_bt_on(void) { rltk_wlan_btcoex_set_bt_state(1); } void wifi_btcoex_set_bt_off(void) { rltk_wlan_btcoex_set_bt_state(0); } #if 0 //Not ready //----------------------------------------------------------------------------// int wifi_get_txpower(int *poweridx) { int ret = 0; char buf[11]; rtw_memset(buf, 0, sizeof(buf)); rtw_memcpy(buf, "txpower", 11); ret = wext_private_command_with_retval(WLAN0_NAME, buf, buf, 11); sscanf(buf, "%d", poweridx); return ret; } int wifi_set_txpower(int poweridx) { int ret = 0; char buf[24]; rtw_memset(buf, 0, sizeof(buf)); snprintf(buf, 24, "txpower patha=%d", poweridx); ret = wext_private_command(WLAN0_NAME, buf, 0); return ret; } #endif //----------------------------------------------------------------------------// int wifi_get_associated_client_list(void * client_list_buffer, uint16_t buffer_length) { /* To avoid gcc warnings */ ( void ) buffer_length; const char * ifname = WLAN0_NAME; int ret = 0; char buf[25]; if(wifi_mode == RTW_MODE_STA_AP) { ifname = WLAN1_NAME; } rtw_memset(buf, 0, sizeof(buf)); snprintf(buf, 25, "get_client_list %x", (unsigned int)client_list_buffer); ret = wext_private_command(ifname, buf, 0); return ret; } //----------------------------------------------------------------------------// int wifi_get_ap_bssid(unsigned char *bssid) { if( RTW_SUCCESS == wifi_is_ready_to_transceive(RTW_STA_INTERFACE)){ rtw_memcpy(bssid, ap_bssid, ETH_ALEN); return RTW_SUCCESS; } return RTW_ERROR; } //----------------------------------------------------------------------------// int wifi_get_ap_info(rtw_bss_info_t * ap_info, rtw_security_t* security) { const char * ifname = WLAN0_NAME; int ret = 0; char buf[24]; if(wifi_mode == RTW_MODE_STA_AP) { ifname = WLAN1_NAME; } rtw_memset(buf, 0, sizeof(buf)); snprintf(buf, 24, "get_ap_info %x", (unsigned int)ap_info); ret = wext_private_command(ifname, buf, 0); snprintf(buf, 24, "get_security"); ret = wext_private_command_with_retval(ifname, buf, buf, 24); sscanf(buf, "%d", security); return ret; } int wifi_get_drv_ability(uint32_t *ability) { return wext_get_drv_ability(WLAN0_NAME, (__u32 *)ability); } //----------------------------------------------------------------------------// int wifi_set_country(rtw_country_code_t country_code) { int ret; ret = wext_set_country(WLAN0_NAME, country_code); return ret; } //----------------------------------------------------------------------------// int wifi_change_channel_plan(uint8_t channel_plan) { int ret; ret = rltk_wlan_change_channel_plan(channel_plan); return ret; } //----------------------------------------------------------------------------// int wifi_set_channel_plan(uint8_t channel_plan) { const char * ifname = WLAN0_NAME; int ret = 0; char buf[24]; rtw_memset(buf, 0, sizeof(buf)); snprintf(buf, 24, "set_ch_plan %x", channel_plan); ret = wext_private_command(ifname, buf, 0); return ret; } int wifi_get_channel_plan(uint8_t *channel_plan) { int ret = 0; char buf[24]; char *ptmp; rtw_memset(buf, 0, sizeof(buf)); rtw_memcpy(buf, "get_ch_plan", 11); ret = wext_private_command_with_retval(WLAN0_NAME, buf, buf, 24); *channel_plan = strtoul(buf, &ptmp, 16); return ret; } /*this function is a new added API to get snr and rssi info wifi_get_rssi can get the ava rssi info. this function can get the ava rssi, rssi in latest packet, snr, snr in latest packet */ int wifi_get_signal_info(int32_t *signal) { int ret = 0; char buf[24]; char *ptmp; int total_info; rtw_memset(buf, 0, sizeof(buf)); rtw_memcpy(buf, "get_signal_info", 15); ret = wext_private_command_with_retval(WLAN0_NAME, buf, buf, 24); total_info = strtoul(buf, &ptmp, 16); //get the snr info of latest received packet //*signal = total_info & 0xFF; //get the avarage snr info *signal = (total_info >> 8) & 0xFF; //get the rssi info of latest received packet //*signal = (total_info >> 16) & 0xFF; //get the avarage rssi info the same as (wifi_get_rssi) //*signal = (total_info >> 24) & 0xFF; return ret; } //----------------------------------------------------------------------------// extern int rltk_wlan_get_sta_max_data_rate(u8 *inidata_rate); int wifi_get_sta_max_data_rate(OUT u8 * inidata_rate) { return rltk_wlan_get_sta_max_data_rate(inidata_rate); } //----------------------------------------------------------------------------// int wifi_get_rssi(int *pRSSI) { return wext_get_rssi(WLAN0_NAME, pRSSI); } int wifi_get_bcn_rssi(int *pRSSI) { return wext_get_bcn_rssi(WLAN0_NAME, pRSSI); } //----------------------------------------------------------------------------// int wifi_set_channel(int channel) { return wext_set_channel(WLAN0_NAME, channel); } int wifi_get_channel(int *channel) { u8 ch; if(wext_get_channel(WLAN0_NAME, &ch) < 0) return -1; *channel = (int)ch; return 0; } //----------------------------------------------------------------------------// int wifi_register_multicast_address(rtw_mac_t *mac) { return wext_register_multicast_address(WLAN0_NAME, mac); } int wifi_unregister_multicast_address(rtw_mac_t *mac) { return wext_unregister_multicast_address(WLAN0_NAME, mac); } //----------------------------------------------------------------------------// _WEAK void wifi_set_mib(void) { // adaptivity wext_set_adaptivity(RTW_ADAPTIVITY_DISABLE); //trp tis wext_set_trp_tis(RTW_TRP_TIS_DISABLE); wext_set_anti_interference(DISABLE); #ifdef CONFIG_POWER_SAVING //PS_MODE_MIN:1(default), PS_MODE_MAX:2 wext_set_powersave_mode(1); #endif #ifdef CONFIG_SAE_SUPPORT // set to 'ENABLE' when using WPA3 wext_set_support_wpa3(ENABLE); #endif wext_set_ant_div_gpio(0); wext_set_bw40_enable(0); //default disable 40m } //----------------------------------------------------------------------------// _WEAK void wifi_set_country_code(void) { //wifi_set_country(RTW_COUNTRY_US); // 2.4G only //wifi_change_channel_plan(0x25); // Support 2.4G and 5G, ex: 0x25 = 2G_FCC1, 5G_FCC1 } //----------------------------------------------------------------------------// int wifi_rf_on(void) { int ret; ret = rltk_wlan_rf_on(); return ret; } //----------------------------------------------------------------------------// int wifi_rf_off(void) { int ret; ret = rltk_wlan_rf_off(); return ret; } //----------------------------------------------------------------------------// int wifi_on(rtw_mode_t mode) { int ret = 1; int timeout = 20; int idx; int devnum = 1; static int event_init = 0; device_mutex_lock(RT_DEV_LOCK_WLAN); if(rltk_wlan_running(WLAN0_IDX)) { RTW_API_INFO("\n\rWIFI is already running"); device_mutex_unlock(RT_DEV_LOCK_WLAN); return 1; } if(event_init == 0){ init_event_callback_list(); event_init = 1; } wifi_mode = mode; if(mode == RTW_MODE_STA_AP) devnum = 2; // set wifi mib wifi_set_mib(); RTW_API_INFO("\n\rInitializing WIFI ..."); for(idx=0;idx<devnum;idx++){ ret = rltk_wlan_init(idx, mode); if(ret <0){ wifi_mode = RTW_MODE_NONE; device_mutex_unlock(RT_DEV_LOCK_WLAN); return ret; } } for(idx=0;idx<devnum;idx++){ ret = rltk_wlan_start(idx); if(ret == 0) _wifi_is_on = 1; if(ret <0){ RTW_API_INFO("\n\rERROR: Start WIFI Failed!"); rltk_wlan_deinit(); wifi_mode = RTW_MODE_NONE; device_mutex_unlock(RT_DEV_LOCK_WLAN); return ret; } } device_mutex_unlock(RT_DEV_LOCK_WLAN); while(1) { if(rltk_wlan_running(devnum-1)) { RTW_API_INFO("\n\rWIFI initialized\n"); wifi_set_country_code(); break; } if(timeout == 0) { RTW_API_INFO("\n\rERROR: Init WIFI timeout!"); break; } rtw_msleep_os(1000); timeout --; } #if CONFIG_LWIP_LAYER #if defined(CONFIG_MBED_ENABLED) || defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO #else netif_set_up(&xnetif[0]); if(mode == RTW_MODE_AP) netif_set_link_up(&xnetif[0]); else if(mode == RTW_MODE_STA_AP) { netif_set_up(&xnetif[1]); netif_set_link_up(&xnetif[1]); } #endif #endif #if CONFIG_INIC_EN inic_start(); #endif return ret; } int wifi_off(void) { int ret = 0; int timeout = 20; if((rltk_wlan_running(WLAN0_IDX) == 0) && (rltk_wlan_running(WLAN1_IDX) == 0)) { RTW_API_INFO("\n\rWIFI is not running"); return 0; } #if CONFIG_LWIP_LAYER #if defined(CONFIG_MBED_ENABLED) || defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO #else dhcps_deinit(); LwIP_DHCP(0, DHCP_STOP); netif_set_down(&xnetif[0]); netif_set_down(&xnetif[1]); #endif #endif #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP if((wifi_mode == RTW_MODE_AP) || (wifi_mode == RTW_MODE_STA_AP)) wpas_wps_deinit(); #endif RTW_API_INFO("\n\rDeinitializing WIFI ..."); device_mutex_lock(RT_DEV_LOCK_WLAN); rltk_wlan_deinit(); _wifi_is_on = 0; device_mutex_unlock(RT_DEV_LOCK_WLAN); while(1) { if((rltk_wlan_running(WLAN0_IDX) == 0) && (rltk_wlan_running(WLAN1_IDX) == 0)) { RTW_API_INFO("\n\rWIFI deinitialized"); break; } if(timeout == 0) { RTW_API_INFO("\n\rERROR: Deinit WIFI timeout!"); break; } rtw_msleep_os(1000); timeout --; } wifi_mode = RTW_MODE_NONE; #if CONFIG_INIC_EN inic_stop(); #endif return ret; } int wifi_off_fastly(void) { #if CONFIG_LWIP_LAYER #if defined(CONFIG_MBED_ENABLED) || defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO #else dhcps_deinit(); LwIP_DHCP(0, DHCP_STOP); #endif #endif //RTW_API_INFO("\n\rDeinitializing WIFI ..."); device_mutex_lock(RT_DEV_LOCK_WLAN); rltk_wlan_deinit_fastly(); device_mutex_unlock(RT_DEV_LOCK_WLAN); return 0; } int wifi_set_mode(rtw_mode_t mode) { int ret = 0; #ifdef CONFIG_WLAN_SWITCH_MODE rtw_mode_t curr_mode, next_mode; #if defined(CONFIG_AUTO_RECONNECT) && CONFIG_AUTO_RECONNECT u8 autoreconnect_mode; #endif #endif if((rltk_wlan_running(WLAN0_IDX) == 0) && (rltk_wlan_running(WLAN1_IDX) == 0)) { RTW_API_INFO("\n\r[%s] WIFI is not running",__FUNCTION__); return -1; } #ifdef CONFIG_WLAN_SWITCH_MODE #if defined(CONFIG_AUTO_RECONNECT) && CONFIG_AUTO_RECONNECT wifi_get_autoreconnect(&autoreconnect_mode); if(autoreconnect_mode != RTW_AUTORECONNECT_DISABLE){ wifi_set_autoreconnect(RTW_AUTORECONNECT_DISABLE); // if set to AP mode, delay until the autoconnect task is finished if(mode == RTW_MODE_AP){ while(param_indicator != NULL){ rtw_msleep_os(2); } } } #endif curr_mode = wifi_mode; next_mode = mode; ret = rltk_set_mode_prehandle(curr_mode, next_mode, WLAN0_NAME); if(ret < 0) goto Exit; #endif if((wifi_mode == RTW_MODE_STA) && (mode == RTW_MODE_AP)){ RTW_API_INFO("\n\r[%s] WIFI Mode Change: STA-->AP",__FUNCTION__); wifi_disconnect(); //must add this delay, because this API may have higher priority, wifi_disconnect will rely RTW_CMD task, may not be excuted immediately. rtw_msleep_os(50); #if CONFIG_LWIP_LAYER netif_set_link_up(&xnetif[0]); #endif wifi_mode = mode; #ifdef CONFIG_PMKSA_CACHING wifi_set_pmk_cache_enable(0); #endif }else if((wifi_mode == RTW_MODE_AP) && (mode ==RTW_MODE_STA)){ RTW_API_INFO("\n\r[%s] WIFI Mode Change: AP-->STA",__FUNCTION__); ret = wext_set_mode(WLAN0_NAME, IW_MODE_INFRA); if(ret < 0) goto Exit; rtw_msleep_os(50); #if CONFIG_LWIP_LAYER netif_set_link_down(&xnetif[0]); #endif wifi_mode = mode; #ifdef CONFIG_PMKSA_CACHING wifi_set_pmk_cache_enable(1); #endif }else if ((wifi_mode == RTW_MODE_AP) && (mode == RTW_MODE_AP)){ RTW_API_INFO("\n\rWIFI Mode Change: AP-->AP"); ret = wext_set_mode(WLAN0_NAME, IW_MODE_INFRA); if(ret < 0) goto Exit; rtw_msleep_os(50); }else if ((wifi_mode == RTW_MODE_STA) && (mode == RTW_MODE_STA)){ RTW_API_INFO("\n\rWIFI Mode No Need To Change: STA -->STA"); }else if ((wifi_mode == RTW_MODE_STA) && (mode == RTW_MODE_PROMISC)){ RTW_API_INFO("\n\rWIFI Mode Change: STA-->PROMISC"); unsigned char ssid[33]; if(wext_get_ssid(WLAN0_NAME, ssid) > 0) wifi_disconnect(); }else if ((wifi_mode == RTW_MODE_AP) && (mode == RTW_MODE_PROMISC)){ RTW_API_INFO("\n\rWIFI Mode Change: AP-->PROMISC");//Same as AP--> STA ret = wext_set_mode(WLAN0_NAME, IW_MODE_INFRA); if(ret < 0) goto Exit; rtw_msleep_os(50); #if CONFIG_LWIP_LAYER netif_set_link_down(&xnetif[0]); #endif wifi_mode = mode; }else{ RTW_API_INFO("\n\rWIFI Mode Change: not support"); goto Exit; } #ifdef CONFIG_WLAN_SWITCH_MODE ret = rltk_set_mode_posthandle(curr_mode, next_mode, WLAN0_NAME); if(ret < 0) goto Exit; #if defined(CONFIG_AUTO_RECONNECT) && CONFIG_AUTO_RECONNECT /* enable auto reconnect */ if(autoreconnect_mode != RTW_AUTORECONNECT_DISABLE){ wifi_set_autoreconnect(autoreconnect_mode); } #endif #endif return 0; Exit: #ifdef CONFIG_WLAN_SWITCH_MODE #if defined(CONFIG_AUTO_RECONNECT) && CONFIG_AUTO_RECONNECT /* enable auto reconnect */ if(autoreconnect_mode != RTW_AUTORECONNECT_DISABLE){ wifi_set_autoreconnect(autoreconnect_mode); } #endif #endif return -1; } int wifi_set_power_mode(unsigned char ips_mode, unsigned char lps_mode) { return wext_enable_powersave(WLAN0_NAME, ips_mode, lps_mode); } int wifi_set_tdma_param(unsigned char slot_period, unsigned char rfon_period_len_1, unsigned char rfon_period_len_2, unsigned char rfon_period_len_3) { return wext_set_tdma_param(WLAN0_NAME, slot_period, rfon_period_len_1, rfon_period_len_2, rfon_period_len_3); } int wifi_set_lps_dtim(unsigned char dtim) { return wext_set_lps_dtim(WLAN0_NAME, dtim); } int wifi_get_lps_dtim(unsigned char *dtim) { return wext_get_lps_dtim(WLAN0_NAME, dtim); } // mode == 0: packet count, 1: enter directly, 2: tp threshold (default) int wifi_set_lps_thresh(rtw_lps_thresh_t mode) { return wext_set_lps_thresh(WLAN0_NAME, mode); } int wifi_set_beacon_mode(int mode) { return wext_set_beacon_mode(WLAN0_NAME, mode); } int wifi_set_lps_level(unsigned char lps_level) { return wext_set_lps_level(WLAN0_NAME, lps_level); } #ifdef LONG_PERIOD_TICKLESS int wifi_set_lps_smartps(unsigned char smartps) { return wext_set_lps_smartps(WLAN0_NAME, smartps); } #endif //----------------------------------------------------------------------------// static void wifi_ap_sta_assoc_hdl( char* buf, int buf_len, int flags, void* userdata) { /* To avoid gcc warnings */ ( void ) buf; ( void ) buf_len; ( void ) flags; ( void ) userdata; //USER TODO } static void wifi_ap_sta_disassoc_hdl( char* buf, int buf_len, int flags, void* userdata) { /* To avoid gcc warnings */ ( void ) buf; ( void ) buf_len; ( void ) flags; ( void ) userdata; //USER TODO } static void wifi_softap_start_hdl(char* buf, int buf_len, int flags, void* userdata) { /* To avoid gcc warnings */ ( void ) buf; ( void ) buf_len; ( void ) flags; ( void ) userdata; } static void wifi_softap_stop_hdl(char* buf, int buf_len, int flags, void* userdata) { /* To avoid gcc warnings */ ( void ) buf; ( void ) buf_len; ( void ) flags; ( void ) userdata; } int wifi_get_last_error(void) { return error_flag; } #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP int wpas_wps_init(const char* ifname); #endif int wifi_set_mfp_support(unsigned char value) { return wext_set_mfp_support(WLAN0_NAME, value); } #ifdef CONFIG_SAE_SUPPORT int wifi_set_group_id(unsigned char value) { return wext_set_group_id(WLAN0_NAME, value); } #endif #ifdef CONFIG_PMKSA_CACHING int wifi_set_pmk_cache_enable(unsigned char value) { return wext_set_pmk_cache_enable(WLAN0_NAME, value); } #endif int wifi_start_ap( char *ssid, rtw_security_t security_type, char *password, int ssid_len, int password_len, int channel) { const char *ifname = WLAN0_NAME; int ret = 0; if((ssid_len < 0)|| (ssid_len > 32)){ printf("Error: SSID should be 0-32 characters\r\n"); ret = -1; goto exit; } if(security_type != RTW_SECURITY_OPEN){ if(password == NULL){ if(security_type != RTW_SECURITY_OPEN){ printf("Error: password is NULL\n\r"); ret = RTW_INVALID_KEY; goto exit; } } if(password_len <= RTW_MAX_PSK_LEN && password_len >= RTW_MIN_PSK_LEN){ if(password_len == RTW_MAX_PSK_LEN){//password_len=64 means pre-shared key, pre-shared key should be 64 hex characters unsigned char i,j; for(i = 0;i < 64;i++){ j = password[i]; if(!((j >='0' && j<='9') || (j >='A' && j<='F') || (j >='a' && j<='f'))){ printf("Error: password should be 64 hex characters or 8-63 ASCII characters\n\r"); ret = RTW_INVALID_KEY; goto exit; } } } #ifdef CONFIG_FPGA }else if((password_len == 5)&&(security_type == RTW_SECURITY_WEP_PSK)){ #endif }else{ printf("Error: password should be 64 hex characters or 8-63 ASCII characters\n\r"); ret = RTW_INVALID_KEY; goto exit; } } #if defined (CONFIG_AP_MODE) && defined (CONFIG_NATIVEAP_MLME) if(wifi_mode == RTW_MODE_STA_AP) { ifname = WLAN1_NAME; } if(is_promisc_enabled()) promisc_set(0, NULL, 0); wifi_reg_event_handler(WIFI_EVENT_STA_ASSOC, wifi_ap_sta_assoc_hdl, NULL); wifi_reg_event_handler(WIFI_EVENT_STA_DISASSOC, wifi_ap_sta_disassoc_hdl, NULL); wifi_reg_event_handler(WIFI_EVENT_SOFTAP_START, wifi_softap_start_hdl, NULL); wifi_reg_event_handler(WIFI_EVENT_SOFTAP_STOP, wifi_softap_stop_hdl, NULL); ret = wext_set_mode(ifname, IW_MODE_MASTER); if(ret < 0) goto exit; ret = wext_set_channel(ifname, channel); //Set channel before starting ap if(ret < 0) goto exit; switch(security_type) { case RTW_SECURITY_OPEN: break; #if defined(CONFIG_FPGA) && CONFIG_FPGA case RTW_SECURITY_WEP_PSK: ret = wext_set_auth_param(ifname, IW_AUTH_80211_AUTH_ALG, IW_AUTH_ALG_OPEN_SYSTEM); if(ret == 0) ret = wext_set_key_ext(ifname, IW_ENCODE_ALG_WEP, NULL, 0, 1, 0, 0, (u8*)password, password_len); break; case RTW_SECURITY_WPA2_TKIP_PSK: ret = wext_set_auth_param(ifname, IW_AUTH_80211_AUTH_ALG, IW_AUTH_ALG_OPEN_SYSTEM); if(ret == 0) ret = wext_set_key_ext(ifname, IW_ENCODE_ALG_TKIP, NULL, 0, 0, 0, 0, NULL, 0); if(ret == 0) ret = wext_set_passphrase(ifname, (u8*)password, password_len); break; #endif case RTW_SECURITY_WPA2_AES_PSK: ret = wext_set_auth_param(ifname, IW_AUTH_80211_AUTH_ALG, IW_AUTH_ALG_OPEN_SYSTEM); if(ret == 0) ret = wext_set_key_ext(ifname, IW_ENCODE_ALG_CCMP, NULL, 0, 0, 0, 0, NULL, 0); if(ret == 0) ret = wext_set_passphrase(ifname, (u8*)password, password_len); break; #ifdef CONFIG_IEEE80211W case RTW_SECURITY_WPA2_AES_CMAC: ret = wext_set_auth_param(ifname, IW_AUTH_80211_AUTH_ALG, IW_AUTH_ALG_OPEN_SYSTEM); if(ret == 0) ret = wext_set_key_ext(ifname, IW_ENCODE_ALG_AES_CMAC, NULL, 0, 0, 0, 0, NULL, 0); if(ret == 0) ret = wext_set_passphrase(ifname, (u8*)password, password_len); break; #endif default: ret = -1; RTW_API_INFO("\n\rWIFICONF: security type is not supported"); break; } if(ret < 0) goto exit; ret = wext_set_ap_ssid(ifname, (u8*)ssid, ssid_len); #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP wpas_wps_init(ifname); #endif #if CONFIG_LWIP_LAYER #if defined(CONFIG_MBED_ENABLED) || defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO #else if(wifi_mode == RTW_MODE_STA_AP) netif_set_link_up(&xnetif[1]); else netif_set_link_up(&xnetif[0]); #endif #endif exit: #endif return ret; } extern int set_hidden_ssid(const char * ifname, u8 value); int wifi_start_ap_with_hidden_ssid( char *ssid, rtw_security_t security_type, char *password, int ssid_len, int password_len, int channel) { const char *ifname = WLAN0_NAME; int ret = 0; if((ssid_len < 0)|| (ssid_len > 32)){ printf("Error: SSID should be 0-32 characters\r\n"); ret = -1; goto exit; } if(security_type != RTW_SECURITY_OPEN){ if(password == NULL){ if(security_type != RTW_SECURITY_OPEN){ printf("Error: password is NULL\n\r"); ret = RTW_INVALID_KEY; goto exit; } } if(password_len <= RTW_MAX_PSK_LEN && password_len >= RTW_MIN_PSK_LEN){ if(password_len == RTW_MAX_PSK_LEN){//password_len=64 means pre-shared key, pre-shared key should be 64 hex characters unsigned char i,j; for(i = 0;i < 64;i++){ j = password[i]; if(!((j >='0' && j<='9') || (j >='A' && j<='F') || (j >='a' && j<='f'))){ printf("Error: password should be 64 hex characters or 8-63 ASCII characters\n\r"); ret = RTW_INVALID_KEY; goto exit; } } } #ifdef CONFIG_FPGA }else if((password_len == 5)&&(security_type == RTW_SECURITY_WEP_PSK)){ #endif }else{ printf("Error: password should be 64 hex characters or 8-63 ASCII characters\n\r"); ret = RTW_INVALID_KEY; goto exit; } } #if defined (CONFIG_AP_MODE) && defined (CONFIG_NATIVEAP_MLME) if(wifi_mode == RTW_MODE_STA_AP) { ifname = WLAN1_NAME; } if(is_promisc_enabled()) promisc_set(0, NULL, 0); wifi_reg_event_handler(WIFI_EVENT_STA_ASSOC, wifi_ap_sta_assoc_hdl, NULL); wifi_reg_event_handler(WIFI_EVENT_STA_DISASSOC, wifi_ap_sta_disassoc_hdl, NULL); wifi_reg_event_handler(WIFI_EVENT_SOFTAP_START, wifi_softap_start_hdl, NULL); wifi_reg_event_handler(WIFI_EVENT_SOFTAP_STOP, wifi_softap_stop_hdl, NULL); ret = wext_set_mode(ifname, IW_MODE_MASTER); if(ret < 0) goto exit; ret = wext_set_channel(ifname, channel); //Set channel before starting ap if(ret < 0) goto exit; switch(security_type) { case RTW_SECURITY_OPEN: break; case RTW_SECURITY_WPA2_AES_PSK: ret = wext_set_auth_param(ifname, IW_AUTH_80211_AUTH_ALG, IW_AUTH_ALG_OPEN_SYSTEM); if(ret == 0) ret = wext_set_key_ext(ifname, IW_ENCODE_ALG_CCMP, NULL, 0, 0, 0, 0, NULL, 0); if(ret == 0) ret = wext_set_passphrase(ifname, (u8*)password, password_len); break; default: ret = -1; RTW_API_INFO("\n\rWIFICONF: security type is not supported"); break; } if(ret < 0) goto exit; ret = set_hidden_ssid(ifname, 1); if(ret < 0) goto exit; ret = wext_set_ap_ssid(ifname, (u8*)ssid, ssid_len); #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP wpas_wps_init(ifname); #endif exit: #endif return ret; } void wifi_scan_each_report_hdl( char* buf, int buf_len, int flags, void* userdata) { /* To avoid gcc warnings */ ( void ) buf_len; ( void ) flags; ( void ) userdata; int i =0; int j =0; int insert_pos = 0; rtw_scan_result_t** result_ptr = (rtw_scan_result_t**)buf; rtw_scan_result_t* temp = NULL; for(i=0; i<scan_result_handler_ptr.scan_cnt; i++){ if(CMP_MAC(scan_result_handler_ptr.pap_details[i]->BSSID.octet, (*result_ptr)->BSSID.octet)){ if((*result_ptr)->signal_strength > scan_result_handler_ptr.pap_details[i]->signal_strength){ temp = scan_result_handler_ptr.pap_details[i]; for(j = i-1; j >= 0; j--){ if(scan_result_handler_ptr.pap_details[j]->signal_strength >= (*result_ptr)->signal_strength) break; else scan_result_handler_ptr.pap_details[j+1] = scan_result_handler_ptr.pap_details[j]; } scan_result_handler_ptr.pap_details[j+1] = temp; scan_result_handler_ptr.pap_details[j+1]->signal_strength = (*result_ptr)->signal_strength; } memset(*result_ptr, 0, sizeof(rtw_scan_result_t)); return; } } //scan_result_handler_ptr.scan_cnt++; if(scan_result_handler_ptr.scan_cnt >= scan_result_handler_ptr.max_ap_size){ scan_result_handler_ptr.scan_cnt = scan_result_handler_ptr.max_ap_size; if((*result_ptr)->signal_strength > scan_result_handler_ptr.pap_details[scan_result_handler_ptr.max_ap_size-1]->signal_strength){ rtw_memcpy(scan_result_handler_ptr.pap_details[scan_result_handler_ptr.max_ap_size-1], *result_ptr, sizeof(rtw_scan_result_t)); temp = scan_result_handler_ptr.pap_details[scan_result_handler_ptr.max_ap_size -1]; scan_result_handler_ptr.scan_cnt = scan_result_handler_ptr.max_ap_size -1; }else return; }else{ rtw_memcpy(&scan_result_handler_ptr.ap_details[scan_result_handler_ptr.scan_cnt], *result_ptr, sizeof(rtw_scan_result_t)); } for(i=0; i< scan_result_handler_ptr.scan_cnt; i++){ if((*result_ptr)->signal_strength > scan_result_handler_ptr.pap_details[i]->signal_strength) break; } insert_pos = i; for(i = scan_result_handler_ptr.scan_cnt; i>insert_pos; i--) scan_result_handler_ptr.pap_details[i] = scan_result_handler_ptr.pap_details[i-1]; if(temp != NULL) scan_result_handler_ptr.pap_details[insert_pos] = temp; else scan_result_handler_ptr.pap_details[insert_pos] = &scan_result_handler_ptr.ap_details[scan_result_handler_ptr.scan_cnt]; if(scan_result_handler_ptr.scan_cnt < scan_result_handler_ptr.max_ap_size) scan_result_handler_ptr.scan_cnt++; rtw_memset(*result_ptr, 0, sizeof(rtw_scan_result_t)); } void wifi_scan_done_hdl( char* buf, int buf_len, int flags, void* userdata) { /* To avoid gcc warnings */ ( void ) buf; ( void ) buf_len; ( void ) flags; ( void ) userdata; int i = 0; rtw_scan_handler_result_t scan_result_report; for(i=0; i<scan_result_handler_ptr.scan_cnt; i++){ rtw_memcpy(&scan_result_report.ap_details, scan_result_handler_ptr.pap_details[i], sizeof(rtw_scan_result_t)); scan_result_report.scan_complete = scan_result_handler_ptr.scan_complete; scan_result_report.user_data = scan_result_handler_ptr.user_data; (*scan_result_handler_ptr.gscan_result_handler)(&scan_result_report); } scan_result_handler_ptr.scan_complete = RTW_TRUE; scan_result_report.scan_complete = RTW_TRUE; scan_result_report.user_data = scan_result_handler_ptr.user_data; (*scan_result_handler_ptr.gscan_result_handler)(&scan_result_report); rtw_free(scan_result_handler_ptr.ap_details); rtw_free(scan_result_handler_ptr.pap_details); #if SCAN_USE_SEMAPHORE rtw_up_sema(&scan_result_handler_ptr.scan_semaphore); #else scan_result_handler_ptr.scan_running = 0; #endif wifi_unreg_event_handler(WIFI_EVENT_SCAN_RESULT_REPORT, wifi_scan_each_report_hdl); wifi_unreg_event_handler(WIFI_EVENT_SCAN_DONE, wifi_scan_done_hdl); return; } void wifi_scan_done_hdl_mcc( char* buf, int buf_len, int flags, void* userdata) { #if SCAN_USE_SEMAPHORE rtw_up_sema(&scan_result_handler_ptr.scan_semaphore); #else scan_result_handler_ptr.scan_running = 0; #endif return; } //int rtk_wifi_scan(char *buf, int buf_len, xSemaphoreHandle * semaphore) int wifi_scan(rtw_scan_type_t scan_type, rtw_bss_type_t bss_type, void* result_ptr) { int ret; scan_buf_arg * pscan_buf; u16 flags = scan_type | (bss_type << 8); if(result_ptr != NULL){ pscan_buf = (scan_buf_arg *)result_ptr; ret = wext_set_scan(WLAN0_NAME, (char*)pscan_buf->buf, pscan_buf->buf_len, flags); }else{ wifi_reg_event_handler(WIFI_EVENT_SCAN_RESULT_REPORT, wifi_scan_each_report_hdl, NULL); wifi_reg_event_handler(WIFI_EVENT_SCAN_DONE, wifi_scan_done_hdl, NULL); ret = wext_set_scan(WLAN0_NAME, NULL, 0, flags); } if(ret == 0) { if(result_ptr != NULL){ ret = wext_get_scan(WLAN0_NAME, pscan_buf->buf, pscan_buf->buf_len); } } else if(ret == -1){ if(result_ptr == NULL){ wifi_unreg_event_handler(WIFI_EVENT_SCAN_RESULT_REPORT, wifi_scan_each_report_hdl); wifi_unreg_event_handler(WIFI_EVENT_SCAN_DONE, wifi_scan_done_hdl); } } return ret; } int wifi_scan_networks_with_ssid(int (results_handler)(char*buf, int buflen, char *ssid, void *user_data), OUT void* user_data, IN int scan_buflen, IN char* ssid, IN int ssid_len) { int scan_cnt = 0, add_cnt = 0; scan_buf_arg scan_buf; int ret; scan_buf.buf_len = scan_buflen; scan_buf.buf = (char*)rtw_malloc(scan_buf.buf_len); if(!scan_buf.buf){ RTW_API_INFO("\n\rERROR: Can't malloc memory(%d)", scan_buf.buf_len); return RTW_NOMEM; } //set ssid memset(scan_buf.buf, 0, scan_buf.buf_len); memcpy(scan_buf.buf, &ssid_len, sizeof(int)); memcpy(scan_buf.buf+sizeof(int), ssid, ssid_len); //Scan channel if((scan_cnt = wifi_scan(RTW_SCAN_TYPE_ACTIVE, RTW_BSS_TYPE_ANY, &scan_buf)) < 0){ RTW_API_INFO("\n\rERROR: wifi scan failed"); ret = RTW_ERROR; }else{ if(NULL == results_handler) { int plen = 0; while(plen < scan_buf.buf_len){ int len, rssi, ssid_len, i, security_mode; int wps_password_id; char *mac, *ssid; //u8 *security_mode; RTW_API_INFO("\n\r"); // len len = (int)*(scan_buf.buf + plen); RTW_API_INFO("len = %d,\t", len); // check end if(len == 0) break; // mac mac = scan_buf.buf + plen + 1; RTW_API_INFO("mac = "); for(i=0; i<6; i++) RTW_API_INFO("%02x ", (u8)*(mac+i)); RTW_API_INFO(",\t"); // rssi rssi = *(int*)(scan_buf.buf + plen + 1 + 6); RTW_API_INFO(" rssi = %d,\t", rssi); // security_mode security_mode = (int)*(scan_buf.buf + plen + 1 + 6 + 4); switch (security_mode) { case IW_ENCODE_ALG_NONE: RTW_API_INFO("sec = open ,\t"); break; case IW_ENCODE_ALG_WEP: RTW_API_INFO("sec = wep ,\t"); break; case IW_ENCODE_ALG_CCMP: RTW_API_INFO("sec = wpa/wpa2,\t"); break; } // password id wps_password_id = (int)*(scan_buf.buf + plen + 1 + 6 + 4 + 1); RTW_API_INFO("wps password id = %d,\t", wps_password_id); RTW_API_INFO("channel = %d,\t", *(scan_buf.buf + plen + 1 + 6 + 4 + 1 + 1)); // ssid ssid_len = len - 1 - 6 - 4 - 1 - 1 - 1; ssid = scan_buf.buf + plen + 1 + 6 + 4 + 1 + 1 + 1; RTW_API_INFO("ssid = "); for(i=0; i<ssid_len; i++) RTW_API_INFO("%c", *(ssid+i)); plen += len; add_cnt++; } RTW_API_INFO("\n\rwifi_scan: add count = %d, scan count = %d", add_cnt, scan_cnt); } ret = RTW_SUCCESS; } if(results_handler) results_handler(scan_buf.buf, scan_buf.buf_len, ssid, user_data); if(scan_buf.buf) rtw_free(scan_buf.buf); return ret; } #define BUFLEN_LEN 1 #define MAC_LEN 6 #define RSSI_LEN 4 #define SECURITY_LEN 1 #define SECURITY_LEN_EXTENDED 4 #define WPS_ID_LEN 1 #define CHANNEL_LEN 1 #ifdef CONFIG_P2P_NEW #define P2P_ROLE_LEN 1 #define P2P_CHANNEL_LEN 1 #define P2P_ROLE_DISABLE 0 #define P2P_ROLE_DEVICE 1 #define P2P_ROLE_CLIENT 2 #define P2P_ROLE_GO 3 #endif int wifi_scan_networks_with_ssid_by_extended_security(int (results_handler)(char*buf, int buflen, char *ssid, void *user_data), OUT void* user_data, IN int scan_buflen, IN char* ssid, IN int ssid_len) { int scan_cnt = 0, add_cnt = 0; scan_buf_arg scan_buf; int ret; scan_buf.buf_len = scan_buflen; scan_buf.buf = (char*)rtw_malloc(scan_buf.buf_len); if(!scan_buf.buf){ RTW_API_INFO("\n\rERROR: Can't malloc memory(%d)", scan_buf.buf_len); return RTW_NOMEM; } rltk_wlan_enable_scan_with_ssid_by_extended_security(1); //set ssid memset(scan_buf.buf, 0, scan_buf.buf_len); memcpy(scan_buf.buf, &ssid_len, sizeof(int)); memcpy(scan_buf.buf+sizeof(int), ssid, ssid_len); //Scan channel if((scan_cnt = wifi_scan(RTW_SCAN_TYPE_ACTIVE, RTW_BSS_TYPE_ANY, &scan_buf)) < 0){ RTW_API_INFO("\n\rERROR: wifi scan failed"); ret = RTW_ERROR; }else{ if(NULL == results_handler) { int plen = 0; while(plen < scan_buf.buf_len){ int len, rssi, ssid_len, i, security_mode; int wps_password_id; char *mac, *ssid; #ifdef CONFIG_P2P_NEW int p2p_role, p2p_listen_channel; char *dev_name = NULL; int dev_name_len = 0; #endif RTW_API_INFO("\n\r"); // len len = (int)*(scan_buf.buf + plen); RTW_API_INFO("len = %d,\t", len); // check end if(len == 0) break; // mac mac = scan_buf.buf + plen + BUFLEN_LEN; RTW_API_INFO("mac = "); for(i=0; i<6; i++) RTW_API_INFO("%02x ", (u8)*(mac+i)); RTW_API_INFO(",\t"); // rssi rssi = *(int*)(scan_buf.buf + plen + BUFLEN_LEN + MAC_LEN); RTW_API_INFO(" rssi = %d,\t", rssi); // security_mode //get extended security flag is up, output detailed security infomation security_mode = *(int*)(scan_buf.buf + plen + BUFLEN_LEN + MAC_LEN + RSSI_LEN); switch (security_mode) { case RTW_SECURITY_OPEN: RTW_API_INFO("sec = RTW_SECURITY_OPEN ,\t"); break; case RTW_SECURITY_WEP_PSK: RTW_API_INFO("sec = RTW_SECURITY_WEP_PSK ,\t"); break; case RTW_SECURITY_WEP_SHARED: RTW_API_INFO("sec = RTW_SECURITY_WEP_SHARED,\t"); break; case RTW_SECURITY_WPA_TKIP_PSK: RTW_API_INFO("sec = RTW_SECURITY_WPA_TKIP_PSK,\t"); break; case RTW_SECURITY_WPA_AES_PSK: RTW_API_INFO("sec = RTW_SECURITY_WPA_AES_PSK,\t"); break; case RTW_SECURITY_WPA_MIXED_PSK: RTW_API_INFO("sec = RTW_SECURITY_WPA_MIXED_PSK,\t"); break; case RTW_SECURITY_WPA2_AES_PSK: RTW_API_INFO("sec = RTW_SECURITY_WPA2_AES_PSK,\t"); break; case RTW_SECURITY_WPA2_TKIP_PSK: RTW_API_INFO("sec = RTW_SECURITY_WPA2_TKIP_PSK,\t"); break; case RTW_SECURITY_WPA2_MIXED_PSK: RTW_API_INFO("sec = RTW_SECURITY_WPA2_MIXED_PSK,\t"); break; case RTW_SECURITY_WPA_WPA2_TKIP_PSK: RTW_API_INFO("sec = RTW_SECURITY_WPA_WPA2_TKIP_PSK,\t"); break; case RTW_SECURITY_WPA_WPA2_AES_PSK: RTW_API_INFO("sec = RTW_SECURITY_WPA_WPA2_AES_PSK,\t"); break; case RTW_SECURITY_WPA_WPA2_MIXED_PSK: RTW_API_INFO("sec = RTW_SECURITY_WPA_WPA2_MIXED_PSK,\t"); break; case RTW_SECURITY_WPA2_AES_CMAC: RTW_API_INFO("sec = RTW_SECURITY_WPA2_AES_CMAC,\t"); break; case RTW_SECURITY_WPA2_ENTERPRISE: RTW_API_INFO("sec = RTW_SECURITY_WPA2_ENTERPRISE,\t"); break; case RTW_SECURITY_WPA_WPA2_ENTERPRISE: RTW_API_INFO("sec = RTW_SECURITY_WPA_WPA2_ENTERPRISE,\t"); break; case RTW_SECURITY_WPS_OPEN: RTW_API_INFO("sec = RTW_SECURITY_WPS_OPEN,\t"); break; case RTW_SECURITY_WPS_SECURE: RTW_API_INFO("sec = RTW_SECURITY_WPS_SECURE,\t"); break; case RTW_SECURITY_WPA3_AES_PSK: RTW_API_INFO("sec = RTW_SECURITY_WPA3_AES_PSK,\t"); break; } // password id wps_password_id = (int)*(scan_buf.buf + plen + BUFLEN_LEN + MAC_LEN + RSSI_LEN + SECURITY_LEN_EXTENDED); RTW_API_INFO("wps password id = %d,\t", wps_password_id); #ifdef CONFIG_P2P_NEW if(wifi_mode == RTW_MODE_P2P){ p2p_role = (int)*(scan_buf.buf + plen + BUFLEN_LEN + MAC_LEN + RSSI_LEN + SECURITY_LEN_EXTENDED + WPS_ID_LEN); switch(p2p_role){ case P2P_ROLE_DISABLE: RTW_API_INFO("p2p role = P2P_ROLE_DISABLE,\t"); break; case P2P_ROLE_DEVICE: RTW_API_INFO("p2p role = P2P_ROLE_DEVICE,\t"); break; case P2P_ROLE_CLIENT: RTW_API_INFO("p2p role = P2P_ROLE_CLIENT,\t"); break; case P2P_ROLE_GO: RTW_API_INFO("p2p role = P2P_ROLE_GO,\t"); break; } p2p_listen_channel = (int)*(scan_buf.buf + plen + BUFLEN_LEN + MAC_LEN + RSSI_LEN + SECURITY_LEN_EXTENDED + WPS_ID_LEN + P2P_ROLE_LEN); RTW_API_INFO("p2p listen channel = %d,\t", p2p_listen_channel); if(p2p_role == P2P_ROLE_DEVICE){ //device name dev_name_len = len - BUFLEN_LEN - MAC_LEN - RSSI_LEN - SECURITY_LEN_EXTENDED - WPS_ID_LEN - P2P_ROLE_LEN - P2P_CHANNEL_LEN; dev_name = scan_buf.buf + plen + BUFLEN_LEN + MAC_LEN + RSSI_LEN + SECURITY_LEN_EXTENDED + P2P_ROLE_LEN + P2P_CHANNEL_LEN; RTW_API_INFO("dev_name = "); for(i=0; i<dev_name_len; i++) RTW_API_INFO("%c", *(dev_name+i)); }else{ //ssid ssid_len = len - BUFLEN_LEN - MAC_LEN - RSSI_LEN - SECURITY_LEN_EXTENDED - WPS_ID_LEN - P2P_ROLE_LEN - P2P_CHANNEL_LEN; ssid = scan_buf.buf + plen + BUFLEN_LEN + MAC_LEN + RSSI_LEN + SECURITY_LEN_EXTENDED + P2P_ROLE_LEN + P2P_CHANNEL_LEN; RTW_API_INFO("ssid = "); for(i=0; i<ssid_len; i++) RTW_API_INFO("%c", *(ssid+i)); } } else #endif //CONFIG_P2P_NEW { RTW_API_INFO("channel = %d,\t", *(scan_buf.buf + plen + BUFLEN_LEN + MAC_LEN + RSSI_LEN + SECURITY_LEN_EXTENDED + WPS_ID_LEN)); // ssid ssid_len = len - BUFLEN_LEN - MAC_LEN - RSSI_LEN - SECURITY_LEN_EXTENDED - WPS_ID_LEN - CHANNEL_LEN; ssid = scan_buf.buf + plen + BUFLEN_LEN + MAC_LEN + RSSI_LEN + SECURITY_LEN_EXTENDED + WPS_ID_LEN + CHANNEL_LEN; RTW_API_INFO("ssid = "); for(i=0; i<ssid_len; i++) RTW_API_INFO("%c", *(ssid+i)); } plen += len; add_cnt++; } RTW_API_INFO("\n\rwifi_scan: add count = %d, scan count = %d", add_cnt, scan_cnt); } ret = RTW_SUCCESS; } if(results_handler) results_handler(scan_buf.buf, scan_buf.buf_len, ssid, user_data); if(scan_buf.buf) rtw_free(scan_buf.buf); return ret; } int wifi_scan_networks(rtw_scan_result_handler_t results_handler, void* user_data) { unsigned int max_ap_size = 64; /* lock 2s to forbid suspend under scan */ rtw_wakelock_timeout(2*1000); #if SCAN_USE_SEMAPHORE rtw_bool_t result; if(NULL == scan_result_handler_ptr.scan_semaphore) rtw_init_sema(&scan_result_handler_ptr.scan_semaphore, 1); scan_result_handler_ptr.scan_start_time = rtw_get_current_time(); /* Initialise the semaphore that will prevent simultaneous access - cannot be a mutex, since * we don't want to allow the same thread to start a new scan */ result = (rtw_bool_t)rtw_down_timeout_sema(&scan_result_handler_ptr.scan_semaphore, SCAN_LONGEST_WAIT_TIME); if ( result != RTW_TRUE ) { /* Return error result, but set the semaphore to work the next time */ rtw_up_sema(&scan_result_handler_ptr.scan_semaphore); return RTW_TIMEOUT; } #else if(scan_result_handler_ptr.scan_running){ int count = 100; while(scan_result_handler_ptr.scan_running && count > 0) { rtw_msleep_os(20); count --; } if(count == 0){ RTW_API_INFO("\n\r[%d]WiFi: Scan is running. Wait 2s timeout.", rtw_get_current_time()); return RTW_TIMEOUT; } } scan_result_handler_ptr.scan_start_time = rtw_get_current_time(); scan_result_handler_ptr.scan_running = 1; #endif scan_result_handler_ptr.gscan_result_handler = results_handler; scan_result_handler_ptr.max_ap_size = max_ap_size; scan_result_handler_ptr.ap_details = (rtw_scan_result_t*)rtw_zmalloc(max_ap_size*sizeof(rtw_scan_result_t)); if(scan_result_handler_ptr.ap_details == NULL){ goto err_exit; } rtw_memset(scan_result_handler_ptr.ap_details, 0, max_ap_size*sizeof(rtw_scan_result_t)); scan_result_handler_ptr.pap_details = (rtw_scan_result_t**)rtw_zmalloc(max_ap_size*sizeof(rtw_scan_result_t*)); if(scan_result_handler_ptr.pap_details == NULL) goto error2_with_result_ptr; rtw_memset(scan_result_handler_ptr.pap_details, 0, max_ap_size*sizeof(rtw_scan_result_t*)); scan_result_handler_ptr.scan_cnt = 0; scan_result_handler_ptr.scan_complete = RTW_FALSE; scan_result_handler_ptr.user_data = user_data; if (wifi_scan( RTW_SCAN_COMMAMD<<4 | RTW_SCAN_TYPE_ACTIVE, RTW_BSS_TYPE_ANY, NULL) != RTW_SUCCESS) { goto error1_with_result_ptr; } return RTW_SUCCESS; error1_with_result_ptr: rtw_free((u8*)scan_result_handler_ptr.pap_details); scan_result_handler_ptr.pap_details = NULL; error2_with_result_ptr: rtw_free((u8*)scan_result_handler_ptr.ap_details); scan_result_handler_ptr.ap_details = NULL; err_exit: rtw_memset((void *)&scan_result_handler_ptr, 0, sizeof(scan_result_handler_ptr)); return RTW_ERROR; } /* * SCAN_DONE_INTERVAL is the interval between each channel scan done, * to make AP mode can send beacon during this interval. * It is to fix client disconnection when doing wifi scan in AP/concurrent mode. * User can fine tune SCAN_DONE_INTERVAL value. */ #define SCAN_DONE_INTERVAL 100 //100ms /* * Noted : the scan channel list needs to be modified depending on user's channel plan. */ #define SCAN_CHANNEL_NUM 13+25 //2.4GHz + 5GHz u8 scan_channel_list[SCAN_CHANNEL_NUM] = {1,2,3,4,5,6,7,8,9,10,11,12,13, 36,40,44,48,52,56,60,64,100,104,108,112,116,120,124,128,132,136,140,144,149,153,157,161,165}; int wifi_scan_networks_mcc(rtw_scan_result_handler_t results_handler, void* user_data) { unsigned int max_ap_size = 64; u8 channel_index; u8 pscan_config; int ret; /* lock 2s to forbid suspend under scan */ rtw_wakelock_timeout(2*1000); for(channel_index=0;channel_index<SCAN_CHANNEL_NUM;channel_index++){ #if SCAN_USE_SEMAPHORE rtw_bool_t result; if(NULL == scan_result_handler_ptr.scan_semaphore) rtw_init_sema(&scan_result_handler_ptr.scan_semaphore, 1); scan_result_handler_ptr.scan_start_time = rtw_get_current_time(); /* Initialise the semaphore that will prevent simultaneous access - cannot be a mutex, since * we don't want to allow the same thread to start a new scan */ result = (rtw_bool_t)rtw_down_timeout_sema(&scan_result_handler_ptr.scan_semaphore, SCAN_LONGEST_WAIT_TIME); if ( result != RTW_TRUE ) { /* Return error result, but set the semaphore to work the next time */ rtw_up_sema(&scan_result_handler_ptr.scan_semaphore); return RTW_TIMEOUT; } #else if(scan_result_handler_ptr.scan_running){ int count = 200; while(scan_result_handler_ptr.scan_running && count > 0) { rtw_msleep_os(5); count --; } if(count == 0){ printf("\n\r[%d]WiFi: Scan is running. Wait 1s timeout.", rtw_get_current_time()); return RTW_TIMEOUT; } } rtw_msleep_os(SCAN_DONE_INTERVAL); scan_result_handler_ptr.scan_running = 1; scan_result_handler_ptr.scan_start_time = rtw_get_current_time(); #endif if(channel_index == 0){ scan_result_handler_ptr.gscan_result_handler = results_handler; scan_result_handler_ptr.max_ap_size = max_ap_size; scan_result_handler_ptr.ap_details = (rtw_scan_result_t*)rtw_zmalloc(max_ap_size*sizeof(rtw_scan_result_t)); if(scan_result_handler_ptr.ap_details == NULL){ goto err_exit; } rtw_memset(scan_result_handler_ptr.ap_details, 0, max_ap_size*sizeof(rtw_scan_result_t)); scan_result_handler_ptr.pap_details = (rtw_scan_result_t**)rtw_zmalloc(max_ap_size*sizeof(rtw_scan_result_t*)); if(scan_result_handler_ptr.pap_details == NULL) goto error2_with_result_ptr; rtw_memset(scan_result_handler_ptr.pap_details, 0, max_ap_size*sizeof(rtw_scan_result_t*)); scan_result_handler_ptr.scan_cnt = 0; scan_result_handler_ptr.scan_complete = RTW_FALSE; scan_result_handler_ptr.user_data = user_data; wifi_reg_event_handler(WIFI_EVENT_SCAN_RESULT_REPORT, wifi_scan_each_report_hdl, NULL); wifi_reg_event_handler(WIFI_EVENT_SCAN_DONE, wifi_scan_done_hdl_mcc, NULL); } if(channel_index == SCAN_CHANNEL_NUM-1){ wifi_unreg_event_handler(WIFI_EVENT_SCAN_DONE, wifi_scan_done_hdl_mcc); wifi_reg_event_handler(WIFI_EVENT_SCAN_DONE, wifi_scan_done_hdl, NULL); } pscan_config = PSCAN_ENABLE; //set partial scan for entering to listen beacon quickly ret = wifi_set_pscan_chan(&scan_channel_list[channel_index], &pscan_config, 1); if(ret < 0){ #if SCAN_USE_SEMAPHORE rtw_up_sema(&scan_result_handler_ptr.scan_semaphore); #else scan_result_handler_ptr.scan_running = 0; #endif if(channel_index == SCAN_CHANNEL_NUM-1) { wifi_scan_done_hdl(NULL, 0, 0, NULL); } continue; } if ( wext_set_scan(WLAN0_NAME, NULL, 0, (RTW_SCAN_COMMAMD<<4 | RTW_SCAN_TYPE_ACTIVE | (RTW_BSS_TYPE_ANY << 8))) != RTW_SUCCESS) { goto error1_with_result_ptr; } } return RTW_SUCCESS; error1_with_result_ptr: wifi_unreg_event_handler(WIFI_EVENT_SCAN_DONE, wifi_scan_done_hdl_mcc); wifi_unreg_event_handler(WIFI_EVENT_SCAN_RESULT_REPORT, wifi_scan_each_report_hdl); wifi_unreg_event_handler(WIFI_EVENT_SCAN_DONE, wifi_scan_done_hdl); rtw_free((u8*)scan_result_handler_ptr.pap_details); scan_result_handler_ptr.pap_details = NULL; error2_with_result_ptr: rtw_free((u8*)scan_result_handler_ptr.ap_details); scan_result_handler_ptr.ap_details = NULL; err_exit: rtw_memset((void *)&scan_result_handler_ptr, 0, sizeof(scan_result_handler_ptr)); return RTW_ERROR; } //----------------------------------------------------------------------------// int wifi_set_pscan_chan(__u8 * channel_list,__u8 * pscan_config, __u8 length) { if(channel_list) return wext_set_pscan_channel(WLAN0_NAME, channel_list, pscan_config, length); else return -1; } //----------------------------------------------------------------------------// int wifi_get_setting(const char *ifname, rtw_wifi_setting_t *pSetting) { int ret = 0; int mode = 0; unsigned short security = 0; #ifdef CONFIG_SAE_SUPPORT unsigned short auth_alg = 0; #endif memset(pSetting, 0, sizeof(rtw_wifi_setting_t)); if(wext_get_mode(ifname, &mode) < 0) ret = -1; switch(mode) { case IW_MODE_MASTER: pSetting->mode = RTW_MODE_AP; break; case IW_MODE_INFRA: default: pSetting->mode = RTW_MODE_STA; break; //default: //RTW_API_INFO("\r\n%s(): Unknown mode %d\n", __func__, mode); //break; } if(wext_get_ssid(ifname, pSetting->ssid) < 0) ret = -1; if(wext_get_channel(ifname, &pSetting->channel) < 0) ret = -1; if(wext_get_enc_ext(ifname, &security, &pSetting->key_idx, pSetting->password) < 0) ret = -1; switch(security){ case IW_ENCODE_ALG_NONE: pSetting->security_type = RTW_SECURITY_OPEN; break; case IW_ENCODE_ALG_WEP: pSetting->security_type = RTW_SECURITY_WEP_PSK; break; case IW_ENCODE_ALG_TKIP: pSetting->security_type = RTW_SECURITY_WPA_TKIP_PSK; break; case IW_ENCODE_ALG_CCMP: pSetting->security_type = RTW_SECURITY_WPA2_AES_PSK; break; default: break; } if(security == IW_ENCODE_ALG_TKIP || security == IW_ENCODE_ALG_CCMP) if(wext_get_passphrase(ifname, pSetting->password) < 0) ret = -1; return ret; } //----------------------------------------------------------------------------// int wifi_show_setting(const char *ifname, rtw_wifi_setting_t *pSetting) { int ret = 0; #ifndef CONFIG_INIC_NO_FLASH RTW_API_INFO("\n\r\nWIFI %s Setting:",ifname); RTW_API_INFO("\n\r=============================="); switch(pSetting->mode) { case RTW_MODE_AP: #if (defined(CONFIG_EXAMPLE_UART_ATCMD) && CONFIG_EXAMPLE_UART_ATCMD) || (defined(CONFIG_EXAMPLE_SPI_ATCMD) && CONFIG_EXAMPLE_SPI_ATCMD) at_printf("\r\nAP,"); #endif RTW_API_INFO("\n\r MODE => AP"); break; case RTW_MODE_STA: #if (defined(CONFIG_EXAMPLE_UART_ATCMD) && CONFIG_EXAMPLE_UART_ATCMD) || (defined(CONFIG_EXAMPLE_SPI_ATCMD) && CONFIG_EXAMPLE_SPI_ATCMD) at_printf("\r\nSTA,"); #endif RTW_API_INFO("\n\r MODE => STATION"); break; default: #if (defined(CONFIG_EXAMPLE_UART_ATCMD) && CONFIG_EXAMPLE_UART_ATCMD) || (defined(CONFIG_EXAMPLE_SPI_ATCMD) && CONFIG_EXAMPLE_SPI_ATCMD) at_printf("\r\nUNKNOWN,"); #endif RTW_API_INFO("\n\r MODE => UNKNOWN"); } #if (defined(CONFIG_EXAMPLE_UART_ATCMD) && CONFIG_EXAMPLE_UART_ATCMD) || (defined(CONFIG_EXAMPLE_SPI_ATCMD) && CONFIG_EXAMPLE_SPI_ATCMD) at_printf("%s,%d,", pSetting->ssid, pSetting->channel); #endif RTW_API_INFO("\n\r SSID => %s", pSetting->ssid); RTW_API_INFO("\n\r CHANNEL => %d", pSetting->channel); switch(pSetting->security_type) { case RTW_SECURITY_OPEN: #if (defined(CONFIG_EXAMPLE_UART_ATCMD) && CONFIG_EXAMPLE_UART_ATCMD) || (defined(CONFIG_EXAMPLE_SPI_ATCMD) && CONFIG_EXAMPLE_SPI_ATCMD) at_printf("OPEN,"); #endif RTW_API_INFO("\n\r SECURITY => OPEN"); break; case RTW_SECURITY_WEP_PSK: #if (defined(CONFIG_EXAMPLE_UART_ATCMD) && CONFIG_EXAMPLE_UART_ATCMD) || (defined(CONFIG_EXAMPLE_SPI_ATCMD) && CONFIG_EXAMPLE_SPI_ATCMD) at_printf("WEP,%d,", pSetting->key_idx); #endif RTW_API_INFO("\n\r SECURITY => WEP"); RTW_API_INFO("\n\r KEY INDEX => %d", pSetting->key_idx); break; case RTW_SECURITY_WPA_TKIP_PSK: #if (defined(CONFIG_EXAMPLE_UART_ATCMD) && CONFIG_EXAMPLE_UART_ATCMD) || (defined(CONFIG_EXAMPLE_SPI_ATCMD) && CONFIG_EXAMPLE_SPI_ATCMD) at_printf("TKIP,"); #endif RTW_API_INFO("\n\r SECURITY => TKIP"); break; case RTW_SECURITY_WPA2_AES_PSK: #if (defined(CONFIG_EXAMPLE_UART_ATCMD) && CONFIG_EXAMPLE_UART_ATCMD) || (defined(CONFIG_EXAMPLE_SPI_ATCMD) && CONFIG_EXAMPLE_SPI_ATCMD) at_printf("AES,"); #endif RTW_API_INFO("\n\r SECURITY => AES"); break; default: #if (defined(CONFIG_EXAMPLE_UART_ATCMD) && CONFIG_EXAMPLE_UART_ATCMD) || (defined(CONFIG_EXAMPLE_SPI_ATCMD) && CONFIG_EXAMPLE_SPI_ATCMD) at_printf("UNKNOWN,"); #endif RTW_API_INFO("\n\r SECURITY => UNKNOWN"); } #if (defined(CONFIG_EXAMPLE_UART_ATCMD) && CONFIG_EXAMPLE_UART_ATCMD) || (defined(CONFIG_EXAMPLE_SPI_ATCMD) && CONFIG_EXAMPLE_SPI_ATCMD) at_printf("%s,", pSetting->password); #endif RTW_API_INFO("\n\r PASSWORD => %s", pSetting->password); RTW_API_INFO("\n\r"); #endif return ret; } //----------------------------------------------------------------------------// int wifi_set_network_mode(rtw_network_mode_t mode) { if((mode == RTW_NETWORK_B) || (mode == RTW_NETWORK_BG) || (mode == RTW_NETWORK_BGN)) return rltk_wlan_wireless_mode((unsigned char) mode); return -1; } int wifi_get_network_mode(rtw_network_mode_t *pmode) { if(pmode != NULL) return rltk_wlan_get_wireless_mode((unsigned char *) pmode); return -1; } int wifi_set_wps_phase(unsigned char is_trigger_wps) { return rltk_wlan_set_wps_phase(is_trigger_wps); } //----------------------------------------------------------------------------// int wifi_set_promisc(rtw_rcr_level_t enabled, void (*callback)(unsigned char*, unsigned int, void*), unsigned char len_used) { return promisc_set(enabled, callback, len_used); } void wifi_enter_promisc_mode(){ #ifdef CONFIG_PROMISC int mode = 0; unsigned char ssid[33]; if(wifi_mode == RTW_MODE_STA_AP){ wifi_off(); rtw_msleep_os(20); wifi_on(RTW_MODE_PROMISC); }else{ wext_get_mode(WLAN0_NAME, &mode); switch(mode) { case IW_MODE_MASTER: //In AP mode //rltk_wlan_deinit(); wifi_off();//modified by Chris Yang for iNIC rtw_msleep_os(20); //rltk_wlan_init(0, RTW_MODE_PROMISC); //rltk_wlan_start(0); wifi_on(RTW_MODE_PROMISC); break; case IW_MODE_INFRA: //In STA mode if(wext_get_ssid(WLAN0_NAME, ssid) > 0) wifi_disconnect(); } } #endif } int wifi_restart_ap( unsigned char *ssid, rtw_security_t security_type, unsigned char *password, int ssid_len, int password_len, int channel) { #if defined (CONFIG_AP_MODE) && defined (CONFIG_NATIVEAP_MLME) unsigned char idx = 0; #if CONFIG_LWIP_LAYER #if defined(CONFIG_MBED_ENABLED) || defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO #else ip_addr_t ipaddr; ip_addr_t netmask; ip_addr_t gw; struct netif * pnetif = &xnetif[0]; #endif #endif #ifdef CONFIG_CONCURRENT_MODE rtw_wifi_setting_t setting; int sta_linked = 0; #endif if(rltk_wlan_running(WLAN1_IDX)){ idx = 1; } // stop dhcp server #if CONFIG_LWIP_LAYER #if defined(CONFIG_MBED_ENABLED) || defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO #else dhcps_deinit(); #endif #endif #ifdef CONFIG_CONCURRENT_MODE if(idx > 0){ sta_linked = wifi_get_setting(WLAN0_NAME, &setting); wifi_off(); rtw_msleep_os(20); wifi_on(RTW_MODE_STA_AP); } else #endif { #if CONFIG_LWIP_LAYER #if defined(CONFIG_MBED_ENABLED) || defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO #else #if LWIP_VERSION_MAJOR >= 2 IP4_ADDR(ip_2_ip4(&ipaddr), GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3); IP4_ADDR(ip_2_ip4(&netmask), NETMASK_ADDR0, NETMASK_ADDR1 , NETMASK_ADDR2, NETMASK_ADDR3); IP4_ADDR(ip_2_ip4(&gw), GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3); netif_set_addr(pnetif, ip_2_ip4(&ipaddr), ip_2_ip4(&netmask),ip_2_ip4(&gw)); #else IP4_ADDR(&ipaddr, GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3); IP4_ADDR(&netmask, NETMASK_ADDR0, NETMASK_ADDR1 , NETMASK_ADDR2, NETMASK_ADDR3); IP4_ADDR(&gw, GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3); netif_set_addr(pnetif, &ipaddr, &netmask,&gw); #endif #endif #endif wifi_off(); rtw_msleep_os(20); wifi_on(RTW_MODE_AP); } // start ap if(wifi_start_ap((char*)ssid, security_type, (char*)password, ssid_len, password_len, channel) < 0) { RTW_API_INFO("\n\rERROR: Operation failed!"); return -1; } #ifdef CONFIG_CONCURRENT_MODE // connect to ap if wlan0 was linked with ap if(idx > 0 && sta_linked == 0){ volatile int ret; (void) ret; RTW_API_INFO("\r\nAP: ssid=%s", (char*)setting.ssid); RTW_API_INFO("\r\nAP: security_type=%d", setting.security_type); RTW_API_INFO("\r\nAP: password=%s", (char*)setting.password); RTW_API_INFO("\r\nAP: key_idx =%d\n", setting.key_idx); ret = wifi_connect((char*)setting.ssid, setting.security_type, (char*)setting.password, strlen((char*)setting.ssid), strlen((char*)setting.password), setting.key_idx, NULL); #if defined(CONFIG_DHCP_CLIENT) && CONFIG_DHCP_CLIENT if(ret == RTW_SUCCESS) { /* Start DHCPClient */ LwIP_DHCP(0, DHCP_START); } #endif } #endif #if defined(CONFIG_MBED_ENABLED) osThreadId_t id = osThreadGetId(); RTW_API_INFO("\r\nWebServer Thread: High Water Mark is %ld\n", osThreadGetStackSpace(id)); #else #endif #if CONFIG_LWIP_LAYER #if defined(CONFIG_MBED_ENABLED) || defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO #else // start dhcp server dhcps_init(&xnetif[idx]); #endif #endif #endif return 0; } #if defined(CONFIG_AUTO_RECONNECT) && CONFIG_AUTO_RECONNECT extern void (*p_wlan_autoreconnect_hdl)(rtw_security_t, char*, int, char*, int, int); struct wifi_autoreconnect_param { rtw_security_t security_type; char *ssid; int ssid_len; char *password; int password_len; int key_id; }; #if defined(CONFIG_MBED_ENABLED) || defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) void wifi_autoreconnect_hdl(rtw_security_t security_type, char *ssid, int ssid_len, char *password, int password_len, int key_id) { RTW_API_INFO("\n\r%s Not Implemented Yet!\n", __func__); } #else static void wifi_autoreconnect_thread(void *param) { #if defined(configENABLE_TRUSTZONE) && (configENABLE_TRUSTZONE == 1) rtw_create_secure_context(configMINIMAL_SECURE_STACK_SIZE); #endif int ret = RTW_ERROR; struct wifi_autoreconnect_param *reconnect_param = (struct wifi_autoreconnect_param *) param; RTW_API_INFO("\n\rauto reconnect ...\n"); #ifdef CONFIG_SAE_SUPPORT if(reconnect_param->security_type == RTW_SECURITY_WPA2_AES_PSK) { if(wext_get_support_wpa3() == 1) { wext_set_support_wpa3(DISABLE); ret = wifi_connect(reconnect_param->ssid, reconnect_param->security_type, reconnect_param->password, reconnect_param->ssid_len, reconnect_param->password_len, reconnect_param->key_id, NULL); wext_set_support_wpa3(ENABLE); } else { ret = wifi_connect(reconnect_param->ssid, reconnect_param->security_type, reconnect_param->password, reconnect_param->ssid_len, reconnect_param->password_len, reconnect_param->key_id, NULL); } } #ifdef CONFIG_PMKSA_CACHING else if(reconnect_param->security_type == RTW_SECURITY_WPA3_AES_PSK) { wifi_set_pmk_cache_enable(0); ret = wifi_connect(reconnect_param->ssid, reconnect_param->security_type, reconnect_param->password, reconnect_param->ssid_len, reconnect_param->password_len, reconnect_param->key_id, NULL); wifi_set_pmk_cache_enable(1); } #endif else #endif { ret = wifi_connect(reconnect_param->ssid, reconnect_param->security_type, reconnect_param->password, reconnect_param->ssid_len, reconnect_param->password_len, reconnect_param->key_id, NULL); } #if CONFIG_LWIP_LAYER if(ret == RTW_SUCCESS) { printf("\r\nWifi_connect successed, Begin to DHCP\n\r"); ret = LwIP_DHCP(0, DHCP_START); } #endif //#if CONFIG_LWIP_LAYER rtw_free(param); param = NULL; param_indicator = NULL; aos_task_exit(0); } void wifi_autoreconnect_hdl(rtw_security_t security_type, char *ssid, int ssid_len, char *password, int password_len, int key_id) { struct wifi_autoreconnect_param *param = (struct wifi_autoreconnect_param*)rtw_malloc(sizeof(struct wifi_autoreconnect_param)); param_indicator = (void *)param; param->security_type = security_type; param->ssid = ssid; param->ssid_len = ssid_len; param->password = password; param->password_len = password_len; param->key_id = key_id; //xTaskCreate(wifi_autoreconnect_thread, (const char *)"wifi_autoreconnect", 512, &param, tskIDLE_PRIORITY + 1, NULL); aos_task_new("wifi_autoreconnect", wifi_autoreconnect_thread, param, 4096); } #endif int wifi_config_autoreconnect(__u8 mode, __u8 retry_times, __u16 timeout) { if(mode == RTW_AUTORECONNECT_DISABLE) p_wlan_autoreconnect_hdl = NULL; else p_wlan_autoreconnect_hdl = wifi_autoreconnect_hdl; return wext_set_autoreconnect(WLAN0_NAME, mode, retry_times, timeout); } int wifi_set_autoreconnect(__u8 mode) { p_wlan_autoreconnect_hdl = wifi_autoreconnect_hdl; return wifi_config_autoreconnect(mode, AUTO_RECONNECT_COUNT, AUTO_RECONNECT_INTERVAL);//default retry 8 times, timeout 5 seconds } int wifi_get_autoreconnect(__u8 *mode) { return wext_get_autoreconnect(WLAN0_NAME, mode); } #endif #if defined( CONFIG_ENABLE_AP_POLLING_CLIENT_ALIVE )&&( CONFIG_ENABLE_AP_POLLING_CLIENT_ALIVE == 1 ) extern void (*p_ap_polling_sta_hdl)(void *); extern void (*p_ap_polling_sta_int_hdl)(void *, u16, u32 ); extern void ap_polling_sta_hdl(void *); extern void ap_polling_sta_int_hdl(void *, u16, u32 ); void wifi_set_ap_polling_sta(__u8 enabled) { if(_TRUE == enabled) { p_ap_polling_sta_hdl = ap_polling_sta_hdl; p_ap_polling_sta_int_hdl = ap_polling_sta_int_hdl; }else { p_ap_polling_sta_hdl = NULL; p_ap_polling_sta_int_hdl = NULL; } return ; } #endif #ifdef CONFIG_CUSTOM_IE /* * Example for custom ie * * u8 test_1[] = {221, 2, 2, 2}; * u8 test_2[] = {221, 2, 1, 1}; * rtw_custom_ie_t buf[2] = {{test_1, PROBE_REQ}, * {test_2, PROBE_RSP | BEACON}}; * u8 buf_test2[] = {221, 2, 1, 3} ; * rtw_custom_ie_t buf_update = {buf_test2, PROBE_REQ}; * * add ie list * static void cmd_add_ie(int argc, char **argv) * { * wifi_add_custom_ie((void *)buf, 2); * } * * update current ie * static void cmd_update_ie(int argc, char **argv) * { * wifi_update_custom_ie(&buf_update, 2); * } * * delete all ie * static void cmd_del_ie(int argc, char **argv) * { * wifi_del_custom_ie(); * } */ int wifi_add_custom_ie(void *cus_ie, int ie_num) { return wext_add_custom_ie(WLAN0_NAME, cus_ie, ie_num); } int wifi_update_custom_ie(void *cus_ie, int ie_index) { return wext_update_custom_ie(WLAN0_NAME, cus_ie, ie_index); } int wifi_del_custom_ie() { return wext_del_custom_ie(WLAN0_NAME); } #endif #ifdef CONFIG_PROMISC extern void promisc_init_packet_filter(void); extern int promisc_add_packet_filter(u8 filter_id, rtw_packet_filter_pattern_t *patt, rtw_packet_filter_rule_t rule); extern int promisc_enable_packet_filter(u8 filter_id); extern int promisc_disable_packet_filter(u8 filter_id); extern int promisc_remove_packet_filter(u8 filter_id); void wifi_init_packet_filter() { promisc_init_packet_filter(); } int wifi_add_packet_filter(unsigned char filter_id, rtw_packet_filter_pattern_t *patt, rtw_packet_filter_rule_t rule) { return promisc_add_packet_filter(filter_id, patt, rule); } int wifi_enable_packet_filter(unsigned char filter_id) { return promisc_enable_packet_filter(filter_id); } int wifi_disable_packet_filter(unsigned char filter_id) { return promisc_disable_packet_filter(filter_id); } int wifi_remove_packet_filter(unsigned char filter_id) { return promisc_remove_packet_filter(filter_id); } extern void promisc_filter_by_ap_and_phone_mac(u8 enable, void *ap_mac, void *phone_mac); void wifi_filter_by_ap_and_phone_mac(u8 enable, void *ap_mac, void *phone_mac) { promisc_filter_by_ap_and_phone_mac(enable,ap_mac,phone_mac); } #endif #ifdef CONFIG_AP_MODE extern int wext_enable_forwarding(const char *ifname); extern int wext_disable_forwarding(const char *ifname); int wifi_enable_forwarding(void) { return wext_enable_forwarding(WLAN0_NAME); } int wifi_disable_forwarding(void) { return wext_disable_forwarding(WLAN0_NAME); } #endif /* API to set flag for concurrent mode wlan1 issue_deauth when channel switched by wlan0 * usage: wifi_set_ch_deauth(0) -> wlan0 wifi_connect -> wifi_set_ch_deauth(1) */ #ifdef CONFIG_CONCURRENT_MODE int wifi_set_ch_deauth(__u8 enable) { return wext_set_ch_deauth(WLAN1_NAME, enable); } #endif void wifi_set_indicate_mgnt(int enable) { wext_set_indicate_mgnt(enable); return; } #ifdef CONFIG_ANTENNA_DIVERSITY int wifi_get_antenna_info(unsigned char *antenna) { int ret = 0; char buf[32]; rtw_memset(buf, 0, sizeof(buf)); rtw_memcpy(buf, "get_ant_info", 12); ret = wext_private_command_with_retval(WLAN0_NAME, buf, buf, 32); sscanf(buf, "%d", antenna); // 0: main, 1: aux return ret; } #endif #ifdef CONFIG_CONCURRENT_MODE extern void wext_suspend_softap(const char *ifname); extern void wext_suspend_softap_beacon(const char *ifname); void wifi_suspend_softap(void) { int client_number; struct { int count; rtw_mac_t mac_list[AP_STA_NUM]; } client_info; client_info.count = AP_STA_NUM; wifi_get_associated_client_list(&client_info, sizeof(client_info)); for(client_number = 0; client_number < client_info.count; client_number ++) { wext_del_station(WLAN1_NAME, client_info.mac_list[client_number].octet); } wext_suspend_softap(WLAN1_NAME); } void wifi_suspend_softap_beacon(void) { int client_number; struct { int count; rtw_mac_t mac_list[AP_STA_NUM]; } client_info; client_info.count = AP_STA_NUM; wifi_get_associated_client_list(&client_info, sizeof(client_info)); for(client_number = 0; client_number < client_info.count; client_number ++) { wext_del_station(WLAN1_NAME, client_info.mac_list[client_number].octet); } wext_suspend_softap_beacon(WLAN1_NAME); } #endif #ifdef CONFIG_SW_MAILBOX_EN int mailbox_to_wifi(u8 *data, u8 len) { return wext_mailbox_to_wifi(WLAN0_NAME, data, len); } #endif #ifdef CONFIG_WOWLAN_TCP_KEEP_ALIVE #define IP_HDR_LEN 20 #define TCP_HDR_LEN 20 #define ETH_HDR_LEN 14 #define ETH_ALEN 6 static uint32_t _checksum32(uint32_t start_value, uint8_t *data, size_t len) { uint32_t checksum32 = start_value; uint16_t data16 = 0; int i; for(i = 0; i < (len / 2 * 2); i += 2) { data16 = (data[i] << 8) | data[i + 1]; checksum32 += data16; } if(len % 2) { data16 = data[len - 1] << 8; checksum32 += data16; } return checksum32; } static uint16_t _checksum32to16(uint32_t checksum32) { uint16_t checksum16 = 0; checksum32 = (checksum32 >> 16) + (checksum32 & 0x0000ffff); checksum32 = (checksum32 >> 16) + (checksum32 & 0x0000ffff); checksum16 = (uint16_t) ~(checksum32 & 0xffff); return checksum16; } #endif int wifi_set_tcp_keep_alive_offload(int socket_fd, uint8_t *content, size_t len, uint32_t interval_ms) { /* To avoid gcc warnings */ ( void ) socket_fd; ( void ) content; ( void ) len; ( void ) interval_ms; #ifdef CONFIG_WOWLAN_TCP_KEEP_ALIVE struct sockaddr_in peer_addr, sock_addr; socklen_t peer_addr_len = sizeof(peer_addr); socklen_t sock_addr_len = sizeof(sock_addr); getpeername(socket_fd, (struct sockaddr *) &peer_addr, &peer_addr_len); getsockname(socket_fd, (struct sockaddr *) &sock_addr, &sock_addr_len); uint8_t *peer_ip = (uint8_t *) &peer_addr.sin_addr; uint16_t peer_port = ntohs(peer_addr.sin_port); uint8_t *sock_ip = (uint8_t *) &sock_addr.sin_addr; uint16_t sock_port = ntohs(sock_addr.sin_port); // ip header uint8_t ip_header[IP_HDR_LEN] = {0x45, 0x00, /*len*/ 0x00, 0x00 /*len*/, /*id*/ 0x00, 0x00 /*id*/, 0x00, 0x00, 0xff, /*protocol*/ 0x00 /*protocol*/, /*chksum*/ 0x00, 0x00 /*chksum*/, /*srcip*/ 0x00, 0x00, 0x00, 0x00 /*srcip*/, /*dstip*/ 0x00, 0x00, 0x00, 0x00 /*dstip*/}; // len uint16_t ip_len = IP_HDR_LEN + TCP_HDR_LEN + len; ip_header[2] = (uint8_t) (ip_len >> 8); ip_header[3] = (uint8_t) (ip_len & 0xff); // id extern u16_t ip4_getipid(void); uint16_t ip_id = ip4_getipid(); ip_header[4] = (uint8_t) (ip_id >> 8); ip_header[5] = (uint8_t) (ip_id & 0xff); // protocol ip_header[9] = 0x06; // src ip ip_header[12] = sock_ip[0]; ip_header[13] = sock_ip[1]; ip_header[14] = sock_ip[2]; ip_header[15] = sock_ip[3]; // dst ip ip_header[16] = peer_ip[0]; ip_header[17] = peer_ip[1]; ip_header[18] = peer_ip[2]; ip_header[19] = peer_ip[3]; // checksum uint32_t ip_checksum32 = 0; uint16_t ip_checksum16 = 0; ip_checksum32 = _checksum32(ip_checksum32, ip_header, sizeof(ip_header)); ip_checksum16 = _checksum32to16(ip_checksum32); ip_header[10] = (uint8_t) (ip_checksum16 >> 8); ip_header[11] = (uint8_t) (ip_checksum16 & 0xff); // pseudo header uint8_t pseudo_header[12] = {/*srcip*/ 0x00, 0x00, 0x00, 0x00 /*srcip*/, /*dstip*/ 0x00, 0x00, 0x00, 0x00 /*dstip*/, 0x00, /*protocol*/ 0x00 /*protocol*/, /*l4len*/ 0x00, 0x00 /*l4len*/}; // src ip pseudo_header[0] = sock_ip[0]; pseudo_header[1] = sock_ip[1]; pseudo_header[2] = sock_ip[2]; pseudo_header[3] = sock_ip[3]; // dst ip pseudo_header[4] = peer_ip[0]; pseudo_header[5] = peer_ip[1]; pseudo_header[6] = peer_ip[2]; pseudo_header[7] = peer_ip[3]; // protocol pseudo_header[9] = 0x06; // layer 4 len uint16_t l4_len = TCP_HDR_LEN + len; pseudo_header[10] = (uint8_t) (l4_len >> 8); pseudo_header[11] = (uint8_t) (l4_len & 0xff); // tcp header uint8_t tcp_header[TCP_HDR_LEN] = {/*srcport*/ 0x00, 0x00 /*srcport*/, /*dstport*/ 0x00, 0x00 /*dstport*/, /*seqno*/ 0x00, 0x00, 0x00, 0x00 /*seqno*/, /*ackno*/ 0x00, 0x00, 0x00, 0x00 /*ackno*/, 0x50, 0x18, /*window*/ 0x00, 0x00 /*window*/, /*checksum*/ 0x00, 0x00 /*checksum*/, 0x00, 0x00}; // src port tcp_header[0] = (uint8_t) (sock_port >> 8); tcp_header[1] = (uint8_t) (sock_port & 0xff); // dst port tcp_header[2] = (uint8_t) (peer_port >> 8); tcp_header[3] = (uint8_t) (peer_port & 0xff); uint32_t seqno = 0; uint32_t ackno = 0; uint16_t wnd = 0; extern int lwip_gettcpstatus(int s, uint32_t *seqno, uint32_t *ackno, uint16_t *wnd); lwip_gettcpstatus(socket_fd, &seqno, &ackno, &wnd); // seqno tcp_header[4] = (uint8_t) (seqno >> 24); tcp_header[5] = (uint8_t) ((seqno & 0x00ff0000) >> 16); tcp_header[6] = (uint8_t) ((seqno & 0x0000ff00) >> 8); tcp_header[7] = (uint8_t) (seqno & 0x000000ff); // ackno tcp_header[8] = (uint8_t) (ackno >> 24); tcp_header[9] = (uint8_t) ((ackno & 0x00ff0000) >> 16); tcp_header[10] = (uint8_t) ((ackno & 0x0000ff00) >> 8); tcp_header[11] = (uint8_t) (ackno & 0x000000ff); // window tcp_header[14] = (uint8_t) (wnd >> 8); tcp_header[15] = (uint8_t) (wnd & 0xff); // checksum uint32_t tcp_checksum32 = 0; uint16_t tcp_checksum16 = 0; tcp_checksum32 = _checksum32(tcp_checksum32, pseudo_header, sizeof(pseudo_header)); tcp_checksum32 = _checksum32(tcp_checksum32, tcp_header, sizeof(tcp_header)); tcp_checksum32 = _checksum32(tcp_checksum32, content, len); tcp_checksum16 = _checksum32to16(tcp_checksum32); tcp_header[16] = (uint8_t) (tcp_checksum16 >> 8); tcp_header[17] = (uint8_t) (tcp_checksum16 & 0xff); // eth header uint8_t eth_header[ETH_HDR_LEN] = {/*dstaddr*/ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /*dstaddr*/, /*srcaddr*/ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /*srcaddr*/, 0x08, 0x00}; struct eth_addr *dst_eth_ret = NULL; ip4_addr_t *dst_ip, *dst_ip_ret = NULL; dst_ip = (ip4_addr_t *) peer_ip; if(!ip4_addr_netcmp(dst_ip, netif_ip4_addr(&xnetif[0]), netif_ip4_netmask(&xnetif[0]))) { //outside local network dst_ip = (ip4_addr_t *) netif_ip4_gw(&xnetif[0]); } // dst addr if(etharp_find_addr(&xnetif[0], dst_ip, &dst_eth_ret, &dst_ip_ret) >= 0) { memcpy(eth_header, dst_eth_ret->addr, ETH_ALEN); } // src addr memcpy(eth_header + ETH_ALEN, LwIP_GetMAC(&xnetif[0]), ETH_ALEN); // eth frame without FCS uint32_t frame_len = sizeof(eth_header) + sizeof(ip_header) + sizeof(tcp_header) + len; uint8_t *eth_frame = (uint8_t *) malloc(frame_len); memcpy(eth_frame, eth_header, sizeof(eth_header)); memcpy(eth_frame + sizeof(eth_header), ip_header, sizeof(ip_header)); memcpy(eth_frame + sizeof(eth_header) + sizeof(ip_header), tcp_header, sizeof(tcp_header)); memcpy(eth_frame + sizeof(eth_header) + sizeof(ip_header) + sizeof(tcp_header), content, len); //extern void rtw_set_keepalive_offload(uint8_t *eth_frame, uint32_t frame_len, uint32_t interval_ms); rtw_set_keepalive_offload(eth_frame, frame_len, interval_ms); free(eth_frame); return 0; #else return -1; #endif } //----------------------------------------------------------------------------// #ifdef CONFIG_WOWLAN int wifi_wlan_redl_fw(void) { int ret = 0; ret = wext_wlan_redl_fw(WLAN0_NAME); return ret; } int wifi_wowlan_ctrl(int enable) { int ret = 0; ret = wext_wowlan_ctrl(WLAN0_NAME, enable); return ret; } #ifdef CONFIG_WOWLAN_CUSTOM_PATTERN int wifi_wowlan_set_pattern(wowlan_pattern_t pattern) { int ret = 0; ret = wext_wowlan_set_pattern(WLAN0_NAME, pattern); return ret; } #endif #endif //----------------------------------------------------------------------------// /** * @brief App can enable or disable wifi radio directly through this API. * @param new_status: the new state of the WIFI RF. * This parameter can be: ON/OFF. * @retval 0: success * @note wifi can't Tx/Rx packet after radio off, so you use this API carefully!! */ int wifi_rf_contrl(uint32_t new_status) { #ifdef CONFIG_APP_CTRL_RF_ONOFF rtw_rf_cmd(new_status); #endif return 0; } /** * @brief Get wifi TSF[63:0]. * @param port: wifi port 0/1. * @retval TSF[63:0] */ u32 wifi_get_tsf_low(u32 port) { #ifdef CONFIG_APP_CTRL_RF_ONOFF return rtw_get_tsf(port); #else return 0; #endif } /* * @brief get WIFI band type *@retval the support band type. * WL_BAND_2_4G: only support 2.4G * WL_BAND_5G: only support 5G * WL_BAND_2_4G_5G_BOTH: support both 2.4G and 5G */ WL_BAND_TYPE wifi_get_band_type(void) { u8 ret; ret = rtw_get_band_type(); if(ret == 0) { return WL_BAND_2_4G; } else if(ret == 1){ return WL_BAND_5G; } else { return WL_BAND_2_4G_5G_BOTH; } } #ifdef LOW_POWER_WIFI_CONNECT int wifi_set_psk_eap_interval(uint16_t psk_interval, uint16_t eap_interval) { return rltk_set_psk_eap_interval(psk_interval, eap_interval); } int wifi_set_null1_param(uint8_t check_period, uint8_t pkt_num, uint8_t limit, uint8_t interval) { return rltk_set_null1_param(check_period, pkt_num, limit, interval); } #endif #if WIFI_LOGO_CERTIFICATION_CONFIG #ifdef CONFIG_IEEE80211W u32 wifi_set_pmf(unsigned char pmf_mode){ int ret; ret = rltk_set_pmf(pmf_mode); return ret; } #endif #endif int wifi_ap_switch_chl_and_inform(unsigned char new_channel) { wext_ap_switch_chl_and_inform(new_channel); } #endif //#if CONFIG_WLAN
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/wifi_conf.c
C
apache-2.0
102,012
/****************************************************************************** * Copyright (c) 2013-2016 Realtek Semiconductor Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** ****************************************************************************** * @file wifi_conf.h * @author * @version * @brief This file provides user interface for Wi-Fi station and AP mode configuration * base on the functionalities provided by Realtek Wi-Fi driver. ****************************************************************************** */ #ifndef __WIFI_API_H #define __WIFI_API_H /** @addtogroup nic NIC * @ingroup wlan * @brief NIC functions * @{ */ #include "wifi_constants.h" #include "wifi_structures.h" #include "wifi_util.h" #include "wifi_ind.h" #include <platform/platform_stdlib.h> #ifdef __cplusplus extern "C" { #endif /****************************************************** * Macros ******************************************************/ #define RTW_ENABLE_API_INFO #ifdef RTW_ENABLE_API_INFO #if defined(CONFIG_MBED_ENABLED) extern __u32 GlobalDebugEnable; #define RTW_API_INFO(...) do {\ if (GlobalDebugEnable) \ printf(__VA_ARGS__);\ }while(0) #else #define RTW_API_INFO printf #endif #else #define RTW_API_INFO(args) #endif #define MAC_ARG(x) ((u8*)(x))[0],((u8*)(x))[1],((u8*)(x))[2],((u8*)(x))[3],((u8*)(x))[4],((u8*)(x))[5] #define CMP_MAC( a, b ) (((a[0])==(b[0]))&& \ ((a[1])==(b[1]))&& \ ((a[2])==(b[2]))&& \ ((a[3])==(b[3]))&& \ ((a[4])==(b[4]))&& \ ((a[5])==(b[5]))) /****************************************************** * Constants ******************************************************/ #define SCAN_LONGEST_WAIT_TIME (4500) #define MAC_FMT "%02x:%02x:%02x:%02x:%02x:%02x" #define PSCAN_ENABLE 0x01 //enable for partial channel scan #define PSCAN_FAST_SURVEY 0x02 //set to select scan time to FAST_SURVEY_TO, otherwise SURVEY_TO #define PSCAN_SIMPLE_CONFIG 0x04 //set to select scan time to FAST_SURVEY_TO and resend probe request typedef enum _WL_BAND_TYPE{ WL_BAND_2_4G = 0, WL_BAND_5G, WL_BAND_2_4G_5G_BOTH, WL_BANDMAX }WL_BAND_TYPE,*PWL_BAND_TYPE; /****************************************************** * Type Definitions ******************************************************/ /** Scan result callback function pointer type * * @param result_ptr : A pointer to the pointer that indicates where to put the next scan result * @param user_data : User provided data */ typedef void (*rtw_scan_result_callback_t)( rtw_scan_result_t** result_ptr, void* user_data ); typedef rtw_result_t (*rtw_scan_result_handler_t)( rtw_scan_handler_result_t* malloced_scan_result ); /****************************************************** * Structures ******************************************************/ typedef struct { char *buf; int buf_len; } scan_buf_arg; /****************************************************** * Structures ******************************************************/ typedef struct internal_scan_handler{ rtw_scan_result_t** pap_details; rtw_scan_result_t * ap_details; int scan_cnt; rtw_bool_t scan_complete; unsigned char max_ap_size; rtw_scan_result_handler_t gscan_result_handler; #if defined(SCAN_USE_SEMAPHORE) && SCAN_USE_SEMAPHORE void *scan_semaphore; #else int scan_running; #endif void* user_data; unsigned int scan_start_time; } internal_scan_handler_t; typedef struct { rtw_network_info_t network_info; void *join_sema; } internal_join_result_t; /****************************************************** * Function Declarations ******************************************************/ /** * @brief Initialize Realtek WiFi API System. * - Initialize the required parts of the software platform. * i.e. worker, event registering, semaphore, etc. * - Initialize the RTW API thread which handles the asynchronous event. * @return RTW_SUCCESS if initialization is successful, RTW_ERROR otherwise */ int wifi_manager_init(void); /** * @brief Join a Wi-Fi network. * Scan for, associate and authenticate with a Wi-Fi network. * On successful return, the system is ready to send data packets. * * @param[in] ssid: A null terminated string containing the SSID name of the network to join. * @param[in] security_type: Authentication type: * - RTW_SECURITY_OPEN - Open Security * - RTW_SECURITY_WEP_PSK - WEP Security with open authentication * - RTW_SECURITY_WEP_SHARED - WEP Security with shared authentication * - RTW_SECURITY_WPA_TKIP_PSK - WPA Security * - RTW_SECURITY_WPA2_AES_PSK - WPA2 Security using AES cipher * - RTW_SECURITY_WPA2_TKIP_PSK - WPA2 Security using TKIP cipher * - RTW_SECURITY_WPA2_MIXED_PSK - WPA2 Security using AES and/or TKIP ciphers * @param[in] password: A byte array containing either the cleartext security key for WPA/WPA2 * secured networks, or a pointer to an array of rtw_wep_key_t * structures for WEP secured networks. * @param[in] ssid_len: The length of the SSID in bytes. * @param[in] password_len: The length of the security_key in bytes. * @param[in] key_id: The index of the wep key (0, 1, 2, or 3). If not using it, leave it with value -1. * @param[in] semaphore: A user provided semaphore that is flagged when the join is complete. If not using it, leave it with NULL value. * @return RTW_SUCCESS: when the system is joined and ready to send data packets. * @return RTW_ERROR: if an error occurred. * @note Please make sure the Wi-Fi is enabled before invoking this function. (@ref wifi_on()) */ int wifi_connect( char *ssid, rtw_security_t security_type, char *password, int ssid_len, int password_len, int key_id, void *semaphore); /** * @brief Join a Wi-Fi network with specified BSSID. * Scan for, associate and authenticate with a Wi-Fi network. * On successful return, the system is ready to send data packets. * @param[in] bssid: The specified BSSID to connect. * @param[in] ssid: A null terminated string containing the SSID name of the network to join. * @param[in] security_type: Authentication type: * - RTW_SECURITY_OPEN - Open Security * - RTW_SECURITY_WEP_PSK - WEP Security with open authentication * - RTW_SECURITY_WEP_SHARED - WEP Security with shared authentication * - RTW_SECURITY_WPA_TKIP_PSK - WPA Security * - RTW_SECURITY_WPA2_AES_PSK - WPA2 Security using AES cipher * - RTW_SECURITY_WPA2_TKIP_PSK - WPA2 Security using TKIP cipher * - RTW_SECURITY_WPA2_MIXED_PSK - WPA2 Security using AES and/or TKIP ciphers * @param[in] password: A byte array containing either the cleartext security key for WPA/WPA2 * secured networks, or a pointer to an array of rtw_wep_key_t * structures for WEP secured networks. * @param[in] ssid_len: The length of the SSID in bytes. * @param[in] password_len: The length of the security_key in bytes. * @param[in] key_id: The index of the wep key. * @param[in] semaphore: A user provided semaphore that is flagged when the join is complete. * @return RTW_SUCCESS: when the system is joined and ready to send data packets. * @return RTW_ERROR: if an error occurred. * @note Please make sure the Wi-Fi is enabled before invoking this function. (@ref wifi_on()) * @note The difference between @ref wifi_connect_bssid() and @ref wifi_connect() is that BSSID has higher priority as the basis of connection in @ref wifi_connect_bssid. */ int wifi_connect_bssid( unsigned char bssid[ETH_ALEN], char *ssid, rtw_security_t security_type, char *password, int bssid_len, int ssid_len, int password_len, int key_id, void *semaphore); /** * @brief Disassociates from current Wi-Fi network. * @param None * @return RTW_SUCCESS: On successful disassociation from the AP. * @return RTW_ERROR: If an error occurred. */ int wifi_disconnect(void); /** * @brief Check if Wi-Fi has connected to AP before dhcp. * @param None * @return RTW_SUCCESS: If conneced. * @return RTW_ERROR: If not connect. */ int wifi_is_connected_to_ap(void); /** * @brief Check if the specified interface is up. * @param[in] interface: The interface can be set as RTW_STA_INTERFACE or RTW_AP_INTERFACE. (@ref rtw_interface_t) * @return If the function succeeds, the return value is 1. Otherwise, return 0. */ int wifi_is_up(rtw_interface_t interface); /** Determines if a particular interface is ready to transceive ethernet packets * * @param Radio interface to check, options are * RTW_STA_INTERFACE, RTW_AP_INTERFACE * @return RTW_SUCCESS : if the interface is ready to * transceive ethernet packets * @return RTW_ERROR : if the interface is not ready to * transceive ethernet packets */ int wifi_is_ready_to_transceive(rtw_interface_t interface); /** * @brief This function sets the current Media Access Control (MAC) address of the 802.11 device. * @param[in] mac: Wi-Fi MAC address. * @return RTW_SUCCESS or RTW_ERROR */ int wifi_set_mac_address(char * mac); /** * @brief Retrieves the current Media Access Control (MAC) address * (or Ethernet hardware address) of the 802.11 device. * @param[in] mac: Point to the result of the mac address will be get. * @return RTW_SUCCESS or RTW_ERROR */ int wifi_get_mac_address(char * mac); /** * @brief Enable Wi-Fi powersave mode. * @param None * @return RTW_SUCCESS or RTW_ERROR. */ int wifi_enable_powersave(void); /** * @brief Resume Wi-Fi powersave mode. * @param None * @return RTW_SUCCESS or RTW_ERROR. */ int wifi_resume_powersave(void); /** * @brief Disable Wi-Fi powersave mode. * @param None * @return RTW_SUCCESS or RTW_ERROR. */ int wifi_disable_powersave(void); /** Gets the tx power in index units * * @param dbm : The variable to receive the tx power in index. * * @return RTW_SUCCESS : if successful * RTW_ERROR : if not successful */ void wifi_btcoex_set_bt_on(void); void wifi_btcoex_set_bt_off(void); int wifi_get_txpower(int *poweridx); /** * @brief Set the tx power in index units. * @param[in] poweridx: The desired tx power in index. * @return RTW_SUCCESS: if tx power is successfully set * @return RTW_ERROR: if tx power is not successfully set */ int wifi_set_txpower(int poweridx); /** * @brief Get the associated clients with SoftAP. * @param[out] client_list_buffer: The location where the client list will be stored. * @param[in] buffer_length: The buffer length. * @return RTW_SUCCESS: The result is successfully got. * @return RTW_ERROR: The result is not successfully got. */ int wifi_get_associated_client_list(void * client_list_buffer, unsigned short buffer_length); /** * @brief Get connected AP's BSSID * @param[out] bssid : the location where the AP BSSID will be stored * @return RTW_SUCCESS : if result was successfully get * @return RTW_ERROR : if result was not successfully get */ int wifi_get_ap_bssid(unsigned char *bssid); /** * @brief Get the SoftAP information. * @param[out] ap_info: The location where the AP info will be stored. * @param[out] security: The security type. * @return RTW_SUCCESS: The result is successfully got. * @return RTW_ERROR: The result is not successfully got. */ int wifi_get_ap_info(rtw_bss_info_t * ap_info, rtw_security_t* security); /** * @brief Set the country code to driver to determine the channel set. * @param[in] country_code: Specify the country code. * @return RTW_SUCCESS: If result is successfully set. * @return RTW_ERROR: If result is not successfully set. */ int wifi_set_country(rtw_country_code_t country_code); /** * @brief retrieved sta mode MAX data rate. * @param[out] inidata_rate: MAX data rate. * @return RTW_SUCCESS: If the INIDATA_RATE is successfully retrieved. * @return RTW_ERROR: If the INIDATA_RATE is not retrieved. * note: inidata_rate = 2 * (data rate), you need inidata_rate/2.0 to get the real rate */ int wifi_get_sta_max_data_rate(__u8 * inidata_rate); /** * @brief Retrieve the latest RSSI value. * @param[out] pRSSI: Points to the integer to store the RSSI value gotten from driver. * @return RTW_SUCCESS: If the RSSI is succesfully retrieved. * @return RTW_ERROR: If the RSSI is not retrieved. */ int wifi_get_rssi(int *pRSSI); /** * @brief Retrieve the latest average beacon RSSI value. * @param[out] pRSSI: Points to the integer to store the RSSI value gotten from driver. * @return RTW_SUCCESS: If the RSSI is succesfully retrieved. * @return RTW_ERROR: If the RSSI is not retrieved. */ int wifi_get_bcn_rssi(int *pRSSI); /** * @brief Set the listening channel for promiscuous mode. * @param[in] channel: The desired channel. * @return RTW_SUCCESS: If the channel is successfully set. * @return RTW_ERROR: If the channel is not successfully set. * @note Do NOT need to call this function for STA mode wifi driver, since it will determine the channel from received beacon. */ int wifi_set_channel(int channel); /** * @brief Get the current channel on STA interface. * @param[out] channel: A pointer to the variable where the * channel value will be written * @return RTW_SUCCESS: If the channel is successfully read. * @return RTW_ERROR: If the channel is not successfully read. */ int wifi_get_channel(int *channel); /** * @brief switch the current channelPlan on STA or AP interface. * @param[in] channel_plan: the available channelPlan Map index * from 0x20 to 0x79 * @return RTW_SUCCESS: If the channel is successfully read. * @return RTW_ERROR: If the channel is not successfully read. */ int wifi_change_channel_plan(uint8_t channel_plan); /** * @brief Register interest in a multicast address.\n * Once a multicast address has been registered, all packets detected on the * medium destined for that address are forwarded to the host. * Otherwise they are ignored. * @param[in] mac: Ethernet MAC address * @return RTW_SUCCESS: If the address is registered successfully. * @return RTW_ERROR: If the address is not registered. */ int wifi_register_multicast_address(rtw_mac_t *mac); /** * @brief Unregister interest in a multicast address.\n * Once a multicast address has been unregistered, all packets detected on the * medium destined for that address are ignored. * @param[in] mac: Ethernet MAC address * @return RTW_SUCCESS: If the address is unregistered successfully. * @return RTW_ERROR: If the address is not unregistered. */ int wifi_unregister_multicast_address(rtw_mac_t *mac); /** * @brief Setup the adaptivity mode. * You can replace this weak function by the same name funcation to setup adaptivity mode you want. * @param None * @return If the function succeeds, the return value is 0. */ _WEAK void wifi_set_mib(void); /** * @brief Setup country code. * You can replace this weak function by the same name funcation to setup country code you want. * @param None * @return If the function succeeds, the return value is 0. */ //----------------------------------------------------------------------------// _WEAK void wifi_set_country_code(void); /** * @brief Enable Wi-Fi RF. * @param None * @return If the function succeeds, the return value is 0. * @note The difference between @ref wifi_rf_on() and @ref wifi_on() is that @ref wifi_rf_on() simply enable RF HAL, it does not enable the driver or allocate memory. */ int wifi_rf_on(void); /** * @brief Disable Wi-Fi RF. * @param None * @return If the function succeeds, the return value is 0. * @note The difference between @ref wifi_rf_off() and @ref wifi_off() is that @ref wifi_rf_off() simply disable RF HAL, the driver and used heap memory will NOT be released. */ int wifi_rf_off(void); /** * @brief Enable Wi-Fi. * - Bring the Wireless interface "Up" * - Initialize the driver thread which arbitrates access * to the SDIO/SPI bus * * @param[in] mode: Decide to enable WiFi in which mode. The optional modes are enumerated in @ref rtw_mode_t. * @return RTW_SUCCESS: if the WiFi chip was initialized successfully. * @return RTW_ERROR: if the WiFi chip was not initialized successfully. */ int wifi_on(rtw_mode_t mode); /** * @brief Disable Wi-Fi. * * @param None * @return RTW_SUCCESS: if deinitialization is successful. * @return RTW_ERROR: otherwise. */ int wifi_off(void); /** * @brief Switch Wifi Mode * * - Switch Wifi Mode to @param[in] * * @param[in] mode: Decide to switch WiFi to which mode. The optional modes are RTW_MODE_STA or RTW_MODE_AP. * @return RTW_SUCCESS: if the WiFi switch mode successful. * @return RTW_ERROR: if the WiFi swithc mdoe not successful. */ int wifi_set_mode(rtw_mode_t mode); /** * Turn off the Wi-Fi device * * - Bring the Wireless interface "Down" * - De-Initialises the driver thread which arbitrates access * to the SDIO/SPI bus * * @return RTW_SUCCESS if deinitialization is successful, * RTW_ERROR otherwise */ int wifi_off_fastly(void); /** * @brief Set IPS/LPS mode. * @param[in] ips_mode: The desired IPS mode. It becomes effective when wlan enter ips.\n * @ref ips_mode is inactive power save mode. Wi-Fi automatically turns RF off if it is not associated to AP. Set 1 to enable inactive power save mode. * @param[in] lps_mode: The desired LPS mode. It becomes effective when wlan enter lps.\n * @ref lps_mode is leisure power save mode. Wi-Fi automatically turns RF off during the association to AP is traffic is not busy while it also automatically turns RF on to listen to beacon. Set 1 to enable leisure power save mode. * @return RTW_SUCCESS if setting LPS mode successful. * @return RTW_ERROR otherwise. */ int wifi_set_power_mode(unsigned char ips_mode, unsigned char lps_mode); /** * Set TDMA parameters * * @param[in] slot_period : We separate TBTT into 2 or 3 slots. * If we separate TBTT into 2 slots, then slot_period should be larger or equal to 50ms. * It means 2 slot period is * slot_period, 100-slot_period * If we separate TBTT into 3 slots, then slot_period should be less or equal to 33ms. * It means 3 slot period is * 100 - 2 * slot_period, slot_period, slot_period * @param[in] rfon_period_len_1: rf on period of slot 1 * @param[in] rfon_period_len_2: rf on period of slot 2 * @param[in] rfon_period_len_3: rf on period of slot 3 * * @return RTW_SUCCESS if setting TDMA parameters successful * RTW_ERROR otherwise */ int wifi_set_tdma_param(unsigned char slot_period, unsigned char rfon_period_len_1, unsigned char rfon_period_len_2, unsigned char rfon_period_len_3); /** * @brief Set LPS DTIM. * @param[in] dtim: In LPS, the package can be buffered at AP side. * STA leave LPS until dtim count of packages buffered at AP side. * @return RTW_SUCCESS if setting LPS dtim successful. * @return RTW_ERROR otherwise */ int wifi_set_lps_dtim(unsigned char dtim); /** * @brief Get LPS DTIM. * @param[out] dtim: In LPS, the package can be buffered at AP side. * STA leave LPS until dtim count of packages buffered at AP side. * @return RTW_SUCCESS if getting LPS dtim successful. * @return RTW_ERROR otherwise. */ int wifi_get_lps_dtim(unsigned char *dtim); enum { LPS_THRESH_PKT_COUNT = 0, LPS_THRESH_DIRECT_ENTER, LPS_THRESH_TP, }; typedef unsigned char rtw_lps_thresh_t; /** * @brief Set LPS threshold. * @param[in] mode: LPS threshold mode LPS_THRESH_PKT_COUNT/LPS_THRESH_DIRECT_ENTER/LPS_THRESH_TP * @return RTW_SUCCESS if set LPS threshold successful. * @return RTW_ERROR otherwise. */ int wifi_set_lps_thresh(rtw_lps_thresh_t mode); /** * @brief Set LPS LEVEL * @param[in] lps_level: 0 is LPS_NORMAL, 1 is LPS_LCLK, 2 is LPS_PG * * @return RTW_SUCCESS if setting LPS level successful. * @return RTW_ERROR otherwise */ int wifi_set_lps_level(unsigned char lps_level); #ifdef LONG_PERIOD_TICKLESS /** * @brief Set Smart PS * @param[in] smartps: 0 is issue NULL data, 2 is issue PS-Poll * * @return RTW_SUCCESS if setting Smart PS successful. * @return RTW_ERROR otherwise */ int wifi_set_lps_smartps(unsigned char smartps); #endif /** * @brief Set Management Frame Protection Support. * @param[in] value: * - NO_MGMT_FRAME_PROTECTION - not support * - MGMT_FRAME_PROTECTION_OPTIONAL - capable * - MGMT_FRAME_PROTECTION_REQUIRED - required * @return RTW_SUCCESS if setting Management Frame Protection Support successful. * @return RTW_ERROR otherwise. */ int wifi_set_mfp_support(unsigned char value); /** * @brief Trigger Wi-Fi driver to start an infrastructure Wi-Fi network. * @warning If a STA interface is active when this function is called, the softAP will * start on the same channel as the STA. It will NOT use the channel provided! * @param[in] ssid: A null terminated string containing the SSID name of the network. * @param[in] security_type: * - RTW_SECURITY_OPEN - Open Security * - RTW_SECURITY_WPA_TKIP_PSK - WPA Security * - RTW_SECURITY_WPA2_AES_PSK - WPA2 Security using AES cipher * - RTW_SECURITY_WPA2_MIXED_PSK - WPA2 Security using AES and/or TKIP ciphers * - WEP security is NOT IMPLEMENTED. It is NOT SECURE! * @param[in] password: A byte array containing the cleartext security key for the network. * @param[in] ssid_len: The length of the SSID in bytes. * @param[in] password_len: The length of the security_key in bytes. * @param[in] channel: 802.11 channel number. * @return RTW_SUCCESS: If successfully creates an AP. * @return RTW_ERROR: If an error occurred. * @note Please make sure the Wi-Fi is enabled before invoking this function. (@ref wifi_on()) */ int wifi_start_ap( char *ssid, rtw_security_t security_type, char *password, int ssid_len, int password_len, int channel); /** * @brief Start an infrastructure Wi-Fi network with hidden SSID. * @warning If a STA interface is active when this function is called, the softAP will * start on the same channel as the STA. It will NOT use the channel provided! * * @param[in] ssid: A null terminated string containing * the SSID name of the network to join. * @param[in] security_type: Authentication type: \n * - RTW_SECURITY_OPEN - Open Security * - RTW_SECURITY_WPA_TKIP_PSK - WPA Security * - RTW_SECURITY_WPA2_AES_PSK - WPA2 Security using AES cipher * - RTW_SECURITY_WPA2_MIXED_PSK - WPA2 Security using AES and/or TKIP ciphers * - WEP security is NOT IMPLEMENTED. It is NOT SECURE! * @param[in] password: A byte array containing the cleartext * security key for the network. * @param[in] ssid_len: The length of the SSID in bytes. * @param[in] password_len: The length of the security_key in bytes. * @param[in] channel: 802.11 channel number * * @return RTW_SUCCESS: If successfully creates an AP. * @return RTW_ERROR: If an error occurred. */ int wifi_start_ap_with_hidden_ssid( char *ssid, rtw_security_t security_type, char *password, int ssid_len, int password_len, int channel); /** * @brief Initiate a scan to search for 802.11 networks. * * @param[in] scan_type: Specifies whether the scan should * be Active, Passive or scan * Prohibited channels * @param[in] bss_type: Specifies whether the scan should * search for Infrastructure * networks (those using an Access * Point), Ad-hoc networks, or both * types. * @param[in] result_ptr: Scan specific ssid. The first 4 * bytes is ssid lenth, and ssid name * append after it. * If no specific ssid need to scan, * PLEASE CLEAN result_ptr before pass * it into parameter. * @param[out] result_ptr: a pointer to a pointer to a result * storage structure. * @return RTW_SUCCESS or RTW_ERROR * @note The scan progressively accumulates results over time, and * may take between 1 and 3 seconds to complete. The results of * the scan will be individually provided to the callback * function. Note: The callback function will be executed in * the context of the RTW thread. * @note When scanning specific channels, devices with a * strong signal strength on nearby channels may be * detected */ int wifi_scan(rtw_scan_type_t scan_type, rtw_bss_type_t bss_type, void* result_ptr); /** * @brief Initiate a scan to search for 802.11 networks, a higher level API based on wifi_scan * to simplify the scan operation. * @param[in] results_handler: The callback function which will receive and process the result data. * @param[in] user_data: User specified data that will be passed directly to the callback function. * @return RTW_SUCCESS or RTW_ERROR * @note Callback must not use blocking functions, since it is called from the context of the RTW thread. * The callback, user_data variables will be referenced after the function returns. * Those variables must remain valid until the scan is completed. * The usage of this api can reference ATWS in atcmd_wifi.c. */ int wifi_scan_networks(rtw_scan_result_handler_t results_handler, void* user_data); /** * @brief Initiate a scan to search for 802.11 networks, a higher level API based on wifi_scan * to simplify the scan operation. This API separate full scan channel to partial scan * each channel for concurrent mode. MCC means Multi-channel concurrent. * @param[in] results_handler: The callback function which will receive and process the result data. * @param[in] user_data: User specified data that will be passed directly to the callback function. * @return RTW_SUCCESS or RTW_ERROR * @note Callback must not use blocking functions, since it is called from the context of the RTW thread. * The callback, user_data variables will be referenced after the function returns. * Those variables must remain valid until the scan is completed. * The usage of this api can reference ATWS in atcmd_wifi.c. */ int wifi_scan_networks_mcc(rtw_scan_result_handler_t results_handler, void* user_data); /** * @brief Initiate a scan to search for 802.11 networks with specified SSID. * @param[in] results_handler: The callback function which will receive and process the result data. * @param[in] user_data: User specified data that will be passed directly to the callback function. * @param[in] scan_buflen: The length of the result storage structure. * @param[in] ssid: The SSID of target network. * @param[in] ssid_len: The length of the target network SSID. * @return RTW_SUCCESS or RTW_ERROR * @note Callback must not use blocking functions, since it is called from the context of the RTW thread. * The callback, user_data variables will be referenced after the function returns. * Those variables must remain valid until the scan is completed. */ int wifi_scan_networks_with_ssid(int (results_handler)(char*, int, char *, void *), void* user_data, int scan_buflen, char* ssid, int ssid_len); /** * @brief Initiate a scan to search for 802.11 networks with specified SSID. * @param[in] results_handler: The callback function which will receive and process the result data. * @param[in] user_data: User specified data that will be passed directly to the callback function. * @param[in] scan_buflen: The length of the result storage structure. * @param[in] ssid: The SSID of target network. * @param[in] ssid_len: The length of the target network SSID. * @return RTW_SUCCESS or RTW_ERROR * @note Callback must not use blocking functions, since it is called from the context of the RTW thread. * The callback, user_data variables will be referenced after the function returns. * Those variables must remain valid until the scan is completed. */ int wifi_scan_networks_with_ssid_by_extended_security(int (results_handler)(char*, int, char *, void *), void* user_data, int scan_buflen, char* ssid, int ssid_len); /** * @brief Set the channel used to be partial scanned. * @param[in] channel_list: An array stores the channel list. * @param[in] pscan_config: the pscan_config of the channel set. * @param[in] length: The length of the channel_list. * @return RTW_SUCCESS or RTW_ERROR. * @note This function should be used with wifi_scan function. First, use @ref wifi_set_pscan_chan to * indicate which channel will be scanned, and then use @ref wifi_scan to get scanned results. */ int wifi_set_pscan_chan(__u8 * channel_list,__u8 * pscan_config, __u8 length); /** * @brief Get current Wi-Fi setting from driver. * @param[in] ifname: the wlan interface name, can be WLAN0_NAME or WLAN1_NAME. * @param[out] pSetting: Points to the rtw_wifi_setting_t structure to store the WIFI setting gotten from driver. * @return RTW_SUCCESS or RTW_ERROR. */ int wifi_get_setting(const char *ifname,rtw_wifi_setting_t *pSetting); /** * @brief Show the network information stored in a rtw_wifi_setting_t structure. * @param[in] ifname: the wlan interface name, can be WLAN0_NAME or WLAN1_NAME. * @param[in] pSetting: Points to the rtw_wifi_setting_t structure which information is gotten by @ref wifi_get_setting(). * @return RTW_SUCCESS or RTW_ERROR. */ int wifi_show_setting(const char *ifname,rtw_wifi_setting_t *pSetting); /** * @brief Set the network mode according to the data rate its supported. * Driver works in BGN mode in default after driver initialization. This function is used to * change wireless network mode for station mode before connecting to AP. * @param[in] mode: Network mode to set. The value can be RTW_NETWORK_B/RTW_NETWORK_BG/RTW_NETWORK_BGN. * @return RTW_SUCCESS or RTW_ERROR. */ int wifi_set_network_mode(rtw_network_mode_t mode); /** * @brief Get the network mode. * Driver works in BGN mode in default after driver initialization. This function is used to * get the current wireless network mode for station mode. * @param[in] pmode: Network mode to get. * @return RTW_SUCCESS or RTW_ERROR. */ int wifi_get_network_mode(rtw_network_mode_t *pmode); /** * @brief Set the chip to start or stop the promiscuous mode. * @param[in] enabled: enabled can be set 0, 1, 2, 3 and 4. if enabled is zero, disable the promisc, else enable the promisc. * - 0 means disable the promisc. * - 1 means enable the promisc special for all ethernet frames. * - 2 means enable the promisc special for Broadcast/Multicast ethernet frames. * - 3 means enable the promisc special for all 802.11 frames. * - 4 means enable the promisc special for Broadcast/Multicast 802.11 frames. * @param[in] callback: the callback function which will * receive and process the netowork data. * @param[in] len_used: specify if the the promisc data length is used. * If len_used set to 1, packet(frame data) length will be saved and transferred to callback function. * * @return RTW_SUCCESS or RTW_ERROR * @note This function can be used to implement vendor specified simple configure. * @note To fetch Ethernet frames, the len_used should be set to 1 */ int wifi_set_promisc(rtw_rcr_level_t enabled, void (*callback)(unsigned char*, unsigned int, void*), unsigned char len_used); /** * @brief Let Wi-Fi enter promiscuous mode. * @param[in] None * @return None */ void wifi_enter_promisc_mode(void); /** Set the wps phase * * @param is_trigger_wps[in] : to trigger wps function or not * * @return RTW_SUCCESS or RTW_ERROR */ int wifi_set_wps_phase(unsigned char is_trigger_wps); /** * @brief Trigger Wi-Fi driver to restart an infrastructure Wi-Fi network. * @warning If a STA interface is active when this function is called, the softAP will * start on the same channel as the STA. It will NOT use the channel provided! * @param[in] ssid: A null terminated string containing the SSID name of the network. * @param[in] security_type: * - RTW_SECURITY_OPEN - Open Security * - RTW_SECURITY_WPA_TKIP_PSK - WPA Security * - RTW_SECURITY_WPA2_AES_PSK - WPA2 Security using AES cipher * - RTW_SECURITY_WPA2_MIXED_PSK - WPA2 Security using AES and/or TKIP ciphers * - WEP security is NOT IMPLEMENTED. It is NOT SECURE! * @param[in] password: A byte array containing the cleartext security key for the network. * @param[in] ssid_len: The length of the SSID in bytes. * @param[in] password_len: The length of the security_key in bytes. * @param[in] channel: 802.11 channel number. * @return RTW_SUCCESS: If successfully creates an AP. * @return RTW_ERROR: If an error occurred. * @note Please make sure the Wi-Fi is enabled before invoking this function. (@ref wifi_on()) */ int wifi_restart_ap( unsigned char *ssid, rtw_security_t security_type, unsigned char *password, int ssid_len, int password_len, int channel); /** * @brief Set reconnection mode with configuration. * @param[in] mode: Set 1/0 to enalbe/disable the reconnection mode. * @param[in] retry_times: The number of retry limit. * @param[in] timeout: The timeout value (in seconds). * @return 0 if success, otherwise return -1. * @note Defining CONFIG_AUTO_RECONNECT in "autoconf.h" needs to be done before compiling, * or this API won't be effective. * @note The difference between @ref wifi_config_autoreconnect() and @ref wifi_set_autoreconnect() is that * user can specify the retry times and timeout value in @ref wifi_config_autoreconnect(). * But in @ref wifi_set_autoreconnect() these values are set with 3 retry limit and 5 seconds timeout as default. */ int wifi_config_autoreconnect(__u8 mode, __u8 retry_times, __u16 timeout); /** * @brief Set reconnection mode with 3 retry limit and 5 seconds timeout as default. * @param[in] mode: Set 1/0 to enalbe/disable the reconnection mode. * @return 0 if success, otherwise return -1. * @note Defining CONFIG_AUTO_RECONNECT in "autoconf.h" needs to be done before compiling, * or this API won't be effective. * @note The difference between @ref wifi_config_autoreconnect() and @ref wifi_set_autoreconnect() is that * user can specify the retry times and timeout value in @ref wifi_config_autoreconnect(). * But in @ref wifi_set_autoreconnect() these values are set with 3 retry limit and 5 seconds timeout as default. */ int wifi_set_autoreconnect(__u8 mode); /** * @brief Get the result of setting reconnection mode. * @param[out] mode: Point to the result of setting reconnection mode. * @return 0 if success, otherwise return -1. * @note Defining CONFIG_AUTO_RECONNECT in "autoconf.h" needs to be done before compiling, * or this API won't be effective. */ int wifi_get_autoreconnect(__u8 *mode); /** * @brief Present the device disconnect reason while connecting. * @param None * @return @ref rtw_connect_error_flag_t * - 0: RTW_NO_ERROR * - 1: RTW_NONE_NETWORK * - 2: RTW_CONNECT_FAIL * - 3: RTW_WRONG_PASSWORD * - 4: RTW_DHCP_FAIL * - 5: RTW_UNKNOWN (initial status) */ int wifi_get_last_error(void); #ifdef CONFIG_CUSTOM_IE #ifndef BIT #define BIT(x) ((__u32)1 << (x)) #endif #ifndef _CUSTOM_IE_TYPE_ #define _CUSTOM_IE_TYPE_ /** * @brief The enumeration is transmission type for wifi custom ie. */ enum CUSTOM_IE_TYPE{ PROBE_REQ = BIT(0), PROBE_RSP = BIT(1), BEACON = BIT(2), ASSOC_REQ =BIT(3), }; typedef __u32 rtw_custom_ie_type_t; #endif /* _CUSTOM_IE_TYPE_ */ /* ie format * +-----------+--------+-----------------------+ * |element ID | length | content in length byte| * +-----------+--------+-----------------------+ * * type: refer to CUSTOM_IE_TYPE */ #ifndef _CUS_IE_ #define _CUS_IE_ /** * @brief The structure is used to set WIFI custom ie list, and type match CUSTOM_IE_TYPE.\n * The ie will be transmitted according to the type. */ typedef struct _cus_ie{ __u8 *ie; __u8 type; }rtw_custom_ie_t, *p_rtw_custom_ie_t; #endif /* _CUS_IE_ */ /** * @brief Setup custom ie list. * @warning This API can't be executed twice before deleting the previous custom ie list. * @param[in] cus_ie: Pointer to WIFI CUSTOM IE list. * @param[in] ie_num: The number of WIFI CUSTOM IE list. * @return 0 if success, otherwise return -1. * @note Defininig CONFIG_CUSTOM_IE in "autoconf.h" needs to be done before compiling, * or this API won't be effective. */ int wifi_add_custom_ie(void *cus_ie, int ie_num); /** * @brief Update the item in WIFI CUSTOM IE list. * @param[in] cus_ie: Pointer to WIFI CUSTOM IE address. * @param[in] ie_index: Index of WIFI CUSTOM IE list. * @return 0 if success, otherwise return -1. * @note Defininig CONFIG_CUSTOM_IE in "autoconf.h" needs to be done before compiling, * or this API won't be effective. */ int wifi_update_custom_ie(void *cus_ie, int ie_index); /** * @brief Delete WIFI CUSTOM IE list. * @param None * @return 0 if success, otherwise return -1. * @note Defininig CONFIG_CUSTOM_IE in "autoconf.h" needs to be done before compiling, * or this API won't be effective. */ int wifi_del_custom_ie(void); #endif #ifdef CONFIG_PROMISC /** * @brief Initialize packet filter related data. * @param None * @return None */ void wifi_init_packet_filter(void); /** * @brief Add packet filter. * @param[in] filter_id: The filter id. * @param[in] patt: Point to the filter pattern. * @param[in] rule: Point to the filter rule. * @return 0 if success, otherwise return -1. * @note For now, the maximum number of filters is 5. */ int wifi_add_packet_filter(unsigned char filter_id, rtw_packet_filter_pattern_t *patt, rtw_packet_filter_rule_t rule); /** * @brief Enable the packet filter. * @param[in] filter_id: The filter id. * @return 0 if success, otherwise return -1. * @note The filter can be used only if it has been enabled. */ int wifi_enable_packet_filter(unsigned char filter_id); /** * @brief Disable the packet filter. * @param[in] filter_id: The filter id. * @return 0 if success, otherwise return -1. */ int wifi_disable_packet_filter(unsigned char filter_id); /** * @brief Remove the packet filter. * @param[in] filter_id: The filter id. * @return 0 if success, otherwise return -1. */ int wifi_remove_packet_filter(unsigned char filter_id); /** * @brief: Only receive the packets sent by the specified ap and phone in promisc mode. * @param[in] enable: set 1 to enable filter, set 0 to disable this filter function. * @param[in] ap_mac: if 'enable' equals 0, it's useless; if 'enable' equals 1, this value is the ap's mac address. * @param[in] phone_mac: if 'enable' equals 0, it's useless; if 'enable' equals 1, this value is the phone's mac address. * @return None. * @note Please invoke this function as "wifi_filter_by_ap_and_phone_mac(0,NULL,NULL)" before exiting promisc mode if you enabled it during the promisc mode. */ void wifi_filter_by_ap_and_phone_mac(u8 enable, void *ap_mac, void *phone_mac); #endif /** * @brief Get antenna infomation. * @param[in] antenna: Points to store the antenna value gotten from driver, 0: main, 1: aux. * @return 0 if success, otherwise return -1. */ #ifdef CONFIG_ANTENNA_DIVERSITY int wifi_get_antenna_info(unsigned char *antenna); #endif // #ifdef CONFIG_ANTENNA_DIVERSITY /** * @brief: config mode of HW indicating packets(mgnt and data) and SW reporting packets to wifi_indication(). * @param[in] * 0: disable mode(default), HW only indicate bssid-matched pkts and SW don't report. * 1: normal mode, HW only indicate bssid-matched pkts and SW report. * 2: wild mode, HW indicate all pkts and SW report. * * @return None * @note None */ void wifi_set_indicate_mgnt(int enable); /** * @brief Get the information of MP driver * @param[out] ability : 0x1 stand for mp driver, and 0x0 stand for normal driver * @return RTW_SUCCESS */ int wifi_get_drv_ability(uint32_t *ability); /** * @brief Set channel plan into flash/efuse, must reboot after setting channel plan * @param[in] channel_plan : the value of channel plan, define in wifi_constants.h * @return RTW_SUCCESS or RTW_ERROR */ int wifi_set_channel_plan(uint8_t channel_plan); /** * @brief Get channel plan from calibration section * @param[out] channel_plan : point to the value of channel plan, define in wifi_constants.h * @return RTW_SUCCESS or RTW_ERROR */ int wifi_get_channel_plan(uint8_t *channel_plan); #ifdef CONFIG_AP_MODE /** * @brief Enable packets forwarding in ap mode * @return RTW_SUCCESS */ int wifi_enable_forwarding(void); /** * @brief Disable packets forwarding in ap mode * @return RTW_SUCCESS */ int wifi_disable_forwarding(void); #endif #ifdef CONFIG_CONCURRENT_MODE /** * @brief Set flag for concurrent mode wlan1 issue_deauth when channel switched by wlan0 * usage: wifi_set_ch_deauth(0) -> wlan0 wifi_connect -> wifi_set_ch_deauth(1) * @param[in] enable : 0 for disable and 1 for enable * @return RTW_SUCCESS */ int wifi_set_ch_deauth(__u8 enable); #endif ///@name Ameba1 Only ///@{ /** * @brief enable AP sending QoS Null0 Data to poll Sta be alive * @param[in] enabled: enabled can be set to 0,1. * - 0 means enable. * - 1 means disable. * @return None */ void wifi_set_ap_polling_sta(__u8 enabled); ///@} #ifdef CONFIG_SW_MAILBOX_EN /** * @brief interface for bt to set mailbox info to wifi, mostly for coexistence usage * @param[in] data : pointer of mailbox data * @param[in] len : length of mailbox data * @return 0 if success, otherwise return -1 */ int mailbox_to_wifi(u8 *data, u8 len); #else #define mailbox_to_wifi(data, len) #endif #ifdef CONFIG_WOWLAN_TCP_KEEP_ALIVE /** * @brief construct a tcp packet that offload to wlan. wlan would keep sending this packet to tcp server. * * @param[in] socket_fd : tcp socket * @param[in] content : tcp payload * @param[in] len : tcp payload size * @param[in] interval_ms : send this packeter every interval_ms milliseconds * @return RTW_SUCCESS */ int wifi_set_tcp_keep_alive_offload(int socket_fd, uint8_t *content, size_t len, uint32_t interval_ms); #endif // WoWlan related //-------------------------------------------------------------// #ifdef CONFIG_WOWLAN typedef struct { unsigned int filter_id; unsigned int polarity; unsigned int type; unsigned int offset; unsigned char *bitmask; unsigned char *pattern; } wowlan_pattern_param_t; int wifi_wowlan_ctrl(int enable); int wifi_wowlan_set_pattern(wowlan_pattern_t pattern); #endif //-------------------------------------------------------------// #ifdef CONFIG_APP_CTRL_RF_ONOFF extern void rtw_rf_cmd(u32 Status); extern u32 rtw_get_tsf(u32 Port); #endif /* * @brief get band *@retval the support band type. * WL_BAND_2_4G: only support 2.4G * WL_BAND_5G: only support 5G * WL_BAND_2_4G_5G_BOTH: support both 2.4G and 5G */ WL_BAND_TYPE wifi_get_band_type(void); #ifdef LOW_POWER_WIFI_CONNECT int wifi_set_psk_eap_interval(uint16_t psk_interval, uint16_t eap_interval); int wifi_set_null1_param(uint8_t check_period, uint8_t pkt_num, uint8_t limit, uint8_t interval); #endif /** * @brief Switch channel of softap and inform connected stations to keep wifi connection. * @param[in] new_channel: The channel number that softap will switch to. * @return RTW_SUCCESS: If switching channel is successful. * @return RTW_ERROR: If switching channel is failed. */ int wifi_ap_switch_chl_and_inform(unsigned char new_channel); #ifdef __cplusplus } #endif /*\@}*/ #endif // __WIFI_API_H //----------------------------------------------------------------------------//
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/wifi_conf.h
C
apache-2.0
45,818
/****************************************************************************** * * Copyright(c) 2007 - 2021 Realtek Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ //----------------------------------------------------------------------------// #include "wifi/wifi_ind.h" #include "wifi/wifi_conf.h" #include "osdep_service.h" #include "platform_stdlib.h" /****************************************************** * Constants ******************************************************/ #define WIFI_INDICATE_MSG 0 #define WIFI_MANAGER_STACKSIZE 1300 #define WIFI_MANAGER_PRIORITY (0) //Actual priority is 4 since calling rtw_create_task #define WIFI_MANAGER_Q_SZ 8 #define WIFI_EVENT_MAX_ROW 3 /****************************************************** * Globals ******************************************************/ static event_list_elem_t event_callback_list[WIFI_EVENT_MAX][WIFI_EVENT_MAX_ROW]; #if CONFIG_WIFI_IND_USE_THREAD static rtw_worker_thread_t wifi_worker_thread; #endif //----------------------------------------------------------------------------// #if CONFIG_WIFI_IND_USE_THREAD static rtw_result_t rtw_send_event_to_worker(int event_cmd, char *buf, int buf_len, int flags) { rtw_event_message_t message; int i; rtw_result_t ret = RTW_SUCCESS; char *local_buf = NULL; if(event_cmd >= WIFI_EVENT_MAX) return RTW_BADARG; for(i = 0; i < WIFI_EVENT_MAX_ROW; i++){ if(event_callback_list[event_cmd][i].handler == NULL) continue; message.function = (event_handler_t)event_callback_list[event_cmd][i].handler; message.buf_len = buf_len; if(buf_len){ local_buf = (char*)pvPortMalloc(buf_len); if(local_buf == NULL) return RTW_NOMEM; memcpy(local_buf, buf, buf_len); //printf("\n!!!!!Allocate %p(%d) for evcmd %d\n", local_buf, buf_len, event_cmd); } message.buf = local_buf; message.flags = flags; message.user_data = event_callback_list[event_cmd][i].handler_user_data; ret = rtw_push_to_xqueue(&wifi_worker_thread.event_queue, &message, 0); if(ret != RTW_SUCCESS){ if(local_buf){ printf("\r\nrtw_send_event_to_worker: enqueue cmd %d failed and free %p(%d)\n", event_cmd, local_buf, buf_len); vPortFree(local_buf); } break; } } return ret; } #else static rtw_result_t rtw_indicate_event_handle(int event_cmd, char *buf, int buf_len, int flags) { rtw_event_handler_t handle = NULL; int i; if(event_cmd >= WIFI_EVENT_MAX) return (rtw_result_t)RTW_BADARG; for(i = 0; i < WIFI_EVENT_MAX_ROW; i++){ handle = event_callback_list[event_cmd][i].handler; if(handle == NULL) continue; handle(buf, buf_len, flags, event_callback_list[event_cmd][i].handler_user_data); } return RTW_SUCCESS; } #endif void wifi_indication( rtw_event_indicate_t event, char *buf, int buf_len, int flags) { // // If upper layer application triggers additional operations on receiving of wext_wlan_indicate, // please strictly check current stack size usage (by using uxTaskGetStackHighWaterMark() ) // , and tries not to share the same stack with wlan driver if remaining stack space is // not available for the following operations. // ex: using semaphore to notice another thread. switch(event) { case WIFI_EVENT_DISCONNECT: #if(WIFI_INDICATE_MSG==1) printf("\n\r %s():Disconnection indication received", __FUNCTION__); #endif break; case WIFI_EVENT_CONNECT: // For WPA/WPA2 mode, indication of connection does not mean data can be // correctly transmitted or received. Data can be correctly transmitted or // received only when 4-way handshake is done. // Please check WIFI_EVENT_FOURWAY_HANDSHAKE_DONE event #if(WIFI_INDICATE_MSG==1) // Sample: return mac address if(buf != NULL && buf_len == 6) { printf("\n\r%s():Connect indication received: %02x:%02x:%02x:%02x:%02x:%02x", __FUNCTION__, buf[0],buf[1],buf[2],buf[3],buf[4],buf[5]); } #endif break; case WIFI_EVENT_FOURWAY_HANDSHAKE_DONE: #if(WIFI_INDICATE_MSG==1) if(buf != NULL) { if(buf_len == strlen(IW_EXT_STR_FOURWAY_DONE)) printf("\n\r%s():%s", __FUNCTION__, buf); } #endif break; case WIFI_EVENT_SCAN_RESULT_REPORT: #if(WIFI_INDICATE_MSG==1) printf("\n\r%s(): WIFI_EVENT_SCAN_RESULT_REPORT\n", __func__); #endif break; case WIFI_EVENT_SCAN_DONE: #if(WIFI_INDICATE_MSG==1) printf("\n\r%s(): WIFI_EVENT_SCAN_DONE\n", __func__); #endif break; case WIFI_EVENT_RECONNECTION_FAIL: #if(WIFI_INDICATE_MSG==1) if(buf != NULL){ if(buf_len == strlen(IW_EXT_STR_RECONNECTION_FAIL)) printf("\n\r%s", buf); } #endif break; case WIFI_EVENT_NO_NETWORK: #if(WIFI_INDICATE_MSG==1) printf("\n\r%s(): WIFI_EVENT_NO_NETWORK\n", __func__); #endif break; case WIFI_EVENT_RX_MGNT: #if(WIFI_INDICATE_MSG==1) printf("\n\r%s(): WIFI_EVENT_RX_MGNT\n", __func__); #endif break; #if CONFIG_ENABLE_P2P case WIFI_EVENT_SEND_ACTION_DONE: #if(WIFI_INDICATE_MSG==1) printf("\n\r%s(): WIFI_EVENT_SEND_ACTION_DONE\n", __func__); #endif break; #endif //CONFIG_ENABLE_P2P case WIFI_EVENT_STA_ASSOC: #if(WIFI_INDICATE_MSG==1) printf("\n\r%s(): WIFI_EVENT_STA_ASSOC\n", __func__); #endif break; case WIFI_EVENT_STA_DISASSOC: #if(WIFI_INDICATE_MSG==1) printf("\n\r%s(): WIFI_EVENT_STA_DISASSOC\n", __func__); #endif break; #ifdef CONFIG_WPS case WIFI_EVENT_STA_WPS_START: #if(WIFI_INDICATE_MSG==1) printf("\n\r%s(): WIFI_EVENT_STA_WPS_START\n", __func__); #endif break; case WIFI_EVENT_WPS_FINISH: #if(WIFI_INDICATE_MSG==1) printf("\n\r%s(): WIFI_EVENT_WPS_FINISH\n", __func__); #endif break; case WIFI_EVENT_EAPOL_RECVD: #if(WIFI_INDICATE_MSG==1) printf("\n\r%s(): WIFI_EVENT_EAPOL_RECVD\n", __func__); #endif break; #endif case WIFI_EVENT_BEACON_AFTER_DHCP: #if(WIFI_INDICATE_MSG==1) printf("\n\r%s(): WIFI_EVENT_BEACON_AFTER_DHCP\n", __func__); #endif break; case WIFI_EVENT_IP_CHANGED: #if(WIFI_INDICATE_MSG==1) printf("\n\r%s(): WIFI_EVENT_IP_CHANNGED\n", __func__); #endif break; case WIFI_EVENT_ICV_ERROR: #if(WIFI_INDICATE_MSG==1) printf("\n\r%s(): WIFI_EVENT_ICV_ERROR\n", __func__); #endif case WIFI_EVENT_CHALLENGE_FAIL: #if(WIFI_INDICATE_MSG==1) printf("\n\r%s(): WIFI_EVENT_CHALLENGE_FAIL\n", __func__); #endif break; case WIFI_EVENT_SOFTAP_START: #if(WIFI_INDICATE_MSG==1) printf("\n\r%s(): WIFI_EVENT_SOFTAP_START\n", __func__); #endif break; case WIFI_EVENT_SOFTAP_STOP: #if(WIFI_INDICATE_MSG==1) printf("\n\r%s(): WIFI_EVENT_SOFTAP_STOP\n", __func__); #endif break; } #if CONFIG_INIC_EN inic_indicate_event(event, buf, buf_len, flags); #endif//CONFIG_INIC_EN #if CONFIG_WIFI_IND_USE_THREAD rtw_send_event_to_worker(event, buf, buf_len, flags); #else rtw_indicate_event_handle(event, buf, buf_len, flags); #endif } void wifi_reg_event_handler(unsigned int event_cmds, rtw_event_handler_t handler_func, void *handler_user_data) { int i = 0, j = 0; if(event_cmds < WIFI_EVENT_MAX){ for(i=0; i < WIFI_EVENT_MAX_ROW; i++){ if(event_callback_list[event_cmds][i].handler == NULL){ for(j=0; j<WIFI_EVENT_MAX_ROW; j++){ if(event_callback_list[event_cmds][j].handler == handler_func){ return; } } event_callback_list[event_cmds][i].handler = handler_func; event_callback_list[event_cmds][i].handler_user_data = handler_user_data; return; } } } } void wifi_unreg_event_handler(unsigned int event_cmds, rtw_event_handler_t handler_func) { int i; if(event_cmds < WIFI_EVENT_MAX){ for(i = 0; i < WIFI_EVENT_MAX_ROW; i++){ if(event_callback_list[event_cmds][i].handler == handler_func){ event_callback_list[event_cmds][i].handler = NULL; event_callback_list[event_cmds][i].handler_user_data = NULL; return; } } } } void init_event_callback_list(void){ memset(event_callback_list, 0, sizeof(event_callback_list)); } int wifi_manager_init(void) { #if CONFIG_WIFI_IND_USE_THREAD rtw_create_worker_thread(&wifi_worker_thread, WIFI_MANAGER_PRIORITY, WIFI_MANAGER_STACKSIZE, WIFI_MANAGER_Q_SZ); #endif return 0; } void rtw_wifi_manager_deinit(void) { #if CONFIG_WIFI_IND_USE_THREAD rtw_delete_worker_thread(&wifi_worker_thread); #endif }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/wifi_ind.c
C
apache-2.0
8,951
/****************************************************************************** * Copyright (c) 2013-2016 Realtek Semiconductor Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ****************************************************************************** * @file wifi_ind.h * @author * @version * @brief This file provides the functions related to event handler mechanism. ****************************************************************************** */ #ifndef _WIFI_INDICATE_H #define _WIFI_INDICATE_H /** @addtogroup nic NIC * @ingroup wlan * @brief NIC functions * @{ */ #include "wifi_conf.h" #ifdef __cplusplus extern "C" { #endif typedef void (*rtw_event_handler_t)(char *buf, int buf_len, int flags, void* handler_user_data ); typedef struct { // rtw_event_indicate_t event_cmd; rtw_event_handler_t handler; void* handler_user_data; } event_list_elem_t; /** * @brief Initialize the event callback list. * @warning Please make sure this function has been invoked before * using the event handler related mechanism. * @param None * @return None */ void init_event_callback_list(void); /** * @brief Wlan driver indicate event to upper layer through wifi_indication. * @param[in] event: An event reported from driver to upper layer application. Please refer to rtw_event_indicate_t enum. * @param[in] buf: If it is not NUL, buf is a pointer to the buffer for message string. * @param[in] buf_len: The length of the buffer. * @param[in] flags: Indicate some extra information, sometimes it is 0. * @retval None * @note If upper layer application triggers additional operations on receiving of wext_wlan_indicate, * please strictly check current stack size usage (by using uxTaskGetStackHighWaterMark() ), * and tries not to share the same stack with wlan driver if remaining stack space is not available * for the following operations. * ex: using semaphore to notice another thread instead of handing event directly in wifi_indication(). */ extern void wifi_indication( rtw_event_indicate_t event, char *buf, int buf_len, int flags); /** * @brief Register the event listener. * @param[in] event_cmds : The event command number indicated. * @param[in] handler_func : the callback function which will * receive and process the event. * @param[in] handler_user_data : user specific data that will be * passed directly to the callback function. * @return RTW_SUCCESS : if successfully registers the event. * @return RTW_ERROR : if an error occurred. * @note Set the same event_cmds with empty handler_func will * unregister the event_cmds. */ extern void wifi_reg_event_handler(unsigned int event_cmds, rtw_event_handler_t handler_func, void *handler_user_data); /** * @brief Un-register the event listener. * @param[in] event_cmds : The event command number indicated. * @param[in] handler_func : the callback function which will * receive and process the event. * * @return RTW_SUCCESS : if successfully un-registers the event . * @return RTW_ERROR : if an error occurred. */ extern void wifi_unreg_event_handler(unsigned int event_cmds, rtw_event_handler_t handler_func); #ifdef __cplusplus } #endif /*\@}*/ #endif //_WIFI_INDICATE_H
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/wifi_ind.h
C
apache-2.0
3,829
#if !defined(CONFIG_MBED_ENABLED) && !defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) #include "main.h" #include "lwip/tcpip.h" #endif #include <osdep_service.h> #include "wifi/wifi_conf.h" #include "k_api.h" #ifndef CONFIG_WLAN #define CONFIG_WLAN 1 #endif #if CONFIG_WLAN #include <platform/platform_stdlib.h> extern void _promisc_deinit(void *padapter); extern int _promisc_recv_func(void *padapter, void *rframe); extern int _promisc_set(rtw_rcr_level_t enabled, void (*callback)(unsigned char*, unsigned int, void*), unsigned char len_used); extern unsigned char _is_promisc_enabled(void); extern int _promisc_get_fixed_channel(void * fixed_bssid, u8 *ssid, int * ssid_length); extern void _promisc_filter_by_ap_and_phone_mac(u8 enable, void *ap_mac, void *phone_mac); // Add extra interfaces to make release sdk able to determine promisc API linking void promisc_deinit(void *padapter) { #ifdef CONFIG_PROMISC _promisc_deinit(padapter); #endif } int promisc_recv_func(void *padapter, void *rframe) { // Never reach here if not define CONFIG_PROMISC #ifdef CONFIG_PROMISC return _promisc_recv_func(padapter, rframe); #else return 0; #endif } int promisc_recv_lens_func(void *padapter, u8 *payload, u8 plen) { /* To avoid gcc warnings */ ( void ) padapter; ( void ) payload; ( void ) plen; // Never reach here if not define CONFIG_PROMISC #ifdef CONFIG_PROMISC #if defined(CONFIG_UNSUPPORT_PLCPHDR_RPT) && CONFIG_UNSUPPORT_PLCPHDR_RPT return _promisc_recv_lens_func(padapter, payload, plen); #else return 0; #endif #else return 0; #endif } int promisc_filter_with_len(u16 len) { /* To avoid gcc warnings */ ( void ) len; // Never reach here if not define CONFIG_PROMISC #ifdef CONFIG_PROMISC #if defined(CONFIG_UNSUPPORT_PLCPHDR_RPT) && CONFIG_UNSUPPORT_PLCPHDR_RPT return _promisc_filter_with_len(len); #else return -1; #endif #else return -1; #endif } int promisc_set(rtw_rcr_level_t enabled, void (*callback)(unsigned char*, unsigned int, void*), unsigned char len_used) { #ifdef CONFIG_PROMISC return _promisc_set(enabled, callback, len_used); #else return -1; #endif } unsigned char is_promisc_enabled(void) { #ifdef CONFIG_PROMISC return _is_promisc_enabled(); #else return 0; #endif } int promisc_get_fixed_channel(void *fixed_bssid, u8 *ssid, int *ssid_length) { #ifdef CONFIG_PROMISC return _promisc_get_fixed_channel(fixed_bssid, ssid, ssid_length); #else return 0; #endif } void promisc_filter_by_ap_and_phone_mac(u8 enable, void *ap_mac, void *phone_mac) { #ifdef CONFIG_PROMISC _promisc_filter_by_ap_and_phone_mac(enable, ap_mac, phone_mac); #endif } // End of Add extra interfaces struct eth_frame { struct eth_frame *prev; struct eth_frame *next; unsigned char da[6]; unsigned char sa[6]; unsigned int len; unsigned char type; signed char rssi; }; #ifndef CONFIG_INIC_CMD_RSP #define CONFIG_INIC_CMD_RSP 0 #endif #if CONFIG_INIC_CMD_RSP #if defined(__IAR_SYSTEMS_ICC__) || defined (__GNUC__) #pragma pack(1) #endif struct inic_eth_frame { unsigned char da[6]; unsigned char sa[6]; unsigned int len; unsigned char type; }; #if defined(__IAR_SYSTEMS_ICC__) || defined (__GNUC__) #pragma pack() #endif static struct inic_eth_frame *inic_frame, *inic_frame_tail = NULL; static int inic_frame_cnt = 0; #define MAX_INIC_FRAME_NUM 50 //maximum packets for each channel extern void inic_c2h_msg(const char *atcmd, char status, char *msg, u16 msg_len); #endif struct eth_buffer { struct eth_frame *head; struct eth_frame *tail; }; static struct eth_buffer eth_buffer; #ifdef CONFIG_PROMISC #define MAX_PACKET_FILTER_INFO 5 #define FILTER_ID_INIT_VALUE 10 rtw_packet_filter_info_t paff_array[MAX_PACKET_FILTER_INFO]={0}; static u8 packet_filter_enable_num = 0; void promisc_init_packet_filter(void) { int i = 0; for(i=0; i<MAX_PACKET_FILTER_INFO; i++){ paff_array[i].filter_id = FILTER_ID_INIT_VALUE; paff_array[i].enable = 0; paff_array[i].patt.mask_size = 0; paff_array[i].rule = RTW_POSITIVE_MATCHING; paff_array[i].patt.mask = NULL; paff_array[i].patt.pattern = NULL; } packet_filter_enable_num = 0; } int promisc_add_packet_filter(u8 filter_id, rtw_packet_filter_pattern_t *patt, rtw_packet_filter_rule_t rule) { int i = 0; while(i < MAX_PACKET_FILTER_INFO){ if(paff_array[i].filter_id == FILTER_ID_INIT_VALUE){ break; } i++; } if(i == MAX_PACKET_FILTER_INFO) return -1; paff_array[i].filter_id = filter_id; paff_array[i].patt.offset= patt->offset; paff_array[i].patt.mask_size = patt->mask_size; paff_array[i].patt.mask = rtw_malloc(patt->mask_size); memcpy(paff_array[i].patt.mask, patt->mask, patt->mask_size); paff_array[i].patt.pattern= rtw_malloc(patt->mask_size); memcpy(paff_array[i].patt.pattern, patt->pattern, patt->mask_size); paff_array[i].rule = rule; paff_array[i].enable = 0; return 0; } int promisc_enable_packet_filter(u8 filter_id) { int i = 0; while(i < MAX_PACKET_FILTER_INFO){ if(paff_array[i].filter_id == filter_id) break; i++; } if(i == MAX_PACKET_FILTER_INFO) return -1; paff_array[i].enable = 1; packet_filter_enable_num++; return 0; } int promisc_disable_packet_filter(u8 filter_id) { int i = 0; while(i < MAX_PACKET_FILTER_INFO){ if(paff_array[i].filter_id == filter_id) break; i++; } if(i == MAX_PACKET_FILTER_INFO) return -1; paff_array[i].enable = 0; packet_filter_enable_num--; return 0; } int promisc_remove_packet_filter(u8 filter_id) { int i = 0; while(i < MAX_PACKET_FILTER_INFO){ if(paff_array[i].filter_id == filter_id) break; i++; } if(i == MAX_PACKET_FILTER_INFO) return -1; paff_array[i].filter_id = FILTER_ID_INIT_VALUE; paff_array[i].enable = 0; paff_array[i].patt.mask_size = 0; paff_array[i].rule = 0; if(paff_array[i].patt.mask){ rtw_free(paff_array[i].patt.mask); paff_array[i].patt.mask = NULL; } if(paff_array[i].patt.pattern){ rtw_free(paff_array[i].patt.pattern); paff_array[i].patt.pattern = NULL; } return 0; } #endif /* Make callback simple to prevent latency to wlan rx when promiscuous mode */ static void promisc_callback(unsigned char *buf, unsigned int len, void* userdata) { struct eth_frame *frame = (struct eth_frame *) rtw_malloc(sizeof(struct eth_frame)); _lock lock; _irqL irqL; if(frame) { frame->prev = NULL; frame->next = NULL; memcpy(frame->da, buf, 6); memcpy(frame->sa, buf+6, 6); frame->len = len; frame->rssi = ((ieee80211_frame_info_t *)userdata)->rssi; rtw_enter_critical(&lock, &irqL); if(eth_buffer.tail) { eth_buffer.tail->next = frame; frame->prev = eth_buffer.tail; eth_buffer.tail = frame; } else { eth_buffer.head = frame; eth_buffer.tail = frame; } rtw_exit_critical(&lock, &irqL); } } struct eth_frame* retrieve_frame(void) { struct eth_frame *frame = NULL; _lock lock; _irqL irqL; rtw_enter_critical(&lock, &irqL); if(eth_buffer.head) { frame = eth_buffer.head; if(eth_buffer.head->next) { eth_buffer.head = eth_buffer.head->next; eth_buffer.head->prev = NULL; } else { eth_buffer.head = NULL; eth_buffer.tail = NULL; } } rtw_exit_critical(&lock, &irqL); return frame; } static void promisc_test(int duration, unsigned char len_used) { int ch; unsigned int start_time; struct eth_frame *frame; eth_buffer.head = NULL; eth_buffer.tail = NULL; wifi_enter_promisc_mode(); wifi_set_promisc(RTW_PROMISC_ENABLE, promisc_callback, len_used); for(ch = 1; ch <= 13; ch ++) { if(wifi_set_channel(ch) == 0) printf("\n\n\rSwitch to channel(%d)", ch); start_time = rtw_get_current_time(); while(1) { unsigned int current_time = rtw_get_current_time(); if(rtw_systime_to_ms(current_time - start_time) < (unsigned int)duration) { frame = retrieve_frame(); if(frame) { int i; printf("\n\rDA:"); for(i = 0; i < 6; i ++) printf(" %02x", frame->da[i]); printf(", SA:"); for(i = 0; i < 6; i ++) printf(" %02x", frame->sa[i]); printf(", len=%d", frame->len); printf(", RSSI=%d", frame->rssi); #if CONFIG_INIC_CMD_RSP if(inic_frame_tail){ if(inic_frame_cnt < MAX_INIC_FRAME_NUM){ memcpy(inic_frame_tail->da, frame->da, 6); memcpy(inic_frame_tail->sa, frame->sa, 6); inic_frame_tail->len = frame->len; inic_frame_tail++; inic_frame_cnt++; } } #endif rtw_free((void *) frame); } else rtw_mdelay_os(1); //delay 1 tick } else break; } #if CONFIG_INIC_CMD_RSP if(inic_frame){ inic_c2h_msg("ATWM", RTW_SUCCESS, (char *)inic_frame, sizeof(struct inic_eth_frame)*inic_frame_cnt); memset(inic_frame, '\0', sizeof(struct inic_eth_frame)*MAX_INIC_FRAME_NUM); inic_frame_tail = inic_frame; inic_frame_cnt = 0; rtw_msleep_os(10); } #endif } wifi_set_promisc(RTW_PROMISC_DISABLE, NULL, 0); while((frame = retrieve_frame()) != NULL) rtw_free((void *) frame); } static void promisc_callback_all(unsigned char *buf, unsigned int len, void* userdata) { struct eth_frame *frame = (struct eth_frame *) rtw_malloc(sizeof(struct eth_frame)); _lock lock; _irqL irqL; if(frame) { frame->prev = NULL; frame->next = NULL; #if defined(CONFIG_UNSUPPORT_PLCPHDR_RPT) && CONFIG_UNSUPPORT_PLCPHDR_RPT if(((ieee80211_frame_info_t *)userdata)->type == RTW_RX_UNSUPPORT){ //NOTICE: buf structure now is rtw_rx_info_t. frame->type = 0xFF; memset(frame->da, 0, 6); memset(frame->sa, 0, 6); } else #endif { memcpy(frame->da, buf+4, 6); memcpy(frame->sa, buf+10, 6); frame->type = *buf; } frame->len = len; /* * type is the first byte of Frame Control Field of 802.11 frame * If the from/to ds information is needed, type could be reused as follows: * frame->type = ((((ieee80211_frame_info_t *)userdata)->i_fc & 0x0100) == 0x0100) ? 2 : 1; * 1: from ds; 2: to ds */ frame->rssi = ((ieee80211_frame_info_t *)userdata)->rssi; rtw_enter_critical(&lock, &irqL); if(eth_buffer.tail) { eth_buffer.tail->next = frame; frame->prev = eth_buffer.tail; eth_buffer.tail = frame; } else { eth_buffer.head = frame; eth_buffer.tail = frame; } rtw_exit_critical(&lock, &irqL); } } static void promisc_test_all(int duration, unsigned char len_used) { int ch; unsigned int start_time; struct eth_frame *frame; eth_buffer.head = NULL; eth_buffer.tail = NULL; wifi_enter_promisc_mode(); wifi_set_promisc(RTW_PROMISC_ENABLE_2, promisc_callback_all, len_used); for(ch = 1; ch <= 13; ch ++) { if(wifi_set_channel(ch) == 0) printf("\n\n\rSwitch to channel(%d)", ch); start_time = rtw_get_current_time(); while(1) { unsigned int current_time = rtw_get_current_time(); if(rtw_systime_to_ms(current_time - start_time) < (unsigned int)duration) { frame = retrieve_frame(); if(frame) { int i; printf("\n\rTYPE: 0x%x, ", frame->type); printf("DA:"); for(i = 0; i < 6; i ++) printf(" %02x", frame->da[i]); printf(", SA:"); for(i = 0; i < 6; i ++) printf(" %02x", frame->sa[i]); printf(", len=%d", frame->len); printf(", RSSI=%d", frame->rssi); #if CONFIG_INIC_CMD_RSP if(inic_frame_tail){ if(inic_frame_cnt < MAX_INIC_FRAME_NUM){ memcpy(inic_frame_tail->da, frame->da, 6); memcpy(inic_frame_tail->sa, frame->sa, 6); inic_frame_tail->len = frame->len; inic_frame_tail->type = frame->type; inic_frame_tail++; inic_frame_cnt++; } } #endif rtw_free((void *) frame); } else rtw_mdelay_os(1); //delay 1 tick } else break; } #if CONFIG_INIC_CMD_RSP if(inic_frame){ inic_c2h_msg("ATWM", RTW_SUCCESS, (char *)inic_frame, sizeof(struct inic_eth_frame)*inic_frame_cnt); memset(inic_frame, '\0', sizeof(struct inic_eth_frame)*MAX_INIC_FRAME_NUM); inic_frame_tail = inic_frame; inic_frame_cnt = 0; rtw_msleep_os(10); } #endif } wifi_set_promisc(RTW_PROMISC_DISABLE, NULL, 0); while((frame = retrieve_frame()) != NULL) rtw_free((void *) frame); } void cmd_promisc(int argc, char **argv) { int duration; #if CONFIG_INIC_CMD_RSP inic_frame_tail = inic_frame = rtw_malloc(sizeof(struct inic_eth_frame)*MAX_INIC_FRAME_NUM); if(inic_frame == NULL){ inic_c2h_msg("ATWM", RTW_BUFFER_UNAVAILABLE_TEMPORARY, NULL, 0); return; } #endif #ifdef CONFIG_PROMISC wifi_init_packet_filter(); #endif if((argc == 2) && ((duration = atoi(argv[1])) > 0)) //promisc_test(duration, 0); promisc_test_all(duration, 0); else if((argc == 3) && ((duration = atoi(argv[1])) > 0) && (strcmp(argv[2], "with_len") == 0)) promisc_test(duration, 1); else printf("\n\rUsage: %s DURATION_SECONDS [with_len]", argv[0]); #if CONFIG_INIC_CMD_RSP if(inic_frame) rtw_free(inic_frame); inic_frame_tail = NULL; inic_frame_cnt = 0; #endif } #endif //#if CONFIG_WLAN
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/wifi_promisc.c
C
apache-2.0
12,827
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "FreeRTOS.h" #include "task.h" #include "main.h" #include "udp.h" #include <sockets.h> #include <lwip_netconf.h> #include <osdep_service.h> #include "wifi_simple_config_parser.h" #include "wifi_simple_config.h" #include "wifi_conf.h" #include "wifi_util.h" #include "platform_stdlib.h" #if (defined(CONFIG_EXAMPLE_UART_ATCMD) && CONFIG_EXAMPLE_UART_ATCMD) || (defined(CONFIG_EXAMPLE_SPI_ATCMD) && CONFIG_EXAMPLE_SPI_ATCMD) #include "at_cmd/atcmd_wifi.h" #endif #define SC_SOFTAP_EN 1 // on/off softAP mode #define STACKSIZE 512 #define LEAVE_ACK_EARLY 1 #if (CONFIG_LWIP_LAYER == 0) extern u32 _ntohl(u32 n); #endif #if LWIP_VERSION_MAJOR >= 2 #undef lwip_ntohl #define lwip_ntohl lwip_htonl #endif #if CONFIG_INIC_EN #undef SC_SOFTAP_EN #define SC_SOFTAP_EN 0 // disable softAP mode for iNIC applications #endif #if CONFIG_WLAN #if (CONFIG_INCLUDE_SIMPLE_CONFIG) #include "wifi/wifi_conf.h" int is_promisc_callback_unlock = 0; static int is_fixed_channel; int fixed_channel_num; unsigned char g_ssid[33]; int g_ssid_len; extern int promisc_get_fixed_channel( void *, u8 *, int* ); extern struct netif xnetif[NET_IF_NUM]; #if CONFIG_EXAMPLE_WLAN_FAST_CONNECT typedef int (*init_done_ptr)(void); extern init_done_ptr p_wlan_init_done_callback; extern int wlan_init_done_callback(void); #endif struct rtk_test_sc; static enum sc_result promisc_mode_ret = SC_SUCCESS; static int is_need_connect_to_AP = 0; static u8 mac_addr[6]; extern int get_sc_profile_fmt(void); extern int get_sc_profile_info(void *fmt_info_t); extern int get_sc_dsoc_info(void *dsoc_info_t); extern int rtl_dsoc_parse(u8 *mac_addr, u8 *buf, void *userdata, unsigned int *len); void filter1_add_enable(void); extern void remove_filter(void); void remove1_filter(void); static void sc_callback_handler(unsigned char *buf, unsigned int len, void* userdata); int fmt_val = 0; rtw_security_t security_type = -1; static _sema sc_dsoc_sema; struct fmt_info *fmt_info_t; struct dsoc_info *dsoc_info_t; int ssid_hidden; #if SC_SOFTAP_EN SC_softAP_decode_ctx *softAP_decode_ctx = NULL; static u8 simple_config_softAP_onAuth = 0; static u8 simple_config_softAP_channel = 6; static int softAP_socket = -1; #ifdef NOT_SUPPORT_5G static int simple_config_promisc_channel_tbl[] = {1,2,3,4,5,6,7,8,9,10,11,1,2,3,4,5,6,7,8,9,10,11,1}; #else static int simple_config_promisc_channel_tbl[] = { 1,2,3,4,5,6,7,8,9,10,11, 36,40,44,48,52,56,60,64,100,104,108,112,116,120,124,128,132,136,140,149,153,157,161,165, 1 }; #endif static int softAP_decode_success = -1; static _sema sc_sta_assoc_sema; static unsigned char softap_prefix[16] = {0}; #else #ifdef NOT_SUPPORT_5G static const int simple_config_promisc_channel_tbl[] = {1,2,3,4,5,6,7,8,9,10,11,12,13}; #else static const int simple_config_promisc_channel_tbl[] = { 1,2,3,4,5,6,7,8,9,10,11,12,13, 36,40,44,48,52,56,60,64,100,104,108,112,116,120,124,128,132,136,140,149,153,157,161,165 }; #endif #endif static _sema simple_config_finish_sema; #ifdef PACK_STRUCT_USE_INCLUDES #include "arch/bpstruct.h" #endif // support scan list function from APP, comment by default //#define SC_SCAN_SUPPORT PACK_STRUCT_BEGIN struct ack_msg { PACK_STRUCT_FIELD(u8_t flag); PACK_STRUCT_FIELD(u16_t length); PACK_STRUCT_FIELD(u8_t smac[6]); PACK_STRUCT_FIELD(u8_t status); PACK_STRUCT_FIELD(u16_t device_type); PACK_STRUCT_FIELD(u32_t device_ip); PACK_STRUCT_FIELD(u8_t device_name[64]); } PACK_STRUCT_STRUCT; PACK_STRUCT_END #ifdef PACK_STRUCT_USE_INCLUDES #include "arch/epstruct.h" #endif #define MULCAST_PORT (8864) #define SCAN_BUFFER_LENGTH (1024) #define SC_SOFTAP_TIMEOUT (60000) #define SSID_SOFTAP_TIMEOUT (30000) #ifndef WLAN0_NAME #define WLAN0_NAME "wlan0" #endif #define JOIN_SIMPLE_CONFIG (uint32_t)(1 << 8) extern uint32_t rtw_join_status; char simple_config_terminate = 0; int simple_config_result; static struct ack_msg *ack_content; struct rtk_test_sc *backup_sc_ctx; // listen scan command and ACK #ifdef SC_SCAN_SUPPORT static int pin_enable = 0; static int scan_start = 0; #ifdef RTW_PACK_STRUCT_USE_INCLUDES #include "pack_begin.h" #endif RTW_PACK_STRUCT_BEGIN struct ack_msg_scan { u8_t flag; u16_t length; u8_t smac[6]; u8_t status; u16_t device_type; u32_t device_ip; u8_t device_name[64]; u8_t pin_enabled; } RTW_PACK_STRUCT_STRUCT; RTW_PACK_STRUCT_END #ifdef RTW_PACK_STRUCT_USE_INCLUDES #include "pack_end.h" #endif static void set_device_name(char *device_name) { int pos = 0; memcpy(device_name, "ameba_", 6); for(int i = 0; i < 3; i++) { sprintf(device_name + 6 + pos, "%02x", xnetif[0].hwaddr[i + 3]); pos += 2; if(i != 2) device_name[6 + pos++] = ':'; } return; } void SC_scan_thread(void *para) { int sockfd_scan; struct sockaddr_in device_addr; unsigned char packet[256]; struct sockaddr from; struct sockaddr_in *from_sin = (struct sockaddr_in*) &from; socklen_t fromLen = sizeof(from); struct ack_msg_scan ack_msg; #ifdef RTW_PACK_STRUCT_USE_INCLUDES #include "pack_begin.h" #endif RTW_PACK_STRUCT_BEGIN struct scan_msg{ unsigned char flag; unsigned short length; unsigned char sec_level; unsigned char nonce[64]; unsigned char digest[16]; unsigned char smac[6]; unsigned short device_type; }; RTW_PACK_STRUCT_STRUCT; RTW_PACK_STRUCT_END #ifdef RTW_PACK_STRUCT_USE_INCLUDES #include "pack_end.h" #endif struct scan_msg *pMsg; if ((sockfd_scan = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { printf("SC scan socket error\n"); return; } memset(&device_addr, 0, sizeof(struct sockaddr_in)); device_addr.sin_family = AF_INET; device_addr.sin_port = htons(18864); device_addr.sin_addr.s_addr = INADDR_ANY; if (bind(sockfd_scan, (struct sockaddr *)&device_addr, sizeof(struct sockaddr)) == -1) { printf("SC scan bind error\n"); close(sockfd_scan); return; } memset(packet, 0, sizeof(packet)); // for now, no checking for the validity of received data, wf, 0225 while(1) { if((recvfrom(sockfd_scan, &packet, sizeof(packet), MSG_DONTWAIT, &from, &fromLen)) >= 0) { uint16_t from_port = ntohs(from_sin->sin_port); //printf("SC_scan: recv %d bytes from %d.%d.%d.%d:%d\n",packetLen, ip[0], ip[1], ip[2], ip[3], from_port); from_sin->sin_port = htons(8864); // send ACK for scan pMsg = (struct scan_msg *)packet; if(pMsg->flag == 0x00) // scan flag { ack_msg.flag = 0x21; ack_msg.length = sizeof(struct ack_msg_scan); ack_msg.status = 1; memcpy(ack_msg.smac, xnetif[0].hwaddr, 6); ack_msg.device_type = 0; ack_msg.device_ip = xnetif[0].ip_addr.addr; memset(ack_msg.device_name, 0, 64); set_device_name((char*)ack_msg.device_name); // set the device_name to: ameba_xxxxxx(last 3 bytes of MAC) ack_msg.pin_enabled = pin_enable; for(int i = 0; i < 3;i++) { int ret = sendto(sockfd_scan,(unsigned char *)&ack_msg,sizeof(struct ack_msg_scan),0,(struct sockaddr *)&from, fromLen); if(ret < 0) printf("send ACK for scan fail\n"); //else //printf("send %d bytes of ACK to scan\n", ret); } } else continue; } vTaskDelay(500); } } void SC_listen_ACK_scan() { if(xTaskCreate(SC_scan_thread, ((const char*)"SC_scan_thread"), 512, NULL, tskIDLE_PRIORITY + 1, NULL) != pdPASS) printf("\n\r%s xTaskCreate(SC_scan_thread) failed", __FUNCTION__); } #endif void SC_set_ack_content(void) { memset(ack_content, 0, sizeof(struct ack_msg)); ack_content->flag = 0x20; ack_content->length = htons(sizeof(struct ack_msg)-3); memcpy(ack_content->smac, xnetif[0].hwaddr, 6); ack_content->status = 0; ack_content->device_type = 0; #if LWIP_VERSION_MAJOR >= 2 ack_content->device_ip = ip4_addr_get_u32(ip_2_ip4(netif_ip_addr4(&xnetif[0]))); #else ack_content->device_ip = xnetif[0].ip_addr.addr; #endif memset(ack_content->device_name, 0, 64); } int SC_send_simple_config_ack(u8 round) { #if CONFIG_LWIP_LAYER int ack_transmit_round, ack_num_each_sec; int ack_socket; //int sended_data = 0; struct sockaddr_in to_addr; #if LEAVE_ACK_EARLY u8 check_phone_ack = 0; #endif SC_set_ack_content(); ack_socket = socket(PF_INET, SOCK_DGRAM, IP_PROTO_UDP); if (ack_socket == -1) { return -1; } #if LEAVE_ACK_EARLY else { struct sockaddr_in bindAddr; bindAddr.sin_family = AF_INET; bindAddr.sin_port = htons(8864); bindAddr.sin_addr.s_addr = INADDR_ANY; if(bind(ack_socket, (struct sockaddr *) &bindAddr, sizeof(bindAddr)) == 0) check_phone_ack = 1; } #endif printf("\nSending simple config ack\n"); FD_ZERO(&to_addr); to_addr.sin_family = AF_INET; to_addr.sin_port = htons(8864); to_addr.sin_addr.s_addr = (backup_sc_ctx->ip_addr); for (ack_transmit_round = 0;ack_transmit_round < round; ack_transmit_round++) { for (ack_num_each_sec = 0;ack_num_each_sec < 20; ack_num_each_sec++) { //sended_data = sendto(ack_socket, (unsigned char *)ack_content, sizeof(struct ack_msg), 0, (struct sockaddr *) &to_addr, sizeof(struct sockaddr)); //printf("\r\nAlready send %d bytes data\n", sended_data); vTaskDelay(50); /* delay 50 ms */ #if LEAVE_ACK_EARLY if(check_phone_ack) { unsigned char packet[100]; int packetLen; struct sockaddr from; struct sockaddr_in *from_sin = (struct sockaddr_in*) &from; socklen_t fromLen = sizeof(from); if((packetLen = recvfrom(ack_socket, &packet, sizeof(packet), MSG_DONTWAIT, &from, &fromLen)) >= 0) { uint8_t *ip = (uint8_t *) &from_sin->sin_addr.s_addr; uint16_t from_port = ntohs(from_sin->sin_port); printf("recv %d bytes from %d.%d.%d.%d:%d at round=%d, num=%d\n", packetLen, ip[0], ip[1], ip[2], ip[3], from_port, ack_transmit_round, ack_num_each_sec); goto leave_ack; } } #endif } } leave_ack: close(ack_socket); #endif #if defined(CONFIG_INIC_CMD_RSP) && CONFIG_INIC_CMD_RSP extern unsigned int inic_sc_ip_addr; inic_sc_ip_addr = backup_sc_ctx->ip_addr; inic_c2h_wifi_info("ATWQ", RTW_SUCCESS); #endif return 0; } static int SC_check_and_show_connection_info(void) { rtw_wifi_setting_t setting; #if CONFIG_LWIP_LAYER int ret = -1; int retry = 0; vTaskPrioritySet(NULL, tskIDLE_PRIORITY + 3); while(retry < 2) { /* If not rise priority, LwIP DHCP may timeout */ /* Start DHCP Client */ ret = LwIP_DHCP(0, DHCP_START); if (ret == DHCP_ADDRESS_ASSIGNED) break; else retry++; } vTaskPrioritySet(NULL, tskIDLE_PRIORITY + 1); #endif #if !(defined(CONFIG_EXAMPLE_UART_ATCMD) && CONFIG_EXAMPLE_UART_ATCMD) || (defined(CONFIG_EXAMPLE_SPI_ATCMD) && CONFIG_EXAMPLE_SPI_ATCMD) wifi_get_setting(WLAN0_NAME, &setting); wifi_show_setting(WLAN0_NAME, &setting); #endif #if CONFIG_LWIP_LAYER if (ret != DHCP_ADDRESS_ASSIGNED) return SC_DHCP_FAIL; else #endif return SC_SUCCESS; } static void check_and_set_security_in_connection(rtw_security_t security_mode, rtw_network_info_t *wifi) { if (security_mode == RTW_SECURITY_WPA2_AES_PSK) { printf("\r\nwifi->security_type = RTW_SECURITY_WPA2_AES_PSK\n"); wifi->security_type = RTW_SECURITY_WPA2_AES_PSK; } else if (security_mode == RTW_SECURITY_WEP_PSK) { printf("\r\nwifi->security_type = RTW_SECURITY_WEP_PSK\n"); wifi->security_type = RTW_SECURITY_WEP_PSK; wifi->key_id = 0; } else if (security_mode == RTW_SECURITY_WPA_AES_PSK) { printf("\r\nwifi->security_type = RTW_SECURITY_WPA_AES_PSK\n"); wifi->security_type = RTW_SECURITY_WPA_AES_PSK; } else { printf("\r\nwifi->security_type = RTW_SECURITY_OPEN\n"); wifi->security_type = RTW_SECURITY_OPEN; } } #if SC_SOFTAP_EN static int SC_softAP_find_ap_from_scan_buf(char*buf, int buflen, char *target_ssid, void *user_data) { rtw_wifi_setting_t *pwifi = (rtw_wifi_setting_t *)user_data; int plen = 0; while(plen < buflen){ u8 len, ssid_len, security_mode; char *ssid; // len offset = 0 len = (int)*(buf + plen); // check end if(len == 0) break; // ssid offset = 14 ssid_len = len - 14; ssid = buf + plen + 14 ; if((ssid_len == strlen(target_ssid)) && (!memcmp(ssid, target_ssid, ssid_len))) { strcpy((char*)pwifi->ssid, target_ssid); // channel offset = 13 pwifi->channel = *(buf + plen + 13); // security_mode offset = 11 security_mode = (u8)*(buf + plen + 11); if(security_mode == IW_ENCODE_ALG_NONE) pwifi->security_type = RTW_SECURITY_OPEN; else if(security_mode == IW_ENCODE_ALG_WEP) pwifi->security_type = RTW_SECURITY_WEP_PSK; else if(security_mode == IW_ENCODE_ALG_CCMP) pwifi->security_type = RTW_SECURITY_WPA2_AES_PSK; break; } plen += len; } return 0; } static int SC_softAP_get_ap_security_mode(IN char * ssid, OUT rtw_security_t *security_mode) { rtw_wifi_setting_t wifi; u32 scan_buflen = 1000; memset(&wifi, 0, sizeof(wifi)); if(wifi_scan_networks_with_ssid(SC_softAP_find_ap_from_scan_buf, (void*)&wifi, scan_buflen, ssid, strlen(ssid)) != RTW_SUCCESS){ printf("Wifi scan failed!\n"); return 0; } if(strcmp((char const*)wifi.ssid, ssid) == 0){ *security_mode = wifi.security_type; return 1; } return 0; } #endif // end of SC_SOFTAP_EN int sc_set_val1(rtw_network_info_t *wifi) { int ret = -1; if (fmt_val == 1) { fmt_info_t = malloc(sizeof(struct fmt_info)); memset(fmt_info_t, 0, sizeof(struct fmt_info)); get_sc_profile_info(fmt_info_t); fixed_channel_num = fmt_info_t->fmt_channel[1]; ssid_hidden = fmt_info_t->fmt_hidden[0]; //printf("\nhidden: %d\n", ssid_hidden); //printf("\nchannel: %d\n",fixed_channel_num); //printf(MAC_FMT, MAC_ARG(fmt_info_t->fmt_bssid)); rtw_memcpy(mac_addr, fmt_info_t->fmt_bssid, 6); memset(backup_sc_ctx->ssid, 0, sizeof(backup_sc_ctx->ssid)); #if SC_SOFTAP_EN wifi->ssid.len = strlen((const char *)backup_sc_ctx->ssid); rtw_memcpy(wifi->ssid.val, backup_sc_ctx->ssid, wifi->ssid.len); wifi->ssid.val[wifi->ssid.len] = 0; #else if(memcmp(mac_addr, g_bssid, 6) == 0){ rtw_memcpy(backup_sc_ctx->ssid, g_ssid, g_ssid_len); wifi->ssid.len = strlen(backup_sc_ctx->ssid); rtw_memcpy(wifi->ssid.val, backup_sc_ctx->ssid, wifi->ssid.len); wifi->ssid.val[wifi->ssid.len] = 0; printf("using ssid from profile and scan result\n"); } else{ rtw_memcpy(g_bssid, mac_addr, 6); } #endif free(fmt_info_t); ret = 0; } return ret; } int get_connection_info_from_profile(rtw_security_t security_mode, rtw_network_info_t *wifi) { printf("\r\n======= Connection Information =======\n"); #if !SC_SOFTAP_EN check_and_set_security_in_connection(security_mode, wifi); #endif wifi->password = backup_sc_ctx->password; wifi->password_len = (int)strlen((char const *)backup_sc_ctx->password); #if SC_SOFTAP_EN // reconfigure the security mode, when under softAP mode; do not support WEP now if(softAP_decode_success == 0) { if(sc_set_val1(wifi) == -1) { wifi->ssid.len = strlen((char const*)backup_sc_ctx->ssid); rtw_memcpy(wifi->ssid.val, backup_sc_ctx->ssid, wifi->ssid.len); wifi->ssid.val[wifi->ssid.len] = 0; if(0 == SC_softAP_get_ap_security_mode((char*)wifi->ssid.val, &wifi->security_type)) { if(wifi->password_len) wifi->security_type = RTW_SECURITY_WPA2_AES_PSK; else wifi->security_type = RTW_SECURITY_OPEN; } } if (wifi->security_type == RTW_SECURITY_WPA2_AES_PSK) { printf("\r\nwifi->security_type = RTW_SECURITY_WPA2_AES_PSK\n"); } else if (wifi->security_type == RTW_SECURITY_WEP_PSK) { printf("\r\nwifi->security_type = RTW_SECURITY_WEP_PSK\n"); wifi->key_id = 0; } else if (wifi->security_type == RTW_SECURITY_WPA_AES_PSK) { printf("\r\nwifi->security_type = RTW_SECURITY_WPA_AES_PSK\n"); } else { printf("\r\nwifi->security_type = RTW_SECURITY_OPEN\n"); } goto ssid_set_done; } else check_and_set_security_in_connection(security_mode, wifi); #endif /* 1.both scanned g_ssid and ssid from profile are null, return fail */ if ((0 == g_ssid_len) && (0 == strlen((char const*)backup_sc_ctx->ssid))) { printf("no ssid info found, connect will fail\n"); return -1; } if(sc_set_val1(wifi) == 0) { goto ssid_set_done; } /* g_ssid and ssid from profile are same, enter connect and retry */ if (0 == strcmp((char const*)backup_sc_ctx->ssid, (char const*)g_ssid)) { wifi->ssid.len = strlen((char const*)backup_sc_ctx->ssid); rtw_memcpy(wifi->ssid.val, backup_sc_ctx->ssid, wifi->ssid.len); wifi->ssid.val[wifi->ssid.len] = 0; printf("using ssid from profile and scan result\n"); goto ssid_set_done; } /* if there is profile, but g_ssid and profile are different, using profile to connect and retry */ if (strlen((char const*)backup_sc_ctx->ssid) > 0) { wifi->ssid.len = strlen((char const*)backup_sc_ctx->ssid); rtw_memcpy(wifi->ssid.val, backup_sc_ctx->ssid, wifi->ssid.len); wifi->ssid.val[wifi->ssid.len] = 0; printf("using ssid only from profile\n"); goto ssid_set_done; } /* if there is no profile but have scanned ssid, using g_ssid to connect and retry (maybe ssid is right and password is wrong) */ if (g_ssid_len > 0) { wifi->ssid.len = g_ssid_len; rtw_memcpy(wifi->ssid.val, g_ssid, wifi->ssid.len); wifi->ssid.val[wifi->ssid.len] = 0; printf("using ssid only from scan result\n"); goto ssid_set_done; } ssid_set_done: if(wifi->security_type == RTW_SECURITY_WEP_PSK) { if(wifi->password_len == 10) { u32 p[5] = {0}; u8 pwd[6], i = 0; sscanf((const char*)backup_sc_ctx->password, "%02x%02x%02x%02x%02x", &p[0], &p[1], &p[2], &p[3], &p[4]); for(i=0; i< 5; i++) pwd[i] = (u8)p[i]; pwd[5] = '\0'; memset(backup_sc_ctx->password, 0, 65); strcpy((char*)backup_sc_ctx->password, (char*)pwd); wifi->password_len = 5; }else if(wifi->password_len == 26){ u32 p[13] = {0}; u8 pwd[14], i = 0; sscanf((const char*)backup_sc_ctx->password, "%02x%02x%02x%02x%02x%02x%02x"\ "%02x%02x%02x%02x%02x%02x", &p[0], &p[1], &p[2], &p[3], &p[4],\ &p[5], &p[6], &p[7], &p[8], &p[9], &p[10], &p[11], &p[12]); for(i=0; i< 13; i++) pwd[i] = (u8)p[i]; pwd[13] = '\0'; memset(backup_sc_ctx->password, 0, 64); strcpy((char*)backup_sc_ctx->password, (char*)pwd); wifi->password_len = 13; } } printf("\r\nwifi.password = %s\n", wifi->password); printf("\r\nwifi.password_len = %d\n", wifi->password_len); printf("\r\nwifi.ssid = %s\n", wifi->ssid.val); printf("\r\nwifi.ssid_len = %d\n", wifi->ssid.len); printf("\r\nwifi.channel = %d\n", fixed_channel_num); printf("\r\n===== start to connect target AP =====\n"); return 0; } #pragma pack(1) struct scan_with_ssid_result { u8 len; /* len of a memory area store ap info */ u8 mac[ETH_ALEN]; int rssi; u8 sec_mode; u8 password_id; u8 channel; //char ssid[65]; }; struct sc_ap_info { char *ssid; int ssid_len; }; rtw_security_t SC_translate_iw_security_mode(u8 security_type) { rtw_security_t security_mode = RTW_SECURITY_UNKNOWN; switch (security_type) { case IW_ENCODE_ALG_NONE: security_mode = RTW_SECURITY_OPEN; break; case IW_ENCODE_ALG_WEP: security_mode = RTW_SECURITY_WEP_PSK; break; case IW_ENCODE_ALG_CCMP: security_mode = RTW_SECURITY_WPA2_AES_PSK; break; default: printf("error: security type not supported\n"); break; }; return security_mode; } /* scan buf format: len mac rssi sec wps channel ssid 1B 6B 4B 1B 1B 1B (len - 14)B */ enum sc_result SC_parse_scan_result_and_connect(scan_buf_arg* scan_buf, rtw_network_info_t *wifi) { struct scan_with_ssid_result scan_result; char *buf = scan_buf->buf; int buf_len = scan_buf->buf_len; char ssid[65]; int ssid_len = 0 ; int parsed_len = 0; u8 scan_channel = 0; int i = 0; enum sc_result ret; u8 pscan_config = PSCAN_ENABLE | PSCAN_SIMPLE_CONFIG; memset((void*)&scan_result, 0, sizeof(struct scan_with_ssid_result)); /* if wifi_is_connected_to_ap and we run here, ther will be hardfault(caused by auto reconnect) */ printf("Scan result got, start to connect AP with scanned bssid\n"); while (1) { memcpy(&scan_result, buf, sizeof(struct scan_with_ssid_result)); /* len maybe 3*/ if (scan_result.len < sizeof(struct scan_with_ssid_result)) { printf("length = %d, too small!\n",scan_result.len); goto sc_connect_wifi_fail; } /* set ssid */ memset(ssid, 0, 65); ssid_len = scan_result.len - sizeof(struct scan_with_ssid_result); memcpy(ssid, buf + sizeof(struct scan_with_ssid_result), ssid_len); /* run here means there is a match */ if (ssid_len == wifi->ssid.len) { if (memcmp(ssid, wifi->ssid.val, ssid_len) == 0) { printf("Connecting to MAC=%02x:%02x:%02x:%02x:%02x:%02x, ssid = %s, SEC=%d\n", scan_result.mac[0], scan_result.mac[1], scan_result.mac[2], scan_result.mac[3], scan_result.mac[4], scan_result.mac[5], ssid, scan_result.sec_mode); scan_channel = scan_result.channel; // translate wep key if get_connection_info_from_profile() does not do it due to wrong security form locked ssid for dual band router if(SC_translate_iw_security_mode(scan_result.sec_mode) == RTW_SECURITY_WEP_PSK) { if(wifi->password_len == 10) { u32 p[5] = {0}; u8 pwd[6], i = 0; sscanf((const char*)backup_sc_ctx->password, "%02x%02x%02x%02x%02x", &p[0], &p[1], &p[2], &p[3], &p[4]); for(i=0; i< 5; i++) pwd[i] = (u8)p[i]; pwd[5] = '\0'; memset(backup_sc_ctx->password, 0, 65); strcpy((char*)backup_sc_ctx->password, (char*)pwd); wifi->password_len = 5; }else if(wifi->password_len == 26){ u32 p[13] = {0}; u8 pwd[14], i = 0; sscanf((const char*)backup_sc_ctx->password, "%02x%02x%02x%02x%02x%02x%02x"\ "%02x%02x%02x%02x%02x%02x", &p[0], &p[1], &p[2], &p[3], &p[4],\ &p[5], &p[6], &p[7], &p[8], &p[9], &p[10], &p[11], &p[12]); for(i=0; i< 13; i++) pwd[i] = (u8)p[i]; pwd[13] = '\0'; memset(backup_sc_ctx->password, 0, 64); strcpy((char*)backup_sc_ctx->password, (char*)pwd); wifi->password_len = 13; } } /* try 3 times to connect */ for (i = 0; i < 3; i++) { if(wifi_set_pscan_chan(&scan_channel, &pscan_config, 1) < 0){ printf("\n\rERROR: wifi set partial scan channel fail"); ret = SC_TARGET_CHANNEL_SCAN_FAIL; goto sc_connect_wifi_fail; } rtw_join_status = 0; ret = (enum sc_result) wifi_connect_bssid(scan_result.mac, (char*)wifi->ssid.val, SC_translate_iw_security_mode(scan_result.sec_mode), (char*)wifi->password, ETH_ALEN, wifi->ssid.len, wifi->password_len, 0, NULL); if (ret == (enum sc_result)RTW_SUCCESS) goto sc_connect_wifi_success; } } } buf = buf + scan_result.len; parsed_len += scan_result.len; if (parsed_len >= buf_len) { printf("parsed=%d, total = %d\n", parsed_len, buf_len); break; } } sc_connect_wifi_success: printf("%s success\n", __FUNCTION__); return ret; sc_connect_wifi_fail: printf("%s fail\n", __FUNCTION__); return ret; } /* When BSSID_CHECK_SUPPORT is not set, there will be problems: 1.AP1 and AP2 (different SSID) both forward simple config packets, profile is from AP2, but Ameba connect with AP1 2.AP1 and AP2 (same SSID, but different crypto or password), both forward simple config packets, profile is from AP2, but Ameba connect with AP1 3. ... fix: using SSID to query matched BSSID(s) in scan result, traverse and connect. Consideration: 1.Only take ssid and password 2.Assume they have different channel. 3.Assume they have different encrypt methods */ int SC_connect_to_candidate_AP (rtw_network_info_t *wifi){ int ret; scan_buf_arg scan_buf; volatile int scan_cnt = 0; char *ssid = (char*)wifi->ssid.val; int ssid_len = wifi->ssid.len; printf("\nConnect with SSID=%s password=%s\n", wifi->ssid.val, wifi->password); /* scan buf init */ scan_buf.buf_len = 1000; scan_buf.buf = (char*)pvPortMalloc(scan_buf.buf_len); if(!scan_buf.buf){ printf("\n\rERROR: Can't malloc memory"); return RTW_NOMEM; } /* set ssid_len, ssid to scan buf */ memset(scan_buf.buf, 0, scan_buf.buf_len); if(ssid && ssid_len > 0 && ssid_len <= 32){ memcpy(scan_buf.buf, &ssid_len, sizeof(int)); memcpy(scan_buf.buf+sizeof(int), ssid, ssid_len); } /* call wifi scan to scan */ if((scan_cnt = (wifi_scan(RTW_SCAN_TYPE_ACTIVE, RTW_BSS_TYPE_ANY, &scan_buf))) < 0){ printf("\n\rERROR: wifi scan failed"); ret = RTW_ERROR; }else{ ret = SC_parse_scan_result_and_connect(&scan_buf, wifi); } if(scan_buf.buf) vPortFree(scan_buf.buf); return ret; } rtw_security_t SC_translate_security(u8 security_type) { rtw_security_t security_mode = RTW_SECURITY_UNKNOWN; switch (security_type) { case RTW_ENCRYPTION_OPEN: security_mode = RTW_SECURITY_OPEN; break; case RTW_ENCRYPTION_WEP40: case RTW_ENCRYPTION_WEP104: security_mode = RTW_SECURITY_WEP_PSK; break; case RTW_ENCRYPTION_WPA_TKIP: case RTW_ENCRYPTION_WPA_AES: case RTW_ENCRYPTION_WPA2_TKIP: case RTW_ENCRYPTION_WPA2_AES: case RTW_ENCRYPTION_WPA2_MIXED: security_mode = RTW_SECURITY_WPA2_AES_PSK; break; case RTW_ENCRYPTION_UNKNOWN: case RTW_ENCRYPTION_UNDEF: default: printf( "unknow security mode,connect fail\n"); } return security_mode; } static void sc_callback_handler(unsigned char *buf, unsigned int len, void* userdata) { int ret = -1; taskENTER_CRITICAL(); ret = rtl_dsoc_parse(mac_addr, buf, userdata, &len); taskEXIT_CRITICAL(); if(ret == 0) { //printf("\nhandler part\n"); rtw_up_sema(&sc_dsoc_sema); return; } } int sc_set_val2(rtw_network_info_t *wifi) { int ret = 1; if(fmt_val == 1){ #if !SC_SOFTAP_EN remove_filter(); filter1_add_enable(); #endif wifi_set_channel(fixed_channel_num); rtw_init_sema(&sc_dsoc_sema, 0); if(wifi_set_promisc(RTW_PROMISC_ENABLE_2, sc_callback_handler, 1) != 0) { printf("\nset promisc failed\n"); rtw_free_sema(&sc_dsoc_sema); ret = -1; } if(rtw_down_timeout_sema(&sc_dsoc_sema, SSID_SOFTAP_TIMEOUT) == RTW_FALSE) { printf("\nsc callback failed\n"); wifi_set_promisc(RTW_PROMISC_DISABLE, NULL, 0); rtw_free_sema(&sc_dsoc_sema); ret = -1; } else{ wifi_set_promisc(RTW_PROMISC_DISABLE, NULL, 0); dsoc_info_t = malloc(sizeof(struct dsoc_info)); memset(dsoc_info_t, 0, sizeof(struct dsoc_info)); get_sc_dsoc_info(dsoc_info_t); wifi->ssid.len = dsoc_info_t->dsoc_length; rtw_memcpy(wifi->ssid.val, dsoc_info_t->dsoc_ssid, wifi->ssid.len); wifi->ssid.val[wifi->ssid.len] = 0; #if SC_SOFTAP_EN if(0 == SC_softAP_get_ap_security_mode((char *)wifi->ssid.val, &wifi->security_type)) { if(wifi->password_len) wifi->security_type = RTW_SECURITY_WPA2_AES_PSK; else wifi->security_type = RTW_SECURITY_OPEN; } #endif rtw_free_sema(&sc_dsoc_sema); free(dsoc_info_t); ret = 1; } #if !SC_SOFTAP_EN remove1_filter(); #endif } return ret; } enum sc_result SC_connect_to_AP(void) { enum sc_result ret = SC_ERROR; int max_retry = 5, retry = 0; rtw_security_t security_mode; rtw_network_info_t wifi = {0}; #ifdef NOT_SUPPORT_5G u8 scan_channel; u8 pscan_config; if(!(fixed_channel_num == 0)){ scan_channel = fixed_channel_num; } pscan_config = PSCAN_ENABLE | PSCAN_SIMPLE_CONFIG; #endif #if SC_SOFTAP_EN if(softAP_decode_success != 0) #endif { security_mode = SC_translate_security(g_security_mode); g_security_mode = 0xff;//clear it } fmt_val = get_sc_profile_fmt(); if (-1 == get_connection_info_from_profile(security_mode, &wifi)) { ret = SC_CONTROLLER_INFO_PARSE_FAIL; goto wifi_connect_fail; } #if CONFIG_AUTO_RECONNECT /* disable auto reconnect */ wifi_set_autoreconnect(0); #endif #if 1 /* optimization: get g_bssid to connect with only pscan */ while (1) { #if SC_SOFTAP_EN if(softAP_decode_success != 0) #endif { ret = (enum sc_result)sc_set_val2(&wifi); if(ret == 1) { // for dual band router, locked channel may not be target channel #ifdef NOT_SUPPORT_5G if(wifi_set_pscan_chan(&scan_channel, &pscan_config, 1) < 0){ printf("\n\rERROR: wifi set partial scan channel fail"); ret = SC_TARGET_CHANNEL_SCAN_FAIL; goto wifi_connect_fail; } #endif rtw_join_status = 0; ret = (enum sc_result)wifi_connect_bssid(g_bssid, (char*)wifi.ssid.val, wifi.security_type, (char*)wifi.password, ETH_ALEN, wifi.ssid.len, wifi.password_len, wifi.key_id, NULL); } else goto wifi_connect_fail; } #if SC_SOFTAP_EN // when configured by softAP mode else { ret = (enum sc_result)sc_set_val2(&wifi); if(ret == 1) { rtw_join_status = 0; ret = (enum sc_result)wifi_connect((char*)wifi.ssid.val, wifi.security_type, (char*)wifi.password, wifi.ssid.len, wifi.password_len, 0, NULL); } else goto wifi_connect_fail; } #endif if (ret ==(enum sc_result) RTW_SUCCESS) goto wifi_connect_success; if (retry == max_retry) { printf("connect fail with bssid, try ssid instead\n"); break; } retry ++; } #endif #if 1 /* when optimization fail: if connect with bssid fail because of we have connect to the wrong AP */ ret = (enum sc_result)SC_connect_to_candidate_AP(&wifi); if ((enum sc_result)RTW_SUCCESS == ret) { goto wifi_connect_success; } else { ret = SC_JOIN_BSS_FAIL; goto wifi_connect_fail; } #endif wifi_connect_success: ret = (enum sc_result)SC_check_and_show_connection_info(); goto wifi_connect_end; wifi_connect_fail: printf("SC_connect_to_AP failed\n"); goto wifi_connect_end; wifi_connect_end: #if CONFIG_AUTO_RECONNECT wifi_config_autoreconnect(1, 10, 5); #endif return ret; } void simple_config_callback(unsigned char *buf, unsigned int len, void* userdata) { int ret = 0; unsigned char *da = NULL; unsigned char *sa = NULL; #if SC_SOFTAP_EN ret = rtl_pre_parse(mac_addr, buf, userdata, &da, &sa, &len); if(ret == -1) return; else if(ret == 1) simple_config_softAP_onAuth = 1; else #else da = buf; sa = buf + ETH_ALEN; #endif { taskENTER_CRITICAL(); if (is_promisc_callback_unlock == 1) { simple_config_result = rtk_start_parse_packet(da, sa, len, userdata, (void *)backup_sc_ctx); } taskEXIT_CRITICAL(); } } static unsigned int simple_config_cmd_start_time; static unsigned int simple_config_cmd_current_time; extern int simple_config_status; extern void rtk_restart_simple_config(void); extern void rtk_sc_deinit(void); void init_simple_config_lib_config(struct simple_config_lib_config* config) { config->free_fn = (simple_config_free_fn)rtw_mfree; config->malloc_fn = (simple_config_malloc_fn)rtw_malloc; config->memcmp_fn = (simple_config_memcmp_fn)memcmp; config->memcpy_fn = (simple_config_memcpy_fn)memcpy; config->memset_fn = (simple_config_memset_fn)memset; config->printf_fn = (simple_config_printf_fn)printf; config->strcpy_fn = (simple_config_strcpy_fn)strcpy; config->strlen_fn = (simple_config_strlen_fn)strlen; config->zmalloc_fn = (simple_config_zmalloc_fn)rtw_zmalloc; #if CONFIG_LWIP_LAYER config->ntohl_fn = lwip_ntohl; #else config->ntohl_fn = _ntohl; #endif config->is_promisc_callback_unlock = &is_promisc_callback_unlock; } int init_test_data(char *custom_pin_code) { #if (CONFIG_INCLUDE_SIMPLE_CONFIG) if(rtw_join_status & JOIN_SIMPLE_CONFIG){ printf("\r\npromisc mode is running!"); return -1; }else rtw_join_status |= JOIN_SIMPLE_CONFIG; is_promisc_callback_unlock = 1; is_fixed_channel = 0; fixed_channel_num = 0; simple_config_result = 0; rtw_memset(g_ssid, 0, 33); g_ssid_len = 0; simple_config_cmd_start_time = xTaskGetTickCount(); promisc_mode_ret = SC_SUCCESS; is_need_connect_to_AP = 0; memset(mac_addr, 0, sizeof(mac_addr)); ssid_hidden = 0; #if SC_SOFTAP_EN simple_config_softAP_onAuth = 0; softAP_socket = -1; softAP_decode_success = -1; rtw_init_sema(&sc_sta_assoc_sema, 0); softAP_decode_ctx = pvPortMalloc(sizeof(SC_softAP_decode_ctx)); if(!softAP_decode_ctx) { printf("malloc softAP_decode_cxt fail"); return -1; } else memset(softAP_decode_ctx, 0, sizeof(SC_softAP_decode_ctx)); #endif rtw_init_sema(&simple_config_finish_sema, 0); if (ack_content != NULL) { vPortFree(ack_content); ack_content = NULL; } ack_content = pvPortMalloc(sizeof(struct ack_msg)); if (!ack_content) { printf("\n\rrtk_sc_init fail by allocate ack\n"); } memset(ack_content, 0, sizeof(struct ack_msg)); #ifdef SC_SCAN_SUPPORT if(custom_pin_code) pin_enable = 1; else pin_enable = 0; #endif backup_sc_ctx = pvPortMalloc(sizeof(struct rtk_test_sc)); if (!backup_sc_ctx) { printf("\n\r[Mem]malloc SC context fail\n"); } else { memset(backup_sc_ctx, 0, sizeof(struct rtk_test_sc)); struct simple_config_lib_config lib_config; init_simple_config_lib_config(&lib_config); //custom_pin_code can be null if (rtk_sc_init(custom_pin_code, &lib_config) < 0) { printf("\n\rRtk_sc_init fail\n"); } else { return 0; } } #else printf("\n\rPlatform no include simple config now\n"); #endif return -1; } void deinit_test_data(void){ #if (CONFIG_INCLUDE_SIMPLE_CONFIG) rtk_sc_deinit(); if (backup_sc_ctx != NULL) { vPortFree(backup_sc_ctx); backup_sc_ctx = NULL; } if (ack_content != NULL) { vPortFree(ack_content); ack_content = NULL; } #if SC_SOFTAP_EN if(softAP_decode_ctx != NULL) { vPortFree(softAP_decode_ctx); softAP_decode_ctx = NULL; } rtw_free_sema(&sc_sta_assoc_sema); #endif rtw_join_status = 0;//clear simple config status rtw_free_sema(&simple_config_finish_sema); #endif } void stop_simple_config(void) { simple_config_terminate = 1; } #if SC_SOFTAP_EN // use new ssid generation function static void simpleConfig_get_softAP_profile(unsigned char *SimpleConfig_SSID, unsigned char *SimpleConfig_password) { char MAC_sum_complement = 0; memcpy(mac_addr, LwIP_GetMAC(&xnetif[0]), 6); if(mac_addr == NULL) { printf("Get MAC error\n"); return; } // copy MAC to softAP decode ctx memcpy(softAP_decode_ctx -> mac, mac_addr, 6); MAC_sum_complement = -(mac_addr[3] + mac_addr[4] + mac_addr[5]); if(strlen((char const*)softap_prefix) > 0) sprintf((char*)SimpleConfig_SSID, "%s-%02X%02X%02X00%02X", softap_prefix, mac_addr[3], mac_addr[4], mac_addr[5], (MAC_sum_complement & 0xff)); else sprintf((char*)SimpleConfig_SSID, "@RSC-%02X%02X%02X00%02X", mac_addr[3], mac_addr[4], mac_addr[5], (MAC_sum_complement & 0xff)); memcpy(SimpleConfig_password, "12345678", 8); printf("softAP ssid: %s, password: %s\n", SimpleConfig_SSID, SimpleConfig_password); return; } static void sc_sta_asso_cb( char* buf, int buf_len, int flags, void* userdata) { /* To avoid gcc warnings */ ( void ) buf; ( void ) buf_len; ( void ) flags; ( void ) userdata; rtw_up_sema(&sc_sta_assoc_sema); return; } static void simple_config_kick_STA(void) { int client_idx = 0; struct { int count; rtw_mac_t mac_list[AP_STA_NUM]; } client_info; memset(&client_info, 0, sizeof(client_info)); client_info.count = AP_STA_NUM; wifi_get_associated_client_list(&client_info, sizeof(client_info)); while(client_idx < client_info.count) { unsigned char *pmac = client_info.mac_list[client_idx].octet; printf("kick out sta: %02x:%02x:%02x:%02x:%02x:%02x\n", pmac[0],pmac[1],pmac[2],pmac[3],pmac[4],pmac[5]); wext_del_station("wlan0", pmac); ++client_idx; } return; } // triggered by sta association event static int simple_config_softap_config(void) { int ret = -1; struct sockaddr from; socklen_t fromLen = sizeof(from); unsigned char recv_buf[128]; int client_fd = -1; int tcp_err = 0; SC_softAP_status decode_ret = SOFTAP_ERROR; // block 10s to receive udp packet from smart phone client_fd = accept(softAP_socket, (struct sockaddr *) &from, &fromLen); if(client_fd < 0) { printf("no client connection, timeout\n"); //kick the sta, wf, 0817 simple_config_kick_STA(); return -1; } //printf("accept a new client: %d\n", client_fd); while(1) { int sock_err = 0; size_t err_len = sizeof(sock_err); vTaskDelay(10); ret = recv(client_fd, recv_buf, sizeof(recv_buf), MSG_DONTWAIT); getsockopt(client_fd, SOL_SOCKET, SO_ERROR, &sock_err, &err_len); // ret == -1 and socket error == EAGAIN when no data received for nonblocking if ((ret == -1) && ((sock_err == EAGAIN) #if LWIP_VERSION_MAJOR >= 2 ||(sock_err == 0) #endif )) continue; else if (ret <= 0) { tcp_err = -1; break; } else { // decode simpleConfig pkt decode_ret = softAP_simpleConfig_parse(recv_buf, ret, backup_sc_ctx, softAP_decode_ctx); switch (decode_ret) { case SOFTAP_ERROR: continue; case SOFTAP_RECV_A: //send nonceB if(send(client_fd, softAP_decode_ctx -> nonceB, sizeof(softAP_decode_ctx -> nonceB), 0) < 0) { tcp_err = -2; break; } else continue; case SOFTAP_HANDSHAKE_DONE:// send response to finish handshake if(send(client_fd, "OK", 2, 0) < 0) { tcp_err = -2; break; } continue; case SOFTAP_DECODE_SUCCESS: { char softAP_ack_content[17]; //printf("softAP mode simpleConfig success, send response\n"); // ack content: MAC address in string mode sprintf(softAP_ack_content, "%02x:%02x:%02x:%02x:%02x:%02x", mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); if(send(client_fd, softAP_ack_content, sizeof(softAP_ack_content), 0) <= 0) tcp_err = -3; else vTaskDelay(500); // make sure the response pkt has enough time to be transmitted break; } default: break; } break; // break the while loop } } // close the client socket close(client_fd); //error handler here, wf, 0816 if(tcp_err < 0) { if(tcp_err == -1) printf("tcp recv error\n"); else printf("tcp send response error\n"); tcp_err = 0; return -1; } else return 0; } #if CONFIG_EXAMPLE_WLAN_FAST_CONNECT static void stop_fast_connect(void) { p_wlan_init_done_callback = NULL; return; } static void resume_fast_connect(void) { p_wlan_init_done_callback = wlan_init_done_callback; return; } #endif // use the softAP channel to reset the promisc channel table static void init_promisc_scan_channel(unsigned char softAP_ch) { int i = sizeof(simple_config_promisc_channel_tbl)/sizeof(simple_config_promisc_channel_tbl[0]); simple_config_promisc_channel_tbl[i - 1] = softAP_ch; return; } extern void dhcps_deinit(void); extern void dhcps_init(struct netif * pnetif); static int SimpleConfig_softAP_start(const char* ap_name, const char *ap_password) { int timeout = 20; #if CONFIG_LWIP_LAYER struct ip_addr ipaddr; struct ip_addr netmask; struct ip_addr gw; struct netif * pnetif = &xnetif[0]; #endif int ret = 0; #if CONFIG_LWIP_LAYER dhcps_deinit(); #if LWIP_VERSION_MAJOR >= 2 IP4_ADDR(ip_2_ip4(&ipaddr), GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3); IP4_ADDR(ip_2_ip4(&netmask), NETMASK_ADDR0, NETMASK_ADDR1 , NETMASK_ADDR2, NETMASK_ADDR3); IP4_ADDR(ip_2_ip4(&gw), GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3); netif_set_addr(pnetif, ip_2_ip4(&ipaddr), ip_2_ip4(&netmask),ip_2_ip4(&gw)); #else IP4_ADDR(&ipaddr, GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3); IP4_ADDR(&netmask, NETMASK_ADDR0, NETMASK_ADDR1 , NETMASK_ADDR2, NETMASK_ADDR3); IP4_ADDR(&gw, GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3); netif_set_addr(pnetif, &ipaddr, &netmask,&gw); #endif #endif wifi_off(); vTaskDelay(20); if (wifi_on(RTW_MODE_AP) < 0){ printf("Wifi on failed!"); return -1; } wifi_disable_powersave();//add to close powersave #ifdef CONFIG_WPS_AP wpas_wps_dev_config(pnetif->hwaddr, 1); #endif if(ap_password) { if(wifi_start_ap((char*)ap_name, RTW_SECURITY_WPA2_AES_PSK, (char*)ap_password, strlen((const char *)ap_name), strlen((const char *)ap_password), simple_config_softAP_channel ) != RTW_SUCCESS) { printf("wifi start ap mode failed!\n\r"); return -1; } } else { if(wifi_start_ap((char*)ap_name, RTW_SECURITY_OPEN, NULL, strlen((const char *)ap_name), 0, simple_config_softAP_channel ) != RTW_SUCCESS) { printf("wifi start ap mode failed!\n\r"); return -1; } } while(1) { char essid[33]; if(wext_get_ssid(WLAN0_NAME, (unsigned char *) essid) > 0) { if(strcmp((const char *) essid, (const char *)ap_name) == 0) { //printf("%s started\n", ap_name); ret = 0; break; } } if(timeout == 0) { printf("Start AP timeout!\n\r"); ret = -1; break; } vTaskDelay(1 * configTICK_RATE_HZ); timeout --; } #if CONFIG_LWIP_LAYER //LwIP_UseStaticIP(pnetif); dhcps_init(pnetif); #endif return ret; } #endif // end of SC_SOFTAP_EN static int simple_config_get_channel_interval(int ch_idx) { int interval = 105; #if SC_SOFTAP_EN int ch_len = sizeof(simple_config_promisc_channel_tbl)/sizeof(simple_config_promisc_channel_tbl[0]); if(ch_idx == ch_len - 1) // this is the softAP channel idx interval = 5000; #endif return interval; } extern unsigned char is_promisc_enabled(void); static void simple_config_channel_control(void *para) { int ch_idx = 0; unsigned int start_time; int fix_channel = 0; int delta_time = 0; #if SC_SOFTAP_EN unsigned char softAP_SSID[33]; unsigned char softAP_password[65]; #endif rtw_network_info_t *wifi = (rtw_network_info_t *)para; start_time = xTaskGetTickCount(); while (simple_config_terminate != 1) { vTaskDelay(50); //delay 0.5s to release CPU usage #if SC_SOFTAP_EN // softAP mode already get the AP profile if(is_need_connect_to_AP == 1) break; if(simple_config_softAP_onAuth == 1) { wifi_set_promisc(RTW_PROMISC_DISABLE, NULL, 0); wifi_set_channel(simple_config_softAP_channel); wifi_reg_event_handler(WIFI_EVENT_STA_ASSOC, sc_sta_asso_cb, NULL); if(rtw_down_timeout_sema(&sc_sta_assoc_sema, SC_SOFTAP_TIMEOUT) == RTW_FALSE) { //printf("no sta associated after 10s, start promisc\n"); simple_config_softAP_onAuth = 0; wifi_set_promisc(RTW_PROMISC_ENABLE_2, simple_config_callback, 1); } else { //printf("new sta associated, wait tcp connection\n"); softAP_decode_success = simple_config_softap_config(); if(softAP_decode_success == 0) { is_need_connect_to_AP = 1; wifi_unreg_event_handler(WIFI_EVENT_STA_ASSOC, sc_sta_asso_cb); break; } else { simple_config_softAP_onAuth = 0; wifi_set_promisc(RTW_PROMISC_ENABLE_2, simple_config_callback, 1); } } wifi_unreg_event_handler(WIFI_EVENT_STA_ASSOC, sc_sta_asso_cb); } #endif simple_config_cmd_current_time = xTaskGetTickCount(); #if CONFIG_GAGENT if (simple_config_cmd_current_time - simple_config_cmd_start_time < ((50 + delta_time)*configTICK_RATE_HZ)) #else if (simple_config_cmd_current_time - simple_config_cmd_start_time < ((120 + delta_time)*configTICK_RATE_HZ)) #endif { unsigned int current_time = xTaskGetTickCount(); int interval = simple_config_get_channel_interval(ch_idx); if (((current_time - start_time)*1000 /configTICK_RATE_HZ < (u32)interval) || (is_fixed_channel == 1)) { if(is_fixed_channel == 0 && get_channel_flag == 1){ fix_channel = promisc_get_fixed_channel(g_bssid,g_ssid,&g_ssid_len); if(fix_channel != 0) { printf("\r\nin simple_config_test fix channel = %d ssid: %s\n",fix_channel, g_ssid); is_fixed_channel = 1; fixed_channel_num = fix_channel; wifi_set_channel(fix_channel); #if SC_SOFTAP_EN if(simple_config_softAP_channel != fixed_channel_num){ simple_config_softAP_channel = fixed_channel_num; memset(softAP_SSID, 0, sizeof(softAP_SSID)); memset(softAP_password, 0, sizeof(softAP_password)); simpleConfig_get_softAP_profile(softAP_SSID, softAP_password); SimpleConfig_softAP_start((char const*)softAP_SSID, (char const*)softAP_password); wifi_set_promisc(RTW_PROMISC_ENABLE_2, simple_config_callback, 1); } #endif } else printf("get channel fail\n"); } if (simple_config_result == 1) { is_need_connect_to_AP = 1; is_fixed_channel = 0; break; } if (simple_config_result == -1) { printf("\r\nsimple_config_test restart for result = -1"); delta_time = 60; wifi_set_channel(1); is_need_connect_to_AP = 0; is_fixed_channel = 0; fixed_channel_num = 0; memset(g_ssid, 0, 33); g_ssid_len = 0; simple_config_result = 0; g_security_mode = 0xff; rtk_restart_simple_config(); } } else { ch_idx++; if(ch_idx >= (int)sizeof(simple_config_promisc_channel_tbl)/(int)sizeof(simple_config_promisc_channel_tbl[0])) ch_idx = 0; if (wifi_set_channel(simple_config_promisc_channel_tbl[ch_idx]) == 0) { start_time = xTaskGetTickCount(); printf("\n\rSwitch to channel(%d)\n", simple_config_promisc_channel_tbl[ch_idx]); } } } else { promisc_mode_ret = SC_NO_CONTROLLER_FOUND; break; } } // end of while if(is_promisc_enabled()) wifi_set_promisc(RTW_PROMISC_DISABLE, NULL, 0); #if SC_SOFTAP_EN simple_config_kick_STA(); close(softAP_socket); wifi_off(); #if CONFIG_EXAMPLE_WLAN_FAST_CONNECT stop_fast_connect(); #endif wifi_on(RTW_MODE_STA); #if CONFIG_EXAMPLE_WLAN_FAST_CONNECT resume_fast_connect(); #endif #endif // end of SC_SOFTAP_EN if (is_need_connect_to_AP == 1) { if(NULL == wifi){ int tmp_res = SC_connect_to_AP(); if (SC_SUCCESS == tmp_res) { if(-1 == SC_send_simple_config_ack(30)) promisc_mode_ret = SC_UDP_SOCKET_CREATE_FAIL; #ifdef SC_SCAN_SUPPORT // check whether the thread of listen scan command is already created if(scan_start == 0) { scan_start = 1; SC_listen_ACK_scan(); } #endif } else { promisc_mode_ret =(enum sc_result) tmp_res; } }else{ if (-1 == get_connection_info_from_profile(wifi->security_type,wifi)) { promisc_mode_ret = SC_CONTROLLER_INFO_PARSE_FAIL; }else promisc_mode_ret = SC_SUCCESS; } }else{ promisc_mode_ret = SC_NO_CONTROLLER_FOUND; } rtw_up_sema(&simple_config_finish_sema); vTaskDelete(NULL); return; } enum sc_result simple_config_test(rtw_network_info_t *wifi) { #if SC_SOFTAP_EN unsigned char softAP_SSID[33]; unsigned char softAP_password[65]; struct sockaddr_in softAP_addr; //unsigned char channel_set[11]; unsigned char channel_set[3]; int auto_chl = 0; int timeout = 60000; int tcp_reuse_timeout = 1; memset(softAP_SSID, 0, sizeof(softAP_SSID)); memset(softAP_password, 0, sizeof(softAP_password)); simpleConfig_get_softAP_profile(softAP_SSID, softAP_password); channel_set[0] = 1; channel_set[1] = 6; channel_set[2] = 11; auto_chl = wext_get_auto_chl("wlan0", channel_set, sizeof(channel_set)/sizeof(channel_set[0])); if(auto_chl <= 0) { printf("Get softAP channel error\n, use static channel\n"); simple_config_softAP_channel = 6; }else simple_config_softAP_channel = auto_chl; //printf("softAP channel is set to %d\n", simple_config_softAP_channel); init_promisc_scan_channel(simple_config_softAP_channel); SimpleConfig_softAP_start((char const*)softAP_SSID, (char const*)softAP_password); wifi_set_promisc(RTW_PROMISC_ENABLE_2, simple_config_callback, 1); softAP_socket = socket(PF_INET, SOCK_STREAM, 0); if (softAP_socket == -1) { printf("softAP_socket create error\n"); return SC_UDP_SOCKET_CREATE_FAIL; } setsockopt(softAP_socket, SOL_SOCKET, SO_REUSEADDR, (const char *)&tcp_reuse_timeout, sizeof(tcp_reuse_timeout)); memset(&softAP_addr, 0, sizeof(softAP_addr)); softAP_addr.sin_family = AF_INET; softAP_addr.sin_port = htons(18884); softAP_addr.sin_addr.s_addr = INADDR_ANY; if(bind(softAP_socket, (struct sockaddr *) &softAP_addr, sizeof(softAP_addr)) != 0) { printf("softAP bind error\n"); close(softAP_socket); return SC_UDP_SOCKET_CREATE_FAIL; } if(lwip_setsockopt(softAP_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(int)) < 0) printf("set socket timeout error\n"); if(listen(softAP_socket, 2) != 0) { printf("ERROR: listen\n"); close(softAP_socket); return SC_UDP_SOCKET_CREATE_FAIL; } #else wifi_set_promisc(RTW_PROMISC_ENABLE, simple_config_callback, 1); #endif if(xTaskCreate(simple_config_channel_control, ((const char*)"simple_config_channel_control"), 1024, wifi, tskIDLE_PRIORITY + 5, NULL) != pdPASS) printf("\n\r%s xTaskCreate(simple_config_channel_control) failed", __FUNCTION__); if (rtw_down_sema(&simple_config_finish_sema) == _FAIL) printf("%s, Take Semaphore Fail\n", __FUNCTION__); return promisc_mode_ret; } //Filter packet da[] = {0x01, 0x00, 0x5e} //add another filter for bcast, {0xff, 0xff, 0xff, 0xff} #define MASK_SIZE 3 void filter_add_enable(void){ u8 mask[MASK_SIZE]={0xFF,0xFF,0xFF}; u8 pattern[MASK_SIZE]={0x01,0x00,0x5e}; rtw_packet_filter_pattern_t packet_filter; rtw_packet_filter_rule_t rule; packet_filter.offset = 0; packet_filter.mask_size = 3; packet_filter.mask = mask; packet_filter.pattern = pattern; rule = RTW_POSITIVE_MATCHING; wifi_init_packet_filter(); wifi_add_packet_filter(1, &packet_filter,rule); wifi_enable_packet_filter(1); } void remove_filter(void){ wifi_disable_packet_filter(1); wifi_remove_packet_filter(1); } #define MASK1_SIZE 12 #define MASK2_SIZE 18 void filter1_add_enable(void){ u8 mask1[MASK1_SIZE]={0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF}; u8 pattern[MASK1_SIZE]={0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,mac_addr[0],mac_addr[1],mac_addr[2],mac_addr[3],mac_addr[4],mac_addr[5]}; u8 pattern2[MASK1_SIZE]={mac_addr[0],mac_addr[1],mac_addr[2],mac_addr[3],mac_addr[4],mac_addr[5],mac_addr[0],mac_addr[1],mac_addr[2],mac_addr[3],mac_addr[4],mac_addr[5]}; u8 mask2[MASK2_SIZE]={0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF}; u8 pattern3[MASK2_SIZE]={mac_addr[0],mac_addr[1],mac_addr[2],mac_addr[3],mac_addr[4],mac_addr[5],0x00,0x00,0x00,0x00,0x00,0x00,mac_addr[0],mac_addr[1],mac_addr[2],mac_addr[3],mac_addr[4],mac_addr[5]}; rtw_packet_filter_pattern_t packet_filter, packet_filter2, packet_filter3; rtw_packet_filter_rule_t rule; packet_filter.offset = 4; packet_filter.mask_size = 12; packet_filter.mask = mask1; packet_filter.pattern = pattern; packet_filter2.offset = 10; packet_filter2.mask_size = 12; packet_filter2.mask = mask1; packet_filter2.pattern = pattern2; packet_filter3.offset = 4; packet_filter3.mask_size = 18; packet_filter3.mask = mask2; packet_filter3.pattern = pattern3; rule = RTW_POSITIVE_MATCHING; wifi_init_packet_filter(); wifi_add_packet_filter(1, &packet_filter2,rule); wifi_enable_packet_filter(1); wifi_add_packet_filter(2, &packet_filter3,rule); wifi_enable_packet_filter(2); if(ssid_hidden == 0){ wifi_add_packet_filter(3, &packet_filter,rule); wifi_enable_packet_filter(3); } } void remove1_filter(void){ wifi_disable_packet_filter(1); wifi_remove_packet_filter(1); wifi_disable_packet_filter(2); wifi_remove_packet_filter(2); if(ssid_hidden == 0){ wifi_disable_packet_filter(3); wifi_remove_packet_filter(3); } } void print_simple_config_result(enum sc_result sc_code) { printf("\r\n"); switch (sc_code) { case SC_NO_CONTROLLER_FOUND: printf("Simple Config timeout!! Can't get Ap profile. Please try again\n"); break; case SC_CONTROLLER_INFO_PARSE_FAIL: printf("Simple Config fail, cannot parse target ap info from controller\n"); break; case SC_TARGET_CHANNEL_SCAN_FAIL: printf("Simple Config cannot scan the target channel\n"); break; case SC_JOIN_BSS_FAIL: printf("Simple Config Join bss failed\n"); break; case SC_DHCP_FAIL: printf("Simple Config fail, cannot get dhcp ip address\n"); break; case SC_UDP_SOCKET_CREATE_FAIL: printf("Simple Config Ack socket create fail!!!\n"); break; case SC_TERMINATE: printf("Simple Config terminate\n"); break; case SC_SUCCESS: printf("Simple Config success\n"); break; case SC_ERROR: default: printf("unknown error when simple config!\n"); } } #endif //CONFIG_INCLUDE_SIMPLE_CONFIG void cmd_simple_config(int argc, char **argv){ #if CONFIG_INCLUDE_SIMPLE_CONFIG char *custom_pin_code = NULL; enum sc_result ret = SC_ERROR; if(argc > 2){ printf("\n\rInput Error!"); } if(argc == 2){ custom_pin_code = (argv[1]); if(strlen(custom_pin_code) != 8){ printf("Pin length error, please input 8 byte pin code"); return; } } // check whether the pin code is valid simple_config_terminate = 0; #if !SC_SOFTAP_EN wifi_enter_promisc_mode(); #endif if(init_test_data(custom_pin_code) == 0){ #if !SC_SOFTAP_EN filter_add_enable(); #endif ret = simple_config_test(NULL); deinit_test_data(); #if !SC_SOFTAP_EN remove_filter(); #endif print_simple_config_result(ret); } #if defined(CONFIG_INIC_CMD_RSP) && CONFIG_INIC_CMD_RSP if(ret != SC_SUCCESS) inic_c2h_wifi_info("ATWQ", RTW_ERROR); #endif #if (defined(CONFIG_EXAMPLE_UART_ATCMD) && CONFIG_EXAMPLE_UART_ATCMD) || (defined(CONFIG_EXAMPLE_SPI_ATCMD) && CONFIG_EXAMPLE_SPI_ATCMD) if(ret == SC_SUCCESS){ at_printf("\n\r[ATWQ] OK"); }else{ at_printf("\n\r[ATWQ] ERROR:%d",ret); } #endif #endif } #endif //#if CONFIG_WLAN
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/wifi_simple_config.c
C
apache-2.0
54,925
#ifndef __WIFI_SIMPLE_CONFIG_H #define __WIFI_SIMPLE_CONFIG_H /*****************************wifi_simple_config.h****************************/ enum sc_result { SC_ERROR = -1, /* default error code*/ SC_NO_CONTROLLER_FOUND = 1, /* cannot get sta(controller) in the air which starts a simple config session */ SC_CONTROLLER_INFO_PARSE_FAIL, /* cannot parse the sta's info */ SC_TARGET_CHANNEL_SCAN_FAIL, /* cannot scan the target channel */ SC_JOIN_BSS_FAIL, /* fail to connect to target ap */ SC_DHCP_FAIL, /* fail to get ip address from target ap */ /* fail to create udp socket to send info to controller. note that client isolation must be turned off in ap. we cannot know if ap has configured this */ SC_UDP_SOCKET_CREATE_FAIL, SC_TERMINATE, SC_SUCCESS, /* default success code */ }; int SC_send_simple_config_ack(u8 round); #endif //__WIFI_SIMPLE_CONFIG_H
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/wifi_simple_config.h
C
apache-2.0
876
#ifndef __SIMPLE_CONFIG_H__ #define __SIMPLE_CONFIG_H__ #ifdef __cplusplus extern "C" { #endif /* This macro means user take simple config * lib to another platform such as linux, and * have no rom crypto libs of simple config, * so we take simple_config_crypto as a sw lib * This macro is used by Realtek internal to generate simple config lib * Please delete this macro after generation. */ #define SIMPLE_CONFIG_PLATFORM_LIB 0 #include "platform_opts.h" #include "autoconf.h" /* platform related settings */ #if (defined(CONFIG_PLATFORM_8195A)|| defined(CONFIG_PLATFORM_8711B)|| defined(CONFIG_PLATFORM_8721D) || defined(CONFIG_PLATFORM_8195BHP) || defined(CONFIG_PLATFORM_8710C)) #undef u32 #undef s32 #undef u8 #undef s8 #undef u16 #undef s16 typedef unsigned int u32; typedef signed int s32; typedef unsigned char u8; typedef char s8; typedef unsigned short int u16; typedef signed short int s16; #else #include "osdep_service.h" #endif typedef int (*simple_config_printf_fn) (char const * fmt, ...); typedef void* (*simple_config_memset_fn) (void *dst0, s32 Val, u32 length); typedef void* (*simple_config_memcpy_fn) ( void *s1, const void *s2, u32 n ); typedef u32 (*simple_config_strlen_fn) (const char *s); typedef char * (*simple_config_strcpy_fn) (char *dest, const char *src); typedef void (*simple_config_free_fn) (u8 *pbuf, u32 sz); typedef u8* (*simple_config_zmalloc_fn) (u32 sz); typedef u8* (*simple_config_malloc_fn) (u32 sz); typedef int (*simple_config_memcmp_fn) (const void *av, const void *bv, u32 len); typedef u32 (*simple_config_ntohl_fn)(u32 x); struct simple_config_lib_config { simple_config_printf_fn printf_fn; simple_config_memset_fn memset_fn; simple_config_memcpy_fn memcpy_fn; simple_config_strlen_fn strlen_fn; simple_config_strcpy_fn strcpy_fn; simple_config_free_fn free_fn; simple_config_zmalloc_fn zmalloc_fn; simple_config_malloc_fn malloc_fn; simple_config_memcmp_fn memcmp_fn; simple_config_ntohl_fn ntohl_fn; int *is_promisc_callback_unlock; }; struct fmt_info { u8 fmt_channel[2]; u8 fmt_hidden[1]; u8 fmt_bssid[6]; }; struct dsoc_info { unsigned char dsoc_ssid[33]; unsigned char dsoc_length; }; #pragma pack(1) struct rtk_test_sc { /* API exposed to user */ unsigned char ssid[33]; unsigned char password[65]; unsigned int ip_addr; }; // for softAP mode typedef enum { SOFTAP_ERROR = -1, SOFTAP_INIT, SOFTAP_RECV_A, SOFTAP_HANDSHAKE_DONE, SOFTAP_DECODE_SUCCESS, } SC_softAP_status; #pragma pack(1) typedef struct _SC_softAP_decode_ctx { u8 nonceA[16]; u8 nonceB[32]; u8 mac[6]; SC_softAP_status softAP_decode_status; } SC_softAP_decode_ctx; /* expose data */ extern s32 is_promisc_callback_unlock; extern u8 g_bssid[6]; extern u8 get_channel_flag; extern u8 g_security_mode; /* expose API */ extern s32 rtk_sc_init(char *custom_pin_code, struct simple_config_lib_config* config); extern int rtl_pre_parse(u8 *mac_addr, u8 *buf, void *userdata, u8 **da, u8 **sa, unsigned int *len); extern s32 rtk_start_parse_packet(u8 *da, u8 *sa, s32 len, void * user_data, void *backup_sc); extern SC_softAP_status softAP_simpleConfig_parse(unsigned char *buf, int len, void *backup_sc_ctx, void *psoftAP_ctx); extern void rtk_restart_simple_config(void); extern void rtk_sc_deinit(void); extern void wifi_enter_promisc_mode(void); extern void whc_fix_channel(void); extern void whc_unfix_channel(void); #ifdef __cplusplus } #endif #endif /* __SIMPLE_CONFIG_H__*/
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/wifi_simple_config_parser.h
C
apache-2.0
3,533
/****************************************************************************** * * Copyright(c) 2007 - 2021 Realtek Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ #include <wireless.h> #include <wlan_intf.h> #include <platform/platform_stdlib.h> #include <wifi/wifi_conf.h> #include <wifi/wifi_ind.h> #include <osdep_service.h> int iw_ioctl(const char * ifname, unsigned long request, struct iwreq * pwrq) { memcpy(pwrq->ifr_name, ifname, 5); return rltk_wlan_control(request, (void *) pwrq); } int wext_get_ssid(const char *ifname, __u8 *ssid) { struct iwreq iwr; int ret = 0; memset(&iwr, 0, sizeof(iwr)); iwr.u.essid.pointer = ssid; iwr.u.essid.length = 32; if (iw_ioctl(ifname, SIOCGIWESSID, &iwr) < 0) { #if defined(CONFIG_EXAMPLE_BT_CONFIG) && (CONFIG_EXAMPLE_BT_CONFIG!=1) RTW_API_INFO("\n\rioctl[SIOCGIWESSID] ssid = NULL, not connected"); //do not use perror #endif ret = -1; } else { ret = iwr.u.essid.length; if (ret > 32) ret = 32; /* Some drivers include nul termination in the SSID, so let's * remove it here before further processing. WE-21 changes this * to explicitly require the length _not_ to include nul * termination. */ if (ret > 0 && ssid[ret - 1] == '\0') ret--; ssid[ret] = '\0'; } return ret; } int wext_set_ssid(const char *ifname, const __u8 *ssid, __u16 ssid_len) { struct iwreq iwr; int ret = 0; memset(&iwr, 0, sizeof(iwr)); iwr.u.essid.pointer = (void *) ssid; iwr.u.essid.length = ssid_len; iwr.u.essid.flags = (ssid_len != 0); if (iw_ioctl(ifname, SIOCSIWESSID, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWESSID] error"); ret = -1; } return ret; } int wext_set_bssid(const char *ifname, const __u8 *bssid) { struct iwreq iwr; int ret = 0; memset(&iwr, 0, sizeof(iwr)); iwr.u.ap_addr.sa_family = ARPHRD_ETHER; memcpy(iwr.u.ap_addr.sa_data, bssid, ETH_ALEN); if(bssid[ETH_ALEN]=='#' && bssid[ETH_ALEN + 1]=='@'){ memcpy(iwr.u.ap_addr.sa_data + ETH_ALEN, bssid + ETH_ALEN, 6); } if (iw_ioctl(ifname, SIOCSIWAP, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWAP] error"); ret = -1; } return ret; } int wext_get_bssid(const char*ifname, __u8 *bssid) { struct iwreq iwr; int ret = 0; memset(&iwr, 0, sizeof(iwr)); if (iw_ioctl(ifname, SIOCGIWAP, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWAP] error"); ret = -1; } else { memcpy(bssid, iwr.u.ap_addr.sa_data, ETH_ALEN); } return ret; } int is_broadcast_ether_addr(const unsigned char *addr) { return (addr[0] & addr[1] & addr[2] & addr[3] & addr[4] & addr[5]) == 0xff; } int wext_set_auth_param(const char *ifname, __u16 idx, __u32 value) { struct iwreq iwr; int ret = 0; memset(&iwr, 0, sizeof(iwr)); iwr.u.param.flags = idx & IW_AUTH_INDEX; iwr.u.param.value = value; if (iw_ioctl(ifname, SIOCSIWAUTH, &iwr) < 0) { RTW_API_INFO("\n\rWEXT: SIOCSIWAUTH(param %d value 0x%x) failed)", idx, value); } return ret; } int wext_set_mfp_support(const char *ifname, __u8 value) { int ret = 0; struct iwreq iwr; memset(&iwr, 0, sizeof(iwr)); iwr.u.param.value = value; if (iw_ioctl(ifname, SIOCSIWMFP, &iwr) < 0) { RTW_API_INFO("\n\rWEXT: SIOCSIWMFP(value 0x%x) failed)", value); } return ret; } #ifdef CONFIG_SAE_SUPPORT int wext_set_group_id(const char *ifname, __u8 value) { int ret = 0; struct iwreq iwr; memset(&iwr, 0, sizeof(iwr)); iwr.u.param.value = value; if (iw_ioctl(ifname, SIOCSIWGRPID, &iwr) < 0) { RTW_API_INFO("\n\rWEXT: SIOCSIWGRPID(value 0x%x) failed)", value); } return ret; } int wext_set_support_wpa3(__u8 enable) { extern u8 rtw_cmd_tsk_spt_wap3; rtw_cmd_tsk_spt_wap3 = enable; return 0; } unsigned char wext_get_support_wpa3(void) { extern u8 rtw_cmd_tsk_spt_wap3; return rtw_cmd_tsk_spt_wap3; } #endif #ifdef CONFIG_PMKSA_CACHING int wext_set_pmk_cache_enable(const char *ifname, __u8 value) { int ret = 0; struct iwreq iwr; memset(&iwr, 0, sizeof(iwr)); iwr.u.param.value = value; if (iw_ioctl(ifname, SIOCSIWPMKSA, &iwr) < 0) { RTW_API_INFO("\n\rWEXT: SIOCSIWPMKSA(value 0x%x) failed)", value); } return ret; } #endif int wext_set_key_ext(const char *ifname, __u16 alg, const __u8 *addr, int key_idx, int set_tx, const __u8 *seq, __u16 seq_len, __u8 *key, __u16 key_len) { struct iwreq iwr; int ret = 0; struct iw_encode_ext *ext; ext = (struct iw_encode_ext *) malloc(sizeof(struct iw_encode_ext) + key_len); if (ext == NULL) return -1; else memset(ext, 0, sizeof(struct iw_encode_ext) + key_len); memset(&iwr, 0, sizeof(iwr)); iwr.u.encoding.flags = key_idx + 1; iwr.u.encoding.flags |= IW_ENCODE_TEMP; iwr.u.encoding.pointer = ext; iwr.u.encoding.length = sizeof(struct iw_encode_ext) + key_len; if (alg == IW_ENCODE_DISABLED) iwr.u.encoding.flags |= IW_ENCODE_DISABLED; if (addr == NULL || is_broadcast_ether_addr(addr)) ext->ext_flags |= IW_ENCODE_EXT_GROUP_KEY; if (set_tx) ext->ext_flags |= IW_ENCODE_EXT_SET_TX_KEY; ext->addr.sa_family = ARPHRD_ETHER; if (addr) memcpy(ext->addr.sa_data, addr, ETH_ALEN); else memset(ext->addr.sa_data, 0xff, ETH_ALEN); if (key && key_len) { memcpy(ext->key, key, key_len); ext->key_len = key_len; } ext->alg = alg; if (seq && seq_len) { ext->ext_flags |= IW_ENCODE_EXT_RX_SEQ_VALID; memcpy(ext->rx_seq, seq, seq_len); } if (iw_ioctl(ifname, SIOCSIWENCODEEXT, &iwr) < 0) { ret = -2; RTW_API_INFO("\n\rioctl[SIOCSIWENCODEEXT] set key fail"); } free(ext); return ret; } int wext_get_enc_ext(const char *ifname, __u16 *alg, __u8 *key_idx, __u8 *passphrase) { struct iwreq iwr; int ret = 0; struct iw_encode_ext *ext; ext = (struct iw_encode_ext *) malloc(sizeof(struct iw_encode_ext) + 16); if (ext == NULL) return -1; else memset(ext, 0, sizeof(struct iw_encode_ext) + 16); iwr.u.encoding.pointer = ext; if (iw_ioctl(ifname, SIOCGIWENCODEEXT, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCGIWENCODEEXT] error"); ret = -1; } else { *alg = ext->alg; if(key_idx) *key_idx = (__u8)iwr.u.encoding.flags; if(passphrase) memcpy(passphrase, ext->key, ext->key_len); } if(ext != NULL) free(ext); return ret; } int wext_set_passphrase(const char *ifname, const __u8 *passphrase, __u16 passphrase_len) { struct iwreq iwr; int ret = 0; memset(&iwr, 0, sizeof(iwr)); iwr.u.passphrase.pointer = (void *) passphrase; iwr.u.passphrase.length = passphrase_len; iwr.u.passphrase.flags = (passphrase_len != 0); if (iw_ioctl(ifname, SIOCSIWPRIVPASSPHRASE, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWESSID+0x1f] error"); ret = -1; } return ret; } int wext_get_passphrase(const char *ifname, __u8 *passphrase) { struct iwreq iwr; int ret = 0; memset(&iwr, 0, sizeof(iwr)); iwr.u.passphrase.pointer = (void *) passphrase; if (iw_ioctl(ifname, SIOCGIWPRIVPASSPHRASE, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCGIWPRIVPASSPHRASE] error"); ret = -1; } else { ret = iwr.u.passphrase.length; passphrase[ret] = '\0'; } return ret; } #if 0 int wext_set_mac_address(const char *ifname, char * mac) { char buf[13+17+1]; rtw_memset(buf, 0, sizeof(buf)); snprintf(buf, 13+17, "write_mac %s", mac); return wext_private_command(ifname, buf, 0); } int wext_get_mac_address(const char *ifname, char * mac) { int ret = 0; char buf[32]; rtw_memset(buf, 0, sizeof(buf)); rtw_memcpy(buf, "read_mac", 8); ret = wext_private_command_with_retval(ifname, buf, buf, 32); strcpy(mac, buf); return ret; } #endif int wext_enable_powersave(const char *ifname, __u8 ips_mode, __u8 lps_mode) { struct iwreq iwr; int ret = 0; __u16 pindex = 0; __u8 *para = NULL; int cmd_len = 0; memset(&iwr, 0, sizeof(iwr)); cmd_len = sizeof("pm_set"); // Encode parameters as TLV (type, length, value) format para = rtw_malloc( 7 + (1+1+1) + (1+1+1) ); if(para == NULL) return -1; snprintf((char*)para, cmd_len, "pm_set"); pindex = 7; para[pindex++] = 0; // type 0 for ips para[pindex++] = 1; para[pindex++] = ips_mode; para[pindex++] = 1; // type 1 for lps para[pindex++] = 1; para[pindex++] = lps_mode; iwr.u.data.pointer = para; iwr.u.data.length = pindex; if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWPRIVPMSET] error"); ret = -1; } rtw_free(para); return ret; } int wext_resume_powersave(const char *ifname) { struct iwreq iwr; int ret = 0; __u16 pindex = 0; __u8 *para = NULL; int cmd_len = 0; memset(&iwr, 0, sizeof(iwr)); cmd_len = sizeof("pm_set"); // Encode parameters as TLV (type, length, value) format para = rtw_malloc( 7 + (1+1+1) + (1+1+1) ); if(para == NULL) return -1; snprintf((char*)para, cmd_len, "pm_set"); pindex = 7; para[pindex++] = 8; // type 8 for power save resume para[pindex++] = 0; iwr.u.data.pointer = para; iwr.u.data.length = pindex; if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWPRIVPMSET] error"); ret = -1; } rtw_free(para); return ret; } int wext_disable_powersave(const char *ifname) { struct iwreq iwr; int ret = 0; __u16 pindex = 0; __u8 *para = NULL; int cmd_len = 0; memset(&iwr, 0, sizeof(iwr)); cmd_len = sizeof("pm_set"); // Encode parameters as TLV (type, length, value) format para = rtw_malloc( 7 + (1+1+1) + (1+1+1) ); if(para == NULL) return -1; snprintf((char*)para, cmd_len, "pm_set"); pindex = 7; para[pindex++] = 0; // type 0 for ips para[pindex++] = 1; para[pindex++] = 0; // ips = 0 para[pindex++] = 1; // type 1 for lps para[pindex++] = 1; para[pindex++] = 0; // lps = 0 iwr.u.data.pointer = para; iwr.u.data.length = pindex; if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWPRIVPMSET] error"); ret = -1; } rtw_free(para); return ret; } int wext_set_tdma_param(const char *ifname, __u8 slot_period, __u8 rfon_period_len_1, __u8 rfon_period_len_2, __u8 rfon_period_len_3) { struct iwreq iwr; int ret = 0; __u16 pindex = 0; __u8 *para = NULL; int cmd_len = 0; memset(&iwr, 0, sizeof(iwr)); cmd_len = sizeof("pm_set"); // Encode parameters as TLV (type, length, value) format para = rtw_malloc( 7 + (1+1+4) ); snprintf((char*)para, cmd_len, "pm_set"); pindex = 7; para[pindex++] = 2; // type 2 tdma param para[pindex++] = 4; para[pindex++] = slot_period; para[pindex++] = rfon_period_len_1; para[pindex++] = rfon_period_len_2; para[pindex++] = rfon_period_len_3; iwr.u.data.pointer = para; iwr.u.data.length = pindex; if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWPRIVPMSET] error"); ret = -1; } rtw_free(para); return ret; } int wext_set_lps_dtim(const char *ifname, __u8 lps_dtim) { struct iwreq iwr; int ret = 0; __u16 pindex = 0; __u8 *para = NULL; int cmd_len = 0; memset(&iwr, 0, sizeof(iwr)); cmd_len = sizeof("pm_set"); // Encode parameters as TLV (type, length, value) format para = rtw_malloc( 7 + (1+1+1) ); snprintf((char*)para, cmd_len, "pm_set"); pindex = 7; para[pindex++] = 3; // type 3 lps dtim para[pindex++] = 1; para[pindex++] = lps_dtim; iwr.u.data.pointer = para; iwr.u.data.length = pindex; if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWPRIVPMSET] error"); ret = -1; } rtw_free(para); return ret; } int wext_get_lps_dtim(const char *ifname, __u8 *lps_dtim) { struct iwreq iwr; int ret = 0; __u16 pindex = 0; __u8 *para = NULL; int cmd_len = 0; memset(&iwr, 0, sizeof(iwr)); cmd_len = sizeof("pm_get"); // Encode parameters as TLV (type, length, value) format para = rtw_malloc( 7 + (1+1+1) ); snprintf((char*)para, cmd_len, "pm_get"); pindex = 7; para[pindex++] = 3; // type 3 for lps dtim para[pindex++] = 1; para[pindex++] = 0; iwr.u.data.pointer = para; iwr.u.data.length = pindex; if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWPRIVPMGET] error"); ret = -1; goto exit; } //get result at the beginning of iwr.u.data.pointer if((para[0]==3)&&(para[1]==1)) *lps_dtim = para[2]; else RTW_API_INFO("\n\r%s error", __func__); exit: rtw_free(para); return ret; } int wext_set_lps_thresh(const char *ifname, u8 low_thresh) { struct iwreq iwr; int ret = 0; __u16 pindex = 0; __u8 *para = NULL; int cmd_len = 0; memset(&iwr, 0, sizeof(iwr)); cmd_len = sizeof("pm_set"); // Encode parameters as TLV (type, length, value) format para = rtw_malloc( 7 + (1+1+1) ); snprintf((char*)para, cmd_len, "pm_set"); pindex = 7; para[pindex++] = 6; // type 6 lps threshold para[pindex++] = 1; // len para[pindex++] = low_thresh; iwr.u.data.pointer = para; iwr.u.data.length = pindex; if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWPRIVPMSET] error"); ret = -1; } rtw_free(para); return ret; } #ifdef LONG_PERIOD_TICKLESS int wext_set_lps_smartps(const char *ifname, __u8 smartps) { struct iwreq iwr; int ret = 0; __u16 pindex = 0; __u8 *para = NULL; int cmd_len = 0; memset(&iwr, 0, sizeof(iwr)); cmd_len = sizeof("pm_set"); // Encode parameters as TLV (type, length, value) format para = rtw_malloc( 7 + (1+1+1) ); snprintf((char*)para, cmd_len, "pm_set"); pindex = 7; para[pindex++] = 9; // type 9 smartps para[pindex++] = 1; // len para[pindex++] = smartps; iwr.u.data.pointer = para; iwr.u.data.length = pindex; if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWPRIVPMSET] error"); ret = -1; } rtw_free(para); return ret; } #endif int wext_set_beacon_mode(const char *ifname, __u8 mode) { struct iwreq iwr; int ret = 0; __u16 pindex = 0; __u8 *para = NULL; int cmd_len = 0; memset(&iwr, 0, sizeof(iwr)); cmd_len = sizeof("pm_set"); // Encode parameters as TLV (type, length, value) format para = rtw_malloc( 7 + (1+1+1) ); snprintf((char*)para, cmd_len, "pm_set"); pindex = 7; para[pindex++] = 4; // type 4 beacon mode para[pindex++] = 1; // len para[pindex++] = mode; iwr.u.data.pointer = para; iwr.u.data.length = pindex; if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWPRIVPMSET] error"); ret = -1; } rtw_free(para); return ret; } int wext_set_lps_level(const char *ifname, __u8 lps_level) { struct iwreq iwr; int ret = 0; __u16 pindex = 0; __u8 *para = NULL; int cmd_len = 0; memset(&iwr, 0, sizeof(iwr)); cmd_len = sizeof("pm_set"); // Encode parameters as TLV (type, length, value) format para = rtw_malloc( 7 + (1+1+1) ); snprintf((char*)para, cmd_len, "pm_set"); pindex = 7; para[pindex++] = 5; // type 5 lps_level para[pindex++] = 1; // len para[pindex++] = lps_level; iwr.u.data.pointer = para; iwr.u.data.length = pindex; if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWPRIVPMSET] error"); ret = -1; } rtw_free(para); return ret; } int wext_set_tos_value(const char *ifname, __u8 *tos_value) { struct iwreq iwr; int ret = 0; __u8 *para = NULL; int cmd_len = sizeof("set_tos_value"); memset(&iwr, 0, sizeof(iwr)); para = rtw_malloc(cmd_len + 4); snprintf((char*)para, cmd_len, "set_tos_value"); if(*tos_value <=32){ *(para + cmd_len) = 0x4f; *(para + cmd_len+1) = 0xa4; *(para + cmd_len+2) = 0; *(para + cmd_len+3) = 0; } else if(*tos_value > 32 && *tos_value <=96){ *(para + cmd_len) = 0x2b; *(para + cmd_len+1) = 0xa4; *(para + cmd_len+2) = 0; *(para + cmd_len+3) = 0; } else if(*tos_value > 96 && *tos_value <= 160){ *(para + cmd_len) = 0x22; *(para + cmd_len+1) = 0x43; *(para + cmd_len+2) = 0x5e; *(para + cmd_len+3) = 0; } else if(*tos_value > 160){ *(para + cmd_len) = 0x22; *(para + cmd_len+1) = 0x32; *(para + cmd_len+2) = 0x2f; *(para + cmd_len+3) = 0; } iwr.u.data.pointer = para; iwr.u.data.length = cmd_len + 4; if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rwext_set_tos_value():ioctl[SIOCDEVPRIVATE] error"); ret = -1; } rtw_free(para); return ret; } int wext_get_tx_power(const char *ifname, __u8 *poweridx) { struct iwreq iwr; int ret = 0; __u8 *para = NULL; int cmd_len = sizeof("get_tx_power"); memset(&iwr, 0, sizeof(iwr)); //Tx power size : 20 Bytes //CCK 1M,2M,5.5M,11M : 4 Bytes //OFDM 6M, 9M, 12M, 18M, 24M, 36M 48M, 54M : 8 Bytes //MCS 0~7 : 8 Bytes para = rtw_malloc(cmd_len + 20); snprintf((char*)para, cmd_len, "get_tx_power"); iwr.u.data.pointer = para; iwr.u.data.length = cmd_len + 20; if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rwext_get_tx_power():ioctl[SIOCDEVPRIVATE] error"); ret = -1; } memcpy(poweridx,(__u8 *)(iwr.u.data.pointer),20); rtw_free(para); return ret; } #if 0 int wext_set_txpower(const char *ifname, int poweridx) { int ret = 0; char buf[24]; rtw_memset(buf, 0, sizeof(buf)); snprintf(buf, 24, "txpower patha=%d", poweridx); ret = wext_private_command(ifname, buf, 0); return ret; } int wext_get_associated_client_list(const char *ifname, void * client_list_buffer, uint16_t buffer_length) { int ret = 0; char buf[25]; rtw_memset(buf, 0, sizeof(buf)); snprintf(buf, 25, "get_client_list %x", client_list_buffer); ret = wext_private_command(ifname, buf, 0); return ret; } int wext_get_ap_info(const char *ifname, rtw_bss_info_t * ap_info, rtw_security_t* security) { int ret = 0; char buf[24]; rtw_memset(buf, 0, sizeof(buf)); snprintf(buf, 24, "get_ap_info %x", ap_info); ret = wext_private_command(ifname, buf, 0); snprintf(buf, 24, "get_security"); ret = wext_private_command_with_retval(ifname, buf, buf, 24); sscanf(buf, "%d", security); return ret; } #endif int wext_set_mode(const char *ifname, int mode) { struct iwreq iwr; int ret = 0; memset(&iwr, 0, sizeof(iwr)); iwr.u.mode = mode; if (iw_ioctl(ifname, SIOCSIWMODE, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWMODE] error"); ret = -1; } return ret; } int wext_get_mode(const char *ifname, int *mode) { struct iwreq iwr; int ret = 0; memset(&iwr, 0, sizeof(iwr)); if (iw_ioctl(ifname, SIOCGIWMODE, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCGIWMODE] error"); ret = -1; } else *mode = iwr.u.mode; return ret; } int wext_set_ap_ssid(const char *ifname, const __u8 *ssid, __u16 ssid_len) { struct iwreq iwr; int ret = 0; if(ssid_len > 32){ printf("Error: SSID should be 0-32 characters\r\n"); return -1; } memset(&iwr, 0, sizeof(iwr)); iwr.u.essid.pointer = (void *) ssid; iwr.u.essid.length = ssid_len; iwr.u.essid.flags = (ssid_len != 0); if (iw_ioctl(ifname, SIOCSIWPRIVAPESSID, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWPRIVAPESSID] error"); ret = -1; } return ret; } int wext_set_country(const char *ifname, rtw_country_code_t country_code) { struct iwreq iwr; int ret = 0; memset(&iwr, 0, sizeof(iwr)); iwr.u.param.value = country_code; if (iw_ioctl(ifname, SIOCSIWPRIVCOUNTRY, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWPRIVCOUNTRY] error"); ret = -1; } return ret; } int wext_get_rssi(const char *ifname, int *rssi) { struct iwreq iwr; int ret = 0; memset(&iwr, 0, sizeof(iwr)); if (iw_ioctl(ifname, SIOCGIWSENS, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCGIWSENS] error"); ret = -1; } else { *rssi = 0 - iwr.u.sens.value; } return ret; } int wext_get_bcn_rssi(const char *ifname, int *rssi) { struct iwreq iwr; int ret = 0; memset(&iwr, 0, sizeof(iwr)); if (iw_ioctl(ifname, SIOCGIWBCNSENS, &iwr) < 0) { printf("\n\rioctl[SIOCGIWBCNSENS] error"); ret = -1; } else { *rssi = 0 - iwr.u.bcnsens.value; } return ret; } int wext_set_pscan_channel(const char *ifname, __u8 *ch, __u8 *pscan_config, __u8 length) { struct iwreq iwr; int ret = 0; __u8 *para = NULL; int i =0; memset(&iwr, 0, sizeof(iwr)); //Format of para:function_name num_channel chan1... pscan_config1 ... para = rtw_malloc((length + length + 1) + 12);//size:num_chan + num_time + length + function_name if(para == NULL) return -1; //Cmd snprintf((char*)para, 12, "PartialScan"); //length *(para+12) = length; for(i = 0; i < length; i++){ *(para + 13 + i)= *(ch + i); *(para + 13 + length + i)= *(pscan_config + i); } iwr.u.data.pointer = para; iwr.u.data.length = (length + length + 1) + 12; if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rwext_set_pscan_channel():ioctl[SIOCDEVPRIVATE] error"); ret = -1; } rtw_free(para); return ret; } int wext_set_channel(const char *ifname, __u8 ch) { struct iwreq iwr; int ret = 0; memset(&iwr, 0, sizeof(iwr)); iwr.u.freq.m = 0; iwr.u.freq.e = 0; iwr.u.freq.i = ch; if (iw_ioctl(ifname, SIOCSIWFREQ, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWFREQ] error"); ret = -1; } return ret; } int wext_get_channel(const char *ifname, __u8 *ch) { struct iwreq iwr; int ret = 0; memset(&iwr, 0, sizeof(iwr)); if (iw_ioctl(ifname, SIOCGIWFREQ, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCGIWFREQ] error"); ret = -1; } else *ch = iwr.u.freq.i; return ret; } int wext_register_multicast_address(const char *ifname, rtw_mac_t *mac) { int ret = 0; char buf[32]; rtw_memset(buf, 0, sizeof(buf)); snprintf(buf, 32, "reg_multicast "MAC_FMT, MAC_ARG(mac->octet)); ret = wext_private_command(ifname, buf, 0); return ret; } int wext_unregister_multicast_address(const char *ifname, rtw_mac_t *mac) { int ret = 0; char buf[35]; rtw_memset(buf, 0, sizeof(buf)); snprintf(buf, 35, "reg_multicast -d "MAC_FMT, MAC_ARG(mac->octet)); ret = wext_private_command(ifname, buf, 0); return ret; } int wext_set_scan(const char *ifname, char *buf, __u16 buf_len, __u16 flags) { struct iwreq iwr; int ret = 0; memset(&iwr, 0, sizeof(iwr)); #if 0 //for scan_with_ssid if(buf) memset(buf, 0, buf_len); #endif iwr.u.data.pointer = buf; iwr.u.data.flags = flags; iwr.u.data.length = buf_len; if (iw_ioctl(ifname, SIOCSIWSCAN, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWSCAN] error"); ret = -1; } return ret; } int wext_get_scan(const char *ifname, char *buf, __u16 buf_len) { struct iwreq iwr; int ret = 0; iwr.u.data.pointer = buf; iwr.u.data.length = buf_len; if (iw_ioctl(ifname, SIOCGIWSCAN, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCGIWSCAN] error"); ret = -1; }else ret = iwr.u.data.flags; return ret; } int wext_private_command_with_retval(const char *ifname, char *cmd, char *ret_buf, int ret_len) { struct iwreq iwr; int ret = 0; unsigned int buf_size; char *buf; buf_size = 128; if(strlen(cmd) >= buf_size) buf_size = strlen(cmd) + 1; // 1 : '\0' buf = (char*)rtw_malloc(buf_size); if(!buf){ RTW_API_INFO("\n\rWEXT: Can't malloc memory"); return -1; } memset(buf, 0, buf_size); strncpy(buf, cmd, buf_size); memset(&iwr, 0, sizeof(iwr)); iwr.u.data.pointer = buf; iwr.u.data.length = buf_size; iwr.u.data.flags = 0; if ((ret = iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr)) < 0) { RTW_API_INFO("\n\rioctl[SIOCDEVPRIVATE] error. ret=%d\n", ret); } if(ret_buf){ if(ret_len > iwr.u.data.length) ret_len = iwr.u.data.length; rtw_memcpy(ret_buf, (char *) iwr.u.data.pointer, ret_len); } rtw_free(buf); return ret; } int wext_private_command(const char *ifname, char *cmd, int show_msg) { struct iwreq iwr; int ret = 0; unsigned int buf_size; char *buf; u8 cmdname[17] = {0}; // IFNAMSIZ+1 sscanf(cmd, "%16s", cmdname); if((strcmp((const char *)cmdname, "config_get") == 0) || (strcmp((const char *)cmdname, "config_set") == 0) || (strcmp((const char *)cmdname, "efuse_get") == 0) || (strcmp((const char *)cmdname, "efuse_set") == 0) || (strcmp((const char *)cmdname, "mp_psd") == 0)) buf_size = 2600;//2600 for config_get rmap,0,512 (or realmap) else buf_size = 512; if(strlen(cmd) >= buf_size) buf_size = strlen(cmd) + 1; // 1 : '\0' buf = (char*)rtw_malloc(buf_size); if(!buf){ RTW_API_INFO("\n\rWEXT: Can't malloc memory"); return -1; } memset(buf, 0, buf_size); strncpy(buf, cmd, buf_size); memset(&iwr, 0, sizeof(iwr)); iwr.u.data.pointer = buf; iwr.u.data.length = buf_size; iwr.u.data.flags = 0; if ((ret = iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr)) < 0) { RTW_API_INFO("\n\rioctl[SIOCDEVPRIVATE] error. ret=%d\n", ret); } if (show_msg && iwr.u.data.length) { if(iwr.u.data.length > buf_size) RTW_API_INFO("\n\rWEXT: Malloc memory is not enough"); RTW_API_INFO("\n\rPrivate Message: %s", (char *) iwr.u.data.pointer); } rtw_free(buf); return ret; } void wext_wlan_indicate(unsigned int cmd, union iwreq_data *wrqu, char *extra) { unsigned char null_mac[6] = {0}; switch(cmd) { case SIOCGIWAP: if(wrqu->ap_addr.sa_family == ARPHRD_ETHER) { if(!memcmp(wrqu->ap_addr.sa_data, null_mac, sizeof(null_mac))) wifi_indication(WIFI_EVENT_DISCONNECT, wrqu->ap_addr.sa_data, sizeof(null_mac)+ 2, 0); else wifi_indication(WIFI_EVENT_CONNECT, wrqu->ap_addr.sa_data, sizeof(null_mac), 0); } break; case IWEVCUSTOM: if(extra) { if(!memcmp(IW_EXT_STR_FOURWAY_DONE, extra, strlen(IW_EXT_STR_FOURWAY_DONE))) wifi_indication(WIFI_EVENT_FOURWAY_HANDSHAKE_DONE, extra, strlen(IW_EXT_STR_FOURWAY_DONE), 0); else if(!memcmp(IW_EXT_STR_RECONNECTION_FAIL, extra, strlen(IW_EXT_STR_RECONNECTION_FAIL))) wifi_indication(WIFI_EVENT_RECONNECTION_FAIL, extra, strlen(IW_EXT_STR_RECONNECTION_FAIL), 0); else if(!memcmp(IW_EVT_STR_NO_NETWORK, extra, strlen(IW_EVT_STR_NO_NETWORK))) wifi_indication(WIFI_EVENT_NO_NETWORK, extra, strlen(IW_EVT_STR_NO_NETWORK), 0); else if(!memcmp(IW_EVT_STR_ICV_ERROR, extra, strlen(IW_EVT_STR_ICV_ERROR))) wifi_indication(WIFI_EVENT_ICV_ERROR, extra, strlen(IW_EVT_STR_ICV_ERROR), 0); else if(!memcmp(IW_EVT_STR_CHALLENGE_FAIL, extra, strlen(IW_EVT_STR_CHALLENGE_FAIL))) wifi_indication(WIFI_EVENT_CHALLENGE_FAIL, extra, strlen(IW_EVT_STR_CHALLENGE_FAIL), 0); #if CONFIG_ENABLE_P2P || defined(CONFIG_AP_MODE) else if(!memcmp(IW_EVT_STR_STA_ASSOC, extra, strlen(IW_EVT_STR_STA_ASSOC))) wifi_indication(WIFI_EVENT_STA_ASSOC, wrqu->data.pointer, wrqu->data.length, 0); else if(!memcmp(IW_EVT_STR_STA_DISASSOC, extra, strlen(IW_EVT_STR_STA_DISASSOC))) wifi_indication(WIFI_EVENT_STA_DISASSOC, wrqu->addr.sa_data, sizeof(null_mac), 0); else if(!memcmp(IW_EVT_STR_SEND_ACTION_DONE, extra, strlen(IW_EVT_STR_SEND_ACTION_DONE))) wifi_indication(WIFI_EVENT_SEND_ACTION_DONE, NULL, 0, wrqu->data.flags); else if(!memcmp(IW_EVT_STR_SOFTAP_START, extra, strlen(IW_EVT_STR_SOFTAP_START))) wifi_indication(WIFI_EVENT_SOFTAP_START, extra, strlen(IW_EVT_STR_SOFTAP_START), 0); else if(!memcmp(IW_EVT_STR_SOFTAP_STOP, extra, strlen(IW_EVT_STR_SOFTAP_STOP))) wifi_indication(WIFI_EVENT_SOFTAP_STOP, extra, strlen(IW_EVT_STR_SOFTAP_STOP), 0); #endif } break; case SIOCGIWSCAN: if(wrqu->data.pointer == NULL) wifi_indication(WIFI_EVENT_SCAN_DONE, NULL, 0, 0); else wifi_indication(WIFI_EVENT_SCAN_RESULT_REPORT, wrqu->data.pointer, wrqu->data.length, 0); break; case IWEVMGNTRECV: wifi_indication(WIFI_EVENT_RX_MGNT, wrqu->data.pointer, wrqu->data.length, wrqu->data.flags); break; #ifdef REPORT_STA_EVENT case IWEVREGISTERED: if(wrqu->addr.sa_family == ARPHRD_ETHER) wifi_indication(WIFI_EVENT_STA_ASSOC, wrqu->addr.sa_data, sizeof(null_mac), 0); break; case IWEVEXPIRED: if(wrqu->addr.sa_family == ARPHRD_ETHER) wifi_indication(WIFI_EVENT_STA_DISASSOC, wrqu->addr.sa_data, sizeof(null_mac), 0); break; #endif default: break; } } int wext_send_eapol(const char *ifname, char *buf, __u16 buf_len, __u16 flags) { struct iwreq iwr; int ret = 0; memset(&iwr, 0, sizeof(iwr)); iwr.u.data.pointer = buf; iwr.u.data.length = buf_len; iwr.u.data.flags = flags; if (iw_ioctl(ifname, SIOCSIWEAPOLSEND, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWEAPOLSEND] error"); ret = -1; } return ret; } int wext_send_mgnt(const char *ifname, char *buf, __u16 buf_len, __u16 flags) { struct iwreq iwr; int ret = 0; memset(&iwr, 0, sizeof(iwr)); iwr.u.data.pointer = buf; iwr.u.data.length = buf_len; iwr.u.data.flags = flags; if (iw_ioctl(ifname, SIOCSIWMGNTSEND, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWMGNTSEND] error"); ret = -1; } return ret; } int wext_set_gen_ie(const char *ifname, char *buf, __u16 buf_len, __u16 flags) { struct iwreq iwr; int ret = 0; memset(&iwr, 0, sizeof(iwr)); iwr.u.data.pointer = buf; iwr.u.data.length = buf_len; iwr.u.data.flags = flags; if (iw_ioctl(ifname, SIOCSIWGENIE, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWGENIE] error"); ret = -1; } return ret; } int wext_set_autoreconnect(const char *ifname, __u8 mode, __u8 retry_times, __u16 timeout) { struct iwreq iwr; int ret = 0; __u8 *para = NULL; int cmd_len = 0; memset(&iwr, 0, sizeof(iwr)); cmd_len = sizeof("SetAutoRecnt"); para = rtw_malloc((4) + cmd_len);//size:para_len+cmd_len if(para == NULL) return -1; //Cmd snprintf((char*)para, cmd_len, "SetAutoRecnt"); //length *(para+cmd_len) = mode; //para1 *(para+cmd_len+1) = retry_times; //para2 *(para+cmd_len+2) = timeout; //para3 iwr.u.data.pointer = para; iwr.u.data.length = (4) + cmd_len; if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rwext_set_autoreconnect():ioctl[SIOCDEVPRIVATE] error"); ret = -1; } rtw_free(para); return ret; } int wext_get_autoreconnect(const char *ifname, __u8 *mode) { struct iwreq iwr; int ret = 0; __u8 *para = NULL; int cmd_len = 0; memset(&iwr, 0, sizeof(iwr)); cmd_len = sizeof("GetAutoRecnt"); para = rtw_malloc(cmd_len);//size:para_len+cmd_len //Cmd snprintf((char*)para, cmd_len, "GetAutoRecnt"); //length iwr.u.data.pointer = para; iwr.u.data.length = cmd_len; if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rwext_get_autoreconnect():ioctl[SIOCDEVPRIVATE] error"); ret = -1; } *mode = *(__u8 *)(iwr.u.data.pointer); rtw_free(para); return ret; } int wext_get_drv_ability(const char *ifname, __u32 *ability) { int ret = 0; char * buf = (char *)rtw_zmalloc(33); if(buf == NULL) return -1; snprintf(buf, 33, "get_drv_ability %x", (unsigned int)ability); ret = wext_private_command(ifname, buf, 0); rtw_free(buf); return ret; } #ifdef CONFIG_CUSTOM_IE int wext_add_custom_ie(const char *ifname, void *cus_ie, int ie_num) { struct iwreq iwr; int ret = 0; __u8 *para = NULL; int cmd_len = 0; if(ie_num <= 0 || !cus_ie){ RTW_API_INFO("\n\rwext_add_custom_ie():wrong parameter"); ret = -1; return ret; } memset(&iwr, 0, sizeof(iwr)); cmd_len = sizeof("SetCusIE"); para = rtw_malloc((4)* 2 + cmd_len);//size:addr len+cmd_len if(para == NULL) return -1; //Cmd snprintf((char*)para, cmd_len, "SetCusIE"); //addr length *(__u32 *)(para + cmd_len) = (__u32)cus_ie; //ie addr //ie_num *(__u32 *)(para + cmd_len + 4) = ie_num; //num of ie iwr.u.data.pointer = para; iwr.u.data.length = (4)* 2 + cmd_len;// 2 input if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rwext_add_custom_ie():ioctl[SIOCDEVPRIVATE] error"); ret = -1; } rtw_free(para); return ret; } int wext_update_custom_ie(const char *ifname, void * cus_ie, int ie_index) { struct iwreq iwr; int ret = 0; __u8 *para = NULL; int cmd_len = 0; if(ie_index <= 0 || !cus_ie){ RTW_API_INFO("\n\rwext_update_custom_ie():wrong parameter"); ret = -1; return ret; } memset(&iwr, 0, sizeof(iwr)); cmd_len = sizeof("UpdateIE"); para = rtw_malloc((4)* 2 + cmd_len);//size:addr len+cmd_len if(para == NULL) return -1; //Cmd snprintf((char*)para, cmd_len, "UpdateIE"); //addr length *(__u32 *)(para + cmd_len) = (__u32)cus_ie; //ie addr //ie_index *(__u32 *)(para + cmd_len + 4) = ie_index; //num of ie iwr.u.data.pointer = para; iwr.u.data.length = (4)* 2 + cmd_len;// 2 input if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rwext_update_custom_ie():ioctl[SIOCDEVPRIVATE] error"); ret = -1; } rtw_free(para); return ret; } int wext_del_custom_ie(const char *ifname) { struct iwreq iwr; int ret = 0; __u8 *para = NULL; int cmd_len = 0; memset(&iwr, 0, sizeof(iwr)); cmd_len = sizeof("DelIE"); para = rtw_malloc(cmd_len);//size:addr len+cmd_len //Cmd snprintf((char*)para, cmd_len, "DelIE"); iwr.u.data.pointer = para; iwr.u.data.length = cmd_len; if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rwext_del_custom_ie():ioctl[SIOCDEVPRIVATE] error"); ret = -1; } rtw_free(para); return ret; } #endif #ifdef CONFIG_AP_MODE int wext_enable_forwarding(const char *ifname) { struct iwreq iwr; int ret = 0; __u8 *para = NULL; int cmd_len = 0; memset(&iwr, 0, sizeof(iwr)); cmd_len = sizeof("forwarding_set"); para = rtw_malloc(cmd_len + 1); if(para == NULL) return -1; // forwarding_set 1 snprintf((char *) para, cmd_len, "forwarding_set"); *(para + cmd_len) = '1'; iwr.u.essid.pointer = para; iwr.u.essid.length = cmd_len + 1; if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rwext_enable_forwarding(): ioctl[SIOCDEVPRIVATE] error"); ret = -1; } rtw_free(para); return ret; } int wext_disable_forwarding(const char *ifname) { struct iwreq iwr; int ret = 0; __u8 *para = NULL; int cmd_len = 0; memset(&iwr, 0, sizeof(iwr)); cmd_len = sizeof("forwarding_set"); para = rtw_malloc(cmd_len + 1); if(para == NULL) return -1; // forwarding_set 0 snprintf((char *) para, cmd_len, "forwarding_set"); *(para + cmd_len) = '0'; iwr.u.essid.pointer = para; iwr.u.essid.length = cmd_len + 1; if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rwext_disable_forwarding(): ioctl[SIOCDEVPRIVATE] error"); ret = -1; } rtw_free(para); return ret; } #endif #ifdef CONFIG_CONCURRENT_MODE int wext_set_ch_deauth(const char *ifname, __u8 enable) { int ret = 0; char * buf = (char *)rtw_zmalloc(16); if(buf == NULL) return -1; snprintf(buf, 16, "SetChDeauth %d", enable); ret = wext_private_command(ifname, buf, 0); rtw_free(buf); return ret; } #endif int wext_set_adaptivity(rtw_adaptivity_mode_t adaptivity_mode) { extern u8 rtw_adaptivity_en; extern u8 rtw_adaptivity_mode; switch(adaptivity_mode){ case RTW_ADAPTIVITY_NORMAL: rtw_adaptivity_en = 1; // enable adaptivity rtw_adaptivity_mode = RTW_ADAPTIVITY_MODE_NORMAL; break; case RTW_ADAPTIVITY_CARRIER_SENSE: rtw_adaptivity_en = 1; // enable adaptivity rtw_adaptivity_mode = RTW_ADAPTIVITY_MODE_CARRIER_SENSE; break; case RTW_ADAPTIVITY_DISABLE: default: rtw_adaptivity_en = 0; //disable adaptivity break; } return 0; } int wext_set_trp_tis(__u8 enable) { extern u8 rtw_tx_pwr_lmt_enable; extern u8 rtw_tx_pwr_by_rate; extern u8 rtw_trp_tis_cert_en; #ifdef CONFIG_POWER_SAVING extern u8 rtw_powersave_en; #endif if(enable != RTW_TRP_TIS_DISABLE){ //close the tx power limit and pwr by rate incase the efficiency of Antenna is not good enough. rtw_tx_pwr_lmt_enable = 2;//set 0 to disable, set 2 to use efuse value rtw_tx_pwr_by_rate = 2;//set 0 to disable, set 2 to use efuse value //disable power save. #ifdef CONFIG_POWER_SAVING rtw_powersave_en = 0; #endif if(enable == RTW_TRP_TIS_NORMAL){ //disable some dynamic mechanism rtw_trp_tis_cert_en = BIT0; }else if(enable == RTW_TRP_TIS_DYNAMIC){ rtw_trp_tis_cert_en = BIT1 | BIT0; }else if(enable == RTW_TRP_TIS_FIX_ACK_RATE){ rtw_trp_tis_cert_en = BIT2 | BIT0; } //you can change autoreconnct mode to RTW_AUTORECONNECT_INFINITE in init_thread function } return 0; } int wext_set_anti_interference(__u8 enable) { extern u8 rtw_anti_interference_en; if(enable == ENABLE){ rtw_anti_interference_en = 1; }else{ rtw_anti_interference_en = 0; } return 0; } int wext_set_ant_div_gpio(__u8 type) { extern u8 rtw_ant_div_gpio_ext; rtw_ant_div_gpio_ext = type; return 0; } int wext_set_adaptivity_th_l2h_ini(__u8 l2h_threshold) { extern s8 rtw_adaptivity_th_l2h_ini; rtw_adaptivity_th_l2h_ini = (__s8)l2h_threshold; return 0; } int wext_set_bw40_enable(__u8 enable) { extern u8 rtw_cbw40_enable; /* 0: 20 MHz, 1: 40 MHz, 2: 80 MHz, 3: 160MHz, 4: 80+80MHz * 2.4G use bit 0 ~ 3, 5G use bit 4 ~ 7 * 0x21 means enable 2.4G 40MHz & 5G 80MHz */ extern u8 rtw_bw_mode; if(enable == ENABLE){ rtw_cbw40_enable = 1; rtw_bw_mode = 0x11; }else{ rtw_cbw40_enable = 0; rtw_bw_mode = 0; } return 0; } extern int rltk_get_auto_chl(const char *ifname, unsigned char *channel_set, unsigned char channel_num); int wext_get_auto_chl(const char *ifname, unsigned char *channel_set, unsigned char channel_num) { int ret = -1; int channel = 0; wext_disable_powersave(ifname); if((channel = rltk_get_auto_chl(ifname,channel_set,channel_num)) != 0 ) ret = channel ; wext_enable_powersave(ifname, 1, 1); return ret; } extern int rltk_set_sta_num(unsigned char ap_sta_num); int wext_set_sta_num(unsigned char ap_sta_num) { return rltk_set_sta_num(ap_sta_num); } extern int rltk_del_station(const char *ifname, unsigned char* hwaddr); int wext_del_station(const char *ifname, unsigned char* hwaddr) { return rltk_del_station(ifname, hwaddr); } extern struct list_head *mf_list_head; int wext_init_mac_filter(void) { if(mf_list_head != NULL){ return -1; } mf_list_head = (struct list_head *)malloc(sizeof(struct list_head)); if(mf_list_head == NULL){ RTW_API_INFO("\n\r[ERROR] %s : can't allocate mf_list_head",__func__); return -1; } INIT_LIST_HEAD(mf_list_head); return 0; } int wext_deinit_mac_filter(void) { if(mf_list_head == NULL){ return -1; } struct list_head *iterator; rtw_mac_filter_list_t *item; list_for_each(iterator, mf_list_head) { item = list_entry(iterator, rtw_mac_filter_list_t, node); list_del(iterator); free(item); item = NULL; iterator = mf_list_head; } free(mf_list_head); mf_list_head = NULL; return 0; } int wext_add_mac_filter(unsigned char* hwaddr) { if(mf_list_head == NULL){ return -1; } rtw_mac_filter_list_t *mf_list_new; mf_list_new =(rtw_mac_filter_list_t *) malloc(sizeof(rtw_mac_filter_list_t)); if(mf_list_new == NULL){ RTW_API_INFO("\n\r[ERROR] %s : can't allocate mf_list_new",__func__); return -1; } memcpy(mf_list_new->mac_addr,hwaddr,6); list_add(&(mf_list_new->node), mf_list_head); return 0; } int wext_del_mac_filter(unsigned char* hwaddr) { if(mf_list_head == NULL){ return -1; } struct list_head *iterator; rtw_mac_filter_list_t *item; list_for_each(iterator, mf_list_head) { item = list_entry(iterator, rtw_mac_filter_list_t, node); if(memcmp(item->mac_addr,hwaddr,6) == 0){ list_del(iterator); free(item); item = NULL; return 0; } } return -1; } extern void rtw_set_indicate_mgnt(int enable); void wext_set_indicate_mgnt(int enable) { rtw_set_indicate_mgnt(enable); return; } #ifdef CONFIG_AP_MODE extern void rltk_suspend_softap(const char *ifname); extern void rltk_suspend_softap_beacon(const char *ifname); extern int rtw_ap_switch_chl_and_inform(unsigned char new_channel); void wext_suspend_softap(const char *ifname) { rltk_suspend_softap(ifname); } void wext_suspend_softap_beacon(const char *ifname) { rltk_suspend_softap_beacon(ifname); } int wext_ap_switch_chl_and_inform(unsigned char new_channel) { if(rtw_ap_switch_chl_and_inform(new_channel)) return RTW_SUCCESS; else return RTW_ERROR; } #endif #ifdef CONFIG_SW_MAILBOX_EN int wext_mailbox_to_wifi(const char *ifname, char *buf, __u16 buf_len) { struct iwreq iwr; int ret = 0; memset(&iwr, 0, sizeof(iwr)); iwr.u.data.pointer = buf; iwr.u.data.length = buf_len; if (iw_ioctl(ifname, SIOCSIMAILBOX, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIMAILBOX] error"); ret = -1; } return ret; } #endif #ifdef CONFIG_WOWLAN int wext_wowlan_ctrl(const char *ifname, int enable){ struct iwreq iwr; int ret = 0; __u16 pindex = 0; __u8 *para = NULL; int cmd_len = 0; printf("wext_wowlan_ctrl: enable=%d\n\r", enable); memset(&iwr, 0, sizeof(iwr)); cmd_len = sizeof("wowlan_ctrl"); // Encode parameters as TLV (type, length, value) format para = rtw_malloc( cmd_len + (1+1+1) ); snprintf((char*)para, cmd_len, "wowlan_ctrl"); pindex = cmd_len; para[pindex++] = 0; // type 0 wowlan enable disable para[pindex++] = 1; para[pindex++] = enable; iwr.u.data.pointer = para; iwr.u.data.length = pindex; if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWPRIVWWCTL] error"); ret = -1; } rtw_free(para); return ret; } int wext_wowlan_set_pattern(const char *ifname, wowlan_pattern_t pattern) { struct iwreq iwr; int ret = 0; __u16 pindex = 0; __u8 *para = NULL; int cmd_len = 0; memset(&iwr, 0, sizeof(iwr)); cmd_len = sizeof("wowlan_ctrl"); para = rtw_malloc( cmd_len + (1+1+1) + sizeof(pattern)); snprintf((char*)para, cmd_len, "wowlan_ctrl"); pindex = cmd_len; para[pindex++] = 1; // type 1 wowlan set pattern para[pindex++] = 2; para[pindex++] = sizeof(pattern); memcpy(&(para[pindex]), &pattern, sizeof(pattern)); iwr.u.data.pointer = para; iwr.u.data.length = pindex; if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCDEVPRIVWWPTN] error"); ret = -1; } rtw_free(para); return ret; } int wext_wlan_redl_fw(const char *ifname){ struct iwreq iwr; int ret = 0; __u16 pindex = 0; __u8 *para = NULL; int cmd_len = 0; printf("+ wext_wlan_redl_fw\n\r"); memset(&iwr, 0, sizeof(iwr)); cmd_len = sizeof("wowlan_ctrl"); // Encode parameters as TLV (type, length, value) format para = rtw_malloc( cmd_len + (1+1) ); snprintf((char*)para, cmd_len, "wowlan_ctrl"); pindex = cmd_len; para[pindex++] = 2; // type 2 redownload fw para[pindex++] = 0; iwr.u.data.pointer = para; iwr.u.data.length = pindex; if (iw_ioctl(ifname, SIOCDEVPRIVATE, &iwr) < 0) { RTW_API_INFO("\n\rioctl[SIOCSIWPRIVREDLFW] error"); ret = -1; } rtw_free(para); return ret; } #endif #ifdef CONFIG_POWER_SAVING extern u8 rtw_power_mgnt; void wext_set_powersave_mode(__u8 ps_mode){ if((ps_mode!=1)&&(ps_mode!=2)){ printf("\n\rSet powersave mode fail! Wrong powersave mode value, input value can only be 1(min mode) or 2(max mode)"); return; } rtw_power_mgnt = ps_mode; return; } void wext_get_powersave_mode(__u8 *ps_mode){ *ps_mode = rtw_power_mgnt; return; } #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/wifi_util.c
C
apache-2.0
42,823
/****************************************************************************** * Copyright (c) 2013-2016 Realtek Semiconductor Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ #ifndef _UTIL_H #define _UTIL_H #include <wireless.h> #include <wlan_intf.h> #include <wifi_constants.h> #include "wifi_structures.h" #ifdef __cplusplus extern "C" { #endif int wext_get_ssid(const char *ifname, __u8 *ssid); int wext_set_ssid(const char *ifname, const __u8 *ssid, __u16 ssid_len); int wext_set_bssid(const char *ifname, const __u8 *bssid); int wext_get_bssid(const char *ifname, __u8 *bssid); int wext_set_auth_param(const char *ifname, __u16 idx, __u32 value); int wext_set_mfp_support(const char *ifname, __u8 value); #ifdef CONFIG_SAE_SUPPORT int wext_set_group_id(const char *ifname, __u8 value); int wext_set_support_wpa3(__u8 enable); unsigned char wext_get_support_wpa3(void); #endif #ifdef CONFIG_PMKSA_CACHING int wext_set_pmk_cache_enable(const char *ifname, __u8 value); #endif int wext_set_key_ext(const char *ifname, __u16 alg, const __u8 *addr, int key_idx, int set_tx, const __u8 *seq, __u16 seq_len, __u8 *key, __u16 key_len); int wext_get_enc_ext(const char *ifname, __u16 *alg, __u8 *key_idx, __u8 *passphrase); int wext_set_passphrase(const char *ifname, const __u8 *passphrase, __u16 passphrase_len); int wext_get_passphrase(const char *ifname, __u8 *passphrase); int wext_set_mode(const char *ifname, int mode); int wext_get_mode(const char *ifname, int *mode); int wext_set_ap_ssid(const char *ifname, const __u8 *ssid, __u16 ssid_len); int wext_set_country(const char *ifname, rtw_country_code_t country_code); int wext_get_rssi(const char *ifname, int *rssi); int wifi_get_bcn_rssi(int *pRSSI); int wext_set_channel(const char *ifname, __u8 ch); int wext_get_channel(const char *ifname, __u8 *ch); int wext_register_multicast_address(const char *ifname, rtw_mac_t *mac); int wext_unregister_multicast_address(const char *ifname, rtw_mac_t *mac); int wext_set_scan(const char *ifname, char *buf, __u16 buf_len, __u16 flags); int wext_get_scan(const char *ifname, char *buf, __u16 buf_len); int wext_set_mac_address(const char *ifname, char * mac); int wext_get_mac_address(const char *ifname, char * mac); int wext_enable_powersave(const char *ifname, __u8 lps_mode, __u8 ips_mode); int wext_resume_powersave(const char *ifname); int wext_disable_powersave(const char *ifname); int wext_set_tdma_param(const char *ifname, __u8 slot_period, __u8 rfon_period_len_1, __u8 rfon_period_len_2, __u8 rfon_period_len_3); int wext_set_lps_dtim(const char *ifname, __u8 lps_dtim); int wext_get_lps_dtim(const char *ifname, __u8 *lps_dtim); int wext_set_lps_thresh(const char *ifname, __u8 low_thresh); #ifdef LONG_PERIOD_TICKLESS int wext_set_lps_smartps(const char *ifname, __u8 smart_ps); #endif int wext_set_beacon_mode(const char *ifname, __u8 mode); int wext_set_lps_level(const char *ifname, __u8 lps_level); int wext_get_tx_power(const char *ifname, __u8 *poweridx); int wext_set_txpower(const char *ifname, int poweridx); int wext_get_associated_client_list(const char *ifname, void * client_list_buffer, __u16 buffer_length); int wext_get_ap_info(const char *ifname, rtw_bss_info_t * ap_info, rtw_security_t* security); int wext_mp_command(const char *ifname, char *cmd, int show_msg); int wext_private_command(const char *ifname, char *cmd, int show_msg); int wext_private_command_with_retval(const char *ifname, char *cmd, char *ret_buf, int ret_len); void wext_wlan_indicate(unsigned int cmd, union iwreq_data *wrqu, char *extra); int wext_set_pscan_channel(const char *ifname, __u8 *ch, __u8 *pscan_config, __u8 length); int wext_set_autoreconnect(const char *ifname, __u8 mode, __u8 retry_times, __u16 timeout); int wext_get_autoreconnect(const char *ifname, __u8 *mode); int wext_set_adaptivity(rtw_adaptivity_mode_t adaptivity_mode); int wext_set_trp_tis(__u8 enable); int wext_set_anti_interference(__u8 enable); int wext_set_adaptivity_th_l2h_ini(__u8 l2h_threshold); int wext_get_auto_chl(const char *ifname, unsigned char *channel_set, unsigned char channel_num); int wext_set_sta_num(unsigned char ap_sta_num); int wext_del_station(const char *ifname, unsigned char* hwaddr); int wext_init_mac_filter(void); int wext_deinit_mac_filter(void); int wext_add_mac_filter(unsigned char* hwaddr); int wext_del_mac_filter(unsigned char* hwaddr); void wext_set_indicate_mgnt(int enable); #ifdef CONFIG_SW_MAILBOX_EN int wext_mailbox_to_wifi(const char *ifname, char *buf, __u16 buf_len); #endif #ifdef CONFIG_CUSTOM_IE int wext_add_custom_ie(const char *ifname, void * cus_ie, int ie_num); int wext_update_custom_ie(const char *ifname, void * cus_ie, int ie_index); int wext_del_custom_ie(const char *ifname); #endif #define wext_handshake_done rltk_wlan_handshake_done int wext_send_mgnt(const char *ifname, char *buf, __u16 buf_len, __u16 flags); int wext_send_eapol(const char *ifname, char *buf, __u16 buf_len, __u16 flags); int wext_set_gen_ie(const char *ifname, char *buf, __u16 buf_len, __u16 flags); int wext_get_drv_ability(const char *ifname, __u32 *ability); int wext_enable_forwarding(const char *ifname); int wext_disable_forwarding(const char *ifname); int wext_set_ch_deauth(const char *ifname, __u8 enable); int wext_ap_switch_chl_and_inform(unsigned char new_channel); #ifdef CONFIG_WOWLAN int wext_wowlan_ctrl(const char *ifname, int enable); int wext_wowlan_set_pattern(const char *ifname, wowlan_pattern_t pattern); int wext_wlan_redl_fw(const char *ifname); #endif #ifdef CONFIG_POWER_SAVING void wext_set_powersave_mode(__u8 ps_mode); void wext_get_powersave_mode(__u8 *ps_mode); #endif int wext_get_bcn_rssi(const char *ifname, int *rssi); int wext_set_ant_div_gpio(__u8 type); int wext_set_bw40_enable(__u8 enable); extern int (*p_wlan_mgmt_filter)(__u8 *ie, __u16 ie_len, __u16 frame_type); extern int (*p_wlan_action_filter)(__u8 *ie, __u16 ie_len, __u16 frame_type); #ifdef __cplusplus } #endif #endif /* _UTIL_H */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi/wifi_util.h
C
apache-2.0
6,573
#if !defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) #include "FreeRTOS.h" #include "task.h" #include "semphr.h" #include "main.h" #include <lwip_netconf.h> #include "tcpip.h" #include <wlan/wlan_test_inc.h> #include <dhcp/dhcps.h> #endif #include <osdep_service.h> #include <wifi/wifi_conf.h> #include <wifi/wifi_util.h> #include <platform/platform_stdlib.h> #ifndef CONFIG_INTERACTIVE_EXT #define CONFIG_INTERACTIVE_EXT 0 #endif #ifndef CONFIG_SSL_CLIENT #define CONFIG_SSL_CLIENT 1 #endif #ifndef CONFIG_GOOGLENEST #define CONFIG_GOOGLENEST 0 #endif #if CONFIG_LWIP_LAYER #ifndef CONFIG_WEBSERVER #define CONFIG_WEBSERVER 0 #endif #endif #ifndef CONFIG_OTA_UPDATE #define CONFIG_OTA_UPDATE 0 #endif #ifndef CONFIG_BSD_TCP #define CONFIG_BSD_TCP 0 #endif #define CONFIG_JD_SMART 0 #ifndef CONFIG_ENABLE_P2P #define CONFIG_ENABLE_P2P 0 #endif #define SCAN_WITH_SSID 0 #ifdef CONFIG_WPS #define STACKSIZE 1280 #else #define STACKSIZE 1024 #endif #ifndef WLAN0_NAME #define WLAN0_NAME "wlan0" #endif #ifndef WLAN1_NAME #define WLAN1_NAME "wlan1" #endif /* Give default value if not defined */ #ifndef NET_IF_NUM #ifdef CONFIG_CONCURRENT_MODE #define NET_IF_NUM 2 #else #define NET_IF_NUM 1 #endif #endif /*Static IP ADDRESS*/ #ifndef IP_ADDR0 #define IP_ADDR0 192 #define IP_ADDR1 168 #define IP_ADDR2 1 #define IP_ADDR3 80 #endif /*NETMASK*/ #ifndef NETMASK_ADDR0 #define NETMASK_ADDR0 255 #define NETMASK_ADDR1 255 #define NETMASK_ADDR2 255 #define NETMASK_ADDR3 0 #endif /*Gateway Address*/ #ifndef GW_ADDR0 #define GW_ADDR0 192 #define GW_ADDR1 168 #define GW_ADDR2 1 #define GW_ADDR3 1 #endif /*Static IP ADDRESS*/ #ifndef AP_IP_ADDR0 #define AP_IP_ADDR0 192 #define AP_IP_ADDR1 168 #define AP_IP_ADDR2 43 #define AP_IP_ADDR3 1 #endif /*NETMASK*/ #ifndef AP_NETMASK_ADDR0 #define AP_NETMASK_ADDR0 255 #define AP_NETMASK_ADDR1 255 #define AP_NETMASK_ADDR2 255 #define AP_NETMASK_ADDR3 0 #endif /*Gateway Address*/ #ifndef AP_GW_ADDR0 #define AP_GW_ADDR0 192 #define AP_GW_ADDR1 168 #define AP_GW_ADDR2 43 #define AP_GW_ADDR3 1 #endif static void cmd_help(int argc, char **argv); #if CONFIG_SSL_CLIENT extern void cmd_ssl_client(int argc, char **argv); #endif #if CONFIG_GOOGLENEST extern void cmd_googlenest(int argc, char **argv); #endif #if CONFIG_JD_SMART extern void cmd_jd_smart(int argc, char **argv); #endif #if CONFIG_BSD_TCP extern void cmd_tcp(int argc, char **argv); extern void cmd_udp(int argc, char **argv); #endif #if CONFIG_WLAN static void cmd_wifi_on(int argc, char **argv); static void cmd_wifi_off(int argc, char **argv); static void cmd_wifi_disconnect(int argc, char **argv); extern void cmd_promisc(int argc, char **argv); extern void cmd_simple_config(int argc, char **argv); #if CONFIG_OTA_UPDATE extern void cmd_update(int argc, char **argv); #endif #if CONFIG_WEBSERVER extern void start_web_server(void); extern void stop_web_server(void); #endif extern void cmd_app(int argc, char **argv); #if CONFIG_ENABLE_WPS extern void cmd_wps(int argc, char **argv); #endif #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP extern void cmd_ap_wps(int argc, char **argv); extern int wpas_wps_dev_config(u8 *dev_addr, u8 bregistrar); #endif //CONFIG_ENABLE_WPS_AP #if CONFIG_ENABLE_P2P extern void cmd_wifi_p2p_start(int argc, char **argv); extern void cmd_wifi_p2p_stop(int argc, char **argv); extern void cmd_p2p_listen(int argc, char **argv); extern void cmd_p2p_find(int argc, char **argv); extern void cmd_p2p_peers(int argc, char **argv); extern void cmd_p2p_info(int argc, char **argv); extern void cmd_p2p_disconnect(int argc, char **argv); extern void cmd_p2p_connect(int argc, char **argv); #endif //CONFIG_ENABLE_P2P #if defined(CONFIG_RTL8195A) || defined(CONFIG_RTL8711B) || defined(CONFIG_RTL8721D) extern u32 CmdDumpWord(IN u16 argc, IN u8 *argv[]); extern u32 CmdWriteWord(IN u16 argc, IN u8 *argv[]); #endif #if CONFIG_LWIP_LAYER extern struct netif xnetif[NET_IF_NUM]; #endif #ifdef CONFIG_CONCURRENT_MODE static void cmd_wifi_sta_and_ap(int argc, char **argv) { int timeout = 20;//, mode; #if CONFIG_LWIP_LAYER #if !defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) struct netif * pnetiff = (struct netif *)&xnetif[1]; #endif #endif int channel; if((argc != 3) && (argc != 4)) { printf("\n\rUsage: wifi_ap SSID CHANNEL [PASSWORD]"); return; } if(atoi((const char *)argv[2]) > 14){ printf("\n\r bad channel!Usage: wifi_ap SSID CHANNEL [PASSWORD]"); return; } #if CONFIG_LWIP_LAYER #if defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO #else dhcps_deinit(); #endif #endif #if 0 //Check mode wext_get_mode(WLAN0_NAME, &mode); switch(mode) { case IW_MODE_MASTER: //In AP mode cmd_wifi_off(0, NULL); cmd_wifi_on(0, NULL); break; case IW_MODE_INFRA: //In STA mode if(wext_get_ssid(WLAN0_NAME, ssid) > 0) cmd_wifi_disconnect(0, NULL); } #endif wifi_off(); #if defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO //delay 20 Ticks #else vTaskDelay(20); #endif if (wifi_on(RTW_MODE_STA_AP) < 0){ printf("\n\rERROR: Wifi on failed!"); return; } printf("\n\rStarting AP ..."); channel = atoi((const char *)argv[2]); if(channel > 13){ printf("\n\rChannel is from 1 to 13. Set channel 1 as default!\n"); channel = 1; } if(argc == 4) { if(wifi_start_ap(argv[1], RTW_SECURITY_WPA2_AES_PSK, argv[3], strlen((const char *)argv[1]), strlen((const char *)argv[3]), channel ) != RTW_SUCCESS) { printf("\n\rERROR: Operation failed!"); return; } } else { if(wifi_start_ap(argv[1], RTW_SECURITY_OPEN, NULL, strlen((const char *)argv[1]), 0, channel ) != RTW_SUCCESS) { printf("\n\rERROR: Operation failed!"); return; } } while(1) { char essid[33]; if(wext_get_ssid(WLAN1_NAME, (unsigned char *) essid) > 0) { if(strcmp((const char *) essid, (const char *)argv[1]) == 0) { printf("\n\r%s started", argv[1]); break; } } if(timeout == 0) { printf("\n\rERROR: Start AP timeout!"); break; } #if defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO //Delay 1s #else vTaskDelay(1 * configTICK_RATE_HZ); #endif timeout --; } #if CONFIG_LWIP_LAYER #if defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO #else LwIP_UseStaticIP(&xnetif[1]); #ifdef CONFIG_DONT_CARE_TP pnetiff->flags |= NETIF_FLAG_IPSWITCH; #endif dhcps_init(pnetiff); #endif #endif } #endif static void cmd_wifi_ap(int argc, char **argv) { int timeout = 20; #if CONFIG_LWIP_LAYER #if !defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) struct ip_addr ipaddr; struct ip_addr netmask; struct ip_addr gw; struct netif * pnetif = &xnetif[0]; #endif #endif int channel; #ifdef CONFIG_IEEE80211W if((argc != 3) && (argc != 4) && (argc != 5)) { printf("\n\rUsage: wifi_ap SSID CHANNEL [PASSWORD] [MFP_SUPPORT]"); return; } #else if((argc != 3) && (argc != 4)) { printf("\n\rUsage: wifi_ap SSID CHANNEL [PASSWORD]"); return; } #endif #if CONFIG_LWIP_LAYER #if defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO #else dhcps_deinit(); #if LWIP_VERSION_MAJOR >= 2 IP4_ADDR(ip_2_ip4(&ipaddr), GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3); IP4_ADDR(ip_2_ip4(&netmask), NETMASK_ADDR0, NETMASK_ADDR1 , NETMASK_ADDR2, NETMASK_ADDR3); IP4_ADDR(ip_2_ip4(&gw), GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3); netif_set_addr(pnetif, ip_2_ip4(&ipaddr), ip_2_ip4(&netmask),ip_2_ip4(&gw)); #else IP4_ADDR(&ipaddr, GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3); IP4_ADDR(&netmask, NETMASK_ADDR0, NETMASK_ADDR1 , NETMASK_ADDR2, NETMASK_ADDR3); IP4_ADDR(&gw, GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3); netif_set_addr(pnetif, &ipaddr, &netmask,&gw); #endif #ifdef CONFIG_DONT_CARE_TP pnetif->flags |= NETIF_FLAG_IPSWITCH; #endif #endif #endif #if 0 //Check mode wext_get_mode(WLAN0_NAME, &mode); switch(mode) { case IW_MODE_MASTER: //In AP mode wifi_off(); wifi_on(1); break; case IW_MODE_INFRA: //In STA mode if(wext_get_ssid(WLAN0_NAME, ssid) > 0) cmd_wifi_disconnect(0, NULL); } #else wifi_off(); #if defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO //Delay 20 Ticks #else vTaskDelay(20); #endif if (wifi_on(RTW_MODE_AP) < 0){ printf("\n\rERROR: Wifi on failed!"); return; } #endif printf("\n\rStarting AP ..."); channel = atoi((const char *)argv[2]); if(channel > 13){ printf("\n\rChannel is from 1 to 13. Set channel 1 as default!\n"); channel = 1; } #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP wpas_wps_dev_config(pnetif->hwaddr, 1); #endif if(argc == 4) { if(wifi_start_ap(argv[1], RTW_SECURITY_WPA2_AES_PSK, argv[3], strlen((const char *)argv[1]), strlen((const char *)argv[3]), channel ) != RTW_SUCCESS) { printf("\n\rERROR: Operation failed!"); return; } } #ifdef CONFIG_IEEE80211W else if(argc == 5) { rtw_security_t alg = RTW_SECURITY_WPA2_AES_CMAC; u8 mfp = atoi((const char *)argv[4]); if (mfp == 0 || mfp > 2) {// not support alg = RTW_SECURITY_WPA2_AES_PSK; mfp = 0; } wifi_set_mfp_support(mfp); if (wifi_start_ap(argv[1], alg, argv[3], strlen((const char *)argv[1]), strlen((const char *)argv[3]), channel ) != RTW_SUCCESS) { printf("\n\rERROR: Operation failed!"); return; } } #endif else { if(wifi_start_ap(argv[1], RTW_SECURITY_OPEN, NULL, strlen((const char *)argv[1]), 0, channel ) != RTW_SUCCESS) { printf("\n\rERROR: Operation failed!"); return; } } while(1) { char essid[33]; if(wext_get_ssid(WLAN0_NAME, (unsigned char *) essid) > 0) { if(strcmp((const char *) essid, (const char *)argv[1]) == 0) { printf("\n\r%s started\n", argv[1]); break; } } if(timeout == 0) { printf("\n\rERROR: Start AP timeout!"); break; } #if defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO //Delay 1 Tick #else vTaskDelay(1 * configTICK_RATE_HZ); #endif timeout --; } #if CONFIG_LWIP_LAYER #if defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO #else //LwIP_UseStaticIP(pnetif); dhcps_init(pnetif); #endif #endif } static void cmd_wifi_connect(int argc, char **argv) { int ret = RTW_ERROR; unsigned long tick1 = xTaskGetTickCount(); unsigned long tick2, tick3; int mode; char *ssid; rtw_security_t security_type; char *password; int ssid_len; int password_len; int key_id; void *semaphore; if((argc != 2) && (argc != 3) && (argc != 4)) { printf("\n\rUsage: wifi_connect SSID [WPA PASSWORD / (5 or 13) ASCII WEP KEY] [WEP KEY ID 0/1/2/3]"); return; } //Check if in AP mode wext_get_mode(WLAN0_NAME, &mode); if(mode == IW_MODE_MASTER) { #if CONFIG_LWIP_LAYER #if defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO #else dhcps_deinit(); #endif #endif wifi_off(); vTaskDelay(20); if (wifi_on(RTW_MODE_STA) < 0){ printf("\n\rERROR: Wifi on failed!"); return; } } ssid = argv[1]; if(argc == 2){ security_type = RTW_SECURITY_OPEN; password = NULL; ssid_len = strlen((const char *)argv[1]); password_len = 0; key_id = 0; semaphore = NULL; }else if(argc ==3){ security_type = RTW_SECURITY_WPA2_AES_PSK; password = argv[2]; ssid_len = strlen((const char *)argv[1]); password_len = strlen((const char *)argv[2]); key_id = 0; semaphore = NULL; }else{ security_type = RTW_SECURITY_WEP_PSK; password = argv[2]; ssid_len = strlen((const char *)argv[1]); password_len = strlen((const char *)argv[2]); key_id = atoi(argv[3]); if(( password_len != 5) && (password_len != 13)) { printf("\n\rWrong WEP key length. Must be 5 or 13 ASCII characters."); return; } if((key_id < 0) || (key_id > 3)) { printf("\n\rWrong WEP key id. Must be one of 0,1,2, or 3."); return; } semaphore = NULL; } ret = wifi_connect(ssid, security_type, password, ssid_len, password_len, key_id, semaphore); if(ret != RTW_SUCCESS) { printf("\n\rERROR: Operation failed!"); return; } else { tick2 = xTaskGetTickCount(); printf("\r\nConnected after %dms.\n", (tick2-tick1)); #if CONFIG_LWIP_LAYER #if defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO #else /* Start DHCPClient */ LwIP_DHCP(0, DHCP_START); #endif #endif } tick3 = xTaskGetTickCount(); printf("\r\n\nGot IP after %dms.\n", (tick3-tick1)); } static void cmd_wifi_connect_bssid(int argc, char **argv) { int ret = RTW_ERROR; unsigned long tick1 = xTaskGetTickCount(); unsigned long tick2, tick3; int mode; unsigned char bssid[ETH_ALEN]; char *ssid = NULL; rtw_security_t security_type; char *password; int bssid_len; int ssid_len = 0; int password_len; int key_id; void *semaphore; u32 mac[ETH_ALEN]; u32 i; u32 index = 0; if((argc != 3) && (argc != 4) && (argc != 5) && (argc != 6)) { printf("\n\rUsage: wifi_connect_bssid 0/1 [SSID] BSSID / xx:xx:xx:xx:xx:xx [WPA PASSWORD / (5 or 13) ASCII WEP KEY] [WEP KEY ID 0/1/2/3]"); return; } //Check if in AP mode wext_get_mode(WLAN0_NAME, &mode); if(mode == IW_MODE_MASTER) { #if CONFIG_LWIP_LAYER #if defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO #else dhcps_deinit(); #endif #endif wifi_off(); vTaskDelay(20); if (wifi_on(RTW_MODE_STA) < 0){ printf("\n\rERROR: Wifi on failed!"); return; } } //check ssid if(memcmp(argv[1], "0", 1)){ index = 1; ssid_len = strlen((const char *)argv[2]); if((ssid_len <= 0) || (ssid_len > 32)) { printf("\n\rWrong ssid. Length must be less than 32."); return; } ssid = argv[2]; } sscanf(argv[2 + index], MAC_FMT, mac, mac + 1, mac + 2, mac + 3, mac + 4, mac + 5); for(i=0; i<ETH_ALEN; i++) bssid[i] = (u8)mac[i]&0xFF; if(argc == 3 + (int)index){ security_type = RTW_SECURITY_OPEN; password = NULL; bssid_len = ETH_ALEN; password_len = 0; key_id = 0; semaphore = NULL; }else if(argc ==4 + (int)index){ security_type = RTW_SECURITY_WPA2_AES_PSK; password = argv[3 + index]; bssid_len = ETH_ALEN; password_len = strlen((const char *)argv[3 + index]); key_id = 0; semaphore = NULL; }else{ security_type = RTW_SECURITY_WEP_PSK; password = argv[3 + index]; bssid_len = ETH_ALEN; password_len = strlen((const char *)argv[3 + index]); key_id = atoi(argv[4 + index]); if(( password_len != 5) && (password_len != 13)) { printf("\n\rWrong WEP key length. Must be 5 or 13 ASCII characters."); return; } if((key_id < 0) || (key_id > 3)) { printf("\n\rWrong WEP key id. Must be one of 0,1,2, or 3."); return; } semaphore = NULL; } ret = wifi_connect_bssid(bssid, ssid, security_type, password, bssid_len, ssid_len, password_len, key_id, semaphore); if(ret != RTW_SUCCESS) { printf("\n\rERROR: Operation failed!"); return; } else { tick2 = xTaskGetTickCount(); printf("\r\nConnected after %dms.\n", (tick2-tick1)); #if CONFIG_LWIP_LAYER #if defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO #else /* Start DHCPClient */ LwIP_DHCP(0, DHCP_START); #endif #endif } tick3 = xTaskGetTickCount(); printf("\r\n\nGot IP after %dms.\n", (tick3-tick1)); } static void cmd_wifi_disconnect(int argc, char **argv) { /* To avoid gcc warnings */ ( void ) argc; ( void ) argv; int timeout = 20; char essid[33]; printf("\n\rDeassociating AP ..."); if(wext_get_ssid(WLAN0_NAME, (unsigned char *) essid) < 0) { printf("\n\rWIFI disconnected"); return; } if(wifi_disconnect() < 0) { printf("\n\rERROR: Operation failed!"); return; } while(1) { if(wext_get_ssid(WLAN0_NAME, (unsigned char *) essid) < 0) { printf("\n\rWIFI disconnected"); break; } if(timeout == 0) { printf("\n\rERROR: Deassoc timeout!"); break; } #if defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO //Delay 1 Tick #else vTaskDelay(1 * configTICK_RATE_HZ); #endif timeout --; } } static void cmd_wifi_info(int argc, char **argv) { /* To avoid gcc warnings */ ( void ) argc; ( void ) argv; int i = 0; #if CONFIG_LWIP_LAYER #if !defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) u8 *mac = LwIP_GetMAC(&xnetif[0]); u8 *ip = LwIP_GetIP(&xnetif[0]); u8 *gw = LwIP_GetGW(&xnetif[0]); #endif #endif u8 *ifname[2] = {(u8*)WLAN0_NAME,(u8*)WLAN1_NAME}; #ifdef CONFIG_MEM_MONITOR extern int min_free_heap_size; #endif rtw_wifi_setting_t setting; for(i=0;i<NET_IF_NUM;i++){ if(rltk_wlan_running(i)){ #if CONFIG_LWIP_LAYER #if defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO #else mac = LwIP_GetMAC(&xnetif[i]); ip = LwIP_GetIP(&xnetif[i]); gw = LwIP_GetGW(&xnetif[i]); #endif #endif printf("\n\r\nWIFI %s Status: Running", ifname[i]); printf("\n\r=============================="); rltk_wlan_statistic(i); wifi_get_setting((const char*)ifname[i],&setting); wifi_show_setting((const char*)ifname[i],&setting); #if CONFIG_LWIP_LAYER #if defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO #else printf("\n\rInterface (%s)", ifname[i]); printf("\n\r=============================="); printf("\n\r\tMAC => %02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]) ; printf("\n\r\tIP => %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); printf("\n\r\tGW => %d.%d.%d.%d\n\r", gw[0], gw[1], gw[2], gw[3]); #endif #endif if(setting.mode == RTW_MODE_AP || i == 1) { int client_number; struct { int count; rtw_mac_t mac_list[AP_STA_NUM]; } client_info; client_info.count = AP_STA_NUM; wifi_get_associated_client_list(&client_info, sizeof(client_info)); printf("\n\rAssociated Client List:"); printf("\n\r=============================="); if(client_info.count == 0) printf("\n\rClient Num: 0\n\r"); else { printf("\n\rClient Num: %d", client_info.count); for( client_number=0; client_number < client_info.count; client_number++ ) { printf("\n\rClient [%d]:", client_number); printf("\n\r\tMAC => "MAC_FMT"", MAC_ARG(client_info.mac_list[client_number].octet)); } printf("\n\r"); } } { int error = wifi_get_last_error(); printf("\n\rLast Link Error"); printf("\n\r=============================="); switch(error) { case RTW_NO_ERROR: printf("\n\r\tNo Error"); break; case RTW_NONE_NETWORK: printf("\n\r\tTarget AP Not Found"); break; case RTW_CONNECT_FAIL: printf("\n\r\tAssociation Failed"); break; case RTW_WRONG_PASSWORD: printf("\n\r\tWrong Password"); break; case RTW_DHCP_FAIL: printf("\n\r\tDHCP Failed"); break; default: printf("\n\r\tUnknown Error(%d)", error); } printf("\n\r"); } } } #if defined(configUSE_TRACE_FACILITY) && (configUSE_TRACE_FACILITY == 1) { signed char pcWriteBuffer[1024]; vTaskList((char*)pcWriteBuffer); printf("\n\rTask List: \n%s", pcWriteBuffer); } #endif #ifdef CONFIG_MEM_MONITOR printf("\n\rMemory Usage"); printf("\n\r=============================="); printf("\r\nMin Free Heap Size: %d", min_free_heap_size); printf("\r\nCur Free Heap Size: %d\n", xPortGetFreeHeapSize()); #endif } static void cmd_wifi_on(int argc, char **argv) { /* To avoid gcc warnings */ ( void ) argc; ( void ) argv; if(wifi_on(RTW_MODE_STA)<0){ printf("\n\rERROR: Wifi on failed!\n"); } } static void cmd_wifi_off(int argc, char **argv) { /* To avoid gcc warnings */ ( void ) argc; ( void ) argv; #if CONFIG_WEBSERVER stop_web_server(); #endif #if CONFIG_ENABLE_P2P cmd_wifi_p2p_stop(0, NULL); #else wifi_off(); #endif } static void print_scan_result( rtw_scan_result_t* record ) { RTW_API_INFO( "%s\t ", ( record->bss_type == RTW_BSS_TYPE_ADHOC ) ? "Adhoc" : "Infra" ); RTW_API_INFO( MAC_FMT, MAC_ARG(record->BSSID.octet) ); RTW_API_INFO( " %d\t ", record->signal_strength ); RTW_API_INFO( " %d\t ", record->channel ); RTW_API_INFO( " %d\t ", record->wps_type ); RTW_API_INFO( "%s\t\t ", ( record->security == RTW_SECURITY_OPEN ) ? "Open" : ( record->security == RTW_SECURITY_WEP_PSK ) ? "WEP" : ( record->security == RTW_SECURITY_WPA_TKIP_PSK ) ? "WPA TKIP" : ( record->security == RTW_SECURITY_WPA_AES_PSK ) ? "WPA AES" : ( record->security == RTW_SECURITY_WPA_MIXED_PSK ) ? "WPA Mixed" : ( record->security == RTW_SECURITY_WPA2_AES_PSK ) ? "WPA2 AES" : ( record->security == RTW_SECURITY_WPA2_TKIP_PSK ) ? "WPA2 TKIP" : ( record->security == RTW_SECURITY_WPA2_MIXED_PSK ) ? "WPA2 Mixed" : ( record->security == RTW_SECURITY_WPA_WPA2_TKIP_PSK) ? "WPA/WPA2 TKIP" : ( record->security == RTW_SECURITY_WPA_WPA2_AES_PSK) ? "WPA/WPA2 AES" : ( record->security == RTW_SECURITY_WPA_WPA2_MIXED_PSK) ? "WPA/WPA2 Mixed" : #ifdef CONFIG_SAE_SUPPORT ( record->security == RTW_SECURITY_WPA3_AES_PSK) ? "WP3-SAE AES" : #endif "Unknown" ); RTW_API_INFO( " %s ", record->SSID.val ); RTW_API_INFO( "\r\n" ); } static rtw_result_t app_scan_result_handler( rtw_scan_handler_result_t* malloced_scan_result ) { static int ApNum = 0; if (malloced_scan_result->scan_complete != RTW_TRUE) { rtw_scan_result_t* record = &malloced_scan_result->ap_details; record->SSID.val[record->SSID.len] = 0; /* Ensure the SSID is null terminated */ RTW_API_INFO( "%d\t ", ++ApNum ); print_scan_result(record); } else{ ApNum = 0; } return RTW_SUCCESS; } #if SCAN_WITH_SSID static void cmd_wifi_scan_with_ssid(int argc, char **argv) { u8 *channel_list = NULL; u8 *pscan_config = NULL; char *ssid = NULL; int ssid_len = 0; //Fully scan int scan_buf_len = 500; if(argc == 3 && argv[1] && argv[2]){ ssid = argv[1]; ssid_len = strlen((const char *)argv[1]); if((ssid_len <= 0) || (ssid_len > 32)) { printf("\n\rWrong ssid. Length must be less than 32."); goto exit; } scan_buf_len = atoi(argv[2]); if(scan_buf_len < 36){ printf("\n\rBUFFER_LENGTH too short\n\r"); goto exit; } }else if(argc > 3){ int i = 0; int num_channel = atoi(argv[2]); ssid = argv[1]; ssid_len = strlen((const char *)argv[1]); if((ssid_len <= 0) || (ssid_len > 32)) { printf("\n\rWrong ssid. Length must be less than 32."); goto exit; } channel_list = (u8*)pvPortMalloc(num_channel); if(!channel_list){ printf("\n\r ERROR: Can't malloc memory for channel list"); goto exit; } pscan_config = (u8*)pvPortMalloc(num_channel); if(!pscan_config){ printf("\n\r ERROR: Can't malloc memory for pscan_config"); goto exit; } //parse command channel list for(i = 3; i <= argc -1 ; i++){ *(channel_list + i - 3) = (u8)atoi(argv[i]); *(pscan_config + i - 3) = PSCAN_ENABLE; } if(wifi_set_pscan_chan(channel_list, pscan_config, num_channel) < 0){ printf("\n\rERROR: wifi set partial scan channel fail"); goto exit; } }else{ printf("\n\r For Scan all channel Usage: wifi_scan_with_ssid ssid BUFFER_LENGTH"); printf("\n\r For Scan partial channel Usage: wifi_scan_with_ssid ssid num_channels channel_num1 ..."); return; } if(wifi_scan_networks_with_ssid(NULL, NULL, scan_buf_len, ssid, ssid_len) != RTW_SUCCESS){ printf("\n\rERROR: wifi scan failed"); goto exit; } exit: if(argc > 2 && channel_list) vPortFree(channel_list); if(argc > 2 && pscan_config) vPortFree(pscan_config); } #endif static void cmd_wifi_scan(int argc, char **argv) { u8 *channel_list = NULL; u8 *pscan_config = NULL; if(argc > 2){ int i = 0; int num_channel = atoi(argv[1]); channel_list = (u8*)pvPortMalloc(num_channel); if(!channel_list){ printf("\n\r ERROR: Can't malloc memory for channel list"); goto exit; } pscan_config = (u8*)pvPortMalloc(num_channel); if(!pscan_config){ printf("\n\r ERROR: Can't malloc memory for pscan_config"); goto exit; } //parse command channel list for(i = 2; i <= argc -1 ; i++){ *(channel_list + i - 2) = (u8)atoi(argv[i]); *(pscan_config + i - 2) = PSCAN_ENABLE; } if(wifi_set_pscan_chan(channel_list, pscan_config, num_channel) < 0){ printf("\n\rERROR: wifi set partial scan channel fail"); goto exit; } } if(wifi_scan_networks(app_scan_result_handler, NULL ) != RTW_SUCCESS){ printf("\n\rERROR: wifi scan failed"); goto exit; } exit: if(argc > 2 && channel_list) vPortFree(channel_list); if(argc > 2 && pscan_config) vPortFree(pscan_config); } #if CONFIG_WEBSERVER static void cmd_wifi_start_webserver(int argc, char **argv) { start_web_server(); } #endif static void cmd_wifi_iwpriv(int argc, char **argv) { if(argc == 2 && argv[1]) { wext_private_command(WLAN0_NAME, argv[1], 1); } else { printf("\n\rUsage: iwpriv COMMAND PARAMETERS"); } } #endif //#if CONFIG_WLAN static void cmd_ping(int argc, char **argv) { #if !defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) if(argc == 2) { do_ping_call(argv[1], 0, 5); //Not loop, count=5 } else if(argc == 3) { if(strcmp(argv[2], "loop") == 0) do_ping_call(argv[1], 1, 0); //loop, no count else do_ping_call(argv[1], 0, atoi(argv[2])); //Not loop, with count } else { printf("\n\rUsage: ping IP [COUNT/loop]"); } #else printf("\n\r unsupported cmd for customer platform!!!!!!!!"); #endif } #if ( configGENERATE_RUN_TIME_STATS == 1 ) static char cBuffer[ 512 ]; static void cmd_cpustat(int argc, char **argv) { vTaskGetRunTimeStats( ( char * ) cBuffer ); printf( cBuffer ); } #endif #if defined(CONFIG_RTL8195A) || defined(CONFIG_RTL8711B) || defined(CONFIG_RTL8721D) static void cmd_dump_reg(int argc, char **argv) { CmdDumpWord(argc-1, (u8**)(argv+1)); } static void cmd_edit_reg(int argc, char **argv) { CmdWriteWord(argc-1, (u8**)(argv+1)); } #endif static void cmd_exit(int argc, char **argv) { /* To avoid gcc warnings */ ( void ) argc; ( void ) argv; printf("\n\rLeave INTERACTIVE MODE"); vTaskDelete(NULL); } static void cmd_debug(int argc, char **argv) { if(strcmp(argv[1], "ready_trx") == 0) { printf("\r\n%d", wifi_is_ready_to_transceive((rtw_interface_t)rtw_atoi((u8*)argv[2]))); } else if(strcmp(argv[1], "is_up") == 0) { printf("\r\n%d", wifi_is_up((rtw_interface_t)rtw_atoi((u8*)argv[2]))); } else if(strcmp(argv[1], "set_mac") == 0) { printf("\r\n%d", wifi_set_mac_address(argv[2])); } else if(strcmp(argv[1], "get_mac") == 0) { u8 mac[18] = {0}; wifi_get_mac_address((char*)mac); printf("\r\n%s", mac); } else if(strcmp(argv[1], "ps_on") == 0) { printf("\r\n%d", wifi_enable_powersave()); } else if(strcmp(argv[1], "ps_off") == 0) { printf("\r\n%d", wifi_disable_powersave()); #if 0 //TODO } else if(strcmp(argv[1], "get_txpwr") == 0) { int idx; wifi_get_txpower(&idx); printf("\r\n%d", idx); } else if(strcmp(argv[1], "set_txpwr") == 0) { printf("\r\n%d", wifi_set_txpower(rtw_atoi((u8*)argv[2]))); #endif } else if(strcmp(argv[1], "get_clientlist") == 0) { int client_number; struct { int count; rtw_mac_t mac_list[3]; } client_info; client_info.count = 3; printf("\r\n%d\r\n", wifi_get_associated_client_list(&client_info, sizeof(client_info))); if( client_info.count == 0 ) { RTW_API_INFO(("Clients connected 0..\r\n")); } else { RTW_API_INFO("Clients connected %d..\r\n", client_info.count); for( client_number=0; client_number < client_info.count; client_number++ ) { RTW_API_INFO(("------------------------------------\r\n")); RTW_API_INFO("| %d | "MAC_FMT" |\r\n", client_number, MAC_ARG(client_info.mac_list[client_number].octet) ); } RTW_API_INFO(("------------------------------------\r\n")); } } else if(strcmp(argv[1], "get_apinfo") == 0) { rtw_bss_info_t ap_info; rtw_security_t sec; if(wifi_get_ap_info(&ap_info, &sec) == RTW_SUCCESS) { RTW_API_INFO( "\r\nSSID : %s\r\n",(char*)ap_info.SSID ); RTW_API_INFO("BSSID : "MAC_FMT"\r\n", MAC_ARG(ap_info.BSSID.octet)); RTW_API_INFO("RSSI : %d\r\n", ap_info.RSSI); //RTW_API_INFO( ("SNR : %d\r\n", ap_info.SNR) ); RTW_API_INFO("Beacon period : %d\r\n", ap_info.beacon_period); RTW_API_INFO("Security : %s\r\n", ( sec == RTW_SECURITY_OPEN ) ? "Open" : ( sec == RTW_SECURITY_WEP_PSK ) ? "WEP" : ( sec == RTW_SECURITY_WPA_TKIP_PSK ) ? "WPA TKIP" : ( sec == RTW_SECURITY_WPA_AES_PSK ) ? "WPA AES" : ( sec == RTW_SECURITY_WPA_MIXED_PSK ) ? "WPA Mixed" : ( sec == RTW_SECURITY_WPA2_AES_PSK ) ? "WPA2 AES" : ( sec == RTW_SECURITY_WPA2_TKIP_PSK ) ? "WPA2 TKIP" : ( sec == RTW_SECURITY_WPA2_MIXED_PSK ) ? "WPA2 Mixed" : ( sec == RTW_SECURITY_WPA_WPA2_TKIP_PSK) ? "WPA/WPA2 TKIP" : ( sec == RTW_SECURITY_WPA_WPA2_AES_PSK) ? "WPA/WPA2 AES" : ( sec == RTW_SECURITY_WPA_WPA2_MIXED_PSK) ? "WPA/WPA2 Mixed" : "Unknown" ); } } else if(strcmp(argv[1], "reg_mc") == 0) { rtw_mac_t mac; sscanf(argv[2], MAC_FMT, (int*)(mac.octet+0), (int*)(mac.octet+1), (int*)(mac.octet+2), (int*)(mac.octet+3), (int*)(mac.octet+4), (int*)(mac.octet+5)); printf("\r\n%d", wifi_register_multicast_address(&mac)); } else if(strcmp(argv[1], "unreg_mc") == 0) { rtw_mac_t mac; sscanf(argv[2], MAC_FMT, (int*)(mac.octet+0), (int*)(mac.octet+1), (int*)(mac.octet+2), (int*)(mac.octet+3), (int*)(mac.octet+4), (int*)(mac.octet+5)); printf("\r\n%d", wifi_unregister_multicast_address(&mac)); } else if(strcmp(argv[1], "get_rssi") == 0) { int rssi = 0; wifi_get_rssi(&rssi); printf("\n\rwifi_get_rssi: rssi = %d", rssi); }else if(strcmp(argv[1], "dbg") == 0) { char buf[32] = {0}; char * copy = buf; int i = 0; int len = 0; for(i=1;i<argc;i++){ strcpy(&buf[len], argv[i]); len = strlen(copy); buf[len++] = ' '; buf[len] = '\0'; } wext_private_command(WLAN0_NAME, copy, 1); #ifdef CONFIG_IEEE80211W } else if(strcmp(argv[1], "11w_sa") == 0) { rltk_wlan_tx_sa_query(atoi((const char *)argv[2])); } else if(strcmp(argv[1], "11w_deauth") == 0) { rltk_wlan_tx_deauth(atoi((const char *)argv[2]), atoi((const char *)argv[3])); } else if(strcmp(argv[1], "11w_auth") == 0) { rltk_wlan_tx_auth(); #endif } else { printf("\r\nUnknown CMD\r\n"); } } typedef struct _cmd_entry { char *command; void (*function)(int, char **); } cmd_entry; static const cmd_entry cmd_table[] = { #if CONFIG_WLAN {"wifi_connect", cmd_wifi_connect}, {"wifi_connect_bssid", cmd_wifi_connect_bssid}, {"wifi_disconnect", cmd_wifi_disconnect}, {"wifi_info", cmd_wifi_info}, {"wifi_on", cmd_wifi_on}, {"wifi_off", cmd_wifi_off}, {"wifi_ap", cmd_wifi_ap}, {"wifi_scan", cmd_wifi_scan}, #if SCAN_WITH_SSID {"wifi_scan_with_ssid", cmd_wifi_scan_with_ssid}, #endif {"iwpriv", cmd_wifi_iwpriv}, {"wifi_promisc", cmd_promisc}, #if CONFIG_OTA_UPDATE {"wifi_update", cmd_update}, #endif #if CONFIG_WEBSERVER {"wifi_start_webserver", cmd_wifi_start_webserver}, #endif #if (CONFIG_INCLUDE_SIMPLE_CONFIG) {"wifi_simple_config", cmd_simple_config}, #endif #ifdef CONFIG_WPS #if CONFIG_ENABLE_WPS {"wifi_wps", cmd_wps}, #endif #if defined(CONFIG_ENABLE_WPS_AP) && CONFIG_ENABLE_WPS_AP {"wifi_ap_wps", cmd_ap_wps}, #endif #if CONFIG_ENABLE_P2P {"wifi_p2p_start", cmd_wifi_p2p_start}, {"wifi_p2p_stop", cmd_wifi_p2p_stop}, {"p2p_find", cmd_p2p_find}, {"p2p_info", cmd_p2p_info}, {"p2p_disconnect", cmd_p2p_disconnect}, {"p2p_connect", cmd_p2p_connect}, #endif #endif #ifdef CONFIG_CONCURRENT_MODE {"wifi_sta_ap",cmd_wifi_sta_and_ap}, #endif #if CONFIG_SSL_CLIENT {"ssl_client", cmd_ssl_client}, #endif #if CONFIG_GOOGLENEST {"gn", cmd_googlenest}, #endif #endif #if CONFIG_LWIP_LAYER // {"app", cmd_app}, {"wifi_debug", cmd_debug}, #if CONFIG_BSD_TCP {"tcp", cmd_tcp}, {"udp", cmd_udp}, #endif #if CONFIG_JD_SMART {"jd_smart", cmd_jd_smart}, #endif {"ping", cmd_ping}, #endif #if ( configGENERATE_RUN_TIME_STATS == 1 ) {"cpu", cmd_cpustat}, #endif #if defined(CONFIG_RTL8195A) || defined(CONFIG_RTL8711B) || defined(CONFIG_RTL8721D) {"dw", cmd_dump_reg}, {"ew", cmd_edit_reg}, #endif {"exit", cmd_exit}, {"help", cmd_help} }; #if CONFIG_INTERACTIVE_EXT /* must include here, ext_cmd_table in wifi_interactive_ext.h uses struct cmd_entry */ #include <wifi_interactive_ext.h> #endif static void cmd_help(int argc, char **argv) { /* To avoid gcc warnings */ ( void ) argc; ( void ) argv; u32 i; printf("\n\rCOMMAND LIST:"); printf("\n\r=============================="); for(i = 0; i < sizeof(cmd_table) / sizeof(cmd_table[0]); i ++) printf("\n\r %s", cmd_table[i].command); #if CONFIG_INTERACTIVE_EXT for(i = 0; i < sizeof(ext_cmd_table) / sizeof(ext_cmd_table[0]); i ++) printf("\n\r %s", ext_cmd_table[i].command); #endif } #define MAX_ARGC 6 static int parse_cmd(char *buf, char **argv) { int argc = 0; memset(argv, 0, sizeof(argv)*MAX_ARGC); while((argc < MAX_ARGC) && (*buf != '\0')) { argv[argc] = buf; argc ++; buf ++; while((*buf != ' ') && (*buf != '\0')) buf ++; while(*buf == ' ') { *buf = '\0'; buf ++; } // Don't replace space if(argc == 1){ if(strcmp(argv[0], "iwpriv") == 0){ if(*buf != '\0'){ argv[1] = buf; argc ++; } break; } } } return argc; } char uart_buf[64]; void interactive_mode(void *param) { /* To avoid gcc warnings */ ( void ) param; int argc; unsigned int i; char *argv[MAX_ARGC]; #if defined(CONFIG_PLATFOMR_CUSTOMER_RTOS) //TODO //Get content from uart #else extern xSemaphoreHandle uart_rx_interrupt_sema; printf("\n\rEnter INTERACTIVE MODE\n\r"); printf("\n\r# "); while(1){ while(xSemaphoreTake(uart_rx_interrupt_sema, portMAX_DELAY) != pdTRUE); if((argc = parse_cmd(uart_buf, argv)) > 0) { int found = 0; for(i = 0; i < sizeof(cmd_table) / sizeof(cmd_table[0]); i ++) { if(strcmp((const char *)argv[0], (const char *)(cmd_table[i].command)) == 0) { cmd_table[i].function(argc, argv); found = 1; break; } } #if CONFIG_INTERACTIVE_EXT if(!found) { for(i = 0; i < sizeof(ext_cmd_table) / sizeof(ext_cmd_table[0]); i ++) { if(strcmp(argv[0], ext_cmd_table[i].command) == 0) { ext_cmd_table[i].function(argc, argv); found = 1; break; } } } #endif if(!found) printf("\n\runknown command '%s'", argv[0]); printf("\n\r[MEM] After do cmd, available heap %d\n\r", xPortGetFreeHeapSize()); } printf("\r\n\n# "); uart_buf[0] = '\0'; } #endif } void start_interactive_mode(void) { #ifdef SERIAL_DEBUG_RX if(xTaskCreate(interactive_mode, (char const *)"interactive_mode", STACKSIZE, NULL, tskIDLE_PRIORITY + 4, NULL) != pdPASS) printf("\n\r%s xTaskCreate failed", __FUNCTION__); #else printf("\n\rERROR: No SERIAL_DEBUG_RX to support interactive mode!"); #endif } #if defined(CONFIG_PLATFORM_8195A) || defined(CONFIG_PLATFORM_8711B) || defined(CONFIG_PLATFORM_8721D) VOID WlanNormal( IN u16 argc, IN u8 *argv[]) { u8 i, j= 0; u8* pbuf = (u8*)uart_buf; extern xSemaphoreHandle uart_rx_interrupt_sema; memset(uart_buf, 0, sizeof(uart_buf)); printf("argc=%d\n", argc); for(i = 0 ; i < argc ; i++) { printf("command element [%d] = %s\n", i, argv[i]); for(j = 0; j<strlen((char const*)argv[i]) ;j++) { *pbuf = argv[i][j]; pbuf++; } if(i < (argc-1)) { *pbuf = ' '; pbuf++; } } printf("command %s\n", uart_buf); xSemaphoreGive( uart_rx_interrupt_sema); } #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/api/wifi_interactive_mode.c
C
apache-2.0
35,628
#include <platform_stdlib.h> #include <math.h> #include "rl6548.h" #include "audio_internel.h" #include "osdep_service.h" //#define ENABLE_PA static u8 sp_rx_buf[SP_DMA_PAGE_SIZE * SP_DMA_PAGE_NUM]__attribute__((aligned(32))); static u8 sp_tx_buf[SP_DMA_PAGE_SIZE * SP_DMA_PAGE_NUM]__attribute__((aligned(32))); static u8 sp_zero_buf[SP_ZERO_BUF_SIZE]__attribute__((aligned(32))); static u8 sp_full_buf[SP_FULL_BUF_SIZE]__attribute__((aligned(32))); static u8 rx_data_cache[SP_DMA_PAGE_SIZE]; static uint32_t rx_data_cache_len = 0; static SP_InitTypeDef SP_InitStruct; static SP_GDMA_STRUCT SPGdmaStruct; static SP_OBJ sp_obj; static SP_RX_INFO sp_rx_info; static SP_TX_INFO sp_tx_info; static int RX_GDMA_flag = 0; //0, start, 1, stop, 2, close static int TX_GDMA_flag = 0; static SP_OBJ sp_obj; static SP_InitTypeDef SP_InitStruct; extern void PLL_Div(u32 div); extern BOOL AUDIO_SP_TXGDMA_Restart(u8 GDMA_Index, u8 GDMA_ChNum, u32 tx_addr, u32 tx_length); extern BOOL AUDIO_SP_RXGDMA_Restart(u8 GDMA_Index, u8 GDMA_ChNum, u32 rx_addr, u32 rx_length); static u8 *sp_get_free_tx_page(void) { pTX_BLOCK ptx_block = &(sp_tx_info.tx_block[sp_tx_info.tx_usr_cnt]); if (ptx_block->tx_gdma_own) return NULL; else{ return (u8*)ptx_block->tx_addr; } } static void sp_write_tx_page(u8 *src, u32 length) { pTX_BLOCK ptx_block = &(sp_tx_info.tx_block[sp_tx_info.tx_usr_cnt]); memcpy((void*)ptx_block->tx_addr, src, length); ptx_block-> tx_gdma_own = 1; ptx_block -> tx_length = length; sp_tx_info.tx_usr_cnt++; if (sp_tx_info.tx_usr_cnt == SP_DMA_PAGE_NUM){ sp_tx_info.tx_usr_cnt = 0; } } static void sp_release_tx_page(void) { pTX_BLOCK ptx_block = &(sp_tx_info.tx_block[sp_tx_info.tx_gdma_cnt]); if (sp_tx_info.tx_empty_flag){ } else{ ptx_block->tx_gdma_own = 0; sp_tx_info.tx_gdma_cnt++; if (sp_tx_info.tx_gdma_cnt == SP_DMA_PAGE_NUM){ sp_tx_info.tx_gdma_cnt = 0; } } } static u8 *sp_get_ready_tx_page(void) { pTX_BLOCK ptx_block = &(sp_tx_info.tx_block[sp_tx_info.tx_gdma_cnt]); if (ptx_block->tx_gdma_own){ sp_tx_info.tx_empty_flag = 0; return (u8*)ptx_block->tx_addr; } else{ sp_tx_info.tx_empty_flag = 1; return (u8*)sp_tx_info.tx_zero_block.tx_addr; //for audio buffer empty case } } static u32 sp_get_ready_tx_length(void) { pTX_BLOCK ptx_block = &(sp_tx_info.tx_block[sp_tx_info.tx_gdma_cnt]); if (sp_tx_info.tx_empty_flag){ return sp_tx_info.tx_zero_block.tx_length; } else{ return ptx_block->tx_length; } } static void sp_tx_complete(void *Data) { SP_GDMA_STRUCT *gs = (SP_GDMA_STRUCT *) Data; PGDMA_InitTypeDef GDMA_InitStruct; u32 tx_addr; u32 tx_length; GDMA_InitStruct = &(gs->SpTxGdmaInitStruct); /* Clear Pending ISR */ GDMA_ClearINT(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); sp_release_tx_page(); tx_addr = (u32)sp_get_ready_tx_page(); tx_length = sp_get_ready_tx_length(); if(TX_GDMA_flag == 0) { AUDIO_SP_TXGDMA_Restart(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum, tx_addr, tx_length); } else { GDMA_ChnlFree(SPGdmaStruct.SpTxGdmaInitStruct.GDMA_Index, SPGdmaStruct.SpTxGdmaInitStruct.GDMA_ChNum); AUDIO_SP_TdmaCmd(AUDIO_SPORT_DEV, DISABLE); // AUDIO_SP_TxStart(AUDIO_SPORT_DEV, DISABLE); if(TX_GDMA_flag == 2){ RCC_PeriphClockCmd(APBPeriph_AUDIOC, APBPeriph_AUDIOC_CLOCK, DISABLE); RCC_PeriphClockCmd(APBPeriph_SPORT, APBPeriph_SPORT_CLOCK, DISABLE); CODEC_DeInit(APP_LINE_OUT); PLL_PCM_Set(DISABLE); } } } static u8 *sp_get_ready_rx_page(void) { pRX_BLOCK prx_block = &(sp_rx_info.rx_block[sp_rx_info.rx_usr_cnt]); if (prx_block->rx_gdma_own) return NULL; else{ return (u8 *)prx_block->rx_addr; } } static void sp_read_rx_page(u8 *dst, u32 length) { pRX_BLOCK prx_block = &(sp_rx_info.rx_block[sp_rx_info.rx_usr_cnt]); memcpy(dst, (u8 *)prx_block->rx_addr, length); prx_block->rx_gdma_own = 1; sp_rx_info.rx_usr_cnt++; if (sp_rx_info.rx_usr_cnt == SP_DMA_PAGE_NUM){ sp_rx_info.rx_usr_cnt = 0; } } static void sp_release_rx_page(void) { pRX_BLOCK prx_block = &(sp_rx_info.rx_block[sp_rx_info.rx_gdma_cnt]); if (sp_rx_info.rx_full_flag){ } else{ prx_block->rx_gdma_own = 0; sp_rx_info.rx_gdma_cnt++; if (sp_rx_info.rx_gdma_cnt == SP_DMA_PAGE_NUM){ sp_rx_info.rx_gdma_cnt = 0; } } } static u8 *sp_get_free_rx_page(void) { pRX_BLOCK prx_block = &(sp_rx_info.rx_block[sp_rx_info.rx_gdma_cnt]); if (prx_block->rx_gdma_own){ sp_rx_info.rx_full_flag = 0; return (u8 *)prx_block->rx_addr; } else{ sp_rx_info.rx_full_flag = 1; return (u8 *)sp_rx_info.rx_full_block.rx_addr; //for audio buffer full case } } static u32 sp_get_free_rx_length(void) { pRX_BLOCK prx_block = &(sp_rx_info.rx_block[sp_rx_info.rx_gdma_cnt]); if (sp_rx_info.rx_full_flag){ return sp_rx_info.rx_full_block.rx_length; } else{ return prx_block->rx_length; } } static void sp_init_tx_variables(void) { int i; for(i=0; i<SP_ZERO_BUF_SIZE; i++){ sp_zero_buf[i] = 0; } sp_tx_info.tx_zero_block.tx_addr = (u32)sp_zero_buf; sp_tx_info.tx_zero_block.tx_length = (u32)SP_ZERO_BUF_SIZE; sp_tx_info.tx_gdma_cnt = 0; sp_tx_info.tx_usr_cnt = 0; sp_tx_info.tx_empty_flag = 0; for(i=0; i<SP_DMA_PAGE_NUM; i++){ sp_tx_info.tx_block[i].tx_gdma_own = 0; sp_tx_info.tx_block[i].tx_addr = (u32)sp_tx_buf+i*SP_DMA_PAGE_SIZE; sp_tx_info.tx_block[i].tx_length = SP_DMA_PAGE_SIZE; } } static void sp_init_rx_variables(void) { int i; sp_rx_info.rx_full_block.rx_addr = (u32)sp_full_buf; sp_rx_info.rx_full_block.rx_length = (u32)SP_FULL_BUF_SIZE; sp_rx_info.rx_gdma_cnt = 0; sp_rx_info.rx_usr_cnt = 0; sp_rx_info.rx_full_flag = 0; for(i=0; i<SP_DMA_PAGE_NUM; i++){ sp_rx_info.rx_block[i].rx_gdma_own = 1; sp_rx_info.rx_block[i].rx_addr = (u32)(sp_rx_buf + i*SP_DMA_PAGE_SIZE); sp_rx_info.rx_block[i].rx_length = SP_DMA_PAGE_SIZE; } } static void sp_rx_complete(void *data) { SP_GDMA_STRUCT *gs = (SP_GDMA_STRUCT *) data; PGDMA_InitTypeDef GDMA_InitStruct; u32 rx_addr; u32 rx_length; char *pbuf; GDMA_InitStruct = &(gs->SpRxGdmaInitStruct); DCache_Invalidate(GDMA_InitStruct->GDMA_DstAddr, GDMA_InitStruct->GDMA_BlockSize<<2); /* Clear Pending ISR */ GDMA_ClearINT(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); sp_release_rx_page(); rx_addr = (u32)sp_get_free_rx_page(); rx_length = sp_get_free_rx_length(); if(RX_GDMA_flag == 0) { AUDIO_SP_RXGDMA_Restart(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum, rx_addr, rx_length); } else { GDMA_ChnlFree(SPGdmaStruct.SpRxGdmaInitStruct.GDMA_Index, SPGdmaStruct.SpRxGdmaInitStruct.GDMA_ChNum); AUDIO_SP_RdmaCmd(AUDIO_SPORT_DEV, DISABLE); // AUDIO_SP_RxStart(AUDIO_SPORT_DEV, DISABLE); if(RX_GDMA_flag == 2) { RCC_PeriphClockCmd(APBPeriph_AUDIOC, APBPeriph_AUDIOC_CLOCK, DISABLE); RCC_PeriphClockCmd(APBPeriph_SPORT, APBPeriph_SPORT_CLOCK, DISABLE); CODEC_DeInit(APP_AMIC_IN); PLL_PCM_Set(DISABLE); } } } static void sp_init_hal(pSP_OBJ psp_obj) { u32 div; PLL_I2S_Set(ENABLE); //enable 98.304MHz PLL. needed if fs=8k/16k/32k/48k/96k //PLL_PCM_Set(ENABLE); //enable 45.1584MHz PLL. needed if fs=44.1k/8.2k RCC_PeriphClockCmd(APBPeriph_AUDIOC, APBPeriph_AUDIOC_CLOCK, ENABLE); RCC_PeriphClockCmd(APBPeriph_SPORT, APBPeriph_SPORT_CLOCK, ENABLE); //set clock divider to gen clock sample_rate*256 from 98.304M. switch(psp_obj->sample_rate){ case SR_48K: div = 8; break; case SR_96K: div = 4; break; case SR_32K: div = 12; break; case SR_16K: div = 24; break; case SR_8K: div = 48; break; default: DBG_8195A("sample rate not supported!!\n"); break; } PLL_Div(div); PAD_CMD(_PA_0, DISABLE); PAD_CMD(_PA_1, DISABLE); PAD_CMD(_PA_2, DISABLE); PAD_CMD(_PA_3, DISABLE); PAD_CMD(_PA_4, DISABLE); PAD_CMD(_PB_28, DISABLE); PAD_CMD(_PB_29, DISABLE); PAD_CMD(_PB_30, DISABLE); PAD_CMD(_PB_31, DISABLE); /*codec init*/ CODEC_Init(psp_obj->sample_rate, psp_obj->word_len, psp_obj->mono_stereo, psp_obj->direction); #ifdef ENABLE_PA CODEC_SetAmicBst(0x3, 0x1); //right loopback CODEC_SetVolume(0x82, 0x82); u32 reg_value = 0; reg_value = AUDIO_SI_ReadReg(0x2); //reg_value &= ~(15<<BIT_MICBST_GSELL); reg_value |= (1<<14); AUDIO_SI_WriteReg(0x2, reg_value); #else CODEC_SetAmicBst(0x3, 0x3); CODEC_SetVolume(0x92, 0x92); #endif } // static void rl6548_capture_start() { u32 rx_addr; u32 rx_length; RX_GDMA_flag = 0; memset(rx_data_cache, 0x00, SP_DMA_PAGE_SIZE); rx_data_cache_len = 0; sp_init_rx_variables(); // AUDIO_SP_Init(AUDIO_SPORT_DEV, &SP_InitStruct); AUDIO_SP_RdmaCmd(AUDIO_SPORT_DEV, ENABLE); AUDIO_SP_RxStart(AUDIO_SPORT_DEV, ENABLE); rx_addr = (u32)sp_get_free_rx_page(); rx_length = sp_get_free_rx_length(); AUDIO_SP_RXGDMA_Init(0, &SPGdmaStruct.SpRxGdmaInitStruct, &SPGdmaStruct, (IRQ_FUN)sp_rx_complete, (u8 *)rx_addr, rx_length); } // static void rl6548_capture_stop() { RX_GDMA_flag = 1; } // static void rl6548_playback_start() { u32 tx_addr; u32 tx_length; TX_GDMA_flag = 0; sp_init_tx_variables(); // AUDIO_SP_Init(AUDIO_SPORT_DEV, &SP_InitStruct); AUDIO_SP_TdmaCmd(AUDIO_SPORT_DEV, ENABLE); AUDIO_SP_TxStart(AUDIO_SPORT_DEV, ENABLE); tx_addr = (u32)sp_get_ready_tx_page(); tx_length = sp_get_ready_tx_length(); AUDIO_SP_TXGDMA_Init(0, &SPGdmaStruct.SpTxGdmaInitStruct, &SPGdmaStruct, (IRQ_FUN)sp_tx_complete, (u8 *)tx_addr, tx_length); } // static void rl6548_playback_stop() { TX_GDMA_flag = 1; } void *rl6548_audio_init(int sampleRate, int channels, int wordLen) { // printf("enter rl6548_audio_init\n"); pSP_OBJ psp_obj = &sp_obj; if(channels == 1) psp_obj->mono_stereo= CH_MONO; else if(channels == 2) psp_obj->mono_stereo= CH_STEREO; psp_obj->word_len = wordLen; switch(sampleRate) { case 48000: psp_obj->sample_rate = SR_48K; break; case 96000: psp_obj->sample_rate = SR_96K; break; case 32000: psp_obj->sample_rate = SR_32K; break; case 16000: psp_obj->sample_rate = SR_16K; break; case 8000: psp_obj->sample_rate = SR_8K; break; case 44100: psp_obj->sample_rate = SR_44P1K; break; case 88200: psp_obj->sample_rate = SR_88P2K; break; default: printf("not support sr %d\n", sampleRate); } psp_obj->direction = APP_AMIC_IN | APP_LINE_OUT; //default sp_init_hal(psp_obj); sp_init_rx_variables(); sp_init_tx_variables(); /*configure Sport according to the parameters*/ AUDIO_SP_StructInit(&SP_InitStruct); SP_InitStruct.SP_MonoStereo= psp_obj->mono_stereo; SP_InitStruct.SP_WordLen = psp_obj->word_len; AUDIO_SP_Init(AUDIO_SPORT_DEV, &SP_InitStruct); return psp_obj; } void rl6548_audio_deinit() { // printf("enter rl6548_audio_deinit\n"); RCC_PeriphClockCmd(APBPeriph_AUDIOC, APBPeriph_AUDIOC_CLOCK, DISABLE); RCC_PeriphClockCmd(APBPeriph_SPORT, APBPeriph_SPORT_CLOCK, DISABLE); CODEC_DeInit(APP_AMIC_IN | APP_LINE_OUT); PLL_PCM_Set(DISABLE); } int rl6548_audio_write(void *h, uint8_t *buf, uint32_t size) { uint32_t offset = 0; uint32_t tx_len; while(size) { if (sp_get_free_tx_page()){ tx_len = (size >= SP_DMA_PAGE_SIZE) ? SP_DMA_PAGE_SIZE : size; sp_write_tx_page((buf+offset), tx_len); offset += tx_len; size -= tx_len; } else { // rtw_msleep_os(1); aos_msleep(1); } } } int rl6548_data_read(void *handle, void *buf, unsigned int size) { int sz = size; char *dst = (char*)buf; if(sz >= rx_data_cache_len && rx_data_cache_len > 0) { memcpy(dst, rx_data_cache, rx_data_cache_len); sz -= rx_data_cache_len; dst += rx_data_cache_len; rx_data_cache_len = 0; } else if(sz < rx_data_cache_len) { memcpy(dst, rx_data_cache, sz); rx_data_cache_len -= sz; memmove(rx_data_cache, rx_data_cache + sz, rx_data_cache_len); sz = 0; } while(sz > 0) { if (sp_get_ready_rx_page()) { sp_read_rx_page((u8 *)rx_data_cache, SP_DMA_PAGE_SIZE); rx_data_cache_len = SP_DMA_PAGE_SIZE; if(sz >= rx_data_cache_len) { memcpy(dst, rx_data_cache, rx_data_cache_len); sz -= rx_data_cache_len; dst += rx_data_cache_len; rx_data_cache_len = 0; } else { memcpy(dst, rx_data_cache, sz); rx_data_cache_len -= sz; memmove(rx_data_cache, rx_data_cache + sz, rx_data_cache_len); sz = 0; } } else { // rtw_msleep_os(1); aos_msleep(1); } } return size - sz; } void rl6548_volume_set(int index) { int vol = (int)(VOLUME_MAX / 100.0 * index) ; SET_VOLUME(vol, vol); // printf("Volume Set, index %d, value %d\r\n", index, vol); } int rl6548_volume_get() { int vol = 0; int volume_index = 0; u16 volume_16 = 0; GET_VOLUME(&volume_16); // printf("Volume Register Data %x", volume_16); vol = volume_16 & 0x00FF; volume_index = round(vol * 100.0 / VOLUME_MAX); return volume_index; } void rl6548_set_mute(int mute) { if(mute) rl6548_volume_set(0); } int rl6548_get_mute() { return rl6548_volume_get() == 0; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/audio/core/audio_internel.c
C
apache-2.0
14,444
#ifndef _AUDIO_RL6548_H #define _AUDIO_RL6548_H #include "ameba_soc.h" #include "rl6548.h" #define SP_DMA_PAGE_SIZE 1600 #define SP_DMA_PAGE_NUM 4 #define SP_FULL_BUF_SIZE 128 #define SP_ZERO_BUF_SIZE 128 #define SET_VOLUME CODEC_SetVolume #define GET_VOLUME CODEC_GetVolume #define VOLUME_MAX (0xAF) #define VOLUME_MIX (0x00) //#define ENABLE_PA typedef struct { GDMA_InitTypeDef SpTxGdmaInitStruct; //Pointer to GDA_InitTypeDef GDMA_InitTypeDef SpRxGdmaInitStruct; //Pointer to GDA_InitTypeDef }SP_GDMA_STRUCT, *pSP_GDMA_STRUCT; typedef struct { u8 rx_gdma_own; u32 rx_addr; u32 rx_length; }RX_BLOCK, *pRX_BLOCK; typedef struct { RX_BLOCK rx_block[SP_DMA_PAGE_NUM]; RX_BLOCK rx_full_block; u8 rx_gdma_cnt; u8 rx_usr_cnt; u8 rx_full_flag; }SP_RX_INFO, *pSP_RX_INFO; typedef struct { u8 tx_gdma_own; u32 tx_addr; u32 tx_length; }TX_BLOCK, *pTX_BLOCK; typedef struct { TX_BLOCK tx_block[SP_DMA_PAGE_NUM]; TX_BLOCK tx_zero_block; u8 tx_gdma_cnt; u8 tx_usr_cnt; u8 tx_empty_flag; }SP_TX_INFO, *pSP_TX_INFO; typedef struct { u32 sample_rate; u32 word_len; u32 mono_stereo; u32 direction; }SP_OBJ, *pSP_OBJ; void *rl6548_audio_init(int sampleRate, int channels, int wordLen); void rl6548_audio_deinit(); void rl6548_capture_start(); void rl6548_playback_start(); void rl6548_capture_stop(); void rl6548_playback_stop(); int rl6548_audio_write(void *h, uint8_t *buf, uint32_t size); int rl6548_data_read(void *handle, void *buf, unsigned int size); int rl6548_volume_get(); void rl6548_volume_set(int index); int rl6548_get_mute(); void rl6548_set_mute(int mute); #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/audio/core/audio_internel.h
C
apache-2.0
1,718
/** * Copyright (c) 2015, Realsil Semiconductor Corporation. All rights reserved. * */ #ifndef _BOARD_H_ #define _BOARD_H_ #ifdef __cplusplus extern "C" { #endif #include <stdio.h> #include "ameba_soc.h" #define platform_debug DBG_8195A #define TRACE_SWITCH_CLOSE //trace_uart //======================================== /* CONFIG */ //#define TRACE_UART_DEFAULT #define TRACE_UART_TX_IRQ //#define TRACE_UART_TX_WHILE //#define TRACE_UART_DMA /* TRACE UART DEFAULT USE PA18 PA19 UART0 (BEBCAUSE OF THE BT LOG IS PA16)*/ #define TRACE_UART_BAUDRATE 1500000 #ifdef TRACE_UART_DEFAULT #define TRACE_UART_DEV UART0_DEV #define TRACE_UART_IRQ UART0_IRQ #define TRACE_UART_TX _PA_18 //#define TRACE_UART_RX _PA_19 #ifdef TRACE_UART_DMA #define TRACE_UART_INDEX 0 #define TRACEUART_DMA_PRIO 12 #endif #else #define TRACE_UART_DEV UART3_DEV #define TRACE_UART_IRQ UARTLP_IRQ #define TRACE_UART_TX _PA_26 //#define TRACE_UART_RX _PA_25 //km0 not support dma #endif #ifdef TRACE_UART_TX_IRQ #define TRACE_COUNT 16 //ONE IRQ send DATA LEN #define TRACEUART_IRQ_PRIO 12 #endif //==hci_uart============================ //====trace_task======== #define TRACE_TASK_PRIO 3 //hci_rtk============ #define hci_board_debug printf #define BT_DEFAUT_LMP_SUBVER 0x8721 #define HCI_START_IQK #define HCI_WRITE_IQK #ifdef CONFIG_MP_INCLUDED #define BT_MP_MODE #define HCI_MP_BRIDGE 1 #endif //=board.h==== #define MERGE_PATCH_ADDRESS_OTA1 0x080F8000 #define MERGE_PATCH_ADDRESS_OTA2 0x081F8000 #define MERGE_PATCH_SWITCH_ADDR 0x08003028 #define MERGE_PATCH_SWITCH_SINGLE 0xAAAAAAAA #define CALI_IQK_RF_STEP0 0x4000 #define CALI_IQK_RF_STEP1 0x0180 #define CALI_IQK_RF_STEP2 0x3800 #define CALI_IQK_RF_STEP3F 0x0400 #define LEFUSE(x) (x-0x190) #define EFUSE_SW_USE_FLASH_PATCH BIT0 #define EFUSE_SW_BT_FW_LOG BIT1 #define EFUSE_SW_RSVD BIT2 #define EFUSE_SW_HCI_OUT BIT3 #define EFUSE_SW_UPPERSTACK_SWITCH BIT4 #define EFUSE_SW_TRACE_SWITCH BIT5 #define EFUSE_SW_DRIVER_DEBUG_LOG BIT6 #define EFUSE_SW_RSVD2 BIT7 //#define CHECK_SW(x) (HAL_READ32(SPI_FLASH_BASE, FLASH_SYSTEM_DATA_ADDR + 0x28) & x) #define CHECK_SW(x) (1) extern uint8_t rltk_wlan_is_mp(void); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/bluetooth/realtek/sdk/board/amebad/src/bt_board.h
C
apache-2.0
2,513