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-2020 Alibaba Group Holding Limited */ #include <stdlib.h> #include "aos/hal/flash.h" #include "cmsis_os.h" #include "cmsis.h" #include "hal_trace.h" #include "hal_norflash.h" #define BES_HAL_DEBUG 0 #include "app_hal.h" #include "ota_port.h" #define FLASH_PAGE_SIZE_IN_BYTES 256 extern const size_t hal_partitions_amount; extern const hal_logic_partition_t hal_partitions[]; enum ota_link ota_current_link = OTA_LINK_ERR; osMutexId FlashMutex = NULL; osMutexDef_t os_mutex_def_flash; static void FlashosMutexWait(void) { if(FlashMutex == NULL) { FlashMutex = osMutexCreate(&os_mutex_def_flash); } osMutexWait(FlashMutex, osWaitForever); } void * my_memcpy(void *dst, void *src, size_t num) { int offset1 = (4 - ((uint32)dst & 3)) & 3; int offset2 = (4 - ((uint32)src & 3)) & 3; if(offset1 != offset2) { return memcpy(dst, src, num); } int wordnum = num > offset1 ? (num - offset1) /8 : 0; int slice = num > offset1 ? (num-offset1) % 8 : 0; char *pdst = (char *)dst; char *psrc = (char *)src; long long * pintsrc; long long * pintdst; while(offset1--) { *pdst++ = *psrc++; } pintdst = (long long*)pdst; pintsrc = (long long*)psrc; while(wordnum--) { *pintdst++ = *pintsrc++; } pdst = (char*)pintdst; psrc = (char*)pintsrc; while(slice--) { *pdst++ = *psrc++; } return dst; } int bes_hal_flash_read(const hal_partition_t partition, const uint32_t addr, uint8_t *dst, const uint32_t size) { int ret = 0; uint32_t lock = 0; volatile char *flashPointer = NULL; if (NULL == dst) { ret = -1; goto RETURN; } watchdog_feeddog(); FlashosMutexWait(); if (ota_current_link == OTA_LINK_B) { if (partition == HAL_PARTITION_APPLICATION) { hal_norflash_disable_remap(HAL_NORFLASH_ID_0); } } flashPointer = (volatile char *)(FLASH_NC_BASE + addr); //memcpy(dst, (void *)flashPointer, size); my_memcpy(dst, (void *)flashPointer, size); if (ota_current_link == OTA_LINK_B) { if (partition == HAL_PARTITION_APPLICATION) { hal_norflash_re_enable_remap(HAL_NORFLASH_ID_0); } } osMutexRelease(FlashMutex); RETURN: return ret; } #if 0 int bes_hal_flash_write(const uint32_t addr, const uint8_t *src, const uint32_t size) { int ret = 0; uint32_t lock; uint32_t num = 0; uint32_t left_len = 0; uint32_t align_len = 0; uint32_t fill_len = 0; uint32_t flash_offset = addr; uint32_t lengthToBurn = size; uint8_t *ptrSource = NULL; volatile char *flashPointer = NULL; uint8_t *buf = NULL; ptrSource = (uint8_t *)src; if (NULL == ptrSource) { ret = -2; goto RETURN; } FlashosMutexWait(); if (addr % FLASH_BLOCK_SIZE_IN_BYTES != 0) { //buf = (uint8_t *)rt_malloc(FLASH_BLOCK_SIZE_IN_BYTES); buf = (uint8_t *)malloc(FLASH_BLOCK_SIZE_IN_BYTES); if (!buf) { TRACE("%s %d, rt_malloc error", __func__, __LINE__); ret = -1; goto end; } } else { if (lengthToBurn % FLASH_BLOCK_SIZE_IN_BYTES != 0) { //buf = (uint8_t *)rt_malloc(FLASH_BLOCK_SIZE_IN_BYTES); buf = (uint8_t *)malloc(FLASH_BLOCK_SIZE_IN_BYTES); if (!buf) { TRACE("%s %d, rt_malloc error", __func__, __LINE__); ret = -1; goto end; } } } pmu_flash_write_config(); if (flash_offset % FLASH_BLOCK_SIZE_IN_BYTES != 0) { left_len = FLASH_BLOCK_SIZE_IN_BYTES - flash_offset % FLASH_BLOCK_SIZE_IN_BYTES; fill_len = (left_len >= lengthToBurn) ? lengthToBurn : left_len; align_len = flash_offset; align_len -= align_len % FLASH_BLOCK_SIZE_IN_BYTES; memset(buf, 0, FLASH_BLOCK_SIZE_IN_BYTES); // read first lock = int_lock(); flashPointer = (volatile char *)(FLASH_NC_BASE + align_len); memcpy(buf, (void *)flashPointer, FLASH_BLOCK_SIZE_IN_BYTES); ret = hal_norflash_erase(HAL_NORFLASH_ID_0, align_len, FLASH_BLOCK_SIZE_IN_BYTES); if (ret != HAL_NORFLASH_OK) { TRACE("error %s %d, hal_norflash_erase ret:%d", __func__, __LINE__, ret); pmu_flash_read_config(); int_unlock(lock); goto end; } memcpy((buf + flash_offset % FLASH_BLOCK_SIZE_IN_BYTES), ptrSource, fill_len); ret = hal_norflash_write(HAL_NORFLASH_ID_0, align_len, buf, FLASH_BLOCK_SIZE_IN_BYTES); if (ret != HAL_NORFLASH_OK) { TRACE("error %s %d, hal_norflash_write ret:%d", __func__, __LINE__, ret); pmu_flash_read_config(); int_unlock(lock); goto end; } int_unlock(lock); #ifdef __WATCHER_DOG_RESET__ app_wdt_ping(); #endif lengthToBurn -= fill_len; flash_offset += fill_len; ptrSource += fill_len; } if (lengthToBurn > 0) { for (num = 0; num < lengthToBurn / FLASH_BLOCK_SIZE_IN_BYTES; num ++) { lock = int_lock(); ret = hal_norflash_erase(HAL_NORFLASH_ID_0, flash_offset, FLASH_BLOCK_SIZE_IN_BYTES); if (ret != HAL_NORFLASH_OK) { TRACE("error %s %d, hal_norflash_erase ret:%d", __func__, __LINE__, ret); pmu_flash_read_config(); int_unlock(lock); goto end; } ret = hal_norflash_write(HAL_NORFLASH_ID_0, flash_offset, ptrSource, FLASH_BLOCK_SIZE_IN_BYTES); if (ret != HAL_NORFLASH_OK) { TRACE("error %s %d, hal_norflash_write ret:%d", __func__, __LINE__, ret); pmu_flash_read_config(); int_unlock(lock); goto end; } int_unlock(lock); #ifdef __WATCHER_DOG_RESET__ app_wdt_ping(); #endif flash_offset += FLASH_BLOCK_SIZE_IN_BYTES; ptrSource += FLASH_BLOCK_SIZE_IN_BYTES; } left_len = lengthToBurn % FLASH_BLOCK_SIZE_IN_BYTES; if (left_len) { memset(buf, 0, FLASH_BLOCK_SIZE_IN_BYTES); // read first lock = int_lock(); flashPointer = (volatile char *)(FLASH_NC_BASE + flash_offset); memcpy(buf, (void *)flashPointer, FLASH_BLOCK_SIZE_IN_BYTES); ret = hal_norflash_erase(HAL_NORFLASH_ID_0, flash_offset, FLASH_BLOCK_SIZE_IN_BYTES); if (ret != HAL_NORFLASH_OK) { TRACE("error %s %d, hal_norflash_erase ret:%d", __func__, __LINE__, ret); pmu_flash_read_config(); int_unlock(lock); goto end; } memcpy(buf, ptrSource, left_len); ret = hal_norflash_write(HAL_NORFLASH_ID_0, flash_offset, buf, FLASH_BLOCK_SIZE_IN_BYTES); if (ret != HAL_NORFLASH_OK) { TRACE("error %s %d, hal_norflash_write ret:%d", __func__, __LINE__, ret); pmu_flash_read_config(); int_unlock(lock); goto end; } int_unlock(lock); #ifdef __WATCHER_DOG_RESET__ app_wdt_ping(); #endif } } pmu_flash_read_config(); end: if (addr % FLASH_BLOCK_SIZE_IN_BYTES != 0) { //rt_free(buf); free(buf); buf = NULL; } else { if (lengthToBurn % FLASH_BLOCK_SIZE_IN_BYTES != 0) { //rt_free(buf); free(buf); buf = NULL; } } osMutexRelease(FlashMutex); RETURN: return ret; } #else int bes_hal_flash_write(const hal_partition_t partition, const uint32_t addr, const uint8_t *src, const uint32_t size) { int ret = 0; uint32_t lock; watchdog_feeddog(); FlashosMutexWait(); lock = int_lock(); pmu_flash_write_config(); if (partition == HAL_PARTITION_APPLICATION) { hal_norflash_disable_remap(HAL_NORFLASH_ID_0); } ret = hal_norflash_write(HAL_NORFLASH_ID_0, addr, src, size); if (partition == HAL_PARTITION_APPLICATION) { hal_norflash_re_enable_remap(HAL_NORFLASH_ID_0); } pmu_flash_read_config(); int_unlock(lock); osMutexRelease(FlashMutex); if (ret != HAL_NORFLASH_OK) { TRACE("error %s %d, hal_norflash_write ret:%d", __func__, __LINE__, ret); } return ret; } #endif #if 0 int bes_hal_flash_erase(const uint32_t addr, const uint32_t size) { int i = 0; int ret = 0; uint32_t lock = 0; uint32_t start_addr = addr; uint16_t start_sec = (addr / FLASH_SECTOR_SIZE_IN_BYTES); uint16_t end_sec = ((addr + size - 1) / FLASH_SECTOR_SIZE_IN_BYTES); if (addr % FLASH_SECTOR_SIZE_IN_BYTES != 0) { TRACE("%s %d, unaligned addr:%d", __func__, __LINE__, addr); //return -2; // allow to erase from unaligned addr } FlashosMutexWait(); lock = int_lock(); pmu_flash_write_config(); for (i = start_sec; i <= end_sec; i++) { ret = hal_norflash_erase(HAL_NORFLASH_ID_0, start_addr, FLASH_SECTOR_SIZE_IN_BYTES); if (ret != HAL_NORFLASH_OK) { TRACE("error %s %d, ret:%d", __func__, __LINE__, ret); goto end; } start_addr += FLASH_SECTOR_SIZE_IN_BYTES; } end: pmu_flash_read_config(); int_unlock(lock); osMutexRelease(FlashMutex); return ret; } #else int bes_hal_flash_erase(const hal_partition_t partition, const uint32_t addr, const uint32_t size) { int i = 0; int ret = 0; uint32_t lock = 0; FlashosMutexWait(); lock = int_lock(); pmu_flash_write_config(); if (partition == HAL_PARTITION_APPLICATION) { hal_norflash_disable_remap(HAL_NORFLASH_ID_0); } ret = hal_norflash_erase(HAL_NORFLASH_ID_0, addr, size); if (ret != HAL_NORFLASH_OK) { TRACE("error %s %d, ret:%d", __func__, __LINE__, ret); } if (partition == HAL_PARTITION_APPLICATION) { hal_norflash_re_enable_remap(HAL_NORFLASH_ID_0); } pmu_flash_read_config(); int_unlock(lock); osMutexRelease(FlashMutex); return ret; } #endif enum ota_link bes_get_current_link(void) { int32_t ret = 0; struct ota_boot_info info; enum bootinfo_zone zone; zone = ota_get_valid_bootinfo_zone(); ret = ota_get_bootinfo(&info, zone); if (ret) { return -1; } return info.update_link; } hal_partition_t bes_get_operate_partition(const hal_partition_t in_partition) { hal_partition_t out_partition = 0; int32_t ret = 0; hal_partition_t partition_index; hal_logic_partition_t partition_info; struct ota_boot_info info; enum bootinfo_zone zone; if (in_partition >= HAL_PARTITION_MAX) { return HAL_PARTITION_ERROR; } if (ota_current_link == OTA_LINK_ERR) { ota_current_link = bes_get_current_link(); } if (in_partition == HAL_PARTITION_OTA_TEMP) { if (ota_current_link == OTA_LINK_A) { //Now run RTOS zoneA, update zoneB. out_partition = HAL_PARTITION_OTA_TEMP; } else if (ota_current_link == OTA_LINK_B) { //Now run RTOS zoneB, update zoneA. out_partition = HAL_PARTITION_APPLICATION; } } else { out_partition = in_partition; } return out_partition; } int32_t hal_flash_mtdpart_info_get(hal_mtdpart_info_t **result_array, int *cnt) { #if CONFIG_U_FLASH_CORE return -1; #else hal_logic_partition_t *p; hal_mtdpart_info_t *arr; size_t total = hal_partitions_amount; /* get the actual cnt */ *cnt = 0; for (int i = 0; i < total; i++) { p = &hal_partitions[i]; if (p->partition_description == NULL) continue; *cnt += 1; } /* memory alloc */ *result_array = (hal_mtdpart_info_t *)malloc(sizeof(hal_mtdpart_info_t) * (*cnt)); if (*result_array == NULL) { return -1; } /* fetch result */ int idx = 0; arr = *result_array; for (int i = 0; i < total; i++) { p = &hal_partitions[i]; if (p->partition_description == NULL) continue; arr[idx].p = i; arr[idx].descr = (char *)p->partition_description; arr[idx].offset = p->partition_start_addr; arr[idx].siz = p->partition_length; arr[idx].ssiz = CONFIG_LFS_PROG_SIZE; arr[idx].bsiz = CONFIG_LFS_PROG_SIZE * CONFIG_LFS_PAGE_NUM_PER_BLOCK; idx++; } return 0; #endif } /** * Get the information of the specified flash area * * @param[in] in_partition The target flash logical partition * @param[in] partition The buffer to store partition info * * @return 0: On success, otherwise is error */ int32_t hal_flash_info_get(hal_partition_t in_partition, hal_logic_partition_t *partition) { int32_t ret = -1; hal_logic_partition_t *logic_partition; hal_partition_t partition_id = 0; if ((partition != NULL) && (in_partition < hal_partitions_amount)) { ENTER_FUNCTION(); partition_id = bes_get_operate_partition(in_partition); if (partition_id < 0) { TRACE("bes_get_operate_partition fail\n"); } else { logic_partition = (hal_logic_partition_t *)&hal_partitions[partition_id]; memcpy(partition, logic_partition, sizeof(hal_logic_partition_t)); ret = 0; } LEAVE_FUNCTION(); } return ret; } /** * Erase an area on a Flash logical partition * * @note Erase on an address will erase all data on a sector that the * address is belonged to, this function does not save data that * beyond the address area but in the affected sector, the data * will be lost. * * @param[in] in_partition The target flash logical partition which should be erased * @param[in] off_set Start address of the erased flash area * @param[in] size Size of the erased flash area * * @return 0 : On success, EIO : If an error occurred with any step */ int32_t hal_flash_erase(hal_partition_t in_partition, uint32_t off_set, uint32_t size) { uint32_t start_addr; hal_logic_partition_t info; hal_partition_t operate_partition_id = 0; int32_t ret = 0; watchdog_feeddog(); ENTER_FUNCTION(); if (hal_flash_info_get(in_partition, &info) != 0) { TRACEME("hal_flash_info_get fail\n"); ret = -1; goto RETURN; } start_addr = info.partition_start_addr + off_set; operate_partition_id = bes_get_operate_partition(in_partition); TRACEME("hal_flash_erase part start0x%x offset 0x%x size 0x%x\n", info.partition_start_addr, off_set, size); ret = bes_hal_flash_erase(operate_partition_id, start_addr, size); RETURN: LEAVE_FUNCTION(); return ret; } /** * Write data to an area on a flash logical partition without erase * * @param[in] in_partition The target flash logical partition which should be read which should be written * @param[in] off_set Point to the start address that the data is written to, and * point to the last unwritten address after this function is * returned, so you can call this function serval times without * update this start address. * @param[in] inBuffer point to the data buffer that will be written to flash * @param[in] inBufferLength The length of the buffer * * @return 0 : On success, EIO : If an error occurred with any step */ int32_t hal_flash_write(hal_partition_t in_partition, uint32_t *off_set, const void *in_buf, uint32_t in_buf_len) { int32_t ret = 0; uint32_t start_addr; uint32_t partition_end; hal_logic_partition_t info; hal_partition_t operate_partition_id = 0; ENTER_FUNCTION(); if (hal_flash_info_get(in_partition, &info) != 0) { TRACEME("hal_flash_info_get fail\n"); ret = -1; goto RETURN; } start_addr = info.partition_start_addr + *off_set; partition_end = info.partition_start_addr + info.partition_length; TRACEME("hal_flash_write partstart 0x%x offset 0x%x len 0x%x\n", info.partition_start_addr, *off_set, in_buf_len); if(start_addr >= partition_end){ TRACEME("flash over write\r\n"); ret = -1; goto RETURN; } if((start_addr + in_buf_len) > partition_end){ in_buf_len = partition_end - start_addr; TRACEME("flash over write, new len is %d\r\n", in_buf_len); } operate_partition_id = bes_get_operate_partition(in_partition); ret = bes_hal_flash_write(operate_partition_id, start_addr, in_buf, in_buf_len); if (!ret) { *off_set += in_buf_len; } RETURN: LEAVE_FUNCTION(); return ret; } /** * Write data to an area on a flash logical partition with erase first * * @param[in] in_partition The target flash logical partition which should be read which should be written * @param[in] off_set Point to the start address that the data is written to, and * point to the last unwritten address after this function is * returned, so you can call this function serval times without * update this start address. * @param[in] inBuffer point to the data buffer that will be written to flash * @param[in] inBufferLength The length of the buffer * * @return 0 : On success, EIO : If an error occurred with any step */ int32_t hal_flash_erase_write(hal_partition_t in_partition, uint32_t *off_set, const void *in_buf, uint32_t in_buf_len) { int32_t ret = 0; uint32_t start_addr; uint32_t partition_end; hal_logic_partition_t info; hal_partition_t operate_partition_id = 0; ENTER_FUNCTION(); if (hal_flash_info_get(in_partition, &info) != 0) { TRACEME("hal_flash_info_get fail\n"); ret = -1; goto RETURN; } start_addr = info.partition_start_addr + *off_set; partition_end = info.partition_start_addr + info.partition_length; if(start_addr >= partition_end){ TRACEME("flash over write\r\n"); ret = -1; goto RETURN; } if((start_addr + in_buf_len) > partition_end){ in_buf_len = partition_end - start_addr; TRACEME("flash over write, new len is %d\r\n", in_buf_len); } operate_partition_id = bes_get_operate_partition(in_partition); ret = bes_hal_flash_erase(operate_partition_id, start_addr, in_buf_len); if (ret) { TRACEME("flash erase fail\r\n"); ret = -1; goto RETURN; } ret = bes_hal_flash_write(operate_partition_id, start_addr, in_buf, in_buf_len); if (!ret) { *off_set += in_buf_len; } RETURN: LEAVE_FUNCTION(); return ret; } /** * Read data from an area on a Flash to data buffer in RAM * * @param[in] in_partition The target flash logical partition which should be read * @param[in] off_set Point to the start address that the data is read, and * point to the last unread address after this function is * returned, so you can call this function serval times without * update this start address. * @param[in] outBuffer Point to the data buffer that stores the data read from flash * @param[in] inBufferLength The length of the buffer * * @return 0 : On success, EIO : If an error occurred with any step */ int32_t hal_flash_read(hal_partition_t in_partition, uint32_t *off_set, void *out_buf, uint32_t in_buf_len) { int32_t ret = 0; uint32_t start_addr; hal_logic_partition_t info; hal_partition_t operate_partition_id = 0; ENTER_FUNCTION(); if (hal_flash_info_get(in_partition, &info) != 0) { TRACEME("hal_flash_info_get fail\n"); ret = -1; goto RETURN; } start_addr = info.partition_start_addr + *off_set; operate_partition_id = bes_get_operate_partition(in_partition); ret = bes_hal_flash_read(operate_partition_id, start_addr, out_buf, in_buf_len); if(ret == 0) { *off_set += in_buf_len; } RETURN: LEAVE_FUNCTION(); return ret; } /** * Set security options on a logical partition * * @param[in] partition The target flash logical partition * @param[in] offset Point to the start address that the data is read, and * point to the last unread address after this function is * returned, so you can call this function serval times without * update this start address. * @param[in] size Size of enabled flash area * * @return 0 : On success, EIO : If an error occurred with any step */ int32_t hal_flash_enable_secure(hal_partition_t partition, uint32_t off_set, uint32_t size) { //FAIL_FUNCTION(); return 0; } /** * Disable security options on a logical partition * * @param[in] partition The target flash logical partition * @param[in] offset Point to the start address that the data is read, and * point to the last unread address after this function is * returned, so you can call this function serval times without * update this start address. * @param[in] size Size of disabled flash area * * @return 0 : On success, EIO : If an error occurred with any step */ int32_t hal_flash_dis_secure(hal_partition_t partition, uint32_t off_set, uint32_t size) { //FAIL_FUNCTION(); return 0; } /** * Convert physical address to logic partition id and offset in partition * * @param[out] in_partition Point to the logic partition id * @param[out] off_set Point to the offset in logic partition * @param[in] addr The physical address * * @return 0 : On success, EIO : If an error occurred with any step */ int32_t hal_flash_addr2offset(hal_partition_t *in_partition, uint32_t *off_set, uint32_t addr) { //FAIL_FUNCTION(); return 0; }
YifuLiu/AliOS-Things
hardware/chip/haas1000/hal/flash.c
C
apache-2.0
21,934
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <string.h> #include "aos/hal/gpio.h" #include "hal_gpio.h" #include "hal_trace.h" struct gpio_irq_handler { uint8_t port; gpio_irq_handler_t func; void *arg; }; static struct gpio_irq_handler bes_gpio_irq_handler[HAL_GPIO_PIN_NUM] = {0}; /** * Initialises a GPIO pin * * @note Prepares a GPIO pin for use. * * @param[in] gpio the gpio pin which should be initialised * @param[in] configuration A structure containing the required gpio configuration * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_gpio_init(gpio_dev_t *gpio) { struct HAL_IOMUX_PIN_FUNCTION_MAP cfg_hw_gpio; if (gpio->port >= HAL_IOMUX_PIN_LED_NUM) { return -1; } cfg_hw_gpio.pin = gpio->port; cfg_hw_gpio.function = HAL_IOMUX_FUNC_AS_GPIO; cfg_hw_gpio.volt = HAL_IOMUX_PIN_VOLTAGE_VIO; cfg_hw_gpio.pull_sel = HAL_IOMUX_PIN_NOPULL; if ((gpio->config == OUTPUT_PUSH_PULL) || (gpio->config == OUTPUT_OPEN_DRAIN_PULL_UP) || (gpio->config == INPUT_PULL_UP) || (gpio->config == IRQ_MODE)) { cfg_hw_gpio.pull_sel = HAL_IOMUX_PIN_PULLUP_ENALBE; } else if ((gpio->config == INPUT_PULL_DOWN)) { cfg_hw_gpio.pull_sel = HAL_IOMUX_PIN_PULLDOWN_ENALBE; } hal_iomux_init((struct HAL_IOMUX_PIN_FUNCTION_MAP *)&cfg_hw_gpio, 1); return 0; } /** * Sets an output GPIO pin high * * @note Using this function on a gpio pin which is set to input mode is undefined. * * @param[in] gpio the gpio pin which should be set high * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_gpio_output_high(gpio_dev_t *gpio) { hal_gpio_pin_set_dir((enum HAL_GPIO_PIN_T)gpio->port, HAL_GPIO_DIR_OUT, 1); return 0; } /** * Sets an output GPIO pin low * * @note Using this function on a gpio pin which is set to input mode is undefined. * * @param[in] gpio the gpio pin which should be set low * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_gpio_output_low(gpio_dev_t *gpio) { hal_gpio_pin_set_dir((enum HAL_GPIO_PIN_T)gpio->port, HAL_GPIO_DIR_OUT, 0); return 0; } /** * Trigger an output GPIO pin's output. Using this function on a * gpio pin which is set to input mode is undefined. * * @param[in] gpio the gpio pin which should be set low * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_gpio_output_toggle(gpio_dev_t *gpio) { uint8_t level = 0; level = hal_gpio_pin_get_val((enum HAL_GPIO_PIN_T)gpio->port); level ^= 1; hal_gpio_pin_set_dir((enum HAL_GPIO_PIN_T)gpio->port, HAL_GPIO_DIR_OUT, level); return 0; } /** * Get the state of an input GPIO pin. Using this function on a * gpio pin which is set to output mode will return an undefined value. * * @param[in] gpio the gpio pin which should be read * @param[in] value gpio value * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_gpio_input_get(gpio_dev_t *gpio, uint32_t *value) { int32_t ret = -1; if(NULL != gpio && NULL != value) { hal_gpio_pin_set_dir(gpio->port, HAL_GPIO_DIR_IN, 0); *value = hal_gpio_pin_get_val(gpio->port); ret = 0; } return ret; } int32_t hal_gpio_get(gpio_dev_t *gpio, uint32_t *value) { int32_t ret = -1; if(NULL != gpio && NULL != value) { *value = hal_gpio_pin_get_val(gpio->port); ret = 0; } return ret; } void bes_gpio_irq_hdl(enum HAL_GPIO_PIN_T pin) { struct gpio_irq_handler *hdl_pointer = NULL; if (pin >= HAL_GPIO_PIN_NUM) { TRACE("%s %d, error pin:%d", __func__, __LINE__, pin); return; } //TRACE("%s %d, pin:%d", __func__, __LINE__, pin); hdl_pointer = &bes_gpio_irq_handler[pin]; if (hdl_pointer->port == pin) { if (hdl_pointer->func) { hdl_pointer->func(hdl_pointer->arg); } else { TRACE("%s %d, error hdl_pointer->func == NULL", __func__, __LINE__); } } else { TRACE("%s %d, error pin:%d, hdl_pointer->port:%d", __func__, __LINE__, pin, hdl_pointer->port); } } /** * Enables an interrupt trigger for an input GPIO pin. * Using this function on a gpio pin which is set to * output mode is undefined. * * @param[in] gpio the gpio pin which will provide the interrupt trigger * @param[in] trigger the type of trigger (rising/falling edge) * @param[in] handler a function pointer to the interrupt handler * @param[in] arg an argument that will be passed to the interrupt handler * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_gpio_enable_irq(gpio_dev_t *gpio, gpio_irq_trigger_t trigger, gpio_irq_handler_t handler, void *arg) { struct HAL_GPIO_IRQ_CFG_T gpiocfg; if (gpio->port >= HAL_GPIO_PIN_NUM) { TRACE("%s %d, error gpio->port:%d", __func__, __LINE__, gpio->port); return -1; } memset(&bes_gpio_irq_handler[gpio->port], 0, sizeof(struct gpio_irq_handler)); bes_gpio_irq_handler[gpio->port].port = gpio->port; bes_gpio_irq_handler[gpio->port].func = handler; bes_gpio_irq_handler[gpio->port].arg = arg; hal_gpio_pin_set_dir(gpio->port, HAL_GPIO_DIR_IN, 0); gpiocfg.irq_enable = true; gpiocfg.irq_debounce = true; gpiocfg.irq_polarity = (trigger == IRQ_TRIGGER_RISING_EDGE) ? HAL_GPIO_IRQ_POLARITY_HIGH_RISING : HAL_GPIO_IRQ_POLARITY_LOW_FALLING; gpiocfg.irq_handler = bes_gpio_irq_hdl; gpiocfg.irq_type = HAL_GPIO_IRQ_TYPE_EDGE_SENSITIVE; hal_gpio_setup_irq(gpio->port, &gpiocfg); return 0; } /** * Disables an interrupt trigger for an input GPIO pin. * Using this function on a gpio pin which has not been set up * using @ref hal_gpio_input_irq_enable is undefined. * * @param[in] gpio the gpio pin which provided the interrupt trigger * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_gpio_disable_irq(gpio_dev_t *gpio) { const struct HAL_GPIO_IRQ_CFG_T gpiocfg = { .irq_enable = false, .irq_debounce = false, .irq_polarity = HAL_GPIO_IRQ_POLARITY_LOW_FALLING, .irq_handler = NULL, .irq_type = HAL_GPIO_IRQ_TYPE_EDGE_SENSITIVE, }; hal_gpio_setup_irq(gpio->port, &gpiocfg); return 0; } /** * Clear an interrupt status for an input GPIO pin. * Using this function on a gpio pin which has generated a interrupt. * * @param[in] gpio the gpio pin which provided the interrupt trigger * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_gpio_clear_irq(gpio_dev_t *gpio) { const struct HAL_GPIO_IRQ_CFG_T gpiocfg = { .irq_enable = false, .irq_debounce = false, .irq_polarity = HAL_GPIO_IRQ_POLARITY_LOW_FALLING, .irq_handler = NULL, .irq_type = HAL_GPIO_IRQ_TYPE_EDGE_SENSITIVE, }; hal_gpio_setup_irq(gpio->port, &gpiocfg); return 0; } /** * Set a GPIO pin in default state. * * @param[in] gpio the gpio pin which should be deinitialised * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_gpio_finalize(gpio_dev_t *gpio) { return 0; }
YifuLiu/AliOS-Things
hardware/chip/haas1000/hal/gpio.c
C
apache-2.0
7,325
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/hal/i2c.h" #include "hal_i2c.h" #include "app_hal.h" #include "aos/kernel.h" #include "hal_trace.h" aos_mutex_t i2c_mutex; static bool mutex_init = false; /*#define I2C1_IOMUX_INDEX 22*/ /** * Initialises an I2C interface * Prepares an I2C hardware interface for communication as a master or slave * * @param[in] i2c the device for which the i2c port should be initialised * * @return 0 : on success, EIO : if an error occurred during initialisation */ int32_t hal_i2c_init(i2c_dev_t *i2c) { uint32_t ret = 0; int32_t lock_ret = -1; uint8_t i2c_port; struct HAL_I2C_CONFIG_T i2c_cfg; if (mutex_init == false) { ret = aos_mutex_new(&i2c_mutex); TRACE("aos_mutex_new returns %d", ret); mutex_init = true; } lock_ret = aos_mutex_lock(&i2c_mutex, AOS_WAIT_FOREVER); if (lock_ret != 0) { TRACE("get i2c_mutex lock fail"); return lock_ret; } i2c_port = i2c->port; if (i2c_port == 0) { hal_iomux_set_i2c0(); } else if (i2c_port == 1) { hal_iomux_set_i2c1(); } i2c_cfg.mode = HAL_I2C_API_MODE_TASK; i2c_cfg.use_dma = 0; i2c_cfg.use_sync = 1; i2c_cfg.speed = i2c->config.freq; i2c_cfg.as_master = 1; ret = hal_i2c_open(i2c_port, &i2c_cfg); if (ret) { TRACE("open i2c fail\n"); } else { TRACE("open i2c succ.\n"); } aos_mutex_unlock(&i2c_mutex); return 0; } /** * I2c master send * * @param[in] i2c the i2c device * @param[in] dev_addr device address * @param[in] data i2c send data * @param[in] size i2c send data size * @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 during initialisation */ 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; uint8_t i2c_port; int32_t lock_ret = -1; lock_ret = aos_mutex_lock(&i2c_mutex, timeout); if (lock_ret != 0) { TRACE("i2c_master_send, get i2c_mutex lock fail, timeout:%d", timeout); return lock_ret; } i2c_port = i2c->port; ret = hal_i2c_task_send(i2c_port, dev_addr, data, size, 0, NULL); if(ret) { TRACE("%s:%d,i2c send fail, dev_addr = 0x%x, data[0] = 0x%x, data[1]= 0x%x, ret = %d\n", __func__,__LINE__,dev_addr, data[0], data[1], ret); } aos_mutex_unlock(&i2c_mutex); return ret; } /** * I2c master recv * * @param[in] i2c the i2c device * @param[in] dev_addr device address * @param[out] data i2c receive data * @param[in] size i2c receive data size * @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 during initialisation */ 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; uint8_t i2c_port; int32_t lock_ret = -1; lock_ret = aos_mutex_lock(&i2c_mutex, timeout); if (lock_ret != 0) { TRACE("i2c_master_recv, get i2c_mutex lock fail ret:%d", lock_ret); return lock_ret; } i2c_port = i2c->port; /*ret = hal_i2c_recv(i2c_port, dev_addr, data, 1, size - 1, HAL_I2C_RESTART_AFTER_WRITE, 0, NULL);*/ ret = hal_i2c_recv(i2c_port, dev_addr, data, 0, size, HAL_I2C_RESTART_AFTER_WRITE, 0, NULL); if(ret) { TRACE("%s:%d,i2c read failed, dev_addr = 0x%x, data[0] = 0x%x, data[1]= 0x%x, ret = %d\n", __func__,__LINE__,dev_addr, data[0], data[1], ret); } aos_mutex_unlock(&i2c_mutex); return ret; } uint32_t hal_i2c_master_recv_vendor(i2c_dev_t *i2c, uint16_t device_addr, uint8_t *tx_buf, uint16_t tx_len, uint8_t *rx_buf, uint16_t rx_len) { int32_t ret; uint8_t i2c_port; int32_t lock_ret = -1; lock_ret = aos_mutex_lock(&i2c_mutex, AOS_WAIT_FOREVER); if (lock_ret != 0) { TRACE("i2c_master_recv, get i2c_mutex lock fail"); return lock_ret; } i2c_port = i2c->port; ret = hal_i2c_task_recv(i2c_port, device_addr, tx_buf, tx_len, rx_buf, rx_len, 0, NULL); if(ret) { TRACE("%s:%d,i2c read failed, dev_addr=0x%x, data[0]=0x%x, ret=%d", __func__,__LINE__,device_addr, ret); } aos_mutex_unlock(&i2c_mutex); return ret; } /** * I2c slave send * * @param[in] i2c the i2c device * @param[in] data i2c slave send data * @param[in] size i2c slave send data size * @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 during initialisation */ int32_t hal_i2c_slave_send(i2c_dev_t *i2c, const uint8_t *data, uint16_t size, uint32_t timeout) { uint32_t act_write; int32_t ret; uint8_t i2c_port; int32_t lock_ret = -1; lock_ret = aos_mutex_lock(&i2c_mutex, timeout); if (lock_ret != 0) { TRACE("hal_i2c_slave_send, get i2c_mutex lock fail"); return lock_ret; } i2c_port = i2c->port; ret = hal_i2c_slv_write(i2c_port, data, size, &act_write); aos_mutex_unlock(&i2c_mutex); return ret; } /** * I2c slave receive * * @param[in] i2c tthe i2c device * @param[out] data i2c slave receive data * @param[in] size i2c slave receive data size * @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 during initialisation */ int32_t hal_i2c_slave_recv(i2c_dev_t *i2c, uint8_t *data, uint16_t size, uint32_t timeout) { uint32_t act_read; int32_t ret; uint8_t i2c_port; int32_t lock_ret = -1; lock_ret = aos_mutex_lock(&i2c_mutex, timeout); if (lock_ret != 0) { TRACE("hal_i2c_slave_recv, get i2c_mutex lock fail"); return lock_ret; } i2c_port = i2c->port; ret = hal_i2c_slv_read(i2c_port, data, size, &act_read); aos_mutex_unlock(&i2c_mutex); return ret; } /** * I2c mem write * * @param[in] i2c the i2c device * @param[in] dev_addr device address * @param[in] mem_addr mem address * @param[in] mem_addr_size mem address * @param[in] data i2c master send data * @param[in] size i2c master send data size * @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 during initialisation */ 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; uint8_t i2c_port; int32_t lock_ret = -1; uint8_t *txbuf; uint16_t txlen; if((NULL == i2c) || (NULL == data) || (0 == mem_addr_size) || (0 == size)) { TRACE("i2c input para err"); return -1; } i2c_port = i2c->port; txlen = size + mem_addr_size; txbuf = (uint8_t *)malloc(txlen); if (txbuf == NULL) { TRACE("%s malloc size %d error\r", __FUNCTION__, txlen); return -1; } memset(txbuf, 0, txlen); txbuf[0] = (uint8_t)mem_addr; memcpy(&txbuf[1], data, size); lock_ret = aos_mutex_lock(&i2c_mutex, timeout); if (lock_ret != 0) { TRACE("hal_i2c_mem_write, get i2c_mutex lock fail"); free(txbuf); return lock_ret; } ret = hal_i2c_task_send(i2c_port, dev_addr, txbuf, txlen, 0, NULL); if(ret) { TRACE("%s:%d,i2c send failed,dev_addr = 0x%x,ret = %d\n", __func__,__LINE__,dev_addr,ret); } aos_mutex_unlock(&i2c_mutex); free(txbuf); return ret; } /** * I2c master mem read * * @param[in] i2c the i2c device * @param[in] dev_addr device address * @param[in] mem_addr mem address * @param[in] mem_addr_size mem address * @param[out] data i2c master send data * @param[in] size i2c master send data size * @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 during initialisation */ 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; uint8_t i2c_port; int32_t lock_ret = -1; uint8_t *txrxbuf; uint16_t txrxlen; if((NULL == i2c) || (NULL == data) || (0 == mem_addr_size) || (0 == size)) { TRACE("i2c input para err"); return -1; } i2c_port = i2c->port; txrxlen = size + mem_addr_size; txrxbuf = (uint8_t *)malloc(txrxlen); if (txrxbuf == NULL) { TRACE("%s malloc size %d error\r", __FUNCTION__, txrxlen); return -1; } memset(txrxbuf, 0, txrxlen); txrxbuf[0] = (uint8_t)mem_addr; lock_ret = aos_mutex_lock(&i2c_mutex, timeout); if (lock_ret != 0) { TRACE("hal_i2c_mem_read, get i2c_mutex lock fail"); free(txrxbuf); return lock_ret; } ret = hal_i2c_recv(i2c_port, dev_addr, txrxbuf, mem_addr_size, size, HAL_I2C_RESTART_AFTER_WRITE, 0, 0); if (ret) { TRACE("%s:i2c recv failed,dev_addr = 0x%x,ret = %d\n", __func__, dev_addr, ret); } else { memcpy(data, &txrxbuf[1], size); } aos_mutex_unlock(&i2c_mutex); free(txrxbuf); return ret; } /** * Deinitialises an I2C device * * @param[in] i2c the i2c device * * @return 0 : on success, EIO : if an error occurred during deinitialisation */ int32_t hal_i2c_finalize(i2c_dev_t *i2c) { int32_t ret = 0; ret = hal_i2c_close(i2c->port); if (ret) { TRACE("close i2c fail\n"); } else { TRACE("close i2c succ.\n"); } return ret; }
YifuLiu/AliOS-Things
hardware/chip/haas1000/hal/i2c.c
C
apache-2.0
9,755
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/hal/i2s.h" /** * Initialises a I2S dev * * @param[in] i2s the dev which should be initialised * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_i2s_init(i2s_dev_t *i2s) { return 0; } /** * Transmit data on a I2S dev * * @param[in] i2s the I2S dev * @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_i2s_send(i2s_dev_t *i2s, const void *data, uint32_t size, uint32_t timeout) { return 0; } /** * Receive data on a I2S dev * * @param[in] i2s the I2S dev * @param[out] data pointer to the buffer which will store incoming data * @param[in] size number of bytes to receive * @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_i2s_recv(i2s_dev_t *i2s, void *data, uint32_t size, uint32_t timeout) { return 0; } /** * Pause a I2S dev * * @param[in] i2s the dev which should be deinitialised * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_i2s_pause(i2s_dev_t *i2s) { return 0; } /** * Resume a I2S dev * * @param[in] i2s the dev which should be deinitialised * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_i2s_resume(i2s_dev_t *i2s) { return 0; } /** * Stop a I2S dev * * @param[in] i2s the dev which should be deinitialised * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_i2s_stop(i2s_dev_t *i2s) { return 0; } /** * Deinitialises a I2S dev * * @param[in] i2s the dev which should be deinitialised * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_i2s_finalize(i2s_dev_t *i2s) { return 0; }
YifuLiu/AliOS-Things
hardware/chip/haas1000/hal/i2s.c
C
apache-2.0
2,181
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/hal/interpt.h" /** * Interrupt vector init * * @return 0 : on success, -1 : if an error occurred with any step */ int32_t hal_interpt_init(void) { return 0; } /** * Mask specified interrupt vector * * * @param[in] vec specified interrupt vector * * @return 0 : on success, -1 : if an error occurred with any step */ int32_t hal_interpt_mask(int32_t vec) { return 0; } /** * Unmask specified interrupt vector * * * @param[in] vec specified interrupt vector * * @return 0 : on success, -1 : if an error occurred with any step */ int32_t hal_interpt_umask(int32_t vec) { return 0; } /** * Install specified interrupt vector * * * @param[in] vec specified interrupt vector * * @return 0 : on success, -1 : if an error occurred with any step */ int32_t hal_interpt_install(int32_t vec, hal_interpt_t handler, void *para, char *name) { return 0; }
YifuLiu/AliOS-Things
hardware/chip/haas1000/hal/interpt.c
C
apache-2.0
967
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/hal/nand.h" /** * Initialises a nand flash interface * * @param[in] nand the interface which should be initialised * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_nand_init(nand_dev_t *nand) { return 0; } /** * Deinitialises a nand flash interface * * @param[in] nand the interface which should be initialised * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_nand_finalize(nand_dev_t *nand) { return 0; } /** * Read nand page(s) * * @param[in] nand the interface which should be initialised * @param[out] data pointer to the buffer which will store incoming data * @param[in] addr nand address * @param[in] page_count the number of pages to read * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_nand_read_page(nand_dev_t *nand, nand_addr_t *addr, uint8_t *data, uint32_t page_count) { return 0; } /** * Write nand page(s) * * @param[in] nand the interface which should be initialised * @param[in] data pointer to source buffer to write * @param[in] addr nand address * @param[in] page_count the number of pages to write * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_nand_write_page(nand_dev_t *nand, nand_addr_t *addr, uint8_t *data, uint32_t page_count) { return 0; } /** * Read nand spare area * * @param[in] nand the interface which should be initialised * @param[out] data pointer to the buffer which will store incoming data * @param[in] addr nand address * @param[in] data_len the number of spares to read * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_nand_read_spare(nand_dev_t *nand, nand_addr_t *addr, uint8_t *data, uint32_t data_len) { return 0; } /** * Write nand spare area * * @param[in] nand the interface which should be initialised * @param[in] data pointer to source buffer to write * @param[in] addr nand address * @param[in] data_len the number of spares to write * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_nand_write_spare(nand_dev_t *nand, nand_addr_t *addr, uint8_t *data, uint32_t data_len) { return 0; } /** * Erase nand block * * @param[in] nand the interface which should be initialised * @param[in] addr nand address * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_nand_erase_block(nand_dev_t *nand, nand_addr_t *addr) { return 0; }
YifuLiu/AliOS-Things
hardware/chip/haas1000/hal/nand.c
C
apache-2.0
2,700
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/hal/nor.h" /** * Initialises a nor flash interface * * @param[in] nor the interface which should be initialised * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_nor_init(nor_dev_t *nor) { return 0; } /** * Deinitialises a nor flash interface * * @param[in] nand the interface which should be initialised * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_nor_finalize(nor_dev_t *nor) { return 0; } /** * Read data from NOR memory * * @param[in] nor the interface which should be initialised * @param[out] data pointer to the buffer which will store incoming data * @param[in] addr nor memory address * @param[in] len the number of bytes to read * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_nor_read(nor_dev_t *nor, uint32_t *addr, uint8_t *data, uint32_t len) { return 0; } /** * Write data to NOR memory * * @param[in] nor the interface which should be initialised * @param[in] data pointer to source buffer to write * @param[in] addr nor memory address * @param[in] len the number of bytes to write * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_nor_write(nor_dev_t *nor, uint32_t *addr, uint8_t *data, uint32_t len) { return 0; } /* * Erase the blocks of the NOR memory * * @param[in] nor the interface which should be initialised * @param[in] addr nor memory address * @param[in] block_count the number of block to erase * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_nor_erase_block(nor_dev_t *nor, uint32_t *addr, uint32_t block_count) { return 0; } /* * Erase the entire NOR chip * * @param[in] nor the interface which should be initialised * @param[in] addr nor memory address * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_nor_erase_chip(nor_dev_t *nor, uint32_t *addr) { return 0; }
YifuLiu/AliOS-Things
hardware/chip/haas1000/hal/nor.c
C
apache-2.0
2,109
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/hal/pwm.h" #include "hal_pwm.h" #include "hal_gpio.h" #include "hal_trace.h" #include "hal_iomux.h" #include "hal_cmu.h" #include "pmu.h" #define _HAL_PWM_MAX_NUM 4 static struct HAL_IOMUX_PIN_FUNCTION_MAP pinmux_pwm[_HAL_PWM_MAX_NUM] = { {HAL_IOMUX_PIN_P2_6, HAL_IOMUX_FUNC_PWM0, HAL_IOMUX_PIN_VOLTAGE_VIO, HAL_IOMUX_PIN_PULLUP_ENALBE}, {HAL_IOMUX_PIN_P2_7, HAL_IOMUX_FUNC_PWM1, HAL_IOMUX_PIN_VOLTAGE_VIO, HAL_IOMUX_PIN_PULLUP_ENALBE}, {HAL_IOMUX_PIN_P2_4, HAL_IOMUX_FUNC_PWM2, HAL_IOMUX_PIN_VOLTAGE_VIO, HAL_IOMUX_PIN_PULLUP_ENALBE}, {HAL_IOMUX_PIN_P2_5, HAL_IOMUX_FUNC_PWM3, HAL_IOMUX_PIN_VOLTAGE_VIO, HAL_IOMUX_PIN_PULLUP_ENALBE}, }; typedef struct { uint8 chan; int start; struct HAL_PWM_CFG_T pwm_cfg; } _HAL_PWM_PRIV_T; static int inited[_HAL_PWM_MAX_NUM] = {0}; static enum HAL_PWM_ID_T __hal_pwm_port2chan(uint8_t port) { return (port<_HAL_PWM_MAX_NUM) ? port+HAL_PWM_ID_0 : HAL_PWM_ID_QTY; } static void __hal_pwm_pram2cfg(struct HAL_PWM_CFG_T *cfg, pwm_config_t *pram) { cfg->freq = pram->freq; cfg->ratio = pram->duty_cycle*1000; cfg->inv = false; cfg->sleep_on = false; } /** * 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) { //printf("%s port=%d, duty_cycle=%f, freq=%d, priv=%p\r\n", __FUNCTION__, pwm->port, pwm->config.duty_cycle, pwm->config.freq, pwm->priv); if (pwm->priv != NULL) { printf("%s priv=%p, SHOULD be NULL!\n", __FUNCTION__, pwm->priv); return -1; } _HAL_PWM_PRIV_T *_cfg = malloc(sizeof(_HAL_PWM_PRIV_T)); if (!_cfg) { printf("%s malloc for _HAL_PWM_PRIV_T failed\n", __FUNCTION__); return -1; } if (inited[pwm->port] == 0) { hal_iomux_init(&pinmux_pwm[pwm->port], 1); // for (int i=0; i<_HAL_PWM_MAX_NUM; i++) { hal_gpio_pin_set_dir(pinmux_pwm[pwm->port].pin, HAL_GPIO_DIR_OUT, 1); // } //init pmu pwm //pmu_write(0x2b, 0xce89); //pmu_write(0x30, 0x560c); //pmu_write(0x2f, 0x0000); hal_pwm_set_ratio_max(1000); inited[pwm->port] = 1; } _cfg->chan = __hal_pwm_port2chan(pwm->port); _cfg->start = 0; __hal_pwm_pram2cfg(&_cfg->pwm_cfg, &pwm->config); pwm->priv = (void *)_cfg; 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) { //printf("%s port=%d, duty_cycle=%f, freq=%d, priv=%p\r\n", __FUNCTION__, pwm->port, pwm->config.duty_cycle, pwm->config.freq, pwm->priv); _HAL_PWM_PRIV_T *_cfg = (_HAL_PWM_PRIV_T *)pwm->priv; if (_cfg->start == 0) { if (hal_pwm_enable(_cfg->chan, &_cfg->pwm_cfg) == 0) { _cfg->start = 1; } } 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) { //printf("%s port=%d, duty_cycle=%f, freq=%d, priv=%p\r\n", __FUNCTION__, pwm->port, pwm->config.duty_cycle, pwm->config.freq, pwm->priv); _HAL_PWM_PRIV_T *_cfg = (_HAL_PWM_PRIV_T *)pwm->priv; if (_cfg->start == 1) { if (hal_pwm_disable(_cfg->chan) == 0) { _cfg->start = 0; } } 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) { /*printf("%s port=%d, duty_cycle=%f, freq=%d, priv=%p\n", __FUNCTION__, pwm->port, pwm->config.duty_cycle, pwm->config.freq, pwm->priv);*/ /*printf("%s new duty_cycle=%f, freq=%d\n", __FUNCTION__, para.duty_cycle, para.freq);*/ _HAL_PWM_PRIV_T *_cfg = (_HAL_PWM_PRIV_T *)pwm->priv; memcpy(&pwm->config, &para, sizeof(pwm_config_t)); __hal_pwm_pram2cfg(&_cfg->pwm_cfg, &pwm->config); if (_cfg->start == 1) { hal_pwm_enable(_cfg->chan, &_cfg->pwm_cfg); } 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) { //printf("%s port=%d, duty_cycle=%f, freq=%d, priv=%p\n", __FUNCTION__, pwm->port, pwm->config.duty_cycle, pwm->config.freq, pwm->priv); _HAL_PWM_PRIV_T *_cfg = (_HAL_PWM_PRIV_T *)pwm->priv; if (_cfg) { if (_cfg->start == 1) { hal_pwm_stop(pwm); } free(_cfg); pwm->priv = NULL; } return 0; }
YifuLiu/AliOS-Things
hardware/chip/haas1000/hal/pwm.c
C
apache-2.0
4,610
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/hal/qspi.h" /** * Initialises the QSPI interface for a given QSPI device * * @param[in] qspi the spi device * * @return 0 : on success, EIO : if an error occurred */ int32_t hal_qspi_init(qspi_dev_t *qspi) { return 0; } /** * Qspi send * * @param[in] qspi the qspi device * @param[in] data spi send data * @param[in] size spi send data size * @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 */ int32_t hal_qspi_send(qspi_dev_t *qspi, const uint8_t *data, uint32_t timeout) { return 0; } /** * Qspi recv * * @param[in] qspi the qspi device * @param[out] data qspi recv data * @param[in] size qspi recv data size * @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 */ int32_t hal_qspi_recv(qspi_dev_t *qspi, uint8_t *data, uint32_t timeout) { return 0; } /** * Set qspi command * * @param[in] qspi the qspi device * @param[out] cmd qspi cmd * @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 */ int32_t hal_qspi_command(qspi_dev_t *qspi, qspi_cmd_t *cmd, uint32_t timeout) { return 0; } /** * Configure automatic polling mode to wait for processing * * @param[in] qspi the qspi device * @param[out] cmd qspi cmd * @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 */ int32_t hal_qspi_auto_polling(qspi_dev_t *qspi, uint32_t cmd, uint32_t timeout) { return 0; } /** * De-initialises a QSPI interface * * @param[in] qspi the QSPI device to be de-initialised * * @return 0 : on success, EIO : if an error occurred */ int32_t hal_qspi_finalize(qspi_dev_t *qspi) { return 0; }
YifuLiu/AliOS-Things
hardware/chip/haas1000/hal/qspi.c
C
apache-2.0
2,228
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/hal/rng.h" /** * Fill in a memory buffer with random data * * @param[in] random the random device * @param[out] inBuffer Point to a valid memory buffer, this function will fill * in this memory with random numbers after executed * @param[in] inByteCount Length of the memory buffer (bytes) * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_random_num_read(random_dev_t random, void *buf, int32_t bytes) { return 0; }
YifuLiu/AliOS-Things
hardware/chip/haas1000/hal/rng.c
C
apache-2.0
586
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/hal/rtc.h" /** * 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) { 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) { 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) { 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) { return 0; }
YifuLiu/AliOS-Things
hardware/chip/haas1000/hal/rtc.c
C
apache-2.0
1,239
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <errno.h> #include "aos/hal/sd.h" #include "hal_sdmmc.h" #include "hal_iomux.h" #include "hal_iomux_haas1000.h" #include "hal_gpio.h" #include "hal_trace.h" static struct HAL_IOMUX_PIN_FUNCTION_MAP sd_pinmux[] = { {HAL_IOMUX_PIN_P1_2, HAL_IOMUX_FUNC_SDMMC_CMD, HAL_IOMUX_PIN_VOLTAGE_VIO, HAL_IOMUX_PIN_PULLUP_ENALBE}, {HAL_IOMUX_PIN_P1_3, HAL_IOMUX_FUNC_SDMMC_CLK, HAL_IOMUX_PIN_VOLTAGE_VIO, HAL_IOMUX_PIN_PULLUP_ENALBE}, {HAL_IOMUX_PIN_P1_4, HAL_IOMUX_FUNC_SDMMC_DATA0, HAL_IOMUX_PIN_VOLTAGE_VIO, HAL_IOMUX_PIN_PULLUP_ENALBE}, {HAL_IOMUX_PIN_P1_5, HAL_IOMUX_FUNC_SDMMC_DATA1, HAL_IOMUX_PIN_VOLTAGE_VIO, HAL_IOMUX_PIN_PULLUP_ENALBE}, {HAL_IOMUX_PIN_P1_0, HAL_IOMUX_FUNC_SDMMC_DATA2, HAL_IOMUX_PIN_VOLTAGE_VIO, HAL_IOMUX_PIN_PULLUP_ENALBE}, {HAL_IOMUX_PIN_P1_1, HAL_IOMUX_FUNC_SDMMC_DATA3, HAL_IOMUX_PIN_VOLTAGE_VIO, HAL_IOMUX_PIN_PULLUP_ENALBE}, }; static int sd_initialised = 0; /** * Initialises a sd interface * * @param[in] sd the interface which should be initialised * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_sd_init(sd_dev_t *sd) { int ret; hal_iomux_init((struct HAL_IOMUX_PIN_FUNCTION_MAP *)sd_pinmux, sizeof(sd_pinmux) / sizeof(struct HAL_IOMUX_PIN_FUNCTION_MAP)); ret = hal_sdmmc_open(HAL_SDMMC_ID_0); if (0 == ret) { sd_initialised = 1; if (sd) { sd->port = HAL_SDMMC_ID_0; sd->config.bus_wide = hal_sdmmc_get_bus_width(HAL_SDMMC_ID_0); sd->config.freq = hal_sdmmc_get_clock(HAL_SDMMC_ID_0); sd->priv = NULL; } } else { printf("sd init failed!\n"); } return ret; } /** * Read sd blocks * * @param[in] sd the interface which should be initialised * @param[out] data pointer to the buffer which will store incoming data * @param[in] blk_addr sd blk addr * @param[in] blks sd blks * @param[in] timeout timeout in milisecond * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_sd_blks_read(sd_dev_t *sd, uint8_t *data, uint32_t blk_addr, uint32_t blks, uint32_t timeout) { if (data == NULL || 0 == sd_initialised) return EIO; if(blks == hal_sdmmc_read_blocks(HAL_SDMMC_ID_0, blk_addr, blks, data)) { return 0; } else { printf("sd read blocks failed\n"); return EIO; } } /** * Write sd blocks * * @param[in] sd the interface which should be initialised * @param[in] data pointer to the buffer which will store incoming data * @param[in] blk_addr sd blk addr * @param[in] blks sd blks * @param[in] timeout timeout in milisecond * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_sd_blks_write(sd_dev_t *sd, uint8_t *data, uint32_t blk_addr, uint32_t blks, uint32_t timeout) { if (data == NULL || 0 == sd_initialised) return EIO; if(blks == hal_sdmmc_write_blocks(HAL_SDMMC_ID_0, blk_addr, blks, data)) { return 0; } else { printf("sd write blocks failed\n"); return EIO; } } /** * Erase sd blocks * * @param[in] sd the interface which should be initialised * @param[in] blk_start_addr sd blocks start addr * @param[in] blk_end_addr sd blocks end addr * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_sd_erase(sd_dev_t *sd, uint32_t blk_start_addr, uint32_t blk_end_addr) { return 0; } /** * Get sd state * * @param[in] sd the interface which should be initialised * @param[out] stat pointer to the buffer which will store incoming data * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_sd_stat_get(sd_dev_t *sd, hal_sd_stat *stat) { if(sd_initialised) *stat = SD_STAT_TRANSFER; else *stat = SD_STAT_RESET; return 0; } /** * Get sd info * * @param[in] sd the interface which should be initialised * @param[out] stat pointer to the buffer which will store incoming data * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_sd_info_get(sd_dev_t *sd, hal_sd_info_t *info) { if (info == NULL || 0 == sd_initialised) return EIO; uint32_t sector_count = 0; uint32_t sector_size = 0; hal_sdmmc_info(HAL_SDMMC_ID_0, &sector_count, &sector_size); info->blk_nums = sector_count; info->blk_size = sector_size; return 0; } /** * Deinitialises a sd interface * * @param[in] sd the interface which should be initialised * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_sd_finalize(sd_dev_t *sd) { if (0 == sd_initialised) return 0; hal_sdmmc_close(HAL_SDMMC_ID_0); sd_initialised = 0; return 0; }
YifuLiu/AliOS-Things
hardware/chip/haas1000/hal/sd.c
C
apache-2.0
4,712
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/hal/spi.h" #include "hal_iomux.h" #include "hal_spi.h" #include "hal_trace.h" #include "hal_gpio.h" #include "hal_iomux_haas1000.h" #include "hal_cache.h" #include "cmsis_os.h" #include "cmsis.h" #define SPI_DMA_MAX 4095 osSemaphoreDef(spi0_dma_semaphore); osSemaphoreDef(spi1_dma_semaphore); osMutexDef(spi0_mutex); osMutexDef(spi1_mutex); static void spi0_dma_irq(uint32_t error); static void spi1_dma_irq(uint32_t error); typedef struct { enum HAL_IOMUX_PIN_T spi_pin_DI0; enum HAL_IOMUX_PIN_T spi_pin_CLK; enum HAL_IOMUX_PIN_T spi_pin_CS0; enum HAL_IOMUX_PIN_T spi_pin_DIO; enum HAL_IOMUX_FUNCTION_T spi_fun_DI0; enum HAL_IOMUX_FUNCTION_T spi_fun_CLK; enum HAL_IOMUX_FUNCTION_T spi_fun_CS0; enum HAL_IOMUX_FUNCTION_T spi_fun_DIO; osSemaphoreId spi_dma_semaphore; osMutexId spi_mutex_id; int (*spi_open)(const struct HAL_SPI_CFG_T *cfg); int (*spi_dma_send)(const void *data, uint32_t len, HAL_SPI_DMA_HANDLER_T handler); int (*spi_dma_recv)(const void *cmd, void *data, uint32_t len, HAL_SPI_DMA_HANDLER_T handler); int (*spi_send)(const void *data, uint32_t len); int (*spi_recv)(const void *cmd, void *data, uint32_t len); void (*spi_dma_irq)(uint32_t error); int (*spi_close)(uint32_t cs); } spi_ctx_obj_t; static spi_ctx_obj_t spi_ctx[2] = { { .spi_pin_DI0 = HAL_IOMUX_PIN_P0_4, .spi_pin_CLK = HAL_IOMUX_PIN_P0_5, .spi_pin_CS0 = HAL_IOMUX_PIN_P0_6, .spi_pin_DIO = HAL_IOMUX_PIN_P0_7, .spi_fun_DI0 = HAL_IOMUX_FUNC_SPI_DI0, .spi_fun_CLK = HAL_IOMUX_FUNC_SPI_CLK, .spi_fun_CS0 = HAL_IOMUX_FUNC_AS_GPIO, .spi_fun_DIO = HAL_IOMUX_FUNC_SPI_DIO, .spi_dma_semaphore = NULL, .spi_mutex_id = 0, .spi_open = hal_spi_open, .spi_dma_send = hal_spi_dma_send, .spi_dma_recv = hal_spi_dma_recv, .spi_send = hal_spi_no_dma_send, .spi_recv = hal_spi_no_dma_recv, .spi_dma_irq = spi0_dma_irq, .spi_close = hal_spi_close }, { .spi_pin_DI0 = HAL_IOMUX_PIN_P3_4, .spi_pin_CLK = HAL_IOMUX_PIN_P3_7, .spi_pin_CS0 = HAL_IOMUX_PIN_P3_6, .spi_pin_DIO = HAL_IOMUX_PIN_P3_5, .spi_fun_DI0 = HAL_IOMUX_FUNC_SPILCD_DI0, .spi_fun_CLK = HAL_IOMUX_FUNC_SPILCD_CLK, .spi_fun_CS0 = HAL_IOMUX_FUNC_SPILCD_CS0, .spi_fun_DIO = HAL_IOMUX_FUNC_SPILCD_DIO, .spi_dma_semaphore = NULL, .spi_mutex_id = 0, .spi_open = hal_spilcd_open, .spi_dma_send = hal_spilcd_dma_send, .spi_dma_recv = hal_spilcd_dma_recv, .spi_send = hal_spilcd_send, .spi_recv = hal_spilcd_recv, .spi_dma_irq = spi1_dma_irq, .spi_close = hal_spilcd_close } }; /** * Initialises the SPI interface for a given SPI device * * @param[in] spi the spi device * * @return 0 : on success, EIO : if the SPI device could not be initialised */ int32_t hal_spi_init(spi_dev_t *spi) { int ret = -1; spi_config_t cfg_spi = spi->config; static struct HAL_IOMUX_PIN_FUNCTION_MAP pinmux_spi[] = { {0, 0, HAL_IOMUX_PIN_VOLTAGE_VIO, HAL_IOMUX_PIN_NOPULL}, {0, 0, HAL_IOMUX_PIN_VOLTAGE_VIO, HAL_IOMUX_PIN_NOPULL}, {0, 0, HAL_IOMUX_PIN_VOLTAGE_VIO, HAL_IOMUX_PIN_NOPULL}, {0, 0, HAL_IOMUX_PIN_VOLTAGE_VIO, HAL_IOMUX_PIN_NOPULL}, }; pinmux_spi[0].pin = spi_ctx[spi->port].spi_pin_DI0; pinmux_spi[1].pin = spi_ctx[spi->port].spi_pin_CLK; pinmux_spi[2].pin = spi_ctx[spi->port].spi_pin_CS0; pinmux_spi[3].pin = spi_ctx[spi->port].spi_pin_DIO; pinmux_spi[0].function = spi_ctx[spi->port].spi_fun_DI0; pinmux_spi[1].function = spi_ctx[spi->port].spi_fun_CLK; pinmux_spi[2].function = spi_ctx[spi->port].spi_fun_CS0; pinmux_spi[3].function = spi_ctx[spi->port].spi_fun_DIO; if (cfg_spi.freq > 26000000){ hal_iomux_set_io_driver(pinmux_spi[1].pin,3); hal_iomux_set_io_driver(pinmux_spi[3].pin,3); } hal_iomux_init(pinmux_spi, ARRAY_SIZE(pinmux_spi)); struct HAL_SPI_CFG_T spi_cfg; switch (cfg_spi.mode) { case SPI_WORK_MODE_0: spi_cfg.clk_delay_half = false; spi_cfg.clk_polarity = false; break; case SPI_WORK_MODE_1: spi_cfg.clk_delay_half = true; spi_cfg.clk_polarity = false; break; case SPI_WORK_MODE_2: spi_cfg.clk_delay_half = false; spi_cfg.clk_polarity = true; break; case SPI_WORK_MODE_3: spi_cfg.clk_delay_half = true; spi_cfg.clk_polarity = true; break; default: spi_cfg.clk_delay_half = true; spi_cfg.clk_polarity = true; } spi_cfg.slave = 0; if (cfg_spi.t_mode == SPI_TRANSFER_DMA) { spi_cfg.dma_rx = true; spi_cfg.dma_tx = true; } else { spi_cfg.dma_rx = false; spi_cfg.dma_tx = false; } spi_cfg.rate = cfg_spi.freq; //if (spi_cfg.rate > 26000000) //spi_cfg.rate = 26000000; spi_cfg.cs = 0; spi_cfg.rx_bits = cfg_spi.data_size; spi_cfg.tx_bits = cfg_spi.data_size; spi_cfg.rx_frame_bits = 0; ret = spi_ctx[spi->port].spi_open(&spi_cfg); if (ret != 0) { TRACE("spi %d open error", spi->port); return ret; } else { /*if cs use as gpio ,pull up at first*/ if (spi_ctx[spi->port].spi_fun_CS0 == HAL_IOMUX_FUNC_AS_GPIO) { hal_gpio_pin_set_dir(spi_ctx[spi->port].spi_pin_CS0, HAL_GPIO_DIR_OUT, 1); } TRACE("spi %d open succ", spi->port); } if (!spi_ctx[spi->port].spi_dma_semaphore) { if (spi->port == 0) { spi_ctx[spi->port].spi_dma_semaphore = osSemaphoreCreate(osSemaphore(spi0_dma_semaphore), 0); } else { spi_ctx[spi->port].spi_dma_semaphore = osSemaphoreCreate(osSemaphore(spi1_dma_semaphore), 0); } } if (!spi_ctx[spi->port].spi_dma_semaphore) { TRACE("spi0_dma_semaphore create failed!"); return -1; } if (!spi_ctx[spi->port].spi_mutex_id) { if (spi->port == 0) { spi_ctx[spi->port].spi_mutex_id = osMutexCreate((osMutex(spi0_mutex))); } else { spi_ctx[spi->port].spi_mutex_id = osMutexCreate((osMutex(spi1_mutex))); } } if (!spi_ctx[spi->port].spi_mutex_id) { TRACE("spi0_mutex create failed!"); return -1; } return ret; } void spi0_dma_irq(uint32_t error) { if (osOK != osSemaphoreRelease(spi_ctx[0].spi_dma_semaphore)) { TRACE("spi1dmairq osSemaphoreRelease failed!"); } } void spi1_dma_irq(uint32_t error) { if (osOK != osSemaphoreRelease(spi_ctx[1].spi_dma_semaphore)) { TRACE("spi0dmairq osSemaphoreRelease failed!"); } } /** * Spi send * * @param[in] spi the spi device * @param[in] data spi send data * @param[in] size spi send data size * @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 the SPI device could not be initialised */ #ifdef hal_spi_send #undef hal_spi_send #endif int32_t hal_spi_send(spi_dev_t *spi, const uint8_t *data, uint16_t size, uint32_t timeout) { int32_t ret = 0; uint32_t len = size; uint32_t i = 0; uint8_t *buf = data; osStatus status = osErrorOS; if (NULL == spi || NULL == data || 0 == size) { TRACE("spi input para err"); return -3; } status = osMutexWait(spi_ctx[spi->port].spi_mutex_id, osWaitForever); if (osOK != status) { TRACE("%s spi_mutex wait error = 0x%X!", __func__, status); return -2; } hal_cache_sync(HAL_CACHE_ID_D_CACHE); /*if cs use as gpio, pull down cs at first*/ if (spi_ctx[spi->port].spi_fun_CS0 == HAL_IOMUX_FUNC_AS_GPIO) { hal_gpio_pin_set_dir(spi_ctx[spi->port].spi_pin_CS0, HAL_GPIO_DIR_OUT, 0); } if (spi->config.t_mode == SPI_TRANSFER_DMA) { ret = spi_ctx[spi->port].spi_dma_send(buf, len, spi_ctx[spi->port].spi_dma_irq); if (osSemaphoreWait(spi_ctx[spi->port].spi_dma_semaphore, timeout) <= 0) { TRACE("spi dma tail send timeout"); goto OUT; } } else { ret = spi_ctx[spi->port].spi_send(buf, len); } if (ret) { TRACE("spi dma tail send fail %d, size %d", ret, len); goto OUT; } OUT: /*if cs use as gpio, pull pull up cs at the end*/ if (spi_ctx[spi->port].spi_fun_CS0 == HAL_IOMUX_FUNC_AS_GPIO) { hal_gpio_pin_set_dir(spi_ctx[spi->port].spi_pin_CS0, HAL_GPIO_DIR_OUT, 1); } osMutexRelease(spi_ctx[spi->port].spi_mutex_id); return ret; } #ifdef hal_spi_recv #undef hal_spi_recv #endif /** * spi_recv * * @param[in] spi the spi device * @param[out] data spi recv data * @param[in] size spi recv data size * @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 the SPI device could not be initialised */ int32_t hal_spi_recv(spi_dev_t *spi, uint8_t *data, uint16_t size, uint32_t timeout) { int32_t ret = 0; uint32_t len = size; uint32_t remainder = 0; osStatus status = osOK; uint8_t *cmd; if (NULL == spi || NULL == data || 0 == size) { TRACE("spi input para err"); return -3; } cmd = (uint8_t *)malloc(len); if (cmd == NULL) { TRACE("%s malloc size %d error\r", __FUNCTION__, len); return -1; } memset(cmd, 0, len); status = osMutexWait(spi_ctx[spi->port].spi_mutex_id, osWaitForever); if (osOK != status) { TRACE("%s spi_mutex wait error = 0x%X!", __func__, status); free(cmd); return -2; } hal_cache_sync(HAL_CACHE_ID_D_CACHE); //PSRAM must sync cache to memory when used dma /*if cs use as gpio, pull down cs at first*/ if (spi_ctx[spi->port].spi_fun_CS0 == HAL_IOMUX_FUNC_AS_GPIO) { hal_gpio_pin_set_dir(spi_ctx[spi->port].spi_pin_CS0, HAL_GPIO_DIR_OUT, 0); } do { remainder = len <= SPI_DMA_MAX ? len : SPI_DMA_MAX; //hal_cache_sync(HAL_CACHE_ID_I_CACHE);//PSRAM must sync cache to memory when used dma if (spi->config.t_mode == SPI_TRANSFER_DMA) { ret = spi_ctx[spi->port].spi_dma_recv(cmd, data, remainder, spi_ctx[spi->port].spi_dma_irq); if (osSemaphoreWait(spi_ctx[spi->port].spi_dma_semaphore, timeout) <= 0) { TRACE("SPI Read timeout!"); goto OUT; } } else { ret = spi_ctx[spi->port].spi_recv(cmd, data, remainder); } len -= remainder; data += remainder; if (ret) { TRACE("spi tail fail %d, size %d", ret, len); goto OUT; } } while (len); OUT: /*if cs use as gpio, pull pull up cs at the end*/ if (spi_ctx[spi->port].spi_fun_CS0 == HAL_IOMUX_FUNC_AS_GPIO) { hal_gpio_pin_set_dir(spi_ctx[spi->port].spi_pin_CS0, HAL_GPIO_DIR_OUT, 1); } osMutexRelease(spi_ctx[spi->port].spi_mutex_id); free(cmd); return ret; } //full duplex recev int32_t hal_spi_send_and_recv(spi_dev_t *spi, uint8_t *tx_data, uint16_t tx_size, uint8_t *rx_data, uint16_t rx_size, uint32_t timeout) { int32_t ret = 0; uint32_t len = rx_size; uint32_t offset = tx_size; uint32_t max_len = (len + offset) <= SPI_DMA_MAX ? (len + offset) : SPI_DMA_MAX; uint32_t remainder = 0; osStatus status = 0; uint8_t *cmd; if (NULL == spi || NULL == tx_data || 0 == tx_size || NULL == rx_data || 0 == rx_size) { TRACE("spi input para err"); return -3; } cmd = (uint8_t *)malloc(max_len); if (cmd == NULL) { TRACE("%s malloc size %d error\r", __FUNCTION__, max_len); return -1; } memset(cmd, 0, max_len); memcpy(cmd, tx_data, tx_size); status = osMutexWait(spi_ctx[spi->port].spi_mutex_id, osWaitForever); if (osOK != status) { TRACE("%s spi_mutex wait error = 0x%X!", __func__, status); free(cmd); return -2; } /*if cs use as gpio, pull down cs at first*/ if (spi_ctx[spi->port].spi_fun_CS0 == HAL_IOMUX_FUNC_AS_GPIO) { hal_gpio_pin_set_dir(spi_ctx[spi->port].spi_pin_CS0, HAL_GPIO_DIR_OUT, 0); } do { remainder = max_len; hal_cache_sync(HAL_CACHE_ID_D_CACHE); //PSRAM must sync cache to memory when used dma if (spi->config.t_mode == SPI_TRANSFER_DMA) { ret = spi_ctx[spi->port].spi_dma_recv(cmd, rx_data, remainder, spi_ctx[spi->port].spi_dma_irq); if (osSemaphoreWait(spi_ctx[spi->port].spi_dma_semaphore, 1000) <= 0) { TRACE("SPI Read timeout!"); goto OUT; } } else { ret = spi_ctx[spi->port].spi_recv(cmd, rx_data, remainder); } len -= (remainder - offset); rx_data += (remainder - offset); if (ret) { TRACE("spi dma tail fail %d", ret); goto OUT; } } while (len); OUT: /*if cs use as gpio, pull pull up cs at the end*/ if (spi_ctx[spi->port].spi_fun_CS0 == HAL_IOMUX_FUNC_AS_GPIO) { hal_gpio_pin_set_dir(spi_ctx[spi->port].spi_pin_CS0, HAL_GPIO_DIR_OUT, 1); } osMutexRelease(spi_ctx[spi->port].spi_mutex_id); free(cmd); return ret; } /** * spi send data and recv * * @param[in] spi the spi device * @param[in] tx_data spi send data * @param[in] rx_data spi recv data * @param[in] size spi data to be sent and recived * @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 the SPI device could not be initialised */ // Half duplex send+recv int32_t hal_spi_sends_recvs(spi_dev_t *spi, uint8_t *tx_data, uint16_t tx_size, uint8_t *rx_data, uint16_t rx_size, uint32_t timeout) { int ret = 0; uint32_t len = rx_size; uint32_t offset = 1; uint32_t i = 0; uint8_t *cmd; cmd = (uint8_t *)malloc(rx_size); if (cmd == NULL) { TRACE("%s malloc %d error", __FUNCTION__, rx_size); return -1; } for (size_t i = 0; i < len; i++) { cmd[i] = 0x00; } osStatus status = osMutexWait(spi_ctx[spi->port].spi_mutex_id, osWaitForever); if (osOK != status) { TRACE("%s spi_mutex wait error = 0x%X!", __func__, status); free(cmd); return -2; } /*if cs use as gpio, pull down cs at first*/ if (spi_ctx[spi->port].spi_fun_CS0 == HAL_IOMUX_FUNC_AS_GPIO) { hal_gpio_pin_set_dir(spi_ctx[spi->port].spi_pin_CS0, HAL_GPIO_DIR_OUT, 0); } hal_cache_sync(HAL_CACHE_ID_D_CACHE); //PSRAM must sync cache to memory when used dma if (spi->config.t_mode == SPI_TRANSFER_DMA) { ret = spi_ctx[spi->port].spi_dma_send(tx_data, tx_size, spi_ctx[spi->port].spi_dma_irq); if (osSemaphoreWait(spi_ctx[spi->port].spi_dma_semaphore, timeout) <= 0) { TRACE("spi dma tail send timeout"); goto OUT; } } else { spi_ctx[spi->port].spi_send(tx_data, tx_size); } do { uint32_t remainder = len <= SPI_DMA_MAX ? len : SPI_DMA_MAX; hal_cache_sync(HAL_CACHE_ID_I_CACHE);//PSRAM must sync cache to memory when used dma if (spi->config.t_mode == SPI_TRANSFER_DMA) { ret = spi_ctx[spi->port].spi_dma_recv(cmd, rx_data, remainder, spi_ctx[spi->port].spi_dma_irq); if (osSemaphoreWait(spi_ctx[spi->port].spi_dma_semaphore, timeout) <= 0) { TRACE("SPI Read timeout!"); goto OUT; } } else { ret = spi_ctx[spi->port].spi_recv(cmd, rx_data, remainder); } len -= remainder; rx_data += remainder; if (ret) { TRACE("spi tail fail %d, size %d", ret, len); goto OUT; } } while (len); OUT: /*if cs use as gpio, pull pull up cs at the end*/ if (spi_ctx[spi->port].spi_fun_CS0 == HAL_IOMUX_FUNC_AS_GPIO) { hal_gpio_pin_set_dir(spi_ctx[spi->port].spi_pin_CS0, HAL_GPIO_DIR_OUT, 1); } osMutexRelease(spi_ctx[spi->port].spi_mutex_id); free(cmd); return ret; } int32_t hal_spi_send_recv(spi_dev_t *spi, uint8_t *tx_data, uint8_t *rx_data, uint16_t rx_size, uint32_t timeout) { return hal_spi_sends_recvs(spi, tx_data, 1, rx_data, rx_size, timeout); } /** * spi send data and then send data * @param[in] spi the spi device * @param[in] tx1_data the first data to be sent * @param[in] tx1_size the first data size to be sent * @param[out] tx2_data the second data to be sent * @param[in] tx2_size the second data size to be sent * @param[in] timeout timeout in milisecond, set this value to HAL_WAIT_FOREVER * if you want to wait forever * * @return 0, on success, otherwise is error */ int32_t hal_spi_send_and_send(spi_dev_t *spi, uint8_t *tx1_data, uint16_t tx1_size, uint8_t *tx2_data, uint16_t tx2_size, uint32_t timeout) { //int spi_id = spi->port + 1; void *cmd = spi->priv; int ret = 0; ret = hal_spi_send(spi, tx1_data, tx1_size, timeout); if (!ret) { ret = hal_spi_send(spi, tx2_data, tx2_size, timeout); if (ret) { TRACE("spi send tx2_data fail %d, tx2_size %d", ret, tx2_size); } } else { TRACE("spi send tx1_data fail %d, tx1_size %d", ret, tx1_size); } return ret; } /** * De-initialises a SPI interface * * * @param[in] spi the SPI device to be de-initialised * * @return 0 : on success, EIO : if an error occurred */ int32_t hal_spi_finalize(spi_dev_t *spi) { int ret = 0; spi_config_t cfg_spi = spi->config; ret = spi_ctx[spi->port].spi_close(cfg_spi.cs); if (ret) { TRACE("hal_spi_finalize fail %d", ret); } return 0; }
YifuLiu/AliOS-Things
hardware/chip/haas1000/hal/spi.c
C
apache-2.0
16,444
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/hal/timer.h" #define IGNORE_HAL_TIMER_RAW_API_CHECK #include "hal_timer_raw.h" #define BES_HAL_DEBUG 0 #include "app_hal.h" #undef hal_timer_start #undef hal_timer_stop #include "hal_trace.h" static timer_dev_t _tim; static void oneshot_timer_handler(uint32_t elapsed) { TRACE("%s: elapsed=%d", __FUNCTION__, elapsed); _tim.config.cb(_tim.config.arg); } static void periodic_timer_handler(uint32_t elapsed) { TRACE("%s: elapsed=%d", __FUNCTION__, elapsed); _tim.config.cb(_tim.config.arg); } static void _hal_timer_stop(void) { hal_timer_stop_nickname(); } static int32_t _hal_timer_para_chg(timer_dev_t *tim, timer_config_t para) { int32_t ret = 0; enum HAL_TIMER_TYPE_T type = HAL_TIMER_TYPE_ONESHOT; HAL_TIMER_IRQ_HANDLER_T handler = oneshot_timer_handler; ENTER_FUNCTION(); memcpy(&_tim, tim, sizeof(timer_dev_t)); if (_tim.config.reload_mode == TIMER_RELOAD_AUTO) { type = HAL_TIMER_TYPE_PERIODIC; handler = periodic_timer_handler; } hal_timer_setup(type, handler); LEAVE_FUNCTION(); return 0; } /** * init a hardware timer * * @param[in] tim timer device * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_timer_init(timer_dev_t *tim) { int32_t ret = 0; ENTER_FUNCTION(); ret = _hal_timer_para_chg(tim, tim->config); LEAVE_FUNCTION(); return 0; } /** * start a hardware timer * * @param[in] tim timer device * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_timer_start(timer_dev_t *tim) { int32_t ret = 0; ENTER_FUNCTION(); hal_timer_start_nickname(US_TO_TICKS(tim->config.period)); LEAVE_FUNCTION(); return 0; } /** * stop a hardware timer * * @param[in] tim timer device * * @return none */ void hal_timer_stop(timer_dev_t *tim) { ENTER_FUNCTION(); _hal_timer_stop(); LEAVE_FUNCTION(); } /** * change the config of a hardware timer * * @param[in] tim timer device * @param[in] para timer config * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_timer_para_chg(timer_dev_t *tim, timer_config_t para) { int32_t ret = 0; ENTER_FUNCTION(); ret = _hal_timer_para_chg(tim, para); LEAVE_FUNCTION(); return 0; } /** * De-initialises an TIMER interface, Turns off an TIMER hardware interface * * @param[in] tim timer device * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_timer_finalize(timer_dev_t *tim) { int32_t ret = 0; ENTER_FUNCTION(); _hal_timer_stop(); LEAVE_FUNCTION(); return ret; } static void _hal_timer_test_cb(void *arg) { TRACEME("%s arg=0x%X\n", arg); } void _hal_timer_test() { uint32_t cur_ticks = hal_sys_timer_get(); uint32_t st; timer_dev_t tim = {0, {1000, TIMER_RELOAD_MANU, _hal_timer_test_cb, 100}, NULL}; hal_timer_init(&tim); hal_timer_start(&tim); krhino_task_sleep(3000); tim.config.period = 20; hal_timer_start(&tim); TRACEME("TIMER: oneshot start 20\n"); hal_timer_stop(&tim); hal_timer_finalize(&tim); tim.config.reload_mode = TIMER_RELOAD_AUTO; hal_timer_init(&tim); hal_timer_start(&tim); krhino_task_sleep(3000); tim.config.period = 20; hal_timer_start(&tim); krhino_task_sleep(30000); TRACEME("TIMER: oneshot start 20\n"); hal_timer_stop(&tim); hal_timer_finalize(&tim); }
YifuLiu/AliOS-Things
hardware/chip/haas1000/hal/timer.c
C
apache-2.0
3,538
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "cmsis.h" #include "cmsis_os.h" #define BES_HAL_DEBUG 0 #include "aos/kernel.h" #include "k_api.h" #include "app_hal.h" #include "aos/errno.h" #include "aos/hal/uart.h" #include "ulog/ulog.h" #include "hal_uart.h" #include "hal_trace.h" #include "plat_types.h" #define UART_FIFO_MAX_BUFFER 2048 #define UART_DMA_RING_BUFFER_SIZE 256// mast be 2^n static __SRAMBSS unsigned char _hal_uart_buf[UART_DMA_RING_BUFFER_SIZE]; static __SRAMBSS unsigned char _hal_uart1_buf[UART_DMA_RING_BUFFER_SIZE]; static __SRAMBSS unsigned char _hal_uart2_buf[UART_DMA_RING_BUFFER_SIZE]; typedef struct { uint32_t init_flag; uint8_t *uart_buffer; uint8_t *rx_ringbuf; int32_t rxring_size; int32_t rxbuf_in; int32_t rxbuf_out; ksem_t rx_sem; ksem_t tx_sem; ksem_t rx_irq_bottom_sem; kmutex_t rx_cb_mutex; uart_rx_cb rx_cb; uart_dev_t *rx_cb_arg; ktask_t *rx_irq_bottom_task; void (*uart_dma_rx_handler)(uint32_t xfer_size, int dma_error, union HAL_UART_IRQ_T status); void (*uart_dma_tx_handler)(uint32_t xfer_size, int dma_error); }uart_ctx_obj_t; static uart_ctx_obj_t uart_ctx[3] = {0}; struct HAL_UART_CFG_T low_uart_cfg = { // used for tgdb cli console .parity = HAL_UART_PARITY_NONE, .stop = HAL_UART_STOP_BITS_1, .data = HAL_UART_DATA_BITS_8, .flow = HAL_UART_FLOW_CONTROL_NONE, .tx_level = HAL_UART_FIFO_LEVEL_7_8, .rx_level = HAL_UART_FIFO_LEVEL_1_8, .baud = 0, .dma_rx = false, .dma_tx = false, .dma_rx_stop_on_err = false, }; static void hal_set_uart_iomux(uint32_t uart_id) { if (uart_id == HAL_UART_ID_0) { hal_iomux_set_uart0(); } else if (uart_id == HAL_UART_ID_1) { hal_iomux_set_uart1(); } else { hal_iomux_set_uart2(); } } static void hal_uart_rx_start(uint32_t uart_id) { struct HAL_DMA_DESC_T dma_desc_rx; unsigned int desc_cnt = 1; union HAL_UART_IRQ_T mask; mask.reg = 0; mask.BE = 0; mask.FE = 0; mask.OE = 0; mask.PE = 0; mask.RT = 1; hal_uart_dma_recv_mask(uart_id, uart_ctx[uart_id].uart_buffer, UART_DMA_RING_BUFFER_SIZE, &dma_desc_rx, &desc_cnt, &mask); } static int32_t _get_uart_ringbuf_freesize(uint32_t uart_id) { int32_t size = 0; /*if uart haven't init free size is zero*/ if (uart_ctx[uart_id].init_flag == 0) { return 0; } /*now input index equals output index means fifo empty*/ if (uart_ctx[uart_id].rxbuf_in == uart_ctx[uart_id].rxbuf_out) { size = uart_ctx[uart_id].rxring_size; } else if (uart_ctx[uart_id].rxbuf_in > uart_ctx[uart_id].rxbuf_out) { size = uart_ctx[uart_id].rxring_size - uart_ctx[uart_id].rxbuf_in + uart_ctx[uart_id].rxbuf_out; } else { size = uart_ctx[uart_id].rxbuf_out - uart_ctx[uart_id].rxbuf_in; } return size; } static int32_t _get_uart_ringbuf_available_read_size(uint32_t uart_id) { uint32_t size = 0; /*if uart haven't init free size is zero*/ if (uart_ctx[uart_id].init_flag == 0) { return 0; } size = uart_ctx[uart_id].rxring_size - _get_uart_ringbuf_freesize(uart_id); return size; } /*return value is push in data size */ static int32_t _uart_ringbuffer_push(uint32_t uart_id, uint8_t *buf, int32_t len) { int32_t free_size = 0; int32_t write_size = 0; int32_t spilt_len = 0; if (uart_id > HAL_UART_ID_2 || uart_ctx[uart_id].init_flag == 0) { return 0; } free_size = _get_uart_ringbuf_freesize(uart_id); /*get real read_size */ if (free_size > len) { write_size = len; } else { write_size = free_size; } if (write_size != 0 ) { spilt_len = uart_ctx[uart_id].rxring_size - uart_ctx[uart_id].rxbuf_in; if (spilt_len >= write_size) { memcpy(uart_ctx[uart_id].rx_ringbuf + uart_ctx[uart_id].rxbuf_in, buf, write_size); } else { memcpy(uart_ctx[uart_id].rx_ringbuf + uart_ctx[uart_id].rxbuf_in, buf, spilt_len); memcpy(uart_ctx[uart_id].rx_ringbuf, buf + spilt_len, write_size - spilt_len); } uart_ctx[uart_id].rxbuf_in = (uart_ctx[uart_id].rxbuf_in + write_size) % uart_ctx[uart_id].rxring_size; } return write_size; } /*return value is pop out data size */ static int32_t _uart_ringbuffer_pop(uint32_t uart_id, uint8_t *buf, int32_t len) { int32_t available_size = 0; int32_t read_size = 0; int32_t spilt_len = 0; if (uart_id > HAL_UART_ID_2 || uart_ctx[uart_id].init_flag == 0) { return 0; } available_size = _get_uart_ringbuf_available_read_size(uart_id); /*get real read_size */ if (available_size > len) { read_size = len; } else { read_size = available_size; } spilt_len = uart_ctx[uart_id].rxring_size - uart_ctx[uart_id].rxbuf_out; if (spilt_len >= read_size) { memcpy(buf, uart_ctx[uart_id].rx_ringbuf + uart_ctx[uart_id].rxbuf_out, read_size); } else { memcpy(buf, uart_ctx[uart_id].rx_ringbuf + uart_ctx[uart_id].rxbuf_out, spilt_len); memcpy(buf + spilt_len, uart_ctx[uart_id].rx_ringbuf, read_size - spilt_len); } uart_ctx[uart_id].rxbuf_out = (uart_ctx[uart_id].rxbuf_out + read_size) % uart_ctx[uart_id].rxring_size; return read_size; } extern void panicNmiInputFilter(uint8_t ch); static void _uart_dma_rx_handler(uint32_t xfer_size, int dma_error, union HAL_UART_IRQ_T status) { uint32_t len = 0; uint32_t uartid = 0; len = _uart_ringbuffer_push(uartid, uart_ctx[uartid].uart_buffer, xfer_size); if (len < xfer_size) { printf("%s ringbuf is full have %d need %d\r", __FUNCTION__, len, xfer_size); return; } memset(uart_ctx[uartid].uart_buffer, 0, UART_DMA_RING_BUFFER_SIZE); krhino_sem_give(&(uart_ctx[uartid].rx_sem)); krhino_sem_give(&(uart_ctx[uartid].rx_irq_bottom_sem)); hal_uart_rx_start(uartid); } static void _uart1_dma_rx_handler(uint32_t xfer_size, int dma_error, union HAL_UART_IRQ_T status) { uint32_t len = 0; uint32_t uartid = 1; len = _uart_ringbuffer_push(uartid, uart_ctx[uartid].uart_buffer, xfer_size); if (len < xfer_size) { printf("%s ringbuf is full have %d need %d\r", __FUNCTION__, len, xfer_size); return; } memset(uart_ctx[uartid].uart_buffer, 0, UART_DMA_RING_BUFFER_SIZE); krhino_sem_give(&(uart_ctx[uartid].rx_sem)); krhino_sem_give(&(uart_ctx[uartid].rx_irq_bottom_sem)); hal_uart_rx_start(uartid); } static void _uart1_dma_tx_handler(uint32_t xfer_size, int dma_error) { krhino_sem_give(&(uart_ctx[1].tx_sem)); } /*uart2*/ static void _uart2_dma_rx_handler(uint32_t xfer_size, int dma_error, union HAL_UART_IRQ_T status) { uint32_t len = 0; uint32_t uartid = 2; len = _uart_ringbuffer_push(uartid, uart_ctx[uartid].uart_buffer, xfer_size); if (len < xfer_size) { return; } memset(uart_ctx[uartid].uart_buffer, 0, UART_DMA_RING_BUFFER_SIZE); krhino_sem_give(&(uart_ctx[uartid].rx_sem)); krhino_sem_give(&(uart_ctx[uartid].rx_irq_bottom_sem)); hal_uart_rx_start(uartid); } static void _uart2_dma_tx_handler(uint32_t xfer_size, int dma_error) { krhino_sem_give(&(uart_ctx[2].tx_sem)); } static void rx_irq_bottom(void *arg) { uart_ctx_obj_t *uart_ctx = arg; while (1) { krhino_sem_take(&uart_ctx->rx_irq_bottom_sem, RHINO_WAIT_FOREVER); krhino_mutex_lock(&uart_ctx->rx_cb_mutex, RHINO_WAIT_FOREVER); if (uart_ctx->rx_cb) uart_ctx->rx_cb(uart_ctx->rx_cb_arg); krhino_mutex_unlock(&uart_ctx->rx_cb_mutex); } } static int panic_uart_open = 0; extern int32_t g_cli_direct_read; int32_t hal_panic_uart_open(void) { enum HAL_UART_ID_T uart_id = hal_trace_get_id(); TRACE_FLUSH(); hal_uart_close(uart_id); low_uart_cfg.baud = hal_trace_get_baudrate(); hal_uart_open(uart_id, &low_uart_cfg); panic_uart_open = 1; g_cli_direct_read = 1; 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) { int32_t ret = 0; uint32_t trace_port = hal_trace_get_id(); enum HAL_UART_ID_T uart_id; struct HAL_UART_CFG_T uart_cfg = {0}; if(NULL == uart || uart->port > HAL_UART_ID_2) { return EIO; } uart_id = uart->port; if (uart_ctx[uart_id].init_flag) { /*have already inited*/ return EIO; } if (uart_id == 0) { uart_ctx[uart_id].uart_dma_rx_handler = _uart_dma_rx_handler; uart_ctx[uart_id].uart_buffer = _hal_uart_buf; } if (uart_id == HAL_UART_ID_1) { uart_ctx[uart_id].uart_dma_rx_handler = _uart1_dma_rx_handler; uart_ctx[uart_id].uart_dma_tx_handler = _uart1_dma_tx_handler; uart_ctx[uart_id].uart_buffer = _hal_uart1_buf; } if (uart_id == HAL_UART_ID_2) { uart_ctx[uart_id].uart_dma_rx_handler = _uart2_dma_rx_handler; uart_ctx[uart_id].uart_dma_tx_handler = _uart2_dma_tx_handler; uart_ctx[uart_id].uart_buffer = _hal_uart2_buf; } memset(uart_ctx[uart_id].uart_buffer, 0, UART_DMA_RING_BUFFER_SIZE); uart_cfg.baud = uart->config.baud_rate; uart_cfg.parity = uart->config.parity; uart_cfg.stop = uart->config.stop_bits; uart_cfg.data = uart->config.data_width; uart_cfg.flow = uart->config.flow_control; uart_cfg.tx_level = HAL_UART_FIFO_LEVEL_1_2; uart_cfg.rx_level = HAL_UART_FIFO_LEVEL_1_2; uart_cfg.dma_rx = true; uart_cfg.dma_tx = true; uart_cfg.dma_rx_stop_on_err = false; /*means it have already opened*/ if (uart_id == trace_port) { hal_uart_close(uart_id); ret = hal_uart_open(uart_id, &uart_cfg); } else { ret = hal_uart_open(uart_id, &uart_cfg); } if (ret) { printf("%s %d trace port %d uart %d open fail ret %d\r\n", __FILE__, __LINE__, trace_port, uart_id, ret); return EIO; } hal_set_uart_iomux(uart_id); /*rx fifo buffer, for now fix length 2048*/ uart_ctx[uart_id].rx_ringbuf = aos_malloc(UART_FIFO_MAX_BUFFER); if (NULL == uart_ctx[uart_id].rx_ringbuf) { printf("%s %d uart %d fail to malloc rx fifo buffer\r\n", __FILE__, __LINE__, uart_id); return EIO; } uart_ctx[uart_id].rxring_size = UART_FIFO_MAX_BUFFER; uart_ctx[uart_id].rxbuf_in = 0; uart_ctx[uart_id].rxbuf_out = 0; memset(uart_ctx[uart_id].rx_ringbuf, 0, UART_FIFO_MAX_BUFFER); ret = krhino_sem_create(&uart_ctx[uart_id].rx_sem, "aos", 0); if (ret != RHINO_SUCCESS) { aos_free(uart_ctx[uart_id].rx_ringbuf); return EIO; } ret = krhino_sem_create(&uart_ctx[uart_id].tx_sem, "aos", 0); if (ret != RHINO_SUCCESS) { aos_free(uart_ctx[uart_id].rx_ringbuf); krhino_sem_del(&uart_ctx[uart_id].rx_sem); return EIO; } ret = krhino_sem_create(&uart_ctx[uart_id].rx_irq_bottom_sem, "aos", 0); if (ret != RHINO_SUCCESS) { aos_free(uart_ctx[uart_id].rx_ringbuf); krhino_sem_del(&uart_ctx[uart_id].tx_sem); krhino_sem_del(&uart_ctx[uart_id].rx_sem); return EIO; } ret = krhino_mutex_create(&uart_ctx[uart_id].rx_cb_mutex, "uart_rx_cb"); if (ret != RHINO_SUCCESS) { aos_free(uart_ctx[uart_id].rx_ringbuf); krhino_sem_del(&uart_ctx[uart_id].tx_sem); krhino_sem_del(&uart_ctx[uart_id].rx_sem); krhino_sem_del(&uart_ctx[uart_id].rx_irq_bottom_sem); return EIO; } uart_ctx[uart_id].rx_cb = NULL; uart_ctx[uart_id].rx_cb_arg = NULL; ret = krhino_task_dyn_create(&uart_ctx[uart_id].rx_irq_bottom_task, "uart_rx_irq_bottom", &uart_ctx[uart_id], 20, 0, 1024, rx_irq_bottom, 1); if (ret != RHINO_SUCCESS) { aos_free(uart_ctx[uart_id].rx_ringbuf); krhino_sem_del(&uart_ctx[uart_id].tx_sem); krhino_sem_del(&uart_ctx[uart_id].rx_sem); krhino_sem_del(&uart_ctx[uart_id].rx_irq_bottom_sem); krhino_mutex_del(&uart_ctx[uart_id].rx_cb_mutex); return EIO; } uart_ctx[uart_id].init_flag = 1; hal_uart_irq_set_dma_handler(uart_id, uart_ctx[uart_id].uart_dma_rx_handler, uart_ctx[uart_id].uart_dma_tx_handler, NULL); hal_uart_rx_start(uart_id); return 0; } int32_t hal_uart_any(uart_dev_t *uart) { /*if uart haven't init free size is zero*/ if (uart_ctx[uart->port].init_flag == 0) { return 0; } return uart_ctx[uart->port].rxring_size - _get_uart_ringbuf_freesize(uart->port); } /** * 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) { int32_t ret = EIO; uint8_t uart_id; if (NULL == uart || NULL == data || 0 == size) { printf("%s %d Invalid input \r\n", __FILE__, __LINE__); return ret; } uart_id = uart->port; if (uart_id > HAL_UART_ID_2) { printf("%s %d Invalid input \r\n", __FILE__, __LINE__); return ret; } if (uart_ctx[uart_id].init_flag == 0) { printf("%s %d uart %d haven't init yet \r\n", __FILE__, __LINE__, uart_id); return ret; } if (uart_id == hal_trace_get_id()) { if (panic_uart_open) { for (int i = 0; i < size; i++) hal_uart_blocked_putc(uart_id, *((char *)data + i)); } else { hal_trace_output_block(data, size); } } else { hal_uart_dma_send_sync_cache(uart_id, data, size, NULL, NULL); krhino_sem_take(&uart_ctx[uart_id].tx_sem, krhino_ms_to_ticks(timeout)); } 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[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(uart_dev_t *uart, void *data, uint32_t expect_size, uint32_t timeout) { printf("%s %d is a stub function \r\n", __FILE__, __LINE__); return EIO; } /** * 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) { int32_t ret = EIO; uint8_t uart_id = 0; tick_t begin_time =0; tick_t now_time = 0; uint32_t fifo_pop_len = 0; uint32_t recved_len = 0; uint32_t expect_len = expect_size; if (NULL == uart || NULL == data || expect_size == 0) { printf("%s %d Invalid input \r\n", __FILE__, __LINE__); return ret; } uart_id = uart->port; if (uart_id > HAL_UART_ID_2) { printf("%s %d Invalid input \r\n", __FILE__, __LINE__); return ret; } if (uart_ctx[uart_id].init_flag == 0) { printf("%s %d uart %d haven't init yet \r\n", __FILE__, __LINE__, uart_id); return ret; } begin_time = krhino_sys_tick_get(); do { fifo_pop_len = _uart_ringbuffer_pop(uart_id, (uint8_t *)data + recved_len, expect_len); recved_len += fifo_pop_len; expect_len -= fifo_pop_len; if (recved_len >= expect_size) { break; } /*if reaches here, it means need to wait for more data come*/ krhino_sem_take(&uart_ctx[uart_id].rx_sem, krhino_ms_to_ticks(timeout)); /*time out break*/ now_time = krhino_sys_tick_get(); if((uint32_t)(now_time - begin_time) >= timeout){ break; } } while (1); if (recv_size != NULL) { *recv_size = recved_len; } return 0; } /** * release sem for uart rx port * * @param[in] uartid index of uart * * @return 0 : on success, Others : if an error occurred with any step */ kstat_t hal_uart_rx_sem_give(int uartid) { return krhino_sem_give(&(uart_ctx[uartid].rx_sem)); } /** * take sem for uart rx port * * @param[in] uartid index of uart * @param[in] timeout timeout in milisecond, set this value to HAL_WAIT_FOREVER * if you want to wait forever * * @return 0 : on success, Others : if an error occurred with any step */ kstat_t hal_uart_rx_sem_take(int uartid, int timeout) { return krhino_sem_take(&uart_ctx[uartid].rx_sem, krhino_ms_to_ticks(timeout)); } /** * 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) { int32_t ret = EIO; uint8_t uart_id; if (NULL == uart) { printf("%s %d Invalid input \r\n", __FILE__, __LINE__); return ret; } uart_id = uart->port; if (uart_id > HAL_UART_ID_2) { printf("%s %d Invalid input \r\n", __FILE__, __LINE__); return ret; } if (uart_ctx[uart_id].init_flag == 0) { return 0; } if (uart_id == hal_trace_get_id()) { //hal_uart_close(uart->port); printf("do nothings since we need uart!\n"); return 0; } hal_uart_close(uart->port); aos_free(uart_ctx[uart_id].rx_ringbuf); krhino_sem_del(&uart_ctx[uart_id].rx_sem); krhino_sem_del(&uart_ctx[uart_id].tx_sem); krhino_task_dyn_del(uart_ctx[uart_id].rx_irq_bottom_task); uart_ctx[uart_id].rx_irq_bottom_task = NULL; krhino_sem_del(&uart_ctx[uart_id].rx_irq_bottom_sem); krhino_mutex_del(&uart_ctx[uart_id].rx_cb_mutex); uart_ctx[uart_id].rx_cb = NULL; uart_ctx[uart_id].rx_cb_arg = NULL; memset(&uart_ctx[uart_id], 0, sizeof(uart_ctx_obj_t)); ret = 0; return ret; } int32_t hal_uart_recv_cb_reg(uart_dev_t *uart, uart_rx_cb cb) { int id; if (!uart || uart->port > HAL_UART_ID_2) return -1; id = uart->port; krhino_mutex_lock(&uart_ctx[id].rx_cb_mutex, RHINO_WAIT_FOREVER); uart_ctx[id].rx_cb = cb; uart_ctx[id].rx_cb_arg = cb ? uart : NULL; krhino_mutex_unlock(&uart_ctx[id].rx_cb_mutex); return 0; }
YifuLiu/AliOS-Things
hardware/chip/haas1000/hal/uart.c
C
apache-2.0
19,240
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/hal/usbd.h" /* Initialization */ /******************************************************************************************/ /** * @brief Initialize usb device driver * * @param[in] pdev point to usb device handler * * @return the operation status, USBD_OK is OK, USBD_BUSY is BUSY, others is error */ usbd_stat_t usbd_hal_init(void *pdev) { return 0; } /** * @brief Deinitialize usb device driver * * @param[in] pdev point to usb device handler * * @return the operation status, USBD_OK is OK, USBD_BUSY is BUSY, others is error */ usbd_stat_t usbd_hal_deinit(void *pdev) { return 0; } /** * @brief enable usb device driver * * @param[in] pdev point to usb device handler * * @return the operation status, USBD_OK is OK, USBD_BUSY is BUSY, others is error */ usbd_stat_t usbd_hal_start(void *pdev) { return 0; } /** * @brief disable usb device driver * * @param[in] pdev point to usb device handler * * @return the operation status, USBD_OK is OK, USBD_BUSY is BUSY, others is error */ usbd_stat_t usbd_hal_stop(void *pdev) { return 0; } /** * @brief enable usb device interrupt */ void usbd_hal_connect(void) { return 0; } /** * @brief disable usb device interrupt */ void usbd_hal_disconnect(void) { return 0; } /** * @brief configure usb device info */ void usbd_hal_configure_device(void) { return 0; } /** * @brief unconfigure usb device info */ void usbd_hal_unconfigure_device(void) { return 0; } /** * @brief unconfigure usb device info * * @param[in] pdev point to usb device handler * @param[in] address the usb device address * * @return none */ void usbd_hal_set_address(void *pdev, uint8_t address) { return 0; } /* Endpoint 0 */ /******************************************************************************************/ /** * @brief Endpoint0 setup(read setup packet) * * @param[in] buffer point to usb device handler * * @return none */ void usbd_hal_ep0_setup(uint8_t *buffer) { return 0; } /** * @brief Endpoint0 read packet * * @param[in] pdev point to usb device handler * * @return none */ void usbd_hal_ep0_read(void *pdev) { return 0; } /** * @brief Endpoint0 read stage */ void usbd_hal_ep0_read_stage(void) { return 0; } /** * @brief Endpoint0 get read result * * @param[in] pdev point to usb device handler * @param[in] buffer point to packet * * @return the length of read packet */ uint32_t usbd_hal_get_ep0_read_result(void *pdev, uint8_t *buffer) { return 0; } /** * @brief Endpoint0 write * * @param[in] pdev point to usb device handler * @param[in] buffer point to packet * @param[in] size the length of write packet * * @return none */ void usbd_hal_ep0_write(void *pdev, uint8_t *buffer, uint32_t size) { return 0; } /** * @brief Get endpoint0 write result */ void usbd_hal_get_ep0_write_result(void) { return 0; } /** * @brief Stall endpoint0 * * @param[in] pdev point to usb device handler * * @return none */ void usbd_hal_ep0_stall(void *pdev) { return 0; } /* Other endpoints */ /******************************************************************************************/ /** * @brief open the endpoint * * @param[in] pdev point to usb device handler * @param[in] endpoint the num of endpoint * @param[in] maxPacket the max size of packet * @param[in] flags options flags for configuring endpoints * * @return true is ok, false is false */ bool usbd_hal_realise_endpoint(void *pdev, uint8_t endpoint, uint32_t maxPacket, uint32_t flags) { return 0; } /** * @brief start read the endpoint data * * @param[in] pdev point to usb device handler * @param[in] endpoint the num of endpoint * @param[in] maximumSize amount of data to be received * * @return endpoint status */ ep_status usbd_hal_endpoint_read(void *pdev, uint8_t endpoint, uint32_t maximumSize) { return 0; } /** * @brief read the endpoint data * * @param[in] pdev point to usb device handler * @param[in] endpoint the num of endpoint * @param[in] data point to receive buffer * @param[in] bytesRead amount of data be received * * @return endpoint status */ ep_status usbd_hal_endpoint_read_result(void *pdev, uint8_t endpoint, uint8_t *data, uint32_t *bytesRead) { return 0; } /** * @brief start write the endpoint data * * @param[in] pdev point to usb device handler * @param[in] endpoint the num of endpoint * @param[in] data point to write buffer * @param[in] size amount of data to be write * * @return endpoint status */ ep_status usbd_hal_endpoint_write(void *pdev, uint8_t endpoint, uint8_t *data, uint32_t size) { return 0; } /** * @brief write the endpoint data * * @param[in] pdev point to usb device handler * @param[in] endpoint the num of endpoint * * @return endpoint status */ ep_status usbd_hal_endpoint_write_result(void *pdev, uint8_t endpoint) { return 0; } /** * @brief stall the endpoint * * @param[in] pdev point to usb device handler * @param[in] endpoint the num of endpoint * * @return none */ void usbd_hal_stall_endpoint(void *pdev, uint8_t endpoint) { return 0; } /** * @brief unstall the endpoint * * @param[in] pdev point to usb device handler * @param[in] endpoint the num of endpoint * * @return none */ void usbd_hal_unstall_endpoint(void *pdev, uint8_t endpoint) { return 0; } /** * @brief get the endpoint status of stall * * @param[in] pdev point to usb device handler * @param[in] endpoint the num of endpoint * * @return true is ok, false is false */ bool usbd_hal_get_endpoint_stall_state(void *pdev, uint8_t endpoint) { return 0; }
YifuLiu/AliOS-Things
hardware/chip/haas1000/hal/usbd.c
C
apache-2.0
5,784
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/hal/usbh.h" /** * @brief Initialize The USB Host Controller * * @param[in] phost pointer to the usb host handler * @param[in] phcd pointer to the usb hcd pointer * * @return 0:success, otherwise is failed */ int hal_usbh_init(void *phost, void **phcd) { return 0; } /** * @brief Finalize The USB Host Controller * * @param[in] hcd pointer to the usb hcd * * @return 0:success, otherwise is failed */ int hal_usbh_finalize(void *hcd) { return 0; } /** * @brief Reset Host Controller's Port * * @param[in] hcd pointer to the usb hcd * * @return 0:success, otherwise is failed */ int hal_usbh_port_reset(void *hcd) { return 0; } /** * @brief Get Device Speed * * @param[in] hcd pointer to the usb hcd * * @return the usb host controller's speed (0, 1, 2) */ int hal_usbh_get_speed(void *hcd) { return 0; } /** * @brief Free The Host Controll's Pipe * * @param[in] hcd pointer to the usb hcd * @param[in] pipe_num the index of the pipe * * @return 0:success, otherwise is failed */ int hal_usbh_pipe_free(void *hcd, uint8_t pipe_num) { return 0; } /** * @brief Configure The Host Controller's Pipe * * @param[in] hcd pointer to the usb hcd * @param[in] index the index of the pipe * @param[in] ep_addr the endpoint address * @param[in] dev_addr the device address * @param[in] speed the device speed * @param[in] token the transmit token * @param[in] ep_type the endpoint type * @param[in] mps the max packet size * * @return 0:success, otherwise is failed */ int hal_usbh_pipe_configure(void *hcd, uint8_t index, uint8_t ep_addr, uint8_t dev_addr, uint8_t speed, uint8_t ep_type, uint16_t mps) { return 0; } /** * @brief Submit The Urb * * @param[in] hcd pointer to the usb hcd * @param[in] pipe_num the index of the pipe * @param[in] direction the transmit direction * @param[in] ep_type the endpoint type * @param[in] token the transmit token * @param[in/out] buf pointer to the buffer which will be send or recv * @param[in] length the length of buffer * * @return 0:success, otherwise is failed */ int hal_usbh_submit_urb(void *hcd, uint8_t pipe_num, uint8_t direction, uint8_t ep_type, uint8_t token, uint8_t *buf, uint16_t length) { return 0; } /** * @brief Get The Urb Transmit State * * @param[in] hcd pointer to the usb hcd * @param[in] pipe_num the index of the pipe * * @return 0:Idle, 1:Done, 2:Not Ready, 3:Nyet, 4:Error, 5:Stall */ int hal_usbh_get_urb_state(void *hcd, uint8_t pipe_num) { return 0; }
YifuLiu/AliOS-Things
hardware/chip/haas1000/hal/usbh.c
C
apache-2.0
2,752
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/hal/wdg.h" #include "watchdog.h" /** * This function will initialize the on board CPU hardware watch dog * * @param[in] wdg the watch dog device * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_wdg_init(wdg_dev_t *wdg) { return 0; } /** * Reload watchdog counter. * * @param[in] wdg the watch dog device */ void hal_wdg_reload(wdg_dev_t *wdg) { watchdog_feeddog_user(); return; } /** * This function performs any platform-specific cleanup needed for hardware watch dog. * * @param[in] wdg the watch dog device * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_wdg_finalize(wdg_dev_t *wdg) { watchdog_stopfeed(); return 0; }
YifuLiu/AliOS-Things
hardware/chip/haas1000/hal/wdg.c
C
apache-2.0
817
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <drivers/u_ld.h> #include <vfsdev/wifi_dev.h> #if(AOS_COMP_USERVICE > 0) #include <uservice/uservice.h> #include <uservice/eventid.h> #endif #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" #include <aos/kernel.h> #include <errno.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; /*wifi is connecting*/ volatile uint8_t connecting: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; static aos_sem_t wifi_connect_sem; 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 = aos_sem_create(&wifi_connect_sem, 1, 0); if (ret) { printf("%s:%d: aos_sem_create ret:%d\n", __func__, __LINE__, ret); return -1; } 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) { aos_sem_free(&wifi_connect_sem); 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; aos_sem_wait(&wifi_connect_sem, AOS_WAIT_FOREVER); 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); event_publish(EVENT_WIFI_HANDSHAKE_FAILED, NULL); #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(); wifi_status.connecting = 0; aos_sem_signal(&wifi_connect_sem); } 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; event_publish(EVENT_WIFI_AP_UP, wifi_get_netif(wifi_status.dev, WIFI_MODE_AP)); #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; event_publish(EVENT_WIFI_AP_DOWN, NULL); #endif return 0; } __SRAMDATA osThreadDef(wifi_connect_task, osPriorityNormal, 1, (4096), "wifi_connect"); static int haas1000_wifi_connect(netdev_t *dev, wifi_config_t* config) { aos_status_t ret; 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_connect_task use the static stack space, only 1 instance can run.*/ if (wifi_status.connecting) { printf("%s:%d: wifi is connecting, please try again later.\n", __func__, __LINE__); return -1; } 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; } strncpy(init_config_ptr->ssid, config->ssid, sizeof(init_config_ptr->ssid)-1); strncpy(init_config_ptr->password, config->password, sizeof(init_config_ptr->password)-1); /* Serialize this task and wifi_connect_task. */ ret = aos_sem_wait(&wifi_connect_sem, 100); if (ret != 0) { printf("%s:%d: wifi_connect_task is running, please try again later.\n", __func__, __LINE__); aos_free(init_config_ptr); return -1; } if (osThreadCreate(osThread(wifi_connect_task), init_config_ptr) == NULL) { printf("Failed to create wifi_connect_task\n"); aos_free(init_config_ptr); aos_sem_signal(&wifi_connect_sem); return -1; } wifi_status.connecting = 1; aos_sem_signal(&wifi_connect_sem); } else if (config->mode == WIFI_MODE_AP) { return start_ap(dev, config->ssid, config->password, config->ap_config.beacon_interval, config->ap_config.hide_ssid); } 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 int ret; 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); ret = inet_aton(in_net_para->ip, &ip.ip); if (!ret) { printf("%s:%d: invalid ip address %s\n", __func__, __LINE__, in_net_para->ip); return -1; } ret = inet_aton(in_net_para->mask, &ip.netmask); if (!ret) { printf("%s:%d: invalid network mask %s\n", __func__, __LINE__, in_net_para->mask); return -1; } ret = inet_aton(in_net_para->gate, &ip.gw); if (!ret) { printf("%s:%d: invalid gateway address %s\n", __func__, __LINE__, in_net_para->gate); return -1; } 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 = NULL, *prev_scan_ssid = NULL; struct bwifi_scan_config scan_config = {0}; struct bwifi_bss_info *scan_result = NULL; 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}; int scan_req_num = 0; int scan_req_ap_list_size = 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; /* Check again to make sure ap_list array doesn't overrun, and make static analysis happy. */ scan_req_ap_list_size = sizeof(wifi_status.scan_req.ap_list) / sizeof(wifi_status.scan_req.ap_list[0]); scan_req_num = wifi_status.scan_req.ap_num > scan_req_ap_list_size ? scan_req_ap_list_size : wifi_status.scan_req.ap_num; for (i = 0; i < scan_req_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 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) { return vfs_wifi_dev_register(&haas1000_wifi_driver, 0); } VFS_DRIVER_ENTRY(haas1000_wifi_register)
YifuLiu/AliOS-Things
hardware/chip/haas1000/hal/wifi_port.c
C
apache-2.0
25,309
#!/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) 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_haas1000 """ 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_haas1000' not in configs: configs['chip_haas1000'] = {} if 'serialport' not in configs['chip_haas1000']: configs['chip_haas1000']['serialport'] = "" if 'baudrate' not in configs['chip_haas1000']: configs['chip_haas1000']['baudrate'] = "1500000" if 'binfile' not in configs['chip_haas1000']: configs['chip_haas1000']['binfile'] = [] return configs['chip_haas1000'] def save_config(config): """ save configuration to .config_burn file, only update chip_haas1000 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_haas1000'] = 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] 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/haas1000/release/aos_burn_tool/flash_program.py
Python
apache-2.0
4,144
#!/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'1', 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'1', 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'2ndboot cli menu', 5) 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/haas1000/release/aos_burn_tool/flash_program_ll.py
Python
apache-2.0
6,928
#! /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 / 1024) self._last_valid_packets_size = data_size % 1024 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 / 1024) self._last_valid_packets_size = data_size % 1024 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 = 1024 # [<<< 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 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) + " 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 # 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 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/haas1000/release/aos_burn_tool/ymodem.py
Python
apache-2.0
18,742
#! /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 haas1000_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.bin")) cmd_str = "\"%s\" -f --lzma2=dict=32KiB --check=crc32 -k %s" % (os.path.abspath(path), os.path.join(bin_path, "ota_rtos_ota.bin")) os.system(cmd_str) cmd_str = "python ota_gen_md5_bin.py \"%s\" -m %s" % (os.path.join(bin_path, "ota_rtos_ota.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.bin.xz"), magic) os.system(cmd_str) print("run external script success")
YifuLiu/AliOS-Things
hardware/chip/haas1000/release/auto_build_tool/build_bin.py
Python
apache-2.0
2,265
EXTRA_POST_BUILD_TARGETS += gen_2ndboot_images MODULE_LIB_PATH = out/$(APP_FULL)@$(PLATFORM)/libraries/ DST_LIB_PATH = ./$($(HOST_MCU_FAMILY)_LOCATION)/drivers/tests/ota_boot_secboot/lib/ gen_2ndboot_images: echo "gen 2ndboot image" cp $(MODULE_LIB_PATH)/mcu_haas1000.a $(DST_LIB_PATH)/mcu_haas1000.a cp $(MODULE_LIB_PATH)/board_haas100.a $(DST_LIB_PATH)/board_haas100.a cp $(MODULE_LIB_PATH)/ota_2ndboot.a $(DST_LIB_PATH)/ota_2ndboot.a cp $(MODULE_LIB_PATH)/ota_updater.a $(DST_LIB_PATH)/ota_updater.a cd ./$($(HOST_MCU_FAMILY)_LOCATION)/drivers && . ./build2boot.sh
YifuLiu/AliOS-Things
hardware/chip/haas1000/release/auto_build_tool/haas1000_2ndboot_genbin.mk
Makefile
apache-2.0
578
#!/usr/bin/python # -*- coding: utf-8 -*- #本文件位于\AliOS-Things\platform\mcu\haas1000\release\auto_build_tool文件夹下 #本文件用于适配python3.x版本,在3.7.3版本下测试通过。其他版本未测试。 #修改本文件的目的是解决3.x版本下,使用aos make命令编译固件时发生的两个错误 #第一个错误是“missing parentheses in call to 'print'” #第二个错误是“module ‘string’ has no attribute 'find'" #与阿里云提供的haashaas1000_genbin.py原版相比,本文件一共修改了4处,详见注释。 #花生,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 = {} 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 # print " %s" % (line) 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] # print "para_key %s" % para_key # print "para_val %s" % para_val 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也是相同处理方式 print ("format wrong") 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 True: 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 True: 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 True: 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/ if True: 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/haas1000/release/auto_build_tool/haas1000_genbin.py
Python
apache-2.0
17,324
.\mklittlefs.exe -c ..\\..\\prebuild\\data\\ -d 5 -b 4096 -p 1198 -s 4907008 ..\\..\\prebuild\\littlefs.bin
YifuLiu/AliOS-Things
hardware/chip/haas1000/release/auto_build_tool/haas1000_genfs.bat
Batchfile
apache-2.0
107
#!/usr/bin/env bash if [ "$(uname)" = "Darwin" ]; then ./mklittlefs_osx -c ../../prebuild/data/ -d 5 -b 4096 -p 1198 -s 4907008 ../../prebuild/littlefs.bin elif [ "$(expr substr $(uname -s) 1 5)" = "Linux" ]; then ./mklittlefs_linux -c ../../prebuild/data/ -d 5 -b 4096 -p 1198 -s 4907008 ../../prebuild/littlefs.bin elif [ "$(expr substr $(uname -s) 1 10)" = "MINGW32_NT" ]; then echo fi
YifuLiu/AliOS-Things
hardware/chip/haas1000/release/auto_build_tool/haas1000_genfs.sh
Shell
apache-2.0
394
EXTRA_POST_BUILD_TARGETS += gen_mklitlefs_data GEN_MK_DATA_FILE:= haas1000_genfs.sh gen_mklitlefs_data: echo "make littlefs" cd ./$($(HOST_MCU_FAMILY)_LOCATION)release/auto_build_tool/ && ./$(GEN_MK_DATA_FILE) echo "make littlefs done"
YifuLiu/AliOS-Things
hardware/chip/haas1000/release/auto_build_tool/haas1000_littlefs.mk
Makefile
apache-2.0
245
#! /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/haas1000/release/auto_build_tool/ota_gen_md5_bin.py
Python
apache-2.0
3,481
linux_only_targets="" windows_only_targets=""
YifuLiu/AliOS-Things
hardware/chip/haas1000/ucube.py
Python
apache-2.0
46
#include "rec_pub.h" #include "ameba_soc.h" #include "build_info.h" #include "strproc.h" #include "system_8195a.h" void aos_2boot_os_entry() { uint8_t buf[0x30]; uint32_t bd_addr = 0; uint32_t bd_len = 0; uint32_t partition_start_addr; uint32_t os_entry_section_addr[2] = {0, 0}; hal_logic_partition_t *app_logic_partition = NULL; VOID (*RamStartFun) (VOID); app_logic_partition = rec_flash_get_info(HAL_PARTITION_APPLICATION); if(NULL == app_logic_partition) { return; } partition_start_addr = app_logic_partition->partition_start_addr; rec_flash_read_data(buf, partition_start_addr, 16); bd_addr = partition_start_addr + *(uint32_t *)&buf[8] + 0x20; rec_flash_read_data(buf, bd_addr, 0x30); os_entry_section_addr[0] = *(uint32_t *)(&buf[0x20]); os_entry_section_addr[1] = *(uint32_t *)(&buf[0x24]); bd_len = *(uint32_t *)(&buf[0x8]); printf("os entry section addr 0x%x, 0x%x\n", os_entry_section_addr[0], os_entry_section_addr[1]); /* copy OS data section to BD_RAM 0x10005000 */ rec_flash_read_data(0x10005000, bd_addr + 0x20, bd_len); /* jump to OS entry */ RamStartFun = os_entry_section_addr[0]; RamStartFun(); return; } void aos_2boot_Image2() { /* clear BSS */ uint32_t BssLen = (__bss_end__ - __bss_start__); _memset((void *) __bss_start__, 0, BssLen); printf("2boot image start\n"); if(recovery_check() != REC_NORMAL_START) { recovery_main(); } rec_uart_init(); if(!rec_2boot_cmd_check()) { rec_2boot_cmd_process(); } /* normal start */ printf("os image start\r\n"); aos_2boot_os_entry(); } void aos_2boot_wakeup() { uint8_t buf[0x30]; uint32_t bd_addr = 0; uint32_t bd_len = 0; uint32_t partition_start_addr; uint32_t os_entry_section_addr[2] = {0, 0}; hal_logic_partition_t *app_logic_partition = NULL; VOID (*RamStartFun) (VOID); app_logic_partition = rec_flash_get_info(HAL_PARTITION_APPLICATION); if(NULL == app_logic_partition) { return; } partition_start_addr = app_logic_partition->partition_start_addr; rec_flash_read_data(buf, partition_start_addr, 16); bd_addr = partition_start_addr + *(uint32_t *)&buf[8] + 0x20; rec_flash_read_data(buf, bd_addr, 0x30); os_entry_section_addr[0] = *(uint32_t *)(&buf[0x20]); os_entry_section_addr[1] = *(uint32_t *)(&buf[0x24]); bd_len = *(uint32_t *)(&buf[0x8]); /* Jump to wakeup function */ RamStartFun = os_entry_section_addr[1]; RamStartFun(); return; } IMAGE2_VALID_PATTEN_SECTION const u8 RAM_IMG2_VALID_PATTEN[20] = { 'R', 'T', 'K', 'W', 'i', 'n', 0x0, 0xff, (FW_VERSION&0xff), ((FW_VERSION >> 8)&0xff), (FW_SUBVERSION&0xff), ((FW_SUBVERSION >> 8)&0xff), (FW_CHIP_ID&0xff), ((FW_CHIP_ID >> 8)&0xff), (FW_CHIP_VER), (FW_BUS_TYPE), (FW_INFO_RSV1), (FW_INFO_RSV2), (FW_INFO_RSV3), (FW_INFO_RSV4) }; IMAGE2_ENTRY_SECTION RAM_START_FUNCTION gImage2EntryFun0 = { aos_2boot_Image2, aos_2boot_wakeup };
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/2nd_boot/boot_startup.c
C
apache-2.0
2,871
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "rec_flash.h" #include "flash_api.h" #include "hal_platform.h" static flash_t flash_obj; /* Logic partition on flash devices */ extern const hal_logic_partition_t hal_partitions[]; extern const size_t hal_partitions_amount; static void flash_read_data(UINT8 *buffer, UINT32 address, UINT32 len) { flash_stream_read(&flash_obj, address, len, buffer); } static void flash_write_data(UINT8 *buffer, UINT32 address, UINT32 len) { flash_stream_write(&flash_obj, address, len, buffer); } void rec_flash_init(void) { //flash has init in boot code; } /* offset means physical address */ void rec_flash_erase(unsigned long offset) { offset &= ~(FLASH_SECTOR_SIZE-1); flash_erase_sector(&flash_obj, offset); } /* offset means physical address */ void rec_flash_read_data(unsigned char *buffer, unsigned long offset, unsigned long len) { flash_read_data(buffer, offset, len); } /* offset means physical address */ void rec_flash_write_data(unsigned char *buffer, unsigned long offset, unsigned long len) { flash_write_data(buffer, offset, len); } hal_logic_partition_t *rec_flash_get_info(hal_partition_t pno) { if(pno >= hal_partitions_amount) { return NULL; } return &hal_partitions[pno]; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/2nd_boot/rec_flash.c
C
apache-2.0
1,316
#ifndef __REC_FLASH_H__ #define __REC_FLASH_H__ #include "rec_pub.h" #define REG_READ(addr) *((volatile UINT32 *)(addr)) #define REG_WRITE(addr, _data) (*((volatile UINT32 *)(addr)) = (_data)) #define MODE_STD 0 #define MODE_DUAL 1 #define MODE_QUAD 2 #define FLASH_WRITE_UNIT 32 #define FLASH_BASE (0x00803000) #define REG_FLASH_OPERATE_SW (FLASH_BASE + 0 * 4) #define ADDR_SW_REG_POSI (0) #define ADDR_SW_REG_MASK (0xFFFFFF) #define OP_TYPE_SW_POSI (24) #define OP_TYPE_SW_MASK (0x1F) #define OP_SW (0x01UL << 29) #define WP_VALUE (0x01UL << 30) #define BUSY_SW (0x01UL << 31) #define REG_FLASH_DATA_SW_FLASH (FLASH_BASE + 1 * 4) #define REG_FLASH_DATA_FLASH_SW (FLASH_BASE + 2 * 4) #define REG_FLASH_RDID_DATA_FLASH (FLASH_BASE + 4 * 4) #define REG_FLASH_SR_DATA_CRC_CNT (FLASH_BASE + 5 * 4) #define SR_DATA_FLASH_POSI (0) #define SR_DATA_FLASH_MASK (0xFF) #define CRC_ERROR_COUNT_POSI (8) #define CRC_ERROR_COUNT_MASK (0xFF) #define DATA_FLASH_SW_SEL_POSI (16) #define DATA_FLASH_SW_SEL_MASK (0x07) #define DATA_SW_FLASH_SEL_POSI (19) #define DATA_SW_FLASH_SEL_MASK (0x07) #define REG_FLASH_CONF (FLASH_BASE + 7 * 4) #define FLASH_CLK_CONF_POSI (0) #define FLASH_CLK_CONF_MASK (0x0F) #define MODEL_SEL_POSI (4) #define MODEL_SEL_MASK (0x1F) #define FWREN_FLASH_CPU (0x01UL << 9) #define WRSR_DATA_POSI (10) #define WRSR_DATA_MASK (0xFFFF) #define CRC_EN (0x01UL << 26) typedef enum { FLASH_OPCODE_WREN = 1, FLASH_OPCODE_WRDI = 2, FLASH_OPCODE_RDSR = 3, FLASH_OPCODE_WRSR = 4, FLASH_OPCODE_READ = 5, FLASH_OPCODE_RDSR2 = 6, FLASH_OPCODE_WRSR2 = 7, FLASH_OPCODE_PP = 12, FLASH_OPCODE_SE = 13, FLASH_OPCODE_BE1 = 14, FLASH_OPCODE_BE2 = 15, FLASH_OPCODE_CE = 16, FLASH_OPCODE_DP = 17, FLASH_OPCODE_RFDP = 18, FLASH_OPCODE_RDID = 20, FLASH_OPCODE_HPM = 21, FLASH_OPCODE_CRMR = 22, FLASH_OPCODE_CRMR2 = 23, } FLASH_OPCODE; #endif // __REC_FLASH_H__
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/2nd_boot/rec_flash.h
C
apache-2.0
2,713
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ /* * 该头文件用于为recovery屏蔽平台差异 */ #ifndef _REC_HAL_H_ #define _REC_HAL_H_ #define FLASH_SECTOR_SIZE 0x1000 #define SECTOR_SIZE 0x1000 #define SPLICT_SIZE 0x10000 #define SPLISE_NUM (1024*1024/SPLICT_SIZE) // OTA 分区1M #define OTA_ADDR_NUM (512*1024/SPLICT_SIZE) // OTA 内容 256k #define DIFF_CONF_OFFSET 0x00 #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/2nd_boot/rec_hal.h
C
apache-2.0
449
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "rec_sys.h" #include "sys_api.h" void rec_delayms(volatile int timesMS) { DelayMs(timesMS); } void rec_hal_init() { rec_uart_init(); rec_flash_init(); } void rec_err_print(void *errinfo) { printf("rec Exception.\r\n"); } void rec_reboot(void) { printf("begin reboot!\n"); /* Set processor clock to default(2: 31.25MHz) before system reset */ HAL_WRITE32(SYSTEM_CTRL_BASE, REG_SYS_CLK_CTRL1, 0x00000021); DelayUs(100*1000); /* Cortex-M3 SCB->AIRCR */ SCB->AIRCR = ((0x5FA << SCB_AIRCR_VECTKEY_Pos) | // VECTKEY (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | // PRIGROUP SCB_AIRCR_SYSRESETREQ_Msk); // SYSRESETREQ }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/2nd_boot/rec_sys.c
C
apache-2.0
716
#ifndef __REC_SYS_H__ #define __REC_SYS_H__ #include "rec_pub.h" /* ICU MACROS */ #define REG_ICU_BASE_ADDR (0x00802000UL) #define REG_ICU_PERI_CLK_PWD_ADDR (REG_ICU_BASE_ADDR + 0x2 * 4) #define REG_ICU_PERI_CLK_PWD_MASK 0x000BFFFFUL #define REG_ICU_PERI_CLK_PWD (*((volatile unsigned long *) REG_ICU_PERI_CLK_PWD_ADDR)) #define ICU_PERI_CLK_PWD_SET(x) do {REG_ICU_PERI_CLK_PWD |= (x);} while(0) #define ICU_PERI_CLK_PWD_CLEAR(x) do {REG_ICU_PERI_CLK_PWD &= ~(x);} while(0) #define ICU_PERI_CLK_PWD_ARM_WDT_POSI 8 #define ICU_PERI_CLK_PWD_ARM_WDT_MASK (0x01UL << ICU_PERI_CLK_PWD_ARM_WDT_POSI) /* WDT MACROS */ #define REG_WDT_BASE_ADDR (0x00802900UL) #define REG_WDT_CONFIG_ADDR (REG_WDT_BASE_ADDR + 0*4) #define REG_WDT_CONFIG_MASK 0x00FFFFFFUL #define REG_WDT_CONFIG (*((volatile unsigned long *) REG_WDT_CONFIG_ADDR)) #define WDKEY_ENABLE1 0x005A #define WDKEY_ENABLE2 0x00A5 #define WDT_CONFIG_PERIOD_POSI 0 #define WDT_CONFIG_PERIOD_MASK (0x0000FFFFUL << WDT_CONFIG_PERIOD_POSI) #define WDT_CONFIG_WDKEY_POSI 16 #define WDT_CONFIG_WDKEY_MASK (0x00FFUL << WDT_CONFIG_WDKEY_POSI) #endif // __REC_SYS_H__
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/2nd_boot/rec_sys.h
C
apache-2.0
1,387
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "rec_uart.h" #include "serial_api.h" #define UART_BUFF_LEN 1032 static unsigned char uart_buf[UART_BUFF_LEN]; static unsigned int uart_buf_write_index = 0; static unsigned int uart_buf_read_index = 0; void rec_uart_printf(const char *fmt, ...) { (void)VSprintf(0, fmt, ((const int *)&fmt)+1); return; } static void rec_loguart_irq() { unsigned char nc = 0; unsigned int IrqEn = DiagGetIsrEnReg(); DiagSetIsrEnReg(0); nc = DiagGetChar(0); uart_buf[uart_buf_write_index] = nc; uart_buf_write_index ++; if(uart_buf_write_index == UART_BUFF_LEN) { uart_buf_write_index = 0; } DiagSetIsrEnReg(IrqEn); } static int uart0_recv_byte(unsigned char *c) { unsigned int IrqEn = DiagGetIsrEnReg(); DiagSetIsrEnReg(0); if(uart_buf_read_index != uart_buf_write_index) { *c = uart_buf[uart_buf_read_index]; uart_buf_read_index ++; if(uart_buf_read_index == UART_BUFF_LEN) { uart_buf_read_index = 0; } DiagSetIsrEnReg(IrqEn); return 1; } DiagSetIsrEnReg(IrqEn); return 0; } unsigned char uart_recv_byte(unsigned char *c) { unsigned char tc = 0; if(uart0_recv_byte(&tc)) { *c = tc; return 1; } return 0; } unsigned char rec_uart_recv_byte(unsigned char *c) { return uart_recv_byte(c); } void rec_uart_init() { memset(uart_buf, 0xFF, UART_BUFF_LEN); DIAG_UartReInit((IRQ_FUN) rec_loguart_irq); } void rec_uart_deinit() { } void rec_uart_send_byte(unsigned char buff) { DiagPutChar(buff); } void rec_uart_send_string(char *buff) { int i; if(NULL == buff) { return; } rec_uart_printf(buff); return; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/2nd_boot/rec_uart.c
C
apache-2.0
1,794
#ifndef __REC_UART_H__ #define __REC_UART_H__ #include "rec_pub.h" #endif // __REC_UART_H__
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/2nd_boot/rec_uart.h
C
apache-2.0
98
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "rec_sys.h" #include "sys_api.h" void rec_wdt_init(unsigned int timeout_ms) { watchdog_init(timeout_ms); } void rec_wdt_start() { watchdog_start(); } void rec_wdt_stop() { watchdog_stop(); } void rec_wdt_feed() { watchdog_refresh(); }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/2nd_boot/rec_wdt.c
C
apache-2.0
328
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "CheckSumUtils.h" uint8_t UpdateCRC8(uint8_t crcIn, uint8_t byte) { uint8_t crc = crcIn; uint8_t i; crc ^= byte; for (i = 0; i < 8; i++) { if (crc & 0x01) { crc = (crc >> 1) ^ 0x8C; } else { crc >>= 1; } } return crc; } void CRC8_Init( CRC8_Context *inContext ) { inContext->crc = 0; } void CRC8_Update( CRC8_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 = UpdateCRC8(inContext->crc, *src++); } } void CRC8_Final( CRC8_Context *inContext, uint8_t *outResult ) { //inContext->crc = UpdateCRC8(inContext->crc, 0); *outResult = inContext->crc & 0xffu; } /*******************************************************************************/ uint16_t UpdateCRC16(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( CRC16_Context *inContext ) { inContext->crc = 0; } void CRC16_Update( 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(inContext->crc, *src++); } } void CRC16_Final( CRC16_Context *inContext, uint16_t *outResult ) { inContext->crc = UpdateCRC16(inContext->crc, 0); inContext->crc = UpdateCRC16(inContext->crc, 0); *outResult = inContext->crc & 0xffffu; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/CheckSumUtils.c
C
apache-2.0
1,867
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #ifndef __CheckSumUtils_h__ #define __CheckSumUtils_h__ #include <stdint.h> #include <stdbool.h> #include <stdlib.h> #include <stdio.h> /******************CRC-8 XMODEM x8+x5+x4+1****************************** *******************************************************************************/ typedef struct { uint8_t crc; } CRC8_Context; /** * @brief initialize the CRC8 Context * * @param inContext holds CRC8 result * * @retval none */ void CRC8_Init( CRC8_Context *inContext ); /** * @brief Caculate the CRC8 result * * @param inContext holds CRC8 result during caculation process * @param inSrc input data * @param inLen length of input data * * @retval none */ void CRC8_Update( CRC8_Context *inContext, const void *inSrc, size_t inLen ); /** * @brief output CRC8 result * * @param inContext holds CRC8 result * @param outResutl holds CRC8 final result * * @retval none */ void CRC8_Final( CRC8_Context *inContext, uint8_t *outResult ); /** * @} */ /******************CRC-16/XMODEM x16+x12+x5+1****************************** *******************************************************************************/ /** * @brief caculate the CRC16 result for each byte * * @param crcIn The context to save CRC16 result. * @param byte each byte of input data. * * @retval return the CRC16 result */ typedef struct { uint16_t crc; } CRC16_Context; /** * @brief initialize the CRC16 Context * * @param inContext holds CRC16 result * * @retval none */ void CRC16_Init( CRC16_Context *inContext ); /** * @brief Caculate the CRC16 result * * @param inContext holds CRC16 result during caculation process * @param inSrc input data * @param inLen length of input data * * @retval none */ void CRC16_Update( CRC16_Context *inContext, const void *inSrc, size_t inLen ); /** * @brief output CRC16 result * * @param inContext holds CRC16 result * @param outResutl holds CRC16 final result * * @retval none */ void CRC16_Final( CRC16_Context *inContext, uint16_t *outResult ); /** * @} */ /** * @} */ #endif //__CheckSumUtils_h__
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/CheckSumUtils.h
C
apache-2.0
2,395
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #ifndef AOS_DEBUG_H #define AOS_DEBUG_H #ifdef __cplusplus extern "C" { #endif #define SHORT_FILE __FILENAME__ #define debug_print_assert(A,B,C,D,E,F) #if (!defined(unlikely)) #define unlikely(EXPRESSSION) !!(EXPRESSSION) #endif /* * Check that an expression is true (non-zero). * If expression evalulates to false, this prints debugging information (actual expression string, file, line number, * function name, etc.) using the default debugging output method. * * @param[in] X expression to be evaluated. */ #if (!defined(check)) #define check(X) \ do { \ if (unlikely(!(X))) { \ debug_print_assert(0, #X, NULL, SHORT_FILE, __LINE__, __PRETTY_FUNCTION__); \ } \ } while(1 == 0) #endif /* * Check that an expression is true (non-zero) with an explanation. * If expression evalulates to false, this prints debugging information (actual expression string, file, line number, * function name, etc.) using the default debugging output method. * * @param[in] X expression to be evaluated. * @param[in] STR If the expression evaluate to false, custom string to print. */ #if (!defined(check_string)) #define check_string(X, STR) \ do { \ if (unlikely(!(X))) { \ debug_print_assert(0, #X, STR, SHORT_FILE, __LINE__, __PRETTY_FUNCTION__); \ AOS_ASSERTION_FAIL_ACTION(); \ } \ } while(1 == 0) #endif /* * Requires that an expression evaluate to true. * If expression evalulates to false, this prints debugging information (actual expression string, file, line number, * function name, etc.) using the default debugging output method then jumps to a label. * * @param[in] X expression to be evalulated. * @param[in] LABEL if expression evaluate to false,jumps to the LABEL. */ #if (!defined(require)) #define require(X, LABEL) \ do { \ if (unlikely(!(X))) { \ debug_print_assert( 0, #X, NULL, SHORT_FILE, __LINE__, __PRETTY_FUNCTION__ ); \ goto LABEL; \ } \ } while(1 == 0) #endif /* * Requires that an expression evaluate to true with an explanation. * If expression evalulates to false, this prints debugging information (actual expression string, file, line number, * function name, etc.) and a custom explanation string using the default debugging output method then jumps to a label. * * @param[in] X expression to be evalulated. * @param[in] LABEL if expression evaluate to false,jumps to the LABEL. * @param[in] STR if expression evaluate to false,custom explanation string to print. */ #if (!defined(require_string)) #define require_string(X, LABEL, STR) \ do { \ if (unlikely(!(X))) { \ debug_print_assert(0, #X, STR, SHORT_FILE, __LINE__, __PRETTY_FUNCTION__); \ goto LABEL; \ } \ } while(1 == 0) #endif /* * Requires that an expression evaluate to true. * If expression evalulates to false, this jumps to a label. No debugging information is printed. * * @param[in] X expression to be evalulated * @param[in] LABEL if expression evaluate to false,jumps to the LABEL. */ #if (!defined(require_quiet)) #define require_quiet(X, LABEL) \ do { \ if (unlikely(!(X))) { \ goto LABEL; \ } \ } while(1 == 0) #endif /* * Require that an error code is noErr (0). * If the error code is non-0, this prints debugging information (actual expression string, file, line number, * function name, etc.) using the default debugging output method then jumps to a label. * * @param[in] ERR error to be evaluated * @param[in] LABEL If the error code is non-0,jumps to the LABEL. */ #if (!defined(require_noerr)) #define require_noerr(ERR, LABEL) \ do { \ int localErr; \ \ localErr = (int)(ERR); \ if (unlikely(localErr != 0)) { \ debug_print_assert(localErr, NULL, NULL, SHORT_FILE, __LINE__, __PRETTY_FUNCTION__); \ goto LABEL; \ } \ \ } while(1 == 0) #endif /* * Require that an error code is noErr (0) with an explanation. * If the error code is non-0, this prints debugging information (actual expression string, file, line number, * function name, etc.), and a custom explanation string using the default debugging output method using the * default debugging output method then jumps to a label. * * @param[in] ERR error to be evaluated * @param[in] LABEL If the error code is non-0, jumps to the LABEL. * @param[in] STR If the error code is non-0, custom explanation string to print */ #if (!defined(require_noerr_string)) #define require_noerr_string(ERR, LABEL, STR) \ do { \ int localErr; \ \ localErr = (int)(ERR); \ if (unlikely(localErr != 0)) { \ debug_print_assert(localErr, NULL, STR, SHORT_FILE, __LINE__, __PRETTY_FUNCTION__); \ goto LABEL; \ } \ } while(1 == 0) #endif /* * Require that an error code is noErr (0) with an explanation and action to execute otherwise. * If the error code is non-0, this prints debugging information (actual expression string, file, line number, * function name, etc.), and a custom explanation string using the default debugging output method using the * default debugging output method then executes an action and jumps to a label. * * @param[in] ERR error to be evaluated. * @param[in] LABEL If the error code is non-0, jumps to the LABEL. * @param[in] ACTION If the error code is non-0, custom code to executes. * @param[in] STR If the error code is non-0, custom explanation string to print. */ #if (!defined(require_noerr_action_string)) #define require_noerr_action_string(ERR, LABEL, ACTION, STR) \ do { \ int localErr; \ \ localErr = (int)(ERR); \ if (unlikely(localErr != 0)) { \ debug_print_assert(localErr, NULL, STR, SHORT_FILE, __LINE__, __PRETTY_FUNCTION__); \ { ACTION; } \ goto LABEL; \ } \ } while(1 == 0) #endif /* * Require that an error code is noErr (0). * If the error code is non-0, this jumps to a label. No debugging information is printed. * * @param[in] ERR error to be evaluated. * @param[in] LABEL If the error code is non-0, jumps to the LABEL. */ #if (!defined(require_noerr_quiet)) #define require_noerr_quiet(ERR, LABEL) \ do { \ if (unlikely((ERR) != 0)) { \ goto LABEL; \ } \ } while(1 == 0) #endif /* * Require that an error code is noErr (0) with an action to execute otherwise. * If the error code is non-0, this prints debugging information (actual expression string, file, line number, * function name, etc.) using the default debugging output method then executes an action and jumps to a label. * * @param[in] ERR error to be evaluated. * @param[in] LABEL If the error code is non-0, jumps to the LABEL. * @param[in] ACTION If the error code is non-0, custom code to executes. */ #if (!defined(require_noerr_action)) #define require_noerr_action(ERR, LABEL, ACTION) \ do { \ int localErr; \ \ localErr = (int)(ERR); \ if (unlikely(localErr != 0)) { \ debug_print_assert(localErr, NULL, NULL, SHORT_FILE, __LINE__, __PRETTY_FUNCTION__); \ { ACTION; } \ goto LABEL; \ } \ } while(1 == 0) #endif /* * Require that an error code is noErr (0) with an action to execute otherwise. * If the error code is non-0, this executes an action and jumps to a label. No debugging information is printed. * * @param[in] ERR error to be evaluated. * @param[in] LABEL If the error code is non-0, jumps to the LABEL. * @param[in] ACTION If the error code is non-0, custom code to executes. */ #if (!defined(require_noerr_action_quiet)) #define require_noerr_action_quiet(ERR, LABEL, ACTION) \ do { \ if (unlikely((ERR) != 0)) { \ { ACTION; } \ goto LABEL; \ } \ } while(1 == 0) #endif /* * Requires that an expression evaluate to true with an action to execute otherwise. * If expression evalulates to false, this prints debugging information (actual expression string, file, line number, * function name, etc.) using the default debugging output method then executes an action and jumps to a label. * * @param[in] X expression to be evaluated. * @param[in] LABEL If the expression evaluate to false, jumps to the LABEL. * @param[in] ACTION If the expression evaluate to false, custom code to executes. */ #if (!defined(require_action)) #define require_action(X, LABEL, ACTION) \ do { \ if (unlikely(!(X))) { \ debug_print_assert(0, #X, NULL, SHORT_FILE, __LINE__, __PRETTY_FUNCTION__); \ { ACTION; } \ goto LABEL; \ } \ } while (1 == 0) #endif /* * Requires that an expression evaluate to true with an explanation and action to execute otherwise. * If expression evalulates to false, this prints debugging information (actual expression string, file, line number, * function name, etc.) and a custom explanation string using the default debugging output method then executes an * action and jumps to a label. * * @param[in] X expression to be evaluated. * @param[in] LABEL If the expression evaluate to false, jumps to the LABEL. * @param[in] ACTION If the expression evaluate to false, custom code to executes. * @param[in] STR If the expression evaluate to false, custom string to print. */ #if (!defined(require_action_string)) #define require_action_string(X, LABEL, ACTION, STR) \ do { \ if (unlikely(!(X))) { \ debug_print_assert(0, #X, STR, SHORT_FILE, __LINE__, __PRETTY_FUNCTION__); \ { ACTION; } \ goto LABEL; \ } \ } while (1 == 0) #endif /* * Requires that an expression evaluate to true with an action to execute otherwise. * If expression evalulates to false, this executes an action and jumps to a label. * No debugging information is printed. * * @param[in] X expression to be evaluated. * @param[in] LABEL If the expression evaluate to false, jumps to the LABEL. * @param[in] ACTION If the expression evaluate to false, custom code to executes. */ #if (!defined(require_action_quiet)) #define require_action_quiet(X, LABEL, ACTION) \ do { \ if (unlikely(!(X))) { \ { ACTION; } \ goto LABEL; \ } \ \ } while(1 == 0) #endif #ifdef __cplusplus } #endif #endif /* AOS_DEBUG_H */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/aos/aos_debug.h
C
apache-2.0
16,130
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ //#include <autoconf.h> #include <osdep_service.h> #include <stdio.h> #include <alios/wrapper.h> #include "aos/kernel.h" #include <aos/errno.h> #include <freertos_pmu.h> #include "k_api.h" /********************* os depended utilities ********************/ #ifndef USE_MUTEX_FOR_SPINLOCK #define USE_MUTEX_FOR_SPINLOCK 1 #endif static volatile uint32_t ulCriticalNesting = 0; static u32 uxSavedInterruptStatus = 0; //----- ------------------------------------------------------------------ // Misc Function //----- ------------------------------------------------------------------ #if 0 void save_and_cli() { RHINO_CRITICAL_ENTER(); } void restore_flags() { RHINO_CRITICAL_EXIT(); } #endif void aos_interrupt_enter() { krhino_intrpt_enter(); } void aos_interrupt_leave() { krhino_intrpt_exit(); } void cli() { //RHINO_CPU_INTRPT_DISABLE(); } /* Not needed on 64bit architectures */ static unsigned int __div64_32(u64 *n, unsigned int base) { u64 rem = *n; u64 b = base; u64 res, d = 1; unsigned int high = rem >> 32; /* Reduce the thing a bit first */ res = 0; if (high >= base) { high /= base; res = (u64) high << 32; rem -= (u64) (high * base) << 32; } while ((u64)b > 0 && b < rem) { b = b+b; d = d+d; } do { if (rem >= b) { rem -= b; res += d; } b >>= 1; d >>= 1; } while (d); *n = res; return rem; } /********************* os depended service ********************/ u8* _aos_malloc(u32 sz) { //DBG_8195A(" realsil malloc %d\r\n", sz); return aos_malloc(sz); } u8* _aos_zmalloc(u32 sz) { u8 *pbuf = _aos_malloc(sz); if (pbuf != NULL) memset(pbuf, 0, sz); return pbuf; } void _aos_mfree(u8 *pbuf, u32 sz) { aos_free(pbuf); } static void _aos_memcpy(void* dst, void* src, u32 sz) { _memcpy(dst, src, sz); } static int _aos_memcmp(void *dst, void *src, u32 sz) { //under Linux/GNU/GLibc, the return value of memcmp for two same mem. chunk is 0 if (!(_memcmp(dst, src, sz))) return 1; return 0; } static void _aos_memset(void *pbuf, int c, u32 sz) { _memset(pbuf, c, sz); } static void _aos_init_sema(_sema *sema, int init_val) { aos_sem_new(sema, init_val); //Set max count 0xffffffff } static void _aos_free_sema(_sema *sema) { if(sema != NULL) aos_sem_free(sema); } static void _aos_up_sema(_sema *sema) { aos_sem_signal(sema); } static void _aos_up_sema_from_isr(_sema *sema) { aos_sem_signal(sema); } static u32 _aos_down_sema(_sema *sema, u32 timeout) { //DBG_8195A("_aos_down_sema\r\n"); if(timeout == RTW_MAX_DELAY) { timeout = AOS_WAIT_FOREVER; } else { timeout = rtw_ms_to_systime(timeout); } //DBG_8195A("_aos_down_sema, timeout %d\r\n", timeout); if(aos_sem_wait(sema, timeout) != 0) { printf("_aos_down_sema 0x%x, timeout %d\n", sema, timeout); return FALSE; } return TRUE; //return aos_sem_wait(sema, timeout); } static void _aos_mutex_init(_mutex *pmutex) { aos_mutex_new(pmutex); return; } static void _aos_mutex_free(_mutex *pmutex) { if(pmutex != NULL) aos_mutex_free(pmutex); //pmutex = NULL; } static void _aos_mutex_get(_lock *plock) { while(aos_mutex_lock(plock, 60 * 1000) != 0) DBG_8195A("%s(%p) failed, retry\n", __FUNCTION__, plock); } static int _aos_mutex_get_timeout(_lock *plock, u32 timeout_ms) { if(aos_mutex_lock(plock, timeout_ms ) != 0){ DBG_8195A(" %s(%p) failed, retry\n", __FUNCTION__, plock); return -1; } return 0; } static void _aos_mutex_put(_lock *plock) { aos_mutex_unlock(plock); } #if 1 static void _aos_enter_critical(_lock *plock, _irqL *pirqL) { __asm volatile( "cpsid i" ); ulCriticalNesting++; __asm volatile( "dsb" ::: "memory" ); __asm volatile( "isb" ); } static void _aos_exit_critical(_lock *plock, _irqL *pirqL) { if(ulCriticalNesting == 0) return; ulCriticalNesting--; if( ulCriticalNesting == 0 ) { __asm volatile( "cpsie i" ); } } static void _aos_enter_critical_from_isr(_lock *plock, _irqL *pirqL) { uxSavedInterruptStatus = cpu_intrpt_save( ); } static void _aos_exit_critical_from_isr(_lock *plock, _irqL *pirqL) { cpu_intrpt_restore(uxSavedInterruptStatus); } #endif static int _aos_enter_critical_mutex(_mutex *pmutex, _irqL *pirqL) { int ret = 0; while(aos_mutex_lock(pmutex, 60 * 1000) != 0) DBG_8195A("%s(%p) failed, retry\n", __FUNCTION__, pmutex); return ret; } static void _aos_exit_critical_mutex(_mutex *pmutex, _irqL *pirqL) { aos_mutex_unlock(pmutex); } static void _aos_spinlock_init(_lock *plock) { #if USE_MUTEX_FOR_SPINLOCK aos_mutex_new(plock); #endif } static void _aos_spinlock_free(_lock *plock) { #if USE_MUTEX_FOR_SPINLOCK if(plock != NULL) aos_mutex_free(plock); //*plock = NULL; #endif } static void _aos_spinlock(_lock *plock) { #if USE_MUTEX_FOR_SPINLOCK while(aos_mutex_lock(plock, 60 * 1000) != 0) DBG_8195A(" %s(%p) failed, retry\n", __FUNCTION__, plock); #endif } static void _aos_spinunlock(_lock *plock) { #if USE_MUTEX_FOR_SPINLOCK aos_mutex_unlock(plock); #endif } #if 0 static void _aos_spinlock_irqsave(_lock *plock, _irqL *irqL) { RHINO_CRITICAL_ENTER(); #if USE_MUTEX_FOR_SPINLOCK while(aos_mutex_lock(plock, 60 * 1000) != 0) DBG_8195A("[%s] %s(%p) failed, retry\n", aos_task_name(), __FUNCTION__, plock); #endif } static void _aos_spinunlock_irqsave(_lock *plock, _irqL *irqL) { #if USE_MUTEX_FOR_SPINLOCK aos_mutex_unlock(plock); #endif RHINO_CRITICAL_EXIT(); } } #endif static int _aos_init_xqueue( _xqueue* queue, const char* name, u32 message_size, u32 number_of_messages ) { int ret = 0; ret = krhino_buf_queue_dyn_create(&queue, name, message_size, number_of_messages); return ret; } static int _aos_push_to_xqueue( _xqueue* queue, void* message, u32 timeout_ms ) { krhino_buf_queue_send(queue, message, sizeof(void*)); return 0; } static int _aos_pop_from_xqueue( _xqueue* queue, void* message, u32 timeout_ms ) { int size = 0; krhino_buf_queue_recv(queue, timeout_ms, message, &size); return 0; } static int _aos_deinit_xqueue( _xqueue* queue ) { krhino_buf_queue_dyn_del(queue); return 0; } static u32 _aos_get_current_time(void) { return aos_now_ms(); //The count of ticks since vTaskStartScheduler was called. } static u32 _aos_systime_to_ms(u32 systime) { return krhino_ticks_to_ms(systime); } static u32 _aos_systime_to_sec(u32 systime) { return krhino_ticks_to_ms(systime)/1000; } static u32 _aos_ms_to_systime(u32 ms) { return krhino_ms_to_ticks(ms); } static u32 _aos_sec_to_systime(u32 sec) { return krhino_ms_to_ticks(sec) * 1000; } static void _aos_msleep_os(int ms) { #if defined(CONFIG_PLATFORM_8195A) aos_msleep(ms); #elif defined(CONFIG_PLATFORM_8711B) if (pmu_yield_os_check()) { aos_msleep(ms); } else { DelayMs(ms); } #elif defined(CONFIG_PLATFORM_8721D) if (pmu_yield_os_check()) { aos_msleep(ms); } else { DelayMs(ms); } #endif } static void _aos_usleep_os(int us) { #if defined(STM32F2XX) || defined(STM32F4XX) || defined(STM32F10X_XL) // FreeRTOS does not provide us level delay. Use busy wait WLAN_BSP_UsLoop(us); #elif defined(CONFIG_PLATFORM_8195A) //DBG_ERR("%s: Please Implement micro-second delay\n", __FUNCTION__); #elif defined(CONFIG_PLATFORM_8711B) DelayUs(us); #elif defined(CONFIG_PLATFORM_8721D) DelayUs(us); #else #error "Please implement hardware dependent micro second level sleep here" #endif } static void _aos_mdelay_os(int ms) { #if defined(CONFIG_PLATFORM_8195A) aos_msleep(ms); #elif defined(CONFIG_PLATFORM_8711B) if (pmu_yield_os_check()) { aos_msleep(ms); } else { DelayMs(ms); } #elif defined(CONFIG_PLATFORM_8721D) if (pmu_yield_os_check()) { aos_msleep(ms); } else { DelayMs(ms); } #endif } static void _aos_udelay_os(int us) { #if defined(STM32F2XX) || defined(STM32F4XX) || defined(STM32F10X_XL) // FreeRTOS does not provide us level delay. Use busy wait WLAN_BSP_UsLoop(us); #elif defined(CONFIG_PLATFORM_8195A) HalDelayUs(us); #elif defined(CONFIG_PLATFORM_8711B) DelayUs(us); #elif defined(CONFIG_PLATFORM_8721D) DelayUs(us); #else #error "Please implement hardware dependent micro second level sleep here" #endif } static void _aos_yield_os(void) { #if defined(CONFIG_PLATFORM_8195A) taskYIELD(); #elif defined(CONFIG_PLATFORM_8711B) krhino_task_yield(); #elif defined(CONFIG_PLATFORM_8721D) krhino_task_yield(); #endif } static void _aos_ATOMIC_SET(ATOMIC_T *v, int i) { atomic_set(v,i); } static int _aos_ATOMIC_READ(ATOMIC_T *v) { return atomic_read(v); } static void _aos_ATOMIC_ADD(ATOMIC_T *v, int i) { CPSR_ALLOC(); cpsr = cpu_intrpt_save(); v->counter += i; cpu_intrpt_restore(cpsr); } static void _aos_ATOMIC_SUB(ATOMIC_T *v, int i) { size_t cpsr_sig; CPSR_ALLOC(); cpsr = cpu_intrpt_save(); v->counter -= i; cpu_intrpt_restore(cpsr_sig); } static void _aos_ATOMIC_INC(ATOMIC_T *v) { _aos_ATOMIC_ADD(v, 1); } static void _aos_ATOMIC_DEC(ATOMIC_T *v) { _aos_ATOMIC_SUB(v, 1); } static int _aos_ATOMIC_ADD_RETURN(ATOMIC_T *v, int i) { int temp; CPSR_ALLOC(); cpsr = cpu_intrpt_save(); temp = v->counter; temp += i; v->counter = temp; cpu_intrpt_restore(cpsr); return temp; } static int _aos_ATOMIC_SUB_RETURN(ATOMIC_T *v, int i) { int temp; CPSR_ALLOC(); cpsr = cpu_intrpt_save(); temp = v->counter; temp -= i; v->counter = temp; cpu_intrpt_restore(cpsr); return temp; } static int _aos_ATOMIC_INC_RETURN(ATOMIC_T *v) { return _aos_ATOMIC_ADD_RETURN(v, 1); } static int _aos_ATOMIC_DEC_RETURN(ATOMIC_T *v) { return _aos_ATOMIC_SUB_RETURN(v, 1); } static u64 _aos_modular64(u64 n, u64 base) { unsigned int __base = (base); unsigned int __rem; if (((n) >> 32) == 0) { __rem = (unsigned int)(n) % __base; (n) = (unsigned int)(n) / __base; } else __rem = __div64_32(&(n), __base); return __rem; } /* Refer to ecos bsd tcpip codes */ static int _aos_arc4random(void) { u32 res = aos_now_ms(); static unsigned long seed = 0xDEADB00B; #if CONFIG_PLATFORM_8711B if(random_seed){ seed = random_seed; random_seed = 0; } #endif seed = ((seed & 0x007F00FF) << 7) ^ ((seed & 0x0F80FF00) >> 8) ^ // be sure to stir those low bits (res << 13) ^ (res >> 9); // using the clock too! return (int)seed; } static int _aos_get_random_bytes(void *buf, u32 len) { #if 1 //becuase of 4-byte align, we use the follow code style. unsigned int ranbuf; unsigned int *lp; int i, count; count = len / sizeof(unsigned int); lp = (unsigned int *) buf; for(i = 0; i < count; i ++) { lp[i] = _aos_arc4random(); len -= sizeof(unsigned int); } if(len > 0) { ranbuf = _aos_arc4random(); _aos_memcpy(&lp[i], &ranbuf, len); } return 0; #else unsigned long ranbuf, *lp; lp = (unsigned long *)buf; while (len > 0) { ranbuf = _freertos_arc4random(); *lp++ = ranbuf; //this op need the pointer is 4Byte-align! len -= sizeof(ranbuf); } return 0; #endif } static u32 _aos_GetFreeHeapSize(void) { //return (u32)xPortGetFreeHeapSize(); extern k_mm_head *g_kmm_head; return g_kmm_head->free_size; } static int _aos_create_task(struct task_struct *ptask, const char *name, u32 stack_size, u32 priority, thread_func_t func, void *thctx) { thread_func_t task_func = NULL; void *task_ctx = NULL; int ret = 0; //DBG_8195A("_aos_create_task start\r\n"); ptask->task_name = name; ptask->blocked = 0; ptask->callback_running = 0; _aos_init_sema(&ptask->wakeup_sema, 0); _aos_init_sema(&ptask->terminate_sema, 0); //rtw_init_queue(&wq->work_queue); // DBG_8195A("_aos_create_task init sema done\r\n"); if(func){ task_func = func; task_ctx = thctx; } //else{ // task_func = freertos_wq_thread_handler; // task_ctx = wq; //} priority = 11-priority; ret = aos_task_new_ext(&ptask->task, name, func, task_ctx, stack_size*sizeof(cpu_stack_t), priority); if(ret != 0){ DBG_8195A("Create Task \"%s\" Failed! ret=%d\n", ptask->task_name, ret); } //DBG_8195A("Create Task \"%s\"\n", ptask->task_name); return 1; } static void _aos_delete_task(struct task_struct *ptask) { if (!(ptask->task)){ DBG_8195A("_aos_delete_task(): ptask is NULL!\n"); return; } ptask->blocked = 1; _aos_up_sema(&ptask->wakeup_sema); _aos_down_sema(&ptask->terminate_sema, RTW_MAX_DELAY); //rtw_deinit_queue(&wq->work_queue); _aos_free_sema(&ptask->wakeup_sema); _aos_free_sema(&ptask->terminate_sema); //ptask->task = 0; //DBG_8195A("Delete Task \"%s\"\n", ptask->task_name); } void _aos_wakeup_task(struct task_struct *ptask) { _aos_up_sema(&ptask->wakeup_sema); } void _aos_set_priority_task(void* task, u32 NewPriority) { uint8_t old_pri = 0; uint8_t priority = (uint8_t)(11 - NewPriority); aos_task_pri_change((aos_task_t *)&task, priority, &old_pri); } int _aos_get_priority_task(void* task) { uint8_t priority = 0; aos_task_pri_get((aos_task_t *)&task, &priority); return (int)(11 - priority); } void _aos_suspend_task(void* task) { aos_task_suspend((aos_task_t *)&task); } void _aos_resume_task(void* task) { aos_task_resume((aos_task_t *)&task); } static void _aos_thread_enter(char *name) { //DBG_8195A("\n\rRTKTHREAD %s\n", name); } static void _aos_thread_exit(void) { //DBG_8195A("\n\rRTKTHREAD exit %s\n", __FUNCTION__); aos_task_exit(0); } _timerHandle _aos_timerCreate( const signed char *pcTimerName, osdepTickType xTimerPeriodInTicks, u32 uxAutoReload, void * pvTimerID, TIMER_FUN pxCallbackFunction ) { int ret ; _timerHandle t_handler= _aos_zmalloc(sizeof(struct timerHandle)); if(xTimerPeriodInTicks>= 0xffffffff) xTimerPeriodInTicks = 0x7ffffffe; ret = aos_timer_new_ext(&t_handler->timer, pxCallbackFunction,(void *)t_handler, krhino_ticks_to_ms(xTimerPeriodInTicks), 0, 0); return t_handler; } u32 _aos_timerDelete( _timerHandle xTimer, osdepTickType xBlockTime ) { aos_timer_stop(&xTimer->timer); aos_timer_free(&xTimer->timer); _aos_mfree(xTimer, sizeof(xTimer)); return 0; } u32 _aos_timerIsTimerActive( _timerHandle xTimer ) { return 1; } u32 _aos_timerStop( _timerHandle xTimer, osdepTickType xBlockTime ) { if(!aos_timer_stop(&xTimer->timer)) return 1; return 0; } #define MS2TICK(ms) krhino_ms_to_ticks(ms) int _aos_timer_change_no_repeat(aos_timer_t *timer, int ms) { int ret; ret = aos_timer_change_once(timer, ms); ret = aos_timer_start(timer); return ret; } u32 _aos_timerChangePeriod( _timerHandle xTimer, osdepTickType xNewPeriod, osdepTickType xBlockTime ) { if(xNewPeriod == 0) xNewPeriod += 1; //if(!aos_timer_change(&xTimer->timer, xNewPeriod)) if(!_aos_timer_change_no_repeat(&xTimer->timer, xNewPeriod)) return 1; return 0; } void *_aos_timerGetID( _timerHandle xTimer ){ return 0; } u32 _aos_timerStart( _timerHandle xTimer, osdepTickType xBlockTime ) { int ret; ret = aos_timer_start(&xTimer->timer); return !ret; //!aos_timer_start(&xTimer->timer); } u32 _aos_timerStartFromISR( _timerHandle xTimer, osdepBASE_TYPE *pxHigherPriorityTaskWoken ) { return !aos_timer_start(&xTimer->timer); } u32 _aos_timerStopFromISR( _timerHandle xTimer, osdepBASE_TYPE *pxHigherPriorityTaskWoken ) { return !aos_timer_stop(&xTimer->timer); } u32 _aos_timerResetFromISR( _timerHandle xTimer, osdepBASE_TYPE *pxHigherPriorityTaskWoken ) { (u32)aos_timer_stop(&xTimer->timer); return !aos_timer_start(&xTimer->timer); } u32 _aos_timerChangePeriodFromISR( _timerHandle xTimer, osdepTickType xNewPeriod, osdepBASE_TYPE *pxHigherPriorityTaskWoken ) { if(xNewPeriod == 0) xNewPeriod += 1; (u32)aos_timer_stop(&xTimer->timer); return !aos_timer_change(&xTimer->timer, xNewPeriod); } u32 _aos_timerReset( _timerHandle xTimer, osdepTickType xBlockTime ) { (u32)aos_timer_stop(&xTimer->timer); return !aos_timer_start(&xTimer->timer); } void _aos_acquire_wakelock() { #if defined(CONFIG_PLATFORM_8195A) #if defined(configUSE_WAKELOCK_PMU) && (configUSE_WAKELOCK_PMU == 1) pmu_acquire_wakelock(PMU_WLAN_DEVICE); #endif #elif defined(CONFIG_PLATFORM_8711B) #if defined(configUSE_WAKELOCK_PMU) && (configUSE_WAKELOCK_PMU == 1) if (pmu_yield_os_check()) pmu_acquire_wakelock(PMU_WLAN_DEVICE); #endif #elif defined(CONFIG_PLATFORM_8721D) #if defined(configUSE_WAKELOCK_PMU) && (configUSE_WAKELOCK_PMU == 1) if (pmu_yield_os_check()) pmu_acquire_wakelock(PMU_WLAN_DEVICE); #endif #endif } void _aos_release_wakelock() { #if defined(CONFIG_PLATFORM_8195A) #if defined(configUSE_WAKELOCK_PMU) && (configUSE_WAKELOCK_PMU == 1) pmu_release_wakelock(PMU_WLAN_DEVICE); #endif #elif defined(CONFIG_PLATFORM_8711B) #if defined(configUSE_WAKELOCK_PMU) && (configUSE_WAKELOCK_PMU == 1) if (pmu_yield_os_check()) pmu_release_wakelock(PMU_WLAN_DEVICE); #endif #elif defined(CONFIG_PLATFORM_8721D) #if defined(configUSE_WAKELOCK_PMU) && (configUSE_WAKELOCK_PMU == 1) if (pmu_yield_os_check()) pmu_release_wakelock(PMU_WLAN_DEVICE); #endif #endif } void _aos_wakelock_timeout(uint32_t timeout) { #if defined(CONFIG_PLATFORM_8195A) #elif defined(CONFIG_PLATFORM_8711B) if (pmu_yield_os_check()) pmu_set_sysactive_time(timeout); else DBG_INFO("can't aquire wake during suspend flow!!\n"); #elif defined(CONFIG_PLATFORM_8721D) if (pmu_yield_os_check()) pmu_set_sysactive_time(timeout); else DBG_INFO("can't aquire wake during suspend flow!!\n"); #endif } u8 _aos_get_scheduler_state(void) { return 0; } const struct osdep_service_ops osdep_service = { _aos_malloc, //rtw_vmalloc _aos_zmalloc, //rtw_zvmalloc _aos_mfree, //rtw_vmfree _aos_malloc, //rtw_malloc _aos_zmalloc, //rtw_zmalloc _aos_mfree, //rtw_mfree _aos_memcpy, //rtw_memcpy _aos_memcmp, //rtw_memcmp _aos_memset, //rtw_memset _aos_init_sema, //rtw_init_sema _aos_free_sema, //rtw_free_sema _aos_up_sema, //rtw_up_sema _aos_up_sema_from_isr, //rtw_up_sema_from_isr _aos_down_sema, //rtw_down_sema _aos_mutex_init, //rtw_mutex_init _aos_mutex_free, //rtw_mutex_free _aos_mutex_get, //rtw_mutex_get _aos_mutex_get_timeout,//rtw_mutex_get_timeout _aos_mutex_put, //rtw_mutex_put _aos_enter_critical, //rtw_enter_critical _aos_exit_critical, //rtw_exit_critical _aos_enter_critical_from_isr, //rtw_enter_critical_from_isr _aos_exit_critical_from_isr, //rtw_exit_critical_from_isr NULL, //rtw_enter_critical_bh NULL, //rtw_exit_critical_bh _aos_enter_critical_mutex, //rtw_enter_critical_mutex _aos_exit_critical_mutex, //rtw_exit_critical_mutex _aos_spinlock_init, //rtw_spinlock_init _aos_spinlock_free, //rtw_spinlock_free _aos_spinlock, //rtw_spin_lock _aos_spinunlock, //rtw_spin_unlock NULL, //rtw_spinlock_irqsave NULL, //rtw_spinunlock_irqsave _aos_init_xqueue, //rtw_init_xqueue _aos_push_to_xqueue, //rtw_push_to_xqueue _aos_pop_from_xqueue, //rtw_pop_from_xqueue _aos_deinit_xqueue, //rtw_deinit_xqueue _aos_get_current_time, //rtw_get_current_time _aos_systime_to_ms, //rtw_systime_to_ms _aos_systime_to_sec, //rtw_systime_to_sec _aos_ms_to_systime, //rtw_ms_to_systime _aos_sec_to_systime, //rtw_sec_to_systime _aos_msleep_os, //rtw_msleep_os _aos_usleep_os, //rtw_usleep_os _aos_mdelay_os, //rtw_mdelay_os _aos_udelay_os, //rtw_udelay_os _aos_yield_os, //rtw_yield_os _aos_ATOMIC_SET, //ATOMIC_SET _aos_ATOMIC_READ, //ATOMIC_READ _aos_ATOMIC_ADD, //ATOMIC_ADD _aos_ATOMIC_SUB, //ATOMIC_SUB _aos_ATOMIC_INC, //ATOMIC_INC _aos_ATOMIC_DEC, //ATOMIC_DEC _aos_ATOMIC_ADD_RETURN, //ATOMIC_ADD_RETURN _aos_ATOMIC_SUB_RETURN, //ATOMIC_SUB_RETURN _aos_ATOMIC_INC_RETURN, //ATOMIC_INC_RETURN _aos_ATOMIC_DEC_RETURN, //ATOMIC_DEC_RETURN _aos_modular64, //rtw_modular64 _aos_get_random_bytes, //rtw_get_random_bytes _aos_GetFreeHeapSize, //rtw_getFreeHeapSize _aos_create_task, //rtw_create_task _aos_delete_task, //rtw_delete_task _aos_wakeup_task, //rtw_wakeup_task _aos_set_priority_task, //rtw_set_priority_task _aos_get_priority_task, //rtw_get_priority_task _aos_suspend_task, //rtw_suspend_task _aos_resume_task, //rtw_resume_task _aos_thread_enter, //rtw_thread_enter _aos_thread_exit, //rtw_thread_exit _aos_timerCreate, //rtw_timerCreate, _aos_timerDelete, //rtw_timerDelete, _aos_timerIsTimerActive, //rtw_timerIsTimerActive, _aos_timerStop, //rtw_timerStop, _aos_timerChangePeriod, //rtw_timerChangePeriod _aos_timerGetID, //rtw_timerGetID _aos_timerStart, //rtw_timerStart _aos_timerStartFromISR, //rtw_timerStartFromISR _aos_timerStopFromISR, //rtw_timerStopFromISR _aos_timerResetFromISR, //rtw_timerResetFromISR _aos_timerChangePeriodFromISR, //rtw_timerChangePeriodFromISR _aos_timerReset, //rtw_timerReset _aos_acquire_wakelock, //rtw_acquire_wakelock _aos_release_wakelock, //rtw_release_wakelock _aos_wakelock_timeout, //rtw_wakelock_timeout _aos_get_scheduler_state //rtw_get_scheduler_state };
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/aos/aos_osdep.c
C
apache-2.0
21,549
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #ifndef __AOS_OSDEP_SERVICE_H_ #define __AOS_OSDEP_SERVICE_H_ #include "dlist.h" #include "aos/kernel.h" #include <k_api.h> // -------------------------------------------- // Platform dependent include file // -------------------------------------------- #if defined(CONFIG_PLATFORM_8195A) #include "platform/platform_stdlib.h" extern VOID RtlUdelayOS(u32 us); #elif defined(CONFIG_PLATFORM_8711B) #include "platform/platform_stdlib.h" #elif defined(CONFIG_PLATFORM_8721D) #include "platform/platform_stdlib.h" #else // other MCU may use standard library #include <string.h> #endif #ifndef configTICK_RATE_HZ #define configTICK_RATE_HZ ( ( uint32_t ) 1000 ) #endif #define DBG_ERR(fmt, args...) DBG_8195A("\n\r[%s] " fmt, __FUNCTION__, ## args) #if WLAN_INTF_DBG #define DBG_TRACE(fmt, args...) DBG_8195A("\n\r[%s] " fmt, __FUNCTION__, ## args) #define DBG_INFO(fmt, args...) DBG_8195A("\n\r[%s] " fmt, __FUNCTION__, ## args) #else #define DBG_TRACE(fmt, args...) #define DBG_INFO(fmt, args...) #endif #define pvPortMalloc aos_malloc #define vPortFree aos_free /* * atomic_read - read atomic variable * @v: pointer of type atomic_t * * Atomically reads the value of @v. Note that the guaranteed * useful range of an atomic_t is only 24 bits. */ #undef atomic_read #define atomic_read(v) ((v)->counter) /* * atomic_set - set atomic variable * @v: pointer of type atomic_t * @i: required value * * Atomically sets the value of @v to @i. Note that the guaranteed * useful range of an atomic_t is only 24 bits. */ #undef atomic_set #define atomic_set(v,i) ((v)->counter = (i)) #define HALT() do { cli(); for(;;);} while(0) #undef ASSERT #define ASSERT(x) do { \ if((x) == 0){\ DBG_8195A("\n\rAssert(" #x ") failed on line %d in file %s", __LINE__, __FILE__); \ HALT();}\ } while(0) #undef DBG_ASSERT #define DBG_ASSERT(x, msg) do { \ if((x) == 0) \ DBG_8195A("\n\r%s, Assert(" #x ") failed on line %d in file %s", msg, __LINE__, __FILE__); \ } while(0) // os types typedef char osdepCHAR; typedef float osdepFLOAT; typedef double osdepDOUBLE; typedef long osdepLONG; typedef short osdepSHORT; typedef unsigned long osdepSTACK_TYPE; typedef long osdepBASE_TYPE; typedef unsigned long osdepTickType; struct timerHandle{ aos_timer_t timer; char* q_buf; }; typedef struct timerHandle* _timerHandle; typedef aos_sem_t _sema; typedef aos_mutex_t _mutex; typedef aos_mutex_t _lock; typedef aos_queue_t _queueHandle; typedef kbuf_queue_t _xqueue; #if 0 typedef struct{ aos_queue_t queue; char* q_buf; }_xqueue; #endif typedef struct timer_list _timer; typedef struct sk_buff _pkt; typedef unsigned char _buffer; struct __queue { struct list_head queue; _lock lock; }; typedef struct __queue _queue; typedef struct list_head _list; typedef u32 _irqL; typedef struct {volatile int counter;} atomic_t; #define ATOMIC_T atomic_t #define DBG_ERR(fmt, args...) DBG_8195A("\n\r[%s] " fmt, __FUNCTION__, ## args) #if CONFIG_PLATFORM_8711B extern u32 random_seed; #endif #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/aos/aos_osdep.h
C
apache-2.0
3,156
/** * @file * Ethernet Interface Skeleton * */ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels <adam@sics.se> * */ /* * This file is a skeleton for developing Ethernet network interface * drivers for lwIP. Add code to the low_level functions and do a * search-and-replace for the word "ethernetif" to replace it with * something that better describes your network interface. */ #include "lwip/opt.h" #include "lwip/def.h" #include "lwip/mem.h" #include "lwip/pbuf.h" #include "lwip/sys.h" #include "lwip/tcpip.h" #include "lwip/icmp.h" #include "lwip/timeouts.h" #include "netif/etharp.h" #include "lwip/err.h" #include "ethernetif.h" //#include "queue.h" #include "lwip_netconf.h" //#include "lwip/ethip6.h" //Add for ipv6 #include <platform/platform_stdlib.h> #include "platform_opts.h" #if CONFIG_WLAN #include <lwip_intf.h> #endif #if CONFIG_INIC_HOST #include "freertos/inic_intf.h" #endif #define netifMTU (1500) #define netifINTERFACE_TASK_STACK_SIZE ( 350 ) #define netifINTERFACE_TASK_PRIORITY ( configMAX_PRIORITIES - 1 ) #define netifGUARD_BLOCK_TIME ( 250 ) /* The time to block waiting for input. */ #define emacBLOCK_TIME_WAITING_FOR_INPUT ( ( portTickType ) 100 ) #ifdef CONFIG_CONCURRENT_MODE #define IF2NAME0 'r' #define IF2NAME1 '2' #endif static void arp_timer(void *arg); extern int rltk_wlan_send(int idx, struct eth_drv_sg *sg_list, int sg_len, int total_len); extern void rltk_wlan_recv(int idx, struct eth_drv_sg *sg_list, int sg_len); extern unsigned char rltk_wlan_running(unsigned char idx); // interface is up. 0: interface is down extern int netif_get_idx(struct netif *pnetif); extern void rltk_mii_recv(struct eth_drv_sg *sg_list, int sg_len); extern s8 rltk_mii_send(struct eth_drv_sg *sg_list, int sg_len, int total_len); /** * In this function, the hardware should be initialized. * Called from ethernetif_init(). * * @param netif the already initialized lwip network interface structure * for this ethernetif */ static void low_level_init(struct netif *netif) { /* set netif MAC hardware address length */ netif->hwaddr_len = ETHARP_HWADDR_LEN; /* set netif maximum transfer unit */ netif->mtu = 1500; /* Accept broadcast address and ARP traffic */ netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP; #if LWIP_IGMP /* make LwIP_Init do igmp_start to add group 224.0.0.1 */ netif->flags |= NETIF_FLAG_IGMP; #endif /* Wlan interface is initialized later */ } /** * This function should do the actual transmission of the packet. The packet is * contained in the pbuf that is passed to the function. This pbuf * might be chained. * * @param netif the lwip network interface structure for this ethernetif * @param p the MAC packet to send (e.g. IP packet including MAC addresses and type) * @return ERR_OK if the packet could be sent * an err_t value if the packet couldn't be sent * * @note Returning ERR_MEM here if a DMA queue of your MAC is full can lead to * strange results. You might consider waiting for space in the DMA queue * to become availale since the stack doesn't retry to send a packet * dropped because of memory failure (except for the TCP timers). */ static err_t low_level_output(struct netif *netif, struct pbuf *p) { /* Refer to eCos lwip eth_drv_send() */ struct eth_drv_sg sg_list[MAX_ETH_DRV_SG]; int sg_len = 0; struct pbuf *q; #if CONFIG_WLAN if(!rltk_wlan_running(netif_get_idx(netif))) return ERR_IF; #endif for (q = p; q != NULL && sg_len < MAX_ETH_DRV_SG; q = q->next) { sg_list[sg_len].buf = (unsigned int) q->payload; sg_list[sg_len++].len = q->len; } if (sg_len) { #if CONFIG_WLAN if (rltk_wlan_send(netif_get_idx(netif), sg_list, sg_len, p->tot_len) == 0) #elif CONFIG_INIC_HOST if(rltk_inic_send( sg_list, sg_len, p->tot_len) == 0) #else if(1) #endif return ERR_OK; else return ERR_BUF; // return a non-fatal error } return ERR_OK; } /*for ethernet mii interface*/ static err_t low_level_output_mii(struct netif *netif, struct pbuf *p) { struct eth_drv_sg sg_list[MAX_ETH_DRV_SG]; int sg_len = 0; struct pbuf *q; for (q = p; q != NULL && sg_len < MAX_ETH_DRV_SG; q = q->next) { sg_list[sg_len].buf = (unsigned int) q->payload; sg_list[sg_len++].len = q->len; } if (sg_len) { if(rltk_mii_send(sg_list, sg_len, p->tot_len) == 0) return ERR_OK; else return ERR_BUF; // return a non-fatal error } return ERR_OK; } /** * Should allocate a pbuf and transfer the bytes of the incoming * packet from the interface into the pbuf. * * @param netif the lwip network interface structure for this ethernetif * @return a pbuf filled with the received packet (including MAC header) * NULL on memory error */ //static struct pbuf * low_level_input(struct netif *netif){} /** * This function is the ethernetif_input task, it is processed when a packet * is ready to be read from the interface. It uses the function low_level_input() * that should handle the actual reception of bytes from the network * interface. Then the type of the received packet is determined and * the appropriate input function is called. * * @param netif the lwip network interface structure for this ethernetif */ //void ethernetif_input( void * pvParameters ) /* Refer to eCos eth_drv_recv to do similarly in ethernetif_input */ void ethernetif_recv(struct netif *netif, int total_len) { struct eth_drv_sg sg_list[MAX_ETH_DRV_SG]; struct pbuf *p, *q; int sg_len = 0; #if CONFIG_WLAN if(!rltk_wlan_running(netif_get_idx(netif))) return; #endif if ((total_len > MAX_ETH_MSG) || (total_len < 0)) total_len = MAX_ETH_MSG; // Allocate buffer to store received packet p = pbuf_alloc(PBUF_RAW, total_len, PBUF_POOL); if (p == NULL) { printf("\n\rCannot allocate pbuf to receive packet"); return; } // Create scatter list for (q = p; q != NULL && sg_len < MAX_ETH_DRV_SG; q = q->next) { sg_list[sg_len].buf = (unsigned int) q->payload; sg_list[sg_len++].len = q->len; } // Copy received packet to scatter list from wrapper rx skb //printf("\n\rwlan:%c: Recv sg_len: %d, tot_len:%d", netif->name[1],sg_len, total_len); #if CONFIG_WLAN if (sg_len >= MAX_ETH_DRV_SG) { return; } rltk_wlan_recv(netif_get_idx(netif), sg_list, sg_len); #elif CONFIG_INIC_HOST rltk_inic_recv(sg_list, sg_len); #endif // Pass received packet to the interface if (ERR_OK != netif->input(p, netif)) pbuf_free(p); } void ethernetif_mii_recv(struct netif *netif, int total_len) { struct eth_drv_sg sg_list[MAX_ETH_DRV_SG]; struct pbuf *p, *q; int sg_len = 0; if ((total_len > MAX_ETH_MSG) || (total_len < 0)) total_len = MAX_ETH_MSG; // Allocate buffer to store received packet p = pbuf_alloc(PBUF_RAW, total_len, PBUF_POOL); if (p == NULL) { printf("\n\rCannot allocate pbuf to receive packet"); return; } // Create scatter list for (q = p; q != NULL && sg_len < MAX_ETH_DRV_SG; q = q->next) { sg_list[sg_len].buf = (unsigned int) q->payload; sg_list[sg_len++].len = q->len; } rltk_mii_recv(sg_list, sg_len); // Pass received packet to the interface if (ERR_OK != netif->input(p, netif)) pbuf_free(p); } /** * Should be called at the beginning of the program to set up the * network interface. It calls the function low_level_init() to do the * actual setup of the hardware. * * This function should be passed as a parameter to netif_add(). * * @param netif the lwip network interface structure for this ethernetif * @return ERR_OK if the loopif is initialized * ERR_MEM if private data couldn't be allocated * any other err_t on error */ err_t ethernetif_init(struct netif *netif) { LWIP_ASSERT("netif != NULL", (netif != NULL)); #if LWIP_NETIF_HOSTNAME /* Initialize interface hostname */ if(netif->name[1] == '0') netif->hostname = "lwip0"; else if(netif->name[1] == '1') netif->hostname = "lwip1"; #endif /* LWIP_NETIF_HOSTNAME */ netif->output = etharp_output; //#if LWIP_IPV6 // netif->output_ip6 = ethip6_output; //#endif netif->linkoutput = low_level_output; /* initialize the hardware */ low_level_init(netif); etharp_init(); return ERR_OK; } err_t ethernetif_mii_init(struct netif *netif) { LWIP_ASSERT("netif != NULL", (netif != NULL)); #if LWIP_NETIF_HOSTNAME netif->hostname = "lwip2"; #endif /* LWIP_NETIF_HOSTNAME */ netif->output = etharp_output; //#if LWIP_IPV6 // netif->output_ip6 = ethip6_output; //#endif netif->linkoutput = low_level_output_mii; /* initialize the hardware */ low_level_init(netif); etharp_init(); return ERR_OK; } static void arp_timer(void *arg) { etharp_tmr(); sys_timeout(ARP_TMR_INTERVAL, arp_timer, NULL); } /* * For FreeRTOS tickless */ int lwip_tickless_used = 0; #if 0 int arp_timeout_exist(void) { struct sys_timeouts *timeouts; struct sys_timeo *t; timeouts = sys_arch_timeouts(); for(t = timeouts->next; t != NULL;t = t->next) if(t->h == arp_timer) return 1; return 0; } #endif //Called by rltk_wlan_PRE_SLEEP_PROCESSING() void lwip_PRE_SLEEP_PROCESSING(void) { //if(arp_timeout_exist()) { // tcpip_untimeout(arp_timer, NULL); //} lwip_tickless_used = 1; } //Called in ips_leave() path, support tickless when wifi power wakeup due to ioctl or deinit void lwip_POST_SLEEP_PROCESSING(void) { if(lwip_tickless_used) { tcpip_timeout(ARP_TMR_INTERVAL, arp_timer, NULL); } }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/aos/ethernetif.c
C
apache-2.0
10,967
#ifndef __ETHERNETIF_H__ #define __ETHERNETIF_H__ #include "lwip/err.h" #include "lwip/netif.h" //----- ------------------------------------------------------------------ // Ethernet Buffer //----- ------------------------------------------------------------------ struct eth_drv_sg { unsigned int buf; unsigned int len; }; #define MAX_ETH_DRV_SG 32 #define MAX_ETH_MSG 1540 void ethernetif_recv(struct netif *netif, int total_len); err_t ethernetif_init(struct netif *netif); err_t ethernetif_mii_init(struct netif *netif); void lwip_PRE_SLEEP_PROCESSING(void); void lwip_POST_SLEEP_PROCESSING(void); #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/aos/ethernetif.h
C
apache-2.0
625
#ifndef _GPIO_QC_TEST_H #define _GPIO_QC_TEST_H typedef struct { uint8_t output_pin; uint8_t input_pin; } qc_test_gpio_pair_t; #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/aos/gpio_test.h
C
apache-2.0
154
#include <string.h> #include <aos/flashpart.h> #include "ota_port.h" #include "cmsis.h" #include "sys_api.h" #include "rtl8721d_ota.h" int ota_get_bootinfo(struct ota_boot_info *info, enum bootinfo_zone zone) { return 0; } int ota_set_bootinfo_crc32value(struct ota_boot_info *info) { return 0; } int ota_set_bootinfo(struct ota_boot_info *info, enum bootinfo_zone zone) { return 0; } int ota_clear_reboot_count(void) { return 0; } int ota_get_boot_type() { int boot_type = 1; return boot_type; } int ota_get_running_index(void) { return ota_get_cur_index(); } int ota_set_user_bootinfo(void *param) { unsigned char buf[8] = { 0, }; unsigned char signature[8] = { 0x38, 0x31, 0x39, 0x35, 0x38, 0x37, 0x31, 0x31, }; uint32_t part_id; aos_flashpart_ref_t part_ref; aos_status_t r; /* * step1: enable new partition to valid. */ if (ota_get_running_index() == 0) part_id = HAL_PARTITION_OTA_TEMP; else part_id = HAL_PARTITION_APPLICATION; printf("enable partition[%d]'s signature to valid\r\n", (int)part_id); if (aos_flashpart_get(&part_ref, part_id)) { printf("open partition[%d] failed\r\n", (int)part_id); return -1; } r = aos_flashpart_write(&part_ref, 0, signature, sizeof(signature)); step1err: /* * step1 err: now old partition is valid, so return directly. */ aos_flashpart_put(&part_ref); if (r) { printf("%s-%d ret %d\r\n" , __func__, __LINE__, (int)r); return -1; } /* * step2: enable old partition to invalid. */ if (ota_get_running_index() == 0) part_id = HAL_PARTITION_APPLICATION; else part_id = HAL_PARTITION_OTA_TEMP; printf("enable partition[%d]'s signature to invalid\r\n", (int)part_id); if (aos_flashpart_get(&part_ref, part_id)) { printf("open partition[%d] failed\r\n", (int)part_id); goto rollback; } memset(buf, 0 ,sizeof(buf)); r = aos_flashpart_write(&part_ref, 0, buf, sizeof(buf)); if (r) { unsigned char tmp[8]; r = aos_flashpart_read(&part_ref, 0, tmp, sizeof(tmp)); if (r < 0 || r == AOS_FLASH_ECC_ERROR || !memcmp(tmp, signature, sizeof(tmp))) { aos_flashpart_put(&part_ref); goto rollback; } } aos_flashpart_put(&part_ref); return 0; /* * step2 open failed or step2 write is not valid: new partition needs to be rollbacked. */ rollback: if (ota_get_running_index() == 0) part_id = HAL_PARTITION_OTA_TEMP; else part_id = HAL_PARTITION_APPLICATION; printf("rollback partition[%d]\r\n", (int)part_id); /* * rollback: currently not consider exception. */ if (aos_flashpart_get(&part_ref, part_id)) return -1; (void)aos_flashpart_write(&part_ref, 0, buf, sizeof(buf)); aos_flashpart_put(&part_ref); return -1; } int ota_hal_final(void) { return ota_set_user_bootinfo(NULL); } int ota_hal_platform_boot_type(void) { return ota_get_boot_type(); }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/aos/ota_port.c
C
apache-2.0
3,078
/** * Copyright (C) 2019 Alibaba.inc, All rights reserved. * * @file: ota_port.h * @brief: vendor ota interface * @author: * @date: 2019/12/16 * @version: 1.0 */ #ifndef _TG_VENDOR_OTA_H_ #define _TG_VENDOR_OTA_H_ #include <aos/hal/flash.h> #ifdef __cplusplus extern "C" { #endif #define OTA_BOOT_INFO_SIZE 0x1000 #define OTA_BOOT_INFO_HEAD_LEN 4 #define OTA_BOOT_INFO_BODY_LEN 44 #define OTA_LINK_NOTUSED 0 #define OTA_LINK_USED 1 #define OTA_OK 0 #define OTA_FAILE 1 typedef struct { char *bin_name; hal_partition_t partition; } ota_bin_partition; enum bootinfo_zone { OTA_BOOTINFO_ZONEA, OTA_BOOTINFO_ZONEB, OTA_BOOTINFO_ZONEMAX }; typedef enum { ALI_C2H, ALI_C4H, ALI_C5A01, ALI_C1H, ALI_ODM_MAX } ODM_TYPE; enum ota_link { OTA_LINK_ERR = -1, OTA_LINK_A, OTA_LINK_B, OTA_LINK_MAX }; struct ota_boot_info { uint32_t crc32; uint16_t info_len; uint8_t odm_type; uint8_t reserved; uint16_t linkA_used_flag; uint16_t linkB_used_flag; uint16_t update_link; uint8_t crash_reboot_count; uint8_t secureERR_reboot_count; uint16_t reboot_count_max; uint16_t reboot_reason; uint16_t fallback_disable; uint16_t reserved1; // Tool request struct four byte align uint32_t boot2a_addr; uint32_t boot2b_addr; uint32_t rtosa_addr; uint32_t rtosb_addr; uint32_t boot2_len; uint32_t rtos_len; }; int tg_flash_read(const uint32_t addr, uint8_t *dst, const uint32_t size); int ota_adapt_flash_write(const hal_partition_t partition, const uint32_t addr, const uint8_t *src, const uint32_t size); int ota_set_bootinfo_to_zoneAB(struct ota_boot_info *info); enum bootinfo_zone ota_get_valid_bootinfo_zone(void); int ota_get_bootinfo(struct ota_boot_info *info, enum bootinfo_zone zone); ODM_TYPE ota_adapt_get_odm_type(void); int ota_adapt_set_odm_type(ODM_TYPE type); int ota_upgrade_link(void); int ota_set_user_bootinfo(void *param); int ota_clear_reboot_count(void); /** * @brief Get current active A/B slot * * @returns "a" if current slot is A, or "b" if current slot is B. */ const char *tg_ota_get_current_ab(void); /** * @brief To mark that the non-active slot is upgraded successfully. * It's time to set A/B related flag to let system switch to new system until next reboot. * It MAY do two actions: * 1. To set flag to indicate system boot from non-active slot next time. * 2. To enable A/B fallback to old system if new system boot failed * @return: - 0: success; - -1: fail */ int tg_ota_upgrade_end(void); /** * @brief To mark the ota process is finished and present slot is workable, * It called by genie sdk after main boot flow done * @param[in] ab_fallback: 1: enable ab fallback, if it is not enabled; 0, disable ab_fallback. */ void tg_ota_finish(int ab_fallback); int ota_get_running_index(void); #ifdef __cplusplus } #endif #endif /* _TG_VENDOR_OTA_H_ */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/aos/ota_port.h
C
apache-2.0
3,051
#include <sys/unistd.h> #include <sys/errno.h> #include <stdarg.h> #include "aos/hal/flash.h" #include "aos/hal/uart.h" #include "aos/hal/wifi.h" #include "CheckSumUtils.h" #include <wifi/wifi_conf.h> #include <wifi/wifi_util.h> #include <wifi/wifi_ind.h> static uart_dev_t qc_uart; extern uart_dev_t uart_0; #ifndef SERIAL_NUMBER #define SERIAL_NUMBER "UNDF.0000.0000" #endif #ifndef BOOT_VERSION #define BOOT_VERSION "1.0.0" #endif #define WEAK __attribute__((weak)) WEAK char *get_sn(void) { return SERIAL_NUMBER; } void qc_printf(const char *fmt, ...) { va_list ap; char string[128]; va_start(ap, fmt); vsprintf(string, fmt, ap); string[127] = 0; //hal_uart_send(&qc_uart, string, strlen(string), 0); hal_uart_send(&uart_0, string, strlen(string), 0); va_end(ap); } static void qc_scan_completed_event(hal_wifi_module_t *m, hal_wifi_scan_result_t *result, void *arg) { int i; char ssid[33]; ssid[32] = 0; if (result->ap_num <= 0) { qc_printf("Scan AP Fail"); return; } qc_printf( "Scan AP Success:\r\n" ); for (i = 0; i < (result->ap_num); i++) { memcpy(ssid, result->ap_list[i].ssid, 32);// fix ssid len is 32 bytes. qc_printf(" SSID: %s, RSSI: %d\r\n", ssid, result->ap_list[i].ap_power); } } typedef struct _scan_rst_t_ { rtw_scan_result_t result; struct _scan_rst_t_ *next; }mxchip_scan_rst_t; static mxchip_scan_rst_t *p_result_head = NULL; static void free_ap_list(void) { mxchip_scan_rst_t* p, *q; p = p_result_head; p_result_head = NULL; while(p != NULL) { q = p->next; aos_free(p); p = q; } } static void insert_result_by_rssi(rtw_scan_result_t* result) { mxchip_scan_rst_t *p, *next, *prev; /* New BSSID - add it to the list */ p = (mxchip_scan_rst_t*)aos_malloc(sizeof(mxchip_scan_rst_t)); if (p == NULL) { return; } memcpy(&p->result, result, sizeof(rtw_scan_result_t)); p->next = NULL; if (p_result_head == NULL) { p->next = p_result_head; p_result_head = p; goto DONE; } prev = p_result_head; while(prev->next != NULL) { prev = prev->next; } prev->next = p; DONE: return; } static rtw_result_t scan_result_handler( rtw_scan_handler_result_t* malloced_scan_result ) { 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 */ insert_result_by_rssi(record); } else{ mxchip_scan_rst_t *p; rtw_scan_result_t* result; p = p_result_head; if (p == NULL) { qc_printf("Scan AP Fail\r\n"); return RTW_SUCCESS; } while (p!=NULL) { result = &p->result; qc_printf(" SSID: %s, RSSI: %d\r\n", result->SSID.val, result->signal_strength); p = p->next; } free_ap_list(); } return RTW_SUCCESS; } static void qc_scan(void) { int ret; hal_wifi_module_t *module; uint8_t mac[6]; module = hal_wifi_get_default_module(); hal_wifi_get_mac_addr(module, mac ); qc_printf( "MAC:%02X-%02X-%02X-%02X-%02X-%02X\r\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5] ); ret = wifi_scan_networks(scan_result_handler, NULL); if (ret != RTW_SUCCESS) { qc_printf("Scan AP Fail\r\n"); } } static char *get_bootloader_ver(void) { return BOOT_VERSION; } static uint16_t qc_crc(void) { hal_logic_partition_t* part; int total_len, len, offset=0; uint8_t data[1024]; CRC16_Context contex; uint16_t crc = 0; CRC16_Init( &contex ); part = hal_flash_get_info((hal_partition_t)HAL_PARTITION_APPLICATION); total_len = part->partition_length; while(total_len > 0){ if( 1024 < total_len ){ len = 1024; } else { len = total_len; } hal_flash_read( HAL_PARTITION_APPLICATION, &offset, data , len); total_len -= len; CRC16_Update( &contex, data, len ); } CRC16_Final( &contex, &crc ); } void qc_test(void) { uint8_t mac[6]; uint32_t prov_res, ret; printf( "\r\n" ); qc_uart.port = 4; qc_uart.config.baud_rate = 921600; qc_uart.config.data_width = DATA_WIDTH_8BIT; qc_uart.config.parity = NO_PARITY; qc_uart.config.stop_bits = STOP_BITS_1; qc_uart.config.flow_control = FLOW_CONTROL_DISABLED; //hal_uart_init(&qc_uart); qc_printf( "==== MXCHIP Manufacture Test ====\r\n" ); qc_printf( "Serial Number: %s\r\n", get_sn() ); qc_printf( "App CRC: %04X\r\n", qc_crc() ); qc_printf( "Bootloader Version: %s\r\n", get_bootloader_ver() ); // GPIO test qc_test_gpio(); // BLE test bt_get_mac_address(mac); qc_printf( "Local Bluetooth Address: %02X-%02X-%02X-%02X-%02X-%02X\r\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5] ); qc_scan(); while(1) {// dead loop, DONOT exit QC mode aos_msleep(1000); hal_wdg_reload(NULL); } }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/aos/qc.c
C
apache-2.0
5,234
#include "aos/hal/gpio.h" #include "gpio_test.h" /****************************************************** * Variables Definitions ******************************************************/ extern const qc_test_gpio_pair_t qc_test_gpio_pairs[]; extern const int qc_test_gpio_pairs_num; static int gpio_result = 0; /****************************************************** * Function Definitions ******************************************************/ static int _gpio_test_one( const qc_test_gpio_pair_t* gpio_test_pair ) { gpio_dev_t gpio_out; gpio_dev_t gpio_in; int ret=-1, val; gpio_out.port = gpio_test_pair->output_pin; gpio_out.config = OUTPUT_PUSH_PULL; gpio_in.port = gpio_test_pair->input_pin; gpio_in.config = INPUT_PULL_DOWN; hal_gpio_init(&gpio_out); hal_gpio_init(&gpio_in); hal_gpio_output_high(&gpio_out); aos_msleep(1); hal_gpio_input_get(&gpio_in, &val); if (val != 1) goto EXIT; gpio_in.config = INPUT_PULL_UP; hal_gpio_init(&gpio_in); hal_gpio_output_low(&gpio_out); aos_msleep(1); hal_gpio_input_get(&gpio_in, &val); if (val != 0) goto EXIT; ret = 0; EXIT: hal_gpio_deinit(&gpio_out); hal_gpio_deinit(&gpio_in); return ret; } static int _gpio_test( const qc_test_gpio_pair_t* gpio_test_pair, int num ) { int i; int err = 0; qc_test_gpio_pair_t * gpio_test = (qc_test_gpio_pair_t *)gpio_test_pair; gpio_result = 0; for ( i = 0; i < num; i++ ) { if ( 0 == _gpio_test_one( &gpio_test_pair[i] ) ) { gpio_result |= (1 << i); } else { err = -1; } } return err; } void qc_test_gpio( void ) { char test_result[32]; int gpio_num = 0; if (qc_test_gpio_pairs_num == 0) return; if ( 0 == _gpio_test( qc_test_gpio_pairs, qc_test_gpio_pairs_num ) ) { qc_printf( "GPIO TEST: PASS\r\n" ); } else { sprintf( test_result, "Fail: %d:%x", gpio_num, gpio_result ); qc_printf( "GPIO TEST: %s\r\n", test_result ); } return; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/aos/qc_gpio_test.c
C
apache-2.0
2,263
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <k_api.h> #include <assert.h> #include <stdio.h> #include <sys/time.h> #include "diag.h" #include "ameba_soc.h" #include "build_info.h" //#include "strproc.h" #include "rtl8721d_system.h" #if AOS_COMP_CLI #include "aos/cli.h" #endif float soc_hr_hw_freq_mhz(void) { return (SystemGetCpuClk()/1000000); } uint32_t hal_sys_timer_calc_cpu_freq(uint32_t interval_ms, int high_res) { (void)interval_ms; (void)high_res; return SystemGetCpuClk(); } #if (RHINO_CONFIG_HW_COUNT > 0) void soc_hw_timer_init(void) { uint32_t temp = (uint32_t)(0xFFFFFFFF / 1000000 * 32768); RTIM_ChangePeriodImmediate(TIMx[0], temp); RTIM_INTConfig(TIMx[0], TIM_IT_Update, ENABLE); RTIM_Cmd(TIMx[0], ENABLE); } hr_timer_t soc_hr_hw_cnt_get(void) { uint32_t tick; RTIM_TypeDef *TIM = TIMx[0]; tick = RTIM_GetCount(TIM); return tick; } uint64_t soc_hr_hw_freq_get(void) { return 32768; } lr_timer_t soc_lr_hw_cnt_get(void) { uint32_t tick; RTIM_TypeDef *TIM = TIMx[0]; tick = RTIM_GetCount(TIM); return tick; } #endif /* RHINO_CONFIG_HW_COUNT */ #if (RHINO_CONFIG_INTRPT_STACK_OVF_CHECK > 0) void soc_intrpt_stack_ovf_check(void) { } #endif #if (RHINO_CONFIG_MM_TLF > 0) #if !defined (__CC_ARM) /* Keil / armcc */ extern void *heap_start; extern void *heap_end; extern void *heap_len; //extern void *heap2_start; //extern void *heap2_len; #endif //#include "section_config.h" //SRAM_BF_DATA_SECTION //#endif //static unsigned char ucHeap[ configTOTAL_HEAP_SIZE ]; #if defined (__CC_ARM) /* Keil / armcc */ #define HEAP_BUFFER_SIZE 1024*60 uint8_t g_heap_buf[HEAP_BUFFER_SIZE]; k_mm_region_t g_mm_region[] = {{g_heap_buf, HEAP_BUFFER_SIZE}, {(uint8_t *)0x10000000, 0x8000}}; #else #define configTOTAL_PSRAM_HEAP_SIZE (0x400000 - 0x20000) PSRAM_HEAP_SECTION static unsigned char psRAMHeap[configTOTAL_PSRAM_HEAP_SIZE]; k_mm_region_t g_mm_region[2] = {{(uint8_t*)&heap_start,(size_t)&heap_len}, {(uint8_t*)psRAMHeap,(size_t)configTOTAL_PSRAM_HEAP_SIZE}, }; //, // {(uint8_t*)MM_ALIGN_UP(0x100014f9), MM_ALIGN_DOWN(0xb07)}, // {(uint8_t*)MM_ALIGN_UP(0x10002475), MM_ALIGN_DOWN(0x2b8b)}}; #endif int g_region_num = sizeof(g_mm_region)/sizeof(k_mm_region_t); #endif extern void hal_reboot(void); void soc_err_proc(kstat_t err) { DBG_8195A("soc_err_proc : %d\n\r", err); if ( RHINO_NO_MEM == err ) { /* while mem not enought, reboot */ hal_reboot(); } } krhino_err_proc_t g_err_proc = soc_err_proc; /* use for printk */ int alios_debug_print(const char *buf, int size) { int i; for (i = 0; i < size; i++) { DiagPutChar(*buf++); } return 0; } char uart_input_read(void) { return DiagGetChar(1); } /* check pc available 0:available other:not available */ extern uint8_t __flash_text_start__[]; extern uint8_t __flash_text_end__[]; extern uint8_t __ram_image2_text_start__[]; extern uint8_t __ram_image2_text_end__[]; int alios_debug_pc_check(char *pc) { if ((((uint32_t)pc > (uint32_t)__flash_text_start__) && ((uint32_t)pc < (uint32_t)__flash_text_end__)) || (((uint32_t)pc > (uint32_t)__ram_image2_text_start__) && ((uint32_t)pc < (uint32_t)__ram_image2_text_end__))) { return 0; } else { return -1; } } #if AOS_COMP_CLI void alios_debug_pc_show(int argc, char **argv) { aos_cli_printf("----- PC Addr ------\r\n"); aos_cli_printf("addr 1 : 0x%08X ~ 0x%08X\r\n", (uint32_t)__flash_text_start__, (uint32_t)__flash_text_end__); aos_cli_printf("addr 2 : 0x%08X ~ 0x%08X\r\n", (uint32_t)__ram_image2_text_start__, (uint32_t)__ram_image2_text_end__); } #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/aos/soc_impl.c
C
apache-2.0
3,938
/* * Copyright (C) 2020-2021 Alibaba Group Holding Limited */ #include <aos/flash_core.h> #include <objects.h> #include <PinNames.h> #include <pinmap.h> #include <ameba_soc.h> #include <drv/spiflash.h> typedef struct { aos_flash_t flash; uint32_t page_data_buf[256 / sizeof(uint32_t)]; } flash_rtl872xd_t; static void flash_unregister(aos_flash_t *flash) { } static aos_status_t flash_startup(aos_flash_t *flash) { return 0; } static void flash_shutdown(aos_flash_t *flash) { } static aos_status_t flash_read_page(aos_flash_t *flash, uint64_t page, size_t data_offset, size_t data_count, size_t spare_offset, size_t spare_count) { uint32_t offset = (uint32_t)(page * flash->page_data_size + data_offset); uint32_t offset_aligned = offset & ~(uint32_t)0x3; uint32_t end = offset + (uint32_t)data_count; uint32_t data_offset_aligned = (uint32_t)data_offset & ~(uint32_t)0x3; FLASH_Write_Lock(); for (uint32_t i = 0; offset_aligned + i < end; i += 4) { uint32_t *dst = (uint32_t *)&((uint8_t *)flash->page_data_buf)[data_offset_aligned + i]; *dst = HAL_READ32(SPI_FLASH_BASE, offset_aligned + i); } FLASH_Write_Unlock(); return 0; } static aos_status_t flash_write_page(aos_flash_t *flash, uint64_t page, size_t data_offset, size_t data_count, size_t spare_offset, size_t spare_count) { uint32_t offset = (uint32_t)(page * flash->page_data_size + data_offset); uint32_t offset_aligned = offset & ~(uint32_t)0x3; uint32_t end = offset + (uint32_t)data_count; uint32_t end_aligned = end & ~(uint32_t)0x3; uint32_t data_offset_aligned = (uint32_t)data_offset & ~(uint32_t)0x3; uint32_t data_end = (uint32_t)data_offset & ~(uint32_t)0x3; uint32_t data_end_aligned = data_end & ~(uint32_t)0x3; FLASH_Write_Lock(); if (offset_aligned != offset) { union { uint8_t u8[4]; uint32_t u32; } tmp; tmp.u32 = HAL_READ32(SPI_FLASH_BASE, offset_aligned); for (uint32_t i = 0; data_offset_aligned + i < data_offset; i++) ((uint8_t *)flash->page_data_buf)[data_offset_aligned + i] = tmp.u8[i]; } if (end_aligned != end) { union { uint8_t u8[4]; uint32_t u32; } tmp; tmp.u32 = HAL_READ32(SPI_FLASH_BASE, end_aligned); for (uint32_t i = data_end & ~(uint32_t)0x3; i < 4; i++) ((uint8_t *)flash->page_data_buf)[data_end_aligned + i] = tmp.u8[i]; } for (uint32_t i = 0; offset_aligned + i < end; i += 4) FLASH_TxData12B(offset_aligned + i, 4, &((uint8_t *)flash->page_data_buf)[data_offset_aligned + i]); FLASH_Write_Unlock(); return 0; } static aos_status_t flash_erase_block(aos_flash_t *flash, uint64_t block) { uint32_t block_size = (uint32_t)(flash->pages_per_block * flash->page_data_size); uint32_t offset = (uint32_t)(block * block_size); FLASH_Write_Lock(); FLASH_Erase(EraseSector, offset); DCache_Invalidate(SPI_FLASH_BASE + offset, block_size); FLASH_Write_Unlock(); return 0; } static const aos_flash_ops_t flash_rtl872xd_ops = { .unregister = flash_unregister, .startup = flash_startup, .shutdown = flash_shutdown, .read_page = flash_read_page, .write_page = flash_write_page, .erase_block = flash_erase_block, .is_bad_block = NULL, .mark_bad_block = NULL, }; static aos_status_t flash_rtl872xd_register(flash_rtl872xd_t *flash_rtl872xd) { if (!flash_rtl872xd) return -EINVAL; flash_rtl872xd->flash.ops = &flash_rtl872xd_ops; flash_rtl872xd->flash.flags = AOS_FLASH_F_TYPE_NOR; flash_rtl872xd->flash.block_count = 1024; flash_rtl872xd->flash.pages_per_block = 16; flash_rtl872xd->flash.page_data_size = sizeof(flash_rtl872xd->page_data_buf); flash_rtl872xd->flash.page_spare_size = 0; flash_rtl872xd->flash.page_data_buf = flash_rtl872xd->page_data_buf; flash_rtl872xd->flash.page_spare_buf = NULL; return aos_flash_register(&flash_rtl872xd->flash); } static int flash_rtl872xd_init(void) { static flash_rtl872xd_t flash_rtl872xd; flash_rtl872xd.flash.dev.id = 0; return (int)flash_rtl872xd_register(&flash_rtl872xd); } LEVEL1_DRIVER_ENTRY(flash_rtl872xd_init)
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/aos_adapter/flash.c
C
apache-2.0
4,372
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <drv/pwm.h> #include <aos/pwm_core.h> #include "device.h" #include "objects.h" #include "pinmap.h" #define BIT_PWM_TIM_IDX_FLAG BIT(7) #define BIT_PWM_TIM_IDX_SHIFT 7 #define PWM_TIMER 5 #define DIV_ROUND_CLOSEST(x, divisor)( \ { \ typeof(x) __x = x; \ typeof(divisor) __d = divisor; \ (((typeof(x))-1) > 0 || \ ((typeof(divisor))-1) > 0 || \ (((__x) > 0) == ((__d) > 0))) ? \ (((__x) + ((__d) / 2)) / (__d)) : \ (((__x) - ((__d) / 2)) / (__d)); \ } \ ) typedef struct { aos_pwm_t aos_pwm; uint8_t idx; void *priv; } rtl872xd_pwm_t; /* Table elements express the pin to PWM channel number, they are: * {pinName, km0_pin2chan, km4_pin2chan} */ static const u32 pin2chan[18][2] = { { PA_12, 0 }, { PA_13, 1 }, { PA_23, 2 }, { PA_24, 3 }, { PA_25, 4 }, { PA_26, 5 }, { PA_28, 6 }, { PA_30, 7 }, { PB_4, 8 }, { PB_5, 9 }, { PB_18, 10 }, { PB_19, 11 }, { PB_20, 12 }, { PB_21, 13 }, { PB_22, 14 }, { PB_23, 15 }, { PB_24, 16 }, { PB_7, 17 } // this channel also can be PB_7 }; static RTIM_TypeDef *RTL872xD_PWM_TIM[2] = { TIM5, TIMM05 }; static u8 km4_ch_start[18] = { 0 }; static void rtl872xd_pwm_uninit(rtl872xd_pwm_t *pwm_dev) { uint32_t pwm_chan = pwm_dev->idx & (~BIT_PWM_TIM_IDX_FLAG); uint8_t pwm_tim_idx = pwm_dev->idx >> BIT_PWM_TIM_IDX_SHIFT; if (km4_ch_start[pwm_chan]) { km4_ch_start[pwm_chan] = 0; RTIM_CCxCmd(RTL872xD_PWM_TIM[pwm_tim_idx], pwm_chan, TIM_CCx_Disable); /* stop timer5 if no pwm channels starts */ for (pwm_chan = 0; pwm_chan < 18; pwm_chan++) { if (km4_ch_start[pwm_chan]) { return; } } RTIM_Cmd(RTL872xD_PWM_TIM[pwm_tim_idx], DISABLE); } if (pwm_dev && pwm_dev->priv) { free(pwm_dev->priv); pwm_dev->priv = NULL; } } static int rtl872xd_pwm_out_config(rtl872xd_pwm_t *pwm_dev, uint32_t channel, uint32_t period_ns, uint32_t pulse_width_ns, csi_pwm_polarity_t polarity) { uint32_t arr, tmp, ccrx; uint32_t period; float pulse, value, dc; uint8_t pwm_tim_idx = pwm_dev->idx >> BIT_PWM_TIM_IDX_SHIFT; TIM_CCInitTypeDef *TIM_CCInitStruct = (TIM_CCInitTypeDef *)pwm_dev->priv; u32 prescaler = 0; if (channel > 18) { return 0; } RTIM_CCStructInit(TIM_CCInitStruct); RTIM_CCxInit(RTL872xD_PWM_TIM[pwm_tim_idx], TIM_CCInitStruct, channel); RTIM_CCxCmd(RTL872xD_PWM_TIM[pwm_tim_idx], channel, TIM_CCx_Enable); PinName pin = pin2chan[channel][0]; if (km4_ch_start[channel] == 0) { if (pwm_tim_idx) { Pinmux_Config(pin, PINMUX_FUNCTION_PWM_LP); } else { Pinmux_Config(pin, PINMUX_FUNCTION_PWM_HS); } } km4_ch_start[channel] = 1; tmp = DIV_ROUND_CLOSEST(((uint64_t)period_ns * 40), 1000); tmp = tmp / (prescaler + 1); /* * psr is 8bits */ if (tmp > 0x10000) { prescaler = DIV_ROUND_CLOSEST(((uint64_t)period_ns * 40), 1000); prescaler = DIV_ROUND_CLOSEST(prescaler, 0x10000); if (prescaler > 0xff) { prescaler = 0xff; } RTIM_PrescalerConfig(RTL872xD_PWM_TIM[pwm_tim_idx], prescaler, TIM_PSCReloadMode_Update); } /* * arr is 16bits */ /* * 40M oscilator */ arr = DIV_ROUND_CLOSEST(((uint64_t)period_ns * 40), 1000); arr = DIV_ROUND_CLOSEST(arr, (prescaler + 1)) - 1; if (arr > 0xffff) { arr = 0xffff; } RTIM_ChangePeriod(RTL872xD_PWM_TIM[pwm_tim_idx], arr); ccrx = DIV_ROUND_CLOSEST(((uint64_t)(period_ns - pulse_width_ns) * 40), 1000); ccrx = (ccrx / (prescaler + 1)) & 0x0000ffff; RTIM_CCRxSet(RTL872xD_PWM_TIM[pwm_tim_idx], ccrx, channel); if (0 == polarity) RTIM_CCxPolarityConfig(RTL872xD_PWM_TIM[pwm_tim_idx], TIM_CCPolarity_Low, channel); else RTIM_CCxPolarityConfig(RTL872xD_PWM_TIM[pwm_tim_idx], TIM_CCPolarity_High, channel); return 0; } static int rtl872xd_pwm_out_start(rtl872xd_pwm_t *pwm_dev, uint32_t channel) { uint32_t pwm_chan = channel; uint8_t pwm_tim_idx = pwm_dev->idx >> BIT_PWM_TIM_IDX_SHIFT; RTIM_CCxCmd(RTL872xD_PWM_TIM[pwm_tim_idx], pwm_chan, TIM_CCx_Enable); return 0; } static int rtl872xd_pwm_out_stop(rtl872xd_pwm_t *pwm_dev, uint32_t channel) { uint32_t pwm_chan = channel; uint8_t pwm_tim_idx = pwm_dev->idx >> BIT_PWM_TIM_IDX_SHIFT; RTIM_CCxCmd(RTL872xD_PWM_TIM[pwm_tim_idx], pwm_chan, TIM_CCx_Disable); return 0; } static void rtl872xd_pwm_unregister(aos_pwm_t *pwm) { rtl872xd_pwm_t *pwm_dev = aos_container_of(pwm, rtl872xd_pwm_t, aos_pwm); rtl872xd_pwm_uninit(pwm_dev); } static int rtl872xd_pwm_startup(aos_pwm_t *pwm) { return 0; } static void rtl872xd_pwm_shutdown(aos_pwm_t *pwm) { rtl872xd_pwm_t *pwm_dev = aos_container_of(pwm, rtl872xd_pwm_t, aos_pwm); rtl872xd_pwm_out_stop(pwm_dev, pwm_dev->aos_pwm.dev.id); } static int rtl872xd_pwm_apply(aos_pwm_t *pwm, aos_pwm_attr_t const *attr) { uint32_t period; uint32_t duty_cycle; rtl872xd_pwm_t *pwm_dev = aos_container_of(pwm, rtl872xd_pwm_t, aos_pwm); period = attr->period; duty_cycle = attr->duty_cycle; rtl872xd_pwm_out_config(pwm_dev, pwm_dev->aos_pwm.dev.id, period, duty_cycle, attr->polarity); if (attr->enabled) rtl872xd_pwm_out_start(pwm_dev, pwm_dev->aos_pwm.dev.id); else rtl872xd_pwm_out_stop(pwm_dev, pwm_dev->aos_pwm.dev.id); return 0; } static const aos_pwm_ops_t rtl872xd_pwm_ops = { .unregister = rtl872xd_pwm_unregister, .apply = rtl872xd_pwm_apply, .shutdown = rtl872xd_pwm_shutdown, .startup = rtl872xd_pwm_startup }; static int rtl872xd_pwm_init(void) { int ret; static rtl872xd_pwm_t pwm_dev[CONFIG_PWM_NUM]; int idx = 0, i; RTIM_TimeBaseInitTypeDef TIM_InitStruct; RTIM_TimeBaseStructInit(&TIM_InitStruct); TIM_InitStruct.TIM_Idx = PWM_TIMER; RTIM_TimeBaseInit(RTL872xD_PWM_TIM[idx], &TIM_InitStruct, TIMER5_IRQ, NULL, (u32)&TIM_InitStruct); RTIM_Cmd(RTL872xD_PWM_TIM[idx], ENABLE); for (i = 0; i < CONFIG_PWM_NUM; i++) { pwm_dev[i].priv = (TIM_CCInitTypeDef *)malloc(sizeof(TIM_CCInitTypeDef)); pwm_dev[i].idx = idx << BIT_PWM_TIM_IDX_SHIFT; pwm_dev[i].idx |= (i) & (~BIT_PWM_TIM_IDX_FLAG); if (ret != 0) { return ret; } pwm_dev[i].aos_pwm.dev.id = i; pwm_dev[i].aos_pwm.ops = &rtl872xd_pwm_ops; ret = aos_pwm_register(&(pwm_dev[i].aos_pwm)); if (ret != 0) { return ret; } } return 0; } LEVEL1_DRIVER_ENTRY(rtl872xd_pwm_init)
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/aos_adapter/pwm.c
C
apache-2.0
7,052
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <objects.h> #include <pinmap.h> #include <drv/uart.h> #include <aos/tty_core.h> typedef struct { aos_tty_t tty; UART_InitTypeDef params; uint8_t ier; } tty_uart_t; static const PinMap CSI_PinMap_UART_TX[] = { { PA_12, UART_3, PIN_DATA(PullUp, PINMUX_FUNCTION_UART), }, { PA_18, UART_0, PIN_DATA(PullUp, PINMUX_FUNCTION_UART), }, { PA_7, UART_2, PIN_DATA(PullUp, PINMUX_FUNCTION_LOGUART), }, { NC, NC, 0, }, }; static const PinMap CSI_PinMap_UART_RX[] = { { PA_13, UART_3, PIN_DATA(PullUp, PINMUX_FUNCTION_UART), }, { PA_19, UART_0, PIN_DATA(PullUp, PINMUX_FUNCTION_UART), }, { PA_8, UART_2, PIN_DATA(PullUp, PINMUX_FUNCTION_LOGUART), }, { NC, NC, 0, }, }; static PinName uart_tx_pin_get(uint32_t uart_idx, const PinMap *map) { PinName tx; while (map->peripheral != NC) { if (map->peripheral == uart_idx) { tx = map->pin; break; } map++; } return tx; } static PinName uart_rx_pin_get(uint32_t uart_idx, const PinMap *map) { PinName rx; while (map->peripheral != NC) { if (map->peripheral == uart_idx) { rx = map->pin; break; } map++; } return rx; } static uint32_t uart_idx_get(uint32_t idx) { if (idx == 0) return UART_0; else if (idx == 2) return UART_2; else if (idx == 3) return UART_3; else assert_param(0); return UART_1; } static aos_status_t termios2params(const struct termios *termios, UART_InitTypeDef *params, uint32_t *baudrate) { switch (termios->c_cflag & CSIZE) { case CS7: params->WordLen = RUART_WLS_7BITS; break; case CS8: params->WordLen = RUART_WLS_8BITS; break; default: return -EINVAL; } if (termios->c_cflag & CSTOPB) params->StopBit = RUART_STOP_BIT_2; else params->StopBit = RUART_STOP_BIT_1; if (termios->c_cflag & PARENB) { params->Parity = RUART_PARITY_ENABLE; params->ParityType = (termios->c_cflag & PARODD) ? RUART_ODD_PARITY : RUART_EVEN_PARITY; } else { params->Parity = RUART_PARITY_DISABLE; } switch (termios->c_cflag & CBAUD) { case B50: *baudrate = 50; break; case B75: *baudrate = 75; break; case B110: *baudrate = 110; break; case B134: *baudrate = 134; break; case B150: *baudrate = 150; break; case B200: *baudrate = 200; break; case B300: *baudrate = 300; break; case B600: *baudrate = 600; break; case B1200: *baudrate = 1200; break; case B1800: *baudrate = 1800; break; case B2400: *baudrate = 2400; break; case B4800: *baudrate = 4800; break; case B9600: *baudrate = 9600; break; case B19200: *baudrate = 19200; break; case B38400: *baudrate = 38400; break; case B57600: *baudrate = 57600; break; case B115200: *baudrate = 115200; break; case B230400: *baudrate = 230400; break; case B460800: *baudrate = 460800; break; case B500000: *baudrate = 500000; break; case B576000: *baudrate = 576000; break; case B921600: *baudrate = 921600; break; case B1000000: *baudrate = 1000000; break; case B1152000: *baudrate = 1152000; break; case B1500000: *baudrate = 1500000; break; case B2000000: *baudrate = 2000000; break; case B2500000: *baudrate = 2500000; break; case B3000000: *baudrate = 3000000; break; case B3500000: *baudrate = 3500000; break; case B4000000: *baudrate = 4000000; break; default: return -EINVAL; } return 0; } static void uart_rx_irq_handler(tty_uart_t *tty_uart) { aos_tty_t *tty = &tty_uart->tty; UART_TypeDef *uart = UART_DEV_TABLE[tty->dev.id].UARTx; const size_t rx_fifo_depth = 16; uint8_t buf[rx_fifo_depth]; size_t i; for (i = 0; i < rx_fifo_depth; i++) { if (!UART_Readable(uart)) break; UART_CharGet(uart, &buf[i]); } if (i > 0) (void)aos_tty_rx_buffer_produce(tty, buf, i); } static uint32_t uart_irq_handler(void *data) { tty_uart_t *tty_uart = (tty_uart_t *)data; aos_tty_t *tty = &tty_uart->tty; UART_TypeDef *uart = UART_DEV_TABLE[tty->dev.id].UARTx; uint8_t iir; uint8_t val; aos_irqsave_t flags; flags = aos_spin_lock_irqsave(&tty->lock); iir = UART_IntStatus(uart); if (iir & RUART_IIR_INT_PEND) { aos_spin_unlock_irqrestore(&tty->lock, flags); return 0; } switch ((iir & RUART_IIR_INT_ID) >> 1) { case RUART_LP_RX_MONITOR_DONE: if (!(tty_uart->ier & RUART_IER_EDMI)) break; val = UART_RxMonitorSatusGet(uart); break; case RUART_MODEM_STATUS: if (!(tty_uart->ier & RUART_IER_EDSSI)) break; val = UART_ModemStatusGet(uart); break; case RUART_RECEIVE_LINE_STATUS: if (!(tty_uart->ier & RUART_IER_ELSI)) break; val = UART_LineStatusGet(uart); break; case RUART_TX_FIFO_EMPTY: if (!(tty_uart->ier & RUART_IER_ETBEI)) break; if (UART_LineStatusGet(uart) & RUART_LINE_STATUS_REG_THRE) { const size_t tx_fifo_depth = 16; uint8_t buf[tx_fifo_depth]; size_t count = aos_tty_tx_buffer_consume(tty, buf, tx_fifo_depth); for (size_t i = 0; i < count; i++) UART_CharPut(uart, buf[i]); if (count == 0) { tty_uart->ier &= ~RUART_IER_ETBEI; UART_INTConfig(uart, RUART_IER_ETBEI, DISABLE); } } break; case RUART_RECEIVER_DATA_AVAILABLE: if (!(tty_uart->ier & RUART_IER_ERBI)) break; uart_rx_irq_handler(tty_uart); break; case RUART_TIME_OUT_INDICATION: if (!(tty_uart->ier & RUART_IER_ETOI)) break; uart_rx_irq_handler(tty_uart); break; default: break; } aos_spin_unlock_irqrestore(&tty->lock, flags); return 0; } static void uart_unregister(aos_tty_t *tty) { } static aos_status_t uart_startup(aos_tty_t *tty) { tty_uart_t *tty_uart = aos_container_of(tty, tty_uart_t, tty); UART_TypeDef *uart = UART_DEV_TABLE[tty->dev.id].UARTx; IRQn_Type irq = UART_DEV_TABLE[tty->dev.id].IrqNum; uint32_t uart_idx = uart_idx_get(tty->dev.id); PinName tx_pin = uart_tx_pin_get(uart_idx, CSI_PinMap_UART_TX); PinName rx_pin = uart_rx_pin_get(uart_idx, CSI_PinMap_UART_RX); UART_InitTypeDef params; uint32_t baudrate; aos_status_t ret; UART_StructInit(&params); ret = termios2params(&tty->termios, &params, &baudrate); if (ret) return ret; tty_uart->params = params; pinmap_pinout(tx_pin, CSI_PinMap_UART_TX); pinmap_pinout(rx_pin, CSI_PinMap_UART_RX); pin_mode(tx_pin, PullUp); pin_mode(rx_pin, PullUp); UART_Init(uart, &params); UART_SetRxLevel(uart, UART_RX_FIFOTRIG_LEVEL_8BYTES); uart->LCR = (params.WordLen << 0) | (params.StopBit << 2) | (params.Parity << 3) | (params.ParityType << 4) | (params.StickParity << 5); RCC_PeriphClockSource_UART(uart, UART_RX_CLK_XTAL_40M); UART_SetBaud(uart, baudrate); if (baudrate <= 500000 && uart_config[tty->dev.id].LOW_POWER_RX_ENABLE) { UART_MonitorParaConfig(uart, 100, ENABLE); UART_RxMonitorCmd(uart, ENABLE); RCC_PeriphClockSource_UART(uart, UART_RX_CLK_OSC_LP); UART_LPRxBaudSet(uart, baudrate, 2000000); } tty_uart->ier = 0; InterruptRegister(uart_irq_handler, irq, (uint32_t)tty_uart, 5); InterruptEn(irq, 5); return 0; } static void uart_shutdown(aos_tty_t *tty) { UART_TypeDef *uart = UART_DEV_TABLE[tty->dev.id].UARTx; IRQn_Type irq = UART_DEV_TABLE[tty->dev.id].IrqNum; InterruptDis(irq); InterruptUnRegister(irq); UART_DeInit(uart); } static aos_status_t uart_set_attr(aos_tty_t *tty) { tty_uart_t *tty_uart = aos_container_of(tty, tty_uart_t, tty); UART_TypeDef *uart = UART_DEV_TABLE[tty->dev.id].UARTx; UART_InitTypeDef params = tty_uart->params; uint32_t baudrate; aos_status_t ret; ret = termios2params(&tty->termios, &params, &baudrate); if (ret) return ret; tty_uart->params = params; uart->LCR = (params.WordLen << 0) | (params.StopBit << 2) | (params.Parity << 3) | (params.ParityType << 4) | (params.StickParity << 5); RCC_PeriphClockSource_UART(uart, UART_RX_CLK_XTAL_40M); UART_SetBaud(uart, baudrate); if (baudrate <= 500000 && uart_config[tty->dev.id].LOW_POWER_RX_ENABLE) { UART_MonitorParaConfig(uart, 100, ENABLE); UART_RxMonitorCmd(uart, ENABLE); RCC_PeriphClockSource_UART(uart, UART_RX_CLK_OSC_LP); UART_LPRxBaudSet(uart, baudrate, 2000000); } return 0; } static void uart_enable_rx(aos_tty_t *tty) { tty_uart_t *tty_uart = aos_container_of(tty, tty_uart_t, tty); UART_TypeDef *uart = UART_DEV_TABLE[tty->dev.id].UARTx; aos_irqsave_t flags; UART_RxCmd(uart, ENABLE); flags = aos_spin_lock_irqsave(&tty->lock); tty_uart->ier |= RUART_IER_ERBI | RUART_IER_ELSI | RUART_IER_ETOI; UART_INTConfig(uart, RUART_IER_ERBI | RUART_IER_ELSI | RUART_IER_ETOI, ENABLE); aos_spin_unlock_irqrestore(&tty->lock, flags); } static void uart_disable_rx(aos_tty_t *tty) { tty_uart_t *tty_uart = aos_container_of(tty, tty_uart_t, tty); UART_TypeDef *uart = UART_DEV_TABLE[tty->dev.id].UARTx; aos_irqsave_t flags; flags = aos_spin_lock_irqsave(&tty->lock); tty_uart->ier &= ~(RUART_IER_ERBI | RUART_IER_ELSI | RUART_IER_ETOI); UART_INTConfig(uart, RUART_IER_ERBI | RUART_IER_ELSI | RUART_IER_ETOI, DISABLE); aos_spin_unlock_irqrestore(&tty->lock, flags); UART_RxCmd(uart, DISABLE); UART_ClearRxFifo(uart); } static void uart_start_tx(aos_tty_t *tty) { tty_uart_t *tty_uart = aos_container_of(tty, tty_uart_t, tty); UART_TypeDef *uart = UART_DEV_TABLE[tty->dev.id].UARTx; tty_uart->ier |= RUART_IER_ETBEI; UART_INTConfig(uart, RUART_IER_ETBEI, ENABLE); } static void uart_stop_tx(aos_tty_t *tty) { tty_uart_t *tty_uart = aos_container_of(tty, tty_uart_t, tty); UART_TypeDef *uart = UART_DEV_TABLE[tty->dev.id].UARTx; aos_irqsave_t flags; flags = aos_spin_lock_irqsave(&tty->lock); tty_uart->ier &= ~RUART_IER_ETBEI; UART_INTConfig(uart, RUART_IER_ETBEI, DISABLE); aos_spin_unlock_irqrestore(&tty->lock, flags); for (int i = 0; i < 10; i++) { if (UART_LineStatusGet(uart) & RUART_LINE_STATUS_REG_TEMT) break; aos_msleep(20); } } static const aos_tty_ops_t tty_uart_ops = { .unregister = uart_unregister, .startup = uart_startup, .shutdown = uart_shutdown, .set_attr = uart_set_attr, .enable_rx = uart_enable_rx, .disable_rx = uart_disable_rx, .start_tx = uart_start_tx, .stop_tx = uart_stop_tx, }; static aos_status_t tty_uart_register(tty_uart_t *tty_uart) { if (!tty_uart) return -EINVAL; tty_uart->tty.ops = &tty_uart_ops; tty_uart->tty.flags = 0; return aos_tty_register(&tty_uart->tty); } static aos_status_t tty_uart_unregister(uint32_t id) { return aos_tty_unregister(id); } static int tty_uart_init(void) { static tty_uart_t tty_uarts[4]; int ret; tty_uarts[0].tty.dev.id = 0; ret = (int)tty_uart_register(&tty_uarts[0]); if (ret) return ret; tty_uarts[3].tty.dev.id = 3; ret = (int)tty_uart_register(&tty_uarts[3]); if (ret) { (void)tty_uart_unregister(0); return ret; } return 0; } LEVEL1_DRIVER_ENTRY(tty_uart_init)
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/aos_adapter/uart.c
C
apache-2.0
12,267
/* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels <adam@sics.se> * */ #ifndef __CC_H__ #define __CC_H__ #include "cpu.h" #define LWIP_MAILBOX_QUEUE 1 #define LWIP_TIMEVAL_PRIVATE 0 #define LWIP_NO_INTTYPES_H 1 #if defined(__GNUC__) #define PACK_STRUCT_BEGIN #define PACK_STRUCT_STRUCT __attribute__((packed)) #define PACK_STRUCT_FIELD(x) x #elif defined(__ICCARM__) #define PACK_STRUCT_BEGIN __packed #define PACK_STRUCT_STRUCT #define PACK_STRUCT_FIELD(x) x #else #define PACK_STRUCT_BEGIN #define PACK_STRUCT_STRUCT #define PACK_STRUCT_FIELD(x) x #endif #if LWIP_NO_INTTYPES_H #define U8_F "2d" #define X8_F "2x" #define U16_F "4d" #define S16_F "4d" #define X16_F "4x" #define U32_F "8ld" #define S32_F "8ld" #define X32_F "8lx" #define SZT_F U32_F #endif /* * Platform specific diagnostic output - * LWIP_PLATFORM_DIAG(x) - non-fatal, print a message. * LWIP_PLATFORM_ASSERT(x) - fatal, print message and abandon execution. * Portability defines for printf formatters: * U16_F, S16_F, X16_F, U32_F, S32_F, X32_F, SZT_F */ #ifndef LWIP_PLATFORM_ASSERT #define LWIP_PLATFORM_ASSERT(x) \ do \ { printf("Assertion \"%s\" failed at line %d in %s\n", x, __LINE__, __FILE__); \ } while(0) #endif #ifndef LWIP_PLATFORM_DIAG #define LWIP_PLATFORM_DIAG(x) do {printf x ;} while(0) #endif /* * unknow defination */ // cup byte order #ifndef BYTE_ORDER #define BYTE_ORDER LITTLE_ENDIAN #endif #define LWIP_RAND() ((u32_t)rand()) #if 0 #define LWIP_MAILBOX_QUEUE 1 #define LWIP_TIMEVAL_PRIVATE 0 #define LWIP_NO_INTTYPES_H 1 #define LWIP_RAND() ((u32_t)rand()) #define LWIP_PLATFORM_DIAG(x) do {printf x;} while(0) #if 0 typedef unsigned char u8_t; typedef signed char s8_t; typedef unsigned short u16_t; typedef signed short s16_t; typedef unsigned int u32_t; typedef signed long s32_t; typedef u32_t mem_ptr_t; typedef int sys_prot_t; #endif #define U16_F "d" #define S16_F "d" #define X16_F "x" #define U32_F "d" #define S32_F "d" #define X32_F "x" #define SZT_F "uz" /* define compiler specific symbols */ #if defined (__ICCARM__) #if !defined (__IARSTDLIB__) #define _STRING #ifndef memcmp #define memcmp(dst, src, sz) _memcmp(dst, src, sz) #endif #ifndef memset #define memset(dst, val, sz) _memset(dst, val, sz) #endif #ifndef memcpy #define memcpy(dst, src, sz) _memcpy(dst, src, sz) #endif #endif // __IARSTDLIB__ #define PACK_STRUCT_BEGIN #define PACK_STRUCT_STRUCT #define PACK_STRUCT_END #define PACK_STRUCT_FIELD(x) x #define PACK_STRUCT_USE_INCLUDES #elif defined (__CC_ARM) #define PACK_STRUCT_BEGIN __packed #define PACK_STRUCT_STRUCT #define PACK_STRUCT_END #define PACK_STRUCT_FIELD(x) x #elif defined (__GNUC__) #define PACK_STRUCT_BEGIN #define PACK_STRUCT_STRUCT __attribute__ ((__packed__)) #define PACK_STRUCT_END #define PACK_STRUCT_FIELD(x) x #define PACK_STRUCT_USE_INCLUDES #elif defined (__TASKING__) #define PACK_STRUCT_BEGIN #define PACK_STRUCT_STRUCT #define PACK_STRUCT_END #define PACK_STRUCT_FIELD(x) x #endif //#define LWIP_PLATFORM_DIAG printf //Realtek add #define LWIP_PLATFORM_ASSERT(x) //do { if(!(x)) while(1); } while(0) #endif #endif /* __CC_H__ */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/arch/cc.h
C
apache-2.0
4,754
/* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels <adam@sics.se> * */ #ifndef __CPU_H__ #define __CPU_H__ #undef BYTE_ORDER #define BYTE_ORDER LITTLE_ENDIAN #endif /* __CPU_H__ */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/arch/cpu.h
C
apache-2.0
1,720
#ifndef __LWIP_INTF_H__ #define __LWIP_INTF_H__ #define LWIP_INTF_DEBUG #ifdef LWIP_INTF_DEBUG #define LWIP_INTF_PRT warning_prf #define LWIP_INTF_WARN warning_prf #define LWIP_INTF_FATAL fatal_prf #else #define LWIP_INTF_PRT null_prf #define LWIP_INTF_WARN null_prf #define LWIP_INTF_FATAL null_prf #endif #endif // eof
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/arch/lwip_intf.h
C
apache-2.0
348
/* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels <adam@sics.se> * */ #ifndef __LWIPOPTS_H__ #define __LWIPOPTS_H__ /** * Loopback demo related options. */ #define LWIP_NETIF_LOOPBACK 1 #define LWIP_HAVE_LOOPIF 1 #define LWIP_NETIF_LOOPBACK_MULTITHREADING 1 #define LWIP_LOOPBACK_MAX_PBUFS 8 #define LWIP_TIMERS 1 #define LWIP_TCPIP_TIMEOUT 1 #define TCPIP_THREAD_NAME "tcp/ip" #define TCPIP_THREAD_STACKSIZE 8192 #define TCPIP_THREAD_PRIO 7 #define DEFAULT_THREAD_PRIO 32 /* Disable lwIP asserts */ #define LWIP_NOASSERT 1 #define LWIP_DEBUG 1 //#define LWIP_DEBUG_TRACE 1 #define SOCKETS_DEBUG LWIP_DBG_OFF // | LWIP_DBG_MASK_LEVEL #define IP_DEBUG LWIP_DBG_OFF #define ETHARP_DEBUG LWIP_DBG_OFF #define NETIF_DEBUG LWIP_DBG_OFF #define PBUF_DEBUG LWIP_DBG_OFF #define MEMP_DEBUG LWIP_DBG_OFF #define API_LIB_DEBUG LWIP_DBG_OFF #define API_MSG_DEBUG LWIP_DBG_OFF #define ICMP_DEBUG LWIP_DBG_OFF #define IGMP_DEBUG LWIP_DBG_OFF #define INET_DEBUG LWIP_DBG_OFF #define IP_REASS_DEBUG LWIP_DBG_OFF #define RAW_DEBUG LWIP_DBG_OFF #define MEM_DEBUG LWIP_DBG_OFF #define SYS_DEBUG LWIP_DBG_OFF #define TCP_DEBUG LWIP_DBG_OFF #define TCP_INPUT_DEBUG LWIP_DBG_OFF #define TCP_FR_DEBUG LWIP_DBG_OFF #define TCP_RTO_DEBUG LWIP_DBG_OFF #define TCP_CWND_DEBUG LWIP_DBG_OFF #define TCP_WND_DEBUG LWIP_DBG_OFF #define TCP_OUTPUT_DEBUG LWIP_DBG_OFF #define TCP_RST_DEBUG LWIP_DBG_OFF #define TCP_QLEN_DEBUG LWIP_DBG_OFF #define UDP_DEBUG LWIP_DBG_OFF #define TCPIP_DEBUG LWIP_DBG_OFF #define PPP_DEBUG LWIP_DBG_OFF #define SLIP_DEBUG LWIP_DBG_OFF #define DHCP_DEBUG LWIP_DBG_OFF #define AUTOIP_DEBUG LWIP_DBG_OFF #define SNMP_MSG_DEBUG LWIP_DBG_OFF #define SNMP_MIB_DEBUG LWIP_DBG_OFF #define DNS_DEBUG LWIP_DBG_OFF #define REENTER_DEBUG LWIP_DBG_OFF #define PKTPRINT_DEBUG LWIP_DBG_OFF #define IPERF_DEBUG LWIP_DBG_ON #define PING_DEBUG LWIP_DBG_ON #define DNSCLI_DEBUG LWIP_DBG_ON //#define LWIP_COMPAT_MUTEX 1 /** * SYS_LIGHTWEIGHT_PROT==1: if you want inter-task protection for certain * critical regions during buffer allocation, deallocation and memory * allocation and deallocation. */ #define SYS_LIGHTWEIGHT_PROT 1 /* ------------------------------------ ---------- Memory options ---------- ------------------------------------ */ /** * MEM_ALIGNMENT: should be set to the alignment of the CPU * 4 byte alignment -> #define MEM_ALIGNMENT 4 * 2 byte alignment -> #define MEM_ALIGNMENT 2 */ #define MEM_ALIGNMENT 4 #define MAX_SOCKETS_TCP 12 #define MAX_LISTENING_SOCKETS_TCP 4 #define MAX_SOCKETS_UDP 22 #define TCP_SND_BUF_COUNT 5 /* Value of TCP_SND_BUF_COUNT denotes the number of buffers and is set by * CONFIG option available in the SDK */ /* Buffer size needed for TCP: Max. number of TCP sockets * Size of pbuf * * Max. number of TCP sender buffers per socket * * Listening sockets for TCP servers do not require the same amount buffer * space. Hence do not consider these sockets for memory computation */ #define TCP_MEM_SIZE (MAX_SOCKETS_TCP * \ PBUF_POOL_BUFSIZE * (TCP_SND_BUF/TCP_MSS)) /* Buffer size needed for UDP: Max. number of UDP sockets * Size of pbuf */ #define UDP_MEM_SIZE (MAX_SOCKETS_UDP * PBUF_POOL_BUFSIZE) /** * MEM_SIZE: the size of the heap memory. If the application will send * a lot of data that needs to be copied, this should be set high. */ #define MEM_SIZE (20*1024) /* ------------------------------------------------ ---------- Internal Memory Pool Sizes ---------- ------------------------------------------------ */ /** * MEMP_NUM_PBUF: the number of memp struct pbufs (used for PBUF_ROM and PBUF_REF). * If the application sends a lot of data out of ROM (or other static memory), * this should be set high. */ #define MEMP_NUM_PBUF 10 /** * MEMP_NUM_TCP_PCB: the number of simulatenously active TCP connections. * (requires the LWIP_TCP option) */ #define MEMP_NUM_TCP_PCB MAX_SOCKETS_TCP #define MEMP_NUM_TCP_PCB_LISTEN MAX_LISTENING_SOCKETS_TCP /** * MEMP_NUM_TCP_SEG: the number of simultaneously queued TCP segments. * (requires the LWIP_TCP option) */ //#define MEMP_NUM_TCP_SEG 12 /** * MEMP_NUM_TCPIP_MSG_INPKT: the number of struct tcpip_msg, which are used * for incoming packets. * (only needed if you use tcpip.c) */ #define MEMP_NUM_TCPIP_MSG_INPKT 128 #define TCPIP_MBOX_SIZE 128 /** * MEMP_NUM_SYS_TIMEOUT: the number of simulateously active timeouts. * (requires NO_SYS==0) */ #define MEMP_NUM_SYS_TIMEOUT 12 /** * MEMP_NUM_NETBUF: the number of struct netbufs. * (only needed if you use the sequential API, like api_lib.c) */ #define MEMP_NUM_NETBUF 16 /** * MEMP_NUM_NETCONN: the number of struct netconns. * (only needed if you use the sequential API, like api_lib.c) * * This number corresponds to the maximum number of active sockets at any * given point in time. This number must be sum of max. TCP sockets, max. TCP * sockets used for listening, and max. number of UDP sockets */ #define MEMP_NUM_NETCONN (MAX_SOCKETS_TCP + \ MAX_LISTENING_SOCKETS_TCP + MAX_SOCKETS_UDP) /** * PBUF_POOL_SIZE: the number of buffers in the pbuf pool. */ //#define PBUF_POOL_SIZE 30 /* ---------------------------------- ---------- Pbuf options ---------- ---------------------------------- */ /** * PBUF_POOL_BUFSIZE: the size of each pbuf in the pbuf pool. The default is * designed to accomodate single full size TCP frame in one pbuf, including * TCP_MSS, IP header, and link header. */ #define PBUF_POOL_BUFSIZE 500 /* --------------------------------- ---------- RAW options ---------- --------------------------------- */ /** * LWIP_RAW==1: Enable application layer to hook into the IP layer itself. */ #define LWIP_RAW 1 #define LWIP_IPV6 0 /* Enable IPv4 Auto IP */ #ifdef CONFIG_AUTOIP #define LWIP_AUTOIP 1 #define LWIP_DHCP_AUTOIP_COOP 1 #define LWIP_DHCP_AUTOIP_COOP_TRIES 5 #endif /* ------------------------------------ ---------- Socket options ---------- ------------------------------------ */ /** * LWIP_SOCKET==1: Enable Socket API (require to use sockets.c) */ #define LWIP_SOCKET 1 #define LWIP_NETIF_API 1 /** * LWIP_RECV_CB==1: Enable callback when a socket receives data. */ #define LWIP_RECV_CB 1 /** * SO_REUSE==1: Enable SO_REUSEADDR option. */ #define SO_REUSE 1 #define SO_REUSE_RXTOALL 1 /** * Enable TCP_KEEPALIVE */ #define LWIP_TCP_KEEPALIVE 1 /** * TCP_SYNMAXRTX: Maximum number of retransmissions of SYN segments. */ #define TCP_SYNMAXRTX 10 /* ---------------------------------------- ---------- Statistics options ---------- ---------------------------------------- */ /** * LWIP_STATS==1: Enable statistics collection in lwip_stats. */ #define LWIP_STATS 0 /** * LWIP_STATS_DISPLAY==1: Compile in the statistics output functions. */ #define LWIP_STATS_DISPLAY 0 /* ---------------------------------- ---------- DHCP options ---------- ---------------------------------- */ /** * LWIP_DHCP==1: Enable DHCP module. */ #define LWIP_DHCP 1 #define LWIP_NETIF_STATUS_CALLBACK 1 /** * DNS related options, revisit later to fine tune. */ #define LWIP_DNS 1 #define DNS_TABLE_SIZE (4) // number of table entries, default 4 //#define DNS_MAX_NAME_LENGTH 64 // max. name length, default 256 #define DNS_MAX_SERVERS 2 // number of DNS servers, default 2 #define DNS_DOES_NAME_CHECK 1 // compare received name with given,def 0 #define DNS_MSG_SIZE 512 #define MDNS_MSG_SIZE 512 #define MDNS_TABLE_SIZE 1 // number of mDNS table entries #define MDNS_MAX_SERVERS 1 // number of mDNS multicast addresses /* TODO: Number of active UDP PCBs is equal to number of active UDP sockets plus * two. Need to find the users of these 2 PCBs */ #define MEMP_NUM_UDP_PCB (MAX_SOCKETS_UDP + 2) /* NOTE: some times the socket() call for SOCK_DGRAM might fail if you dont * have enough MEMP_NUM_UDP_PCB */ /* ---------------------------------- ---------- IGMP options ---------- ---------------------------------- */ /** * LWIP_IGMP==1: Turn on IGMP module. */ #define LWIP_IGMP 1 /** * LWIP_SO_SNDTIMEO==1: Enable send timeout for sockets/netconns and * SO_SNDTIMEO processing. */ #define LWIP_SO_SNDTIMEO 1 /** * LWIP_SO_RCVTIMEO==1: Enable receive timeout for sockets/netconns and * SO_RCVTIMEO processing. */ #define LWIP_SO_RCVTIMEO 1 /** * TCP_LISTEN_BACKLOG==1: Handle backlog connections. */ #define TCP_LISTEN_BACKLOG 1 //#define LWIP_PROVIDE_ERRNO 1 #include <errno.h> #define ERRNO 1 //#define LWIP_SNMP 1 /* ------------------------------------------------ ---------- Network Interfaces options ---------- ------------------------------------------------ */ /** * LWIP_NETIF_HOSTNAME==1: use DHCP_OPTION_HOSTNAME with netif's hostname * field. */ #define LWIP_NETIF_HOSTNAME 1 /* The STM32F107 allows computing and verifying the IP, UDP, TCP and ICMP checksums by hardware: - To use this feature let the following define uncommented. - To disable it and process by CPU comment the the checksum. */ //#define CHECKSUM_BY_HARDWARE #ifdef CHECKSUM_BY_HARDWARE /* CHECKSUM_GEN_IP==0: Generate checksums by hardware for outgoing IP packets.*/ #define CHECKSUM_GEN_IP 0 /* CHECKSUM_GEN_UDP==0: Generate checksums by hardware for outgoing UDP packets.*/ #define CHECKSUM_GEN_UDP 0 /* CHECKSUM_GEN_TCP==0: Generate checksums by hardware for outgoing TCP packets.*/ #define CHECKSUM_GEN_TCP 0 /* CHECKSUM_CHECK_IP==0: Check checksums by hardware for incoming IP packets.*/ #define CHECKSUM_CHECK_IP 0 /* CHECKSUM_CHECK_UDP==0: Check checksums by hardware for incoming UDP packets.*/ #define CHECKSUM_CHECK_UDP 0 /* CHECKSUM_CHECK_TCP==0: Check checksums by hardware for incoming TCP packets.*/ #define CHECKSUM_CHECK_TCP 0 #else /* CHECKSUM_GEN_IP==1: Generate checksums in software for outgoing IP packets.*/ #define CHECKSUM_GEN_IP 1 /* CHECKSUM_GEN_UDP==1: Generate checksums in software for outgoing UDP packets.*/ #define CHECKSUM_GEN_UDP 1 /* CHECKSUM_GEN_TCP==1: Generate checksums in software for outgoing TCP packets.*/ #define CHECKSUM_GEN_TCP 1 /* CHECKSUM_CHECK_IP==1: Check checksums in software for incoming IP packets.*/ #define CHECKSUM_CHECK_IP 1 /* CHECKSUM_CHECK_UDP==1: Check checksums in software for incoming UDP packets.*/ #define CHECKSUM_CHECK_UDP 1 /* CHECKSUM_CHECK_TCP==1: Check checksums in software for incoming TCP packets.*/ #define CHECKSUM_CHECK_TCP 1 #endif /** * TCP_RESOURCE_FAIL_RETRY_LIMIT: limit for retrying sending of tcp segment * on resource failure error returned by driver. */ #define TCP_RESOURCE_FAIL_RETRY_LIMIT 50 //yhb changed: //#ifdef CONFIG_ENABLE_MXCHIP /* save memory */ #define PBUF_POOL_SIZE 30 #define TCP_MSS (1500 - 40) /* TCP receive window. */ #define TCP_WND (10 * TCP_MSS) /* TCP sender buffer space (bytes). */ #define TCP_SND_BUF (44 * TCP_MSS) #define TCP_SND_QUEUELEN (4* TCP_SND_BUF/TCP_MSS) /* ARP before DHCP causes multi-second delay - turn it off */ #define DHCP_DOES_ARP_CHECK (0) #define TCP_MAX_ACCEPT_CONN 5 #define MEMP_NUM_TCP_SEG (TCP_SND_QUEUELEN*2) #define IP_REASS_MAX_PBUFS 0 #define IP_REASSEMBLY 0 #define MEMP_NUM_REASSDATA 0 #define IP_FRAG 0 #define MEM_LIBC_MALLOC (1) #define MEMP_MEM_MALLOC (1) #define LWIP_COMPAT_MUTEX_ALLOWED (1) //#endif #define DEFAULT_ACCEPTMBOX_SIZE 8 #define DEFAULT_RAW_RECVMBOX_SIZE 4 #define DEFAULT_UDP_RECVMBOX_SIZE 32 #define DEFAULT_TCP_RECVMBOX_SIZE 32 #ifdef CONFIG_AOS_MESH #define LWIP_DECLARE_HOOK \ struct netif *lwip_hook_ip6_route(const ip6_addr_t *src, const ip6_addr_t *dest); \ int lwip_hook_mesh_is_mcast_subscribed(const ip6_addr_t *dest); #define LWIP_HOOK_IP6_ROUTE(src, dest) lwip_hook_ip6_route(src, dest) #define LWIP_HOOK_MESH_IS_MCAST_SUBSCRIBED(dest) lwip_hook_mesh_is_mcast_subscribed(dest) #define LWIP_ICMP6 1 #define CHECKSUM_CHECK_ICMP6 0 #define LWIP_MULTICAST_PING 1 #endif #define LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS 1 #define TCP_QUEUE_OOSEQ 1 #endif /* __LWIPOPTS_H__ */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/arch/lwipopts.h
C
apache-2.0
15,492
#ifndef _TYPEDEF_H_ #define _TYPEDEF_H_ #include <stdint.h> #include <stdbool.h> typedef unsigned char UINT8; /* Unsigned 8 bit quantity */ typedef signed char INT8; /* Signed 8 bit quantity */ typedef unsigned short UINT16; /* Unsigned 16 bit quantity */ typedef signed short INT16; /* Signed 16 bit quantity */ typedef uint32_t UINT32; /* Unsigned 32 bit quantity */ typedef int32_t INT32; /* Signed 32 bit quantity */ typedef unsigned long long UINT64; /* Unsigned 32 bit quantity */ typedef signed long long INT64; /* Signed 32 bit quantity */ typedef float FP32; /* Single precision floating point */ typedef double FP64; /* Double precision floating point */ typedef unsigned char BOOLEAN; typedef unsigned char BOOL; typedef unsigned int size_t; #define LPVOID void * #define DWORD UINT32 #define VOID void typedef volatile signed long VS32; typedef volatile signed short VS16; typedef volatile signed char VS8; typedef volatile signed long const VSC32; typedef volatile signed short const VSC16; typedef volatile signed char const VSC8; typedef volatile unsigned long VU32; typedef volatile unsigned short VU16; typedef volatile unsigned char VU8; typedef volatile unsigned long const VUC32; typedef volatile unsigned short const VUC16; typedef volatile unsigned char const VUC8; typedef unsigned char u8; //typedef signed char s8; typedef unsigned short u16; typedef signed short s16; typedef unsigned int u32; typedef signed int s32; typedef unsigned long long u64; typedef long long s64; typedef unsigned int __u32; typedef int __s32; typedef unsigned short __u16; typedef signed short __s16; typedef unsigned char __u8; #endif // _TYPEDEF_H_ // eof
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/arch/typedef.h
C
apache-2.0
2,068
#! /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") hw_module = 0 cmd_str = "python haas1000_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.bin")) cmd_str = "\"%s\" -f --lzma2=dict=32KiB --check=crc32 -k %s" % (os.path.abspath(path), os.path.join(bin_path, "ota_rtos_ota.bin")) os.system(cmd_str) cmd_str = "python ota_gen_md5_bin.py \"%s\" -m %s" % (os.path.join(bin_path, "ota_rtos_ota.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.bin.xz"), magic) os.system(cmd_str) print("run external script success")
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/build_bin.py
Python
apache-2.0
1,369
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <drv/adc.h> #include <aos/adc_csi.h> #include "objects.h" #include "PinNames.h" #include "pinmap.h" static const PinMap CSI_PinMap_ADC[] = { { PB_4, ADC_CH0, 0 }, { PB_5, ADC_CH1, 0 }, { PB_6, ADC_CH2, 0 }, { PB_7, ADC_CH3, 0 }, { PB_1, ADC_CH4, 0 }, { PB_2, ADC_CH5, 0 }, { PB_3, ADC_CH6, 0 }, { VBAT_MEAS, ADC_CH7, 0 }, { NC, NC, 0 } }; static uint16_t rtl872xd_adc_offset; static uint16_t rtl872xd_adc_gain; csi_error_t csi_adc_init(csi_adc_t *adc, uint32_t idx) { if (!adc) return CSI_ERROR; adc->priv = (ADC_InitTypeDef *)malloc(sizeof(ADC_InitTypeDef)); ADC_InitTypeDef *ADC_InitStruct = (ADC_InitTypeDef *)adc->priv; adc->dev.idx = idx; /* Initialize ADC */ ADC_StructInit(ADC_InitStruct); ADC_Init(ADC_InitStruct); return CSI_OK; } void csi_adc_uninit(csi_adc_t *adc) { /* Clear ADC Status */ ADC_INTClear(); /* Disable ADC */ ADC_Cmd(DISABLE); if (adc->priv) { free(adc->priv); adc->priv = NULL; } } csi_error_t csi_adc_start(csi_adc_t *adc) { ADC_Cmd(ENABLE); return CSI_OK; } csi_error_t csi_adc_stop(csi_adc_t *adc) { ADC_Cmd(DISABLE); return CSI_OK; } csi_error_t csi_adc_channel_enable(csi_adc_t *adc, uint8_t ch_id, bool is_enable) { ADC_InitTypeDef *ADC_InitStruct = (ADC_InitTypeDef *)adc->priv; uint32_t adc_idx; if (ch_id != adc->dev.idx) adc->dev.idx = ch_id; adc_idx = CSI_PinMap_ADC[ch_id].peripheral; ADC_InitStruct->ADC_CvlistLen = 0; ADC_InitStruct->ADC_Cvlist[0] = adc_idx; ADC_InitStruct->ADC_ChIDEn = is_enable; /* MSB 4bit is channel index*/ ADC_Init(ADC_InitStruct); return CSI_OK; } csi_error_t csi_adc_sampling_time(csi_adc_t *adc, uint16_t clock_num) { /* no need to set sampling time */ return CSI_OK; } csi_error_t csi_adc_channel_sampling_time(csi_adc_t *adc, uint8_t ch_id, uint16_t clock_num) { /* no need to set sampling time */ return CSI_OK; } csi_error_t csi_adc_continue_mode(csi_adc_t *adc, bool is_enable) { ADC_InitTypeDef *ADC_InitStruct = (ADC_InitTypeDef *)adc->priv; if (is_enable) { ADC_InitStruct->ADC_OpMode = ADC_AUTO_MODE; ADC_Init(ADC_InitStruct); } return CSI_OK; } uint32_t csi_adc_freq_div(csi_adc_t *adc, uint32_t div) { ADC_InitTypeDef *ADC_InitStruct = (ADC_InitTypeDef *)adc->priv; uint32_t freq = 0; switch (div) { case 12: ADC_InitStruct->ADC_ClkDiv = ADC_CLK_DIV_12; freq = (uint32_t)(2000000 / 12); break; case 16: ADC_InitStruct->ADC_ClkDiv = ADC_CLK_DIV_16; freq = (uint32_t)(2000000 / 16); break; case 32: ADC_InitStruct->ADC_ClkDiv = ADC_CLK_DIV_32; freq = (uint32_t)(2000000 / 32); break; case 64: ADC_InitStruct->ADC_ClkDiv = ADC_CLK_DIV_64; freq = (uint32_t)(2000000 / 64); break; default: ADC_InitStruct->ADC_ClkDiv = ADC_CLK_DIV_12; freq = (uint32_t)(2000000 / 12); break; } ADC_Init(ADC_InitStruct); return freq; } static int32_t AD2MV(int32_t ad, uint16_t offset, uint16_t gain) { return (int32_t)(((10 * ad) - offset) * 1000 / gain); } static void adc_get_offset_gain(uint16_t *offset, uint16_t *gain, uint8_t vbat) { uint8_t EfuseBuf[2]; uint32_t index; uint32_t addressOffset; uint32_t addressGain; if (vbat) { addressOffset = 0x1D4; addressGain = 0x1D6; } else { addressOffset = 0x1D0; addressGain = 0x1D2; } for (index = 0; index < 2; index++) { EFUSERead8(0, addressOffset + index, EfuseBuf + index, L25EOUTVOLTAGE); } *offset = EfuseBuf[1] << 8 | EfuseBuf[0]; for (index = 0; index < 2; index++) { EFUSERead8(0, addressGain + index, EfuseBuf + index, L25EOUTVOLTAGE); } *gain = EfuseBuf[1] << 8 | EfuseBuf[0]; if (*offset == 0xFFFF) { if (vbat) *offset = 0x9C4; else *offset = 0x9B0; } if (*gain == 0xFFFF) { if (vbat) *gain = 7860; else *gain = 0x2F12; } } csi_error_t csi_adc_get_range(csi_adc_t *adc, uint8_t ch_id, uint32_t *range) { if (ch_id < 4) { *range = 3300; /*CH0~CH3: 3.3V*/ return CSI_OK; } else if (ch_id < 7) { *range = 1800; /*CH4~CH6: 1.8V*/ return CSI_OK; } else if (ch_id == 7) { *range = 5000; /*CH7: 5V*/ return CSI_OK; } else { return CSI_ERROR; } } int32_t csi_adc_read(csi_adc_t *adc) { int32_t value; uint32_t data; /* Clear FIFO */ ADC_ClearFIFO(); /* SW trigger to sample */ ADC_SWTrigCmd(ENABLE); while (ADC_Readable() == 0) ; ADC_SWTrigCmd(DISABLE); data = ADC_Read(); value = (int32_t)(data & BIT_MASK_DAT_GLOBAL); return value; } int32_t csi_adc_read_voltage(csi_adc_t *adc) { int32_t adc_data; adc_data = csi_adc_read(adc); return AD2MV(adc_data, rtl872xd_adc_offset, rtl872xd_adc_gain); } static int adc_csi_init(void) { csi_error_t ret; static aos_adc_csi_t adc_csi_dev; adc_get_offset_gain(&rtl872xd_adc_offset, &rtl872xd_adc_gain, 0); if (rtl872xd_adc_gain == 0) { printf("%s:%d: rtl872xd_adc_gain is 0\r\n", __func__, __LINE__); return -1; } ret = csi_adc_init(&(adc_csi_dev.csi_adc), 0); if (ret != CSI_OK) { printf("%s:%d: csi_adc_init fail, ret:%d\r\n", __func__, __LINE__, ret); return -1; } adc_csi_dev.aos_adc.dev.id = 0; adc_csi_dev.aos_adc.resolution = 12; adc_csi_dev.aos_adc.freq = 2000000 / 12; return aos_adc_csi_register(&adc_csi_dev); } LEVEL1_DRIVER_ENTRY(adc_csi_init)
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/csi_driver/adc/adc.c
C
apache-2.0
5,835
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "objects.h" #include "pinmap.h" #include "PinNames.h" #include <drv/gpio.h> #include <aos/gpioc_csi.h> static void user_interrupt_handler(csi_gpio_t *gpio, uint32_t id) { if (gpio->callback != NULL) { uint32_t pin_mask; pin_mask = (uint32_t)1 << ((id >> 16) & 0x1F); gpio->callback(gpio, pin_mask, gpio->arg); } } csi_error_t csi_gpio_init(csi_gpio_t *gpio, uint32_t port_idx) { if(!gpio) return CSI_ERROR; if (port_idx != PORT_A && port_idx != PORT_B){ printf("error\n"); return CSI_ERROR; } gpio->dev.idx = port_idx; gpio->callback = NULL; gpio->arg = NULL; return CSI_OK; } void csi_gpio_uninit(csi_gpio_t *gpio) { if (gpio->dev.idx != PORT_A && gpio->dev.idx != PORT_B) { return; } uint32_t pin_idx = 0; while(pin_idx < 32) { GPIO_DeInit(((gpio->dev.idx)<<5)|pin_idx); pin_idx++; } } csi_error_t csi_gpio_dir(csi_gpio_t *gpio, uint32_t pin_mask, csi_gpio_dir_t dir) { if (gpio->dev.idx != PORT_A && gpio->dev.idx != PORT_B) { return CSI_ERROR; } uint32_t pin_idx = 0; while(pin_idx < sizeof(pin_mask) * 8) { if((pin_mask >> pin_idx) & 0x01) { GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.GPIO_Pin = ((gpio->dev.idx)<<5)|pin_idx; printf("gpio pin:%d\n",pin_idx); GPIO_InitStruct.GPIO_Mode = dir; GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_Init(&GPIO_InitStruct); } pin_idx++; } return CSI_OK; } csi_error_t csi_gpio_mode(csi_gpio_t *gpio, uint32_t pin_mask, csi_gpio_mode_t mode) { if (gpio->dev.idx != PORT_A && gpio->dev.idx != PORT_B) { return CSI_ERROR; } uint32_t GPIO_PuPd; uint32_t pin_idx = 0; switch (mode) { case GPIO_MODE_PULLNONE:/* No driver -> Input & High Impendance */ GPIO_PuPd = GPIO_PuPd_NOPULL; break; case GPIO_MODE_PULLDOWN: GPIO_PuPd = GPIO_PuPd_DOWN; break; case GPIO_MODE_PULLUP: GPIO_PuPd = GPIO_PuPd_UP; break; default: GPIO_PuPd = GPIO_PuPd_NOPULL; break; } while(pin_idx < sizeof(pin_mask) * 8) { if((pin_mask >> pin_idx) & 0x01) { PAD_PullCtrl(((gpio->dev.idx)<<5)|pin_idx, GPIO_PuPd); } pin_idx++; } return CSI_OK; } csi_error_t csi_gpio_irq_mode(csi_gpio_t *gpio, uint32_t pin_mask, csi_gpio_irq_mode_t mode) { if (gpio->dev.idx != PORT_A && gpio->dev.idx != PORT_B) { return CSI_ERROR; } uint32_t GPIO_ITTrigger; uint32_t GPIO_ITPolarity; uint32_t pin_idx = 0; if(gpio->dev.idx == PORT_A) { InterruptRegister(GPIO_INTHandler, GPIOA_IRQ, (uint32_t)GPIOA_BASE, 5); InterruptEn(GPIOA_IRQ, 5); } else if (gpio->dev.idx == PORT_B){ InterruptRegister(GPIO_INTHandler, GPIOB_IRQ, (uint32_t)GPIOB_BASE, 5); InterruptEn(GPIOB_IRQ, 5); } switch(mode) { case GPIO_IRQ_MODE_RISING_EDGE: GPIO_ITTrigger = GPIO_INT_Trigger_EDGE; GPIO_ITPolarity = GPIO_INT_POLARITY_ACTIVE_HIGH; break; case GPIO_IRQ_MODE_FALLING_EDGE: GPIO_ITTrigger = GPIO_INT_Trigger_EDGE; GPIO_ITPolarity = GPIO_INT_POLARITY_ACTIVE_LOW; break; case GPIO_IRQ_MODE_BOTH_EDGE: GPIO_ITTrigger = GPIO_INT_Trigger_BOTHEDGE; GPIO_ITPolarity = GPIO_INT_POLARITY_ACTIVE_LOW; break; case GPIO_IRQ_MODE_LOW_LEVEL: GPIO_ITTrigger = GPIO_INT_Trigger_LEVEL; GPIO_ITPolarity = GPIO_INT_POLARITY_ACTIVE_LOW; break; case GPIO_IRQ_MODE_HIGH_LEVEL: GPIO_ITTrigger = GPIO_INT_Trigger_LEVEL; GPIO_ITPolarity = GPIO_INT_POLARITY_ACTIVE_HIGH; break; default: break; } while(pin_idx < sizeof(pin_mask) * 8) { if((pin_mask >> pin_idx) & 0x01) { GPIO_INTMode(((gpio->dev.idx)<<5)|pin_idx, ENABLE, GPIO_ITTrigger, GPIO_ITPolarity, GPIO_INT_DEBOUNCE_ENABLE); if(gpio->callback != NULL) { GPIO_UserRegIrq(((gpio->dev.idx)<<5)|pin_idx, user_interrupt_handler, gpio); } } pin_idx++; } return CSI_OK; } csi_error_t csi_gpio_irq_enable(csi_gpio_t *gpio, uint32_t pin_mask, bool enable) { if (gpio->dev.idx != PORT_A && gpio->dev.idx != PORT_B) { return CSI_ERROR; } uint32_t pin_idx = 0; while(pin_idx < sizeof(pin_mask) * 8) { if((pin_mask >> pin_idx) & 0x01) { GPIO_INTConfig(((gpio->dev.idx)<<5)|pin_idx, enable); } pin_idx++; } return CSI_OK; } void csi_gpio_write(csi_gpio_t *gpio, uint32_t pin_mask, csi_gpio_pin_state_t value) { if (gpio->dev.idx != PORT_A && gpio->dev.idx != PORT_B) { return; } uint32_t pin_idx = 0; while(pin_idx < sizeof(pin_mask) * 8) { if((pin_mask >> pin_idx) & 0x01) { GPIO_WriteBit(((gpio->dev.idx)<<5)|pin_idx, value); } pin_idx++; } } void csi_gpio_toggle(csi_gpio_t *gpio, uint32_t pin_mask) { if (gpio->dev.idx != PORT_A && gpio->dev.idx != PORT_B) { return; } uint32_t pin_idx = 0, value; while(pin_idx < sizeof(pin_mask) * 8) { if((pin_mask >> pin_idx) & 0x01) { value = GPIO_ReadDataBit(((gpio->dev.idx)<<5)|pin_idx); GPIO_WriteBit(((gpio->dev.idx)<<5)|pin_idx, !value); } pin_idx++; } } uint32_t csi_gpio_read(csi_gpio_t *gpio, uint32_t pin_mask) { if (gpio->dev.idx != PORT_A && gpio->dev.idx != PORT_B) { return CSI_ERROR; } uint32_t pin_idx = 0, value = 0; while(pin_idx < sizeof(pin_mask) * 8) { if((pin_mask >> pin_idx) & 0x01) { value |= (GPIO_ReadDataBit(((gpio->dev.idx)<<5)|pin_idx) << pin_idx); } pin_idx++; } return value; } csi_error_t csi_gpio_attach_callback(csi_gpio_t *gpio, void *callback, void *arg) { gpio->callback = callback; gpio->arg = arg; return CSI_OK; } void csi_gpio_detach_callback(csi_gpio_t *gpio) { if (gpio->callback != NULL) { gpio->callback = NULL; gpio->arg = NULL; } } static int gpioc_csi_init(void) { static aos_gpioc_csi_t gpioc_csi[2]; int ret; gpioc_csi[0].gpioc.dev.id = 0; gpioc_csi[0].gpioc.num_pins = 32; gpioc_csi[0].default_input_cfg = AOS_GPIO_INPUT_CFG_HI; gpioc_csi[0].default_output_cfg = AOS_GPIO_OUTPUT_CFG_PP; ret = (int)aos_gpioc_csi_register(&gpioc_csi[0]); if (ret) return ret; gpioc_csi[1].gpioc.dev.id = 1; gpioc_csi[1].gpioc.num_pins = 32; gpioc_csi[1].default_input_cfg = AOS_GPIO_INPUT_CFG_HI; gpioc_csi[1].default_output_cfg = AOS_GPIO_OUTPUT_CFG_PP; ret = (int)aos_gpioc_csi_register(&gpioc_csi[1]); if (ret) { (void)aos_gpioc_csi_unregister(0); return ret; } return 0; } LEVEL1_DRIVER_ENTRY(gpioc_csi_init)
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/csi_driver/gpio/gpio.c
C
apache-2.0
7,142
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "objects.h" #include "PinNames.h" #include "pinmap.h" #include <drv/iic.h> static const PinMap CSI_PinMap_I2C_SCL[] = { {PA_25, (int32_t)I2C0_DEV, PIN_DATA(PullUp, PINMUX_FUNCTION_I2C)}, {NC, NC, 0} }; static const PinMap CSI_PinMap_I2C_SDA[] = { {PA_26, (int32_t)I2C0_DEV, PIN_DATA(PullUp, PINMUX_FUNCTION_I2C)}, {NC, NC, 0} }; csi_error_t csi_iic_init(csi_iic_t *iic, uint32_t idx) { if(idx != 0) return CSI_ERROR; if(!iic) return CSI_ERROR; iic->priv = (I2C_InitTypeDef *)malloc(sizeof(I2C_InitTypeDef)); uint32_t i2c_idx = idx; I2C_TypeDef * I2Cx; I2C_InitTypeDef *I2C_InitStruct = (I2C_InitTypeDef *)iic->priv; iic->dev.idx = i2c_idx; iic->mode = I2C_MASTER_MODE; I2Cx = I2C_DEV_TABLE[i2c_idx].I2Cx; /* Set I2C Device Number */ I2C_InitStruct->I2CIdx = i2c_idx; /* Load I2C default value */ I2C_StructInit(I2C_InitStruct); /* Assign I2C Pin Mux */ I2C_InitStruct->I2CMaster = I2C_MASTER_MODE; I2C_InitStruct->I2CSpdMod = I2C_SS_MODE; I2C_InitStruct->I2CClk = 100; I2C_InitStruct->I2CAckAddr = 0; /* I2C Pin Mux Initialization */ PinName scl = CSI_PinMap_I2C_SCL[i2c_idx].pin; PinName sda = CSI_PinMap_I2C_SDA[i2c_idx].pin; printf("scl:%d,sda:%d\n",scl,sda); Pinmux_Config(scl, PINMUX_FUNCTION_I2C); Pinmux_Config(sda, PINMUX_FUNCTION_I2C); PAD_PullCtrl(scl, GPIO_PuPd_UP); PAD_PullCtrl(sda, GPIO_PuPd_UP); /* I2C HAL Initialization */ I2C_Init(I2Cx, I2C_InitStruct); /* Enable i2c master RESTART function */ I2Cx->IC_CON |= BIT_CTRL_IC_CON_IC_RESTART_EN; /* I2C Enable Module */ I2C_Cmd(I2Cx, ENABLE); return CSI_OK; } void csi_iic_uninit(csi_iic_t *iic) { uint32_t i2c_idx = iic->dev.idx; if(i2c_idx != 0) return; I2C_TypeDef * I2Cx = I2C_DEV_TABLE[i2c_idx].I2Cx; /* I2C Disable Module */ I2C_Cmd(I2Cx, DISABLE); if(iic && iic->priv) { free(iic->priv); iic->priv = NULL; } } csi_error_t csi_iic_mode(csi_iic_t *iic, csi_iic_mode_t mode) { uint32_t i2c_idx = iic->dev.idx; if(i2c_idx != 0) return CSI_ERROR; I2C_TypeDef *I2Cx = I2C_DEV_TABLE[i2c_idx].I2Cx; I2C_InitTypeDef *I2C_InitStruct = (I2C_InitTypeDef *)iic->priv; I2C_Cmd(I2Cx, DISABLE); iic->mode = mode; if(mode == IIC_MODE_MASTER) I2C_InitStruct->I2CMaster = I2C_MASTER_MODE; else if(mode == IIC_MODE_SLAVE) I2C_InitStruct->I2CMaster = I2C_SLAVE_MODE; I2C_Init(I2Cx, I2C_InitStruct); I2C_Cmd(I2Cx, ENABLE); return CSI_OK; } csi_error_t csi_iic_addr_mode(csi_iic_t *iic, csi_iic_addr_mode_t addr_mode) { uint32_t i2c_idx = iic->dev.idx; if(i2c_idx != 0) return CSI_ERROR; I2C_TypeDef * I2Cx = I2C_DEV_TABLE[i2c_idx].I2Cx; I2C_InitTypeDef *I2C_InitStruct = (I2C_InitTypeDef *)iic->priv; I2C_Cmd(I2Cx, DISABLE); I2C_InitStruct->I2CAddrMod = addr_mode; I2C_Init(I2Cx, I2C_InitStruct); I2C_Cmd(I2Cx, ENABLE); return CSI_OK; } csi_error_t csi_iic_speed(csi_iic_t *iic, csi_iic_speed_t speed) { uint32_t i2c_idx = iic->dev.idx; if(i2c_idx != 0) return CSI_ERROR; I2C_TypeDef * I2Cx = I2C_DEV_TABLE[i2c_idx].I2Cx; I2C_InitTypeDef *I2C_InitStruct = (I2C_InitTypeDef *)iic->priv; I2C_Cmd(I2Cx, DISABLE); switch(speed) { case IIC_BUS_SPEED_STANDARD: I2C_InitStruct->I2CSpdMod = I2C_SS_MODE; I2C_InitStruct->I2CClk = 100; break; case IIC_BUS_SPEED_FAST: I2C_InitStruct->I2CSpdMod = I2C_FS_MODE; I2C_InitStruct->I2CClk = 400; break; case IIC_BUS_SPEED_FAST_PLUS: case IIC_BUS_SPEED_HIGH: I2C_InitStruct->I2CSpdMod = I2C_HS_MODE; I2C_InitStruct->I2CClk = 1000; break; default: I2C_InitStruct->I2CSpdMod = I2C_SS_MODE; I2C_InitStruct->I2CClk = 100; } I2C_Init(I2Cx, I2C_InitStruct); I2C_Cmd(I2Cx, ENABLE); return CSI_OK; } /** * @brief Read data with special length in master mode through the I2Cx peripheral under in-house IP. * @param I2Cx: where I2Cx can be I2C0_DEV . * @param pBuf: point to the buffer to hold the received data. * @param len: the length of data that to be received. * @param timeout_ms: specifies timeout time, unit is ms. * @retval the length of data read. */ int32_t I2C_MasterRead_TimeOut(I2C_TypeDef *I2Cx, uint8_t* pBuf, uint8_t len, uint32_t timeout_ms) { int32_t cnt = 0; uint32_t InTimeoutCount = 0; /* read in the DR register the data to be received */ for(cnt = 0; cnt < len; cnt++) { InTimeoutCount = timeout_ms*500; if(cnt >= len - 1) { /* generate stop singal */ I2Cx->IC_DATA_CMD = 0x0003 << 8; } else { I2Cx->IC_DATA_CMD = 0x0001 << 8; } /* wait for I2C_FLAG_RFNE flag */ while((I2C_CheckFlagState(I2Cx, BIT_IC_STATUS_RFNE)) == 0) { if(I2C_GetRawINT(I2Cx) & BIT_IC_RAW_INTR_STAT_TX_ABRT) { I2C_ClearAllINT(I2Cx); return cnt; } DelayUs(2); if (InTimeoutCount == 0) { printf("MasterRead_TimeOut\n"); return cnt; } InTimeoutCount--; } *pBuf++ = (uint8_t)I2Cx->IC_DATA_CMD; } return cnt; } /** * @brief Write data with special length in master mode through the I2Cx peripheral under in-house IP. * @param I2Cx: where I2Cx can be I2C0_DEV. * @param pBuf: point to the data to be transmitted. * @param len: the length of data that to be received. * @param timeout_ms: specifies timeout time, unit is ms. * @retval the length of data send. */ int32_t I2C_MasterWrite_TimeOut(I2C_TypeDef *I2Cx, uint8_t* pBuf, uint8_t len, uint32_t timeout_ms, int32_t stop) { int32_t cnt = 0; uint32_t InTimeoutCount = 0; /* Write in the DR register the data to be sent */ for(cnt = 0; cnt < len; cnt++) { InTimeoutCount = timeout_ms*500; while((I2C_CheckFlagState(I2Cx, BIT_IC_STATUS_TFNF)) == 0); if(cnt >= len - 1) { if(stop == 1) { /*generate stop signal*/ I2Cx->IC_DATA_CMD = (*pBuf++) | (1 << 9); } else { /*generate restart signal*/ I2Cx->IC_DATA_CMD = (*pBuf++) | (1 << 10); } } else { I2Cx->IC_DATA_CMD = (*pBuf++); } while((I2C_CheckFlagState(I2Cx, BIT_IC_STATUS_TFE)) == 0) { if(I2C_GetRawINT(I2Cx) & BIT_IC_RAW_INTR_STAT_TX_ABRT) { printf(" TX_ABRT = %x\n", I2Cx->IC_TX_ABRT_SOURCE); I2C_ClearAllINT(I2Cx); return cnt; } DelayUs(2); if (InTimeoutCount == 0) { printf("MasterWrite_TimeOut\n"); return cnt; } InTimeoutCount--; } } return cnt; } /** * @brief Master sends single byte through the I2Cx peripheral to detect slave device. * @param obj: i2c object defined in application software. * @param address: the address of slave that to be detected. * @param timeout_ms: specifies timeout time, unit is ms. * @retval Slave ack condition: * - 0: Slave available * - -1: Slave not available */ int32_t I2C_MasterSendNullData_TimeOut(I2C_TypeDef *I2Cx, int32_t address, uint32_t timeout_ms) { uint8_t I2CTemp = (uint8_t)(address<<1); I2C_MasterSendNullData(I2Cx, &I2CTemp, 0, 1, 0); DelayMs(timeout_ms); if(I2C_GetRawINT(I2Cx) & BIT_IC_RAW_INTR_STAT_TX_ABRT) { I2C_ClearAllINT(I2Cx); /* Wait for i2c enter trap state from trap_stop state*/ DelayUs(100); I2C_Cmd(I2Cx, DISABLE); I2C_Cmd(I2Cx, ENABLE); return CSI_ERROR; } return CSI_OK; } int32_t csi_iic_master_send(csi_iic_t *iic,uint32_t devaddr,const void *data,uint32_t size,uint32_t timeout) { uint32_t i2c_idx = iic->dev.idx; if(i2c_idx != 0) return CSI_ERROR; I2C_TypeDef * I2Cx = I2C_DEV_TABLE[i2c_idx].I2Cx; I2C_InitTypeDef *I2C_InitStruct = (I2C_InitTypeDef *)iic->priv; /* Check the parameters */ if(!IS_I2C_ALL_PERIPH(I2Cx)) return CSI_ERROR; if (I2C_InitStruct->I2CAckAddr != devaddr) { /* Deinit I2C first */ I2C_Cmd(I2Cx, DISABLE); /* Load the user defined I2C target slave address */ I2C_InitStruct->I2CAckAddr = devaddr; /* Init I2C now */ I2C_Init(I2Cx, I2C_InitStruct); I2C_Cmd(I2Cx, ENABLE); } if(!size) { return (I2C_MasterSendNullData_TimeOut(I2Cx, devaddr, timeout)); } return (I2C_MasterWrite_TimeOut(I2Cx, (uint8_t*)data, size,timeout, 1)); } int32_t csi_iic_master_receive(csi_iic_t *iic, uint32_t devaddr, void *data, uint32_t size, uint32_t timeout) { uint32_t i2c_idx = iic->dev.idx; if(i2c_idx != 0) return CSI_ERROR; I2C_TypeDef * I2Cx = I2C_DEV_TABLE[i2c_idx].I2Cx; I2C_InitTypeDef *I2C_InitStruct = (I2C_InitTypeDef *)iic->priv; /* Check the parameters */ if(!IS_I2C_ALL_PERIPH(I2Cx)) return CSI_ERROR; if (I2C_InitStruct->I2CAckAddr != devaddr) { /* Deinit I2C first */ I2C_Cmd(I2Cx, DISABLE); /* Load the user defined I2C target slave address */ I2C_InitStruct->I2CAckAddr = devaddr; /* Init I2C now */ I2C_Init(I2Cx, I2C_InitStruct); I2C_Cmd(I2Cx, ENABLE); } return (I2C_MasterRead_TimeOut(I2Cx, (uint8_t*)data, size,timeout)); } int32_t csi_iic_mem_send(csi_iic_t *iic, uint32_t devaddr,uint16_t memaddr, csi_iic_mem_addr_size_t memaddr_size,const void *data,uint32_t size,uint32_t timeout) { uint32_t i = 0; int cnt = 0; uint32_t i2c_idx = iic->dev.idx; uint32_t mem_size; char *buf = NULL; if(i2c_idx != 0) return CSI_ERROR; buf = malloc(memaddr_size + size); if(!buf) { printf("malloc for i2c mem send fail\r\n"); return CSI_ERROR; } I2C_TypeDef * I2Cx = I2C_DEV_TABLE[i2c_idx].I2Cx; I2C_InitTypeDef *I2C_InitStruct = (I2C_InitTypeDef *)iic->priv; switch(memaddr_size) { case IIC_MEM_ADDR_SIZE_8BIT: mem_size = 1; break; case IIC_MEM_ADDR_SIZE_16BIT: mem_size = 2; break; default: mem_size = 1; break; } /* Check the parameters */ if(!IS_I2C_ALL_PERIPH(I2Cx)) { free(buf); buf = NULL; return CSI_ERROR; } if (I2C_InitStruct->I2CAckAddr != devaddr) { /* Deinit I2C first */ I2C_Cmd(I2Cx, DISABLE); /* Load the user defined I2C target slave address */ I2C_InitStruct->I2CAckAddr = devaddr; /* Init I2C now */ I2C_Init(I2Cx, I2C_InitStruct); I2C_Cmd(I2Cx, ENABLE); } if (mem_size == 1) { buf[i++] = (memaddr) & 0xFF; } else buf[i++] = (memaddr >> 8) & 0xFF; memcpy(&buf[i], data, size); cnt = I2C_MasterWrite_TimeOut(I2Cx, (uint8_t*)buf, mem_size + size, timeout, 1); free(buf); buf = NULL; if (cnt == (mem_size + size)) return size; else return cnt; } int32_t csi_iic_mem_receive(csi_iic_t *iic,uint32_t devaddr, uint16_t memaddr,csi_iic_mem_addr_size_t memaddr_size,void *data,uint32_t size,uint32_t timeout) { int cnt = 0; uint32_t i2c_idx = iic->dev.idx; uint32_t mem_size; if(i2c_idx != 0) return CSI_ERROR; I2C_TypeDef * I2Cx = I2C_DEV_TABLE[i2c_idx].I2Cx; I2C_InitTypeDef *I2C_InitStruct = (I2C_InitTypeDef *)iic->priv; uint8_t memaddr_t[2]; memaddr_t[0] = (memaddr) & 0xFF; memaddr_t[1] = (memaddr >> 8) & 0xFF; switch(memaddr_size) { case IIC_MEM_ADDR_SIZE_8BIT: mem_size = 1; break; case IIC_MEM_ADDR_SIZE_16BIT: mem_size = 2; break; default: mem_size = 1; break; } /* Check the parameters */ if(!IS_I2C_ALL_PERIPH(I2Cx)) return CSI_ERROR; if (I2C_InitStruct->I2CAckAddr != devaddr) { /* Deinit I2C first */ I2C_Cmd(I2Cx, DISABLE); /* Load the user defined I2C target slave address */ I2C_InitStruct->I2CAckAddr = devaddr; /* Init I2C now */ I2C_Init(I2Cx, I2C_InitStruct); I2C_Cmd(I2Cx, ENABLE); } cnt = I2C_MasterWrite_TimeOut(I2Cx, memaddr_t, mem_size, timeout, 0); cnt = I2C_MasterRead_TimeOut(I2Cx, (uint8_t *)data, size, timeout); return cnt; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/csi_driver/iic/iic.c
C
apache-2.0
13,461
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <drv/pwm.h> #include <aos/pwm_csi.h> #include "device.h" #include "objects.h" #include "pinmap.h" #define BIT_PWM_TIM_IDX_FLAG BIT(7) #define BIT_PWM_TIM_IDX_SHIFT 7 #define PWM_TIMER 5 /* Table elements express the pin to PWM channel number, they are: * {pinName, km0_pin2chan, km4_pin2chan} */ const u32 csi_pin2chan[18][2] = { { PA_12, 0 }, { PA_13, 1 }, { PA_23, 2 }, { PA_24, 3 }, { PA_25, 4 }, { PA_26, 5 }, { PA_28, 6 }, { PA_30, 7 }, { PB_4, 8 }, { PB_5, 9 }, { PB_18, 10 }, { PB_19, 11 }, { PB_20, 12 }, { PB_21, 13 }, { PB_22, 14 }, { PB_23, 15 }, { PB_24, 16 }, { PB_25, 17 } // this channel also can be PB_7 }; RTIM_TypeDef *CSI_PWM_TIM[2] = { TIM5, TIMM05 }; u8 csi_km4_ch_start[18] = { 0 }; csi_error_t csi_pwm_init(csi_pwm_t *pwm, uint32_t idx) { if (!pwm) return CSI_ERROR; if (idx != 0) { return CSI_ERROR; } pwm->priv = (TIM_CCInitTypeDef *)malloc(sizeof(TIM_CCInitTypeDef)); pwm->dev.idx = idx << BIT_PWM_TIM_IDX_SHIFT; return CSI_OK; } void csi_pwm_uninit(csi_pwm_t *pwm) { uint32_t pwm_chan = pwm->dev.idx & (~BIT_PWM_TIM_IDX_FLAG); uint8_t pwm_tim_idx = pwm->dev.idx >> BIT_PWM_TIM_IDX_SHIFT; if (csi_km4_ch_start[pwm_chan]) { csi_km4_ch_start[pwm_chan] = 0; RTIM_CCxCmd(CSI_PWM_TIM[pwm_tim_idx], pwm_chan, TIM_CCx_Disable); /* stop timer5 if no pwm channels starts */ for (pwm_chan = 0; pwm_chan < 18; pwm_chan++) { if (csi_km4_ch_start[pwm_chan]) { return; } } RTIM_Cmd(CSI_PWM_TIM[pwm_tim_idx], DISABLE); } if (pwm && pwm->priv) { free(pwm->priv); pwm->priv = NULL; } } csi_error_t csi_pwm_out_config(csi_pwm_t *pwm, uint32_t channel, uint32_t period_us, uint32_t pulse_width_us, csi_pwm_polarity_t polarity) { uint32_t arr, tmp, ccrx; uint32_t period; float pulse, value, dc; uint8_t pwm_tim_idx = pwm->dev.idx >> BIT_PWM_TIM_IDX_SHIFT; TIM_CCInitTypeDef *TIM_CCInitStruct = (TIM_CCInitTypeDef *)pwm->priv; u32 csi_prescaler = 0; if (channel > 18) { return CSI_ERROR; } RTIM_CCStructInit(TIM_CCInitStruct); RTIM_CCxInit(CSI_PWM_TIM[pwm_tim_idx], TIM_CCInitStruct, channel); RTIM_CCxCmd(CSI_PWM_TIM[pwm_tim_idx], channel, TIM_CCx_Enable); PinName pin = csi_pin2chan[channel][0]; if (pwm_tim_idx) { Pinmux_Config(pin, PINMUX_FUNCTION_PWM_LP); } else { Pinmux_Config(pin, PINMUX_FUNCTION_PWM_HS); } pwm->dev.idx |= channel; csi_km4_ch_start[channel] = 1; tmp = period_us * 40 / (csi_prescaler + 1); /* * psr is 8bits */ if (tmp > 0x10000) { csi_prescaler = period_us * 40 / 0x10000; if (csi_prescaler > 0xff) { csi_prescaler = 0xff; } RTIM_PrescalerConfig(CSI_PWM_TIM[pwm_tim_idx], csi_prescaler, TIM_PSCReloadMode_Update); } /* * arr is 16bits */ /* * 40M oscilator range:2HZ-2KHZ? */ arr = period_us * 40 / (csi_prescaler + 1) - 1; if (arr > 0xffff) { arr = 0xffff; } RTIM_ChangePeriod(CSI_PWM_TIM[pwm_tim_idx], arr); ccrx = (u32)((period_us - pulse_width_us) * 40 / (csi_prescaler + 1)) & 0x0000ffff; RTIM_CCRxSet(CSI_PWM_TIM[pwm_tim_idx], ccrx, channel); if (0 == polarity) RTIM_CCxPolarityConfig(CSI_PWM_TIM[pwm_tim_idx], TIM_CCPolarity_Low, channel); else RTIM_CCxPolarityConfig(CSI_PWM_TIM[pwm_tim_idx], TIM_CCPolarity_High, channel); return CSI_OK; } csi_error_t csi_pwm_out_start(csi_pwm_t *pwm, uint32_t channel) { uint32_t pwm_chan = channel; uint8_t pwm_tim_idx = pwm->dev.idx >> BIT_PWM_TIM_IDX_SHIFT; RTIM_CCxCmd(CSI_PWM_TIM[pwm_tim_idx], pwm_chan, TIM_CCx_Enable); return CSI_OK; } void csi_pwm_out_stop(csi_pwm_t *pwm, uint32_t channel) { uint32_t pwm_chan = channel; uint8_t pwm_tim_idx = pwm->dev.idx >> BIT_PWM_TIM_IDX_SHIFT; RTIM_CCxCmd(CSI_PWM_TIM[pwm_tim_idx], pwm_chan, TIM_CCx_Disable); } static int pwm_csi_init(void) { csi_error_t ret; static aos_pwm_csi_t pwm_csi_dev[CONFIG_PWM_NUM]; int idx = 0, i; RTIM_TimeBaseInitTypeDef TIM_InitStruct; RTIM_TimeBaseStructInit(&TIM_InitStruct); TIM_InitStruct.TIM_Idx = PWM_TIMER; RTIM_TimeBaseInit(CSI_PWM_TIM[idx], &TIM_InitStruct, TIMER5_IRQ, NULL, (u32)&TIM_InitStruct); RTIM_Cmd(CSI_PWM_TIM[idx], ENABLE); for (i = 0; i < CONFIG_PWM_NUM; i++) { ret = csi_pwm_init(&(pwm_csi_dev[i].csi_pwm), idx); pwm_csi_dev[i].csi_pwm.dev.idx |= (i) & (~BIT_PWM_TIM_IDX_FLAG); if (ret != CSI_OK) { return ret; } pwm_csi_dev[i].aos_pwm.dev.id = i; ret = aos_pwm_csi_register(&(pwm_csi_dev[i])); if (ret != CSI_OK) { return ret; } } return 0; } LEVEL1_DRIVER_ENTRY(pwm_csi_init)
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/csi_driver/pwm/pwm.c
C
apache-2.0
5,044
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <drv/spi.h> #include "objects.h" #include "PinNames.h" #include "pinmap.h" typedef struct csi_spi_pin { uint32_t spi_idx; PinName spi_mosi; PinName spi_miso; PinName spi_sclk; PinName spi_cs; } csi_spi_pin_t; static csi_spi_pin_t CSI_PinMap_SPI[2] = { { 0, PA_16, PA_17, PA_18, PA_19 }, { 1, PB_4, PB_5, PB_6, PB_7 } }; #define CSI_SPI_STATE_READY 0x00 #define CSI_SPI_STATE_RX_BUSY (1 << 1) #define CSI_SPI_STATE_TX_BUSY (1 << 2) static uint32_t ssi_interrupt(void *Adaptor) { csi_spi_t *spi = (csi_spi_t *)Adaptor; uint32_t spi_idx = spi->dev.idx; SPI_TypeDef *spi_dev = SPI_DEV_TABLE[spi_idx].SPIx; SSI_InitTypeDef *SSI_InitStruct = (SSI_InitTypeDef *)spi->priv; uint32_t InterruptStatus = SSI_GetIsr(spi_dev); uint32_t DataFrameSize = SSI_GetDataFrameSize(spi_dev); SSI_SetIsrClean(spi_dev, InterruptStatus); if (InterruptStatus & (BIT_ISR_TXOIS | BIT_ISR_RXUIS | BIT_ISR_RXOIS | BIT_ISR_MSTIS)) { printf("[INT] Tx/Rx Warning %x\n", InterruptStatus); } // printf("InterruptStatus:%d\n",InterruptStatus); if ((InterruptStatus & BIT_ISR_RXFIS)) { uint32_t TransLen = 0; TransLen = SSI_ReceiveData(spi_dev, spi->rx_data, spi->rx_size); spi->rx_size -= TransLen; if (DataFrameSize > 8) { // 16~9 bits mode spi->rx_data = (uint8_t *)(((uint16_t *)spi->rx_data) + TransLen); } else { // 8~4 bits mode spi->rx_data = (uint8_t *)(((uint8_t *)spi->rx_data) + TransLen); } if (spi->rx_size == 0) { SSI_INTConfig(spi_dev, (BIT_IMR_RXFIM | BIT_IMR_RXOIM | BIT_IMR_RXUIM), DISABLE); if (spi->callback != NULL) { spi->callback(spi, SPI_EVENT_RECEIVE_COMPLETE, NULL); } } } if (InterruptStatus & BIT_ISR_TXEIS) { uint32_t TransLen = 0; volatile uint32_t bus_busy; /* SPIx is busy or not.*/ uint32_t i; /* all data complete */ if (spi->tx_size == 0) { SSI_INTConfig(spi_dev, (BIT_IMR_TXOIM | BIT_IMR_TXEIM), DISABLE); for (i = 0; i < 1000000; i++) { bus_busy = SSI_Busy(spi_dev); if (!bus_busy) { break; // break the for loop } } // If it's not a dummy TX for master read SPI, then call the TX_done callback if (spi->tx_data != NULL) { if (spi->callback != NULL) { spi->callback(spi, SPI_EVENT_SEND_COMPLETE, NULL); } } return 0; } TransLen = SSI_SendData(spi_dev, spi->tx_data, spi->tx_size, SSI_InitStruct->SPI_Role); spi->tx_size -= TransLen; if (spi->tx_data != NULL) { if (DataFrameSize > 8) { // 16~9 bits mode spi->tx_data = (((uint16_t *)spi->tx_data) + TransLen); } else { // 8~4 bits mode spi->tx_data = (void *)(((uint8_t *)spi->tx_data) + TransLen); } } /* all data write into fifo */ if (spi->tx_size == 0) { SSI_INTConfig(spi_dev, (BIT_IMR_TXOIM), DISABLE); // If it's not a dummy TX for master read SPI, then call the TX_done callback if (spi->tx_data != NULL) { if (spi->callback != NULL) { spi->callback(spi, SPI_EVENT_SEND_COMPLETE, NULL); } } } } return 0; } csi_error_t csi_spi_init(csi_spi_t *spi, uint32_t idx) { if (!spi) return CSI_ERROR; if ((idx != 0) && (idx != 1)) { printf("error: spi idx should be 0 or 1\n"); return CSI_ERROR; } spi->priv = (SSI_InitTypeDef *)malloc(sizeof(SSI_InitTypeDef)); SSI_InitTypeDef *SSI_InitStruct = (SSI_InitTypeDef *)spi->priv; SPI_TypeDef *spi_dev; IRQn_Type IrqNum; spi_dev = SPI_DEV_TABLE[idx].SPIx; spi->dev.idx = idx; SSI_StructInit(SSI_InitStruct); PinName mosi = CSI_PinMap_SPI[idx].spi_mosi; PinName miso = CSI_PinMap_SPI[idx].spi_miso; PinName sclk = CSI_PinMap_SPI[idx].spi_sclk; PinName ssel = CSI_PinMap_SPI[idx].spi_cs; if (idx == 1) { RCC_PeriphClockCmd(APBPeriph_SPI1, APBPeriph_SPI1_CLOCK, ENABLE); Pinmux_Config(mosi, PINMUX_FUNCTION_SPIM); Pinmux_Config(miso, PINMUX_FUNCTION_SPIM); Pinmux_Config(sclk, PINMUX_FUNCTION_SPIM); Pinmux_Config(ssel, PINMUX_FUNCTION_SPIM); } else { RCC_PeriphClockCmd(APBPeriph_SPI0, APBPeriph_SPI0_CLOCK, ENABLE); Pinmux_Config(mosi, PINMUX_FUNCTION_SPIS); Pinmux_Config(miso, PINMUX_FUNCTION_SPIS); Pinmux_Config(sclk, PINMUX_FUNCTION_SPIS); Pinmux_Config(ssel, PINMUX_FUNCTION_SPIS); } SSI_Init(spi_dev, SSI_InitStruct); IrqNum = SPI_DEV_TABLE[idx].IrqNum; InterruptRegister((IRQ_FUN)ssi_interrupt, IrqNum, (uint32_t)spi, 5); InterruptEn(IrqNum, 5); return CSI_OK; } void csi_spi_uninit(csi_spi_t *spi) { uint32_t spi_idx = spi->dev.idx; SPI_TypeDef *spi_dev = SPI_DEV_TABLE[spi_idx].SPIx; IRQn_Type IrqNum = SPI_DEV_TABLE[spi_idx].IrqNum; InterruptDis(IrqNum); InterruptUnRegister(IrqNum); SSI_INTConfig(spi_dev, (BIT_IMR_RXFIM | BIT_IMR_RXOIM | BIT_IMR_RXUIM), DISABLE); SSI_Cmd(spi_dev, DISABLE); if (spi && spi->priv) { free(spi->priv); spi->priv = NULL; } } csi_error_t csi_spi_attach_callback(csi_spi_t *spi, void *callback, void *arg) { spi->callback = callback; spi->arg = arg; return CSI_OK; } void csi_spi_detach_callback(csi_spi_t *spi) { spi->callback = NULL; } csi_error_t csi_spi_mode(csi_spi_t *spi, csi_spi_mode_t mode) { uint32_t spi_idx = spi->dev.idx; SPI_TypeDef *spi_dev = SPI_DEV_TABLE[spi_idx].SPIx; SSI_InitTypeDef *SSI_InitStruct = (SSI_InitTypeDef *)spi->priv; switch (mode) { case SPI_MASTER: SSI_InitStruct->SPI_Role = SSI_MASTER; break; case SPI_SLAVE: SSI_InitStruct->SPI_Role = SSI_SLAVE; break; } if (spi_idx == 0) SSI_SetRole(spi_dev, SSI_InitStruct->SPI_Role); // Re-init after setting role SSI_StructInit(SSI_InitStruct); SSI_Init(spi_dev, SSI_InitStruct); return CSI_OK; } csi_error_t csi_spi_cp_format(csi_spi_t *spi, csi_spi_cp_format_t format) { uint32_t spi_idx = spi->dev.idx; SPI_TypeDef *spi_dev = SPI_DEV_TABLE[spi_idx].SPIx; SSI_InitTypeDef *SSI_InitStruct = (SSI_InitTypeDef *)spi->priv; uint32_t SclkPhase; uint32_t SclkPolarity; switch (format) { case SPI_FORMAT_CPOL0_CPHA0: SclkPolarity = SCPOL_INACTIVE_IS_LOW; SclkPhase = SCPH_TOGGLES_IN_MIDDLE; break; case SPI_FORMAT_CPOL0_CPHA1: SclkPolarity = SCPOL_INACTIVE_IS_LOW; SclkPhase = SCPH_TOGGLES_AT_START; break; case SPI_FORMAT_CPOL1_CPHA0: SclkPolarity = SCPOL_INACTIVE_IS_HIGH; SclkPhase = SCPH_TOGGLES_IN_MIDDLE; break; case SPI_FORMAT_CPOL1_CPHA1: SclkPolarity = SCPOL_INACTIVE_IS_HIGH; SclkPhase = SCPH_TOGGLES_AT_START; break; default: // same as 3 SclkPolarity = SCPOL_INACTIVE_IS_HIGH; SclkPhase = SCPH_TOGGLES_AT_START; break; } SSI_SetSclkPhase(spi_dev, SclkPhase); SSI_SetSclkPolarity(spi_dev, SclkPolarity); if (SSI_InitStruct->SPI_Role == SSI_SLAVE) { PinName sclk = CSI_PinMap_SPI[spi_idx].spi_sclk; if (SclkPolarity == SCPOL_INACTIVE_IS_LOW) { PAD_PullCtrl((uint32_t)sclk, GPIO_PuPd_DOWN); } else { PAD_PullCtrl((uint32_t)sclk, GPIO_PuPd_UP); } } return CSI_OK; } csi_error_t csi_spi_frame_len(csi_spi_t *spi, csi_spi_frame_len_t length) { uint32_t spi_idx = spi->dev.idx; SPI_TypeDef *spi_dev = SPI_DEV_TABLE[spi_idx].SPIx; uint32_t DataFrameSize = (length - 1); SSI_SetDataFrameSize(spi_dev, DataFrameSize); return CSI_OK; } uint32_t csi_spi_baud(csi_spi_t *spi, uint32_t baud) { uint32_t spi_idx = spi->dev.idx; SPI_TypeDef *spi_dev = SPI_DEV_TABLE[spi_idx].SPIx; uint32_t IpClk; uint32_t ClockDivider; if (spi_idx == 0) IpClk = 100000000; else IpClk = 50000000; /*Adjust SCKDV-Parameter to an even number */ ClockDivider = IpClk / baud + 1; if ((IpClk % baud) > (uint32_t)(baud / 2)) { ClockDivider++; } if (ClockDivider >= 0xFFFF) { /* devider is 16 bits */ ClockDivider = 0xFFFE; } ClockDivider &= 0xFFFE; // bit 0 always is 0 SSI_SetBaudDiv(spi_dev, ClockDivider); return ClockDivider; } int32_t csi_spi_send(csi_spi_t *spi, const void *data, uint32_t size, uint32_t timeout) { uint8_t spi_idx = spi->dev.idx; SPI_TypeDef *spi_dev = SPI_DEV_TABLE[spi_idx].SPIx; SSI_InitTypeDef *SSI_InitStruct = (SSI_InitTypeDef *)spi->priv; uint32_t DataFrameSize = SSI_GetDataFrameSize(spi_dev); int32_t cnt = 0; uint32_t StartCount = 0; StartCount = SYSTIMER_TickGet(); while (1) { if (SSI_Writeable(spi_dev)) { if (DataFrameSize > 8) { // 16~9 bits mode if (data != NULL) { SSI_WriteData(spi_dev, *((uint16_t *)(data + cnt))); cnt += 2; // For master mode: Push a dummy to TX FIFO for Read if (SSI_InitStruct->SPI_Role == SSI_MASTER) { if (SSI_Readable(spi_dev)) SSI_ReadData(spi_dev); } } } else { if (data != NULL) { SSI_WriteData(spi_dev, *((uint8_t *)(data + cnt))); printf("data:%c\n", *((uint8_t *)(data + cnt))); cnt++; // For master mode: Push a dummy to TX FIFO for Read if (SSI_InitStruct->SPI_Role == SSI_MASTER) { if (SSI_Readable(spi_dev)) SSI_ReadData(spi_dev); } } } } else { aos_msleep(1); } if (cnt == size) break; if (SYSTIMER_GetPassTime(StartCount) > timeout) { break; } } return cnt; } csi_error_t csi_spi_send_async(csi_spi_t *spi, const void *data, uint32_t size) { uint8_t spi_idx = spi->dev.idx; SPI_TypeDef *spi_dev = SPI_DEV_TABLE[spi_idx].SPIx; uint32_t DataFrameSize = SSI_GetDataFrameSize(spi_dev); if (size == 0) return CSI_ERROR; if (DataFrameSize > 8) { /* 16~9 bits mode */ spi->tx_size = size >> 1; // 2 bytes(16 bit) every transfer } else { /* 8~4 bits mode */ spi->tx_size = size; // 1 byte(8 bit) every transfer } spi->tx_data = (uint8_t *)data; SSI_INTConfig(spi_dev, (BIT_IMR_TXOIM | BIT_IMR_TXEIM), ENABLE); return CSI_OK; } int32_t csi_spi_receive(csi_spi_t *spi, void *data, uint32_t size, uint32_t timeout) { uint8_t spi_idx = spi->dev.idx; SPI_TypeDef *spi_dev = SPI_DEV_TABLE[spi_idx].SPIx; uint32_t DataFrameSize = SSI_GetDataFrameSize(spi_dev); int32_t cnt = 0; uint32_t StartCount = 0; StartCount = SYSTIMER_TickGet(); while (1) { if (SSI_Readable(spi_dev)) { if (data != NULL) { if (DataFrameSize > 8) { /* 16~9 bits mode */ *((uint16_t *)(data)) = (uint16_t)SSI_ReadData(spi_dev); data = (void *)(((uint16_t *)data) + 1); cnt += 2; } else { /* 8~4 bits mode */ *((uint8_t *)(data)) = (uint8_t)SSI_ReadData(spi_dev); data = (void *)(((uint8_t *)data) + 1); cnt++; } } else { /* for Master mode, doing TX also will got RX data, so drop the dummy data */ SSI_ReadData(spi_dev); } } else { aos_msleep(1); } if (cnt == size) break; if (SYSTIMER_GetPassTime(StartCount) > timeout) { break; } } return cnt; } csi_error_t csi_spi_receive_async(csi_spi_t *spi, void *data, uint32_t size) { uint8_t spi_idx = spi->dev.idx; SPI_TypeDef *spi_dev = SPI_DEV_TABLE[spi_idx].SPIx; SSI_InitTypeDef *SSI_InitStruct = (SSI_InitTypeDef *)spi->priv; uint32_t DataFrameSize = SSI_GetDataFrameSize(spi_dev); if (size == 0) return CSI_ERROR; /* As a Slave mode, if the peer(Master) side is power off, the BUSY flag is always on */ if (SSI_Busy(spi_dev)) { printf("%s:SSI is busy\n", __func__); return CSI_BUSY; } if (DataFrameSize > 8) { /* 16~9 bits mode */ spi->rx_size = size >> 1; // 2 bytes(16 bit) every transfer } else { /* 8~4 bits mode */ spi->rx_size = size; // 1 byte(8 bit) every transfer } spi->rx_data = (uint8_t *)data; SSI_INTConfig(spi_dev, (BIT_IMR_RXFIM | BIT_IMR_RXOIM | BIT_IMR_RXUIM), ENABLE); if (SSI_InitStruct->SPI_Role == SSI_MASTER) { /* as Master mode, it need to push data to TX FIFO to generate clock out then the slave can transmit data out */ // send some dummy data out if (DataFrameSize > 8) { /* 16~9 bits mode */ spi->tx_size = size >> 1; // 2 bytes(16 bit) every transfer } else { /* 8~4 bits mode */ spi->tx_size = size; // 1 byte(8 bit) every transfer } spi->tx_data = (void *)NULL; SSI_INTConfig(spi_dev, (BIT_IMR_TXOIM | BIT_IMR_TXEIM), ENABLE); } return CSI_OK; } int32_t csi_spi_send_receive(csi_spi_t *spi, const void *data_out, void *data_in, uint32_t size, uint32_t timeout) { uint8_t spi_idx = spi->dev.idx; SPI_TypeDef *spi_dev = SPI_DEV_TABLE[spi_idx].SPIx; uint32_t DataFrameSize = SSI_GetDataFrameSize(spi_dev); int32_t cnt = 0; uint32_t StartCount = 0; StartCount = SYSTIMER_TickGet(); while (1) { if (SSI_Writeable(spi_dev)) { if (DataFrameSize > 8) { /* 16~9 bits mode */ SSI_WriteData(spi_dev, *((uint16_t *)(data_out))); data_out = (void *)(((uint16_t *)data_out) + 1); cnt += 2; if (SSI_Readable(spi_dev)) { *((uint16_t *)(data_in)) = (uint16_t)SSI_ReadData(spi_dev); data_in = (void *)(((uint16_t *)data_in) + 1); } } else { /* 8~4 bits mode */ SSI_WriteData(spi_dev, *((uint8_t *)(data_out))); data_out = (void *)(((uint8_t *)data_out) + 1); cnt++; if (SSI_Readable(spi_dev)) { *((uint8_t *)(data_in)) = (uint8_t)SSI_ReadData(spi_dev); data_in = (void *)(((uint8_t *)data_in) + 1); } } } else { aos_msleep(1); } if (cnt == size) break; if (SYSTIMER_GetPassTime(StartCount) > timeout) { break; } } return cnt; } void csi_spi_select_slave(csi_spi_t *spi, uint32_t slave_num) { uint8_t spi_idx = spi->dev.idx; SPI_TypeDef *spi_dev = SPI_DEV_TABLE[spi_idx].SPIx; SSI_InitTypeDef *SSI_InitStruct = (SSI_InitTypeDef *)spi->priv; if (SSI_InitStruct->SPI_Role == SSI_MASTER) { SSI_SetSlaveEnable(spi_dev, slave_num); } else { assert_param(0); } } csi_error_t csi_spi_get_state(csi_spi_t *spi, csi_state_t *state) { uint8_t spi_idx = spi->dev.idx; SPI_TypeDef *spi_dev = SPI_DEV_TABLE[spi_idx].SPIx; state->readable = SSI_Readable(spi_dev); state->writeable = SSI_Writeable(spi_dev); state->error = SSI_Busy(spi_dev); return CSI_OK; } csi_error_t csi_spi_link_dma(csi_spi_t *spi, csi_dma_ch_t *tx_dma, csi_dma_ch_t *rx_dma) { spi->tx_dma = tx_dma; spi->rx_dma = rx_dma; return CSI_OK; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/csi_driver/spi/spi.c
C
apache-2.0
16,335
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "objects.h" #include "PinNames.h" #include "pinmap.h" #include "ameba_soc.h" #include <drv/spiflash.h> #include <aos/mtd.h> #include <aos/mtdpart.h> #include <aos/hal/flash.h> csi_error_t csi_spiflash_spi_init(csi_spiflash_t *spiflash, uint32_t spi_idx, void *spi_cs_callback) { spiflash->spi_qspi.spi.dev.idx = spi_idx; //spiflash->spi_qspi.spi.dev.reg_base = SPIC; spiflash->spi_cs_callback = spi_cs_callback; return CSI_OK; } void csi_spiflash_spi_uninit(csi_spiflash_t *spiflash) { if(spiflash->spi_cs_callback != NULL) spiflash->spi_cs_callback = NULL; } csi_error_t csi_spiflash_get_flash_info(csi_spiflash_t *spiflash, csi_spiflash_info_t *flash_info) { /* To avoid gcc warnings */ ( void ) spiflash; uint8_t flash_id[4]; FLASH_Write_Lock(); FLASH_RxCmd(flash_init_para.FLASH_cmd_rd_id, 3, flash_id); FLASH_Write_Unlock(); flash_info->flash_id = (flash_id[2] << 16) |(flash_id[1] << 8) |flash_id[0]; /* get flash vender by flash id */ flash_info->xip_addr = SPI_FLASH_BASE; flash_info->sector_size = 0x1000; flash_info->page_size = 256; /* get flash size by flash vendor */ flash_info->flash_size = 0x200000; return CSI_OK; } int32_t csi_spiflash_read(csi_spiflash_t *spiflash, uint32_t offset, void *data, uint32_t size) { /* To avoid gcc warnings */ ( void ) spiflash; //assert_param(data != NULL); if(data == NULL) return CSI_ERROR; uint32_t offset_to_align; uint32_t i; uint32_t read_word; uint8_t *ptr; uint8_t *pbuf; int32_t read_len = 0; FLASH_Write_Lock(); offset_to_align = offset & 0x03; pbuf = (uint8_t *)data; if (offset_to_align != 0) { /* the start address is not 4-bytes aligned */ read_word = HAL_READ32(SPI_FLASH_BASE, (offset - offset_to_align)); ptr = (uint8_t*)&read_word + offset_to_align; offset_to_align = 4 - offset_to_align; for (i=0;i<offset_to_align;i++) { *pbuf = *(ptr+i); pbuf++; size--; if (size == 0) { break; } } } /* address = next 4-bytes aligned */ offset = (((offset-1) >> 2) + 1) << 2; ptr = (uint8_t*)&read_word; if ((uint32_t)pbuf & 0x03) { while (size >= 4) { read_word = HAL_READ32(SPI_FLASH_BASE, offset); for (i=0;i<4;i++) { *pbuf = *(ptr+i); pbuf++; } offset += 4; size -= 4; read_len += 4; } } else { while (size >= 4) { *((uint32_t *)pbuf) = HAL_READ32(SPI_FLASH_BASE, offset); pbuf += 4; offset += 4; size -= 4; read_len += 4; } } if (size > 0) { read_word = HAL_READ32(SPI_FLASH_BASE, offset); for (i=0;i<size;i++) { *pbuf = *(ptr+i); pbuf++; } } read_len += size; FLASH_Write_Unlock(); return read_len; } int32_t csi_spiflash_program(csi_spiflash_t *spiflash, uint32_t offset, const void *data, uint32_t size) { /* To avoid gcc warnings */ ( void ) spiflash; // Check address: 4byte aligned & page(256bytes) aligned uint32_t page_begin = offset & (~0xff); uint32_t page_end = (offset + size) & (~0xff); uint32_t page_cnt = ((page_end - page_begin) >> 8) + 1; uint32_t addr_begin = offset; uint32_t addr_end = (page_cnt == 1) ? (offset + size) : (page_begin + 0x100); uint32_t length = addr_end - addr_begin; uint8_t *buffer = (uint8_t *)data; uint8_t write_data[12]; uint32_t offset_to_align; uint32_t read_word; uint32_t i; int32_t write_len = 0; FLASH_Write_Lock(); while(page_cnt){ offset_to_align = addr_begin & 0x3; write_len += length; if(offset_to_align != 0){ read_word = HAL_READ32(SPI_FLASH_BASE, addr_begin - offset_to_align); for(i = offset_to_align;i < 4;i++){ read_word = (read_word & (~(0xff << (8*i)))) |( (*buffer) <<(8*i)); length--; buffer++; if(length == 0) break; } FLASH_TxData12B(addr_begin - offset_to_align, 4, (uint8_t*)&read_word); } addr_begin = (((addr_begin-1) >> 2) + 1) << 2; for(;length >= 12 ;length -= 12){ _memcpy(write_data, buffer, 12); FLASH_TxData12B(addr_begin, 12, write_data); buffer += 12; addr_begin += 12; } for(;length >= 4; length -=4){ _memcpy(write_data, buffer, 4); FLASH_TxData12B(addr_begin, 4, write_data); buffer += 4; addr_begin += 4; } if(length > 0){ read_word = HAL_READ32(SPI_FLASH_BASE, addr_begin); for( i = 0;i < length;i++){ read_word = (read_word & (~(0xff << (8*i)))) | ((*buffer) <<(8*i)); buffer++; } FLASH_TxData12B(addr_begin, 4, (uint8_t*)&read_word); } page_cnt--; addr_begin = addr_end; addr_end = (page_cnt == 1) ? (offset + size) : (((addr_begin>>8) + 1)<<8); length = addr_end - addr_begin; } DCache_Invalidate(SPI_FLASH_BASE + offset, size); FLASH_Write_Unlock(); return write_len; } csi_error_t csi_spiflash_erase(csi_spiflash_t *spiflash, uint32_t offset, uint32_t size) { /* To avoid gcc warnings */ ( void ) spiflash; /* Sector alignment */ size = (((size - 1) >> 12 ) + 1) << 12; FLASH_Write_Lock(); while(size) { FLASH_Erase(EraseSector, offset); DCache_Invalidate(SPI_FLASH_BASE + offset, 0x1000); offset += 0x1000; size -= 0x1000; } FLASH_Write_Unlock(); return CSI_OK; } static aos_mtd_t g_mtd_nor_dev; struct part_info { uint32_t cnt; struct mtd_part *part; }; static int get_mtd_part(struct part_info *info) { mtd_partition_t *p; struct mtd_part *parts; parts = calloc(mtd_partitions_amount, sizeof(struct mtd_part)); if (parts == NULL) { return -ENOMEM; } for (int i = 0, j = 0; i < mtd_partitions_amount; i++) { p = &mtd_partitions[i]; parts[j].name_std = p->partition_name_std; parts[j].name = p->partition_name; parts[j].offset = p->partition_start_addr; parts[j].size = p->partition_length; j++; } info->cnt = mtd_partitions_amount; info->part = parts; return 0; } int csi_flash_init() { struct part_info info = {0}; uint32_t blk_size = 4096; uint32_t page_size = 256; int ret; printf("%s:%d begin..\r\n", __func__, __LINE__); if (get_mtd_part(&info)) { printf("%s:%d get_mtd_part failed.\r\n", __func__, __LINE__); return -1; } ret = aos_mtd_nor_init(&g_mtd_nor_dev, blk_size, page_size); if (ret != 0) { printf("%s:%d aos_mtd_nor_init failed, ret:%d\r\n", __func__, __LINE__, ret); return -2; } ret = aos_mtd_register(&g_mtd_nor_dev, info.part, info.cnt); if (ret < 0) { printf("%s:%d aos_mtd_register failed, ret:%d\n", __func__, __LINE__, ret); } else { printf("%s:%d done.\r\n", __func__, __LINE__); } return ret; } LEVEL1_DRIVER_ENTRY(csi_flash_init)
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/csi_driver/spiflash/spiflash.c
C
apache-2.0
7,486
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "objects.h" #include <drv/timer.h> #define GTIMER_MAX 4 static void csi_gtimer_timeout_handler(uint32_t data) { csi_timer_t *timer = (csi_timer_t *)data; uint32_t tid = timer->dev.idx; RTIM_INTClear(TIMx[tid]); if (timer->callback != NULL) { timer->callback(timer,timer->arg); } } csi_error_t csi_timer_init(csi_timer_t *timer, uint32_t idx) { if(!timer) return CSI_ERROR; if(idx > GTIMER_MAX) return CSI_ERROR; timer->priv = (RTIM_TimeBaseInitTypeDef *)malloc(sizeof(RTIM_TimeBaseInitTypeDef)); RTIM_TimeBaseInitTypeDef *TIM_InitStruct = (RTIM_TimeBaseInitTypeDef *)timer->priv; timer->dev.idx = idx; RTIM_TimeBaseStructInit(TIM_InitStruct); TIM_InitStruct->TIM_Idx = (uint8_t)idx; TIM_InitStruct->TIM_UpdateEvent = ENABLE; /* UEV enable */ TIM_InitStruct->TIM_UpdateSource = TIM_UpdateSource_Overflow; TIM_InitStruct->TIM_ARRProtection = ENABLE; RTIM_TimeBaseInit(TIMx[idx], TIM_InitStruct, TIMx_irq[idx], (IRQ_FUN)csi_gtimer_timeout_handler, (u32)timer); return CSI_OK; } void csi_timer_uninit(csi_timer_t *timer) { uint32_t tid = timer->dev.idx; RTIM_DeInit(TIMx[tid]); if(timer && timer->priv) { free(timer->priv); timer->priv = NULL; } } csi_error_t csi_timer_start(csi_timer_t *timer, uint32_t timeout_us) { uint32_t tid = timer->dev.idx; uint32_t temp = (uint32_t)((float)timeout_us / 1000000 * 32768); RTIM_ChangePeriodImmediate(TIMx[tid], temp); RTIM_INTConfig(TIMx[tid], TIM_IT_Update, ENABLE); RTIM_Cmd(TIMx[tid], ENABLE); return CSI_OK; } void csi_timer_stop(csi_timer_t *timer) { uint32_t tid = timer->dev.idx; RTIM_Cmd(TIMx[tid], DISABLE); } uint32_t csi_timer_get_remaining_value(csi_timer_t *timer) { uint32_t tid = timer->dev.idx; uint32_t tick; uint32_t load; uint32_t time_us; RTIM_TypeDef* TIM = TIMx[tid]; tick = RTIM_GetCount(TIM); load = (uint32_t)((float)TIM->ARR * 1000000 / 32768); time_us = load - (uint32_t)((float)tick * 1000000 / 32768); return time_us; } uint32_t csi_timer_get_load_value(csi_timer_t *timer) { uint32_t tid = timer->dev.idx; uint32_t time_us; RTIM_TypeDef* TIM = TIMx[tid]; time_us = (uint32_t)((float)TIM->ARR * 1000000 / 32768); return time_us; } bool csi_timer_is_running(csi_timer_t *timer) { uint32_t tid = timer->dev.idx; uint32_t time_us; RTIM_TypeDef* TIM = TIMx[tid]; if(TIM->EN & TIM_CR_CNT_RUN) return TRUE; return FALSE; } csi_error_t csi_timer_attach_callback(csi_timer_t *timer, void *callback, void *arg) { timer->callback = callback; timer->arg = arg; return CSI_OK; } void csi_timer_detach_callback(csi_timer_t *timer) { timer->callback = NULL; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/csi_driver/timer/timer.c
C
apache-2.0
2,984
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <objects.h> #include <pinmap.h> #include <drv/uart.h> #define EVENT_RX_READY ((uint32_t)1 << 0) typedef struct { UART_InitTypeDef init_data; aos_event_t event; } uart_priv_t; static const PinMap CSI_PinMap_UART_TX[] = { { PA_12, UART_3, PIN_DATA(PullUp, PINMUX_FUNCTION_UART), }, { PA_18, UART_0, PIN_DATA(PullUp, PINMUX_FUNCTION_UART), }, { PA_7, UART_2, PIN_DATA(PullUp, PINMUX_FUNCTION_LOGUART), }, { NC, NC, 0, }, }; static const PinMap CSI_PinMap_UART_RX[] = { { PA_13, UART_3, PIN_DATA(PullUp, PINMUX_FUNCTION_UART), }, { PA_19, UART_0, PIN_DATA(PullUp, PINMUX_FUNCTION_UART), }, { PA_8, UART_2, PIN_DATA(PullUp, PINMUX_FUNCTION_LOGUART), }, { NC, NC, 0, }, }; static PinName uart_tx_pin_get(uint32_t uart_idx, const PinMap *map) { PinName tx; while (map->peripheral != NC) { if (map->peripheral == uart_idx) { tx = map->pin; break; } map++; } return tx; } static PinName uart_rx_pin_get(uint32_t uart_idx, const PinMap *map) { PinName rx; while (map->peripheral != NC) { if (map->peripheral == uart_idx) { rx = map->pin; break; } map++; } return rx; } static uint32_t uart_idx_get(uint32_t idx) { if (idx == 0) return UART_0; else if (idx == 2) return UART_2; else if (idx == 3) return UART_3; else assert_param(0); return UART_1; } static uint32_t uart_irqhandler(void *data) { volatile uint8_t reg_iir; uint8_t IntId; uint32_t RegValue; csi_uart_t *uart = (csi_uart_t *)data; UART_TypeDef *UARTx = UART_DEV_TABLE[uart->dev.idx].UARTx; uart_priv_t *priv = (uart_priv_t *)uart->priv; reg_iir = UART_IntStatus(UARTx); if ((reg_iir & RUART_IIR_INT_PEND) != 0) { /* No pending IRQ */ return 0; } IntId = (reg_iir & RUART_IIR_INT_ID) >> 1; switch (IntId) { case RUART_LP_RX_MONITOR_DONE: RegValue = UART_RxMonitorSatusGet(UARTx); break; case RUART_MODEM_STATUS: RegValue = UART_ModemStatusGet(UARTx); break; case RUART_RECEIVE_LINE_STATUS: RegValue = UART_LineStatusGet(UARTx); break; case RUART_TX_FIFO_EMPTY: if (UART_GetTxFlag(uart->dev.idx)) { int32_t cnt = 16; while (cnt > 0 && uart->tx_size > 0) { UART_CharPut(UARTx, *uart->tx_data); uart->tx_size--; uart->tx_data++; cnt--; } if (0 == uart->tx_size) { /* Mask UART TX FIFO empty */ UART_INTConfig(UARTx, RUART_IER_ETBEI, DISABLE); UART_SetTxFlag(uart->dev.idx, 0); if (uart->callback != NULL) { uart->callback(uart, UART_EVENT_SEND_COMPLETE, NULL); } } } else { UART_INTConfig(UARTx, RUART_IER_ETBEI, DISABLE); } break; case RUART_RECEIVER_DATA_AVAILABLE: case RUART_TIME_OUT_INDICATION: if (UART_GetRxFlag(uart->dev.idx) == STATERX_INT) { uint32_t TransCnt = 0; TransCnt = UART_ReceiveDataTO(UARTx, uart->rx_data, uart->rx_size, 1); uart->rx_size -= TransCnt; uart->rx_data += TransCnt; if (uart->rx_size == 0) { /* Disable RX Interrupt */ UART_INTConfig(UARTx, (RUART_IER_ERBI | RUART_IER_ELSI | RUART_IER_ETOI), DISABLE); UART_SetRxFlag(uart->dev.idx, 0); if (uart->callback != NULL) { uart->callback(uart, UART_EVENT_RECEIVE_COMPLETE, NULL); } } } else { /* Call Rx data ready callback */ RegValue = (UART_LineStatusGet(UARTx)); if (RegValue & RUART_LINE_STATUS_REG_DR) { (void)aos_event_set(&priv->event, EVENT_RX_READY, AOS_EVENT_OR); UART_INTConfig(UARTx, (RUART_IER_ERBI | RUART_IER_ELSI | RUART_IER_ETOI), DISABLE); UART_SetRxFlag(uart->dev.idx, 0); } } break; default: printf("Unknown Interrupt \n"); break; } return 0; } csi_error_t csi_uart_init(csi_uart_t *uart, uint32_t idx) { if (!uart) return CSI_ERROR; UART_TypeDef *UARTx = UART_DEV_TABLE[idx].UARTx; IRQn_Type IrqNum = UART_DEV_TABLE[idx].IrqNum; uart->priv = malloc(sizeof(uart_priv_t)); uart_priv_t *priv = (uart_priv_t *)uart->priv; UART_InitTypeDef *UART_InitStruct = &priv->init_data; if (aos_event_new(&priv->event, 0)) { free(uart->priv); uart->priv = NULL; return CSI_ERROR; } uart->dev.idx = idx; uart->dev.irq_num = IrqNum; /* Configure the UART pins */ uint32_t uart_idx = uart_idx_get(idx); printf("uart_idx:%x\n", uart_idx); PinName tx = uart_tx_pin_get(uart_idx, CSI_PinMap_UART_TX); PinName rx = uart_rx_pin_get(uart_idx, CSI_PinMap_UART_RX); pinmap_pinout(tx, CSI_PinMap_UART_TX); pinmap_pinout(rx, CSI_PinMap_UART_RX); pin_mode(tx, PullUp); pin_mode(rx, PullUp); printf("tx:%d,rx:%d\n", tx, rx); UART_StructInit(UART_InitStruct); UART_Init(UARTx, UART_InitStruct); InterruptRegister((IRQ_FUN)uart_irqhandler, IrqNum, (uint32_t)uart, 5); InterruptEn(IrqNum, 5); return CSI_OK; } void csi_uart_uninit(csi_uart_t *uart) { uint32_t uart_idx = uart->dev.idx; UART_TypeDef *UARTx = UART_DEV_TABLE[uart_idx].UARTx; IRQn_Type IrqNum = UART_DEV_TABLE[uart_idx].IrqNum; uart_priv_t *priv = (uart_priv_t *)uart->priv; UART_DeInit(UARTx); InterruptDis(IrqNum); InterruptUnRegister(IrqNum); if (uart && uart->priv) { aos_event_free(&priv->event); free(uart->priv); uart->priv = NULL; } } csi_error_t csi_uart_baud(csi_uart_t *uart, uint32_t baud) { uint32_t uart_idx = uart->dev.idx; UART_TypeDef *UARTx = UART_DEV_TABLE[uart_idx].UARTx; RCC_PeriphClockSource_UART(UARTx, UART_RX_CLK_XTAL_40M); UART_SetBaud(UARTx, baud); UART_RxCmd(UARTx, ENABLE); if (baud <= 500000) { if (uart_config[uart_idx].LOW_POWER_RX_ENABLE) { UART_MonitorParaConfig(UARTx, 100, ENABLE); UART_RxMonitorCmd(UARTx, ENABLE); RCC_PeriphClockSource_UART(UARTx, UART_RX_CLK_OSC_LP); UART_LPRxBaudSet(UARTx, baud, 2000000); UART_RxCmd(UARTx, ENABLE); } } return CSI_OK; } csi_error_t csi_uart_format(csi_uart_t *uart, csi_uart_data_bits_t data_bits, csi_uart_parity_t parity, csi_uart_stop_bits_t stop_bits) { uint32_t uart_idx = uart->dev.idx; UART_TypeDef *UARTx = UART_DEV_TABLE[uart_idx].UARTx; UART_InitTypeDef *UART_InitStruct = &((uart_priv_t *)uart->priv)->init_data; UART_RxCmd(UARTx, DISABLE); if (data_bits == UART_DATA_BITS_8) { UART_InitStruct->WordLen = RUART_WLS_8BITS; } else { UART_InitStruct->WordLen = RUART_WLS_7BITS; } switch (parity) { case UART_PARITY_ODD: UART_InitStruct->Parity = RUART_PARITY_ENABLE; UART_InitStruct->ParityType = RUART_ODD_PARITY; break; case UART_PARITY_EVEN: UART_InitStruct->Parity = RUART_PARITY_ENABLE; UART_InitStruct->ParityType = RUART_EVEN_PARITY; break; default: UART_InitStruct->Parity = RUART_PARITY_DISABLE; break; } if (stop_bits == UART_STOP_BITS_2) { UART_InitStruct->StopBit = RUART_STOP_BIT_2; } else { UART_InitStruct->StopBit = RUART_STOP_BIT_1; } UARTx->LCR = ((UART_InitStruct->WordLen) | (UART_InitStruct->StopBit << 2) | (UART_InitStruct->Parity << 3) | (UART_InitStruct->ParityType << 4) | (UART_InitStruct->StickParity << 5)); UART_RxCmd(UARTx, ENABLE); return CSI_OK; } csi_error_t csi_uart_attach_callback(csi_uart_t *uart, void *callback, void *arg) { uint32_t uart_idx = uart->dev.idx; UART_TypeDef *UARTx = UART_DEV_TABLE[uart_idx].UARTx; uart->callback = callback; UART_INTConfig(UARTx, RUART_IER_ERBI | RUART_IER_ELSI | RUART_IER_ETOI, ENABLE); UART_INTConfig(UARTx, RUART_IER_ETBEI, ENABLE); return CSI_OK; } void csi_uart_detach_callback(csi_uart_t *uart) { uart->callback = NULL; } int32_t csi_uart_send(csi_uart_t *uart, const void *data, uint32_t size, uint32_t timeout) { uint32_t uart_idx = uart->dev.idx; UART_TypeDef *UARTx = UART_DEV_TABLE[uart_idx].UARTx; uint32_t cnt = 0; uint32_t startcount = SYSTIMER_TickGet(); uart->tx_size = size; while (1) { if (UART_Writable(UARTx)) { UART_CharPut(UARTx, *(uint8_t *)data); data++; cnt++; } else { aos_msleep(1); } if (cnt == size) { break; } if (SYSTIMER_GetPassTime(startcount) > timeout) { break; } } return cnt; } int32_t csi_uart_receive(csi_uart_t *uart, void *data, uint32_t size, uint32_t timeout) { uint32_t uart_idx = uart->dev.idx; UART_TypeDef *UARTx = UART_DEV_TABLE[uart_idx].UARTx; uart_priv_t *priv = (uart_priv_t *)uart->priv; uint32_t cnt = 0; uint32_t startcount = SYSTIMER_TickGet(); uart->rx_size = size; while (1) { if (UART_Readable(UARTx)) { UART_CharGet(UARTx, (uint8_t *)data); data++; cnt++; } else { uint32_t val; if (cnt > 0) break; UART_INTConfig(UARTx, RUART_IER_ERBI | RUART_IER_ELSI | RUART_IER_ETOI, ENABLE); (void)aos_event_get(&priv->event, EVENT_RX_READY, AOS_EVENT_OR_CLEAR, &val, 20); } if (cnt == size) { break; } if (SYSTIMER_GetPassTime(startcount) > timeout) { break; } } UART_INTConfig(UARTx, RUART_IER_ERBI | RUART_IER_ELSI | RUART_IER_ETOI, DISABLE); (void)aos_event_set(&priv->event, ~EVENT_RX_READY, AOS_EVENT_AND); return cnt; } csi_error_t csi_uart_send_async(csi_uart_t *uart, const void *data, uint32_t size) { uint32_t uart_idx = uart->dev.idx; UART_TypeDef *UARTx = UART_DEV_TABLE[uart_idx].UARTx; int32_t ret = 0; int32_t cnt = 16; uint8_t *ptxbuf = (uint8_t *)data; assert_param(ptxbuf != NULL); assert_param(size != 0); if (UART_GetTxFlag(uart_idx)) { printf("uart int tx: busy\n"); return CSI_BUSY; } uart->tx_size = size; uart->tx_data = ptxbuf; UART_SetTxFlag(uart_idx, STATETX_INT); while (cnt > 0 && uart->tx_size > 0) { UART_CharPut(UARTx, *uart->tx_data); uart->tx_size--; uart->tx_data++; cnt--; } if (0 == uart->tx_size) { UART_INTConfig(UARTx, RUART_IER_ETBEI, DISABLE); UART_SetTxFlag(uart_idx, 0); if (uart->callback != NULL) { uart->callback(uart, UART_EVENT_SEND_COMPLETE, NULL); } } else { /* Enable Tx FIFO empty interrupt */ UART_INTConfig(UARTx, RUART_IER_ETBEI, ENABLE); } return CSI_OK; } csi_error_t csi_uart_receive_async(csi_uart_t *uart, void *data, uint32_t size) { uint32_t uart_idx = uart->dev.idx; UART_TypeDef *UARTx = UART_DEV_TABLE[uart_idx].UARTx; uint32_t TransCnt = 0; uint8_t *prxbuf = (uint8_t *)data; assert_param(prxbuf != NULL); assert_param(size != 0); if (UART_GetRxFlag(uart_idx)) { printf("uart int rx: busy\n"); return CSI_BUSY; } uart->rx_size = size; uart->rx_data = (uint8_t *)data; UART_SetRxFlag(uart_idx, STATERX_INT); /* Could be the RX FIFO has some data already */ TransCnt = UART_ReceiveDataTO(UARTx, uart->rx_data, uart->rx_size, 1); uart->rx_size -= TransCnt; uart->rx_data += TransCnt; if (uart->rx_size == 0) { UART_INTConfig(UARTx, RUART_IER_ERBI | RUART_IER_ELSI | RUART_IER_ETOI, DISABLE); UART_SetRxFlag(uart_idx, 0); if (uart->callback != NULL) { uart->callback(uart, UART_EVENT_RECEIVE_COMPLETE, NULL); } } else { /* Enable RX Interrupt */ UART_INTConfig(UARTx, RUART_IER_ERBI | RUART_IER_ELSI | RUART_IER_ETOI, ENABLE); } return CSI_OK; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/csi_driver/uart/uart.c
C
apache-2.0
12,499
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "objects.h" #include "ameba_soc.h" #include "cmsis.h" #include <drv/wdt.h> csi_error_t csi_wdt_init(csi_wdt_t *wdt, uint32_t idx) { if(!wdt) return CSI_ERROR; wdt->priv = (WDG_InitTypeDef *)malloc(sizeof(WDG_InitTypeDef)); wdt->dev.idx = idx; return CSI_OK; } void csi_wdt_uninit(csi_wdt_t *wdt) { if(wdt && wdt->priv) { free(wdt->priv); wdt->priv = NULL; } } csi_error_t csi_wdt_set_timeout(csi_wdt_t *wdt, uint32_t ms) { WDG_InitTypeDef *WDG_InitStruct = (WDG_InitTypeDef *)wdt->priv; uint32_t CountProcess; uint32_t DivFacProcess; WDG_Scalar(ms, &CountProcess, &DivFacProcess); WDG_InitStruct->CountProcess = CountProcess; WDG_InitStruct->DivFacProcess = DivFacProcess; WDG_Init(WDG_InitStruct); return CSI_OK; } csi_error_t csi_wdt_start(csi_wdt_t *wdt) { WDG_Cmd(ENABLE); return CSI_OK; } void csi_wdt_stop(csi_wdt_t *wdt) { WDG_Cmd(DISABLE); } csi_error_t csi_wdt_feed(csi_wdt_t *wdt) { WDG_Refresh(); return CSI_OK; } static uint32_t wdt_irqhandler(IN VOID *Data) { csi_wdt_t *wdt = (csi_wdt_t *)Data; if (wdt->callback) wdt->callback(wdt,NULL); else printf("wdt irq happens, but no callback is set\r\n"); return CSI_OK; } csi_error_t csi_wdt_attach_callback(csi_wdt_t *wdt, void *callback, void *arg) { wdt->callback = callback; WDG_IrqInit((VOID *)wdt_irqhandler, (uint32_t)wdt); return CSI_OK; } void csi_wdt_detach_callback(csi_wdt_t *wdt) { printf("%s - %d\r\n", __func__, __LINE__); wdt->callback = NULL; return; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/csi_driver/wdt/wdt.c
C
apache-2.0
1,745
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # Copyright (C) 2021 Alibaba Group Holding Limited """ Generate the bin files including ota bin and the final bin files for chip rtl872xd. """ import sys import os import shutil import subprocess import platform home_path = os.path.expanduser("~") toolchain_path = os.path.join(home_path, ".aliot", "arm-ali-aoseabi", "main", "bin") objcopy = os.path.join(toolchain_path, "arm-ali-aoseabi-objcopy") nm = os.path.join(toolchain_path, "arm-ali-aoseabi-nm") strip = os.path.join(toolchain_path, "arm-ali-aoseabi-strip") cc_size = os.path.join(toolchain_path, "arm-ali-aoseabi-size") objdump = os.path.join(toolchain_path, "arm-ali-aoseabi-objdump") output_dir = os.getcwd() amebaz_dir = os.path.join(output_dir, "..", "..", "hardware", "chip", "rtl872xd") bin_dir = os.path.join(amebaz_dir, "bin") all_bin_output_file = os.path.join(output_dir, "binary", "all.bin") bin_output_file = os.path.join(output_dir, "binary", "burn.bin") km0_boot_file = os.path.join(bin_dir, "km0_boot_all.bin") km02_boot_file = os.path.join(bin_dir, "km0_boot_all_2nd.bin") km4_boot_file = os.path.join(bin_dir, "km4_boot_all.bin") ate_file = os.path.join(bin_dir, "ate.bin") KM0_BOOT_OFFSET = "0x0" KM4_BOOT_OFFSET = "0x4000" ATE_OFFSET = "0x188000" OTA_OFFSET = "0x6000" build_bin_py = os.path.join(amebaz_dir, "release", "auto_build_tool", "build_bin.py") release_dir = os.path.join(amebaz_dir, "release") def concatenate_bin_file(file_lists, output_file_path): """Concatenate multiple binary files. Concatenate binary files in file_lists array into the output_file_path. Args: file_lists: The input files tuple. output_file_path: The output file containing all input files. Returns: None """ output_file = open(output_file_path, "ab") for i in file_lists: tmpFile = open(i, "rb") fileContent = tmpFile.read() output_file.write(fileContent) tmpFile.close() output_file.close() def gen_km0_km4_bin(raw_bin_file): """Generate the final bin files. Generate the bin files including ota bin and the final km0_km4_image2.bin files. Args: raw_bin_file: The compiled raw bin file, e.g. /usr/xxxx/alios/solutions/helloworld_demo/out/ helloworld_demo@haas200.bin Returns: None """ raw_bin_file_array = raw_bin_file.split(".bin") raw_elf_file = raw_bin_file_array[0] + ".elf" print("========= linker img2_ns start =========") image_target_folder = os.path.join(output_dir, "binary") if os.path.exists(image_target_folder): shutil.rmtree(image_target_folder, True) os.makedirs(image_target_folder, 0o755) target_img2_axf = os.path.join(image_target_folder, "target_img2.axf") shutil.copyfile(raw_elf_file, target_img2_axf) target_img2_map = os.path.join(image_target_folder, "target_img2.map") subprocess.call(nm + " " + target_img2_axf + " | " + "sort " + "> " + target_img2_map, shell=True) target_img2_asm = os.path.join(image_target_folder, "target_img2.asm") subprocess.call(objdump + " -d " + target_img2_axf + " > " + target_img2_asm, shell=True) target_pure_img2_axf = os.path.join(image_target_folder, "target_pure_img2.axf") shutil.copyfile(target_img2_axf, target_pure_img2_axf) subprocess.call([strip, target_pure_img2_axf]) target_pure_img2_map = os.path.join(image_target_folder, "target_pure_img2.map") subprocess.call(nm + " " + target_pure_img2_axf + " | sort > " + target_pure_img2_map, shell=True) ram2_bin = os.path.join(image_target_folder, "ram_2.bin") subprocess.call([objcopy, "-j", ".ram_image2.entry", "-j", ".ram_image2.text", "-j", ".ram_image2.data", "-Obinary", target_pure_img2_axf, ram2_bin]) xip_image2_bin = os.path.join(image_target_folder, "xip_image2.bin") subprocess.call([objcopy, "-j", ".xip_image2.text", "-Obinary", target_pure_img2_axf, xip_image2_bin]) psram2_bin = os.path.join(image_target_folder, "psram_2.bin") subprocess.call([objcopy, "-j", ".psram_image2.text", "-j", ".psram_image2.data", "-Obinary", target_pure_img2_axf, psram2_bin]) print("========== Image Info HEX ==========") subprocess.call([cc_size, "-A", "--radix=16", target_img2_axf]) subprocess.call([cc_size, "-t", "--radix=16", target_img2_axf]) print("========== Image Info HEX ==========") print("========== Image Info DEC ==========") subprocess.call([cc_size, "-A", "--radix=10", target_img2_axf]) subprocess.call([cc_size, "-t", "--radix=10", target_img2_axf]) print("========== Image Info DEC ==========") print("========== linker img2_ns end ==========") print("========== Image manipulating start ==========") prepend_header_py = os.path.join(amebaz_dir, "prepend_header.py") subprocess.call(["python", prepend_header_py, ram2_bin, "__ram_image2_text_start__", target_img2_map]) subprocess.call(["python", prepend_header_py, xip_image2_bin, "__flash_text_start__", target_img2_map]) subprocess.call(["python", prepend_header_py, psram2_bin, "__psram_image2_text_start__", target_img2_map]) xip_image2_prepend_bin_path = os.path.join(image_target_folder, "xip_image2_prepend.bin") ram2_prepend_bin_path = os.path.join(image_target_folder, "ram_2_prepend.bin") psram2_prepend_bin_path = os.path.join(image_target_folder, "psram_2_prepend.bin") km4_image2_all_bin_path = os.path.join(image_target_folder, "km4_image2_all.bin") concatenate_bin_file([xip_image2_prepend_bin_path, ram2_prepend_bin_path, psram2_prepend_bin_path], km4_image2_all_bin_path) padPy = os.path.join(amebaz_dir, "pad.py") subprocess.call(["python", padPy, km4_image2_all_bin_path]) km0_image2_all_bin_path = os.path.join(bin_dir, "km0_image2_all.bin") km0_km4_image2_bin_path = os.path.join(image_target_folder, "km0_km4_image2.bin") concatenate_bin_file([km0_image2_all_bin_path, km4_image2_all_bin_path], km0_km4_image2_bin_path) shutil.copyfile(km0_km4_image2_bin_path, bin_output_file) print("========== Image manipulating end ==========") print("========== Generate littlefs, ota, ymodem bins ==========") shutil.copyfile(km02_boot_file, os.path.join(image_target_folder, "km0_boot_all_2nd.bin")) if platform.system() == "Windows": subprocess.call([os.path.join(amebaz_dir, "tools", "genfs.bat")]) else: subprocess.call([os.path.join(amebaz_dir, "tools", "genfs.sh")]) shutil.copyfile(os.path.join(amebaz_dir, "prebuild", "littlefs.bin"), os.path.join(image_target_folder, "littlefs.bin")) subprocess.call(["python", build_bin_py, "--target=" + km0_km4_image2_bin_path]) ymodem_burn_all_bin = os.path.join(image_target_folder, "ymodem_burn_all.bin") shutil.copyfile(km0_km4_image2_bin_path, ymodem_burn_all_bin) stupid_bin_file = os.path.join(release_dir, "auto_build_tool", "stupid.bin") ymodem_burn_all_bin_file_hdl = open(ymodem_burn_all_bin, "r+b") stupid_bin_file_hdl = open(stupid_bin_file, "rb") stupid_bin_file_content = stupid_bin_file_hdl.read() stupid_bin_file_hdl.close() ymodem_burn_all_bin_file_hdl.seek(0) ymodem_burn_all_bin_file_hdl.write(stupid_bin_file_content) ymodem_burn_all_bin_file_hdl.close() shutil.copyfile(ymodem_burn_all_bin, os.path.join(release_dir, "write_flash_gui", "ota_bin", "ymodem_burn_all.bin")) ota_bin_dir = os.path.join(release_dir, "write_flash_gui", "ota_bin") shutil.copyfile(os.path.join(ota_bin_dir, "ota_rtos_ota_all.bin"), os.path.join(image_target_folder, "ota_burn_all.bin")) shutil.copyfile(os.path.join(ota_bin_dir, "ota_rtos_ota_xz.bin.xz"), os.path.join(image_target_folder, "ota_burn_xz.bin")) shutil.copyfile(os.path.join(ota_bin_dir, "ota_rtos_ota_xz.bin.xz"), os.path.join(ota_bin_dir, "ymodem_burn_xz.bin")) shutil.copyfile(os.path.join(ota_bin_dir, "ymodem_burn_xz.bin"), os.path.join(image_target_folder, "ymodem_burn_xz.bin")) print("========== Generate littlefs, ota, ymodem bins end ==========") if __name__ == "__main__": # e.g. args: --target= # "/usr/xxxx/alios/solutions/helloworld_demo/out/helloworld_demo@haas200.bin" args = sys.argv[1].split("=") gen_km0_km4_bin(args[1])
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/gen_crc_bin.py
Python
apache-2.0
8,500
#include <stdint.h> #include "analogin_api.h" #include "aos/hal/adc.h" static analogin_t hal_adc[8]; static u32 adc_pin2chan[8][2]={ {PB_4, 0}, {PB_5, 1}, {PB_6, 2}, {PB_7, 3}, {PB_1, 4}, {PB_2, 5}, {PB_3, 6}, {VBAT_MEAS, 7} }; /** * Initialises an ADC interface, Prepares an ADC hardware interface for sampling * * @param[in] adc the interface which should be initialised * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_adc_init(adc_dev_t *adc) { adc->priv = &hal_adc[adc->port]; analogin_init(adc->priv, adc_pin2chan[adc->port][0]); return 0; } /** * Takes a single sample from an ADC interface * * @param[in] adc the interface which should be sampled * @param[out] output pointer to a variable which will receive the sample * @param[in] timeout ms timeout * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_adc_value_get(adc_dev_t *adc, uint32_t *output, uint32_t timeout) { uint32_t startcount = SYSTIMER_TickGet(); analogin_t *adc_t = adc->priv; uint8_t ChIdx = adc_t->adc_idx; uint32_t data; /* Set channel index into channel switch list*/ ADC->ADC_CHSW_LIST[0] = ChIdx; /* Clear FIFO */ ADC_ClearFIFO(); /* SW trigger to sample */ ADC_SWTrigCmd(ENABLE); while(1){ if(ADC_Readable()) break; if(SYSTIMER_GetPassTime(startcount)>timeout) return -1; } ADC_SWTrigCmd(DISABLE); data = ADC_Read(); *output = data & BIT_MASK_DAT_GLOBAL; return 0; } /** * De-initialises an ADC interface, Turns off an ADC hardware interface * * @param[in] adc the interface which should be de-initialised * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_adc_finalize(adc_dev_t *adc) { analogin_deinit(adc->priv); }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/adc.c
C
apache-2.0
1,906
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <ulog/ulog.h> #include <string.h> #include <stdio.h> #include <aos/list.h> #include "audio_rtos.h" #include "control.h" #include "drv/gpio.h" #include "audio_internel.h" #define LOG_TAG "[haas200_audio]" pcm_stream_handler_t audio_stream_hdl = NULL; pcm_stream_handler_t playback_stream_hdl = NULL; pcm_stream_handler_t capture_stream_hdl = NULL; static int codec_hw_vol_get(struct audio_kcontrol *kcontrol, struct audio_ctl_elem_value *ucontrol); static int codec_hw_vol_put(struct audio_kcontrol *kcontrol, struct audio_ctl_elem_value *ucontrol); static int codec_hw_mute_state_get(struct audio_kcontrol *kcontrol, struct audio_ctl_elem_value *ucontrol); static int codec_hw_mute_state_put(struct audio_kcontrol *kcontrol, struct audio_ctl_elem_value *ucontrol); static const struct audio_kcontrol_new master_codec_controls[] = { SOC_SINGLE_EXT("Master Volume TX", /* master volume attribute name: defined in sound_mixer.h */ 0, 0, /* codec volume minimum value */ 100, /* codec volume maxmum value */ 0, codec_hw_vol_get, /* get codec volume api */ codec_hw_vol_put), /* set codec volume api */ SOC_SINGLE_EXT("Master Mute State", /* master mute attribute name: defined in sound_mixer.h */ 0, 0, /* codec mute state minimum value */ 1, /* codec mute state maxmum value */ 0, codec_hw_mute_state_get, /* get codec mute state */ codec_hw_mute_state_put), /* put codec mute state */ }; static int codec_hw_mute_state_get(struct audio_kcontrol *kcontrol, struct audio_ctl_elem_value *ucontrol) { int mute = 0; if(!kcontrol || !ucontrol) { LOGE(LOG_TAG, "%s:%d: invalid params. \r\n", __func__, __LINE__); return -1; } mute = rl6548_get_mute(); LOGD(LOG_TAG, "%s:%d: get mute state %d \r\n", __func__, __LINE__, mute); ucontrol->value.integer.value[0] = mute; return 0; } static int codec_hw_mute_state_put(struct audio_kcontrol *kcontrol, struct audio_ctl_elem_value *ucontrol) { int mute = 0; if(!kcontrol || !ucontrol) { LOGE(LOG_TAG, "%s:%d: invalid params. \r\n", __func__, __LINE__); return -1; } mute = ucontrol->value.integer.value[0]; LOGD(LOG_TAG, "%s:%d: set mute state %d \r\n", __func__, __LINE__, mute); rl6548_set_mute(mute); return 0; } static int codec_hw_vol_get(struct audio_kcontrol *kcontrol, struct audio_ctl_elem_value *ucontrol) { int volume = 0; if(!kcontrol || !ucontrol) { LOGE(LOG_TAG, "%s:%d: invalid params. \r\n", __func__, __LINE__); return -1; } // TBD: get codec volume, e.g. volume = ac97_get_vol(); volume = rl6548_volume_get(); LOGD(LOG_TAG, "%s:%d: get volume %d \r\n", __func__, __LINE__, volume); ucontrol->value.integer.value[0] = volume; return 0; } static int codec_hw_vol_put(struct audio_kcontrol *kcontrol, struct audio_ctl_elem_value *ucontrol) { int volume = 0, dac_vol = 0; if(!kcontrol || !ucontrol) { LOGE(LOG_TAG, "%s:%d: invalid params. \r\n", __func__, __LINE__); return -1; } volume = ucontrol->value.integer.value[0]; if (volume < 0) { volume = 0; } if (volume > 100) { volume = 100; } LOGD(LOG_TAG, "%s:%d: set volume %d \r\n", __func__, __LINE__, volume); // dac_vol = volume_step[volume]; // alsa_volume_set(volume, dac_vol); rl6548_volume_set(volume); return 0; } static pcm_stream_handler_t codec_pcm_stream_open(int mode, int sampleRate, int channels, pcm_stream_format_t format, aos_hdl_t *event_hdl) { int word_len = WL_16; if(format == PCM_STREAM_FORMAT_S8 ) { word_len = WL_8; } else if(format == PCM_STREAM_FORMAT_S16_LE) { word_len = WL_16; } else if(format == PCM_STREAM_FORMAT_S24_LE) { word_len = WL_24; } if(audio_stream_hdl == NULL) { audio_stream_hdl = (pcm_stream_handler_t) rl6548_audio_init(sampleRate, channels, word_len); } if(mode == PCM_STREAM_IN) { capture_stream_hdl = (char*)audio_stream_hdl + 1; LOGD(LOG_TAG, "%s:%d: capture_stream_hdl 0x%x, mode %d, sampleRate %d, channels %d, format %d \r\n", __func__, __LINE__, capture_stream_hdl, PCM_STREAM_OUT, sampleRate, channels, format); } else if (mode == PCM_STREAM_OUT) { playback_stream_hdl = (char*)audio_stream_hdl + 2; LOGD(LOG_TAG, "%s:%d: playback_stream_hdl 0x%x, mode %d, sampleRate %d, channels %d, format %d \r\n", __func__, __LINE__, playback_stream_hdl, PCM_STREAM_OUT, sampleRate, channels, format); } return audio_stream_hdl; } static int codec_pcm_stream_start(pcm_stream_handler_t hdl) { int ret = 0; if(NULL == hdl) { LOGE(LOG_TAG, "%s:%d, invalid hdl.", __func__, __LINE__); return ret; } if(hdl == capture_stream_hdl) { rl6548_capture_start(); LOGD(LOG_TAG, "rx codec_pcm_stream_start"); } else if (hdl == playback_stream_hdl) { rl6548_playback_start(); LOGD(LOG_TAG, "tx codec_pcm_stream_start"); } // LOGD(LOG_TAG, "%s:%d, ret = %d.", __func__, __LINE__, ret); return ret; } static int codec_pcm_stream_write(pcm_stream_handler_t hdl, void *buf, unsigned int len) { int ret = -1; if(NULL == hdl) { LOGE(LOG_TAG, "%s:%d, invalid hdl.", __func__, __LINE__); return ret; } if(hdl == capture_stream_hdl) { LOGE(LOG_TAG, "%s:%d, write operation not allowed on capture stream.", __func__, __LINE__); } else if (hdl == playback_stream_hdl) { ret = rl6548_audio_write(playback_stream_hdl, (uint8_t *)buf, len); } return ret; } static int codec_pcm_stream_read(pcm_stream_handler_t hdl, void *buf, unsigned int len) { int ret = -1, i = 0, j = 0; int channel_num = 3, sample_bytes = 2, frame_size; char *tempBuf = NULL; if(NULL == hdl) { LOGE(LOG_TAG, "%s:%d, invalid hdl.", __func__, __LINE__); return ret; } if(hdl == playback_stream_hdl) { LOGE(LOG_TAG, "%s:%d, read operation not allowed on playback stream.", __func__, __LINE__); } else if (hdl == capture_stream_hdl) { // TBD: read capture stream, get last channel data frame_size = channel_num * sample_bytes; ret = rl6548_data_read(hdl, buf, len); LOGD(LOG_TAG, "%s:%d, data_dump_read %d bytes", __func__, __LINE__, ret); } return ret; } static int codec_pcm_stream_pause(pcm_stream_handler_t hdl, int enable) { int ret = -1; if(NULL == hdl) { LOGE(LOG_TAG, "%s:%d, invalid hdl.", __func__, __LINE__); return ret; } if(hdl == playback_stream_hdl) { // TBD: pause playback stream } else if (hdl == capture_stream_hdl) { // TBD: pause capture stream } LOGD(LOG_TAG, "%s:%d, ret = %d.", __func__, __LINE__, ret); return ret; } static int codec_pcm_stream_suspend(pcm_stream_handler_t hdl) { int ret = 0; if(hdl == &playback_stream_hdl) { // TBD: put playback stream into lowpower/suspend mode } else if (hdl == &capture_stream_hdl) { // TBD: put capture stream into lowpower/suspend mode } return ret; } static int codec_pcm_stream_resume(pcm_stream_handler_t hdl) { int ret = 0; if(hdl == &playback_stream_hdl) { // TBD: put playback stream into active mode } else if (hdl == &capture_stream_hdl) { // TBD: put playback stream into active mode } return ret; } static int codec_pcm_stream_stop(pcm_stream_handler_t hdl) { int ret = 0; if(NULL == hdl) { LOGE(LOG_TAG, "%s:%d, invalid hdl.", __func__, __LINE__); return ret; } if(hdl == capture_stream_hdl) { rl6548_capture_stop(); } else if (hdl == playback_stream_hdl) { rl6548_playback_stop(); } // LOGD(LOG_TAG, "%s:%d, ret = %d.", __func__, __LINE__, ret); LOGD(LOG_TAG, "codec_pcm_stream_stop"); return ret; } static int codec_pcm_stream_close(pcm_stream_handler_t hdl) { int ret = 0; if(NULL == hdl) { LOGE(LOG_TAG, "%s:%d, invalid hdl.", __func__, __LINE__); return ret; } if(audio_stream_hdl == NULL) { playback_stream_hdl = capture_stream_hdl = NULL; return ret; } if(hdl == capture_stream_hdl) { rl6548_audio_deinit(); capture_stream_hdl = audio_stream_hdl = NULL; } else if (hdl == playback_stream_hdl) { rl6548_audio_deinit(); playback_stream_hdl = audio_stream_hdl = NULL; } LOGD(LOG_TAG, "%s:%d, ret = %d.", __func__, __LINE__, ret); return ret; } static int codec_pcm_stream_recover(pcm_stream_handler_t hdl) { int ret = -1; if(NULL == hdl) { LOGE(LOG_TAG, "%s:%d, invalid hdl.", __func__, __LINE__); return ret; } if(hdl == capture_stream_hdl) { // TBD: recover capture stream } else if (hdl == playback_stream_hdl) { // TBD: recover playback stream } LOGD(LOG_TAG, "%s:%d, ret = %d.", __func__, __LINE__, ret); return ret; } pcm_stream_ops_t codec_pcm_ops = { .open = codec_pcm_stream_open, .start = codec_pcm_stream_start, .read = codec_pcm_stream_read, .write = codec_pcm_stream_write, // .pause = codec_pcm_stream_pause, .stop = codec_pcm_stream_stop, .close = codec_pcm_stream_close, // .recover = codec_pcm_stream_recover, // .suspend = codec_pcm_stream_suspend, // .resume = codec_pcm_stream_resume, }; /* Application shall call this API to install codec driver instance. */ int audio_install_codec_driver() { int pb_stream_num = 1; int cap_stream_num = 1; LOGD(LOG_TAG, "%s:%d, install RTOS codec driver %d Capture %d Playback", __func__, __LINE__, cap_stream_num, pb_stream_num); return audio_native_card_register(cap_stream_num, pb_stream_num, &codec_pcm_ops, master_codec_controls, sizeof(master_codec_controls)/sizeof(master_codec_controls[0])); } //FINSH_FUNCTION_EXPORT_CMD(audio_install_codec_driver, insmod_audio_drv, RTOS Codec Driver Test)
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/audio.c
C
apache-2.0
10,381
/* * Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #ifndef CONFIG_MESH_STACK_ALONE #include <bluetooth/bluetooth.h> #include <bluetooth/storage.h> #include <bluetooth/hci.h> #endif #include <aos/kernel.h> #include <aos/hal/flash.h> #include <aos/errno.h> #include "ble_port.h" #ifndef AOS_COMP_KV #define MAX_REMOTE_DEV_SIZE (5) #ifndef CONFIG_MESH_STACK_ALONE typedef struct{ uint8_t mac[6]; bt_addr_le_t local_mac; uint8_t local_IRK[16]; bt_addr_le_t remote_dev[MAX_REMOTE_DEV_SIZE]; uint8_t remote_IRK[16]; struct bt_storage_ltk LTK; struct bt_storage_ltk slave_LTK; } bt_storage_t; #endif #endif #ifndef CONFIG_MESH_STACK_ALONE static ssize_t storage_read(const bt_addr_le_t *addr, u16_t key, void *data, size_t length) { #if 0 uint8_t mac[6]; int err_code; uint8_t s[20]; sprintf(s ,"BT_STORAGE_%02x", key); #ifdef AOS_COMP_KV err_code = aos_kv_get(s, data, length, 1); #else unsigned int off = 0; bt_storage_t local_storage; memset(&local_storage, 0, sizeof(bt_storage_t)); err_code = hal_flash_read(HAL_PARTITION_PARAMETER_3, &off, &local_storage, sizeof(bt_storage_t)); if(!err_code){ memcpy(mac, (uint8_t*)local_storage.local_mac.a.val, sizeof(mac)); } #endif if(err_code == 0){ if(BT_STORAGE_ID_ADDR == key){ uint8_t mac[6]; memcpy(mac ,((bt_addr_le_t *)data)->a.val, 6); printf("%s: valid mac read - 0x%02x:0x%02x:0x%02x:0x%02x:0x%02x:0x%02x\r\n", __func__, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); return sizeof(bt_addr_le_t); } } else if(err_code == -ENOENT){ if(BT_STORAGE_ID_ADDR == key){ printf("%s: no valid mac read\r\n", __func__); return 0; } } else{ printf("KV read failed(%d)\n", err_code); return -1; } #endif return 0; } static ssize_t storage_write(const bt_addr_le_t *addr, u16_t key, const void *data, size_t length) { #if 0 uint32_t err_code; uint8_t mac[6]; uint8_t s[20]; sprintf(s ,"BT_STORAGE_%02x", key); #ifdef AOS_COMP_KV err_code = aos_kv_set(s, data, length, 1); #else unsigned int off = 0; bt_storage_t local_storage; err_code = hal_flash_read(HAL_PARTITION_PARAMETER_3, &off, &local_storage, sizeof(bt_storage_t)); if(memcmp(mac, (uint8_t*)local_storage.local_mac.a.val, sizeof(mac)) == 0){ printf("No need to store MAC\n"); return sizeof(bt_addr_le_t); } if(!err_code){ memcpy( (uint8_t*)local_storage.local_mac.a.val, mac,sizeof(mac)); err_code = hal_flash_erase(HAL_PARTITION_PARAMETER_3, &off, 4096); if(!err_code){ printf("Flash erase failed\n"); return -1; } } err_code = hal_flash_erase_write(HAL_PARTITION_PARAMETER_3, &off, &local_storage, sizeof(bt_storage_t)); #endif if (err_code != 0) { printf("%s failed.\r\n", __func__); return 0; } return sizeof(bt_addr_le_t); #endif return 0; } static int storage_clear(const bt_addr_le_t *addr) { return 0; } #endif int ble_storage_init(void) { #ifndef CONFIG_MESH_STACK_ALONE static const struct bt_storage storage = { .read = storage_read, .write = storage_write, .clear = storage_clear }; //TBD:should check lower flash APIs bt_storage_register(&storage); #endif return 0; } uint32_t hal_flash_erase_sector_size() { return 0; } #if 0 int32_t hal_flash_enable_secure(hal_partition_t partition, uint32_t off_set, uint32_t size) { return 0; } int32_t hal_flash_dis_secure(hal_partition_t partition, uint32_t off_set, uint32_t size) { return 0; } #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/ble_port.c
C
apache-2.0
3,808
/* * Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #ifndef BLE_PORT_H #define BLE_PORT_H int ble_storage_init(void); #endif//BLE_PORT_H
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/ble_port.h
C
apache-2.0
154
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ //#include "platform_peripheral.h" #include "aos/hal/flash.h" #include "board.h" #include "flash_api.h" #include "hal_platform.h" #define SPI_FLASH_SEC_SIZE 4096 /**< SPI Flash sector size */ #define ROUND_DOWN(a,b) (((a) / (b)) * (b)) flash_t flash_obj; extern const hal_logic_partition_t hal_partitions[]; extern size_t hal_partitions_amount; hal_logic_partition_t *hal_flash_get_info(hal_partition_t in_partition) { hal_logic_partition_t *logic_partition; logic_partition = (hal_logic_partition_t *)&hal_partitions[ in_partition ]; return logic_partition; } int32_t hal_flash_erase(hal_partition_t in_partition, uint32_t off_set, uint32_t size) { uint32_t addr; uint32_t start_addr, end_addr; int32_t ret = 0; hal_logic_partition_t *partition_info; partition_info = hal_flash_get_info( in_partition ); if(size + off_set > partition_info->partition_length){ DBG_8195A("\r\n hal_flash_erase err, partition %d, part_len 0x%x, offset 0x%x, size 0x%x\r\n", in_partition, partition_info->partition_length, off_set, size); return -1; } start_addr = ROUND_DOWN((partition_info->partition_start_addr + off_set), SPI_FLASH_SEC_SIZE); end_addr = ROUND_DOWN((partition_info->partition_start_addr + off_set + size - 1), SPI_FLASH_SEC_SIZE); for (addr = start_addr; addr <= end_addr; addr += SPI_FLASH_SEC_SIZE) { flash_erase_sector(&flash_obj, addr); } return 0; } int32_t hal_flash_write(hal_partition_t in_partition, uint32_t *off_set, const void *in_buf , uint32_t in_buf_len) { uint32_t addr; uint32_t start_addr, end_addr; int32_t ret = 0; hal_logic_partition_t *partition_info; partition_info = hal_flash_get_info( in_partition ); if(off_set == NULL || in_buf == NULL || *off_set + in_buf_len > partition_info->partition_length){ DBG_8195A("\r\n hal_flash_write err, partition %d, part_len 0x%x, offset 0x%x, size 0x%x\r\n", in_partition, partition_info->partition_length, off_set, in_buf_len); return -1; } start_addr = partition_info->partition_start_addr + *off_set; ret = flash_stream_write(&flash_obj, start_addr, in_buf_len, (uint8_t *)in_buf); *off_set += in_buf_len; return 0; } int32_t hal_flash_read(hal_partition_t in_partition, uint32_t *off_set, void *out_buf, uint32_t out_buf_len) { int32_t ret = 0; uint32_t start_addr; hal_logic_partition_t *partition_info; partition_info = hal_flash_get_info( in_partition ); if(off_set == NULL || out_buf == NULL || *off_set + out_buf_len > partition_info->partition_length){ return -1; DBG_8195A("\r\n hal_flash_read err, partition %d, part_len 0x%x, offset 0x%x, size 0x%x\r\n", in_partition, partition_info->partition_length, off_set, out_buf_len); } start_addr = partition_info->partition_start_addr + *off_set; flash_stream_read(&flash_obj, start_addr, out_buf_len, out_buf); *off_set += out_buf_len; return ret; } int32_t hal_flash_enable_secure(hal_partition_t in_partition, uint32_t off_set, uint32_t size) { return 0; } int32_t hal_flash_dis_secure(hal_partition_t in_partition, uint32_t off_set, uint32_t size) { return 0; } int32_t hal_flash_addr2offset(hal_partition_t *in_partition, uint32_t *off_set, uint32_t addr) { int32_t i; uint32_t logic_addr, start_addr, end_addr; hal_logic_partition_t *partition_info; if (addr < SPI_FLASH_BASE) { return -1; } logic_addr = addr - SPI_FLASH_BASE; for (i = 0; i < hal_partitions_amount; i++) { partition_info = hal_flash_get_info(i); start_addr = partition_info->partition_start_addr; end_addr = start_addr + partition_info->partition_length; if ((logic_addr >= start_addr) && (logic_addr < end_addr)) { *in_partition = i; *off_set = logic_addr - start_addr; return 0; } } return -1; } int32_t hal_flash_info_get(hal_partition_t in_partition, hal_logic_partition_t *partition) { return -1; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/flash.c
C
apache-2.0
4,131
/** ****************************************************************************** * @file paltform_gpio.c * @author William Xu * @version V1.0.0 * @date 05-May-2014 * @brief This file provide GPIO driver functions. ****************************************************************************** * * The MIT License * Copyright (c) 2014 MXCHIP Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished * to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************** */ #include "aos/hal/gpio.h" #include "PinNames.h" #include "objects.h" #include "gpio_irq_api.h" #include "gpio_api.h" const static uint8_t gpio_remap[] = { [0] = PA_0, [1] = PA_1, [2] = PA_2, [3] = PA_3, [4] = PA_4, [5] = PA_5, [6] = PA_6, [7] = PA_7, [8] = PA_8, [9] = PA_9, [10] = PA_10, [11] = PA_11, [12] = PA_12, [13] = PA_13, [14] = PA_14, [15] = PA_15, [16] = PA_16, [17] = PA_17, [18] = PA_18, [19] = PA_19, [20] = PA_20, [21] = PA_21, [22] = PA_22, [23] = PA_23, [24] = PA_24, [25] = PA_25, [26] = PA_26, [27] = PA_27, [28] = PA_28, [29] = PA_29, [30] = PA_30, [31] = PA_31, [32] = PB_0, [33] = PB_1, [34] = PB_2, [35] = PB_3, [36] = PB_4, [37] = PB_5, [38] = PB_6, [39] = PB_7, [40] = PB_8, [41] = PB_9, [42] = PB_10, [43] = PB_11, [44] = PB_12, [45] = PB_13, [46] = PB_14, [47] = PB_15, [48] = PB_16, [49] = PB_17, [50] = PB_18, [51] = PB_19, [52] = PB_20, [53] = PB_21, [54] = PB_22, [55] = PB_23, [56] = PB_24, [57] = PB_25, [58] = PB_26, [59] = PB_27, [60] = PB_28, [61] = PB_29, [62] = PB_30, [63] = PB_31, }; #define GPIO_NUM_PINS (sizeof(gpio_remap) / sizeof(gpio_remap[0])) typedef struct { gpio_t gpio_obj; gpio_irq_t gpio_irq_obj; } gpio_objs_t; static gpio_objs_t gpio_objs[GPIO_NUM_PINS]; extern int sys_jtag_off(); void platform_jtag_off(void) { static uint8_t jtag_on = 1; if(jtag_on){ sys_jtag_off(); jtag_on = 0; } } int32_t hal_gpio_init( gpio_dev_t *gpio ) { if(!gpio || gpio->port >= GPIO_NUM_PINS) return -1; gpio_t *gpio_obj = &gpio_objs[gpio->port].gpio_obj; uint8_t pin = gpio_remap[gpio->port]; if(pin == PA_27 || pin == PB_23){ platform_jtag_off(); } gpio_init(gpio_obj, pin); switch(gpio->config){ case INPUT_PULL_UP: gpio_dir(gpio_obj, PIN_INPUT); // Direction: Input gpio_mode(gpio_obj, PullUp); // Pull-High break; case INPUT_PULL_DOWN: gpio_dir(gpio_obj, PIN_INPUT); // Direction: Input gpio_mode(gpio_obj, PullDown); // Pull-Down break; case INPUT_HIGH_IMPEDANCE: gpio_dir(gpio_obj, PIN_INPUT); // Direction: Input gpio_mode(gpio_obj, PullNone); // Pull-None break; case OUTPUT_PUSH_PULL: gpio_dir(gpio_obj, PIN_OUTPUT); // Direction: Input gpio_mode(gpio_obj, PullUp); // Pull-None break; case OUTPUT_OPEN_DRAIN_NO_PULL: case OUTPUT_OPEN_DRAIN_PULL_UP: gpio_dir(gpio_obj, PIN_OUTPUT); // Direction: Input gpio_mode(gpio_obj, PullDown); // Pull-None break; } return 0; } int32_t hal_gpio_deinit( gpio_dev_t *gpio ) { if(!gpio || gpio->port >= GPIO_NUM_PINS) return -1; gpio_deinit(&gpio_objs[gpio->port].gpio_obj); return 0; } int32_t hal_gpio_output_high( gpio_dev_t* gpio ) { if(!gpio || gpio->port >= GPIO_NUM_PINS) return -1; gpio_write(&gpio_objs[gpio->port].gpio_obj, 1); return 0; } int32_t hal_gpio_output_low( gpio_dev_t* gpio ) { if(!gpio || gpio->port >= GPIO_NUM_PINS) return -1; gpio_write(&gpio_objs[gpio->port].gpio_obj, 0); return 0; } int32_t hal_gpio_output_toggle( gpio_dev_t* gpio ) { if(!gpio || gpio->port >= GPIO_NUM_PINS) return -1; gpio_write(&gpio_objs[gpio->port].gpio_obj, !gpio_read(&gpio_objs[gpio->port].gpio_obj)); return 0; } int32_t hal_gpio_input_get(gpio_dev_t *gpio, uint32_t *value) { if(!gpio || gpio->port >= GPIO_NUM_PINS || !value) return -1; *value = gpio_read(&gpio_objs[gpio->port].gpio_obj) == 0 ? 0 : 1; return 0; } int32_t hal_gpio_get(gpio_dev_t *gpio, uint32_t *value) { if(!gpio || gpio->port >= GPIO_NUM_PINS) return -1; return hal_gpio_input_get(gpio, value); } int32_t hal_gpio_enable_irq(gpio_dev_t *gpio, gpio_irq_trigger_t trigger, gpio_irq_handler_t handler, void *arg) { if(!gpio || gpio->port >= GPIO_NUM_PINS) return -1; gpio_irq_t *gpio_irq_obj = &gpio_objs[gpio->port].gpio_irq_obj; uint8_t pin = gpio_remap[gpio->port]; gpio_irq_init(gpio_irq_obj, pin, handler, (uint32_t)(arg)); switch ( trigger ) { case IRQ_TRIGGER_RISING_EDGE: gpio_irq_set(gpio_irq_obj, IRQ_RISE, 1); // Rising Edge Trigger gpio_irq_enable(gpio_irq_obj); break; case IRQ_TRIGGER_FALLING_EDGE: gpio_irq_set(gpio_irq_obj, IRQ_FALL, 1); // Falling Edge Trigger gpio_irq_enable(gpio_irq_obj); break; case IRQ_TRIGGER_BOTH_EDGES: return -1; break; default: return -1; } return 0; } int32_t hal_gpio_clear_irq( gpio_dev_t* gpio ) { if(!gpio || gpio->port >= GPIO_NUM_PINS) return -1; gpio_irq_deinit(&gpio_objs[gpio->port].gpio_irq_obj); return 0; } int32_t hal_gpio_finalize(gpio_dev_t *gpio) { return 0; } int32_t hal_gpio_disable_irq(gpio_dev_t *gpio) { return 0; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/gpio.c
C
apache-2.0
6,588
#include <stdio.h> #include "aos/kernel.h" #include <k_api.h> #include <stdint.h> #include <stdbool.h> #include "board.h" #include "aos/hal/spi.h" #include "spi_api.h" #include "spi_ex_api.h" #include "pinmap.h" /*SPI pin location: * SPI0: * - S0: PA_16(MOSI)/PA_17(MISO)/PA_18(SCLK)/PA_19(CS). * - S1: PB_4(MOSI)/PB_5(MISO)/PB_6(SCLK)/PB_7(CS). */ spi_t spi_a; spi_t spi_b; typedef enum{ SPI_NUM_0 = 0, /*!< SPI port 0 */ SPI_NUM_1 , /*!< SPI port 1 */ SPI_NUM_MAX } spi_port_t; typedef struct spi_pin{ spi_t * dev; PinName spi_mosi; PinName spi_miso; PinName spi_sclk; PinName spi_cs; } spi_pin_t; static spi_pin_t spi_dev[SPI_NUM_MAX] = { {&spi_a, PA_16, PA_17, PA_18, PA_19}, {&spi_b, PB_4, PB_5, PB_6, PB_7} }; #define HAL_WAIT_FOREVER 0xFFFFFFFFU #define HAL_SPI_MODE_MASTER 1 /* spi communication is master mode */ #define HAL_SPI_MODE_SLAVE 2 /* spi communication is slave mode */ aos_sem_t slave_tx_down_sema; aos_sem_t slave_rx_down_sema; aos_sem_t master_tx_down_sema; aos_sem_t master_rx_down_sema; void Master_tr_done_callback(void *pdata, SpiIrq event) { switch(event){ case SpiRxIrq: aos_sem_signal(&master_rx_down_sema); break; case SpiTxIrq: aos_sem_signal(&master_tx_down_sema); break; default: DBG_8195A("unknown interrput evnent!\n"); } } void Slave_tr_done_callback(void *pdata, SpiIrq event) { switch(event){ case SpiRxIrq: aos_sem_signal(&slave_rx_down_sema); break; case SpiTxIrq: aos_sem_signal(&slave_tx_down_sema); break; default: DBG_8195A("unknown interrput evnent!\n"); } } int32_t hal_spi_init(spi_dev_t *spi) { int port = spi->port; int spi_slave; aos_sem_new(&slave_tx_down_sema, 0); aos_sem_new(&slave_rx_down_sema, 0); aos_sem_new(&master_tx_down_sema, 0); aos_sem_new(&master_rx_down_sema, 0); spi_a.spi_idx = MBED_SPI0; spi_b.spi_idx = MBED_SPI1; if(spi->config.role == HAL_SPI_MODE_MASTER) spi_slave = 0; else if(spi->config.role == HAL_SPI_MODE_SLAVE) spi_slave = 1; else printf("ERROR: SPI Config Role Set ERROR = %d", spi->config.role); spi_init(spi_dev[port].dev, spi_dev[port].spi_mosi, spi_dev[port].spi_miso, spi_dev[port].spi_sclk, spi_dev[port].spi_cs); spi_format(spi_dev[port].dev, 8, 0, spi_slave); spi_frequency(spi_dev[port].dev, spi->config.freq); return 0; } int32_t hal_spi_send(spi_dev_t *spi, const uint8_t *data, uint16_t size, uint32_t timeout) { int spi_slave; int port = spi->port; if(spi->config.role == HAL_SPI_MODE_MASTER) spi_slave = 0; else if(spi->config.role == HAL_SPI_MODE_SLAVE) spi_slave = 1; else printf("ERROR: SPI Config Role Set ERROR = %d", spi->config.role); if(spi_slave){ spi_irq_hook(spi_dev[port].dev,(spi_irq_handler) Slave_tr_done_callback, (uint32_t)spi_dev[port].dev); spi_slave_write_stream(spi_dev[port].dev, (uint8_t *)data, size); aos_sem_wait(&slave_tx_down_sema, timeout); }else{ spi_irq_hook(spi_dev[port].dev,(spi_irq_handler) Master_tr_done_callback, (uint32_t)spi_dev[port].dev); spi_master_write_stream(spi_dev[port].dev, (uint8_t *)data, size); aos_sem_wait(&master_tx_down_sema, timeout); } } /** * spi_recv * * @param[in] spi the spi device * @param[out] data spi recv data * @param[in] size spi recv data size * @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 the SPI device could not be initialised */ int32_t hal_spi_recv(spi_dev_t *spi, uint8_t *data, uint16_t size, uint32_t timeout) { int spi_slave; int port = spi->port; if(spi->config.role == HAL_SPI_MODE_MASTER) spi_slave = 0; else if(spi->config.role == HAL_SPI_MODE_SLAVE) spi_slave = 1; else printf("ERROR: SPI Config Role Set ERROR = %d", spi->config.role); if(spi_slave){ spi_irq_hook(spi_dev[port].dev,(spi_irq_handler) Slave_tr_done_callback, (uint32_t)spi_dev[port].dev); spi_slave_read_stream(spi_dev[port].dev, data, size); aos_sem_wait(&slave_rx_down_sema, timeout); }else{ spi_irq_hook(spi_dev[port].dev,(spi_irq_handler) Master_tr_done_callback, (uint32_t)spi_dev[port].dev); spi_master_read_stream(spi_dev[port].dev, data, size); aos_sem_wait(&master_rx_down_sema, timeout); } } /** * spi send data and recv * * @param[in] spi the spi device * @param[in] tx_data spi send data * @param[in] rx_data spi recv data * @param[in] size spi data to be sent and recived * @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 the SPI device could not be initialised */ int32_t hal_spi_sends_recvs(spi_dev_t *spi, uint8_t *tx_data, uint16_t tx_size, uint8_t *rx_data, uint16_t rx_size, uint32_t timeout) { int ret; int spi_slave = 0; int port = spi->port; if (spi->config.role != HAL_SPI_MODE_MASTER) { printf("ERROR: Only support SPI Master Role Send and RECV \n\r"); return -1; } spi_irq_hook(spi_dev[port].dev,(spi_irq_handler) Master_tr_done_callback, (uint32_t)spi_dev[port].dev); ret = spi_master_write_read_stream(spi_dev[port].dev, tx_data, tx_size, rx_data, rx_size); aos_sem_wait(&master_rx_down_sema, timeout); return ret; } int32_t hal_spi_send_recv(spi_dev_t *spi, uint8_t *tx_data, uint8_t *rx_data, uint16_t size, uint32_t timeout) { return hal_spi_sends_recvs(spi, tx_data, 1, rx_data, size, timeout); } int32_t hal_spi_finalize(spi_dev_t *spi) { spi_free(spi_dev[spi->port].dev); aos_sem_free(&slave_tx_down_sema); aos_sem_free(&slave_rx_down_sema); aos_sem_free(&master_tx_down_sema); aos_sem_free(&master_rx_down_sema); return 0; } int32_t hal_spi_send_and_recv(spi_dev_t *spi, uint8_t *tx_data, uint16_t tx_size, uint8_t *rx_data, uint16_t rx_size, uint32_t timeout) { return -1; } int32_t hal_spi_send_and_send(spi_dev_t *spi, uint8_t *tx1_data, uint16_t tx1_size, uint8_t *tx2_data, uint16_t tx2_size, uint32_t timeout) { return -1; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_spi.c
C
apache-2.0
6,729
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdint.h> #include <string.h> #include "aos/kernel.h" #include "aos/hal/adc.h" #include "adc_test.h" static adc_dev_t adc_dev; static aos_timer_t gpio_test_timer; void adc_test_task(void *arg); void hal_adc_test(void) { int ret = -1; printf("*********** adc test start ! ***********\n"); adc_dev.port = PORT_ADC_TEST; ret = hal_adc_init(&adc_dev); if (ret != 0) { printf("hal_adc_init error !\n"); return; } aos_timer_new(&gpio_test_timer, adc_test_task, NULL, 1000, 1); } void adc_test_task(void *arg) { int ret = -1; uint16_t value = 0; printf("adc_test_task\n"); ret = hal_adc_value_get(&adc_dev, &value, 0xFFFFFFFF); if (ret == 0) { printf("adc value: %d\n", value); } else { printf("adc value get error !\n"); } }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/adc/adc_test.c
C
apache-2.0
938
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #define PORT_ADC_TEST 0 void hal_adc_test(void);
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/adc/adc_test.h
C
apache-2.0
115
NAME := adc_test $(NAME)_MBINS_TYPE := app $(NAME)_VERSION := 0.0.1 $(NAME)_SUMMARY := testcase for adc $(NAME)_SOURCES += adc_test.c $(NAME)_CFLAGS += -Wall -Werror
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/adc/aos.mk
Makefile
apache-2.0
176
src = Split(''' adc_test.c ''') component = aos_component('adc_test', src) component.add_cflags('-Wall') component.add_cflags('-Werror')
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/adc/ucube.py
Python
apache-2.0
143
NAME := hal_test $(NAME)_MBINS_TYPE := app $(NAME)_VERSION := 0.0.1 $(NAME)_SUMMARY := testcase for hal $(NAME)_SOURCES += hal_test.c $(NAME)_CFLAGS += -Wall -Werror
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/aos.mk
Makefile
apache-2.0
175
NAME := dac_test $(NAME)_MBINS_TYPE := app $(NAME)_VERSION := 0.0.1 $(NAME)_SUMMARY := testcase for dac $(NAME)_SOURCES += dac_test.c $(NAME)_CFLAGS += -Wall -Werror
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/dac/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/dac.h" #include "dac_test.h" dac_dev_t dac_dev; void hal_dac_test(void) { int ret = -1; printf("*********** dac test start ! ***********\n"); dac_dev.port = PORT_DAC_TEST; ret = hal_dac_init(&dac_dev); if (ret != 0) { printf("hal_dac_init error !\n"); return; } ret = hal_dac_finalize(&dac_dev); if (ret != 0) { printf("hal_dac_finalize error !\n"); return; } printf("dac test result: succeed !\n"); printf("*********** dac test end ! ***********\n"); }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/dac/dac_test.c
C
apache-2.0
704
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #define PORT_DAC_TEST 0 void hal_dac_test(void);
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/dac/dac_test.h
C
apache-2.0
115
src = Split(''' dac_test.c ''') component = aos_component('dac_test', src) component.add_cflags('-Wall') component.add_cflags('-Werror')
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/dac/ucube.py
Python
apache-2.0
143
NAME := flash_test $(NAME)_MBINS_TYPE := app $(NAME)_VERSION := 0.0.1 $(NAME)_SUMMARY := testcase for flash $(NAME)_SOURCES += flash_test.c $(NAME)_CFLAGS += -Wall -Werror
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/flash/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/flash.h" #include "flash_test.h" #define TEST_BUFFER_WORDS 512 uint16_t flash_test_buffer[TEST_BUFFER_WORDS]; void hal_flash_test(void) { int i = 0; int j = 0; int ret = 0; uint32_t off_set = 0; hal_logic_partition_t * partition_info = NULL; printf("*********** flash test start ! ***********\n"); partition_info = hal_flash_get_info(HAL_PARTITION_TEST); if (partition_info == NULL) { printf("flash info get error ! test failed\n"); return; } else { printf("test partition is %s\n", partition_info->partition_description); printf("test partition bytes: %d\n", partition_info->partition_length); } printf("step1: erase the flash !\n"); ret = hal_flash_erase(HAL_PARTITION_TEST, 0, partition_info->partition_length); if (ret != 0) { printf("flash erase return error ! test failed\n"); return; } printf("step2: check if the flash is completely erased!\n"); off_set = 0; for (i = 0; i < partition_info->partition_length / (TEST_BUFFER_WORDS * sizeof(uint16_t)); i++) { ret = hal_flash_read(HAL_PARTITION_TEST, &off_set, flash_test_buffer, (TEST_BUFFER_WORDS * sizeof(uint16_t))); if (ret != 0) { printf("flash read error ! test failed\n"); return; } for (j = 0; j < TEST_BUFFER_WORDS; j++) { if (flash_test_buffer[j] != 0xFFFF) { printf("flash erase data error ! test failed\n"); return; } } } printf("step3: write the flash !\n"); off_set = 0; for (i = 0; i < partition_info->partition_length / (TEST_BUFFER_WORDS * sizeof(uint16_t)); i++) { for (j = 0; j < TEST_BUFFER_WORDS; j++) { flash_test_buffer[j] = j + i * TEST_BUFFER_WORDS; } ret = hal_flash_write(HAL_PARTITION_TEST, &off_set, flash_test_buffer, (TEST_BUFFER_WORDS * sizeof(uint16_t))); if (ret != 0) { printf("flash write error ! test failed\n"); return; } } printf("step4: read the flash to check the data in flash !\n"); off_set = 0; for (i = 0; i < partition_info->partition_length / (TEST_BUFFER_WORDS * sizeof(uint16_t)); i++) { ret = hal_flash_read(HAL_PARTITION_TEST, &off_set, flash_test_buffer, (TEST_BUFFER_WORDS * sizeof(uint16_t))); if (ret != 0) { printf("flash read error ! test failed\n"); return; } for (j = 0; j < TEST_BUFFER_WORDS; j++) { if (flash_test_buffer[j] != j + i * TEST_BUFFER_WORDS) { printf("flash read data error ! test failed\n"); return; } } } printf("flash test result: succeed !\n"); printf("*********** flash test end ! ***********\n"); }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/flash/flash_test.c
C
apache-2.0
3,006
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #define HAL_PARTITION_TEST HAL_PARTITION_PARAMETER_3 void hal_flash_test(void);
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/flash/flash_test.h
C
apache-2.0
146
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/flash/ucube.py
Python
apache-2.0
147
NAME := gpio_test $(NAME)_MBINS_TYPE := app $(NAME)_VERSION := 0.0.1 $(NAME)_SUMMARY := testcase for gpio $(NAME)_SOURCES += gpio_test.c $(NAME)_CFLAGS += -Wall -Werror
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/gpio/aos.mk
Makefile
apache-2.0
179
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdint.h> #include <stdio.h> #include <string.h> #include "aos/kernel.h" #include "aos/hal/gpio.h" #include "gpio_test.h" static aos_timer_t gpio_test_timer; static aos_sem_t gpio_test_sem; static gpio_dev_t gpio_out; static gpio_dev_t gpio_in; int gpio_irq_flag = 0; static void gpio_test_end(void); static void gpio_test_task(void *arg1 , void *arg2); static void gpio_output_irq_test(void); static void gpio_output_in_test(void); static void gpio_in_handler(void *arg); void hal_gpio_test(void) { int ret = -1; printf("*********** gpio test start ! ***********\n"); /* init gpio out in */ gpio_out.port = PORT_GPIO_TEST_OUT; gpio_out.config = OUTPUT_PUSH_PULL; gpio_in.port = PORT_GPIO_TEST_IN; ret = hal_gpio_init(&gpio_out); if (ret != 0) { printf("gpio_out init error !\n"); } /* create a sem and a timer to test gpio */ aos_sem_new(&gpio_test_sem, 0); aos_timer_new(&gpio_test_timer, gpio_test_task, NULL, 100, 1); /* wait the test end */ aos_sem_wait(&gpio_test_sem, AOS_WAIT_FOREVER); hal_gpio_finalize(&gpio_in); hal_gpio_finalize(&gpio_out); aos_sem_free(&gpio_test_sem); aos_timer_free(&gpio_test_timer); printf("*********** gpio test end ! ***********\n"); } void gpio_test_end(void) { aos_task_exit(0); aos_sem_signal(&gpio_test_sem); } void gpio_test_task(void *arg1 , void *arg2) { static int gpio_test_cnt = 0; gpio_test_cnt++; //printf("gpio_test_cnt %d\n", gpio_test_cnt); if ((gpio_test_cnt >= 1) && (gpio_test_cnt <= 100)) { gpio_output_irq_test(); } if ((gpio_test_cnt >= 101) && (gpio_test_cnt <= 200)) { gpio_output_in_test(); } if (gpio_test_cnt > 200) { gpio_test_end(); } } void gpio_output_irq_test(void) { static int test_cnt = 0; static int test_fail_flag = 0; static int arg = 0; int ret = -1; test_cnt++; //printf("test_cnt %d\n", test_cnt); if (test_cnt == 1) { printf("gpio_output_irq_test begin !\n"); ret = hal_gpio_init(&gpio_out); if (ret != 0) { printf("gpio_out init error !\n"); } hal_gpio_output_low(&gpio_out); /* init gpio in */ gpio_in.config = IRQ_MODE; ret = hal_gpio_init(&gpio_in); if (ret != 0) { printf("gpio_in init error !\n"); } /* enable the irg mode */ ret = hal_gpio_enable_irq(&gpio_in, IRQ_TRIGGER_BOTH_EDGES, gpio_in_handler, &arg); if (ret != 0) { printf("gpio_in init irq error !\n"); } } hal_gpio_output_toggle(&gpio_out); if (gpio_irq_flag == 1) { gpio_irq_flag = 0; } else { test_fail_flag = 1; } if (test_cnt == 100) { if (test_fail_flag == 1) { printf("gpio_output_irq_test failed !\n"); } else { printf("gpio_output_irq_test succeed !\n"); } } } void gpio_output_in_test(void) { static int test_cnt = 0; static int test_fail_flag = 0; uint32_t value = 0; int ret = -1; test_cnt++; if (test_cnt == 1) { printf("gpio_output_in_test begin !\n"); hal_gpio_finalize(&gpio_in); gpio_in.config = INPUT_HIGH_IMPEDANCE; ret = hal_gpio_init(&gpio_in); if (ret != 0) { printf("gpio_in init error !\n"); } } hal_gpio_output_high(&gpio_out); hal_gpio_input_get(&gpio_in, &value); if (value == 1) { gpio_irq_flag = 0; } else { test_fail_flag = 1; } hal_gpio_output_low(&gpio_out); hal_gpio_input_get(&gpio_in, &value); if (value == 0) { gpio_irq_flag = 0; } else { test_fail_flag = 1; } hal_gpio_output_toggle(&gpio_out); hal_gpio_input_get(&gpio_in, &value); if (value == 1) { gpio_irq_flag = 0; } else { test_fail_flag = 1; } if (test_cnt == 100) { if (test_fail_flag == 1) { printf("gpio_output_in_test failed !\n"); } else { printf("gpio_output_in_test succeed !\n"); } } } void gpio_in_handler(void *arg) { gpio_irq_flag = 1; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/gpio/gpio_test.c
C
apache-2.0
4,309
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #define PORT_GPIO_TEST_OUT 24 #define PORT_GPIO_TEST_IN 25 void hal_gpio_test(void);
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/gpio/gpio_test.h
C
apache-2.0
152
src = Split(''' gpio_test.c ''') component = aos_component('gpio_test', src) component.add_cflags('-Wall') component.add_cflags('-Werror')
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/gpio/ucube.py
Python
apache-2.0
145
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdint.h> #include <stdio.h> #include <string.h> #include "aos/kernel.h" #include "aos/hal/uart.h" #include "yunit.h" extern void hal_uart_test(void); extern void hal_gpio_test(void); extern void hal_i2c_test(void); extern void hal_spi_test(void); extern void hal_flash_test(void); extern void hal_adc_test(void); extern void hal_dac_test(void); extern void hal_pwm_test_init(void); extern void hal_pwm_test_output(char *msg); extern void hal_rtc_test(void); extern void hal_timer_test(void); extern void hal_wdg_test(void); extern void hal_rng_test(void); #define MAX_CMD_LEN 32 static int hal_test_getchar(char *c); static int hal_test_cmd_read(char *buf, int size); static void hal_test_task(void *arg); static void device_print(void); char hal_test_cmd_buf[MAX_CMD_LEN]; void hal_test(void) { printf("====================== AliOS Things HAL TEST ===================\n"); printf("The supported devices is as follows: \n"); printf("-----------------------------------------------------------------\n"); device_print(); printf("-----------------------------------------------------------------\n"); printf("please enter the device name you want to test !\n"); aos_task_new("hal test task", hal_test_task, NULL, 2048); } void hal_test_task(void *arg) { int ret = -1; while(1) { ret = hal_test_cmd_read(hal_test_cmd_buf, MAX_CMD_LEN); if (ret == 0) { printf("%s\n", hal_test_cmd_buf); #ifdef ENABLE_UART if (strcmp(hal_test_cmd_buf, "uart") == 0) { hal_uart_test(); } #endif #ifdef ENABLE_GPIO if (strcmp(hal_test_cmd_buf, "gpio") == 0) { hal_gpio_test(); } #endif #ifdef ENABLE_I2C if (strcmp(hal_test_cmd_buf, "i2c") == 0) { hal_i2c_test(); } #endif #ifdef ENABLE_SPI if (strcmp(hal_test_cmd_buf, "spi") == 0) { hal_spi_test(); } #endif #ifdef ENABLE_FLASH if (strcmp(hal_test_cmd_buf, "flash") == 0) { hal_flash_test(); } #endif #ifdef ENABLE_ADC if (strcmp(hal_test_cmd_buf, "adc") == 0) { hal_adc_test(); } #endif #ifdef ENABLE_DAC if (strcmp(hal_test_cmd_buf, "dac") == 0) { hal_dac_test(); } #endif #ifdef ENABLE_PWM if (strcmp(hal_test_cmd_buf, "pwm") == 0) { hal_pwm_test_init(); } if (strncmp(hal_test_cmd_buf, "pwm_testcase", 12) == 0) { hal_pwm_test_output(&hal_test_cmd_buf[12]); } #endif #ifdef ENABLE_RTC if (strcmp(hal_test_cmd_buf, "rtc") == 0) { hal_rtc_test(); } #endif #ifdef ENABLE_TIMER if (strcmp(hal_test_cmd_buf, "timer") == 0) { hal_timer_test(); } #endif #ifdef ENABLE_WDG if (strcmp(hal_test_cmd_buf, "wdg") == 0) { hal_wdg_test(); } #endif #ifdef ENABLE_RNG if (strcmp(hal_test_cmd_buf, "rng") == 0) { hal_rng_test(); } #endif } aos_msleep(1000); }; } int hal_test_getchar(char *c) { uart_dev_t uart_stdio; int32_t ret = 0; uint32_t recv_size = 0; memset(&uart_stdio, 0, sizeof(uart_dev_t)); uart_stdio.port = 0; do { ret = hal_uart_recv_II(&uart_stdio, c, 1, &recv_size, HAL_WAIT_FOREVER); } while (ret != 0); if ((ret == 0) && (recv_size == 1)) { return 0; } else { return -1; } } int hal_test_cmd_read(char *buf, int size) { char c = 0; int pos = 0; while (hal_test_getchar(&c) == 0) { if ((c == '\n') || (c == '\r')) { /* end of input line */ buf[pos] = '\0'; return 0; } else { buf[pos] = c; } pos++; if(pos >= size) { return -1; } } return 0; } void device_print(void) { printf("| "); #ifdef ENABLE_UART printf("uart |"); #endif #ifdef ENABLE_GPIO printf("gpio |"); #endif #ifdef ENABLE_I2C printf("i2c |"); #endif #ifdef ENABLE_SPI printf("spi |"); #endif #ifdef ENABLE_FLASH printf("flash |"); #endif #ifdef ENABLE_ADC printf("adc |"); #endif #ifdef ENABLE_DAC printf("dac |"); #endif #ifdef ENABLE_PWM printf("pwm |"); #endif #ifdef ENABLE_RTC printf("rtc |"); #endif #ifdef ENABLE_TIMER printf("timer |"); #endif #ifdef ENABLE_WDG printf("wdg |"); #endif #ifdef ENABLE_RNG printf("rng |"); #endif printf("\n"); } static yunit_test_case_t aos_hal_testcases[] = { { "hal_test", hal_test}, YUNIT_TEST_CASE_NULL }; static int init(void) { return 0; } static int cleanup(void) { return 0; } static void setup(void) { } static void teardown(void) { } static yunit_test_suite_t suites[] = { { "hal test", init, cleanup, setup, teardown, aos_hal_testcases }, YUNIT_TEST_SUITE_NULL }; void test_hal(void) { yunit_add_test_suites(suites); } AOS_TESTCASE(test_hal);
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/hal_test.c
C
apache-2.0
5,393
NAME := i2c_test $(NAME)_MBINS_TYPE := app $(NAME)_VERSION := 0.0.1 $(NAME)_SUMMARY := testcase for i2c $(NAME)_SOURCES += i2c_test.c $(NAME)_CFLAGS += -Wall -Werror
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/i2c/aos.mk
Makefile
apache-2.0
176
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include <stdint.h> #include "aos/kernel.h" #include "aos/hal/i2c.h" #include "aos/hal/rtc.h" #include "i2c_test.h" #define RTC_DATA_LEN 7 #define I2C_RTC_DELAY_MS 2000 #define I2C_RTC_TOLERANCE_RANGE 0.01f static int32_t rtc_i2c_init(void); static int32_t rtc_i2c_get_time(rtc_time_t *time); static int32_t rtc_i2c_set_time(rtc_time_t *time); static i2c_dev_t i2c_dev; static rtc_time_t rtc_time = {.sec = 0x45, .min = 0x8, .hr = 0x1, .weekday = 0x5, .date = 0x1, .month = 0x3, .year = 0x19}; static rtc_time_t rtc_time_r; /* a i2c interface rtc(ds1307) must be connetted to the mcu before testing */ void hal_i2c_test(void) { int ret = -1; printf("*********** i2c test start ! ***********\n"); memset(&rtc_time_r, 0, sizeof(rtc_time_t)); printf("step1: init the i2c !\n"); ret = rtc_i2c_init(); if (ret != 0) { printf("rtc_i2c_init error !\n"); return; } printf("step2: set rtc date to\n"); printf(" year: %x month: %x date: %x weekday: %x hr: %x min: %d sec: %x\n", rtc_time.year, rtc_time.month, rtc_time.date, rtc_time.weekday, rtc_time.hr, rtc_time.min, rtc_time.sec); ret = rtc_i2c_set_time(&rtc_time); if (ret != 0) { printf("rtc_i2c_set_time error !\n"); return; } ret = rtc_i2c_get_time(&rtc_time_r); if (ret != 0) { printf("rtc_i2c_get_time error !\n"); return; } printf("step4: read rtc, current date is\n"); printf(" year: %x month: %x date: %x weekday: %x hr: %x min: %x sec: %x\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); printf("step3: delay 2s !\n"); aos_msleep(I2C_RTC_DELAY_MS * (1 + I2C_RTC_TOLERANCE_RANGE)); ret = rtc_i2c_get_time(&rtc_time_r); if (ret != 0) { printf("rtc_i2c_get_time error !\n"); return; } printf("step4: read rtc, current date is\n"); printf(" year: %x month: %x date: %x weekday: %x hr: %x min: %x sec: %x\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 + I2C_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; } printf("step5: finalize i2c !\n"); ret = hal_i2c_finalize(&i2c_dev); if (ret != 0) { printf("hal_i2c_finalize error !\n"); return; } printf("rtc test result: succeed !\n"); printf("*********** i2c test end ! ***********\n"); } int32_t rtc_i2c_init(void) { int ret = -1; i2c_dev.port = PORT_I2C_TEST; i2c_dev.config.address_width = I2C_HAL_ADDRESS_WIDTH_7BIT; i2c_dev.config.freq = 100000; #if (I2C_ADD_LSB_AUTO == 0) i2c_dev.config.dev_addr = 0xD0; #else i2c_dev.config.dev_addr = 0x68; #endif ret = hal_i2c_init(&i2c_dev); if (ret != 0) { printf("hal_i2c_init error !\n"); } return ret; } int32_t rtc_i2c_get_time(rtc_time_t *time) { int ret = -1; //ret = hal_i2c_master_recv(&i2c_dev, i2c_dev.config.dev_addr, (uint8_t *)time, // RTC_DATA_LEN, AOS_WAIT_FOREVER); ret = hal_i2c_mem_read(&i2c_dev, i2c_dev.config.dev_addr, 0, 1, (uint8_t *)time, 7, AOS_WAIT_FOREVER); return ret; } int32_t rtc_i2c_set_time(rtc_time_t *time) { int ret = -1; //ret = hal_i2c_master_send(&i2c_dev, i2c_dev.config.dev_addr, (uint8_t *)time, // RTC_DATA_LEN, AOS_WAIT_FOREVER); ret = hal_i2c_mem_write(&i2c_dev, i2c_dev.config.dev_addr, 0, 1, (uint8_t *)time, 7, AOS_WAIT_FOREVER); return ret; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/i2c/i2c_test.c
C
apache-2.0
4,148
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #define PORT_I2C_TEST 0 /* if the slave device addr is 0xFF,  and your mcu only need to set the addr to 0xFE, the last bit will be added by the hardware, set I2C_ADD_LSB_AUTO to 1. If your mcu will not add the last bit auto, you must set the addr to 0xFF, set I2C_ADD_LSB_AUTO to 1. set */ #define I2C_ADD_LSB_AUTO 0 void hal_i2c_test(void);
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/i2c/i2c_test.h
C
apache-2.0
423
src = Split(''' i2c_test.c ''') component = aos_component('i2c_test', src) component.add_cflags('-Wall') component.add_cflags('-Werror')
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/hal/hal_test/i2c/ucube.py
Python
apache-2.0
143