rel_1.6.0 init

This commit is contained in:
guocheng.kgc 2020-06-18 20:06:52 +08:00 committed by shengdong.dsd
commit 27b3e2883d
19359 changed files with 8093121 additions and 0 deletions

View file

@ -0,0 +1,180 @@
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include <aos/aos.h>
#include <k_api.h>
#include <k_dbg_api.h>
#include <aos/kernel.h>
#include <stdio.h>
#include <stdlib.h>
#include "hal/soc/soc.h"
#include "diag.h"
#include "platform_stdlib.h"
#include "rtl8710b.h"
#include "core_cm4.h"
#include "wifi_conf.h"
#include "wlan_intf.h"
#include "wifi_constants.h"
#include "osdep_service.h"
#define AOS_START_STACK 2048
ktask_t *g_aos_init;
static kinit_t kinit;
extern int application_start(int argc, char **argv);
extern int aos_framework_init(void);
extern void board_init(void);
extern uint32_t SystemCoreClock;
static void hal_init()
{
}
extern void hw_start_hal(void);
static void board_cli_init(void)
{
kinit.argc = 0;
kinit.argv = NULL;
kinit.cli_enable = 1;
}
void dump_mem_info(){}
static void hal_wlan_init()
{
if ( rtl_cryptoEngine_init() != 0 ) {
DiagPrintf("crypto engine init failed\r\n");
}
/* Initialize log uart and at command service */
//ReRegisterPlatformLogUart();
#if CONFIG_LWIP_LAYER
/* Initilaize the LwIP stack */
LwIP_Init();
#endif
#if CONFIG_WLAN
//wifi_on(RTW_MODE_STA);
//wifi_disable_powersave();
hal_wifi_init();
#if CONFIG_AUTO_RECONNECT
//setup reconnection flag
wifi_set_autoreconnect(RTW_AUTORECONNECT_INFINITE);
#endif
printf("\n\r%s(%d), Available heap 0x%x", __FUNCTION__, __LINE__, rtw_getFreeHeapSize());
#endif
}
void start_ate(void)
{
u32 img2_addr = 0x080D0000;
IMAGE_HEADER *img2_hdr = (IMAGE_HEADER *)img2_addr;
IMAGE_HEADER *ram_img2_hdr = (IMAGE_HEADER *)(img2_addr + IMAGE_HEADER_LEN + img2_hdr->image_size);
u8 *ram_img2_data = (u8*)(ram_img2_hdr + 1);
u8 *ram_img2_valid_code = ram_img2_data + 8;
if (_strcmp((const char *)ram_img2_valid_code, (const char *)"RTKWin")) {
DBG_8195A("IMG_BOOTUSER SIGN Invalid\n");
while(1);
}
/* load ram image2 data into RAM */
_memcpy((void *)ram_img2_hdr->image_addr, ram_img2_data, ram_img2_hdr->image_size);
PRAM_START_FUNCTION img2_entry_fun = (PRAM_START_FUNCTION)ram_img2_data;
img2_entry_fun->RamStartFun();
}
/* For QC test */
static void board_mode_check(void)
{
#define KEY_ELINK 12
#define KEY_BOOT 9
gpio_dev_t gpio_key_boot;
gpio_key_boot.port = KEY_BOOT;
gpio_key_boot.config = INPUT_PULL_UP;
hal_gpio_init(&gpio_key_boot);
uint32_t boot;
hal_gpio_input_get(&gpio_key_boot, &boot);
gpio_dev_t gpio_key_elink;
gpio_key_elink.port = KEY_ELINK;
gpio_key_elink.config = INPUT_PULL_UP;
hal_gpio_init(&gpio_key_elink);
uint32_t elink;
hal_gpio_input_get(&gpio_key_elink, &elink);
printf("--------------------------------> built at "__DATE__" "__TIME__"\r\n");
hal_gpio_input_get(&gpio_key_boot, &boot);
printf("--------------------------------> boot %d, elink %d\r\n", boot, elink);
if(boot == 0)
{
if(elink == 0)
start_ate();
else
qc_test(0);
}
board_init();
}
void sys_init_func(void)
{
#ifdef AOS_COMP_PWRMGMT
pmu_set_sysactive_time();
#endif
hal_init();
hw_start_hal();
hal_wlan_init();
board_cli_init();
#ifdef USE_MX1290
board_mode_check();
#endif
aos_kernel_init(&kinit);
krhino_task_dyn_del(NULL);
}
#if (RHINO_CONFIG_PANIC == 1)
typedef void (*HAL_VECTOR_FUN) (void );
extern HAL_VECTOR_FUN NewVectorTable[];
extern void HardFault_Handler(void);
#endif
void main(void)
{
aos_init();
#if (RHINO_CONFIG_PANIC == 1)
/* AliOS-Things taking over the exception */
/* replace HardFault Vector */
NewVectorTable[3] = HardFault_Handler;
/* replace MemManage Vector */
NewVectorTable[4] = HardFault_Handler;
/* replace BusFault Vector */
NewVectorTable[5] = HardFault_Handler;
/* replace UsageFault Vector */
NewVectorTable[6] = HardFault_Handler;
#endif
krhino_task_dyn_create(&g_aos_init, "aos-init", 0, AOS_DEFAULT_APP_PRI , 0, AOS_START_STACK, (task_entry_t)sys_init_func, 1);
SysTick_Config(SystemCoreClock/RHINO_CONFIG_TICKS_PER_SECOND);
aos_start();
return;
}

View file

@ -0,0 +1,875 @@
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
//#include <autoconf.h>
#include <osdep_service.h>
#include <stdio.h>
#include <freertos/wrapper.h>
#include <aos/aos.h>
#include <freertos_pmu.h>
/********************* os depended utilities ********************/
#ifndef USE_MUTEX_FOR_SPINLOCK
#define USE_MUTEX_FOR_SPINLOCK 1
#endif
//----- ------------------------------------------------------------------
// Misc Function
//----- ------------------------------------------------------------------
#if 0
void save_and_cli()
{
RHINO_CRITICAL_ENTER();
}
void restore_flags()
{
RHINO_CRITICAL_EXIT();
}
#endif
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", 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] %s(%p) failed, retry\n", aos_task_name(), __FUNCTION__, plock);
}
static int _aos_mutex_get_timeout(_lock *plock, u32 timeout_ms)
{
if(aos_mutex_lock(plock, timeout_ms ) != 0){
DBG_8195A("[%s] %s(%p) failed, retry\n", aos_task_name(), __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)
{
*pirqL = cpu_intrpt_save( );
}
static void _aos_exit_critical(_lock *plock, _irqL *pirqL)
{
cpu_intrpt_restore(*pirqL);
}
static void _aos_enter_critical_from_isr(_lock *plock, _irqL *pirqL)
{
*pirqL = cpu_intrpt_save( );
}
static void _aos_exit_critical_from_isr(_lock *plock, _irqL *pirqL)
{
cpu_intrpt_restore(*pirqL);
}
#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] %s(%p) failed, retry\n", aos_task_name(), __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] %s(%p) failed, retry\n", aos_task_name(), __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);
}
#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);
#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);
}
#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);
#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();
#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();
save_and_cli();
v->counter += i;
restore_flags();
}
static void _aos_ATOMIC_SUB(ATOMIC_T *v, int i)
{
CPSR_ALLOC();
save_and_cli();
v->counter -= i;
restore_flags();
}
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();
save_and_cli();
temp = v->counter;
temp += i;
v->counter = temp;
restore_flags();
return temp;
}
static int _aos_ATOMIC_SUB_RETURN(ATOMIC_T *v, int i)
{
int temp;
CPSR_ALLOC();
save_and_cli();
temp = v->counter;
temp -= i;
v->counter = temp;
restore_flags();
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, size_t 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();
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.hdl){
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);
}
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 )
{
_timerHandle t_handler= _aos_zmalloc(sizeof(struct timerHandle));
if(xTimerPeriodInTicks>= 0xffffffff)
xTimerPeriodInTicks = 0x7ffffffe;
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;
if (timer == NULL) {
return -EINVAL;
}
ret = krhino_timer_stop(timer->hdl);
if (ret != RHINO_SUCCESS) {
return ret;
}
ret = krhino_timer_change(timer->hdl, MS2TICK(ms), 0);
if (ret == RHINO_SUCCESS) {
return 0;
}
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 )
{
return !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
#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
#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");
#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_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
};

View file

@ -0,0 +1,128 @@
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef __AOS_OSDEP_SERVICE_H_
#define __AOS_OSDEP_SERVICE_H_
#include "dlist.h"
#include <aos/aos.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"
#else
// other MCU may use standard library
#include <string.h>
#endif
#define configTICK_RATE_HZ ( ( uint32_t ) 1000 )
#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_zmalloc
#define vPortFree _aos_mfree
/*
* 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;
#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

View file

@ -0,0 +1,377 @@
/**
* @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 "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);
/**
* 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
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);
}
}

View file

@ -0,0 +1,25 @@
#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

View file

@ -0,0 +1,135 @@
#include <sys/unistd.h>
#include <sys/errno.h>
#include "hal/soc/soc.h"
#include <stdarg.h>
#include <hal/hal.h>
#include "CheckSumUtils.h"
#include "platform_toolchain.h"
static uart_dev_t qc_uart;
#ifndef SERIAL_NUMBER
#define SERIAL_NUMBER "UNDF.0000.0000"
#endif
#ifndef BOOT_VERSION
#define BOOT_VERSION "1.0.0"
#endif
WEAK char *get_sn(void)
{
return SERIAL_NUMBER;
}
static 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);
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);
}
}
static const hal_wifi_event_cb_t g_wifi_hal_event = {
.connect_fail = NULL,
.ip_got = NULL,
.stat_chg = NULL,
.scan_compeleted = qc_scan_completed_event,
.scan_adv_compeleted = NULL,
.para_chg = NULL,
.fatal_err = NULL,
};
static void qc_scan(void)
{
hal_wifi_module_t *module;
uint8_t mac[6];
module = hal_wifi_get_default_module();
hal_wifi_install_event(module, &g_wifi_hal_event);
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] );
hal_wifi_start_scan(module);
}
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;
qc_uart.port = 0;
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() );
qc_scan();
while(1) // dead loop, DONOT exit QC mode
aos_msleep(10000);
}

View file

@ -0,0 +1,159 @@
/*
* 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 "system_8195a.h"
#if (RHINO_CONFIG_HW_COUNT > 0)
void soc_hw_timer_init(void)
{
}
hr_timer_t soc_hr_hw_cnt_get(void)
{
return 0;
//return *(volatile uint64_t *)0xc0000120;
}
lr_timer_t soc_lr_hw_cnt_get(void)
{
return 0;
}
#endif /* RHINO_CONFIG_HW_COUNT */
#if (RHINO_CONFIG_INTRPT_GUARD > 0)
void soc_intrpt_guard(void)
{
}
#endif
#if (RHINO_CONFIG_INTRPT_STACK_REMAIN_GET > 0)
size_t soc_intrpt_stack_remain_get(void)
{
return 0;
}
#endif
#if (RHINO_CONFIG_INTRPT_STACK_OVF_CHECK > 0)
void soc_intrpt_stack_ovf_check(void)
{
}
#endif
#if (RHINO_CONFIG_DYNTICKLESS > 0)
void soc_tick_interrupt_set(tick_t next_ticks,tick_t elapsed_ticks)
{
}
tick_t soc_elapsed_ticks_get(void)
{
return 0;
}
#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
#if (BOARD_NAME == AMEBAZ)
k_mm_region_t g_mm_region[] = {{(uint8_t*)&heap_start,(size_t)&heap_len},
{(uint8_t*)MM_ALIGN_UP(0x100014f9), MM_ALIGN_DOWN(0xb07)},
{(uint8_t*)MM_ALIGN_UP(0x10002475), MM_ALIGN_DOWN(0x2b8b)}};
#else
k_mm_region_t g_mm_region[] = {{(uint8_t*)&heap_start,(size_t)&heap_len},{(uint8_t*)0x10005000, (size_t)0x8000}};
#endif
#endif
int g_region_num = sizeof(g_mm_region)/sizeof(k_mm_region_t);
#endif
#if (RHINO_CONFIG_MM_LEAKCHECK > 0 )
//extern int __bss_start__, __bss_end__, _sdata, _edata;
//u8* __bss_start__;
void aos_mm_leak_region_init(void)
{
#if (RHINO_CONFIG_MM_DEBUG > 0)
krhino_mm_leak_region_init(__bss_start__, __bss_end__);
//krhino_mm_leak_region_init(&_sdata, &_edata);
#endif
}
#endif
#if (RHINO_CONFIG_TASK_STACK_CUR_CHECK > 0)
size_t soc_get_cur_sp()
{
size_t sp = 0;
#if defined (__GNUC__)&&!defined(__CC_ARM)
asm volatile(
"mov %0,sp\n"
:"=r"(sp));
#endif
return sp;
}
static void soc_print_stack()
{
void *cur, *end;
int i=0;
int *p;
ktask_t * task;
task = krhino_cur_task_get();
printf("task name %s\r\n", task->task_name);
end = krhino_cur_task_get()->task_stack_base + krhino_cur_task_get()->stack_size;
cur = (void *)soc_get_cur_sp();
p = (int*)cur;
while(p < (int*)end) {
if(i%4==0) {
printf("\r\n%08x:",(uint32_t)p);
}
printf("%08x ", *p);
i++;
p++;
}
printf("\r\n");
return;
}
#endif
void soc_err_proc(kstat_t err)
{
(void)err;
printf("soc_err_proc : %d", err);
#if (RHINO_CONFIG_TASK_STACK_CUR_CHECK > 0)
soc_print_stack();
#endif
assert(0);
}
krhino_err_proc_t g_err_proc = soc_err_proc;

View file

@ -0,0 +1,233 @@
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include <k_api.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <aos/network.h>
#include <hal/trace.h>
#include <aos/aos.h>
/* CLI Support */
#ifdef CONFIG_AOS_CLI
/* Trace Open*/
#if (RHINO_CONFIG_TRACE > 0)
#define TRACE_TASK_STACK_SIZE 512
extern struct k_fifo trace_fifo;
extern int32_t set_filter_task(const char * task_name);
extern void set_event_mask(const uint32_t mask);
extern void trace_deinit(void);
static ktask_t *trace_task;
static uint32_t trace_buf[1024];
static volatile int trace_is_started;
static char *filter_task;
static char *ip_addr;
static uint16_t ip_port = 8000;
static int sockfd;
void *trace_hal_init()
{
int fd;
struct sockaddr_in servaddr;
TRACE_INIT();
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
aos_cli_printf("create socket (%s:%u) error: %s(errno: %d)\r\n", ip_addr, ip_port, strerror(errno),errno);
return 0;
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(ip_port);
inet_aton(ip_addr, &servaddr.sin_addr);
if (connect(fd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0) {
aos_cli_printf("connect (%s:%u) error: %s(errno: %d)\r\n", ip_addr, ip_port, strerror(errno),errno);
close(fd);
return 0;
}
aos_cli_printf("connected on (%s:%u)\r\n", ip_addr, ip_port);
return (void *)fd;
}
ssize_t trace_hal_send(void *handle, void *buf, size_t len)
{
int len_send = 0;
int len_total_send = 0;
while (1) {
len_send = send((int)handle, (buf + len_total_send) , len, 0);
if (len_send < 0) {
aos_cli_printf("send (%s:%u) msg error: %s(errno: %d)\r\n", ip_addr, ip_port, strerror(errno), errno);
return 0;
}
len_total_send += len_send;
len -= len_send;
if (len == 0) {
break;
}
}
return len_send;
}
ssize_t trace_hal_recv(void *handle, void *buf)
{
return 0;
}
void trace_hal_deinit(void *handle)
{
int fd;
fd = (int)handle;
close(fd);
*(int *)handle = -1;
sockfd = -1;
}
void trace_stop(void)
{
set_filter_task(NULL);
set_event_mask(0);
trace_deinit();
trace_hal_deinit((void *)sockfd);
aos_cli_printf("trace (%s:%u) stop....\r\n", ip_addr, ip_port);
if (ip_addr) {
aos_free(ip_addr);
ip_addr = NULL;
}
if (filter_task){
aos_free(filter_task);
filter_task = NULL;
}
}
static void trace_entry(void *arg)
{
uint32_t len;
while (1) {
if (trace_is_started == 0 ){
if (sockfd > 0) {
trace_stop();
}
krhino_task_sleep(200);
} else {
if (sockfd <= 0) {
sockfd = (int)trace_hal_init();
}
if (sockfd > 0) {
len = fifo_out_all(&trace_fifo, trace_buf);
if (len > 0) {
trace_hal_send((void *)sockfd, trace_buf, len);
}
}
krhino_task_sleep(20);
}
}
}
static void handle_trace_cmd(char *pwbuf, int blen, int argc, char **argv)
{
const char *rtype = argc > 1 ? argv[1] : "";
int ret = 0;
if (strcmp(rtype, "start") == 0) {
trace_is_started = 1;
if (argc == 3 || argc == 4) {
if (ip_addr == NULL) {
ip_addr = (char *) aos_malloc(strlen(argv[2])+1);
if (ip_addr == NULL) {
k_err_proc(RHINO_NO_MEM);
}
strncpy(ip_addr, argv[2], strlen(argv[2]));
ip_addr[strlen(argv[2])] = '\0';
}
if (argc ==4){
ip_port = atoi(argv[3]);
}
} else {
aos_cli_printf("trace must specify the host ip (port)... \r\n");
return ;
}
if (trace_task == NULL && krhino_task_dyn_create(&trace_task, "trace_task", NULL, 3,
0, TRACE_TASK_STACK_SIZE, trace_entry, 1) != RHINO_SUCCESS) {
aos_cli_printf("trace task creat fail \r\n");
}
} else if (strcmp(rtype, "task") == 0) {
if (argc != 3) {
return;
}
if (filter_task) {
aos_free(filter_task);
}
filter_task = (char *) aos_malloc(strlen(argv[2])+1);
if (filter_task == NULL) {
k_err_proc(RHINO_NO_MEM);
}
strncpy(filter_task, argv[2], strlen(argv[2]));
filter_task[strlen(argv[2])] = '\0';
set_filter_task(filter_task);
} else if (strcmp(rtype, "event") == 0) {
if (argc != 3) {
return;
}
set_event_mask(atoi(argv[2]));
} else if (strcmp(rtype, "stop") == 0) {
trace_is_started = 0;
}
}
static struct cli_command ncmd = {
.name = "trace",
.help = "trace [start ip (port) | task task_name| event event_id| stop]",
.function = handle_trace_cmd,
};
void trace_start(void)
{
aos_cli_register_command(&ncmd);
}
#else
void trace_start(void)
{
printf("trace config close!!!\r\n");
}
#endif /* Trace end*/
#else
void trace_start(void)
{
printf("trace should have cli to control!!!\r\n");
}
#endif /*Cli end*/

View file

@ -0,0 +1,36 @@
/*
* 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>
*
*/
#if defined(__IAR_SYSTEMS_ICC__)|| defined (__GNUC__)
#pragma pack(1)
#endif

View file

@ -0,0 +1,193 @@
/*
* 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"
#include "typedef.h"
/*
* Typedefs for the types used by lwip -
* u8_t, s8_t, u16_t, s16_t, u32_t, s32_t, mem_ptr_t
*/
typedef unsigned char u8_t; /* Unsigned 8 bit quantity */
typedef signed char s8_t; /* Signed 8 bit quantity */
typedef unsigned short u16_t; /* Unsigned 16 bit quantity */
typedef signed short s16_t; /* Signed 16 bit quantity */
typedef unsigned long u32_t; /* Unsigned 32 bit quantity */
typedef signed long s32_t; /* Signed 32 bit quantity */
//typedef unsigned long mem_ptr_t; /* Unsigned 32 bit quantity */
typedef int intptr_t;
typedef unsigned int uintptr_t;
#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__ */

View file

@ -0,0 +1,37 @@
/*
* 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__
#define BYTE_ORDER LITTLE_ENDIAN
#endif /* __CPU_H__ */

View file

@ -0,0 +1,38 @@
/*
* 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>
*
*/
#if defined(__IAR_SYSTEMS_ICC__)
#pragma pack()
#elif defined (__GNUC__)
#pragma pack()
#endif

View file

@ -0,0 +1,44 @@
/*
* 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 __ARCH_INIT_H__
#define __ARCH_INIT_H__
#define TCPIP_INIT_DONE(arg) tcpip_init_done(arg)
void tcpip_init_done(void *);
int wait_for_tcpip_init(void);
#endif /* __ARCH_INIT_H__ */

View file

@ -0,0 +1,38 @@
/*
* 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 __LIB_H__
#define __LIB_H__
#include <string.h>
#endif /* __LIB_H__ */

View file

@ -0,0 +1,17 @@
#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

View file

@ -0,0 +1,472 @@
/*
* 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 3072
#define TCPIP_THREAD_PRIO 7
#define DEFAULT_THREAD_STACKSIZE 200
#define DEFAULT_THREAD_PRIO 1
/* Disable lwIP asserts */
#define LWIP_NOASSERT 1
#define LWIP_DEBUG 0
#define LWIP_DEBUG_TRACE 0
#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 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 16
#define TCPIP_MBOX_SIZE 16
/**
* 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
#define TCP_MAXRTX 6
/*
----------------------------------------
---------- 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 2 // 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
#define LWIP_SO_SNDTIMEO 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 (3*TCP_MSS)
/* TCP sender buffer space (bytes). */
#define TCP_SND_BUF (10*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 IP_REASS_MAX_PBUFS 0
#define IP_REASSEMBLY 0
#define MEMP_NUM_REASSDATA 0
#define IP_FRAG 0
#define MEM_LIBC_MALLOC (1)
#define DEFAULT_UDP_RECVMBOX_SIZE 3 // yhb set, each udp socket max buffer 3 packets.
#define MEMP_MEM_MALLOC (1)
#define TCP_MSL (TCP_TMR_INTERVAL)
#define LWIP_COMPAT_MUTEX_ALLOWED (1)
//#endif
#define TCPIP_MBOX_SIZE 16
#define DEFAULT_ACCEPTMBOX_SIZE 8
#define DEFAULT_RAW_RECVMBOX_SIZE 4
#define DEFAULT_UDP_RECVMBOX_SIZE 8
#define DEFAULT_TCP_RECVMBOX_SIZE 8
#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__ */

View file

@ -0,0 +1,38 @@
/*
* 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 __PERF_H__
#define __PERF_H__
#define PERF_START /* null definition */
#define PERF_STOP(x) /* null definition */
#endif /* __PERF_H__ */

View file

@ -0,0 +1,88 @@
/**
******************************************************************************
* @file platform_assert.h
* @author William Xu
* @version V1.0.0
* @date 05-May-2014
******************************************************************************
* UNPUBLISHED PROPRIETARY SOURCE CODE
* Copyright (c) 2016 MXCHIP Inc.
*
* The contents of this file may not be disclosed to third parties, copied or
* duplicated in any form, in whole or in part, without the prior written
* permission of MXCHIP Corporation.
******************************************************************************
*/
#pragma once
/******************************************************
* Macros
******************************************************/
/******************************************************
* Constants
******************************************************/
#ifdef __GNUC__
#define MICO_ASSERTION_FAIL_ACTION() __asm__("bkpt")
#elif defined ( __IAR_SYSTEMS_ICC__ )
#define MICO_ASSERTION_FAIL_ACTION() __asm("bkpt 0")
#elif defined ( __CC_ARM )
#define MICO_ASSERTION_FAIL_ACTION() __asm("bkpt 0")
#endif
#if defined ( __GNUC__ )
#if defined ( __clang__ )
static inline /*@noreturn@*/void MICO_TRIGGER_BREAKPOINT( void ) __attribute__((analyzer_noreturn))
{
__asm__("bkpt");
}
#else
#define MICO_TRIGGER_BREAKPOINT( ) do { __asm__("bkpt"); } while (0)
#endif /* #if defined ( __clang__ ) */
#ifdef NO_VECTORS
#define MICO_DISABLE_INTERRUPTS() do { __asm__("" : : : "memory"); } while (0)
#define MICO_ENABLE_INTERRUPTS() do { __asm__("" : : : "memory"); } while (0)
#else
#define MICO_DISABLE_INTERRUPTS() do { __asm__("CPSID i" : : : "memory"); } while (0)
#define MICO_ENABLE_INTERRUPTS() do { __asm__("CPSIE i" : : : "memory"); } while (0)
#endif
#define CSPR_INTERRUPTS_DISABLED (0x80)
#elif defined ( __IAR_SYSTEMS_ICC__ )
#define MICO_TRIGGER_BREAKPOINT() do { __asm("bkpt 0"); } while (0)
#define MICO_DISABLE_INTERRUPTS() do { __asm("CPSID i"); } while (0)
#define MICO_ENABLE_INTERRUPTS() do { __asm("CPSIE i"); } while (0)
#endif
/******************************************************
* Enumerations
******************************************************/
/******************************************************
* Type Definitions
******************************************************/
/******************************************************
* Structures
******************************************************/
/******************************************************
* Global Variables
******************************************************/
/******************************************************
* Function Declarations
******************************************************/

View file

@ -0,0 +1,58 @@
#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

Binary file not shown.

View file

@ -0,0 +1,23 @@
.PHONY: download_app download kill_openocd
ifeq (download,$(findstring download,$(MAKECMDGOALS)))
OPENOCD_LOG_FILE ?= $(BUILD_DIR)/openocd_log.txt
DOWNLOAD_LOG := >> $(OPENOCD_LOG_FILE)
endif
ifeq (,$(and $(OPENOCD_PATH),$(OPENOCD_FULL_NAME)))
$(error Path to OpenOCD has not been set using OPENOCD_PATH and OPENOCD_FULL_NAME)
endif
download_app: gen_crc_bin display_map_summary kill_openocd
$(eval IMAGE_SIZE := $(shell $(PYTHON) $(IMAGE_SIZE_SCRIPT) $(BIN_OUTPUT_FILE)))
$(QUIET)$(ECHO) Downloading application to partition: $(APPLICATION_FIRMWARE_PARTITION_TCL) size: $(IMAGE_SIZE) bytes...
$(call CONV_SLASHES, $(OPENOCD_FULL_NAME)) -s $(SOURCE_ROOT) -f $(OPENOCD_CFG_PATH)interface/$(JTAG).cfg -f $(OPENOCD_CFG_PATH)rtl8710/rtl8710.cfg -c "gdb_port disabled" -c "tcl_port disabled" -c "telnet_port disabled" -c init -c erase_chip -c "program_flash $(LINK_OUTPUT_FILE:$(LINK_OUTPUT_SUFFIX)=.all$(BIN_OUTPUT_SUFFIX)) 0" -c reset -c shutdown $(DOWNLOAD_LOG) 2>&1 && $(ECHO) Download complete && $(ECHO_BLANK_LINE) || $(ECHO) Download failed. See $(OPENOCD_LOG_FILE) for detail.
download: download_app $(if $(findstring total,$(MAKECMDGOALS)), EXT_IMAGE_DOWNLOAD,)
kill_openocd:
$(info kill_openocd)

View file

@ -0,0 +1,71 @@
ifneq ($(findstring $(HOST_OS),Win32 Win64),)
AMEBAZ_DIR = $(SOURCE_ROOT)/platform/mcu/$(HOST_MCU_FAMILY)
else
TOP_PATH = $(shell pwd)
AMEBAZ_DIR = $(TOP_PATH)/platform/mcu/$(HOST_MCU_FAMILY)
endif
#AMEBAZ_DIR = C:/raul/code/AliOS/AliOS-Things/platform/mcu/rtl8710bn
#AMEBAZ_DIR = C:\raul\code\AliOS\AliOS-Things\platform\mcu\rtl8710bn
AMEBAZ_TOOLDIR = $(AMEBAZ_DIR)/tools
#BIN_DIR= $(OUTPUT_DIR)/binary
BIN_DIR= $(AMEBAZ_DIR)
TARGET=application
ota1_idx = 1
ota2_idx = 2
ota1_offset = 0x0800B000
ota2_offset = 0x08100000
EXTRA_POST_BUILD_TARGETS += gen_crc_bin gen_standard_images
#cmd /c %cd%\platform\mcu\$(HOST_MCU_FAMILY)\script\postbuild_img2.bat $(ota_offset) %cd% $(APP_FULL) $(PLATFORM)
#$(eval OUT_MSG := $(shell cmd /c %cd%\platform\mcu\$(HOST_MCU_FAMILY)\script\postbuild_img2.bat $(ota_offset) %cd% $(APP_FULL) $(PLATFORM)))
#$(QUIET) $(ECHO) $(HOST_MCU_FAMILY)
gen_crc_bin:
ifneq ($(findstring $(HOST_OS),Win32 Win64),)
@echo $(HOST_OS) $(ota_offset) $(BIN_DIR) $(APP_FULL) $(PLATFORM)
$(eval OUT_MSG := $(shell cmd /c %cd%\platform\mcu\$(HOST_MCU_FAMILY)\script\postbuild_img2.bat $(ota1_offset) %cd% $(APP_FULL) $(PLATFORM)))
$(eval OUT_MSG := $(shell cmd /c %cd%\platform\mcu\$(HOST_MCU_FAMILY)\script\postbuild_img2.bat $(ota2_offset) %cd% $(APP_FULL) $(PLATFORM)))
else
@echo $(HOST_OS) $(ota_idx) $(TOP_PATH) $(APP_FULL) $(PLATFORM) $(TOOLCHAIN_PATH)
$(eval OUT_MSG := $(shell sh $(TOP_PATH)/platform/mcu/$(HOST_MCU_FAMILY)/script/manipulate_image.sh $(ota1_idx) $(TOP_PATH) $(APP_FULL) $(PLATFORM) $(TOOLCHAIN_PATH)))
$(eval OUT_MSG := $(shell sh $(TOP_PATH)/platform/mcu/$(HOST_MCU_FAMILY)/script/manipulate_image.sh $(ota2_idx) $(TOP_PATH) $(APP_FULL) $(PLATFORM) $(TOOLCHAIN_PATH)))
endif
#bootloader
BOOT_BIN_FILE := $(OUTPUT_DIR)/binary/boot_all.bin
BOOT_OFFSET := 0x0
#application
SYSTEM_BIN_FILE :=board/$(PLATFORM)/system.bin
SYSTEM_OFFSET:= 0x9000
#application
APP_BIN_FILE :=$(OUTPUT_DIR)/binary/image2_all_app1.bin
APP_OFFSET:= 0xB000
#ate firmware
ATE_BIN_FILE := board/$(PLATFORM)/ate.bin
ATE_OFFSET:= 0xD0000
# Required to build Full binary file
GEN_COMMON_BIN_OUTPUT_FILE_SCRIPT:= $(SCRIPTS_PATH)/gen_common_bin_output_file.py
MOC_ALL_BIN_OUTPUT_FILE :=$(LINK_OUTPUT_FILE:$(LINK_OUTPUT_SUFFIX)=.all$(BIN_OUTPUT_SUFFIX))
ifeq (EXTRA_ATE_BIN, on)
gen_standard_images: gen_crc_bin
$(QUIET)$(ECHO) Generate Standard Flash Images: $(MOC_ALL_BIN_OUTPUT_FILE)
$(QUIET)$(RM) $(MOC_ALL_BIN_OUTPUT_FILE)
$(PYTHON) $(GEN_COMMON_BIN_OUTPUT_FILE_SCRIPT) -o $(MOC_ALL_BIN_OUTPUT_FILE) -f $(BOOT_OFFSET) $(BOOT_BIN_FILE)
$(PYTHON) $(GEN_COMMON_BIN_OUTPUT_FILE_SCRIPT) -o $(MOC_ALL_BIN_OUTPUT_FILE) -f $(SYSTEM_OFFSET) $(SYSTEM_BIN_FILE)
$(PYTHON) $(GEN_COMMON_BIN_OUTPUT_FILE_SCRIPT) -o $(MOC_ALL_BIN_OUTPUT_FILE) -f $(APP_OFFSET) $(APP_BIN_FILE)
$(PYTHON) $(GEN_COMMON_BIN_OUTPUT_FILE_SCRIPT) -o $(MOC_ALL_BIN_OUTPUT_FILE) -f $(ATE_OFFSET) $(ATE_BIN_FILE)
else
gen_standard_images: gen_crc_bin
$(QUIET)$(ECHO) Generate Standard Flash Images: $(MOC_ALL_BIN_OUTPUT_FILE)
$(QUIET)$(RM) $(MOC_ALL_BIN_OUTPUT_FILE)
$(PYTHON) $(GEN_COMMON_BIN_OUTPUT_FILE_SCRIPT) -o $(MOC_ALL_BIN_OUTPUT_FILE) -f $(BOOT_OFFSET) $(BOOT_BIN_FILE)
$(PYTHON) $(GEN_COMMON_BIN_OUTPUT_FILE_SCRIPT) -o $(MOC_ALL_BIN_OUTPUT_FILE) -f $(SYSTEM_OFFSET) $(SYSTEM_BIN_FILE)
$(PYTHON) $(GEN_COMMON_BIN_OUTPUT_FILE_SCRIPT) -o $(MOC_ALL_BIN_OUTPUT_FILE) -f $(APP_OFFSET) $(APP_BIN_FILE)
endif

View file

@ -0,0 +1,101 @@
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
//#include "platform_peripheral.h"
#include "hal/soc/soc.h"
#include "board.h"
#include "flash_api.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[];
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, 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;
}

View file

@ -0,0 +1,170 @@
/**
******************************************************************************
* @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 "PinNames.h"
#include "objects.h"
#include "gpio_irq_api.h"
#include <hal/soc/soc.h>
const static uint8_t gpio_remap[] =
{
[0 ] = PA_14,
[1 ] = PA_15,
[2 ] = PA_22,
[3 ] = PA_19,
[4 ] = PA_23,
[5 ] = PA_18,
[6 ] = PA_0,
[7 ] = PA_12,
[8 ] = PA_5,
[9 ] = PA_11,
[10] = PA_30,
[11] = PA_29,
[12] = PA_8,
};
typedef struct
{
gpio_t gpio_obj;
gpio_irq_t gpio_irq_obj;
} gpio_objs_t;
int32_t hal_gpio_init( gpio_dev_t *gpio )
{
if(!gpio)
return -1;
gpio->priv = malloc(sizeof(gpio_objs_t));
gpio_t *gpio_obj = &(((gpio_objs_t *)(gpio->priv))->gpio_obj);
uint8_t pin = gpio_remap[gpio->port];
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->priv)
return -1;
gpio_deinit(&(((gpio_objs_t *)(gpio->priv))->gpio_obj));
free(gpio->priv);
gpio->priv = NULL;
return 0;
}
int32_t hal_gpio_output_high( gpio_dev_t* gpio )
{
gpio_write(&(((gpio_objs_t *)(gpio->priv))->gpio_obj), 1);
return 0;
}
int32_t hal_gpio_output_low( gpio_dev_t* gpio )
{
gpio_write(&(((gpio_objs_t *)(gpio->priv))->gpio_obj), 0);
return 0;
}
int32_t hal_gpio_output_toggle( gpio_dev_t* gpio )
{
gpio_write(&(((gpio_objs_t *)(gpio->priv))->gpio_obj), !gpio_read(&(((gpio_objs_t *)(gpio->priv))->gpio_obj)));
return 0;
}
int32_t hal_gpio_input_get(gpio_dev_t *gpio, uint32_t *value)
{
*value = gpio_read(&(((gpio_objs_t *)(gpio->priv))->gpio_obj)) == 0 ? 0 : 1;
return 0;
}
int32_t hal_gpio_enable_irq(gpio_dev_t *gpio, gpio_irq_trigger_t trigger, gpio_irq_handler_t handler, void *arg)
{
gpio_irq_t *gpio_irq_obj = &(((gpio_objs_t *)(gpio->priv))->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 )
{
gpio_irq_deinit(&(((gpio_objs_t *)(gpio->priv))->gpio_irq_obj));
return 0;
}

View file

@ -0,0 +1,84 @@
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <k_api.h>
#include <aos/log.h>
#include <hal/soc/soc.h>
#include <hal/soc/timer.h>
#include <hal/base.h>
#include <hal/wifi.h>
#include "board.h"
#include "diag.h"
#include "platform_stdlib.h"
#define TAG "hw"
#define us2tick(us) \
((us * RHINO_CONFIG_TICKS_PER_SECOND + 999999) / 1000000)
uart_dev_t uart_0;
uart_dev_t uart_1;
extern hal_wifi_module_t sim_aos_wifi_mico;
void hal_reboot(void)
{
sys_reset();
}
static void _timer_cb(void *timer, void *arg)
{
timer_dev_t *tmr = arg;
tmr->config.cb(tmr->config.arg);
}
int32_t hal_timer_init(timer_dev_t *tim)
{
if (tim->config.reload_mode == TIMER_RELOAD_AUTO) {
krhino_timer_dyn_create((ktimer_t **)&tim->priv, "hwtmr", _timer_cb,
us2tick(tim->config.period), us2tick(tim->config.period), tim, 0);
}
else {
krhino_timer_dyn_create((ktimer_t **)&tim->priv, "hwtmr", _timer_cb,
us2tick(tim->config.period), 0, tim, 0);
}
return 0;
}
int32_t hal_timer_start(timer_dev_t *tmr)
{
return krhino_timer_start(tmr->priv);
}
void hal_timer_stop(timer_dev_t *tmr)
{
krhino_timer_stop(tmr->priv);
krhino_timer_dyn_del(tmr->priv);
tmr->priv = NULL;
}
extern hal_wifi_module_t rtl8710bn_wifi_module;
void hw_start_hal(void)
{
DBG_8195A("start hal-----------\n");
hal_wifi_register_module(&rtl8710bn_wifi_module);
#ifdef CONFIG_AOS_MESH
hal_umesh_register_wifi(&rtl8710bn_wifi_module);
#endif
uart_0.port = MICO_UART_1;
uart_0.config.baud_rate = 115200;
uart_0.config.data_width = DATA_WIDTH_8BIT;
uart_0.config.parity = NO_PARITY;
uart_0.config.stop_bits = STOP_BITS_1;
uart_0.config.flow_control = FLOW_CONTROL_DISABLED;
hal_uart_init(&uart_0);
}

View file

@ -0,0 +1,199 @@
/*
Date : 2018/07/26
Author : Snow Yang
Mail : yangsw@mxchip.com
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <hal/ota.h>
#include <aos/aos.h>
#include <hal/soc/soc.h>
#include <CheckSumUtils.h>
#define LOG(fmt, ...)
#define KV_HAL_OTA_CRC16 "hal_ota_get_crc16"
typedef struct ota_hal_module_s {
int (*init)(void *something);
int (*write)(int *off_set, char *in_buf , int in_buf_len);
int (*read)(int *off_set, char *out_buf , int out_buf_len);
int (*boot)(void *something);
int (*rollback)(void *something);
const char *(*version)(unsigned char dev_type);
}ota_hal_module_t;
typedef struct
{
uint32_t ota_len;
uint32_t ota_crc;
} ota_reboot_info_t;
static ota_reboot_info_t ota_info;
static uint16_t hal_ota_get_crc16(void);
static void hal_ota_save_crc16(uint16_t crc16);
static int boot_table_update( boot_table_t * boot_table )
{
int ret = 0;
uint32_t offset;
boot_table_t *boot_table_dump = malloc(sizeof(boot_table_t));
hal_flash_erase(HAL_PARTITION_PARAMETER_1, 0x0, hal_flash_get_info( HAL_PARTITION_PARAMETER_1 )->partition_length);
offset = 0x0;
hal_flash_write(HAL_PARTITION_PARAMETER_1, &offset, boot_table, sizeof(boot_table_t));
offset = 0x0;
hal_flash_read(HAL_PARTITION_PARAMETER_1, &offset, boot_table_dump, sizeof(boot_table_t));
if(memcmp(boot_table, boot_table_dump, sizeof(boot_table_t)) != 0)
{
ret = -1;
}
free(boot_table_dump);
return ret;
}
int hal_ota_switch_to_new_fw(uint8_t parti, int ota_data_len, uint16_t ota_data_crc )
{
int ret = 0;
boot_table_t* boot_table = malloc(sizeof(boot_table_t));
memset(boot_table, 0, sizeof(boot_table_t));
boot_table->length = ota_data_len;
boot_table->start_address = hal_flash_get_info( HAL_PARTITION_OTA_TEMP )->partition_start_addr;
boot_table->type = 'A';
boot_table->upgrade_type = 'U';
boot_table->crc = ota_data_crc;
if(boot_table_update(boot_table) != 0)
{
ret = -1;
}
else
{
/* reboot */
hal_reboot();
}
free(boot_table);
return ret;
}
static CRC16_Context contex;
unsigned int _off_set = 0;
typedef struct {
unsigned int dst_adr;
unsigned int src_adr;
unsigned int len;
unsigned short crc;
unsigned int upg_flag;
unsigned char boot_count;
unsigned int splict_size;
int off_bp; /*Break point offset*/
unsigned char res_type; /*result type: OTA_FINISH, OTA_BREAKPOINT*/
unsigned short param_crc; /*Parameter crc*/
} __attribute__((packed)) ota_boot_param_t;
static int ota_init(void *something)
{
hal_logic_partition_t *partition_info;
ota_boot_param_t *param = (ota_boot_param_t *)something;
_off_set = param->off_bp;
ota_info.ota_len=_off_set;
LOG("ota_init(), offset=%d", param->off_bp);
if(_off_set==0)
{
wdg_dev_t sys_wdg;
sys_wdg.config.timeout = 20000;
hal_wdg_init(&sys_wdg);
partition_info = hal_flash_get_info( HAL_PARTITION_OTA_TEMP );
hal_wdg_reload(NULL);
hal_flash_erase(HAL_PARTITION_OTA_TEMP, 0 ,partition_info->partition_length);
hal_wdg_reload(NULL);
CRC16_Init( &contex );
LOG("ota_init(), return");
}
return 0;
}
static int ota_write(volatile uint32_t* off_set, uint8_t* in_buf ,uint32_t in_buf_len)
{
LOG("ota_write(), offset=0x%x, length=0x%x", *off_set, in_buf_len);
if(ota_info.ota_len == 0) {
_off_set = 0;
CRC16_Init( &contex );
memset(&ota_info, 0 , sizeof ota_info);
}
CRC16_Update( &contex, in_buf, in_buf_len);
hal_wdg_reload(NULL);
int ret = hal_flash_write(HAL_PARTITION_OTA_TEMP, &_off_set, in_buf, in_buf_len);
hal_wdg_reload(NULL);
ota_info.ota_len += in_buf_len;
return ret;
}
static int ota_read(volatile uint32_t* off_set, uint8_t* out_buf, uint32_t out_buf_len)
{
hal_flash_read(HAL_PARTITION_OTA_TEMP, off_set, out_buf, out_buf_len);
return 0;
}
static int ota_set_boot(void *something)
{
ota_boot_param_t *param = (ota_boot_param_t *)something;
LOG("ota_set_boot(), type=%d", param->res_type);
if (param==NULL){
return -1;
}
if (param->res_type==OTA_FINISH)
{
CRC16_Final( &contex, &ota_info.ota_crc );
LOG("ota_set_boot(), switch to new firmware");
hal_ota_switch_to_new_fw(0, ota_info.ota_len, ota_info.ota_crc);
memset(&ota_info, 0 , sizeof ota_info);
}
return 0;
}
static const char *ota_get_version(unsigned char dev_type)
{
if(dev_type) {
return "v1.0.0-20180101-1000";//SYSINFO_APP_VERSION;
} else {
return aos_get_app_version();
}
}
ota_hal_module_t ota_hal_module = {
.init = ota_init,
.write = ota_write,
.read = ota_read,
.boot = ota_set_boot,
.rollback = NULL,
.version = ota_get_version
};
static uint16_t hal_ota_get_crc16(void)
{
int len = 2;
uint16_t crc16=0;
aos_kv_get(KV_HAL_OTA_CRC16, &crc16, &len);
return crc16;
}
static void hal_ota_save_crc16(uint16_t crc16)
{
aos_kv_set(KV_HAL_OTA_CRC16, &crc16, 2, 1);
}

View file

@ -0,0 +1,404 @@
#include <platform/platform_stdlib.h>
#include <osdep_service.h>
#include <rtl8710b_ota.h>
#include <flash_api.h>
#include <device_lock.h>
#include "hal/soc/flash.h"
typedef enum {
OTA_FINISH,
OTA_BREAKPOINT
} OTA_RES_TYPE_E;
typedef struct {
unsigned int dst_adr;
unsigned int src_adr;
unsigned int len;
unsigned short crc;
unsigned int upg_flag;
unsigned char boot_count;
unsigned int splict_size;
int off_bp; /*Break point offset*/
OTA_RES_TYPE_E res_type; /*result type: OTA_FINISH, OTA_BREAKPOINT*/
unsigned short param_crc; /*Parameter crc*/
} __attribute__((packed)) ota_boot_param_t;
typedef struct ota_hal_module_s {
int (*init)(void *something);
int (*write)(int *off_set, char *in_buf , int in_buf_len);
int (*read)(int *off_set, char *out_buf , int out_buf_len);
int (*boot)(void *something);
int (*rollback)(void *something);
const char *(*version)(unsigned char dev_type);
}ota_hal_module_t;
static u32 alinknewImg2Addr = 0xFFFFFFFF;
char *HeadBuffer = NULL;
#define OTA_HEADER_BUF_SIZE 1024
int alink_size = 0;
u8 alink_signature[9] = {0};
extern const update_file_img_id OtaImgId[2];
uint32_t alink_ota_target_index = OTA_INDEX_2;
update_ota_target_hdr OtaTargetHdr;
static int aliota_total_len = 0, aliota_flag = 1, aliota_count = 0;
static uint32_t aliota_address;
static int aliota_RemainBytes = 0;
static int aliota_ota_exit = 0;
static int aliota_ota_flag = 1;
static unsigned long aliota_tick1, aliota_tick2;
static u32 aliota_OtaFg = 0;
static u32 aliota_SigCnt = 0;
static int aliota_end_sig = 0;
hal_logic_partition_t *partition_info = NULL;
#ifndef OTA2_DEFAULT_ADDR
#define OTA2_DEFAULT_ADDR (0x08100000)
#endif
int check_ota_index()
{
uint32_t ota_index = -1;
/* check OTA index we should update */
if (ota_get_cur_index() == OTA_INDEX_1) {
ota_index = OTA_INDEX_2;
} else {
ota_index = OTA_INDEX_1;
}
printf("OTA idx:%d upgrade.\n",ota_index);
return ota_index;
}
bool prepare_ota_address(u32 ota_target_index, u32 * new_addr)
{
IMAGE_HEADER *OTA1Hdr = NULL;
uint32_t OTA1Len = 0;
IMAGE_HEADER *FlashImgDataHdr = NULL;
uint32_t ota2_addr;
ota2_addr = HAL_READ32(SPI_FLASH_BASE, OFFSET_DATA);
printf("ota2_addr = %x\n", ota2_addr);
/*if the OTA2 address is not programmed in system data zone, the default OTA2
address is used. This operation is just used in the local OTA update demo. For the
cloud OTA upgrade based on this demo, this operation may not be used.*/
if(ota2_addr == 0xffffffff) {
ota_write_ota2_addr(OTA2_DEFAULT_ADDR);
ota2_addr = HAL_READ32(SPI_FLASH_BASE, OFFSET_DATA);
}
if((ota2_addr%4096) != 0) {
printf(" ota addr not 4k aligned 0x%x", ota2_addr);
goto error;
}
if(ota_target_index == OTA_INDEX_2) {
/* OAT2 address should not in OTA1 image & should 4K alignment */
OTA1Hdr = (IMAGE_HEADER *)(OTA1_ADDR);
OTA1Len = OTA1Hdr->image_size;
FlashImgDataHdr = (IMAGE_HEADER *)((u32)OTA1Hdr + OTA1Len + IMAGE_HEADER_LEN);
if ((ota2_addr < ((u32)FlashImgDataHdr + FlashImgDataHdr->image_size + IMAGE_HEADER_LEN)) && ((ota2_addr & 0xfff) == 0)) {
printf("\n\r[%s] illegal ota addr 0x%x", __FUNCTION__, ota2_addr);
goto error;
}
*new_addr = ota2_addr;
} else {
*new_addr = OTA1_ADDR;
}
if(*new_addr == 0xFFFFFFFF) {
printf("update addr invalid.\n");
goto error;
}
printf("OTA addr: 0x%x\n", *new_addr);
return TRUE;
error:
return FALSE;
}
static int ota_init(void *something)
{
int ret = 0;
ota_boot_param_t *param = (ota_boot_param_t *)something;
uint32_t part = HAL_PARTITION_OTA_TEMP;
uint32_t offset = 0;
param->off_bp = 0;
printf("ota_init off:0x%x \n", offset);
alink_ota_target_index = check_ota_index();
if(prepare_ota_address(alink_ota_target_index, &alinknewImg2Addr) != TRUE){
printf("get addr failed\n");
ret = -1;
goto RTL8710BN_INIT_ERRO;
}
if(alink_ota_target_index == OTA_INDEX_1) {
part = HAL_PARTITION_APPLICATION;
}
else if(alink_ota_target_index == OTA_INDEX_2) {
part = HAL_PARTITION_OTA_TEMP;
}
else {
printf("flash failed\n");
ret = -1;
goto RTL8710BN_INIT_ERRO;
}
partition_info = hal_flash_get_info(part);
if(partition_info == NULL) {
printf("flash info failed\n");
ret = -1;
goto RTL8710BN_INIT_ERRO;
}
/**dual image pack size + info head(asume 512bytes)**/
if((partition_info->partition_length * 2 + 512) < param->len || param->len == 0) {
ret = -17;
goto RTL8710BN_INIT_ERRO;
}
if(offset == 0) {
alink_size = 0;
aliota_total_len = 0;
aliota_flag = 1;
aliota_count = 0;
aliota_address = 0;
aliota_RemainBytes = 0;
aliota_ota_exit = 0;
aliota_ota_flag = 1;
aliota_tick1 = 0;
aliota_tick2 = 0;
aliota_OtaFg = 0;
aliota_SigCnt = 0;
aliota_end_sig = 0;
/*-------------------erase flash space for new firmware--------------*/
erase_ota_target_flash(alinknewImg2Addr, partition_info->partition_length);
DBG_INFO_MSG_OFF(_DBG_SPI_FLASH_);
HeadBuffer = rtw_malloc(OTA_HEADER_BUF_SIZE);
if (HeadBuffer == NULL) {
printf("malloc head failed\n");
ret = -1;
goto RTL8710BN_INIT_ERRO;
}
}
RTL8710BN_INIT_ERRO:
printf("ota init over!\r\n");
return ret;
}
static int ota_write(int* off_set,char *buffer,int len)
{
char *buf;
flash_t flash;
update_file_hdr OtaFileHdr;
if (aliota_ota_flag) {
aliota_tick1 = rtw_get_current_time();
aliota_ota_flag = 0;
}
/*-----read 4 Dwords from server, get image header number and header length*/
buf = HeadBuffer + aliota_total_len;
aliota_total_len += len;
if (aliota_total_len < 128) {
memcpy(buf, buffer, len);
aliota_count += len;
printf("copy len:%d \n",len);
return 0;
} else if (aliota_total_len >= 128 && aliota_total_len <= OTA_HEADER_BUF_SIZE) {
if (aliota_flag == 1) {
buf = HeadBuffer;
memcpy(buf+aliota_count, buffer, aliota_total_len - aliota_count);
memcpy((u8*)(&OtaTargetHdr.FileHdr), buf, sizeof(OtaTargetHdr.FileHdr));
memcpy((u8*)(&OtaTargetHdr.FileImgHdr), buf+8, 8);
/*------acquire the desired Header info from buffer*/
buf = HeadBuffer;
u8 *TempBuf = NULL;
TempBuf = (u8 *)(&OtaImgId[alink_ota_target_index]);
printf("TempBuf = %s\n",TempBuf);
if (!get_ota_tartget_header(buf, aliota_total_len, &OtaTargetHdr, TempBuf)) {
printf("get header failed\n");
goto update_ota_exit;
}
if (alinknewImg2Addr == 0xFFFFFFFF) {
/*get new image addr and check new address validity*/
if (!get_ota_address(alink_ota_target_index, &alinknewImg2Addr, &OtaTargetHdr)) {
printf("get addr failed\n");
goto update_ota_exit;
}
} else {
/*Image size should not bigger than OTA_SIZE_MAX */
if(partition_info != NULL) {
if(OtaTargetHdr.FileImgHdr.ImgLen > partition_info->partition_length){
printf("illegal image len: 0x%x", OtaTargetHdr.FileImgHdr.ImgLen);
goto update_ota_exit;
}
}
}
/*get new image length from the firmware header*/
uint32_t NewImg2Len = 0, NewImg2BlkSize = 0;
NewImg2Len = OtaTargetHdr.FileImgHdr.ImgLen;
NewImg2BlkSize = ((NewImg2Len - 1)/4096) + 1;
/*the upgrade space should be masked, because the encrypt firmware is used
for checksum calculation*/
OTF_Mask(1, (alinknewImg2Addr - SPI_FLASH_BASE), NewImg2BlkSize, 1);
/* get OTA image and Write New Image to flash, skip the signature,
not write signature first for power down protection*/
aliota_address = alinknewImg2Addr -SPI_FLASH_BASE + 8;
printf("NewImg2Addr = %x\n", alinknewImg2Addr);
aliota_RemainBytes = OtaTargetHdr.FileImgHdr.ImgLen - 8;
aliota_flag = 0;
if (HeadBuffer != NULL) {
rtw_free(HeadBuffer);
}
}
}
/*skip the signature*/
/*download the new firmware from server*/
if(aliota_RemainBytes > 0) {
if(aliota_total_len > OtaTargetHdr.FileImgHdr.Offset) {
if(!aliota_OtaFg) {
u32 Cnt = 0;
/*reach the the desired image, the first packet process*/
aliota_OtaFg = 1;
Cnt = aliota_total_len -OtaTargetHdr.FileImgHdr.Offset;
if(Cnt < 8) {
aliota_SigCnt = Cnt;
} else {
aliota_SigCnt = 8;
}
memcpy(alink_signature, buffer + len -Cnt, aliota_SigCnt);
if((aliota_SigCnt < 8) || (Cnt -8 == 0)) {
return 0;
}
device_mutex_lock(RT_DEV_LOCK_FLASH);
if(flash_stream_write(&flash, aliota_address + alink_size, Cnt -8, buffer + (len -Cnt + 8) ) < 0){
printf("Write failed\r\n");
device_mutex_unlock(RT_DEV_LOCK_FLASH);
goto update_ota_exit;
}
device_mutex_unlock(RT_DEV_LOCK_FLASH);
alink_size += (Cnt - 8);
aliota_RemainBytes -= alink_size;
} else {
/*normal packet process*/
if(aliota_SigCnt < 8) {
if(len < (8 -aliota_SigCnt)) {
memcpy(alink_signature + aliota_SigCnt, buffer, len);
aliota_SigCnt += len;
return 0;
} else {
memcpy(alink_signature + aliota_SigCnt, buffer, (8 -aliota_SigCnt));
aliota_end_sig = 8 -aliota_SigCnt;
len -= (8 -aliota_SigCnt) ;
aliota_SigCnt = 8;
if(!len) {
return 0;
}
aliota_RemainBytes -= len;
if (aliota_RemainBytes <= 0) {
len = len - (-aliota_RemainBytes);
}
device_mutex_lock(RT_DEV_LOCK_FLASH);
if (flash_stream_write(&flash, aliota_address+alink_size, len, buffer+aliota_end_sig) < 0){
printf("Write sector failed\r\n");
device_mutex_unlock(RT_DEV_LOCK_FLASH);
goto update_ota_exit;
}
device_mutex_unlock(RT_DEV_LOCK_FLASH);
alink_size += len;
return 0;
}
}
aliota_RemainBytes -= len;
int end_ota = 0;
if(aliota_RemainBytes <= 0) {
len = len - (-aliota_RemainBytes);
end_ota = 1;
}
device_mutex_lock(RT_DEV_LOCK_FLASH);
if(flash_stream_write(&flash, aliota_address + alink_size, len, buffer) < 0){
printf("Write sec failed\r\n");
device_mutex_unlock(RT_DEV_LOCK_FLASH);
goto update_ota_exit;
}
device_mutex_unlock(RT_DEV_LOCK_FLASH);
alink_size += len;
if (end_ota) {
printf("size = %x\n", alink_size);
}
aliota_tick2 = rtw_get_current_time();
if (aliota_tick2 - aliota_tick1 > 2000) {
printf("Download OTA file: %d B, RemainBytes = %d\n", (alink_size), aliota_RemainBytes);
aliota_ota_flag = 1;
}
}
}
}
return 0;
update_ota_exit:
if (HeadBuffer != NULL) {
rtw_free(HeadBuffer);
}
aliota_ota_exit = 1;
printf("Update task exit");
return -1;
}
static int ota_boot(void *something)
{
ota_boot_param_t *param = (ota_boot_param_t *)something;
if (param == NULL) {
return -1;
}
if (param->res_type == OTA_FINISH) {
flash_t flash;
printf("size = %d, ImgLen = %d sign: %s\n", alink_size, OtaTargetHdr.FileImgHdr.ImgLen, alink_signature);
/*------------- verify checksum and update signature-----------------*/
if(verify_ota_checksum(alinknewImg2Addr, alink_size, alink_signature, &OtaTargetHdr)){
if(!change_ota_signature(alinknewImg2Addr, alink_signature, alink_ota_target_index)) {
printf("\n%s: change signature failed\n");
return -1;
}
return 0;
} else {
/*if checksum error, clear the signature zone which has been
written in flash in case of boot from the wrong firmware*/
device_mutex_lock(RT_DEV_LOCK_FLASH);
flash_erase_sector(&flash, alinknewImg2Addr - SPI_FLASH_BASE);
device_mutex_unlock(RT_DEV_LOCK_FLASH);
printf("chack_sum error\n");
return -1;
}
}
return 0;
}
static int ota_read(int* off, char* out_buf, int out_buf_len)
{
return hal_flash_read(HAL_PARTITION_OTA_TEMP, (uint32_t*)off, out_buf, out_buf_len);
}
static int ota_rollback(void *something)
{
return 0;
}
const char *aos_get_app_version(void);
static const char *ota_get_version(unsigned char dev_type)
{
if(dev_type) {
return "v1.0.0-20180101-1000";//SYSINFO_APP_VERSION;
} else {
return aos_get_app_version();
}
}
ota_hal_module_t ota_hal_module = {
.init = ota_init,
.write = ota_write,
.read = ota_read,
.boot = ota_boot,
.rollback = ota_rollback,
.version = ota_get_version
};

View file

@ -0,0 +1,52 @@
#include "hal/soc/soc.h"
#include "PeripheralNames.h"
#include "pwmout_api.h"
#define PWM_NUM 5
static pwmout_t PWM_OBJ[PWM_NUM];
static PinName PWM_MAP[PWM_NUM] = {
[0] = PA_22,
[1] = PA_0,
[2] = PA_12,
[3] = PA_14,
[4] = PA_5,
};
int32_t hal_pwm_init(pwm_dev_t * pwm)
{
static int init_clk = 0;
if (pwm->port >= PWM_NUM) {
return -1;
}
pwm->priv = &PWM_OBJ[pwm->port];
pwmout_init(pwm->priv, PWM_MAP[pwm->port]);
#if 0
if(!init_clk) {
pwmout_clk_set(pwm->priv, 1, 0);
init_clk = 1;
}
#endif
return 0;
}
int32_t hal_pwm_start(pwm_dev_t * pwm)
{
int us = 1000000/pwm->config.freq;
pwmout_period_us(pwm->priv, us);
pwmout_write(pwm->priv, pwm->config.duty_cycle);
return 0;
}
int32_t hal_pwm_stop(pwm_dev_t * pwm)
{
pwmout_stop(pwm->priv);
return 0;
}
int32_t hal_pwm_finalize(pwm_dev_t * pwm)
{
pwmout_free(pwm->priv);
return 0;
}

View file

@ -0,0 +1,254 @@
/*
* Copyright (C) 2018 Alibaba Group Holding Limited
*/
/*
DESCRIPTION
This library provides the support for the STM32L496G-DISCOVERY
CPU power state control.
CPU power management:
provides low-level interface for setting CPU C-states.
provides low-level interface for setting CPU P-states.
*/
#include <k_api.h>
#if (AOS_COMP_PWRMGMT > 0)
#include <pwrmgmt_api.h>
#include <cpu_pwr_hal_lib.h>
#include <pwrmgmt_debug.h>
#include <cpu_tickless.h>
#include <rtl8710b.h>
typedef enum {
PMU_OS =0,
PMU_WLAN_DEVICE =1,
PMU_LOGUART_DEVICE =2,
PMU_SDIO_DEVICE =3,
PMU_UART0_DEVICE =4,
PMU_UART1_DEVICE =5,
PMU_I2C0_DEVICE =6,
PMU_I2C1_DEVICE =7,
PMU_USOC_DEVICE =8,
PMU_DONGLE_DEVICE =9,
PMU_RTC_DEVICE =10,
PMU_CONSOL_DEVICE =11,
PMU_ADC_DEVICE =12,
PMU_WAKWLOCK_TIMEOUT=13,
PMU_DEV_USER_BASE =16,
PMU_MAX =31
} PMU_DEVICE;
enum SLEEP_TYPE {
SLEEP_PG = 0,
SLEEP_CG = 1,
};
#define PMU_DEV_OTA (PMU_DEV_USER_BASE + 1)
#define SLEEP_WAKEUP_BY_STIMER (BIT_SYSON_WEVT_SYSTIM_MSK) // wake up by system timer
#define SLEEP_WAKEUP_BY_GPIO_INT (BIT_SYSON_WEVT_GPIO_MSK) // wake up by GPIO Port A[31:0] Interrupt
#define SLEEP_WAKEUP_BY_WLAN (BIT_SYSON_WEVT_WLAN_MSK) // wake up by WLan event
#define SLEEP_WAKEUP_BY_SDIO (BIT_SYSON_WEVT_SDIO_MSK) // wake up by SDIO event
#define SLEEP_WAKEUP_BY_USB (BIT_SYSON_WEVT_USB_MSK) // wake up by USB event
#define SLEEP_WAKEUP_BY_GPIO (BIT_SYSON_WEVT_GPIO_DSTBY_MSK) // GPIO Port(PA_18, PA_5, PA_22, PA_23)
#define SLEEP_WAKEUP_BY_UART (BIT_SYSON_WEVT_UART0_MSK | BIT_SYSON_WEVT_UART1_MSK) // wake up by UART event
#define SLEEP_WAKEUP_BY_I2C (BIT_SYSON_WEVT_I2C0_MSK | BIT_SYSON_WEVT_I2C1_MSK) // wake up by I2C event
#define SLEEP_WAKEUP_BY_RTC (BIT_SYSON_WEVT_RTC_MSK) // wake up by RTC event
/* forward declarations */
extern one_shot_timer_t rtc_one_shot; /* wakeup source for C3,C4 */
static uint32_t wakeup_event = SLEEP_WAKEUP_BY_STIMER | SLEEP_WAKEUP_BY_GPIO_INT | SLEEP_WAKEUP_BY_WLAN | SLEEP_WAKEUP_BY_UART | SLEEP_WAKEUP_BY_RTC;
extern uint64_t expeted_sleep_ms;
static cpu_pwr_t cpu_pwr_node_core_0;
void pmu_release_wakelock(uint32_t nDeviceId);
void sleep_ex_cg(uint32_t wakeup_event, uint32_t sleep_duration)
{
SOCPS_SleepInit();
static uint32_t CalibData = 0;
if (CalibData == 0) {
CalibData = SOCPS_CLKCal(A33CK);
}
/* user setting have high priority */
SOCPS_SetWakeEvent(wakeup_event, ENABLE);
if (sleep_duration > 0) {
SOCPS_SET_REGUTIMER(sleep_duration, CalibData);
}
SOCPS_SleepCG();
NVIC_SetPriority(UART_LOG_IRQ, 10);
}
/**
* board_cpu_c_state_set - program CPU into Cx idle state
*
* RUN Context: could be called from ISR context or task context.
*
* SMP Consider: STM32L496G-DISCOVERY do not support SMP, so only UP is enough.
*
* @return PWR_OK or PWR_ERR when failed.
*/
static pwr_status_t board_cpu_c_state_set(uint32_t cpuCState, int master)
{
#if (PWRMGMT_CONFIG_LOG_ENTERSLEEP > 0)
static sys_time_t last_log_entersleep = 0;
#endif
switch (cpuCState) {
case CPU_CSTATE_C0:
if (master) {
/*
* do something needed when CPU waked up from C1 or higher
* Cx state.
*/
}
break;
case CPU_CSTATE_C1:
if ((uint32_t)expeted_sleep_ms < 3) {
return PWR_OK;
}
/* put CPU into C1 state, for ARM we can call WFI instruction
to put CPU into C1 state. */
PWR_DBG(DBG_INFO, "enter C1\n");
#if (PWRMGMT_CONFIG_LOG_ENTERSLEEP > 0)
if (krhino_sys_tick_get() > (last_log_entersleep + RHINO_CONFIG_TICKS_PER_SECOND)) {
last_log_entersleep = krhino_sys_tick_get();
printf("enter sleep %d ms\r\n", (uint32_t) expeted_sleep_ms);
}
#endif
sleep_ex_cg(wakeup_event, (uint32_t)expeted_sleep_ms);
PWR_DBG(DBG_INFO, "exit C1\n");
break;
default:
PWR_DBG(DBG_ERR, "invalid C state: C%d\n", cpuCState);
break;
}
return PWR_OK;
}
/**
* board_cpu_pwr_init() is called by HAL lib to
* init board powr manage configure.
*
* RUN Context: could be called from task context only, ISR context is not
* supported.
*
* SMP Consider: STM32L496G-DISCOVERY do not support SMP, so only UP is enough.
*
* @return PWR_OK or PWR_ERR when failed.
*/
pwr_status_t board_cpu_pwr_init(void)
{
cpu_pwr_t *pCpuNode = NULL;
pwr_status_t retVal = PWR_OK;
uint32_t cpuIndex = 0; /* 0 for UP */
pCpuNode = &cpu_pwr_node_core_0;
retVal = cpu_pwr_node_init_static("core", 0, pCpuNode);
if (retVal != PWR_OK) {
return PWR_ERR;
}
/* record this node */
retVal = cpu_pwr_node_record(pCpuNode, cpuIndex);
if (retVal == PWR_ERR) {
return PWR_ERR;
}
/*
* According reference manual of STM32L496G-DISCOVERY
*
* C0 - RUN, Power supplies are on,all clocks are on.
* C1 - Sleep mode, CPU clock off, all peripherals including
* Cortex®-M4 core peripherals such as NVIC, SysTick, etc. can run
* and wake up the CPU when an interrupt or an event occurs.
*/
retVal = cpu_pwr_c_method_set(cpuIndex, board_cpu_c_state_set);
if (retVal == PWR_ERR) {
return PWR_ERR;
}
/* save support C status bitset : C0,C1 */
cpu_pwr_c_state_capability_set(cpuIndex, CPU_STATE_BIT(CPU_CSTATE_C0)
| CPU_STATE_BIT(CPU_CSTATE_C1)
);
if (retVal == PWR_ERR) {
return PWR_ERR;
}
/*
* According reference manual of STM32L496G-DISCOVERY,
* the wakeup latency of Cx is:
* resume from C1 (Low Power mode) : immediate
*/
cpu_pwr_c_state_latency_save(cpuIndex, CPU_CSTATE_C0, 0);
cpu_pwr_c_state_latency_save(cpuIndex, CPU_CSTATE_C1, 0);
tickless_one_shot_timer_save(CPU_CSTATE_C1, &rtc_one_shot);
/*
Tell the CPU PWR MGMT module which C state is supported with
tickless function through tickless_c_states_add(c_state_x).
*/
tickless_c_states_add(CPU_STATE_BIT(CPU_CSTATE_C0)
| CPU_STATE_BIT(CPU_CSTATE_C1)
);
#if RHINO_CONFIG_CPU_PWR_SHOW
cpu_pwr_info_show();
cpu_pwr_state_show();
#endif
pmu_set_sysactive_time(5000);
pmu_set_sleep_type(SLEEP_CG);
pmu_release_wakelock(PMU_OS);
return retVal;
}
void cpu_pwr_resume_devices() {
}
void cpu_pwr_suspend_devices() {
}
int pwrmgmt_suspend_lowpower() {
CPSR_ALLOC();
RHINO_CRITICAL_ENTER();
pmu_acquire_wakelock(PMU_DEV_OTA);
RHINO_CRITICAL_EXIT_SCHED();
#if (WIFI_CONFIG_SUPPORT_LOWPOWER > 0)
wifi_disable_powersave();
#endif
return 1;
}
int pwrmgmt_resume_lowpower() {
CPSR_ALLOC();
RHINO_CRITICAL_ENTER();
pmu_release_wakelock(PMU_DEV_OTA);
RHINO_CRITICAL_EXIT_SCHED();
#if (WIFI_CONFIG_SUPPORT_LOWPOWER > 0)
wifi_enable_powersave();
#endif
return 1;
}
#endif /* AOS_COMP_PWRMGMT */

View file

@ -0,0 +1,77 @@
/*
* Copyright (C) 2018 Alibaba Group Holding Limited
*/
/*
* This file supplied RTC one-shot start/stop services for CPU tickless
* module, verifyied on STM32L496-DISCOVERY with C3/C4 mode.
* C3: stop mode.
* C4: standby mode.
*/
#include <k_api.h>
#if (AOS_COMP_PWRMGMT > 0)
#include <stdint.h>
#include <stdbool.h>
#include <cpu_tickless.h>
#include <rtl8710b.h>
#include <rtl8710b_delay.h>
#define TIMER_FREQ 32768
static pwr_status_t rtc_init(void);
static uint32_t rtc_one_shot_max_seconds(void);
static pwr_status_t rtc_one_shot_start(uint64_t planUs);
static pwr_status_t rtc_one_shot_stop(uint64_t *pPassedUs);
uint64_t expeted_sleep_ms = 0;
one_shot_timer_t rtc_one_shot = {
rtc_init,
rtc_one_shot_max_seconds,
rtc_one_shot_start,
rtc_one_shot_stop,
};
static uint32_t timer_counter_start = 0;
static pwr_status_t rtc_init(void)
{
SYSTIMER_Init();
return PWR_OK;
}
static pwr_status_t rtc_one_shot_start(uint64_t planUs)
{
expeted_sleep_ms = planUs / 1000;
if (expeted_sleep_ms < 3) {
return PWR_ERR;
}
timer_counter_start = SYSTIMER_TickGet();
return PWR_OK;
}
static pwr_status_t rtc_one_shot_stop(uint64_t *pPassedUs)
{
uint32_t timer_counter_end = SYSTIMER_TickGet();
if (timer_counter_end >= timer_counter_start) {
*pPassedUs = (timer_counter_end - timer_counter_start) * (uint64_t)1000000 / TIMER_FREQ;
} else {
*pPassedUs = (0xffffffff + timer_counter_end - timer_counter_start) * (uint64_t)1000000 / TIMER_FREQ;
}
return PWR_OK;
}
static uint32_t rtc_one_shot_max_seconds(void)
{
if (pmu_get_wakelock_status() == 0) {
return 0xffffffff/TIMER_FREQ;
} else {
return 0;
}
}
#endif /* AOS_COMP_PWRMGMT */

View file

@ -0,0 +1,36 @@
/*
* Copyright (C) 2018 Alibaba Group Holding Limited
*/
/*
DESCRIPTION
This file provides two fundtions systick_suspend()/systick_resume()
which is used by cpu tickless module to suspend/resume system tick
interrupt.
Differrent board may has different way to suspend/resume system tick
interrupt, please reference your board/soc user manual to find the
detail for how to implement these two functions.
*/
#include <k_api.h>
#if (AOS_COMP_PWRMGMT > 0)
#include <rtl8710b.h>
#define NVIC_SYSTICK_CTRL_REG (*((volatile uint32_t *) 0xe000e010))
void systick_suspend(void)
{
pmu_yield_os_set(0);
NVIC_SYSTICK_CTRL_REG &= ~(SysTick_CTRL_ENABLE_Msk | SysTick_CTRL_TICKINT_Msk);
}
void systick_resume(void)
{
NVIC_SYSTICK_CTRL_REG |= (SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk);
pmu_yield_os_set(1);
}
#endif /* AOS_COMP_PWRMGMT */

View file

@ -0,0 +1,76 @@
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include <hal/soc/soc.h>
#include <k_api.h>
#include "platform_peripheral.h"
#include "RingBufferUtils.h"
#include "board.h"
#include "serial_api.h"
serial_t uart_obj_t;
#define UART_TX PA_23 //UART0 TX
#define UART_RX PA_18 //UART0 RX
#define UART_FIFO_SIZE 1024
static ring_buffer_t rx_ringbuf[MICO_UART_MAX];
extern platform_uart_driver_t platform_uart_drivers[MICO_UART_MAX];
extern const platform_uart_t platform_uart_peripherals[];
int32_t hal_uart_init(uart_dev_t *uart)
{
uint8_t *rx_buf;
platform_uart_config_t config;
if (uart->port > MICO_UART_MAX)
return -1;
rx_buf = (uint8_t *)aos_malloc(UART_FIFO_SIZE);
ring_buffer_init(&rx_ringbuf[uart->port], rx_buf, UART_FIFO_SIZE);
config.baud_rate = uart->config.baud_rate;
config.data_width = uart->config.data_width;
config.parity = uart->config.parity;
config.stop_bits = uart->config.stop_bits;
config.flow_control = uart->config.flow_control;
platform_uart_init(&platform_uart_drivers[uart->port], &platform_uart_peripherals[uart->port],
&config, &rx_ringbuf[uart->port]);
return 0;
}
int32_t hal_uart_finalize(uart_dev_t *uart)
{
if (uart->port > MICO_UART_MAX)
return -1;
platform_uart_deinit(&platform_uart_drivers[uart->port]);
return 0;
}
int32_t hal_uart_send(uart_dev_t *uart, const void *data, uint32_t size, uint32_t timeout)
{
if (uart->port > MICO_UART_MAX)
return -1;
platform_uart_transmit_bytes(&platform_uart_drivers[uart->port], data, size);
return 0;
}
int32_t hal_uart_recv_II(uart_dev_t *uart, void *data, uint32_t expect_size, uint32_t *recv_size, uint32_t timeout)
{
if (uart->port > MICO_UART_MAX)
return -1;
int ret = platform_uart_receive_bytes(&platform_uart_drivers[uart->port], data, expect_size, timeout);
if(ret != 0) {
ret = -1;
}
*recv_size = expect_size;
return ret;
}

View file

@ -0,0 +1,52 @@
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include "hal/soc/soc.h"
#include "wdt_api.h"
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
static bool is_enable_handler = FALSE;
void watchdog_irq_handler(uint32_t callback_id)
{
printf("watchdog_irq_handler, callback_id: %d\n", callback_id);
sys_reset( ) ;
}
void watchdog_irq_set(void)
{
if(FALSE == is_enable_handler) {
watchdog_irq_init(watchdog_irq_handler, 0);
is_enable_handler = TRUE;
}
printf("watchdog_irq_set: is_enable_handler =%d\n", is_enable_handler);
return;
}
int32_t hal_wdg_init(wdg_dev_t *wdg)
{
uint32_t msecs = wdg->config.timeout/2;
printf("hal_wdg_init, set timeout:%d ms\n", msecs);
watchdog_init(msecs);
watchdog_irq_set();
watchdog_start();
return 0;
}
void hal_wdg_reload(wdg_dev_t *wdg)
{
watchdog_refresh();
}
int32_t hal_wdg_finalize(wdg_dev_t *wdg)
{
watchdog_stop();
return 0;
}

View file

@ -0,0 +1,891 @@
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hal/base.h>
#include <hal/wifi.h>
#include <platform/platform_stdlib.h>
#include <wifi/wifi_conf.h>
#include <wifi/wifi_util.h>
#include <wifi/wifi_ind.h>
#include <lwip_netconf.h>
#include <osdep_service.h>
#define WIFI_CONNECT_MAX_ATTEMPT_COUNT 3
extern hal_wifi_module_t rtl8710bn_wifi_module;
static rtw_wifi_setting_t alink_wifi_config;
#if CONFIG_LWIP_LAYER
extern struct netif xnetif[NET_IF_NUM];
#endif
/* This is the aligned version of ip_addr_t,
used as local variable, on the stack, etc. */
struct ip_addr {
u32_t addr;
};
/*NETMASK*/
#ifndef RTL_NETMASK_ADDR0
#define RTL_NETMASK_ADDR0 255
#define RTL_NETMASK_ADDR1 255
#define RTL_NETMASK_ADDR2 255
#define RTL_NETMASK_ADDR3 0
#endif
/*Gateway Address*/
#ifndef RTL_GW_ADDR0
#define RTL_GW_ADDR0 192
#define RTL_GW_ADDR1 168
#define RTL_GW_ADDR2 1
#define RTL_GW_ADDR3 1
#endif
/* DHCP Assigned Starting Address*/
#ifndef RTL_DHCP_START_ADDR0
#define RTL_DHCP_START_ADDR0 192
#define RTL_DHCP_START_ADDR1 168
#define RTL_DHCP_START_ADDR2 1
#define RTL_DHCP_START_ADDR3 100
#endif
/* DHCP Assigned Ending Address*/
#ifndef RTL_DHCP_END_ADDR0
#define RTL_DHCP_END_ADDR0 192
#define RTL_DHCP_END_ADDR1 168
#define RTL_DHCP_END_ADDR2 1
#define RTL_DHCP_END_ADDR3 255
#endif
void NetCallback(hal_wifi_ip_stat_t *pnet);
void WifiStatusHandler(int status);
static int wifi_init(hal_wifi_module_t *m)
{
wifi_on(RTW_MODE_STA);
#if (WIFI_CONFIG_SUPPORT_LOWPOWER > 0)
wifi_enable_powersave();
#else
wifi_disable_powersave();
#endif
DBG_8195A("wifi init success!!\n");
return 0;
};
static void wifi_get_mac_addr(hal_wifi_module_t *m, uint8_t *mac)
{
int ret = 0;
memcpy(mac, LwIP_GetMAC(&xnetif[0]), 6);
//DBG_8195A("wifi_get_mac_addr: 0x%x:0x%x:0x%x:0x%x:0x%x:0x%x, mac ptr 0x%x\r\n", mac[0], mac[1],mac[2],mac[3],mac[4],mac[5], mac);
return;
};
static void alink_set_sta_mode()
{
int mode;
//Check if in AP mode
wext_get_mode(WLAN0_NAME, &mode);
if(mode == IW_MODE_MASTER) {
#if CONFIG_LWIP_LAYER
dhcps_deinit();
#endif
wifi_off();
rtw_mdelay_os(20);
if (wifi_on(RTW_MODE_STA) < 0){
DBG_8195A("[%s]: Wifi on failed!Do zconfig reset!", __FUNCTION__);
}
wifi_disable_powersave();
}
return;
}
static int alink_find_ap_from_scan_buf(char*buf, int buflen, char *target_ssid, void *user_data)
{
rtw_wifi_setting_t *pwifi = (rtw_wifi_setting_t *)user_data;
int plen = 0;
while(plen < buflen){
u8 len, ssid_len, security_mode;
char *ssid;
// len offset = 0
len = (int)*(buf + plen);
// check end
if(len == 0) break;
// ssid offset = 14
ssid_len = len - 14;
ssid = buf + plen + 14 ;
if((ssid_len == strlen(target_ssid))
&& (!memcmp(ssid, target_ssid, ssid_len)))
{
strcpy((char*)pwifi->ssid, target_ssid);
// channel offset = 13
pwifi->channel = *(buf + plen + 13);
// security_mode offset = 11
security_mode = (u8)*(buf + plen + 11);
if(security_mode == IW_ENCODE_ALG_NONE)
pwifi->security_type = RTW_SECURITY_OPEN;
else if(security_mode == IW_ENCODE_ALG_WEP)
pwifi->security_type = RTW_SECURITY_WEP_PSK;
else if(security_mode == IW_ENCODE_ALG_CCMP)
pwifi->security_type = RTW_SECURITY_WPA2_AES_PSK;
break;
}
plen += len;
}
return 0;
}
int alink_get_ap_security_mode(char * ssid, rtw_security_t *security_mode, u8 * channel)
{
rtw_wifi_setting_t wifi;
int scan_buflen = 1000;
memset(&wifi, 0, sizeof(wifi));
if(wifi_scan_networks_with_ssid(alink_find_ap_from_scan_buf, (void*)&wifi, scan_buflen, ssid, strlen(ssid)) != RTW_SUCCESS){
DBG_8195A("[%s]: Wifi scan failed!", __FUNCTION__);
return -1;
}
if(strcmp(wifi.ssid, ssid) == 0){
*security_mode = wifi.security_type;
*channel = wifi.channel;
return 0;
}
return -1;
}
#define TRY_SCAN_MAX 8
int alink_connect_to_ap(unsigned char *ssid, unsigned char ssid_len, unsigned char *passwd, unsigned char passwd_len)
{
u8 *ifname[2] = {WLAN0_NAME,WLAN1_NAME};
rtw_wifi_setting_t setting;
rtw_network_info_t wifi_info;
memset(&wifi_info, 0 , sizeof(rtw_network_info_t));
u8 connect_retry = 3;
int ret;
u8 channel;
int try_scan_cnt = TRY_SCAN_MAX;
alink_set_sta_mode();
#if CONFIG_AUTO_RECONNECT
wifi_set_autoreconnect(RTW_AUTORECONNECT_INFINITE);
#endif
wifi_info.password_len = passwd_len;
wifi_info.ssid.len = ssid_len;
memcpy(wifi_info.ssid.val, ssid, ssid_len);
memset(wifi_info.bssid.octet, 0, sizeof(wifi_info.bssid.octet));
wifi_info.password = (unsigned char *)passwd;
while ((try_scan_cnt--) > 0) {
if(alink_get_ap_security_mode(wifi_info.ssid.val, &wifi_info.security_type, &channel) != 0)
{
channel = 0;
if (try_scan_cnt == 0) {
wifi_info.security_type = RTW_SECURITY_WPA2_AES_PSK;
alink_wifi_config.security_type = wifi_info.security_type;
DBG_8195A("Warning : unknow security type, default set to WPA2_AES\r\n");
break;
} else {
DBG_8195A("Warning: no security type detected, retry %d ...\r\n", try_scan_cnt);
continue;
}
} else {
alink_wifi_config.security_type = wifi_info.security_type;
DBG_8195A("Security type (%d) detected by scanning.\r\n", wifi_info.security_type);
break;
}
}
if (wifi_info.security_type == RTW_SECURITY_WEP_PSK) {
if(wifi_info.password_len == 10) {
u32 p[5];
u8 pwd[6], i = 0;
sscanf((const char*)wifi_info.password, "%02x%02x%02x%02x%02x", &p[0], &p[1], &p[2], &p[3], &p[4]);
for(i=0; i< 5; i++)
pwd[i] = (u8)p[i];
pwd[5] = '\0';
memset(wifi_info.password, 0, 33);
strcpy(wifi_info.password, pwd);
} else if (wifi_info.password_len == 26) {
u32 p[13];
u8 pwd[14], i = 0;
sscanf((const char*)wifi_info.password, "%02x%02x%02x%02x%02x%02x%02x"\
"%02x%02x%02x%02x%02x%02x", &p[0], &p[1], &p[2], &p[3], &p[4],\
&p[5], &p[6], &p[7], &p[8], &p[9], &p[10], &p[11], &p[12]);
for(i=0; i< 13; i++)
pwd[i] = (u8)p[i];
pwd[13] = '\0';
memset(wifi_info.password, 0, 33);
strcpy(wifi_info.password, pwd);
}
memset(alink_wifi_config.password, 0, 65);
memcpy(alink_wifi_config.password, wifi_info.password, strlen(wifi_info.password));
}
while (connect_retry) {
//DBG_8195A("\r\nwifi_connect to ssid: %s, type %d, password %s\r\n", wifi_info.ssid.val, wifi_info.security_type, wifi_info.password);
DBG_8195A("\r\nwifi_connect to ssid: %s\r\n", wifi_info.ssid.val);
ret = wifi_connect(wifi_info.ssid.val, wifi_info.security_type,
wifi_info.password, wifi_info.ssid.len,
wifi_info.password_len,
0,NULL);
if (ret == 0) {
WifiStatusHandler(NOTIFY_STATION_UP);
ret = LwIP_DHCP(0, DHCP_START);
if(DHCP_TIMEOUT == ret){
aos_reboot();
}
int i = 0;
for(i=0;i<NET_IF_NUM;i++){
if(rltk_wlan_running(i)){
wifi_get_setting((const char*)ifname[i],&setting);
}
}
// need to set again because umesh may change this.
netif_set_default(&xnetif[0]);
alink_wifi_config.channel = setting.channel;
memcpy(alink_wifi_config.ssid, ssid, ssid_len);
memcpy(alink_wifi_config.password, passwd, passwd_len);
hal_wifi_ip_stat_t stat;
u8 *ip = LwIP_GetIP(&xnetif[0]);
u8 *gw = LwIP_GetGW(&xnetif[0]);
u8 *mask = LwIP_GetMASK(&xnetif[0]);
u8 *mac = LwIP_GetMAC(&xnetif[0]);
stat.dhcp = DHCP_CLIENT;
snprintf(stat.ip, 16, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
snprintf(stat.gate, 16, "%d.%d.%d.%d", gw[0], gw[1], gw[2], gw[3]);
snprintf(stat.mask, 16, "%d.%d.%d.%d", mask[0], mask[1], mask[2], mask[3]);
snprintf(stat.dns, 16, "%d.%d.%d.%d", gw[0], gw[1], gw[2], gw[3]);
snprintf(stat.mac, 16, "%x%x%x%x%x%x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
DBG_8195A("ip %s gw %s mask %s dns %s mac %s \r\n", stat.ip, stat.gate, stat.mask, stat.dns, stat.mac);
NetCallback(&stat);
return 0;
}else{
WifiStatusHandler(NOTIFY_STATION_DOWN);
DBG_8195A("\r\nwifi connect failed, ret %d, retry %d\r\n", ret, connect_retry);
}
connect_retry --;
if (connect_retry == 0) {
return -1;
}
}
return 0;
}
void wifi_connect_task(void *arg)
{
int ret = 0;
hal_wifi_init_type_t *init_para = (hal_wifi_init_type_t*)arg;
if(init_para == NULL) {
DBG_8195A("init_para == NULL");
return;
}
//DBG_8195A("init_para->wifi_ssid =%s,init_para->wifi_key=%s\n",init_para->wifi_ssid,init_para->wifi_key);
ret = alink_connect_to_ap(init_para->wifi_ssid, strlen(init_para->wifi_ssid),
init_para->wifi_key, strlen(init_para->wifi_key));
rtw_free(init_para);
aos_task_exit(0);
}
/*return---- 0:succese, -1: fail*/
int wifi_start_softap(hal_wifi_init_type_t *init_para)
{
int timeout = 20;
#if CONFIG_LWIP_LAYER
struct ip_addr ipaddr;
struct ip_addr netmask;
struct ip_addr gw;
struct ip_addr ipaddr_pool_start;//chenwen
struct ip_addr ipaddr_pool_end;
struct netif * pnetif = &xnetif[0];
#endif
int channel = 6;
int ret = 0;
#if CONFIG_LWIP_LAYER
dhcps_deinit();
IP4_ADDR(&ipaddr, RTL_GW_ADDR0, RTL_GW_ADDR1, RTL_GW_ADDR2, RTL_GW_ADDR3);
IP4_ADDR(&netmask, RTL_NETMASK_ADDR0, RTL_NETMASK_ADDR1, RTL_NETMASK_ADDR2, RTL_NETMASK_ADDR3);
IP4_ADDR(&gw, RTL_GW_ADDR0, RTL_GW_ADDR1, RTL_GW_ADDR2, RTL_GW_ADDR3);
netif_set_addr(pnetif, &ipaddr, &netmask,&gw);
IP4_ADDR(&ipaddr_pool_start, RTL_DHCP_START_ADDR0, RTL_DHCP_START_ADDR1 , RTL_DHCP_START_ADDR2, RTL_DHCP_START_ADDR3);
IP4_ADDR(&ipaddr_pool_end, RTL_DHCP_END_ADDR0, RTL_DHCP_END_ADDR1, RTL_DHCP_END_ADDR2, RTL_DHCP_END_ADDR3);
#endif
wifi_off();
rtw_mdelay_os(20);
if (wifi_on(RTW_MODE_AP) < 0){
DBG_8195A("Wifi on failed!");
return -1;
}
// wifi_disable_powersave();//add to close powersave
if(channel > 14){
DBG_8195A("Invalid Channel,plese check!\r\n");
channel = 1;
}
#ifdef CONFIG_WPS_AP
wpas_wps_dev_config(pnetif->hwaddr, 1);
#endif
if(init_para->wifi_key) {
if(wifi_start_ap((char*)init_para->wifi_ssid,
RTW_SECURITY_WPA2_AES_PSK,
(char*)init_para->wifi_key,
strlen((const char *)init_para->wifi_ssid),
strlen((const char *)init_para->wifi_key),
channel
) != RTW_SUCCESS)
{
DBG_8195A("wifi start ap mode failed!\n\r");
return -1;
}
} else {
if(wifi_start_ap((char*)init_para->wifi_ssid,
RTW_SECURITY_OPEN,
NULL,
strlen((const char *)init_para->wifi_ssid),
0,
channel
) != RTW_SUCCESS)
{
DBG_8195A("wifi start ap mode failed!\n\r");
return -1;
}
}
while(1) {
char essid[33];
if(wext_get_ssid(WLAN0_NAME, (unsigned char *) essid) > 0) {
if(strcmp((const char *) essid, (const char *)init_para->wifi_ssid) == 0) {
DBG_8195A("%s started\n", init_para->wifi_ssid);
ret = 0;
break;
}
}
if(timeout == 0) {
DBG_8195A("Start AP timeout!\n\r");
ret = -1;
break;
}
rtw_mdelay_os(1 * configTICK_RATE_HZ);
timeout --;
}
#if CONFIG_LWIP_LAYER
//LwIP_UseStaticIP(pnetif);
dhcps_set_addr_pool(1, &ipaddr_pool_start, &ipaddr_pool_end);//Set the IP address of the DHCP allocation starting range
dhcps_init(pnetif);
#endif
return ret;
}
static int wifi_start(hal_wifi_module_t *m, hal_wifi_init_type_t *init_para)
{
DBG_8195A("wifi_start ssid %s\r\n", init_para->wifi_ssid);
if (NULL == m || NULL == init_para) {
DBG_8195A("wifi_start: invalid parameter\n");
return -1;
}
/*Disable promisc mode completely*/
wifi_off();
rtw_mdelay_os(20);
wifi_on(RTW_MODE_STA);
#if (WIFI_CONFIG_SUPPORT_LOWPOWER > 0)
wifi_enable_powersave();
#else
wifi_disable_powersave();
#endif
hal_wifi_init_type_t * init_para_ptr = rtw_malloc(sizeof(hal_wifi_init_type_t));
if (init_para_ptr == NULL) {
DBG_8195A("wifi_start: fail to alloc init para\n");
return -1;
}
strcpy(init_para_ptr->wifi_ssid, init_para->wifi_ssid);
strcpy(init_para_ptr->wifi_key, init_para->wifi_key);
DBG_8195A("wifi_ssid =%s, wifi_mode %d\n",
init_para_ptr->wifi_ssid, init_para_ptr->wifi_mode);
if(init_para->wifi_mode == STATION) {
DBG_8195A("wifi_mode == STATION \n");
aos_task_new("wifi_connect", wifi_connect_task, init_para_ptr, 4096);
} else if (init_para->wifi_mode == SOFT_AP){
DBG_8195A("wifi_mode == SOFT_AP \n");
if(wifi_start_softap(init_para_ptr) == 0) {
m->ev_cb->stat_chg(m, NOTIFY_AP_UP, NULL);
}else {
//m->ev_cb->stat_chg(m, NOTIFY_AP_UP_FAILED, NULL);
}
rtw_free(init_para_ptr);
}
return 0;
}
static int wifi_start_adv(hal_wifi_module_t *m, hal_wifi_init_type_adv_t *init_para_adv)
{
DBG_8195A("wifi_start adv\r\n");
return 0;
}
static int get_ip_stat(hal_wifi_module_t *m, hal_wifi_ip_stat_t *out_net_para, hal_wifi_type_t wifi_type)
{
DBG_8195A("get_ip_stat\r\n");
return 0;
}
static int get_link_stat(hal_wifi_module_t *m, hal_wifi_link_stat_t *out_stat)
{
DBG_8195A("get_link_stat\r\n");
u8 *ifname[2] = {WLAN0_NAME,WLAN1_NAME};
rtw_wifi_setting_t setting;
int rssi;
wifi_get_setting((const char*)ifname[0],&setting);
wifi_show_setting((const char*)ifname[0],&setting);
out_stat->is_connected = wifi_is_ready_to_transceive(RTW_STA_INTERFACE)?0:1;
wifi_get_rssi(&rssi);
out_stat->wifi_strength = rssi;
strcpy(out_stat->ssid, setting.ssid);
out_stat->channel = setting.channel;
return 0;
}
static void start_scan(hal_wifi_module_t *m)
{
DBG_8195A("start_scan\r\n");
fATWS(NULL);
DBG_8195A("start_scan done\r\n");
return;
}
static void start_scan_adv(hal_wifi_module_t *m)
{
DBG_8195A("start_scan_adv, %d\r\n", rtw_getFreeHeapSize());
fATWS(NULL);
return;
}
static int power_off(hal_wifi_module_t *m)
{
wifi_off();
return 0;
}
static int power_on(hal_wifi_module_t *m)
{
wifi_on(RTW_MODE_STA);
wifi_disable_powersave();
return 0;
}
static int suspend(hal_wifi_module_t *m)
{
return 0;
}
static int suspend_station(hal_wifi_module_t *m)
{
return 0;
}
static int suspend_soft_ap(hal_wifi_module_t *m)
{
wifi_off();
m->ev_cb->stat_chg(m, NOTIFY_AP_DOWN, NULL);
return 0;
}
static int set_channel(hal_wifi_module_t *m, int ch)
{
//printf("set chanel to %d\r\n", ch);
wifi_set_channel(ch);
return 0;
}
static int get_channel(hal_wifi_module_t *m)
{
int ch = 0;
wifi_get_channel(&ch);
//printf("get_channel to %d\r\n", ch);
return ch;
}
monitor_data_cb_t g_monitor_cb = NULL;
monitor_data_cb_t g_monitor_cb_handler = NULL;
void monitor_rx_handle(unsigned char* data, unsigned int len, void *info)
{
hal_wifi_link_info_t link_info;
link_info.rssi = ((ieee80211_frame_info_t *)info)->rssi;
if (g_monitor_cb_handler) {
g_monitor_cb_handler(data, len, &link_info);
}
}
static void start_monitor(hal_wifi_module_t *m)
{
DBG_8195A("start_monitor\r\n");
#if CONFIG_AUTO_RECONNECT
wifi_set_autoreconnect(RTW_AUTORECONNECT_DISABLE);
#endif
g_monitor_cb_handler = g_monitor_cb;
wifi_enter_promisc_mode();
return;
}
void wifi_stop_monitor_task(void *arg)
{
DBG_8195A("stop_monitor task create\r\n");
wifi_set_promisc(RTW_PROMISC_DISABLE, NULL, 0);
#if CONFIG_AUTO_RECONNECT
wifi_set_autoreconnect(RTW_AUTORECONNECT_INFINITE);
#endif
pmu_release_wakelock(0);
#if (WIFI_CONFIG_SUPPORT_LOWPOWER > 0)
wifi_enable_powersave();
#endif
aos_task_exit(0);
}
static void stop_monitor(hal_wifi_module_t *m)
{
DBG_8195A("stop_monitor\r\n");
aos_task_new("wifi_connect", wifi_stop_monitor_task, NULL, 1024);
g_monitor_cb_handler = NULL;
return;
}
void start_softap_thread(void *arg)
{
hal_wifi_init_type_t *init = (hal_wifi_init_type_t *)arg;
struct netif *pnetif = &xnetif[0];
rtw_security_t security;
ip4_addr_t ipaddr;
ip4_addr_t netmask;
ip4_addr_t gw;
if (strlen(init->wifi_key) == 0)
security = RTW_SECURITY_OPEN;
else
security = RTW_SECURITY_WPA2_AES_PSK;
dhcps_deinit();
ip4addr_aton(init->local_ip_addr, &ipaddr);
ip4addr_aton(init->net_mask, &netmask);
ip4addr_aton(init->gateway_ip_addr, &gw);
netif_set_addr(pnetif, &ipaddr, &netmask, &gw);
printf("Restarting Wi-Fi ...\r\n");
wifi_off();
aos_msleep(20);
if (wifi_on(RTW_MODE_AP) < 0) {
printf("ERROR: Restart Wi-Fi failed!\r\n");
goto exit;
}
printf("Starting AP ...\r\n");
if (wifi_start_ap(init->wifi_ssid, security, init->wifi_key, strlen(init->wifi_ssid), strlen(init->wifi_key), 6) < 0) {
printf("ERROR: Start AP failed!\r\n");
goto exit;
}
dhcps_init(pnetif);
printf("Start AP Success!\r\n");
exit:
rtw_free(init);
}
static int start_ap(hal_wifi_module_t *m, const char *ssid, const char *passwd, int interval, int hide)
{
DBG_8195A("start_ap: %s(%s) \r\n", ssid, passwd);
hal_wifi_init_type_t* aws_ap_info = rtw_malloc(sizeof(hal_wifi_init_type_t));
memset( aws_ap_info, 0x00, sizeof(hal_wifi_init_type_t) );
strcpy(aws_ap_info->wifi_ssid, ssid);
strcpy(aws_ap_info->wifi_key, passwd);
aws_ap_info->dhcp_mode = DHCP_SERVER;
strcpy( aws_ap_info->local_ip_addr, "10.10.100.1" );
strcpy( aws_ap_info->net_mask, "255.255.255.0" );
strcpy( aws_ap_info->gateway_ip_addr, "10.10.100.1" );
strcpy( aws_ap_info->dns_server_ip_addr, "10.10.100.1" );
aos_task_new("softap thread", start_softap_thread, aws_ap_info, 4096);
return 0;
}
static int stop_ap(hal_wifi_module_t *m)
{
DBG_8195A("stop_ap");
wifi_off();
aos_msleep(100);
wifi_on(RTW_MODE_STA);
m->ev_cb->stat_chg(m, NOTIFY_AP_DOWN, NULL);
return 0;
}
static void register_monitor_cb(hal_wifi_module_t *m, monitor_data_cb_t fn)
{
if(fn == NULL) {
return;
}
pmu_acquire_wakelock(0);
wifi_off();
rtw_mdelay_os(20);
wifi_on(RTW_MODE_PROMISC);
wifi_disable_powersave();
g_monitor_cb = fn;
DBG_8195A("register_monitor_cb\r\n");
wifi_set_promisc(RTW_PROMISC_ENABLE_2, monitor_rx_handle, 0);
return;
}
extern int (*p_wlan_mgmt_filter)(u8 *ie, u16 ie_len, u16 frame_type);
monitor_data_cb_t g_mgnt_filter_callback = NULL;
monitor_data_cb_t g_umesh_callback = NULL;
hal_wifi_link_info_t g_mgnt_link_info;
static void wifi_rx_mgnt_hdl(u8 *buf, int buf_len, int flags, void *userdata)
{
g_mgnt_link_info.rssi = (int8_t)flags;
if(g_umesh_callback){
g_umesh_callback((u8*)buf, buf_len+4, &g_mgnt_link_info);
}
/* only deal with Probe Request*/
if(g_mgnt_filter_callback && buf[0] == 0x40)
g_mgnt_filter_callback((u8*)buf, buf_len, &g_mgnt_link_info);
}
static void register_wlan_mgnt_monitor_cb(hal_wifi_module_t *m, monitor_data_cb_t fn)
{
//DBG_8195A("register_wlan_mgnt_monitor_cb fn 0x%x\r\n", fn);
#if (WIFI_CONFIG_SUPPORT_LOWPOWER > 0)
if (fn != NULL) {
wifi_disable_powersave();
}
#endif
g_mgnt_link_info.rssi = 0;
g_mgnt_filter_callback = fn;
if (fn == NULL) {
wifi_set_indicate_mgnt(0);
} else {
wifi_set_indicate_mgnt(1);
}
wifi_reg_event_handler(WIFI_EVENT_RX_MGNT, wifi_rx_mgnt_hdl, NULL);
#if (WIFI_CONFIG_SUPPORT_LOWPOWER > 0)
if (fn == NULL) {
wifi_enable_powersave();
}
#endif
return;
}
static int wlan_send_80211_raw_frame(hal_wifi_module_t *m, uint8_t *buf, int len)
{
int ret = 0;
const char *ifname = WLAN0_NAME;
len = len - 4; /* remove fcs */
ret = wext_send_mgnt(ifname, (char*)buf, len, 1);
return 0;
}
void NetCallback(hal_wifi_ip_stat_t *pnet)
{
hal_wifi_ap_info_adv_t info = {0};
if (rtl8710bn_wifi_module.ev_cb == NULL)
return;
if (rtl8710bn_wifi_module.ev_cb->ip_got == NULL)
return;
rtl8710bn_wifi_module.ev_cb->ip_got(&rtl8710bn_wifi_module, pnet, NULL);
if (rtl8710bn_wifi_module.ev_cb->para_chg == NULL)
return;
if (wext_get_bssid("wlan0", info.bssid) != 0) {
DBG_8195A("%s get bssid failed\r\n", __func__);
return;
}
rtl8710bn_wifi_module.ev_cb->para_chg(&rtl8710bn_wifi_module, &info, NULL, 0, NULL);
}
void connected_ap_info(hal_wifi_ap_info_adv_t *ap_info, char *key, int key_len)
{
if (rtl8710bn_wifi_module.ev_cb == NULL)
return;
if (rtl8710bn_wifi_module.ev_cb->para_chg == NULL)
return;
rtl8710bn_wifi_module.ev_cb->para_chg(&rtl8710bn_wifi_module, ap_info, key, key_len, NULL);
}
void WifiStatusHandler(int status)
{
if (rtl8710bn_wifi_module.ev_cb == NULL)
return;
if (rtl8710bn_wifi_module.ev_cb->stat_chg == NULL)
return;
rtl8710bn_wifi_module.ev_cb->stat_chg(&rtl8710bn_wifi_module, (hal_wifi_event_t)status, NULL);
}
void ApListCallback(hal_wifi_scan_result_t *pApList)
{
int i;
DBG_8195A("AP %d: \r\n", pApList->ap_num);
for(i=0; i<pApList->ap_num; i++) {
DBG_8195A("\t %s rssi %d\r\n", pApList->ap_list[i].ssid, pApList->ap_list[i].ap_power);
}
if (rtl8710bn_wifi_module.ev_cb == NULL)
return;
if (rtl8710bn_wifi_module.ev_cb->scan_compeleted == NULL)
return;
rtl8710bn_wifi_module.ev_cb->scan_compeleted(&rtl8710bn_wifi_module,
(hal_wifi_scan_result_t*)pApList, NULL);
}
void ApListAdvCallback(hal_wifi_scan_result_adv_t *pApAdvList)
{
if (rtl8710bn_wifi_module.ev_cb == NULL)
return;
if (rtl8710bn_wifi_module.ev_cb->scan_adv_compeleted == NULL)
return;
rtl8710bn_wifi_module.ev_cb->scan_adv_compeleted(&rtl8710bn_wifi_module,
pApAdvList, NULL);
}
static int mesh_enable(hal_wifi_module_t *module)
{
return 0;
}
static int mesh_disable(hal_wifi_module_t *module)
{
return 0;
}
static void register_mesh_cb(hal_wifi_module_t *m, monitor_data_cb_t fn)
{
DBG_8195A("register_mesh_cb fn 0x%x\r\n", fn);
g_umesh_callback = fn;
wifi_set_indicate_mgnt(1);
wifi_reg_event_handler(WIFI_EVENT_RX_MGNT, wifi_rx_mgnt_hdl, NULL);
return;
}
#if (WIFI_CONFIG_SUPPORT_LOWPOWER > 0)
static int set_listeninterval(hal_wifi_module_t *m, uint8_t listen_interval)
{
int status = -1;
status = wifi_set_lps_dtim(listen_interval);
printf("set listern interval %d, status %d\n", (uint32_t) listen_interval, status);
return 0;
}
static int enter_powersave(hal_wifi_module_t *m, uint8_t recvDTIMs)
{
printf("enter_powersave\n");
wifi_enable_powersave();
return 0;
}
static int exit_powersave(hal_wifi_module_t *m)
{
wifi_disable_powersave();
return 0;
}
#endif
hal_wifi_module_t rtl8710bn_wifi_module = {
.base.name = "rtl8710bn_wifi_module",
.init = wifi_init,
.get_mac_addr = wifi_get_mac_addr,
.start = wifi_start,
.start_adv = wifi_start_adv,
.get_ip_stat = get_ip_stat,
.get_link_stat = get_link_stat,
.start_scan = start_scan,
.start_scan_adv = start_scan_adv,
.power_off = power_off,
.power_on = power_on,
.suspend = suspend,
.suspend_station = suspend_station,
.suspend_soft_ap = suspend_soft_ap,
.set_channel = set_channel,
.get_channel = get_channel,
.start_monitor = start_monitor,
.stop_monitor = stop_monitor,
.start_ap = start_ap,
.stop_ap = stop_ap,
.register_monitor_cb = register_monitor_cb,
.register_wlan_mgnt_monitor_cb = register_wlan_mgnt_monitor_cb,
.wlan_send_80211_raw_frame = wlan_send_80211_raw_frame,
/* mesh related */
.mesh_register_cb = register_mesh_cb,
.mesh_enable = mesh_enable,
.mesh_disable = mesh_disable,
#if (WIFI_CONFIG_SUPPORT_LOWPOWER > 0)
.set_listeninterval = set_listeninterval,
.enter_powersave = enter_powersave,
.exit_powersave = exit_powersave,
#endif
};

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,92 @@
/**
******************************************************************************
* @file RingBufferUtils.c
* @author William Xu
* @version V1.0.0
* @date 05-May-2014
* @brief This file contains function called by ring buffer operation
******************************************************************************
* @attention
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, MXCHIP Inc. SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>&copy; COPYRIGHT 2014 MXCHIP Inc.</center></h2>
******************************************************************************
*/
#include "RingBufferUtils.h"
#include "debug.h"
#define ring_buffer_utils_log(M, ...) custom_log("RingBufferUtils", M, ##__VA_ARGS__)
#define ring_buffer_utils_log_trace() custom_log_trace("RingBufferUtils")
OSStatus ring_buffer_init( ring_buffer_t* ring_buffer, uint8_t* buffer, uint32_t size )
{
ring_buffer->buffer = (uint8_t*)buffer;
ring_buffer->size = size;
ring_buffer->head = 0;
ring_buffer->tail = 0;
return kNoErr;
}
OSStatus ring_buffer_deinit( ring_buffer_t* ring_buffer )
{
UNUSED_PARAMETER(ring_buffer);
return kNoErr;
}
uint32_t ring_buffer_free_space( ring_buffer_t* ring_buffer )
{
uint32_t tail_to_end = ring_buffer->size - ring_buffer->tail;
return ((tail_to_end + ring_buffer->head) % ring_buffer->size);
}
uint32_t ring_buffer_used_space( ring_buffer_t* ring_buffer )
{
uint32_t head_to_end = ring_buffer->size - ring_buffer->head;
return ((head_to_end + ring_buffer->tail) % ring_buffer->size);
}
uint8_t ring_buffer_get_data( ring_buffer_t* ring_buffer, uint8_t** data, uint32_t* contiguous_bytes )
{
uint32_t head_to_end = ring_buffer->size - ring_buffer->head;
*data = &(ring_buffer->buffer[ring_buffer->head]);
*contiguous_bytes = MIN(head_to_end, (head_to_end + ring_buffer->tail) % ring_buffer->size);
return 0;
}
uint8_t ring_buffer_consume( ring_buffer_t* ring_buffer, uint32_t bytes_consumed )
{
ring_buffer->head = (ring_buffer->head + bytes_consumed) % ring_buffer->size;
return 0;
}
uint32_t ring_buffer_write( ring_buffer_t* ring_buffer, const uint8_t* data, uint32_t data_length )
{
uint32_t tail_to_end = ring_buffer->size - ring_buffer->tail;
/* Calculate the maximum amount we can copy */
uint32_t amount_to_copy = MIN(data_length, (ring_buffer->tail == ring_buffer->head) ? ring_buffer->size : (tail_to_end + ring_buffer->head) % ring_buffer->size);
/* Copy as much as we can until we fall off the end of the buffer */
memcpy(&ring_buffer->buffer[ring_buffer->tail], data, MIN(amount_to_copy, tail_to_end));
/* Check if we have more to copy to the front of the buffer */
if (tail_to_end < amount_to_copy)
{
memcpy(ring_buffer->buffer, data + tail_to_end, amount_to_copy - tail_to_end);
}
/* Update the tail */
ring_buffer->tail = (ring_buffer->tail + amount_to_copy) % ring_buffer->size;
return amount_to_copy;
}

View file

@ -0,0 +1,56 @@
/**
******************************************************************************
* @file RingBufferUtils.h
* @author William Xu
* @version V1.0.0
* @date 05-May-2014
* @brief This header contains function prototypes called by ring buffer
* operation
******************************************************************************
* @attention
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, MXCHIP Inc. SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>&copy; COPYRIGHT 2014 MXCHIP Inc.</center></h2>
******************************************************************************
*/
#ifndef __RingBufferUtils_h__
#define __RingBufferUtils_h__
#include "common.h"
typedef struct
{
uint32_t size;
uint32_t head;
uint32_t tail;
uint8_t* buffer;
} ring_buffer_t;
#ifndef MIN
#define MIN(x,y) ((x) < (y) ? (x) : (y))
#endif /* ifndef MIN */
OSStatus ring_buffer_init( ring_buffer_t* ring_buffer, uint8_t* buffer, uint32_t size );
OSStatus ring_buffer_deinit( ring_buffer_t* ring_buffer );
uint32_t ring_buffer_free_space( ring_buffer_t* ring_buffer );
uint32_t ring_buffer_used_space( ring_buffer_t* ring_buffer );
uint8_t ring_buffer_get_data( ring_buffer_t* ring_buffer, uint8_t** data, uint32_t* contiguous_bytes );
uint8_t ring_buffer_consume( ring_buffer_t* ring_buffer, uint32_t bytes_consumed );
uint32_t ring_buffer_write( ring_buffer_t* ring_buffer, const uint8_t* data, uint32_t data_length );
#endif // __RingBufferUtils_h__

View file

@ -0,0 +1,60 @@
#
# UNPUBLISHED PROPRIETARY SOURCE CODE
# Copyright (c) 2016 MXCHIP Inc.
#
# The contents of this file may not be disclosed to third parties, copied or
# duplicated in any form, in whole or in part, without the prior written
# permission of MXCHIP Corporation.
#
NAME = rtl8710bn_Peripheral_Drivers
$(NAME)_INCLUDES += peripherals
$(NAME)_INCLUDES += ../../include
$(NAME)_INCLUDES += ../sdk/component/os/os_dep/include
$(NAME)_INCLUDES += ../sdk/component/soc/realtek/8711b/app/monitor/include
$(NAME)_INCLUDES += ../sdk/component/soc/realtek/8711b/cmsis
$(NAME)_INCLUDES += ../sdk/component/soc/realtek/8711b/cmsis/device
$(NAME)_INCLUDES += ../sdk/component/soc/realtek/8711b/fwlib
$(NAME)_INCLUDES += ../sdk/component/soc/realtek/8711b/fwlib/include
$(NAME)_INCLUDES += ../sdk/component/soc/realtek/8711b/fwlib/ram_lib/crypto
$(NAME)_INCLUDES += ../sdk/component/soc/realtek/8711b/fwlib/rom_lib
$(NAME)_INCLUDES += ../sdk/component/soc/realtek/8711b/swlib/os_dep/include
$(NAME)_INCLUDES += ../sdk/component/soc/realtek/8711b/swlib/std_lib/include
$(NAME)_INCLUDES += ../sdk/component/soc/realtek/8711b/swlib/std_lib/libc/include
$(NAME)_INCLUDES += ../sdk/component/soc/realtek/8711b/swlib/std_lib/libc/rom/string
$(NAME)_INCLUDES += ../sdk/component/soc/realtek/8711b/swlib/std_lib/libgcc/rtl8195a/include
$(NAME)_INCLUDES += ../sdk/component/soc/realtek/8711b/swlib/rtl_lib
$(NAME)_INCLUDES += ../sdk/component/soc/realtek/8711b/misc
$(NAME)_INCLUDES += ../sdk/component/soc/realtek/8711b/misc/os
$(NAME)_INCLUDES += ../sdk/component/common/mbed/api
$(NAME)_INCLUDES += ../sdk/component/common/mbed/hal
$(NAME)_INCLUDES += ../sdk/component/common/mbed/hal_ext
$(NAME)_INCLUDES += ../sdk/component/common/mbed/targets/cmsis/rtl8711b
$(NAME)_INCLUDES += ../sdk/component/common/mbed/targets/hal/rtl8711b
$(NAME)_INCLUDES += ../sdk/project/realtek_amebaz_va0_example/inc
#GLOBAL_INCLUDES := .
#GLOBAL_INCLUDES += ..\..\mcu/include
#$(NAME)_INCLUDES += .
#$(NAME)_INCLUDES += .
#$(NAME)_INCLUDES += ../../include
#$(NAME)_INCLUDES += ../../../../include/hal/soc
#$(NAME)_INCLUDES += ../../../../include/aos
#$(NAME)_INCLUDES += ../../../../kernel/vcall/mico/include
#$(NAME)_INCLUDES += ../../../../framework/protocol/alink/os/platform
#$(NAME)_INCLUDES += platform\mcu\rtl8710bn\peripherals\include
$(NAME)_SOURCES := platform_8711.c \
platform_adc.c \
platform_rtc.c \
platform_gpio.c \
platform_i2c.c \
platform_rng.c \
platform_mcu_powersave.c \
platform_pwm.c \
platform_spi.c \
platform_uart.c \
platform_watchdog.c \
RingBufferUtils.c

View file

@ -0,0 +1,462 @@
/**
******************************************************************************
* @file platform.c
* @author William Xu
* @version V1.0.0
* @date 05-May-2014
* @brief This file provides all MICO Peripherals mapping table and platform
* specific funcgtions.
******************************************************************************
*
* 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 "stdio.h"
//#include "string.h"
//#include "platform.h"
//#include "platform_config.h"
#include "platform_peripheral.h"
#include "platform_logging.h"
//#include "MicoPlatform.h"
//#include "wlan_platform_common.h"
/******************************************************
* Macros
******************************************************/
/******************************************************
* Constants
******************************************************/
/******************************************************
* Enumerations
******************************************************/
/******************************************************
* Type Definitions
******************************************************/
/******************************************************
* Structures
******************************************************/
/******************************************************
* Function Declarations
******************************************************/
extern WEAK void PlatformEasyLinkButtonClickedCallback(void);
extern WEAK void PlatformStandbyButtonClickedCallback(void);
extern WEAK void PlatformEasyLinkButtonLongPressedCallback(void);
extern WEAK void bootloader_start(void);
/******************************************************
* Variables Definitions
******************************************************/
/* This table maps STM32 pins to GPIO definitions on the schematic
* A full pin definition is provided in <WICED-SDK>/include/platforms/BCM943362WCD4/platform.h
*/
static uint32_t _default_start_time = 0;
static mico_timer_t _button_EL_timer;
platform_gpio_t platform_gpio_pins[] =
{
/* Common GPIOs for internal use */
// [MICO_SYS_LED] = { GPIOB, 0 },
// [MICO_RF_LED] = { GPIOB, 1 }, //MICO_GPIO_16
// [BOOT_SEL] = { GPIOB, 1 }, //MICO_GPIO_16
// [MFG_SEL] = { GPIOB, 9 }, //MICO_GPIO_30
// [EasyLink_BUTTON] = { GPIOA, 1 }, //MICO_GPIO_11
/* GPIOs for external use */
[MICO_GPIO_1] =
{
.pin = PA_5,
},
[MICO_GPIO_2] =
{
.pin = PA_12,
},
};
/*
* Possible compile time inputs:
* - Set which ADC peripheral to use for each ADC. All on one ADC allows sequential conversion on all inputs. All on separate ADCs allows concurrent conversion.
*/
/* TODO : These need fixing */
platform_adc_t platform_adc_peripherals[] =
{
[MICO_ADC_1] =
{
.pin = AD_1,
},
[MICO_ADC_2] =
{
.pin = AD_2,
},
[MICO_ADC_3] =
{
.pin = AD_3,
},
};
/* PWM mappings */
platform_pwm_t platform_pwm_peripherals[] =
{
[MICO_PWM_1] =
{
.pin = PA_23,
},
[MICO_PWM_2] =
{
.pin = PA_22,
},
[MICO_PWM_3] =
{
.pin = PA_0,
},
[MICO_PWM_4] =
{
.pin = PA_12,
},
/* TODO: fill in the other options here ... */
};
platform_spi_t platform_spi_peripherals[] =
{
[MICO_SPI_1] =
{
.mosi = PA_4,
.miso = PA_3,
.sclk = PA_1,
.ssel = PA_2,
},
[MICO_SPI_2] =
{
.mosi = PA_23,
.miso = PA_22,
.sclk = PA_18,
.ssel = PA_19,
},
[MICO_SPI_3] =
{
.mosi = PB_3,
.miso = PB_2,
.sclk = PB_1,
.ssel = PB_0,
},
};
platform_uart_t platform_uart_peripherals[] =
{
[MICO_UART_1] =
{
.tx = PA_30,
.rx = PA_29,
},
[MICO_UART_2] =
{
.tx = PA_23,
.rx = PA_18,
},
[MICO_UART_2] =
{
.tx = PA_30,
.rx = PA_29,
},
};
platform_uart_driver_t platform_uart_drivers[MICO_UART_MAX];
platform_i2c_t platform_i2c_peripherals[] =
{
[MICO_I2C_1] =
{
.sda = PA_23,
.scl = PA_18,
},
[MICO_I2C_2] =
{
.sda = PA_19,
.scl = PA_22,
},
};
#if 0
/* Flash memory devices */
platform_flash_t platform_flash_peripherals[] =
{
[MICO_FLASH_SPI] =
{
//.flash_type = FLASH_TYPE_SPI,
.flash_start_addr = 0x00000000,
.flash_length = 0x100000,
},
};
platform_flash_driver_t platform_flash_drivers[MICO_FLASH_MAX];
/* Logic partition on flash devices */
const mico_logic_partition_t mico_partitions[] =
{
[MICO_PARTITION_BOOTLOADER] =
{
.partition_owner = MICO_FLASH_SPI,
.partition_description = "Bootloader",
.partition_start_addr = 0x00000000,
.partition_length = 0x4000, //16k bytes
.partition_options = PAR_OPT_READ_EN | PAR_OPT_WRITE_DIS,
},
[MICO_PARTITION_APPLICATION] =
{
.partition_owner = MICO_FLASH_SPI,
.partition_description = "Application",
.partition_start_addr = 0x000C0000,
.partition_length = 0x54000, //336k bytes
.partition_options = PAR_OPT_READ_EN | PAR_OPT_WRITE_EN,
},
[MICO_PARTITION_RF_FIRMWARE] =
{
.partition_owner = MICO_FLASH_SPI,
.partition_description = "RF Firmware",
.partition_start_addr = 0x000C0000,
.partition_length = 0x40000, //256k bytes
.partition_options = PAR_OPT_READ_EN | PAR_OPT_WRITE_DIS,
},
[MICO_PARTITION_OTA_TEMP] =
{
.partition_owner = MICO_FLASH_SPI,
.partition_description = "OTA Storage",
.partition_start_addr = 0x000C0000,
.partition_length = 0x60000, //384k bytes
.partition_options = PAR_OPT_READ_EN | PAR_OPT_WRITE_EN,
},
[MICO_PARTITION_PARAMETER_1] =
{
.partition_owner = MICO_FLASH_SPI,
.partition_description = "PARAMETER1",
.partition_start_addr = 0x000C0000,
.partition_length = 0x4000, // 16k bytes
.partition_options = PAR_OPT_READ_EN | PAR_OPT_WRITE_EN,
},
[MICO_PARTITION_PARAMETER_2] =
{
.partition_owner = MICO_FLASH_SPI,
.partition_description = "PARAMETER1",
.partition_start_addr = 0x000C0000,
.partition_length = 0x4000, //16k bytes
.partition_options = PAR_OPT_READ_EN | PAR_OPT_WRITE_EN,
},
[MICO_PARTITION_ATE] =
{
.partition_owner = MICO_FLASH_NONE,
}
};
#endif
/******************************************************
* Interrupt Handler Definitions
******************************************************/
#if 0
MICO_RTOS_DEFINE_ISR( USART1_IRQHandler )
{
platform_uart_irq( &platform_uart_drivers[MICO_UART_1] );
}
MICO_RTOS_DEFINE_ISR( USART6_IRQHandler )
{
platform_uart_irq( &platform_uart_drivers[MICO_UART_2] );
}
MICO_RTOS_DEFINE_ISR( DMA2_Stream7_IRQHandler )
{
platform_uart_tx_dma_irq( &platform_uart_drivers[MICO_UART_1] );
}
MICO_RTOS_DEFINE_ISR( DMA2_Stream6_IRQHandler )
{
platform_uart_tx_dma_irq( &platform_uart_drivers[MICO_UART_2] );
}
MICO_RTOS_DEFINE_ISR( DMA2_Stream2_IRQHandler )
{
platform_uart_rx_dma_irq( &platform_uart_drivers[MICO_UART_1] );
}
MICO_RTOS_DEFINE_ISR( DMA2_Stream1_IRQHandler )
{
platform_uart_rx_dma_irq( &platform_uart_drivers[MICO_UART_2] );
}
#endif
/******************************************************
* Function Definitions
******************************************************/
#if 0
static void _button_EL_irq_handler( void* arg )
{
(void)(arg);
int interval = -1;
if ( MicoGpioInputGet( (mico_gpio_t)EasyLink_BUTTON ) == 0 ) {
_default_start_time = mico_get_time()+1;
mico_start_timer(&_button_EL_timer);
} else {
interval = mico_get_time() + 1 - _default_start_time;
if ( (_default_start_time != 0) && interval > 50 && interval < RestoreDefault_TimeOut){
/* EasyLink button clicked once */
PlatformEasyLinkButtonClickedCallback();
}
mico_stop_timer(&_button_EL_timer);
_default_start_time = 0;
}
}
static void _button_STANDBY_irq_handler( void* arg )
{
(void)(arg);
PlatformStandbyButtonClickedCallback();
}
static void _button_EL_Timeout_handler( void* arg )
{
(void)(arg);
_default_start_time = 0;
PlatformEasyLinkButtonLongPressedCallback();
}
#endif
bool watchdog_check_last_reset( void )
{
#if 0
if ( RCC->CSR & RCC_CSR_WDGRSTF )
{
/* Clear the flag and return */
RCC->CSR |= RCC_CSR_RMVF;
return true;
}
#endif
return false;
}
void platform_init_peripheral_irq_priorities( void )
{
#if 0
/* Interrupt priority setup. Called by WICED/platform/MCU/STM32F2xx/platform_init.c */
NVIC_SetPriority( RTC_WKUP_IRQn , 1 ); /* RTC Wake-up event */
NVIC_SetPriority( SDIO_IRQn , 2 ); /* WLAN SDIO */
NVIC_SetPriority( DMA2_Stream3_IRQn, 3 ); /* WLAN SDIO DMA */
NVIC_SetPriority( DMA1_Stream3_IRQn, 3 ); /* WLAN SPI DMA */
NVIC_SetPriority( USART1_IRQn , 6 ); /* MICO_UART_1 */
NVIC_SetPriority( USART6_IRQn , 6 ); /* MICO_UART_2 */
NVIC_SetPriority( DMA2_Stream7_IRQn, 7 ); /* MICO_UART_1 TX DMA */
NVIC_SetPriority( DMA2_Stream2_IRQn, 7 ); /* MICO_UART_1 RX DMA */
NVIC_SetPriority( DMA2_Stream6_IRQn, 7 ); /* MICO_UART_2 TX DMA */
NVIC_SetPriority( DMA2_Stream1_IRQn, 7 ); /* MICO_UART_2 RX DMA */
NVIC_SetPriority( EXTI0_IRQn , 14 ); /* GPIO */
NVIC_SetPriority( EXTI1_IRQn , 14 ); /* GPIO */
NVIC_SetPriority( EXTI2_IRQn , 14 ); /* GPIO */
NVIC_SetPriority( EXTI3_IRQn , 14 ); /* GPIO */
NVIC_SetPriority( EXTI4_IRQn , 14 ); /* GPIO */
NVIC_SetPriority( EXTI9_5_IRQn , 14 ); /* GPIO */
NVIC_SetPriority( EXTI15_10_IRQn , 14 ); /* GPIO */
#endif
}
void init_platform( void )
{
#if 0
MicoGpioInitialize( (mico_gpio_t)MICO_SYS_LED, OUTPUT_PUSH_PULL );
MicoGpioOutputLow( (mico_gpio_t)MICO_SYS_LED );
MicoGpioInitialize( (mico_gpio_t)MICO_RF_LED, OUTPUT_OPEN_DRAIN_NO_PULL );
MicoGpioOutputHigh( (mico_gpio_t)MICO_RF_LED );
// Initialise EasyLink buttons
MicoGpioInitialize( (mico_gpio_t)EasyLink_BUTTON, INPUT_PULL_UP );
mico_init_timer(&_button_EL_timer, RestoreDefault_TimeOut, _button_EL_Timeout_handler, NULL);
MicoGpioEnableIRQ( (mico_gpio_t)EasyLink_BUTTON, IRQ_TRIGGER_BOTH_EDGES, _button_EL_irq_handler, NULL );
// Initialise Standby/wakeup switcher
MicoGpioInitialize( Standby_SEL, INPUT_PULL_UP );
MicoGpioEnableIRQ( Standby_SEL , IRQ_TRIGGER_FALLING_EDGE, _button_STANDBY_irq_handler, NULL);
#endif
}
void init_platform_bootloader( void )
{
#if 0
MicoGpioInitialize( (mico_gpio_t)MICO_SYS_LED, OUTPUT_PUSH_PULL );
MicoGpioOutputLow( (mico_gpio_t)MICO_SYS_LED );
MicoGpioInitialize( (mico_gpio_t)MICO_RF_LED, OUTPUT_OPEN_DRAIN_NO_PULL );
MicoGpioOutputHigh( (mico_gpio_t)MICO_RF_LED );
MicoGpioInitialize((mico_gpio_t)BOOT_SEL, INPUT_PULL_UP);
MicoGpioInitialize((mico_gpio_t)MFG_SEL, INPUT_HIGH_IMPEDANCE);
#endif
}
void MicoSysLed(bool onoff)
{
#if 0
if (onoff) {
MicoGpioOutputHigh( (mico_gpio_t)MICO_SYS_LED );
} else {
MicoGpioOutputLow( (mico_gpio_t)MICO_SYS_LED );
}
#endif
}
void MicoRfLed(bool onoff)
{
#if 0
if (onoff) {
MicoGpioOutputLow( (mico_gpio_t)MICO_RF_LED );
} else {
MicoGpioOutputHigh( (mico_gpio_t)MICO_RF_LED );
}
#endif
}
#if 0
bool MicoShouldEnterMFGMode(void)
{
if(MicoGpioInputGet((mico_gpio_t)BOOT_SEL)==false && MicoGpioInputGet((mico_gpio_t)MFG_SEL)==false)
return true;
else
return false;
}
bool MicoShouldEnterBootloader(void)
{
if(MicoGpioInputGet((mico_gpio_t)BOOT_SEL)==false && MicoGpioInputGet((mico_gpio_t)MFG_SEL)==true)
return true;
else
return false;
}
#endif

View file

@ -0,0 +1,121 @@
/**
******************************************************************************
* @file paltform_adc.c
* @author William Xu
* @version V1.0.0
* @date 05-May-2014
* @brief This file provide ADC 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 "MICOPlatform.h"
//#include "MICORTOS.h"
//#include "platform.h"
#include "platform_peripheral.h"
#include "platform_logging.h"
#include "analogin_api.h"
/******************************************************
* Constants
******************************************************/
/******************************************************
* Enumerations
******************************************************/
/******************************************************
* Type Definitions
******************************************************/
/******************************************************
* Structures
******************************************************/
/******************************************************
* Variables Definitions
******************************************************/
/******************************************************
* Function Declarations
******************************************************/
/******************************************************
* Function Definitions
******************************************************/
OSStatus platform_adc_init( const platform_adc_t* adc, uint32_t sample_cycle )
{
OSStatus err = kNoErr;
platform_mcu_powersave_disable();
require_action_quiet( adc != NULL, exit, err = kParamErr);
analogin_init((analogin_t *)&adc->adc_obj, adc->pin);
exit:
platform_mcu_powersave_enable();
return err;
}
OSStatus platform_adc_take_sample( const platform_adc_t* adc, uint16_t* output )
{
OSStatus err = kNoErr;
platform_mcu_powersave_disable();
require_action_quiet( adc != NULL, exit, err = kParamErr);
*output = analogin_read_u16((analogin_t *)&adc->adc_obj);
exit:
platform_mcu_powersave_enable();
return err;
}
OSStatus platform_adc_take_sample_stream( const platform_adc_t* adc, void* buffer, uint16_t buffer_length )
{
UNUSED_PARAMETER(adc);
UNUSED_PARAMETER(buffer);
UNUSED_PARAMETER(buffer_length);
platform_log("unimplemented");
return kNotPreparedErr;
}
OSStatus platform_adc_deinit( const platform_adc_t* adc )
{
OSStatus err = kNoErr;
require_action_quiet( adc != NULL, exit, err = kParamErr);
analogin_deinit((analogin_t *)&adc->adc_obj);
exit:
return err;
}

View file

@ -0,0 +1,259 @@
/**
******************************************************************************
* @file platform_flash.c
* @author William Xu
* @version V1.0.0
* @date 05-May-2014
* @brief This file provides flash operation 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.
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
//#include "MICOPlatform.h"
//#include "MICORTOS.h"
#include "platform_logging.h"
//#include "MicoPlatform.h"
#include "board.h"
#include "platform_config.h"
#include "platform_peripheral.h"
//#include "PlatformLogging.h"
#include "stdio.h"
#include "device_lock.h"
#ifdef USE_MICO_SPI_FLASH
//#include "spi_flash.h"
//#include "hal_platform.h"
//#include "hal_spi_flash.h"
//#include "rtl8195a_spi_flash.h"
#endif
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
#ifdef USE_MICO_SPI_FLASH
//static sflash_handle_t sflash_handle = {0x0, 0x0, SFLASH_WRITE_NOT_ALLOWED};
#endif
/* Private function prototypes -----------------------------------------------*/
OSStatus platform_flash_init( const platform_flash_t *peripheral )
{
OSStatus err = kNoErr;
require_action_quiet( peripheral != NULL, exit, err = kParamErr);
if( peripheral->flash_type == FLASH_TYPE_EMBEDDED ){
err = kUnsupportedErr;
require_noerr(err, exit);
}
else{
err = kNoErr;
goto exit;
}
exit:
return err;
}
OSStatus platform_flash_erase( const platform_flash_t *peripheral, uint32_t start_address, uint32_t end_address )
{
OSStatus err = kNoErr;
int section_start, section_num, section_end, section_ro_start, ro_section_num, start_sector;
int i =0;
require_action_quiet( end_address > start_address, exit, err = kParamErr);
require_action_quiet( peripheral != NULL, exit, err = kParamErr);
require_action( start_address >= peripheral->flash_start_addr
&& end_address <= peripheral->flash_start_addr + peripheral->flash_length - 1, exit, err = kParamErr);
section_ro_start = peripheral->flash_readonly_start/0x1000;
ro_section_num = peripheral->flash_readonly_len/0x1000;
if( peripheral->flash_type == FLASH_TYPE_EMBEDDED ){
err = kUnsupportedErr;
require_noerr(err, exit);
}
#ifdef USE_MICO_SPI_FLASH
else if( peripheral->flash_type == FLASH_TYPE_SPI ){
device_mutex_lock(RT_DEV_LOCK_FLASH);
start_sector = start_address/0x1000;
section_start = start_sector*0x1000;
section_end = (end_address+0x1000-1)/0x1000*0x1000;
section_num = (section_end - section_start)/0x1000;
section_ro_start = section_ro_start - start_sector;
for(i =0; i < section_num; i++){
if (i == section_ro_start) {// read only section don't write
i += ro_section_num;
i--;
continue;
}
flash_erase_sector((flash_t *)&peripheral->flash_obj, section_start + i*0x1000);
}
device_mutex_unlock(RT_DEV_LOCK_FLASH);
}
#endif
else{
err = kTypeErr;
goto exit;
}
exit:
return err;
}
OSStatus platform_flash_write( const platform_flash_t *peripheral, volatile uint32_t* start_address, uint8_t* data ,uint32_t length )
{
OSStatus err = kNoErr;
uint32_t ro_start, ro_end;
uint32_t start = *start_address, end=*start_address + length;
uint32_t write_len;
u8 *sram_data = malloc(length);
memcpy(sram_data, data, length);
ro_start = peripheral->flash_readonly_start;
ro_end = peripheral->flash_readonly_len + ro_start;
require_action_quiet( peripheral != NULL, exit, err = kParamErr);
require_action( *start_address >= peripheral->flash_start_addr
&& *start_address + length <= peripheral->flash_start_addr + peripheral->flash_length, exit, err = kParamErr);
if( peripheral->flash_type == FLASH_TYPE_EMBEDDED ){
err = kUnsupportedErr;
require_noerr(err, exit);
}
#ifdef USE_MICO_SPI_FLASH
else if( peripheral->flash_type == FLASH_TYPE_SPI ){
device_mutex_lock(RT_DEV_LOCK_FLASH);
if ((start > ro_end) || (end < ro_start)) {
flash_stream_write((flash_t *)&peripheral->flash_obj, start, length, sram_data);
} else {
if (start < ro_start) {
write_len = ro_start - start;
flash_stream_write((flash_t *)&peripheral->flash_obj, start, write_len, sram_data);
}
if (ro_end < end) {// start is in ro_start~ro_end
write_len = ro_end - start;
sram_data += write_len;
flash_stream_write((flash_t *)&peripheral->flash_obj, ro_end, length - write_len, sram_data);
}
}
device_mutex_unlock(RT_DEV_LOCK_FLASH);
*start_address += length;
}
#endif
else{
err = kTypeErr;
goto exit;
}
free(sram_data);
exit:
return err;
}
OSStatus platform_flash_read( const platform_flash_t *peripheral, volatile uint32_t* start_address, uint8_t* data ,uint32_t length )
{
OSStatus err = kNoErr;
u8 *sram_data = malloc(length);
require_action_quiet( peripheral != NULL, exit, err = kParamErr);
require_action( (*start_address >= peripheral->flash_start_addr)
&& (*start_address + length) <= ( peripheral->flash_start_addr + peripheral->flash_length), exit, err = kParamErr);
if( peripheral->flash_type == FLASH_TYPE_EMBEDDED ){
err = kUnsupportedErr;
require_noerr(err, exit);
}
#ifdef USE_MICO_SPI_FLASH
else if( peripheral->flash_type == FLASH_TYPE_SPI ){
device_mutex_lock(RT_DEV_LOCK_FLASH);
flash_stream_read((flash_t*)&peripheral->flash_obj, (*start_address), length, sram_data);
memcpy(data, sram_data, length);
device_mutex_unlock(RT_DEV_LOCK_FLASH);
*start_address += length;
}
#endif
else{
err = kTypeErr;
goto exit;
}
free(sram_data);
exit:
return err;
}
OSStatus platform_flash_enable_protect( const platform_flash_t *peripheral, uint32_t start_address, uint32_t end_address )
{
OSStatus err = kNoErr;
require_action_quiet( peripheral != NULL, exit, err = kParamErr);
require_action( start_address >= peripheral->flash_start_addr
&& end_address <= peripheral->flash_start_addr + peripheral->flash_length - 1, exit, err = kParamErr);
if( peripheral->flash_type == FLASH_TYPE_EMBEDDED ){
err = kUnsupportedErr;
require_noerr(err, exit);
}
#ifdef USE_MICO_SPI_FLASH
else if( peripheral->flash_type == FLASH_TYPE_SPI ){
err = kNoErr;
goto exit;
}
#endif
else{
err = kTypeErr;
goto exit;
}
exit:
return err;
}
OSStatus platform_flash_disable_protect( const platform_flash_t *peripheral, uint32_t start_address, uint32_t end_address )
{
OSStatus err = kNoErr;
require_action_quiet( peripheral != NULL, exit, err = kParamErr);
require_action( start_address >= peripheral->flash_start_addr
&& end_address <= peripheral->flash_start_addr + peripheral->flash_length - 1, exit, err = kParamErr);
if( peripheral->flash_type == FLASH_TYPE_EMBEDDED ){
err = kUnsupportedErr;
require_noerr(err, exit);
}
#ifdef USE_MICO_SPI_FLASH
else if( peripheral->flash_type == FLASH_TYPE_SPI ){
err = kNoErr;
goto exit;
}
#endif
else{
err = kTypeErr;
goto exit;
}
exit:
return err;
}

View file

@ -0,0 +1,267 @@
/**
******************************************************************************
* @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 "mico_platform.h"
#include "mico_rtos.h"
#include "board.h"
#include "platform_peripheral.h"
#include "platform_logging.h"
#include "gpio_irq_api.h"
/******************************************************
* Constants
******************************************************/
/******************************************************
* Enumerations
******************************************************/
/******************************************************
* Type Definitions
******************************************************/
/******************************************************
* Structures
******************************************************/
/******************************************************
* Variables Definitions
******************************************************/
/******************************************************
* Function Declarations
******************************************************/
/******************************************************
* Function Definitions
******************************************************/
OSStatus platform_gpio_init( const platform_gpio_t* gpio, platform_pin_config_t config )
{
OSStatus err = kNoErr;
platform_mcu_powersave_disable();
require_action_quiet( gpio != NULL, exit, err = kParamErr);
gpio_init((gpio_t *)&gpio->gpio_obj, gpio->pin);
switch(config){
case INPUT_PULL_UP:
gpio_dir((gpio_t *)&gpio->gpio_obj, PIN_INPUT); // Direction: Input
gpio_mode((gpio_t *)&gpio->gpio_obj, PullUp); // Pull-High
break;
case INPUT_PULL_DOWN:
gpio_dir((gpio_t *)&gpio->gpio_obj, PIN_INPUT); // Direction: Input
gpio_mode((gpio_t *)&gpio->gpio_obj, PullDown); // Pull-Down
break;
case INPUT_HIGH_IMPEDANCE:
gpio_dir((gpio_t *)&gpio->gpio_obj, PIN_INPUT); // Direction: Input
gpio_mode((gpio_t *)&gpio->gpio_obj, PullNone); // Pull-None
break;
case OUTPUT_PUSH_PULL:
gpio_dir((gpio_t *)&gpio->gpio_obj, PIN_OUTPUT); // Direction: Input
gpio_mode((gpio_t *)&gpio->gpio_obj, PullUp); // Pull-None
break;
case OUTPUT_OPEN_DRAIN_NO_PULL:
case OUTPUT_OPEN_DRAIN_PULL_UP:
gpio_dir((gpio_t *)&gpio->gpio_obj, PIN_OUTPUT); // Direction: Input
gpio_mode((gpio_t *)&gpio->gpio_obj, PullDown); // Pull-None
break;
}
exit:
platform_mcu_powersave_enable();
return err;
}
OSStatus platform_gpio_deinit( const platform_gpio_t* gpio )
{
OSStatus err = kNoErr;
platform_mcu_powersave_disable();
require_action_quiet( gpio != NULL, exit, err = kParamErr);
gpio_deinit((gpio_t *)&gpio->gpio_obj);
exit:
platform_mcu_powersave_enable();
return err;
}
#if 0
OSStatus platform_gpio_ip_deinit(void)
{
OSStatus err = kNoErr;
platform_mcu_powersave_disable();
HAL_GPIO_IP_DeInit();
exit:
platform_mcu_powersave_enable();
return err;
}
#endif
OSStatus platform_gpio_output_high( const platform_gpio_t* gpio )
{
OSStatus err = kNoErr;
platform_mcu_powersave_disable();
require_action_quiet( gpio != NULL, exit, err = kParamErr);
gpio_write((gpio_t *)&gpio->gpio_obj, 1);
exit:
platform_mcu_powersave_enable();
return err;
}
OSStatus platform_gpio_output_low( const platform_gpio_t* gpio )
{
OSStatus err = kNoErr;
platform_mcu_powersave_disable();
require_action_quiet( gpio != NULL, exit, err = kParamErr);
gpio_write((gpio_t *)&gpio->gpio_obj, 0);
exit:
platform_mcu_powersave_enable();
return err;
}
OSStatus platform_gpio_output_trigger( const platform_gpio_t* gpio )
{
OSStatus err = kNoErr;
platform_mcu_powersave_disable();
require_action_quiet( gpio != NULL, exit, err = kParamErr);
gpio_write((gpio_t *)&gpio->gpio_obj, !gpio_read((gpio_t *)&gpio->gpio_obj));
exit:
platform_mcu_powersave_enable();
return err;
}
bool platform_gpio_input_get( const platform_gpio_t* gpio )
{
bool result = false;
platform_mcu_powersave_disable();
require_quiet( gpio != NULL, exit);
if(gpio_read((gpio_t *)&gpio->gpio_obj)){
result = true;
}else{
result = false;
}
exit:
platform_mcu_powersave_enable();
return result;
}
OSStatus platform_gpio_irq_enable( const platform_gpio_t* gpio, platform_gpio_irq_trigger_t trigger, platform_gpio_irq_callback_t handler, void* arg )
{
OSStatus err = kNoErr;
platform_mcu_powersave_disable();
require_action_quiet( gpio != NULL, exit, err = kParamErr);
gpio_irq_init((gpio_irq_t *)&gpio->gpio_irq_obj, gpio->pin, handler, (uint32_t)(arg));
switch ( trigger )
{
case IRQ_TRIGGER_RISING_EDGE:
gpio_irq_set((gpio_irq_t *)&gpio->gpio_irq_obj, IRQ_RISE, 1); // Rising Edge Trigger
gpio_irq_enable((gpio_irq_t *)&gpio->gpio_irq_obj);
break;
case IRQ_TRIGGER_FALLING_EDGE:
gpio_irq_set((gpio_irq_t *)&gpio->gpio_irq_obj, IRQ_FALL, 1); // Falling Edge Trigger
gpio_irq_enable((gpio_irq_t *)&gpio->gpio_irq_obj);
break;
case IRQ_TRIGGER_BOTH_EDGES:
err = kUnsupportedErr;
goto exit;
break;
default:
err = kParamErr;
goto exit;
}
exit:
platform_mcu_powersave_enable();
return err;
}
OSStatus platform_gpio_irq_disable( const platform_gpio_t* gpio )
{
OSStatus err = kNoErr;
platform_mcu_powersave_disable();
require_action_quiet( gpio != NULL, exit, err = kParamErr);
gpio_irq_deinit((gpio_irq_t *)&gpio->gpio_irq_obj);
exit:
platform_mcu_powersave_enable();
return err;
}
/******************************************************
* STM32F2xx Internal Function Definitions
******************************************************/
/******************************************************
* IRQ Handler Definitions
******************************************************/
/* Common IRQ handler for all GPIOs */
/******************************************************
* IRQ Handler Mapping
******************************************************/

View file

@ -0,0 +1,207 @@
/**
******************************************************************************
* @file paltform_i2c.c
* @author William Xu
* @version V1.0.0
* @date 05-May-2014
* @brief This file provide I2C 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 "MICORTOS.h"
//#include "MICOPlatform.h"
#include "board.h"
#include "platform_peripheral.h"
#include "platform_logging.h"
#include "pinmap.h"
/******************************************************
* Constants
******************************************************/
//#define I2C_USE_DMA
#define I2C_Direction_Transmitter ((uint8_t)0x00)
#define I2C_Direction_Receiver ((uint8_t)0x01)
#define IS_I2C_DIRECTION(DIRECTION) (((DIRECTION) == I2C_Direction_Transmitter) || \
((DIRECTION) == I2C_Direction_Receiver))
/******************************************************
* Enumerations
******************************************************/
/******************************************************
* Type Definitions
******************************************************/
/******************************************************
* Structures
******************************************************/
/******************************************************
* Variables Definitions
******************************************************/
/******************************************************
* Function Declarations
******************************************************/
OSStatus platform_i2c_init( const platform_i2c_t* i2c, const platform_i2c_config_t* config )
{
OSStatus err = kNoErr;
int hz = 100000;
platform_mcu_powersave_disable( );
require_action_quiet( i2c != NULL, exit, err = kParamErr);
if(config->address_width == I2C_ADDRESS_WIDTH_10BIT || config->address_width == I2C_ADDRESS_WIDTH_16BIT)
{
err = kUnsupportedErr;
goto exit;
}
switch ( config->speed_mode )
{
case I2C_LOW_SPEED_MODE:
platform_log("Speed mode is not supported");
err = kUnsupportedErr;
goto exit;
break;
case I2C_STANDARD_SPEED_MODE:
hz = 100000;
break;
case I2C_HIGH_SPEED_MODE:
hz = 500000;
break;
default:
platform_log("Speed mode is not supported");
err = kUnsupportedErr;
goto exit;
break;
}
i2c_init((i2c_t *)&i2c->i2c_obj, i2c->sda, i2c->scl);
i2c_frequency((i2c_t *)&i2c->i2c_obj, hz);
exit:
platform_mcu_powersave_enable( );
return err;
}
bool platform_i2c_probe_device( const platform_i2c_t* i2c, const platform_i2c_config_t* config, int retries )
{
OSStatus err = kNoErr;
platform_mcu_powersave_disable();
require_action_quiet( i2c != NULL, exit, err = kParamErr);
exit:
platform_mcu_powersave_enable();
return ( err == kNoErr) ? true : false;
}
OSStatus platform_i2c_init_tx_message( platform_i2c_message_t* message, const void* tx_buffer, uint16_t tx_buffer_length, uint16_t retries )
{
OSStatus err = kNoErr;
require_action_quiet( ( message != NULL ) && ( tx_buffer != NULL ) && ( tx_buffer_length != 0 ), exit, err = kParamErr);
memset(message, 0x00, sizeof(platform_i2c_message_t));
message->tx_buffer = tx_buffer;
message->retries = retries;
message->tx_length = tx_buffer_length;
exit:
return err;
}
OSStatus platform_i2c_init_rx_message( platform_i2c_message_t* message, void* rx_buffer, uint16_t rx_buffer_length, uint16_t retries )
{
OSStatus err = kNoErr;
require_action_quiet( ( message != NULL ) && ( rx_buffer != NULL ) && ( rx_buffer_length != 0 ), exit, err = kParamErr);
memset(message, 0x00, sizeof(platform_i2c_message_t));
message->rx_buffer = rx_buffer;
message->retries = retries;
message->rx_length = rx_buffer_length;
exit:
return err;
}
OSStatus platform_i2c_init_combined_message( platform_i2c_message_t* message, const void* tx_buffer, void* rx_buffer, uint16_t tx_buffer_length, uint16_t rx_buffer_length, uint16_t retries )
{
OSStatus err = kNoErr;
require_action_quiet( ( message != NULL ) && ( tx_buffer != NULL ) && ( tx_buffer_length != 0 ) && ( rx_buffer != NULL ) && ( rx_buffer_length != 0 ), exit, err = kParamErr);
memset(message, 0x00, sizeof(platform_i2c_message_t));
message->rx_buffer = rx_buffer;
message->tx_buffer = tx_buffer;
message->retries = retries;
message->tx_length = tx_buffer_length;
message->rx_length = rx_buffer_length;
exit:
return err;
}
OSStatus platform_i2c_transfer( const platform_i2c_t* i2c, const platform_i2c_config_t* config, platform_i2c_message_t* messages, uint16_t number_of_messages )
{
OSStatus err = kNoErr;
int i = 0;
platform_mcu_powersave_disable();
require_action_quiet( i2c != NULL, exit, err = kParamErr);
for( i=0; i < number_of_messages; i++ )
{
if((&messages[i])->tx_buffer != NULL)
i2c_write((i2c_t *)&i2c->i2c_obj, (int)config->address, (char *)(&messages[i])->tx_buffer, (&messages[i])->tx_length, 1);
if((&messages[i])->rx_buffer != NULL)
i2c_read((i2c_t *)&i2c->i2c_obj, (int)config->address, (char *)(&messages[i])->rx_buffer, (&messages[i])->rx_length, 1);
}
exit:
platform_mcu_powersave_enable();
return err;
}
OSStatus platform_i2c_deinit( const platform_i2c_t* i2c, const platform_i2c_config_t* config )
{
UNUSED_PARAMETER( config );
OSStatus err = kNoErr;
platform_mcu_powersave_disable();
require_action_quiet( i2c != NULL, exit, err = kParamErr);
exit:
platform_mcu_powersave_enable();
return err;
}

View file

@ -0,0 +1,272 @@
/**
******************************************************************************
* @file platform_mcu_peripheral.h
* @author William Xu
* @version V1.0.0
* @date 05-May-2014
* @brief This file provide all the headers of functions for stm32f2xx platform
******************************************************************************
*
* 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.
******************************************************************************
*/
#pragma once
//#include "rtl8195a.h"
#include "PinNames.h"
#include "objects.h"
#include "mico_rtos.h"
#include "RingBufferUtils.h"
#include "serial_api.h"
#include "i2c_api.h"
#include "pwmout_api.h"
#include "spi_api.h"
#include "aos/aos.h"
//#include "platform_peripheral.h"
#ifdef __cplusplus
extern "C"
{
#endif
/******************************************************
* Macros
******************************************************/
/******************************************************
* Constants
******************************************************/
/* GPIO port */
#if 1
//#define NO_MICO_RTOS
/* GPIOA to I */
#define NUMBER_OF_GPIO_PORTS (8)
/* Interrupt line 0 to 15. Each line is shared among the same numbered pins across all GPIO ports */
#define NUMBER_OF_GPIO_IRQ_LINES (16)
/* USART1 to 6 */
#define NUMBER_OF_UART_PORTS (6)
/* Invalid UART port number */
#define INVALID_UART_PORT_NUMBER (0xff)
/* SPI1 to SPI3 */
#define NUMBER_OF_SPI_PORTS (3)
/******************************************************
* Enumerations
******************************************************/
/******************************************************
* Type Definitions
******************************************************/
/* GPIO port */
//typedef GPIO_TypeDef platform_gpio_port_t;
/* UART port */
//typedef USART_TypeDef platform_uart_port_t;
/* SPI port */
//typedef SPI_TypeDef platform_spi_port_t;
/* I2C port */
//typedef I2C_TypeDef platform_i2c_port_t;
/* GPIO alternate function */
//typedef uint8_t platform_gpio_alternate_function_t;
/* Peripheral clock function */
//typedef void (*platform_peripheral_clock_function_t)(uint32_t clock, FunctionalState state );
//typedef DMA_TypeDef dma_registers_t;
//typedef FunctionalState functional_state_t;
//typedef uint32_t peripheral_clock_t;
#if 0
typedef enum
{
FLASH_TYPE_EMBEDDED,
FLASH_TYPE_SPI,
} platform_flash_type_t;
#endif
/******************************************************
* Structures
******************************************************/
//typedef struct gtimer_s gtimer_t;
typedef struct
{
// DMA_TypeDef* controller;
// DMA_Stream_TypeDef* stream;
uint32_t channel;
// IRQn_Type irq_vector;
uint32_t complete_flags;
uint32_t error_flags;
} platform_dma_config_t;
typedef struct
{
PinName pin;
gpio_t gpio_obj;
gpio_irq_t gpio_irq_obj;
} platform_gpio_t;
typedef struct analogin_s analogin_t;
typedef struct
{
analogin_t adc_obj;
PinName pin;
} platform_adc_t;
typedef struct
{
pwmout_t pwm_obj;
PinName pin;
} platform_pwm_t;
/* DMA can be enabled by setting SPI_USE_DMA */
typedef struct
{
spi_t spi_obj;
PinName mosi;
PinName miso;
PinName sclk;
PinName ssel;
} platform_spi_t;
typedef struct
{
platform_spi_t* peripheral;
mico_mutex_t spi_mutex;
} platform_spi_driver_t;
typedef struct
{
uint8_t unimplemented;
} platform_spi_slave_driver_t;
typedef struct
{
i2c_t i2c_obj;
PinName sda;
PinName scl;
} platform_i2c_t;
typedef void (* wakeup_irq_handler_t)(void *arg);
typedef struct
{
serial_t serial_obj;
PinName tx;
PinName rx;
} platform_uart_t;
typedef struct
{
platform_uart_t* peripheral;
ring_buffer_t* rx_buffer;
#ifndef NO_MICO_RTOS
//mico_semaphore_t rx_complete;
//mico_semaphore_t tx_complete;
//mico_mutex_t tx_mutex;
//mico_semaphore_t sem_wakeup;
aos_sem_t rx_complete;
aos_sem_t tx_complete;
aos_mutex_t tx_mutex;
aos_sem_t sem_wakeup;
#else
volatile bool rx_complete;
volatile bool tx_complete;
#endif
volatile uint32_t tx_size;
volatile uint32_t rx_size;
volatile OSStatus last_receive_result;
volatile OSStatus last_transmit_result;
} platform_uart_driver_t;
#if 1
typedef struct flash_s flash_t;
typedef struct
{
//platform_flash_type_t flash_type;
flash_t flash_obj;
uint32_t flash_start_addr;
uint32_t flash_length;
uint32_t flash_protect_opt;
uint32_t flash_readonly_start; // can't erase and write
uint32_t flash_readonly_len;
} platform_flash_t;
typedef struct
{
//const platform_flash_t* peripheral;
mico_mutex_t flash_mutex;
volatile bool initialized;
} platform_flash_driver_t;
#endif
/******************************************************
* Global Variables
******************************************************/
/******************************************************
* Function Declarations
******************************************************/
OSStatus platform_gpio_irq_manager_init ( void );
//uint8_t platform_gpio_get_port_number ( platform_gpio_port_t* gpio_port );
OSStatus platform_gpio_enable_clock ( const platform_gpio_t* gpio );
//OSStatus platform_gpio_set_alternate_function( platform_gpio_port_t* gpio_port, uint8_t pin_number, GPIOOType_TypeDef output_type, GPIOPuPd_TypeDef pull_up_down_type, uint8_t alternation_function );
OSStatus platform_mcu_powersave_init ( void );
OSStatus platform_rtc_init ( void );
OSStatus platform_rtc_enter_powersave ( void );
OSStatus platform_rtc_abort_powersave ( void );
OSStatus platform_rtc_exit_powersave ( uint32_t requested_sleep_time, uint32_t *cpu_sleep_time );
//uint8_t platform_uart_get_port_number ( platform_uart_port_t* uart );
void platform_uart_irq ( uint32_t id, SerialIrq event );
void platform_loguart_irq ( void* id);
void platform_uart_tx_dma_irq ( uint32_t id );
void platform_uart_rx_dma_irq ( uint32_t id );
//uint8_t platform_spi_get_port_number ( platform_spi_port_t* spi );
#endif
#ifdef __cplusplus
} /* extern "C" */
#endif

View file

@ -0,0 +1,201 @@
/**
******************************************************************************
* @file platform_mcu_peripheral.c
* @author William Xu
* @version V1.0.0
* @date 05-May-2014
* @brief This file provide functions called by MICO to drive stm32f2xx
* platform: - e.g. power save, reboot, platform initialize
******************************************************************************
*
* 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 "platform_peripheral.h"
#include "board.h"
//#include "mico_platform.h"
#include <string.h> // For memcmp
//#include "crt0.h"
//#include "mico_rtos.h"
#include "platform_init.h"
#include "debug.h"
#include "sleep_ex_api.h"
/******************************************************
* Macros
******************************************************/
/******************************************************
* Constants
******************************************************/
/******************************************************
* Enumerations
******************************************************/
/******************************************************
* Type Definitions
******************************************************/
/******************************************************
* Structures
******************************************************/
/******************************************************
* Function Declarations
******************************************************/
#ifndef MICO_DISABLE_MCU_POWERSAVE
static unsigned long stop_mode_power_down_hook( unsigned long sleep_ms );
#else
static unsigned long idle_power_down_hook( unsigned long sleep_ms );
#endif
/******************************************************
* Variables Definitions
******************************************************/
#ifndef MICO_DISABLE_MCU_POWERSAVE
static bool wake_up_interrupt_triggered = false;
static volatile uint32_t rtk_clock_needed_counter = 0;
#endif /* #ifndef MICO_DISABLE_MCU_POWERSAVE */
/******************************************************
* Function Definitions
******************************************************/
OSStatus platform_mcu_powersave_init(void)
{
return kNoErr;
}
OSStatus platform_mcu_powersave_disable( void )
{
#ifndef MICO_DISABLE_MCU_POWERSAVE
/* Atomic operation starts */
//DISABLE_INTERRUPTS;
//pmu_acquire_wakelock(PMU_OS);
/* Atomic operation ends */
//ENABLE_INTERRUPTS;
return kNoErr;
#else
return kNoErr;
#endif
return kNoErr;
}
OSStatus platform_mcu_powersave_enable( void )
{
#ifndef MICO_DISABLE_MCU_POWERSAVE
/* Atomic operation starts */
//DISABLE_INTERRUPTS;
//pmu_release_wakelock(PMU_OS);
/* Atomic operation ends */
//ENABLE_INTERRUPTS;
return kNoErr;
#else
return kNoErr;
#endif
return kNoErr;
}
void platform_mcu_powersave_exit_notify( void )
{
#if 0
#ifndef MICO_DISABLE_MCU_POWERSAVE
wake_up_interrupt_triggered = true;
#endif
#endif
}
/******************************************************
* RTOS Powersave Hooks
******************************************************/
void platform_idle_hook( void )
{
//ENABLE_INTERRUPTS;
//__asm("wfi");
}
uint32_t platform_power_down_hook( uint32_t sleep_ms )
{
#ifdef MICO_DISABLE_MCU_POWERSAVE
/* If MCU powersave feature is disabled, enter idle mode when powerdown hook is called by the RTOS */
return idle_power_down_hook( sleep_ms );
#else
/* If MCU powersave feature is enabled, enter STOP mode when powerdown hook is called by the RTOS */
return stop_mode_power_down_hook( sleep_ms );
#endif
return 0;
}
#ifdef MICO_DISABLE_MCU_POWERSAVE
/* MCU Powersave is disabled */
static unsigned long idle_power_down_hook( unsigned long sleep_ms )
{
UNUSED_PARAMETER( sleep_ms );
//ENABLE_INTERRUPTS;
//__asm("wfi");
return 0;
}
#else
static unsigned long stop_mode_power_down_hook( unsigned long sleep_ms )
{
UNUSED_PARAMETER(sleep_ms);
if (rtk_clock_needed_counter == 0 )
{
//DISABLE_INTERRUPTS;
sleep_ex(0xFFFFFFFF, sleep_ms);
/* as soon as interrupts are enabled, we will go and execute the interrupt handler */
/* which triggered a wake up event */
//ENABLE_INTERRUPTS;
wake_up_interrupt_triggered = false;
return 0;
}
else
{
//ENABLE_INTERRUPTS;
__asm("wfi");
/* Note: We return 0 ticks passed because system tick is still going when wfi instruction gets executed */
return 0;
}
}
#endif /* MICO_DISABLE_MCU_POWERSAVE */

View file

@ -0,0 +1,129 @@
/**
******************************************************************************
* @file paltform_pwm.c
* @author William Xu
* @version V1.0.0
* @date 05-May-2014
* @brief This file provide PWM 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 "MICORTOS.h"
//#include "MICOPlatform.h"
#include "board.h"
#include "platform_peripheral.h"
#include "platform_logging.h"
#include "pinmap.h"
/******************************************************
* Constants
******************************************************/
/******************************************************
* Enumerations
******************************************************/
/******************************************************
* Type Definitions
******************************************************/
/******************************************************
* Structures
******************************************************/
/******************************************************
* Variables Definitions
******************************************************/
/******************************************************
* Function Declarations
******************************************************/
/******************************************************
* Function Definitions
******************************************************/
OSStatus platform_pwm_init( const platform_pwm_t* pwm, uint32_t frequency, float duty_cycle )
{
OSStatus err = kNoErr;
u32 period = (uint32_t)((float)1000000.0/frequency);
float value;
require_action_quiet( pwm != NULL, exit, err = kParamErr);
platform_mcu_powersave_disable();
if (duty_cycle < (float)0.0) {
value = 0.0;
}else if (duty_cycle > (float)100.0) {
value = 1.0;
}else{
value = duty_cycle/100;
}
pwmout_init((pwmout_t*)&pwm->pwm_obj, pwm->pin);
printf("pwm init period %d, duty_cycle %7.5f\r\n", period, value);
pwmout_period_us((pwmout_t*)&pwm->pwm_obj, period);
pwmout_write((pwmout_t*)&pwm->pwm_obj, value);
exit:
platform_mcu_powersave_enable();
return err;
}
OSStatus platform_pwm_start( const platform_pwm_t* pwm )
{
OSStatus err = kNoErr;
platform_mcu_powersave_disable();
require_action_quiet( pwm != NULL, exit, err = kParamErr);
pwmout_start((pwmout_t*)&pwm->pwm_obj);
exit:
platform_mcu_powersave_enable();
return err;
}
OSStatus platform_pwm_stop( const platform_pwm_t* pwm )
{
OSStatus err = kNoErr;
platform_mcu_powersave_disable();
require_action_quiet( pwm != NULL, exit, err = kParamErr);
pwmout_stop((pwmout_t*)&pwm->pwm_obj);
exit:
platform_mcu_powersave_enable();
return err;
}

View file

@ -0,0 +1,91 @@
/**
******************************************************************************
* @file paltform_rng.c
* @author William Xu
* @version V1.0.0
* @date 05-May-2014
* @brief This file provide RNG 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 "MICOPlatform.h"
//#include "MICORTOS.h"
#include "board.h"
#include "platform_peripheral.h"
#include "platform_logging.h"
/******************************************************
* Macros
******************************************************/
/******************************************************
* Enumerations
******************************************************/
/******************************************************
* Type Definitions
******************************************************/
/******************************************************
* Structures
******************************************************/
/******************************************************
* Variables
******************************************************/
/******************************************************
* Function Declarations
******************************************************/
OSStatus platform_random_number_read( void *inBuffer, int inByteCount )
{
// PLATFORM_TO_DO
int idx;
uint32_t *pWord = inBuffer;
uint32_t tempRDM;
uint8_t *pByte = NULL;
int inWordCount;
int remainByteCount;
inWordCount = inByteCount/4;
remainByteCount = inByteCount%4;
pByte = (uint8_t *)pWord+inWordCount*4;
for(idx = 0; idx<inWordCount; idx++, pWord++){
*pWord = Rand3(OSC8M_Get());
}
if(remainByteCount){
tempRDM = Rand3(OSC8M_Get());
memcpy(pByte, &tempRDM, (size_t)remainByteCount);
}
return kNoErr;
}

View file

@ -0,0 +1,202 @@
/**
******************************************************************************
* @file paltform_rtc.c
* @author William Xu
* @version V1.0.0
* @date 05-May-2014
* @brief This file provide RTC 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 "MICORTOS.h"
//#include "MICOPlatform.h"
#include "board.h"
#include "platform_peripheral.h"
//#include "platform_mcu_peripheral.h" /* Include MCU-specific types */
#include "debug.h"
#include "timer_api.h"
#include "rtc_api.h"
#include "wait_api.h"
/******************************************************
* Macros
******************************************************/
#define SW_RTC_TIMER_ID TIMER5
#define MICO_VERIFY_TIME(time, valid) \
if( (time->sec > 60) || ( time->min > 60 ) || (time->hr > 24) || ( time->date > 31 ) || ( time->month > 12 )) \
{ \
valid= false; \
} \
else \
{ \
valid= true; \
}
/******************************************************
* Constants
******************************************************/
static int sw_rtc_en=0;
const static u8 dim[14] = {
31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28 };
/******************************************************
* Enumerations
******************************************************/
/******************************************************
* Type Definitions
******************************************************/
/******************************************************
* Structures
******************************************************/
/******************************************************
* Static Function Declarations
******************************************************/
/******************************************************
* Variables Definitions
******************************************************/
/******************************************************
* Function Declarations
******************************************************/
/******************************************************
* Function Definitions
******************************************************/
OSStatus platform_rtc_init(void)
{
#ifdef MICO_ENABLE_MCU_RTC
rtc_init();
return kNoErr;
#else
return kUnsupportedErr;
#endif
}
/**
* This function will return the value of time read from the on board CPU real time clock. Time value must be given in the format of
* the structure wiced_rtc_time_t
*
* @return WICED_SUCCESS : on success.
* @return WICED_ERROR : if an error occurred with any step
*/
OSStatus platform_rtc_get_time( platform_rtc_time_t* time)
{
time_t seconds;
struct tm *timeinfo;
#ifdef MICO_ENABLE_MCU_RTC
if( time == NULL )
{
return kParamErr;
}
/* fill structure */
seconds = rtc_read();
timeinfo = localtime(&seconds);
time->sec = timeinfo->tm_sec;
time->min = timeinfo->tm_min;
time->hr = timeinfo->tm_hour;
time->weekday = timeinfo->tm_wday;
time->date = timeinfo->tm_mday;
time->month= timeinfo->tm_mon+1;
time->year= timeinfo->tm_year+1900;
return kNoErr;
#else /* #ifdef WICED_ENABLE_MCU_RTC */
UNUSED_PARAMETER(time);
return kUnsupportedErr;
#endif /* #ifdef MICO_ENABLE_MCU_RTC */
}
/**
* This function will set MCU RTC time to a new value. Time value must be given in the format of
* the structure wiced_rtc_time_t
*
* @return WICED_SUCCESS : on success.
* @return WICED_ERROR : if an error occurred with any step
*/
OSStatus platform_rtc_set_time( const platform_rtc_time_t* time )
{
#ifdef MICO_ENABLE_MCU_RTC
struct tm timeinfo;
struct tm *timeinfo_p;
time_t time_in_seconds;
bool valid = false;
MICO_VERIFY_TIME(time, valid);
if( valid == false )
{
return kParamErr;
}
// Set the RTC
timeinfo.tm_sec = time->sec;
timeinfo.tm_min = time->min;
timeinfo.tm_hour = time->hr+1;
timeinfo.tm_mday = time->date;
timeinfo.tm_mon = time->month-1;
timeinfo.tm_year = time->year-1900;
time_in_seconds = mktime(&timeinfo);
timeinfo_p = localtime(&time_in_seconds);
//printf("platform_rtc_set_time %d %d %d %d %d %d %d\r\n", timeinfo_p->tm_year, timeinfo_p->tm_mon, timeinfo_p->tm_mday,
// timeinfo_p->tm_hour, timeinfo_p->tm_min, timeinfo_p->tm_sec, timeinfo_p->tm_wday);
//printf("platform_rtc_set_time %lu \r\n", time_in_seconds);
//DBG_8195A("Time as a basic string = %s", ctime(&time_in_seconds));
rtc_write(time_in_seconds);
return kNoErr;
#else /* #ifdef MICO_ENABLE_MCU_RTC */
UNUSED_PARAMETER(time);
return kUnsupportedErr;
#endif /* #ifdef MICO_ENABLE_MCU_RTC */
}
OSStatus platform_rtc_enter_powersave ( void )
{
return kUnsupportedErr;
}
OSStatus platform_rtc_abort_powersave( void )
{
return kUnsupportedErr;
}
OSStatus platform_rtc_exit_powersave( uint32_t requested_sleep_time, uint32_t *cpu_sleep_time )
{
return kUnsupportedErr;
}

View file

@ -0,0 +1,194 @@
/**
******************************************************************************
* @file paltform_spi.c
* @author William Xu
* @version V1.0.0
* @date 05-May-2014
* @brief This file provide SPI 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 "MICORTOS.h"
//#include "MICOPlatform.h"
#include "board.h"
//#include "platform_config.h"
#include "platform_peripheral.h"
#include "debug.h"
#include "pinmap.h"
#include "spi_ex_api.h"
/******************************************************
* Constants
******************************************************/
/******************************************************
* Enumerations
******************************************************/
/******************************************************
* Type Definitions
******************************************************/
/******************************************************
* Structures
******************************************************/
/******************************************************
* Static Function Declarations
******************************************************/
/******************************************************
* Variables Definitions
******************************************************/
/******************************************************
* Function Definitions
******************************************************/
OSStatus platform_spi_init( platform_spi_driver_t* driver, const platform_spi_t* peripheral, const platform_spi_config_t* config )
{
OSStatus err = kNoErr;
u8 polarity;
u8 phase;
platform_mcu_powersave_disable();
require_action_quiet( ( driver != NULL ) && ( peripheral != NULL ) && ( config != NULL ), exit, err = kParamErr);
//require_action( !(config->mode & SPI_USE_DMA), exit, err = kUnsupportedErr);
require_noerr(err, exit);
spi_init((spi_t*)&peripheral->spi_obj, peripheral->mosi, peripheral->miso, peripheral->sclk, peripheral->ssel);
spi_frequency((spi_t*)&peripheral->spi_obj, config->speed);
if ( config->mode & SPI_CLOCK_IDLE_HIGH )
polarity = SPI_SCLK_IDLE_HIGH;
else
polarity = SPI_SCLK_IDLE_LOW;
if ( config->mode & SPI_CLOCK_RISING_EDGE )
phase = ( config->mode & SPI_CLOCK_IDLE_HIGH ) ? SPI_SCLK_TOGGLE_START : SPI_SCLK_TOGGLE_MIDDLE;
else
phase = ( config->mode & SPI_CLOCK_IDLE_HIGH ) ? SPI_SCLK_TOGGLE_MIDDLE : SPI_SCLK_TOGGLE_START;
spi_format((spi_t*)&peripheral->spi_obj, config->bits, (polarity|phase) , 0);
exit:
platform_mcu_powersave_enable();
return err;
}
OSStatus platform_spi_deinit( platform_spi_driver_t* driver )
{
UNUSED_PARAMETER( driver );
/* TODO: unimplemented */
return kUnsupportedErr;
}
OSStatus platform_spi_transfer( platform_spi_driver_t* driver, const platform_spi_config_t* config, const platform_spi_message_segment_t* segments, uint16_t number_of_segments )
{
OSStatus err = kNoErr;
uint32_t count = 0;
uint16_t i;
platform_mcu_powersave_disable();
require_action_quiet( ( driver != NULL ) && ( config != NULL ) && ( segments != NULL ) && ( number_of_segments != 0 ), exit, err = kParamErr);
/* Activate chip select */
for ( i = 0; i < number_of_segments; i++ )
{
{
count = segments[i].length;
/* in interrupt-less mode */
if ( config->bits == 8 )
{
const uint8_t* send_ptr = ( const uint8_t* )segments[i].tx_buffer;
uint8_t* rcv_ptr = ( uint8_t* )segments[i].rx_buffer;
while ( count-- )
{
uint16_t data = 0xFF;
if ( send_ptr != NULL )
{
data = *send_ptr++;
}
data = spi_master_write( (spi_t*)&driver->peripheral->spi_obj, (int)data );
if ( rcv_ptr != NULL )
{
*rcv_ptr++ = (uint8_t)data;
}
}
}
else if ( config->bits == 16 )
{
const uint16_t* send_ptr = (const uint16_t *) segments[i].tx_buffer;
uint16_t* rcv_ptr = (uint16_t *) segments[i].rx_buffer;
/* Check that the message length is a multiple of 2 */
require_action_quiet( ( count % 2 ) == 0, cleanup_transfer, err = kSizeErr);
/* Transmit/receive data stream, 16-bit at time */
while ( count != 0 )
{
uint16_t data = 0xFFFF;
if ( send_ptr != NULL )
{
data = *send_ptr++;
}
data = spi_master_write( (spi_t*)&driver->peripheral->spi_obj, (int)data );
if ( rcv_ptr != NULL )
{
*rcv_ptr++ = data;
}
count -= 2;
}
}
}
}
cleanup_transfer:
///* Deassert chip select */
//platform_gpio_output_high( config->chip_select );
exit:
platform_mcu_powersave_enable( );
return err;
}

View file

@ -0,0 +1,561 @@
/**
******************************************************************************
* @file paltform_uart.c
* @author William Xu
* @version V1.0.0
* @date 05-May-2014
* @brief This file provide UART 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 "mico_rtos.h"
#include "mico_platform.h"
#include "board.h"
#include "platform_peripheral.h"
#include "debug.h"
#include "pinmap.h"
#define mico_log(M, ...) custom_log("MICO", M, ##__VA_ARGS__)
#define mico_log_trace() custom_log_trace("MICO")
/******************************************************
* Constants
******************************************************/
/******************************************************
* Enumerations
******************************************************/
/******************************************************
* Type Definitions
******************************************************/
/******************************************************
* Structures
******************************************************/
/******************************************************
* Variables Definitions
******************************************************/
/******************************************************
* Static Function Declarations
******************************************************/
/* Interrupt service functions - called from interrupt vector table */
#ifndef NO_MICO_RTOS
static void thread_wakeup(void *arg);
static void RX_PIN_WAKEUP_handler(void *arg);
#endif
/******************************************************
* Function Definitions
******************************************************/
OSStatus platform_uart_init( platform_uart_driver_t* driver, const platform_uart_t* peripheral, const platform_uart_config_t* config, ring_buffer_t* optional_ring_buffer )
{
OSStatus err = kNoErr;
int wordlen;
SerialParity parity;
int stopbit;
FlowControl flowcontrol;
platform_mcu_powersave_disable();
require_action_quiet( ( driver != NULL ) && ( peripheral != NULL ) && ( config != NULL ), exit, err = kParamErr);
require_action_quiet( (optional_ring_buffer == NULL) || ((optional_ring_buffer->buffer != NULL ) && (optional_ring_buffer->size != 0)), exit, err = kParamErr);
driver->rx_size = 0;
driver->tx_size = 0;
driver->last_transmit_result = kNoErr;
driver->last_receive_result = kNoErr;
driver->peripheral = (platform_uart_t*)peripheral;
#ifndef NO_MICO_RTOS
aos_sem_new( &driver->tx_complete, 1 );
aos_sem_new( &driver->rx_complete, 0 );
aos_sem_new( &driver->sem_wakeup, 0 );
aos_mutex_new( &driver->tx_mutex );
#else
driver->tx_complete = false;
driver->rx_complete = false;
#endif
if (optional_ring_buffer != NULL){
/* Note that the ring_buffer should've been initialised first */
driver->rx_buffer = optional_ring_buffer;
driver->rx_size = 0;
//platform_uart_receive_bytes( uart, optional_rx_buffer->buffer, optional_rx_buffer->size, 0 );
}else{
driver->rx_buffer = NULL;
}
if(peripheral->tx == PA_30 && peripheral->rx == PA_29){
DBG_8195A("platform_uart_init 22222 \r\n");
DIAG_UartReInit((IRQ_FUN) platform_loguart_irq);
NVIC_SetPriority(UART_LOG_IRQ, 10); /* this is rom_code_patch */
LOGUART_SetBaud(config->baud_rate);
return;
}
serial_init((serial_t*)&peripheral->serial_obj, peripheral->tx, peripheral->rx);
switch ( config->data_width)
{
case DATA_WIDTH_7BIT :
wordlen = 7;
break;
case DATA_WIDTH_8BIT:
wordlen = 8;
break;
default:
err = kParamErr;
goto exit;
}
switch ( config->parity )
{
case NO_PARITY:
parity = ParityNone;
break;
case EVEN_PARITY:
parity = ParityEven;
break;
case ODD_PARITY:
parity = ParityOdd;
break;
default:
err = kParamErr;
goto exit;
}
switch ( config->stop_bits )
{
case STOP_BITS_1:
stopbit = 1;
break;
case STOP_BITS_2:
stopbit = 2;
break;
default:
err = kParamErr;
goto exit;
}
switch ( config->flow_control )
{
case FLOW_CONTROL_DISABLED:
flowcontrol = FlowControlNone;
break;
case FLOW_CONTROL_RTS:
flowcontrol = FlowControlRTS;
break;
case FLOW_CONTROL_CTS:
flowcontrol = FlowControlCTS;
break;
case FLOW_CONTROL_CTS_RTS:
flowcontrol = FlowControlRTSCTS;
break;
default:
err = kParamErr;
goto exit;
}
/*only UART0 support flow control*/
if(config->flow_control != FLOW_CONTROL_DISABLED && peripheral->serial_obj.uart_idx != 0)
{
err = kUnsupportedErr;
goto exit;
}else if(peripheral->serial_obj.uart_idx == 0)
serial_set_flow_control((serial_t*)&peripheral->serial_obj, flowcontrol, peripheral->rx, peripheral->tx);
serial_baud((serial_t*)&peripheral->serial_obj,config->baud_rate);
serial_format((serial_t*)&peripheral->serial_obj, wordlen, parity, stopbit);
serial_irq_set((serial_t*)&peripheral->serial_obj, RxIrq, 1);
serial_irq_set((serial_t*)&peripheral->serial_obj, TxIrq, 1);
if(!optional_ring_buffer){
serial_recv_comp_handler((serial_t*)&peripheral->serial_obj, (void*)platform_uart_rx_dma_irq, (uint32_t) driver);
}else{
serial_irq_handler((serial_t*)&peripheral->serial_obj, platform_uart_irq, (uint32_t)driver);
}
serial_send_comp_handler((serial_t*)&peripheral->serial_obj, (void*)platform_uart_tx_dma_irq, (uint32_t) driver);
exit:
platform_mcu_powersave_enable();
return err;
}
OSStatus platform_uart_deinit( platform_uart_driver_t* driver )
{
uint8_t uart_number;
OSStatus err = kNoErr;
platform_mcu_powersave_disable();
require_action_quiet( ( driver != NULL ), exit, err = kParamErr);
if(driver->peripheral->tx == PA_30 && driver->peripheral->rx == PA_29){
}else{
serial_free((serial_t*)&driver->peripheral->serial_obj);
}
#ifndef NO_MICO_RTOS
aos_sem_free( &driver->rx_complete );
aos_sem_free( &driver->tx_complete );
aos_mutex_free( &driver->tx_mutex );
aos_sem_free( &driver->sem_wakeup);
#else
driver->rx_complete = false;
driver->tx_complete = true;
#endif
driver->rx_size = 0;
driver->tx_size = 0;
driver->last_transmit_result = kNoErr;
driver->last_receive_result = kNoErr;
exit:
platform_mcu_powersave_enable();
return err;
}
OSStatus platform_uart_transmit_bytes( platform_uart_driver_t* driver, const uint8_t* data_out, uint32_t size )
{
OSStatus err = kNoErr;
int32_t ret;
platform_mcu_powersave_disable();
#if 0
/* Wait for transmission complete */
#ifndef NO_MICO_RTOS
ret = aos_sem_wait( &driver->tx_complete, AOS_WAIT_FOREVER );
if(ret != 0)
DBG_8195A("ret %d, sema 0x%x\r\n", ret, &driver->tx_complete);
#else
while( driver->tx_complete == false ){
rtw_msleep_os(2);
}
driver->tx_complete = false;
#endif
#endif
if(driver->peripheral->tx == PA_30 && driver->peripheral->rx == PA_29){
while (size){
DiagPrintf("%c", *data_out);
size--;
data_out++;
}
}else{
while (size){
serial_putc((serial_t*)&driver->peripheral->serial_obj, *data_out);
size--;
data_out++;
}
}
#if 0
Retry:
//ret = serial_send_stream_dma((serial_t*)&driver->peripheral->serial_obj, (char*)data_out, size);
ret = serial_send_stream((serial_t*)&driver->peripheral->serial_obj, (char*)data_out, size);
if(ret != 0){
DBG_8195A("** %d\r\n", size);
err = kGeneralErr;
goto Retry;
}
#endif
/* Disable DMA and clean up */
driver->tx_size = 0;
err = driver->last_transmit_result;
exit:
platform_mcu_powersave_enable();
return err;
}
OSStatus platform_uart_receive_bytes( platform_uart_driver_t* driver, uint8_t* data_in, uint32_t expected_data_size, uint32_t timeout_ms )
{
OSStatus err = kNoErr;
platform_mcu_powersave_disable();
require_action_quiet( ( driver != NULL ) && ( data_in != NULL ) && ( expected_data_size != 0 ), exit, err = kParamErr);
if ( driver->rx_buffer != NULL )
{
while (expected_data_size != 0)
{
uint32_t transfer_size = MIN( driver->rx_buffer->size/2, expected_data_size );
/* Check if ring buffer already contains the required amount of data. */
if ( transfer_size > ring_buffer_used_space( driver->rx_buffer ) )
{
/* Set rx_size and wait in rx_complete semaphore until data reaches rx_size or timeout occurs */
driver->rx_size = transfer_size;
#ifndef NO_MICO_RTOS
if ( aos_sem_wait( &driver->rx_complete, timeout_ms) != kNoErr )
{
driver->rx_size = 0;
return kTimeoutErr;
}
#else
driver->rx_complete = false;
u32 delay_start = SYSTIMER_TickGet();
while(driver->rx_complete == false){
if(SYSTIMER_TickGet() >= delay_start + timeout_ms && timeout_ms != MICO_NEVER_TIMEOUT){
driver->rx_size = 0;
return kTimeoutErr;
}
}
#endif
/* Reset rx_size to prevent semaphore being set while nothing waits for the data */
driver->rx_size = 0;
}
expected_data_size -= transfer_size;
// Grab data from the buffer
do
{
uint8_t* available_data;
uint32_t bytes_available;
ring_buffer_get_data( driver->rx_buffer, &available_data, &bytes_available );
bytes_available = MIN( bytes_available, transfer_size );
memcpy( data_in, available_data, bytes_available );
transfer_size -= bytes_available;
data_in = ( (uint8_t*) data_in + bytes_available );
ring_buffer_consume( driver->rx_buffer, bytes_available );
} while ( transfer_size != 0 );
}
if ( expected_data_size != 0 )
{
return kGeneralErr;
}
else
{
return kNoErr;
}
}
else
{
err = serial_recv_stream_dma_timeout((serial_t*)&driver->peripheral->serial_obj, data_in, expected_data_size, timeout_ms, NULL );
if(err == expected_data_size)
return kNoErr;
else
return kTimeoutErr;
}
exit:
platform_mcu_powersave_enable();
return err;
}
uint32_t platform_uart_get_length_in_buffer( platform_uart_driver_t* driver )
{
return ring_buffer_used_space( driver->rx_buffer );
}
#if 0
uint8_t platform_uart_get_port_number( USART_TypeDef* uart )
{
if ( uart == USART1 )
{
return 0;
}
else if ( uart == USART2 )
{
return 1;
}
else if ( uart == USART3 )
{
return 2;
}
else if ( uart == UART4 )
{
return 3;
}
else if ( uart == UART5 )
{
return 4;
}
else if ( uart == USART6 )
{
return 5;
}
else
{
return 0xff;
}
}
#endif
#ifndef NO_MICO_RTOS
static void thread_wakeup(void *arg)
{
#if 0
platform_uart_driver_t* driver = arg;
while(1){
if( mico_rtos_get_semaphore( driver->sem_wakeup, 1000) != kNoErr )
{
platform_gpio_irq_enable( driver->peripheral->pin_rx, IRQ_TRIGGER_FALLING_EDGE, RX_PIN_WAKEUP_handler, driver );
platform_mcu_powersave_enable( );
}
}
#endif
}
#endif
/******************************************************
* Interrupt Service Routines
******************************************************/
#ifndef NO_MICO_RTOS
void RX_PIN_WAKEUP_handler(void *arg)
{
#if 0
(void)arg;
platform_uart_driver_t* driver = arg;
uint32_t uart_number;
platform_gpio_enable_clock( driver->peripheral->pin_rx );
uart_number = platform_uart_get_port_number( driver->peripheral->port );
uart_peripheral_clock_functions[ uart_number ]( uart_peripheral_clocks[ uart_number ], ENABLE );
/* Enable DMA peripheral clock */
if ( driver->peripheral->tx_dma_config.controller == DMA1 )
{
RCC->AHB1ENR |= RCC_AHB1Periph_DMA1;
}
else
{
RCC->AHB1ENR |= RCC_AHB1Periph_DMA2;
}
platform_gpio_irq_disable( driver->peripheral->pin_rx );
platform_mcu_powersave_disable( );
mico_rtos_set_semaphore( &driver->sem_wakeup );
#endif
}
#endif
extern platform_uart_driver_t platform_uart_drivers[MICO_UART_MAX];
void platform_loguart_irq( void* id)
{
platform_uart_driver_t* driver = &platform_uart_drivers[0];
u8 UartReceiveData = 0;
BOOL PullMode = _FALSE;
volatile u8 reg_iir;
u32 RegValue;
reg_iir = UART_IntStatus(UART2_DEV);
if ((reg_iir & RUART_RECEIVE_LINE_STATUS) != 0) {
RegValue = UART_LineStatusGet(UART2_DEV);
return;
}
u32 IrqEn = DiagGetIsrEnReg();
DiagSetIsrEnReg(0);
UartReceiveData = DiagGetChar(PullMode);
ring_buffer_write( driver->rx_buffer, &UartReceiveData,1 );
// Notify thread if sufficient data are available
if ( ( driver->rx_size > 0 ) &&
( ring_buffer_used_space( driver->rx_buffer ) >= driver->rx_size ) )
{
#ifndef NO_MICO_RTOS
aos_sem_signal( &driver->rx_complete );
#else
driver->rx_complete = true;
#endif
driver->rx_size = 0;
}
DiagSetIsrEnReg(IrqEn);
}
void platform_uart_irq( uint32_t id, SerialIrq event)
{
uint8_t rxData;
platform_uart_driver_t* driver = (platform_uart_driver_t*)id;
if(event == RxIrq){
rxData = serial_getc((serial_t*)&driver->peripheral->serial_obj);
ring_buffer_write( driver->rx_buffer, &rxData,1 );
//DBG_8195A("\r\nnuart irq\r\n");
// Notify thread if sufficient data are available
if ( ( driver->rx_size > 0 ) &&
( ring_buffer_used_space( driver->rx_buffer ) >= driver->rx_size ) )
{
#ifndef NO_MICO_RTOS
aos_sem_signal( &driver->rx_complete );
#else
driver->rx_complete = true;
#endif
driver->rx_size = 0;
}
}
}
void platform_uart_tx_dma_irq( uint32_t id )
{
platform_uart_driver_t* driver = (platform_uart_driver_t*)id;
/* Set semaphore regardless of result to prevent waiting thread from locking up */
#ifndef NO_MICO_RTOS
aos_sem_signal( &driver->tx_complete );
#else
driver->tx_complete = true;
#endif
}
void platform_uart_rx_dma_irq( uint32_t id )
{
platform_uart_driver_t* driver = (platform_uart_driver_t*)id;
/* Set semaphore regardless of result to prevent waiting thread from locking up */
#ifndef NO_MICO_RTOS
aos_sem_signal( &driver->rx_complete );
#else
driver->rx_complete = true;
#endif
}

View file

@ -0,0 +1,117 @@
/**
******************************************************************************
* @file paltform_watchdog.c
* @author William Xu
* @version V1.0.0
* @date 05-May-2014
* @brief This file provide WDG 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 "MICOPlatform.h"
//#include "MICORTOS.h"
#include "common.h"
#include "debug.h"
#include "board.h"
#include "platform_peripheral.h"
/******************************************************
* Constants
******************************************************/
/******************************************************
* Enumerations
******************************************************/
/******************************************************
* Type Definitions
******************************************************/
/******************************************************
* Structures
******************************************************/
/******************************************************
* Variables Definitions
******************************************************/
/******************************************************
* Function Declarations
******************************************************/
/******************************************************
* Function Definitions
******************************************************/
OSStatus platform_watchdog_init( uint32_t timeout_ms )
{
// PLATFORM_TO_DO
#ifndef MICO_DISABLE_WATCHDOG
OSStatus err = kNoErr;
watchdog_init(timeout_ms);
watchdog_start();
exit:
return err;
#else
UNUSED_PARAMETER( timeout_ms );
return kUnsupportedErr;
#endif
}
OSStatus MicoWdgFinalize( void )
{
// PLATFORM_TO_DO
return kNoErr;
}
bool platform_watchdog_check_last_reset( void )
{
u32 value_bk0 = BKUP_Read(BKUP_REG0);
printf("backup reg0 0x%x\r\n", value_bk0);
if(value_bk0 & BIT_CPU_RESET_HAPPEN){ //system reboot
if(!(value_bk0 & BIT_SYS_RESET_HAPPEN)){
return true;
}
else
BKUP_Clear(BKUP_REG0, BIT_SYS_RESET_HAPPEN);
}
return false;
}
OSStatus platform_watchdog_kick( void )
{
#ifndef MICO_DISABLE_WATCHDOG
watchdog_refresh();
return kNoErr;
#else
return kUnsupportedErr;
#endif
}

View file

@ -0,0 +1,139 @@
/* mbed Microcontroller Library
*******************************************************************************
* Copyright (c) 2014, Realtek Semiconductor Corp.
* All rights reserved.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*******************************************************************************
*/
#include "objects.h"
//#include <stddef.h>
#include "timer_api.h"
//#include "PeripheralNames.h"
#if CONFIG_TIMER_EN
extern HAL_TIMER_OP HalTimerOp;
extern HAL_Status HalTimerInitRtl8195a_Patch(
IN VOID *Data
);
static void gtimer_timeout_handler (uint32_t tid)
{
gtimer_t *obj = (gtimer_t *)tid;
//PTIMER_ADAPTER pTimerAdapter = &(obj->hal_gtimer_adp);
gtimer_irq_handler handler;
if (obj->handler != NULL) {
handler = (gtimer_irq_handler)obj->handler;
handler(obj->hid);
}
if (!obj->is_periodcal) {
gtimer_stop(obj);
}
}
void gtimer_init (gtimer_t *obj, uint32_t tid)
{
PTIMER_ADAPTER pTimerAdapter = &(obj->hal_gtimer_adp);
if (tid > GTIMER_MAX) {
DBG_TIMER_ERR("%s: Invalid TimerId=%d\r\n", __FUNCTION__, tid);
return;
}
pTimerAdapter->IrqDis = 0; // Enable Irq @ initial
pTimerAdapter->IrqHandle.IrqFun = (IRQ_FUN) gtimer_timeout_handler;
pTimerAdapter->IrqHandle.IrqNum = TIMER2_7_IRQ;
pTimerAdapter->IrqHandle.Priority = 0;
pTimerAdapter->IrqHandle.Data = (u32)obj;
pTimerAdapter->TimerId = (u8)tid;
pTimerAdapter->TimerIrqPriority = 0;
pTimerAdapter->TimerLoadValueUs = 0xFFFFFFFF; // Just a whatever value
pTimerAdapter->TimerMode = USER_DEFINED;
HalTimerInit ((VOID*) pTimerAdapter);
// gtimer_stop(obj); // HAL Initial will let the timer started, just stop it after initial
}
void gtimer_deinit (gtimer_t *obj)
{
PTIMER_ADAPTER pTimerAdapter = &(obj->hal_gtimer_adp);
HalTimerDeInit((void*)pTimerAdapter);
}
uint32_t gtimer_read_tick (gtimer_t *obj)
{
PTIMER_ADAPTER pTimerAdapter = &obj->hal_gtimer_adp;
return (HalTimerOp.HalTimerReadCount(pTimerAdapter->TimerId));
}
uint64_t gtimer_read_us (gtimer_t *obj)
{
uint64_t time_us;
time_us = gtimer_read_tick(obj)*1000000/32768;
return (time_us);
}
void gtimer_reload (gtimer_t *obj, uint32_t duration_us)
{
PTIMER_ADAPTER pTimerAdapter = &obj->hal_gtimer_adp;
HalTimerReLoad(pTimerAdapter->TimerId, duration_us);
}
void gtimer_start (gtimer_t *obj)
{
PTIMER_ADAPTER pTimerAdapter = &obj->hal_gtimer_adp;
u8 TimerId = pTimerAdapter->TimerId;
HalTimerEnable(TimerId);
#if 0
HalTimerOp.HalTimerEn(pTimerAdapter->TimerId);
HAL_TIMER_WRITE32((TIMER_INTERVAL*TimerId + TIMER_CTL_REG_OFF),
HAL_TIMER_READ32(TIMER_INTERVAL*TimerId + TIMER_CTL_REG_OFF) | (BIT0));
#endif
}
void gtimer_start_one_shout (gtimer_t *obj, uint32_t duration_us, void* handler, uint32_t hid)
{
obj->is_periodcal = _FALSE;
obj->handler = handler;
obj->hid = hid;
gtimer_reload(obj, duration_us);
gtimer_start(obj);
}
void gtimer_start_periodical (gtimer_t *obj, uint32_t duration_us, void* handler, uint32_t hid)
{
obj->is_periodcal = _TRUE;
obj->handler = handler;
obj->hid = hid;
if (duration_us > GTIMER_TICK_US) {
// reload will takes extra 1 tick
duration_us -= GTIMER_TICK_US;
}
gtimer_reload(obj, duration_us);
gtimer_start(obj);
}
void gtimer_stop (gtimer_t *obj)
{
PTIMER_ADAPTER pTimerAdapter = &obj->hal_gtimer_adp;
// obj->handler = NULL;
// HalTimerOp.HalTimerDis(pTimerAdapter->TimerId);
HalTimerDisable(pTimerAdapter->TimerId);
}
#endif // end of "#if CONFIG_TIMER_EN"

View file

@ -0,0 +1,38 @@
/*******************************************************************************
* Copyright (c) 2014, Realtek Semiconductor Corp.
* All rights reserved.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*******************************************************************************/
#ifndef MBED_EXT_TIMER_API_EXT_H
#define MBED_EXT_TIMER_API_EXT_H
#include "device.h"
//#include "rtl8195a.h"
typedef void (*gtimer_irq_handler)(uint32_t id);
typedef struct gtimer_s gtimer_t;
enum {
TIMER0 = 2, // GTimer 2, share with us_tick(wait_ms()) functions
TIMER1 = 3, // GTimer 3, share with PWM_0
TIMER2 = 4, // GTimer 4, share with PWM_1
TIMER3 = 5, // GTimer 5, share with PWM_2
TIMER4 = 6, // GTimer 6, share with PWM_3
TIMER5 = 7, // share with the software-RTC
GTIMER_MAX = 7
};
void gtimer_init (gtimer_t *obj, uint32_t tid);
void gtimer_deinit (gtimer_t *obj);
uint32_t gtimer_read_tick (gtimer_t *obj);
uint64_t gtimer_read_us (gtimer_t *obj);
void gtimer_reload (gtimer_t *obj, uint32_t duration_us);
void gtimer_start (gtimer_t *obj);
void gtimer_start_one_shout (gtimer_t *obj, uint32_t duration_us, void* handler, uint32_t hid);
void gtimer_start_periodical (gtimer_t *obj, uint32_t duration_us, void* handler, uint32_t hid);
void gtimer_stop (gtimer_t *obj);
#endif

View file

@ -0,0 +1,481 @@
/**
******************************************************************************
* @file FatFs/FatFs_USBDisk_RTOS/Src/usbh_conf.c
* @author MCD Application Team
* @version V1.1.0
* @date 13-March-2014
* @brief USB Host configuration file.
******************************************************************************
* @attention
*
* <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
*
* Licensed under MCD-ST Liberty SW License Agreement V2, (the "License");
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.st.com/software_license_agreement_liberty_v2
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************
*/
#ifdef USE_USB_FS
/* Includes ------------------------------------------------------------------*/
#include "stm32f2xx_hal.h"
#include "usbh_core.h"
#include "platform_common_config.h"
HCD_HandleTypeDef hhcd;
/*******************************************************************************
HCD BSP Routines
*******************************************************************************/
/**
* @brief Initializes the HCD MSP.
* @param hhcd: HCD handle
* @retval None
*/
void HAL_HCD_MspInit(HCD_HandleTypeDef *hhcd)
{
GPIO_InitTypeDef GPIO_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
if(hhcd->Instance == USB_OTG_FS)
{
/* Configure USB FS GPIOs */
RCC_AHB1PeriphClockCmd( RCC_AHB1Periph_GPIOA , ENABLE);
/* Configure SOF VBUS ID DM DP Pins */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11 | GPIO_Pin_12;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOA,GPIO_PinSource11,GPIO_AF_OTG1_FS) ;
GPIO_PinAFConfig(GPIOA,GPIO_PinSource12,GPIO_AF_OTG1_FS) ;
/* Enable USB FS Clocks */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
RCC_AHB2PeriphClockCmd(RCC_AHB2Periph_OTG_FS, ENABLE) ;
/* Enable USB FS Clocks */
/* Set USBFS Interrupt to the lowest priority */
NVIC_InitStructure.NVIC_IRQChannel = OTG_FS_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 5;//1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
/* Enable USBFS Interrupt */
}
else if(hhcd->Instance == USB_OTG_HS)
{
}
}
/**
* @brief DeInitializes the HCD MSP.
* @param hhcd: HCD handle
* @retval None
*/
void HAL_HCD_MspDeInit(HCD_HandleTypeDef *hhcd)
{
if(hhcd->Instance == USB_OTG_FS)
{
/* Disable USB FS Clocks */
RCC_AHB2PeriphClockCmd(RCC_AHB2Periph_OTG_FS, ENABLE) ;
// __USB_OTG_FS_CLK_DISABLE();
}
else if(hhcd->Instance == USB_OTG_HS)
{
}
}
/*******************************************************************************
LL Driver Callbacks (HCD -> USB Host Library)
*******************************************************************************/
/**
* @brief SOF callback.
* @param hhcd: HCD handle
* @retval None
*/
void HAL_HCD_SOF_Callback(HCD_HandleTypeDef *hhcd)
{
USBH_LL_IncTimer (hhcd->pData);
}
/**
* @brief Connect callback.
* @param hhcd: HCD handle
* @retval None
*/
void HAL_HCD_Connect_Callback(HCD_HandleTypeDef *hhcd)
{
USBH_LL_Connect(hhcd->pData);
}
/**
* @brief Disconnect callback.
* @param hhcd: HCD handle
* @retval None
*/
void HAL_HCD_Disconnect_Callback(HCD_HandleTypeDef *hhcd)
{
USBH_LL_Disconnect(hhcd->pData);
}
/**
* @brief Notify URB state change callback.
* @param hhcd: HCD handle
* @param chnum:
* @param urb_state:
* @retval None
*/
void HAL_HCD_HC_NotifyURBChange_Callback(HCD_HandleTypeDef *hhcd, uint8_t chnum, HCD_URBStateTypeDef urb_state)
{
#if (USBH_USE_OS == 1)
USBH_LL_NotifyURBChange(hhcd->pData);
#endif
}
/*******************************************************************************
LL Driver Interface (USB Host Library --> HCD)
*******************************************************************************/
/**
* @brief Initializes the Low Level portion of the Host driver.
* @param phost: Host handle
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_LL_Init(USBH_HandleTypeDef *phost)
{
#ifdef USE_USB_FS
/* Set the LL driver parameters */
hhcd.Instance = USB_OTG_FS;
hhcd.Init.Host_channels = 11;
hhcd.Init.dma_enable = 0;
hhcd.Init.low_power_enable = 0;
hhcd.Init.phy_itface = HCD_PHY_EMBEDDED;
hhcd.Init.Sof_enable = 0;
hhcd.Init.speed = HCD_SPEED_FULL;
hhcd.Init.vbus_sensing_enable = 0;
/* Link the driver to the stack */
hhcd.pData = phost;
phost->pData = &hhcd;
/* Initialize the LL Driver */
HAL_HCD_Init(&hhcd);
#endif
#ifdef USE_USB_HS
/* Set the LL driver parameters */
hhcd.Instance = USB_OTG_HS;
hhcd.Init.Host_channels = 11;
hhcd.Init.dma_enable = 1;
hhcd.Init.low_power_enable = 0;
hhcd.Init.phy_itface = HCD_PHY_ULPI;
hhcd.Init.Sof_enable = 0;
hhcd.Init.speed = HCD_SPEED_HIGH;
hhcd.Init.vbus_sensing_enable = 0;
hhcd.Init.use_external_vbus = 1;
/* Link the driver to the stack */
hhcd.pData = phost;
phost->pData = &hhcd;
/* Initialize the LL driver */
HAL_HCD_Init(&hhcd);
#endif
USBH_LL_SetTimer(phost, HAL_HCD_GetCurrentFrame(&hhcd));
return USBH_OK;
}
/**
* @brief De-Initializes the Low Level portion of the Host driver.
* @param phost: Host handle
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_LL_DeInit(USBH_HandleTypeDef *phost)
{
HAL_HCD_DeInit(phost->pData);
return USBH_OK;
}
/**
* @brief Starts the Low Level portion of the Host driver.
* @param phost: Host handle
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_LL_Start(USBH_HandleTypeDef *phost)
{
HAL_HCD_Start(phost->pData);
return USBH_OK;
}
/**
* @brief Stops the Low Level portion of the Host driver.
* @param phost: Host handle
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_LL_Stop(USBH_HandleTypeDef *phost)
{
HAL_HCD_Stop(phost->pData);
return USBH_OK;
}
/**
* @brief Returns the USB Host Speed from the Low Level Driver.
* @param phost: Host handle
* @retval USBH Speeds
*/
USBH_SpeedTypeDef USBH_LL_GetSpeed(USBH_HandleTypeDef *phost)
{
USBH_SpeedTypeDef speed = USBH_SPEED_FULL;
switch (HAL_HCD_GetCurrentSpeed(phost->pData))
{
case 0:
speed = USBH_SPEED_HIGH;
break;
case 1:
speed = USBH_SPEED_FULL;
break;
case 2:
speed = USBH_SPEED_LOW;
break;
default:
speed = USBH_SPEED_FULL;
break;
}
return speed;
}
/**
* @brief Resets the Host Port of the Low Level Driver.
* @param phost: Host handle
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_LL_ResetPort (USBH_HandleTypeDef *phost)
{
HAL_HCD_ResetPort(phost->pData);
return USBH_OK;
}
/**
* @brief Returns the last transfered packet size.
* @param phost: Host handle
* @param pipe: Pipe index
* @retval Packet Size
*/
uint32_t USBH_LL_GetLastXferSize(USBH_HandleTypeDef *phost, uint8_t pipe)
{
return HAL_HCD_HC_GetXferCount(phost->pData, pipe);
}
/**
* @brief Opens a pipe of the Low Level Driver.
* @param phost: Host handle
* @param pipe: Pipe index
* @param epnum: Endpoint Number
* @param dev_address: Device USB address
* @param speed: Device Speed
* @param ep_type: Endpoint Type
* @param mps: Endpoint Max Packet Size
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_LL_OpenPipe(USBH_HandleTypeDef *phost,
uint8_t pipe,
uint8_t epnum,
uint8_t dev_address,
uint8_t speed,
uint8_t ep_type,
uint16_t mps)
{
HAL_HCD_HC_Init(phost->pData,
pipe,
epnum,
dev_address,
speed,
ep_type,
mps);
return USBH_OK;
}
/**
* @brief Closes a pipe of the Low Level Driver.
* @param phost: Host handle
* @param pipe: Pipe index
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_LL_ClosePipe(USBH_HandleTypeDef *phost, uint8_t pipe)
{
HAL_HCD_HC_Halt(phost->pData, pipe);
return USBH_OK;
}
/**
* @brief Submits a new URB to the low level driver.
* @param phost: Host handle
* @param pipe: Pipe index
* This parameter can be a value from 1 to 15
* @param direction: Channel number
* This parameter can be one of these values:
* 0: Output
* 1: Input
* @param ep_type: Endpoint Type
* This parameter can be one of these values:
* @arg EP_TYPE_CTRL: Control type
* @arg EP_TYPE_ISOC: Isochrounous type
* @arg EP_TYPE_BULK: Bulk type
* @arg EP_TYPE_INTR: Interrupt type
* @param token: Endpoint Type
* This parameter can be one of these values:
* @arg 0: PID_SETUP
* @arg 1: PID_DATA
* @param pbuff: pointer to URB data
* @param length: length of URB data
* @param do_ping: activate do ping protocol (for high speed only)
* This parameter can be one of these values:
* 0: do ping inactive
* 1: do ping active
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_LL_SubmitURB(USBH_HandleTypeDef *phost,
uint8_t pipe,
uint8_t direction,
uint8_t ep_type,
uint8_t token,
uint8_t* pbuff,
uint16_t length,
uint8_t do_ping)
{
HAL_HCD_HC_SubmitRequest(phost->pData,
pipe,
direction,
ep_type,
token,
pbuff,
length,
do_ping);
return USBH_OK;
}
/**
* @brief Gets a URB state from the low level driver.
* @param phost: Host handle
* @param pipe: Pipe index
* This parameter can be a value from 1 to 15
* @retval URB state
* This parameter can be one of these values:
* @arg URB_IDLE
* @arg URB_DONE
* @arg URB_NOTREADY
* @arg URB_NYET
* @arg URB_ERROR
* @arg URB_STALL
*/
USBH_URBStateTypeDef USBH_LL_GetURBState(USBH_HandleTypeDef *phost, uint8_t pipe)
{
return (USBH_URBStateTypeDef)HAL_HCD_HC_GetURBState (phost->pData, pipe);
}
/**
* @brief Drives VBUS.
* @param phost: Host handle
* @param state: VBUS state
* This parameter can be one of these values:
* 0: VBUS Active
* 1: VBUS Inactive
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_LL_DriverVBUS(USBH_HandleTypeDef *phost, uint8_t state)
{
// if(state == 0)
// {
// HAL_GPIO_WritePin(GPIOH, GPIO_PIN_5, GPIO_PIN_SET);
// }
// else
// {
// HAL_GPIO_WritePin(GPIOH, GPIO_PIN_5, GPIO_PIN_RESET);
// }
HAL_Delay(200);
return USBH_OK;
}
/**
* @brief Sets toggle for a pipe.
* @param phost: Host handle
* @param pipe: Pipe index
* @param toggle: toggle (0/1)
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_LL_SetToggle(USBH_HandleTypeDef *phost, uint8_t pipe, uint8_t toggle)
{
if(hhcd.hc[pipe].ep_is_in)
{
hhcd.hc[pipe].toggle_in = toggle;
}
else
{
hhcd.hc[pipe].toggle_out = toggle;
}
return USBH_OK;
}
/**
* @brief Returns the current toggle of a pipe.
* @param phost: Host handle
* @param pipe: Pipe index
* @retval toggle (0/1)
*/
uint8_t USBH_LL_GetToggle(USBH_HandleTypeDef *phost, uint8_t pipe)
{
uint8_t toggle = 0;
if(hhcd.hc[pipe].ep_is_in)
{
toggle = hhcd.hc[pipe].toggle_in;
}
else
{
toggle = hhcd.hc[pipe].toggle_out;
}
return toggle;
}
/**
* @brief Delay routine for the USB Host Library
* @param Delay: Delay in ms
* @retval None
*/
void USBH_Delay(uint32_t Delay)
{
HAL_Delay(Delay);
}
#ifdef USE_USB_FS
void OTG_FS_IRQHandler(void)
{
HAL_HCD_IRQHandler(&hhcd);
}
#endif
#endif
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

View file

@ -0,0 +1,98 @@
/**
******************************************************************************
* @file FatFs/FatFs_USBDisk_RTOS/Inc/usbh_conf.h
* @author MCD Application Team
* @version V1.1.0
* @date 13-March-2014
* @brief General low level driver configuration
******************************************************************************
* @attention
*
* <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
*
* Licensed under MCD-ST Liberty SW License Agreement V2, (the "License");
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.st.com/software_license_agreement_liberty_v2
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USBH_CONF_H
#define __USBH_CONF_H
/* Includes ------------------------------------------------------------------*/
#include "stm32f2xx_hal.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Exported types ------------------------------------------------------------*/
#define USBH_MAX_NUM_ENDPOINTS 2
#define USBH_MAX_NUM_INTERFACES 2
#define USBH_MAX_NUM_CONFIGURATION 1
#define USBH_MAX_NUM_SUPPORTED_CLASS 1
#define USBH_KEEP_CFG_DESCRIPTOR 0
#define USBH_MAX_SIZE_CONFIGURATION 0x200
#define USBH_MAX_DATA_BUFFER 0x200
#define USBH_DEBUG_LEVEL 0
#define USBH_USE_OS 1
/* Exported constants --------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* CMSIS OS macros */
#if (USBH_USE_OS == 1)
#include "MICO.h"
#endif
/* Memory management macros */
#define USBH_malloc malloc
#define USBH_free free
#define USBH_memset memset
#define USBH_memcpy memcpy
#ifdef USE_USB_FS
void OTG_FS_IRQHandler(void);
#endif
#ifdef __cplusplus
}
#endif
/* DEBUG macros */
#if (USBH_DEBUG_LEVEL > 0)
#define USBH_UsrLog(...) custom_log("USB", M, ##__VA_ARGS__)
#else
#define USBH_UsrLog(...)
#endif
#if (USBH_DEBUG_LEVEL > 1)
#define USBH_ErrLog(...) custom_log("ERROR USB", M, ##__VA_ARGS__)
#else
#define USBH_ErrLog(...)
#endif
#if (USBH_DEBUG_LEVEL > 2)
#define USBH_DbgLog(...) custom_log("DEBUG USB", M, ##__VA_ARGS__)
#else
#define USBH_DbgLog(...)
#endif
/* Exported functions ------------------------------------------------------- */
#endif /* __USB_CONF_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

View file

@ -0,0 +1,30 @@
# Date : 2018/07/26
# Author : Snow Yang
# Mail : yangsw@mxchip.com
EXTRA_POST_BUILD_TARGETS += image_xip all_bin ota_bin
TEXT_OUTPUT_FILE :=$(LINK_OUTPUT_FILE:$(LINK_OUTPUT_SUFFIX)=.text.bin)
DATA_OUTPUT_FILE :=$(LINK_OUTPUT_FILE:$(LINK_OUTPUT_SUFFIX)=.data.bin)
image_xip:
$(OBJCOPY) -j .xip_image2.text -Obinary $(LINK_OUTPUT_FILE) $(TEXT_OUTPUT_FILE)
$(OBJCOPY) -j .ram_image2.entry -j .ram_image2.text -j .ram_image2.data -Obinary $(LINK_OUTPUT_FILE) $(DATA_OUTPUT_FILE)
$(PYTHON) $(SOURCE_ROOT)/platform/mcu/rtl8710bn/pick.py $(TEXT_OUTPUT_FILE) $(DATA_OUTPUT_FILE) $(BIN_OUTPUT_FILE)
$(RM) $(TEXT_OUTPUT_FILE) $(DATA_OUTPUT_FILE)
$(RM) $(LINK_OUTPUT_FILE:$(LINK_OUTPUT_SUFFIX)=.xip2$(LINK_OUTPUT_SUFFIX)) $(LINK_OUTPUT_FILE:$(LINK_OUTPUT_SUFFIX)=.xip2.stripped$(LINK_OUTPUT_SUFFIX)) $(LINK_OUTPUT_FILE:$(LINK_OUTPUT_SUFFIX)=.xip2$(BIN_OUTPUT_SUFFIX))
GEN_COMMON_BIN_OUTPUT_FILE_SCRIPT:= $(SCRIPTS_PATH)/gen_common_bin_output_file.py
ALL_BIN_OUTPUT_FILE :=$(LINK_OUTPUT_FILE:$(LINK_OUTPUT_SUFFIX)=.all$(BIN_OUTPUT_SUFFIX))
OTA_BIN_OUTPUT_FILE :=$(LINK_OUTPUT_FILE:$(LINK_OUTPUT_SUFFIX)=.ota$(BIN_OUTPUT_SUFFIX))
all_bin: image_xip
$(QUIET)$(ECHO) Generate $(ALL_BIN_OUTPUT_FILE) ...
$(QUIET)$(RM) $(ALL_BIN_OUTPUT_FILE)
$(PYTHON) $(GEN_COMMON_BIN_OUTPUT_FILE_SCRIPT) -o $(ALL_BIN_OUTPUT_FILE) -f 0x000000 $(SOURCE_ROOT)board/mk3080/boot.bin
$(PYTHON) $(GEN_COMMON_BIN_OUTPUT_FILE_SCRIPT) -o $(ALL_BIN_OUTPUT_FILE) -f 0x013000 $(BIN_OUTPUT_FILE)
$(PYTHON) $(GEN_COMMON_BIN_OUTPUT_FILE_SCRIPT) -o $(ALL_BIN_OUTPUT_FILE) -f 0x0D0000 $(SOURCE_ROOT)board/mk3080/ate.bin
ota_bin: $(BIN_OUTPUT_FILE)
$(CP) $(BIN_OUTPUT_FILE) $(OTA_BIN_OUTPUT_FILE)

View file

@ -0,0 +1,32 @@
# Date : 2018/07/26
# Author : Snow Yang
# Mail : yangsw@mxchip.com
import sys
from struct import pack
textimage = sys.argv[1]
dataimage = sys.argv[2]
outimage = sys.argv[3]
image = b''
with open(textimage, 'rb') as f:
data = f.read()
size = len(data)
image += b'81958711'
image += pack('<L', size)
image += pack('<L', 0)
image += b'\xFF'*16
image += data
with open(dataimage, 'rb') as f:
data = f.read()
size = len(data)
image += b'81958711'
image += pack('<L', size)
image += pack('<L', 0x1000D000)
image += b'\xFF'*16
image += data
image = image[:0x10] + pack('<L', len(image)) + image[0x14:]
with open(outimage, 'wb') as f:
f.write(image)

View file

@ -0,0 +1,208 @@
#
# UNPUBLISHED PROPRIETARY SOURCE CODE
# Copyright (c) 2016 MXCHIP Inc.
#
# The contents of this file may not be disclosed to third parties, copied or
# duplicated in any form, in whole or in part, without the prior written
# permission of MXCHIP Corporation.
#
NAME := rtl8710bn
HOST_OPENOCD := rtl8710bn
#SPI_WIFI_ENABLED := true
$(NAME)_TYPE := kernel
$(NAME)_COMPONENTS += platform/arch/arm/armv7m
#$(NAME)_COMPONENTS += libc rhino hal netmgr framework.common mbedtls cjson cli digest_algorithm
$(NAME)_COMPONENTS += libc rhino hal netmgr framework.common cli digest_algorithm protocols.net
#$(NAME)_COMPONENTS += alicrypto
#$(NAME)_COMPONENTS += protocols.mesh
$(NAME)_COMPONENTS += platform/mcu/rtl8710bn/sdk
$(NAME)_COMPONENTS += platform/mcu/rtl8710bn/peripherals
#GLOBAL_LDFLAGS += -L $(SOURCE_ROOT)/platform/mcu/rtl8710bn
#GLOBAL_LDFLAGS += -I $(SOURCE_ROOT)/platform/mcu/rtl8710bn
#GLOBAL_LDFLAGS += -I $(SOURCE_ROOT)\kernel\rhino\core\include
GLOBAL_DEFINES += CONFIG_AOS_KV_MULTIPTN_MODE
GLOBAL_DEFINES += CONFIG_AOS_KV_PTN=6
GLOBAL_DEFINES += CONFIG_AOS_KV_SECOND_PTN=7
GLOBAL_DEFINES += CONFIG_AOS_KV_PTN_SIZE=4096
GLOBAL_DEFINES += CONFIG_AOS_KV_BUFFER_SIZE=8192
GLOBAL_DEFINES += CONFIG_AOS_CLI_STACK_SIZE=4096
#GLOBAL_DEFINES += WITH_LWIP
GLOBAL_INCLUDES += ../../arch/arm/armv7m/gcc/m4
#GLOBAL_INCLUDES += ../../../board/amebaz_dev
GLOBAL_INCLUDES += .
GLOBAL_INCLUDES += arch
GLOBAL_INCLUDES += sdk
GLOBAL_INCLUDES += aos
GLOBAL_INCLUDES += peripherals
GLOBAL_INCLUDES += ../include
GLOBAL_INCLUDES += ../../../include/hal/soc
GLOBAL_INCLUDES += ../../../kernel/protocols/net/include
GLOBAL_INCLUDES += ../../../kernel/protocols/net/include/lwip
$(NAME)_INCLUDES += .
$(NAME)_INCLUDES += ../include
$(NAME)_INCLUDES += ../../../include/hal/soc
$(NAME)_INCLUDES += ../../../kernel/protocols/net/include
$(NAME)_INCLUDES += ../../../kernel/protocols/net/include/lwip
$(NAME)_INCLUDES += arch
$(NAME)_INCLUDES += aos
$(NAME)_INCLUDES += peripherals
$(NAME)_INCLUDES += sdk
$(NAME)_INCLUDES += sdk/project/realtek_amebaz_va0_example/inc
$(NAME)_INCLUDES += sdk/component/os/os_dep/include
$(NAME)_INCLUDES += sdk/component/common/api/network/include
$(NAME)_INCLUDES += sdk/component/common/api
$(NAME)_INCLUDES += sdk/component/common/api/at_cmd
$(NAME)_INCLUDES += sdk/component/common/api/platform
$(NAME)_INCLUDES += sdk/component/common/api/wifi
$(NAME)_INCLUDES += sdk/component/common/api/wifi/rtw_wpa_supplicant/src
$(NAME)_INCLUDES += sdk/component/common/api/wifi/rtw_wowlan
$(NAME)_INCLUDES += sdk/component/common/api/wifi/rtw_wpa_supplicant/wpa_supplicant
$(NAME)_INCLUDES += sdk/component/common/drivers/modules
$(NAME)_INCLUDES += sdk/component/common/drivers/sdio/realtek/sdio_host/inc
$(NAME)_INCLUDES += sdk/component/common/drivers/inic/rtl8711b
$(NAME)_INCLUDES += sdk/component/common/drivers/usb_class/device
$(NAME)_INCLUDES += sdk/component/common/drivers/usb_class/device/class
$(NAME)_INCLUDES += sdk/component/common/drivers/wlan/realtek/include
$(NAME)_INCLUDES += sdk/component/common/drivers/wlan/realtek/src/osdep
$(NAME)_INCLUDES += sdk/component/common/drivers/wlan/realtek/src/hci
$(NAME)_INCLUDES += sdk/component/common/drivers/wlan/realtek/src/hal
$(NAME)_INCLUDES += sdk/component/common/drivers/wlan/realtek/src/hal/rtl8711b
$(NAME)_INCLUDES += sdk/component/common/drivers/wlan/realtek/src/hal/OUTSRC
$(NAME)_INCLUDES += sdk/component/common/drivers/wlan/realtek/wlan_ram_map/rom
$(NAME)_INCLUDES += sdk/component/common/network
$(NAME)_INCLUDES += sdk/component/soc/realtek/8711b/app/monitor/include
$(NAME)_INCLUDES += sdk/component/soc/realtek/8711b/cmsis
$(NAME)_INCLUDES += sdk/component/soc/realtek/8711b/cmsis/device
$(NAME)_INCLUDES += sdk/component/soc/realtek/8711b/fwlib
$(NAME)_INCLUDES += sdk/component/soc/realtek/8711b/fwlib/include
$(NAME)_INCLUDES += sdk/component/soc/realtek/8711b/fwlib/ram_lib/crypto
$(NAME)_INCLUDES += sdk/component/soc/realtek/8711b/fwlib/rom_lib
$(NAME)_INCLUDES += sdk/component/soc/realtek/8711b/swlib/os_dep/include
$(NAME)_INCLUDES += sdk/component/soc/realtek/8711b/swlib/std_lib/include
$(NAME)_INCLUDES += sdk/component/soc/realtek/8711b/swlib/std_lib/libc/include
$(NAME)_INCLUDES += sdk/component/soc/realtek/8711b/swlib/std_lib/libc/rom/string
$(NAME)_INCLUDES += sdk/component/soc/realtek/8711b/swlib/std_lib/libgcc/rtl8195a/include
$(NAME)_INCLUDES += sdk/component/soc/realtek/8711b/swlib/rtl_lib
$(NAME)_INCLUDES += sdk/component/soc/realtek/8711b/misc
$(NAME)_INCLUDES += sdk/component/soc/realtek/8711b/misc/os
$(NAME)_INCLUDES += sdk/component/common/mbed/api
$(NAME)_INCLUDES += sdk/component/common/mbed/hal
$(NAME)_INCLUDES += sdk/component/common/mbed/hal_ext
$(NAME)_INCLUDES += sdk/component/common/mbed/targets/cmsis/rtl8711b
$(NAME)_INCLUDES += sdk/component/common/mbed/targets/hal/rtl8711b
GLOBAL_CFLAGS += -mcpu=cortex-m4 \
-march=armv7-m \
-mthumb -mthumb-interwork \
-mlittle-endian \
-DCONFIG_PLATFORM_8711B \
-DM3\
-DHardFault_Handler=Ali_HardFault_Handler
GLOBAL_ASMFLAGS += -DHardFault_Handler=Ali_HardFault_Handler
GLOBAL_CFLAGS += -w
GLOBAL_LDFLAGS += -L $(SOURCE_ROOT)/platform/mcu/rtl8710bn
#GLOBAL_LDFLAGS += -I $(SOURCE_ROOT)/platform/mcu/rtl8710bn
ifeq ($(CONFIG_BOARD_NAME), AMEBAZ)
# GLOBAL_LDFLAGS += -T $(SOURCE_ROOT)/platform/mcu/rtl8710bn/script/rlx8711B-symbol-v02-img2_xip1.ld
else
GLOBAL_LDFLAGS += -T $(SOURCE_ROOT)/platform/mcu/rtl8710bn/script/rlx8711B-symbol-v02-img2_xip1_mxchip.ld
endif
#GLOBAL_LDFLAGS += $(SOURCE_ROOT)/platform/mcu/rtl8710bn/bin/boot_all.o
GLOBAL_LDFLAGS += -L$(SOURCE_ROOT)/platform/mcu/rtl8710bn/lib/ -l_platform -l_wlan -l_wps -l_p2p -l_rtlstd
#GLOBAL_LDFLAGS += -mcpu=cortex-m4 \
-mthumb -mthumb-interwork \
-mlittle-endian \
-nostartfiles \
--specs=nosys.specs \
-mfpu=fpv4-sp-d16 \
-mfloat-abi=hard \
-Wl,--no-enum-size-warning \
-Wl,--no-wchar-size-warning \
$(CLIB_LDFLAGS_NANO_FLOAT)
GLOBAL_LDFLAGS += -mcpu=cortex-m4 \
-mthumb\
-Os \
-nostartfiles \
-Wl,--no-enum-size-warning \
-Wl,--no-wchar-size-warning \
-Wl,--gc-sections \
-Wl,--cref \
$(CLIB_LDFLAGS_NANO_FLOAT)
$(NAME)_CFLAGS += -Wall -Werror -Wno-unused-variable -Wno-unused-parameter -Wno-implicit-function-declaration
$(NAME)_CFLAGS += -Wno-type-limits -Wno-sign-compare -Wno-pointer-sign -Wno-uninitialized
$(NAME)_CFLAGS += -Wno-return-type -Wno-unused-function -Wno-unused-but-set-variable
$(NAME)_CFLAGS += -Wno-unused-value -Wno-strict-aliasing
#$(NAME)_SOURCES += aos/soc_impl.c
#$(NAME)_SOURCES += aos/trace_impl.c
#$(NAME)_SOURCES += aos/aos.c
#$(NAME)_SOURCES += soc_impl.c
#$(NAME)_INCLUDES += ../../../kernel/vcall/mico/include
#$(NAME)_INCLUDES += ../../../framework/protocol/alink/os/platform
#$(NAME)_INCLUDES += ../include
#$(NAME)_INCLUDES += ../../../include/hal/soc
#$(NAME)_INCLUDES += ../../../include/aos
#$(NAME)_INCLUDES += arch
#$(NAME)_INCLUDES += peripherals
$(NAME)_SOURCES := aos/soc_impl.c \
aos/trace_impl.c \
aos/aos.c \
aos/aos_osdep.c \
aos/ethernetif.c \
aos/qc.c \
hal/uart.c \
hal/flash.c \
hal/hw.c \
hal/wifi_port.c \
hal/gpio.c \
hal/wdg.c \
hal/pwm.c
ifeq ($(CONFIG_BOARD_NAME), AMEBAZ)
$(NAME)_SOURCES += hal/ota_port.c
else
$(NAME)_SOURCES += hal/ota.c
endif
#$(NAME)_SOURCES += hal/uart.c
#$(NAME)_SOURCES += hal/flash.c
#$(NAME)_SOURCES += hal/hw.c
#$(NAME)_SOURCES += hal/wifi_port.c
#$(NAME)_SOURCES += hal/misc.c
$(NAME)_SOURCES += hal/pwrmgmt_hal/board_cpu_pwr_rtc.c
$(NAME)_SOURCES += hal/pwrmgmt_hal/board_cpu_pwr_systick.c
$(NAME)_SOURCES += hal/pwrmgmt_hal/board_cpu_pwr.c
#$(NAME)_COMPONENTS += platform/mcu/rtl8710bn/peripherals
ifeq ($(CONFIG_BOARD_NAME), AMEBAZ)
PING_PONG_OTA := 1
ifeq ($(PING_PONG_OTA),1)
AOS_IMG1_XIP1_LD_FILE += platform/mcu/rtl8710bn/script/rlx8711B-symbol-v02-img2_xip1.ld
AOS_IMG2_XIP2_LD_FILE += platform/mcu/rtl8710bn/script/rlx8711B-symbol-v02-img2_xip2.ld
else
GLOBAL_LDS_FILES += platform/mcu/rtl8710bn/script/rlx8711B-symbol-v02-img2_xip1.ld
endif
endif

View file

@ -0,0 +1,15 @@
SECTIONS
{
/* Bootloader list */
BOOT_FLASH_RDP_VALID = 0x08000127;
BOOT_FLASH_Image1 = 0x080003f7;
IMAGE1$$Base = 0x10002001;
RamStartTable = 0x10002001;
RAM_IMG1_VALID_PATTEN = 0x10002019;
boot_export_symbol = 0x10002021;
BOOT_System_Init1 = 0x10002259;
BOOT_System_Init2 = 0x1000226b;
BOOT_Swd_Off = 0x1000227d;
boot_ram_end = 0x10002475;
IMAGE1$$Limit = 0x10002479;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,82 @@
#!/bin/sh
export PATH=${PATH}:$5
ota_idx=$1
#dir=/home/cwhaiyi/pcshare/rualxw/AliOS-Things/platform/mcu/rtl8710bn
platform_dir=$2/platform/mcu/rtl8710bn
if [ ! -d "${platform_dir}/Debug/Exe" ]; then
mkdir -p ${platform_dir}/Debug/Exe
fi
BIN_DIR=${platform_dir}/Debug/Exe
outputname=$3@$4
outputdir=$2/out/${outputname}/binary
OS=`uname -s`
PICK=${platform_dir}/tools/pick
PAD=${platform_dir}/tools/padding
CHKSUM=${platform_dir}/tools/checksum
OTA=${platform_dir}/tools/ota
echo ${platform_dir}
echo ""
echo -n "install dependent software packages ..."
if [ "$OS" = "Darwin" ]; then
if [ "`which gawk`" = "" ];then
sudo easy_install gawk > /dev/null
fi
else #Some Linux version
if [ "`which apt-get`" != "" ]; then
if [ "`which gawk`" = "" ];then
sudo sudo apt-get -y install gawk > /dev/null
fi
fi
fi
find ${BIN_DIR}/ -name "*.axf" | xargs rm -rf
find ${BIN_DIR}/ -name "*.map" | xargs rm -rf
if [ "${ota_idx}" = "1" ]; then
cp ${outputdir}/${outputname}.elf ${BIN_DIR}/${outputname}.axf
else
cp ${outputdir}/${outputname}.xip2.elf ${BIN_DIR}/${outputname}.axf
fi
arm-none-eabi-nm ${BIN_DIR}/${outputname}.axf | sort > ${BIN_DIR}/${outputname}.nmap
arm-none-eabi-objcopy -j .ram_image2.entry -j .ram_image2.data -j .ram_image2.text -j .ram_image2.bss -j .ram_image2.skb.bss -j .ram_heap.data -Obinary ${BIN_DIR}/${outputname}.axf ${BIN_DIR}/ram_2.r.bin
arm-none-eabi-objcopy -j .xip_image2.text -Obinary ${BIN_DIR}/${outputname}.axf ${BIN_DIR}/xip_image2.bin
arm-none-eabi-objcopy -j .ram_rdp.text -Obinary ${BIN_DIR}/${outputname}.axf ${BIN_DIR}/rdp.bin
if [ ! -f "${BIN_DIR}/bin/boot_all.bin" ]; then
cp ${platform_dir}/bin/boot_all.bin ${BIN_DIR}/boot_all.bin
fi
chmod 777 ${BIN_DIR}/boot_all.bin
chmod +rx ${PICK} ${CHKSUM} ${PAD} ${OTA}
${PICK} 0x`grep __ram_image2_text_start__ ${BIN_DIR}/${outputname}.nmap | gawk '{print $1}'` 0x`grep __ram_image2_text_end__ ${BIN_DIR}/${outputname}.nmap | gawk '{print $1}'` ${BIN_DIR}/ram_2.r.bin ${BIN_DIR}/ram_2.bin raw
${PICK} 0x`grep __ram_image2_text_start__ ${BIN_DIR}/${outputname}.nmap | gawk '{print $1}'` 0x`grep __ram_image2_text_end__ ${BIN_DIR}/${outputname}.nmap | gawk '{print $1}'` ${BIN_DIR}/ram_2.bin ${BIN_DIR}/ram_2.p.bin
${PICK} 0x`grep __xip_image2_start__ ${BIN_DIR}/${outputname}.nmap | gawk '{print $1}'` 0x`grep __xip_image2_start__ ${BIN_DIR}/${outputname}.nmap | gawk '{print $1}'` ${BIN_DIR}/xip_image2.bin ${BIN_DIR}/xip_image2.p.bin
IMAGE2_OTA1=image2_all_app1.bin
IMAGE2_OTA2=image2_all_app2.bin
OTA_ALL=ota_all.bin
if [ "${ota_idx}" = "1" ]; then
cat ${BIN_DIR}/xip_image2.p.bin > ${BIN_DIR}/${IMAGE2_OTA1}
chmod 777 ${BIN_DIR}/${IMAGE2_OTA1}
cat ${BIN_DIR}/ram_2.p.bin >> ${BIN_DIR}/${IMAGE2_OTA1}
${CHKSUM} ${BIN_DIR}/${IMAGE2_OTA1} || true
rm ${BIN_DIR}/xip_image2.p.bin ${BIN_DIR}/ram_2.p.bin
cp ${platform_dir}/bin/boot_all.bin ${outputdir}/boot_all.bin
cp ${BIN_DIR}/${IMAGE2_OTA1} ${outputdir}/${IMAGE2_OTA1}
elif [ "${ota_idx}" = "2" ]; then
cat ${BIN_DIR}/xip_image2.p.bin > ${BIN_DIR}/${IMAGE2_OTA2}
chmod 777 ${BIN_DIR}/${IMAGE2_OTA2}
cat ${BIN_DIR}/ram_2.p.bin >> ${BIN_DIR}/${IMAGE2_OTA2}
${CHKSUM} ${BIN_DIR}/${IMAGE2_OTA2} || true
${OTA} ${BIN_DIR}/${IMAGE2_OTA1} 0x800B000 ${BIN_DIR}/${IMAGE2_OTA2} 0x08100000 0x20170111 ${BIN_DIR}/${OTA_ALL}
cp ${platform_dir}/bin/boot_all.bin ${outputdir}/boot_all.bin
cp ${BIN_DIR}/${IMAGE2_OTA2} ${outputdir}/${IMAGE2_OTA2}
cp ${BIN_DIR}/${OTA_ALL} ${outputdir}/${OTA_ALL}
else
echo===========================================================
echo “ota_idx must be "1" or "2"
echo===========================================================
fi
#rm -f ${BIN_DIR}/ram_2.bin ${BIN_DIR}/ram_2.p.bin ${BIN_DIR}/ram_2.r.bin ${BIN_DIR}/xip_image2.bin ${BIN_DIR}/xip_image2.p.bin

View file

@ -0,0 +1,123 @@
cd /D %2\platform\mcu\rtl8710bn\
::echo %1 %2 %3 %4 > tmp3.txt
set rootdir=%2
set amebazdir=%2\platform\mcu\rtl8710bn
set tooldir=%2\platform\mcu\rtl8710bn\tools
set libdir=%2\platform\mcu\rtl8710bn\lib
set bindir=%2\platform\mcu\rtl8710bn\Debug\Exe
set ota_bin_ver=0x%date:~0,4%%date:~5,2%%date:~8,2%
set ota_offset=%1
set outputname=%3@%4
set outputdir=%2\out\%outputname%\binary
::echo %outputdir% >tmp2.txt
::echo %outputname% >tmp4.txt
::echo input1=%1 >tmp.txt
::echo input2=%2 >>tmp.txt
::echo ota_bin_ver=%ota_bin_ver% >>tmp.txt
IF NOT EXIST %bindir% MD %bindir%
if "%ota_offset%"=="0x0800B000" (
copy %outputdir%\%outputname%.elf %bindir%\Application.axf
) else (
copy %outputdir%\%outputname%.xip2.elf %bindir%\Application.axf
)
del Debug\Exe\target.map Debug\Exe\application.asm
%tooldir%\nm ./Debug/Exe/application.axf | %tooldir%\sort > ./Debug/Exe/application.map
%tooldir%\objdump -d ./Debug/Exe/application.axf > ./Debug/Exe/application.asm
for /f "delims=" %%i in ('cmd /c "%tooldir%\grep __ram_image2_text_start__ ./Debug/Exe/application.map | %tooldir%\gawk '{print $1}'"') do set ram2_start=0x%%i
for /f "delims=" %%i in ('cmd /c "%tooldir%\grep __ram_image2_text_end__ ./Debug/Exe/application.map | %tooldir%\gawk '{print $1}'"') do set ram2_end=0x%%i
for /f "delims=" %%i in ('cmd /c "%tooldir%\grep __xip_image2_start__ ./Debug/Exe/application.map | %tooldir%\gawk '{print $1}'"') do set xip_image2_start=0x%%i
for /f "delims=" %%i in ('cmd /c "%tooldir%\grep __xip_image2_end__ ./Debug/Exe/application.map | %tooldir%\gawk '{print $1}'"') do set xip_image2_end=0x%%i
::echo ram2_start: %ram2_start% > tmp.txt
::echo ram2_end: %ram2_end% >> tmp.txt
::echo xip_image2_start: %xip_image2_start% >> tmp.txt
::echo xip_image2_end: %xip_image2_end% >> tmp.txt
::findstr /rg "place" Debug\List\application.map > tmp.txt
::setlocal enabledelayedexpansion
::for /f "delims=:" %%i in ('findstr /rg "0x1000" tmp.txt') do (
:: set "var=%%i"
:: set "sectname_ram2=!var:~1,2!"
::)
::for /f "delims=:" %%i in ('findstr /rg "xip_image2.text" tmp.txt') do (
:: set "var=%%i"
:: set "sectname_xip=!var:~1,2!"
::)
::for /f "delims=:" %%i in ('findstr /rg "0x1003f000" tmp.txt') do (
:: set "var=%%i"
:: set "sectname_rdp=!var:~1,2!"
::)
::setlocal disabledelayedexpansion
::del tmp.txt
::echo sectname_ram2: %sectname_ram2% sectname_xip: %sectname_xip% sectname_rdp: %sectname_rdp% >tmp1.txt
%tooldir%\objcopy -j .ram_image2.entry -j .ram_image2.data -j .ram_image2.text -j .ram_image2.bss -j .ram_image2.skb.bss -j .ram_heap.data -Obinary ./Debug/Exe/application.axf ./Debug/Exe/ram_2.r.bin
%tooldir%\objcopy -j .xip_image2.text -Obinary ./Debug/Exe/application.axf ./Debug/Exe/xip_image2.bin
%tooldir%\objcopy -j .ram_rdp.text -Obinary ./Debug/Exe/application.axf ./Debug/Exe/rdp.bin
:: remove bss sections
%tooldir%\pick %ram2_start% %ram2_end% %bindir%\ram_2.r.bin %bindir%\ram_2.bin raw
del %bindir%\ram_2.r.bin
:: add header
%tooldir%\pick %ram2_start% %ram2_end% %bindir%\ram_2.bin %bindir%\ram_2.p.bin
::%tooldir%\pick %xip_image2_start% %xip_image2_end% Debug\Exe\xip_image2.bin Debug\Exe\xip_image2.p.bin
%tooldir%\pick 0 0 %bindir%\xip_image2.bin %bindir%\xip_image2.p.bin
:: get ota_idx and ota_offset from image2.icf
::setlocal enabledelayedexpansion
::findstr /rg "__ICFEDIT_region_XIP_OTA1_start__" image2.icf>test.txt
::for /f "tokens=1,2,3,4,5*" %%i in ('findstr /rg "symbol" test.txt') do (
:: set "var=%%m"
:: set "ota_offset=!var:~0,10!"
::)
::setlocal disabledelayedexpansion
if "%ota_offset%"=="0x0800B000" (
set ota_idx=1
) else (
set ota_idx=2
)
::del test.txt
::echo ota_idx=%ota_idx% >tmp.txt
::echo ota_offset=%ota_offset% >>tmp.txt
:: aggregate image2_all.bin and add checksum
if "%ota_idx%"=="2" (
copy /b %bindir%\xip_image2.p.bin+%bindir%\ram_2.p.bin %bindir%\image2_all_ota2.bin
%tooldir%\checksum %bindir%\image2_all_ota2.bin
%tooldir%\ota %bindir%\image2_all_ota1.bin 0x800B000 %bindir%\image2_all_ota2.bin %ota_offset% %ota_bin_ver% Debug\Exe\ota_all.bin
) else (
copy /b %bindir%\xip_image2.p.bin+%bindir%\ram_2.p.bin %bindir%\image2_all_ota1.bin
%tooldir%\checksum %bindir%\image2_all_ota1.bin
)
del Debug\Exe\ram_2.bin
del Debug\Exe\ram_2.p.bin
del Debug\Exe\xip_image2.bin
del Debug\Exe\xip_image2.p.bin
:: force update boot_all.bin
:: del Debug\Exe\boot_all.bin
:: check boot_all.bin exist, copy default
if not exist Debug\Exe\boot_all.bin (
copy %amebazdir%\bin\boot_all.bin %bindir%\boot_all.bin
)
if "%ota_idx%"=="2" (
copy %bindir%\image2_all_ota2.bin %outputdir%\image2_all_ota2.bin
copy %bindir%\ota_all.bin %outputdir%\ota_all.bin
) else (
copy %bindir%\boot_all.bin %outputdir%\boot_all.bin
copy %bindir%\image2_all_ota1.bin %outputdir%\image2_all_ota1.bin
)
:: board generator
::%tooldir%\..\gen_board_img2.bat %ram2_start% %ram2_end%
exit

View file

@ -0,0 +1,5 @@
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmd /c "+WScript.Arguments.Item(1)+"postbuild_img2.bat "+WScript.Arguments.Item(0)+" "+WScript.Arguments.Item(1), 0

View file

@ -0,0 +1,156 @@
ENTRY(Reset_Handler)
INCLUDE "script/export-rom_symbol_v01.txt"
MEMORY
{
ROM (rx) : ORIGIN = 0x00000000, LENGTH = 0x80000 /* ROM: 512k */
ROMBSS_RAM (rw) : ORIGIN = 0x10000000, LENGTH = 0x2000 /* ROM BSS RAM: 8K */
BOOTLOADER_RAM (rwx) : ORIGIN = 0x10002000, LENGTH = 0x3000 /* BOOT Loader RAM: 12K */
BD_RAM (rwx) : ORIGIN = 0x10005000, LENGTH = 0x39000 /* MAIN RAM: 228 */
MSP_RAM (wx) : ORIGIN = 0x1003E000, LENGTH = 0x1000 /* MSP RAM: 4k */
RDP_RAM (wx) : ORIGIN = 0x1003F000, LENGTH = 0xFF0 /* RDP RAM: 4k-0x10 */
XIPBOOT (rx) : ORIGIN = 0x08000000+0x20, LENGTH = 0x04000-0x20 /* XIPBOOT: 32k, 32 Bytes resvd for header*/
XIPSYS (r) : ORIGIN = 0x08009000, LENGTH = 0x1000 /* XIPSYS: 4K system data in flash */
XIPCAL (r) : ORIGIN = 0x0800A000, LENGTH = 0x1000 /* XIPCAL: 4K calibration data in flash */
XIP1 (rx) : ORIGIN = 0x0800B000+0x20, LENGTH = 0x75000-0x20 /* XIP1: 468k, 32 Bytes resvd for header */
XIP2 (rx) : ORIGIN = 0x08080000+0x20, LENGTH = 0x75000-0x20 /* XIP1: 468k, 32 Bytes resvd for header */
}
SECTIONS
{
.rom.text : { } > ROM
.rom.rodata : { } > ROM
.hal.rom.bss : { } > ROMBSS_RAM
/* image1 entry, this section should in RAM and fixed address for ROM */
.ram_image1.entry :
{
__ram_image1_text_start__ = .;
__ram_start_table_start__ = .;
KEEP(*(SORT(.image1.entry.data*)))
__ram_start_table_end__ = .;
__image1_validate_code__ = .;
KEEP(*(.image1.validate.rodata*))
} > BOOTLOADER_RAM
/* Add . to assign the start address of the section */
/* to prevent the change of the start address by ld doing section alignment */
.ram_image1.text . :
{
/* image1 text */
*(.boot.ram.text*)
*(.boot.rodata*)
} > BOOTLOADER_RAM
.ram_image1.data . :
{
__ram_image1_data_start__ = .;
KEEP(*(.boot.ram.data*))
__ram_image1_data_end__ = .;
__ram_image1_text_end__ = .;
} > BOOTLOADER_RAM
.ram_image1.bss . :
{
__image1_bss_start__ = .;
KEEP(*(.boot.ram.bss*))
KEEP(*(.boot.ram.end.bss*))
__image1_bss_end__ = .;
} > BOOTLOADER_RAM
.ram_image2.entry :
{
__ram_image2_text_start__ = .;
__image2_entry_func__ = .;
KEEP(*(SORT(.image2.entry.data*)))
__image2_validate_code__ = .;
KEEP(*(.image2.validate.rodata*))
} > BD_RAM
.ram_image2.text :
{
KEEP(*(.image2.ram.text*))
} > BD_RAM
.ram_image2.data :
{
__data_start__ = .;
*(.data*)
__data_end__ = .;
__ram_image2_text_end__ = .;
. = ALIGN(16);
} > BD_RAM
.ram_image2.bss :
{
__bss_start__ = .;
*(.bss*)
*(COMMON)
} > BD_RAM
.ram_image2.skb.bss :
{
*(.bdsram.data*)
__bss_end__ = .;
} > BD_RAM
.ram_heap.data :
{
*(.bfsram.data*)
*(.heap.stdlib*)
} > BD_RAM
.ram_rdp.text :
{
__rom_top_4k_start_ = .;
__rdp_text_start__ = .;
KEEP(*(.rdp.ram.text*))
KEEP(*(.rdp.ram.data*))
__rdp_text_end__ = .;
. = ALIGN(16);
} > RDP_RAM
.xip_image1.text :
{
__flash_boot_text_start__ = .;
*(.flashboot.text*)
__flash_boot_text_end__ = .;
. = ALIGN(16);
} > XIPBOOT
.xip_image2.text :
{
__flash_text_start__ = .;
*(.img2_custom_signature*)
*(.text*)
*(.rodata*)
*(.debug_trace*)
__flash_text_end__ = .;
. = ALIGN (16);
} > XIP1
}
SECTIONS
{
/* Bootloader symbol list */
boot_export_symbol = 0x10002020;
}

View file

@ -0,0 +1,182 @@
ENTRY(Reset_Handler)
INCLUDE "script/export-rom_symbol_v01.txt"
GROUP (
libgcc.a
libc.a
libg.a
libm.a
libnosys.a
)
MEMORY
{
ROM (rx) : ORIGIN = 0x00000000, LENGTH = 0x80000 /* ROM: 512k */
ROMBSS_RAM (rw) : ORIGIN = 0x10000000, LENGTH = 0x2000 /* ROM BSS RAM: 8K */
BOOTLOADER_RAM (rwx) : ORIGIN = 0x10002000, LENGTH = 0x3000 /* BOOT Loader RAM: 12K */
BD_RAM (rwx) : ORIGIN = 0x10005000, LENGTH = 0x38000 /* MAIN RAM: 228 */
ROM_BSS_RAM (rwx) : ORIGIN = 0x1003D000, LENGTH = 0x1000 /* ROM BSS RAM: 4K */
MSP_RAM (wx) : ORIGIN = 0x1003E000, LENGTH = 0x1000 /* MSP RAM: 4k */
RDP_RAM (wx) : ORIGIN = 0x1003F000, LENGTH = 0xFF0 /* RDP RAM: 4k-0x10 */
XIPBOOT (rx) : ORIGIN = 0x08000000+0x20, LENGTH = 0x04000-0x20 /* XIPBOOT: 32k, 32 Bytes resvd for header*/
XIPSYS (r) : ORIGIN = 0x08009000, LENGTH = 0x1000 /* XIPSYS: 4K system data in flash */
XIPCAL (r) : ORIGIN = 0x0800A000, LENGTH = 0x1000 /* XIPCAL: 4K calibration data in flash */
XIP1 (rx) : ORIGIN = 0x0800B000+0x20, LENGTH = 0xF2000-0x20 /* XIP1: 968k, 32 Bytes resvd for header */
XIP2 (rx) : ORIGIN = 0x08100000+0x20, LENGTH = 0xF2000-0x20 /* XIP2: 968k, 32 Bytes resvd for header */
}
SECTIONS
{
.rom.text : { } > ROM
.rom.rodata : { } > ROM
.ARM.exidx :
{
__exidx_start = .;
*(.ARM.exidx*)
*(.gnu.linkonce.armexidx.*)
__exidx_end = .;
} > ROM
.hal.rom.bss : { } > ROMBSS_RAM
/* image1 entry, this section should in RAM and fixed address for ROM */
.ram_image1.entry :
{
__ram_image1_text_start__ = .;
__ram_start_table_start__ = .;
KEEP(*(SORT(.image1.entry.data*)))
__ram_start_table_end__ = .;
__image1_validate_code__ = .;
KEEP(*(.image1.validate.rodata*))
KEEP(*(.image1.export.symb*))
} > BOOTLOADER_RAM
/* Add . to assign the start address of the section */
/* to prevent the change of the start address by ld doing section alignment */
.ram_image1.text . :
{
/* image1 text */
*(.boot.ram.text*)
*(.boot.rodata*)
} > BOOTLOADER_RAM
.ram_image1.data . :
{
__ram_image1_data_start__ = .;
KEEP(*(.boot.ram.data*))
__ram_image1_data_end__ = .;
__ram_image1_text_end__ = .;
} > BOOTLOADER_RAM
.ram_image1.bss . :
{
__image1_bss_start__ = .;
KEEP(*(.boot.ram.bss*))
KEEP(*(.boot.ram.end.bss*))
__image1_bss_end__ = .;
} > BOOTLOADER_RAM
.ram_image2.entry :
{
__ram_image2_text_start__ = .;
__image2_entry_func__ = .;
KEEP(*(SORT(.image2.entry.data*)))
__image2_validate_code__ = .;
KEEP(*(.image2.validate.rodata*))
} > BD_RAM
.ram_image2.text :
{
KEEP(*(.image2.ram.text*))
} > BD_RAM
.ram_image2.data :
{
__data_start__ = .;
*(.data*)
__data_end__ = .;
__ram_image2_text_end__ = .;
. = ALIGN(16);
} > BD_RAM
.ram_image2.bss :
{
__bss_start__ = .;
*(.bss*)
*(COMMON)
} > BD_RAM
.ram_image2.skb.bss :
{
*(.bdsram.data*)
__bss_end__ = .;
} > BD_RAM
.ram_heap.data :
{
*(.bfsram.data*)
} > BD_RAM
. = ALIGN(8);
PROVIDE(heap_start = .);
PROVIDE(heap_end = 0x1003CFFF);
PROVIDE(heap_len = heap_end - heap_start);
.rom.bss :
{
*(.heap.stdlib*)
} > ROM_BSS_RAM
.ram_rdp.text :
{
__rom_top_4k_start_ = .;
__rdp_text_start__ = .;
KEEP(*(.rdp.ram.text*))
KEEP(*(.rdp.ram.data*))
__rdp_text_end__ = .;
. = ALIGN(16);
} > RDP_RAM
.xip_image1.text :
{
__flash_boot_text_start__ = .;
*(.flashboot.text*)
__flash_boot_text_end__ = .;
. = ALIGN(16);
} > XIPBOOT
.xip_image2.text :
{
__flash_text_start__ = .;
*(.img2_custom_signature*)
*(.text)
*(.text*)
*(.rodata)
*(.rodata*)
*(.debug_trace*)
__flash_text_end__ = .;
. = ALIGN (16);
} > XIP1
}
SECTIONS
{
/* Bootloader symbol list */
boot_export_symbol = 0x10002020;
}

View file

@ -0,0 +1,182 @@
ENTRY(Reset_Handler)
INCLUDE "script/export-rom_symbol_v01.txt"
GROUP (
libgcc.a
libc.a
libg.a
libm.a
libnosys.a
)
MEMORY
{
ROM (rx) : ORIGIN = 0x00000000, LENGTH = 0x80000 /* ROM: 512k */
ROMBSS_RAM (rw) : ORIGIN = 0x10000000, LENGTH = 0x2000 /* ROM BSS RAM: 8K */
BOOTLOADER_RAM (rwx) : ORIGIN = 0x10002000, LENGTH = 0x3000 /* BOOT Loader RAM: 12K */
BD_RAM (rwx) : ORIGIN = 0x1000D000, LENGTH = 0x39000 /* MAIN RAM: 228 */
ROM_BSS_RAM (rwx) : ORIGIN = 0x1003D000, LENGTH = 0x1000 /* ROM BSS RAM: 4K */
MSP_RAM (wx) : ORIGIN = 0x1003E000, LENGTH = 0x1000 /* MSP RAM: 4k */
RDP_RAM (wx) : ORIGIN = 0x1003F000, LENGTH = 0xFF0 /* RDP RAM: 4k-0x10 */
XIPBOOT (rx) : ORIGIN = 0x08000000+0x20, LENGTH = 0x04000-0x20 /* XIPBOOT: 32k, 32 Bytes resvd for header*/
XIPSYS (r) : ORIGIN = 0x08009000, LENGTH = 0x1000 /* XIPSYS: 4K system data in flash */
XIPCAL (r) : ORIGIN = 0x0800A000, LENGTH = 0x1000 /* XIPCAL: 4K calibration data in flash */
XIP1 (rx) : ORIGIN = 0x08013000+0x20, LENGTH = 0xB5000-0x20 /* XIP1: 968k, 32 Bytes resvd for header */
XIP2 (rx) : ORIGIN = 0x08100000+0x20, LENGTH = 0xF2000-0x20 /* XIP2: 968k, 32 Bytes resvd for header */
}
SECTIONS
{
.rom.text : { } > ROM
.rom.rodata : { } > ROM
.ARM.exidx :
{
__exidx_start = .;
*(.ARM.exidx*)
*(.gnu.linkonce.armexidx.*)
__exidx_end = .;
} > ROM
.hal.rom.bss : { } > ROMBSS_RAM
/* image1 entry, this section should in RAM and fixed address for ROM */
.ram_image1.entry :
{
__ram_image1_text_start__ = .;
__ram_start_table_start__ = .;
KEEP(*(SORT(.image1.entry.data*)))
__ram_start_table_end__ = .;
__image1_validate_code__ = .;
KEEP(*(.image1.validate.rodata*))
KEEP(*(.image1.export.symb*))
} > BOOTLOADER_RAM
/* Add . to assign the start address of the section */
/* to prevent the change of the start address by ld doing section alignment */
.ram_image1.text . :
{
/* image1 text */
*(.boot.ram.text*)
*(.boot.rodata*)
} > BOOTLOADER_RAM
.ram_image1.data . :
{
__ram_image1_data_start__ = .;
KEEP(*(.boot.ram.data*))
__ram_image1_data_end__ = .;
__ram_image1_text_end__ = .;
} > BOOTLOADER_RAM
.ram_image1.bss . :
{
__image1_bss_start__ = .;
KEEP(*(.boot.ram.bss*))
KEEP(*(.boot.ram.end.bss*))
__image1_bss_end__ = .;
} > BOOTLOADER_RAM
.ram_image2.entry :
{
__ram_image2_text_start__ = .;
__image2_entry_func__ = .;
KEEP(*(SORT(.image2.entry.data*)))
__image2_validate_code__ = .;
KEEP(*(.image2.validate.rodata*))
} > BD_RAM
.ram_image2.text :
{
KEEP(*(.image2.ram.text*))
} > BD_RAM
.ram_image2.data :
{
__data_start__ = .;
*(.data*)
__data_end__ = .;
__ram_image2_text_end__ = .;
. = ALIGN(16);
} > BD_RAM
.ram_image2.bss :
{
__bss_start__ = .;
*(.bss*)
*(COMMON)
} > BD_RAM
.ram_image2.skb.bss :
{
*(.bdsram.data*)
__bss_end__ = .;
} > BD_RAM
.ram_heap.data :
{
*(.bfsram.data*)
} > BD_RAM
. = ALIGN(8);
PROVIDE(heap_start = .);
PROVIDE(heap_end = 0x1003CFFF);
PROVIDE(heap_len = heap_end - heap_start);
.rom.bss :
{
*(.heap.stdlib*)
} > ROM_BSS_RAM
.ram_rdp.text :
{
__rom_top_4k_start_ = .;
__rdp_text_start__ = .;
KEEP(*(.rdp.ram.text*))
KEEP(*(.rdp.ram.data*))
__rdp_text_end__ = .;
. = ALIGN(16);
} > RDP_RAM
.xip_image1.text :
{
__flash_boot_text_start__ = .;
*(.flashboot.text*)
__flash_boot_text_end__ = .;
. = ALIGN(16);
} > XIPBOOT
.xip_image2.text :
{
__flash_text_start__ = .;
*(.img2_custom_signature*)
*(.text)
*(.text*)
*(.rodata)
*(.rodata*)
*(.debug_trace*)
__flash_text_end__ = .;
. = ALIGN (16);
} > XIP1
}
SECTIONS
{
/* Bootloader symbol list */
boot_export_symbol = 0x10002020;
}

View file

@ -0,0 +1,182 @@
ENTRY(Reset_Handler)
INCLUDE "script/export-rom_symbol_v01.txt"
GROUP (
libgcc.a
libc.a
libg.a
libm.a
libnosys.a
)
MEMORY
{
ROM (rx) : ORIGIN = 0x00000000, LENGTH = 0x80000 /* ROM: 512k */
ROMBSS_RAM (rw) : ORIGIN = 0x10000000, LENGTH = 0x2000 /* ROM BSS RAM: 8K */
BOOTLOADER_RAM (rwx) : ORIGIN = 0x10002000, LENGTH = 0x3000 /* BOOT Loader RAM: 12K */
BD_RAM (rwx) : ORIGIN = 0x10005000, LENGTH = 0x38000 /* MAIN RAM: 228 */
ROM_BSS_RAM (rwx) : ORIGIN = 0x1003D000, LENGTH = 0x1000 /* ROM BSS RAM: 4K */
MSP_RAM (wx) : ORIGIN = 0x1003E000, LENGTH = 0x1000 /* MSP RAM: 4k */
RDP_RAM (wx) : ORIGIN = 0x1003F000, LENGTH = 0xFF0 /* RDP RAM: 4k-0x10 */
XIPBOOT (rx) : ORIGIN = 0x08000000+0x20, LENGTH = 0x04000-0x20 /* XIPBOOT: 32k, 32 Bytes resvd for header*/
XIPSYS (r) : ORIGIN = 0x08009000, LENGTH = 0x1000 /* XIPSYS: 4K system data in flash */
XIPCAL (r) : ORIGIN = 0x0800A000, LENGTH = 0x1000 /* XIPCAL: 4K calibration data in flash */
XIP1 (rx) : ORIGIN = 0x0800B000+0x20, LENGTH = 0xF2000-0x20 /* XIP1: 968k, 32 Bytes resvd for header */
XIP2 (rx) : ORIGIN = 0x08100000+0x20, LENGTH = 0xF2000-0x20 /* XIP2: 968k, 32 Bytes resvd for header */
}
SECTIONS
{
.rom.text : { } > ROM
.rom.rodata : { } > ROM
.ARM.exidx :
{
__exidx_start = .;
*(.ARM.exidx*)
*(.gnu.linkonce.armexidx.*)
__exidx_end = .;
} > ROM
.hal.rom.bss : { } > ROMBSS_RAM
/* image1 entry, this section should in RAM and fixed address for ROM */
.ram_image1.entry :
{
__ram_image1_text_start__ = .;
__ram_start_table_start__ = .;
KEEP(*(SORT(.image1.entry.data*)))
__ram_start_table_end__ = .;
__image1_validate_code__ = .;
KEEP(*(.image1.validate.rodata*))
KEEP(*(.image1.export.symb*))
} > BOOTLOADER_RAM
/* Add . to assign the start address of the section */
/* to prevent the change of the start address by ld doing section alignment */
.ram_image1.text . :
{
/* image1 text */
*(.boot.ram.text*)
*(.boot.rodata*)
} > BOOTLOADER_RAM
.ram_image1.data . :
{
__ram_image1_data_start__ = .;
KEEP(*(.boot.ram.data*))
__ram_image1_data_end__ = .;
__ram_image1_text_end__ = .;
} > BOOTLOADER_RAM
.ram_image1.bss . :
{
__image1_bss_start__ = .;
KEEP(*(.boot.ram.bss*))
KEEP(*(.boot.ram.end.bss*))
__image1_bss_end__ = .;
} > BOOTLOADER_RAM
.ram_image2.entry :
{
__ram_image2_text_start__ = .;
__image2_entry_func__ = .;
KEEP(*(SORT(.image2.entry.data*)))
__image2_validate_code__ = .;
KEEP(*(.image2.validate.rodata*))
} > BD_RAM
.ram_image2.text :
{
KEEP(*(.image2.ram.text*))
} > BD_RAM
.ram_image2.data :
{
__data_start__ = .;
*(.data*)
__data_end__ = .;
__ram_image2_text_end__ = .;
. = ALIGN(16);
} > BD_RAM
.ram_image2.bss :
{
__bss_start__ = .;
*(.bss*)
*(COMMON)
} > BD_RAM
.ram_image2.skb.bss :
{
*(.bdsram.data*)
__bss_end__ = .;
} > BD_RAM
.ram_heap.data :
{
*(.bfsram.data*)
} > BD_RAM
. = ALIGN(8);
PROVIDE(heap_start = .);
PROVIDE(heap_end = 0x1003CFFF);
PROVIDE(heap_len = heap_end - heap_start);
.rom.bss :
{
*(.heap.stdlib*)
} > ROM_BSS_RAM
.ram_rdp.text :
{
__rom_top_4k_start_ = .;
__rdp_text_start__ = .;
KEEP(*(.rdp.ram.text*))
KEEP(*(.rdp.ram.data*))
__rdp_text_end__ = .;
. = ALIGN(16);
} > RDP_RAM
.xip_image1.text :
{
__flash_boot_text_start__ = .;
*(.flashboot.text*)
__flash_boot_text_end__ = .;
. = ALIGN(16);
} > XIPBOOT
.xip_image2.text :
{
__flash_text_start__ = .;
*(.img2_custom_signature*)
*(.text)
*(.text*)
*(.rodata)
*(.rodata*)
*(.debug_trace*)
__flash_text_end__ = .;
. = ALIGN (16);
} > XIP2
}
SECTIONS
{
/* Bootloader symbol list */
boot_export_symbol = 0x10002020;
}

View file

@ -0,0 +1,7 @@
#define UTS_VERSION "2017/12/20-10:58:56"
#define RTL8195AFW_COMPILE_TIME "2017/12/20-10:58:56"
#define RTL8195AFW_COMPILE_DATE "2017/12/20"
#define RTL8195AFW_COMPILE_BY "Jeanne"
#define RTL8195AFW_COMPILE_HOST "Jeanne-PC"
#define RTL8195AFW_COMPILE_DOMAIN
#define RTL8195AFW_COMPILER "IAR compiler"

View file

@ -0,0 +1,175 @@
#include <stdio.h>
#include "log_service.h"
#include "cmsis_os.h"
#include <platform/platform_stdlib.h>
#if CONFIG_JOYLINK
#if 1
void fATCJ(void *arg)
{
extern void joylink_erase(void);
printf("\r\n[ATCJ] Erase wifi and joylink info.");
if(arg){
printf("\r\n[ATCJ]Usage : ATCJ");
return;
}
joylink_erase();
}
#else
void fATCJ(void *arg)
{
extern void cmd_jd_smart(int argc, char **argv);
int argc;
char *argv[MAX_ARGC] = {0};
printf("[ATCJ]:simple config command for jdsmart\n\r");
if(!arg){
printf("[ATCJ]Usage: ATCJ=simple_config\n\r");
return;
}
argv[0] = "simple_config";
if((argc = parse_param(arg, argv)) > 1){
cmd_jd_smart(argc, argv);
}
else
printf("[ATCJ]Usage: ATCJ=simple_config\n\r");
}
#endif
#endif
#if CONFIG_GAGENT
void fATCG(void *arg)
{
example_gagent();
}
void fATCE(void *arg)
{//Erase gagent config flash
extern int GAgent_DevEraseConfigData();
GAgent_DevEraseConfigData();
}
#endif
#if CONFIG_QQ_LINK
void fATCQ(void *arg)
{
int argc;
unsigned char *argv[MAX_ARGC] = {0};
extern void device_write_sn_license(int argc, unsigned char **argv);
extern void device_erase_all(int argc, unsigned char **argv);
if(!arg)
{
printf("\r\n[ATCQ] Write sn/license into flash or Erase all info\r\n");
printf("\r\n[ATCQ] Usage: ATCQ=erase");
printf("\r\n[ATCQ] Usage: ATCQ=sn,xxxxxxxx\r\n ATCQ=licensepart1,xxxxxxxx\r\n ATCQ=licensepart2,xxxxxxxx");
return;
}
argv[0] = "sn&&license&&erase";
argc = parse_param(arg, argv);
if(argc == 3) // Write sn&&license
{
device_write_sn_license(argc, argv);
}
else if(argc == 2) // Erase all info : ATCQ=erase
{
device_erase_all(argc, argv);
}
else
{
printf("\r\n[ATCQ] Usage: ATCQ=erase");
printf("\r\n[ATCQ]Usage: ATCQ=sn,xxxxxxxx\r\n ATCQ=licensepart1,xxxxxxxx\r\n ATCQ=licensepart2,xxxxxxxx");
}
}
#endif
#if CONFIG_AIRKISS_CLOUD
void fATCW(void *arg)
{
int argc;
unsigned char *argv[MAX_ARGC] = {0};
extern void airkiss_cloud_write_device_info(int argc, unsigned char **argv);
extern void airkiss_cloud_erase_ap_profile(int argc, unsigned char **argv);
if(!arg) goto USAGE;
argv[0] = "type/id/licese/erase";
argc = parse_param(arg, argv);
if(argc == 3) // Write typw/id/license
{
airkiss_cloud_write_device_info(argc, argv);
return;
}
else if(argc == 2) // Erase wifi profile : ATCW=erase
{
airkiss_cloud_erase_ap_profile(argc, argv);
return;
}
else
goto USAGE;
USAGE:
printf("\r\n[ATCW] Write ORDERLY device's type/id/license into flash or Erase wifi profile");
printf("\r\n[ATCW] Usage: ATCW=type,xxxxxxxx");
printf("\r\n[ATCW] Usage: ATCW=id,xxxxxxxx");
printf("\r\n[ATCW] Usage: ATCW=licensepart1,xxxxxxxx\t(80-Byte long)");
printf("\r\n[ATCW] Usage: ATCW=licensepart2,xxxxxxxx\t(80-Byte long)");
printf("\r\n[ATCW] Usage: ATCW=erase");
return;
}
#endif
#if CONFIG_ALINK
extern void example_alink(void);
extern int alink_erase_wifi_config();
extern void alink_reset_to_factory(void *arg);
void fATCA(void *arg)
{
example_alink();
}
void fATCZ(void *arg)
{
//Erase alink config flash
alink_erase_wifi_config();
}
void fATCT(void *arg)
{
alink_reset_to_factory(NULL);
}
#endif
void fATCx(void *arg)
{
}
log_item_t at_cloud_items[ ] = {
#if CONFIG_JOYLINK
{"ATCJ", fATCJ,},
#endif
#if CONFIG_GAGENT
{"ATCG", fATCG,},
{"ATCE", fATCE,},
#endif
#if CONFIG_QQ_LINK
{"ATCQ", fATCQ,},
#endif
#if CONFIG_AIRKISS_CLOUD
{"ATCW", fATCW},
#endif
#if CONFIG_ALINK
{"ATCA", fATCA,},
{"ATCZ", fATCZ,},
{"ATCT", fATCT,},
#endif
{"ATC?", fATCx,},
};
void at_cloud_init(void)
{
log_service_add_table(at_cloud_items, sizeof(at_cloud_items)/sizeof(at_cloud_items[0]));
}
#if SUPPORT_LOG_SERVICE
log_module_init(at_cloud_init);
#endif

View file

@ -0,0 +1,91 @@
#include <stdio.h>
#include "log_service.h"
#include "platform_opts.h"
#include <lwip_netconf.h>
#include "cmsis_os.h"
#include <platform/platform_stdlib.h>
#include <lwip/sockets.h>
#include <lwip/tcpip.h>
#define _AT_DHCP_ETHERNET_MII_ "ATE0"
#define _AT_SET_DEFAULT_INTERFACE "ATE1"
#if CONFIG_ETHERNET
extern int dhcp_ethernet_mii;
extern int ethernet_if_default;
extern struct netif xnetif[NET_IF_NUM];
void fATE0(void *arg)
{
int argc;
char *argv[MAX_ARGC] = {0};
printf("[ATE0]:DHCP configure for ethernet\n\r");
if(!arg){
printf("[ATE0]Usage to disable DHCP: ATE0=0\n");
printf("[ATE0]Usage to enable DHCP: ATE0=1\n");
return;
}
if('0' == *(char *)arg)
{
dhcp_ethernet_mii = 0;
}
else if('1' == *(char *)arg)
{
dhcp_ethernet_mii = 1;
LwIP_DHCP(NET_IF_NUM - 1, DHCP_START);
}
else
{
printf("[ATE0]Usage to disable DHCP: ATE0=0\n");
printf("[ATE0]Usage to enable DHCP: ATE0=1\n");
}
}
void fATE1(void *arg)
{
int argc;
char *argv[MAX_ARGC] = {0};
printf("[ATE1]:Set/check the default interface\n\r");
if(!arg){
if(ethernet_if_default)
printf("Ethernet is the default interface\n");
else
printf("wlan is the default interface\n");
return;
}
if('0' == *(char *)arg)
{
ethernet_if_default = 0;
printf("wlan is set to the default interface\n");
}
else if('1' == *(char *)arg)
{
ethernet_if_default = 1;
printf("ethernet is set to the default interface\n");
}
else
{
printf("[ATE0]Usage to check the default interface: ATE1\n");
printf("[ATE0]Usage to set ethernet as default interface: ATE1=1\n");
printf("[ATE0]Usage to set wlan as default interface: ATE1=0\n");
}
}
log_item_t at_ethernet_items[ ] = {
{"ATE0", fATE0,},
{"ATE1", fATE1,}
};
void at_ethernet_init(void)
{
log_service_add_table(at_ethernet_items, sizeof(at_ethernet_items)/sizeof(at_ethernet_items[0]));
}
log_module_init(at_ethernet_init);
#endif

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,105 @@
#ifndef __ATCMD_LWIP_H__
#define __ATCMD_LWIP_H__
#include "main.h"
#include "osdep_service.h"
#include <lwip/opt.h>
#include "lwip/sockets.h"
#include "lwip/api.h"
#include "lwip/sys.h"
#include "lwip/igmp.h"
#include "lwip/inet.h"
#include "lwip/tcp.h"
#include "lwip/raw.h"
#include "lwip/udp.h"
#include "lwip/tcpip.h"
#include "lwip/pbuf.h"
#include "lwip/netdb.h"
#include "lwip_netconf.h"
#define _AT_TRANSPORT_MODE_ "ATP1"
#define _AT_TRANSPORT_LOCAL_PORT_ "ATP2"
#define _AT_TRANSPORT_REMOTE_IP_ "ATP3"
#define _AT_TRANSPORT_REMOTE_PORT_ "ATP4"
#define _AT_TRANSPORT_START_SERVER_ "ATP5"
#define _AT_TRANSPORT_START_CLIENT_ "ATP6"
#define _AT_TRANSPORT_SHOW_SETTING_ "ATP?"
#define _AT_TRANSPORT_RECEIVE_DATA_ "ATR0"
#define _AT_TRANSPORT_RECEIVE_PACKET_SIZE_ "ATR1"
#define _AT_TRANSPORT_WRITE_DATA_ "ATRA"
#define _AT_TRANSPORT_WRITE_PACKET_SIZE_ "ATRB"
#define NODE_MODE_TCP 0
#define NODE_MODE_UDP 1
#define NODE_MODE_SSL 2
#define NODE_ROLE_SERVER 0
#define NODE_ROLE_CLIENT 1
#define NODE_ROLE_SEED 2
#define INVALID_SOCKET_ID (-1)
//parameters
#ifndef NET_IF_NUM
#define NET_IF_NUM 2
#endif
#define ATCMD_LWIP_TASK_PRIORITY (tskIDLE_PRIORITY + 1)
#if ATCMD_VER == ATVER_2
#ifndef ATCMD_SUPPORT_SSL
#define ATCMD_SUPPORT_SSL 0
#endif
#define SERVER "127.0.0.1"
#define NUM_NS (MEMP_NUM_NETCONN) //maximum number of node and seed, same as NUM_SOCKETS
#define ETH_MAX_MTU 1500
#define INVALID_CON_ID (-1)
#define RECV_SELECT_TIMEOUT_SEC (0)
#define RECV_SELECT_TIMEOUT_USEC (20000) //20ms
typedef struct ns
{
int con_id;
int sockfd;
s8_t role;
int protocol;
u32_t addr;
u16_t port;
u32_t local_addr;
u16_t local_port;
xTaskHandle handletask;
struct ns* next;
struct ns* nextseed;
#if (ATCMD_VER == ATVER_2) && ATCMD_SUPPORT_SSL
void *context;
#endif
} node;
extern xTaskHandle atcmd_lwip_tt_task;
extern _sema atcmd_lwip_tt_sema;
extern volatile int atcmd_lwip_tt_datasize;
extern volatile int atcmd_lwip_tt_lasttickcnt;
#define ATCMD_LWIP_TT_MAX_DELAY_TIME_MS (20) //transparent transmission interval
extern int atcmd_lwip_is_tt_mode(void);
extern void atcmd_lwip_set_tt_mode(int enable);
int atcmd_lwip_send_data(node *curnode, u8 *data, u16 data_sz, struct sockaddr_in cli_addr);
int atcmd_lwip_receive_data(node *curnode, u8 *buffer, u16 buffer_size, int *recv_size,
u8_t *udp_clientaddr, u16_t *udp_clientport);
node* create_node(int mode, s8_t role);
void init_node_pool(void);
void delete_node(node *n);
int hang_node(node* insert_node);
int hang_seednode(node* main_node ,node* insert_node);
node *seek_node(int con_id);
node *tryget_node(int n);
#endif
#endif //#ifndef __ATCMD_LWIP_H__

View file

@ -0,0 +1,195 @@
#include <platform_stdlib.h>
#include <platform_opts.h>
#include <gpio_api.h>
#include "log_service.h"
#include "atcmd_mp.h"
#if CONFIG_ATCMD_MP_EXT0
extern void fATM0(void *arg); // MP ext0 AT command
#endif
#if CONFIG_ATCMD_MP
//-------- AT MP commands ---------------------------------------------------------------
void fATMG(void *arg)
{
gpio_t gpio_test;
int argc = 0, val, cnts, i, write=0, data=0;
char *argv[MAX_ARGC] = {0}, port, num;
PinName pin = NC;
u32 tConfigDebugInfo = ConfigDebugInfo;
AT_DBG_MSG(AT_FLAG_GPIO, AT_DBG_ALWAYS, "[ATMG]: _AT_MP_GPIO_TEST_");
if(!arg){
AT_DBG_MSG(AT_FLAG_GPIO, AT_DBG_ALWAYS, "[ATMG] Usage: ATSG=w,PINNAMES(ex:A0B1C2...),VALUE(0/1)");
AT_DBG_MSG(AT_FLAG_GPIO, AT_DBG_ALWAYS, "[ATMG] Usage: ATSG=r,PINNAMES(ex:A0B1C2...)");
return;
}
argc = parse_param(arg, argv);
cnts = strlen(argv[2]);
if(cnts % 2) return;
cnts /= 2;
if(cnts == 0) return;
if(strcmp(argv[1], "w") == 0){
write = 1;
if(strcmp(argv[3], "1") == 0)
data = 1;
}
// Remove debug info massage
_AT_DBG_MSG(AT_FLAG_GPIO, AT_DBG_ALWAYS, "[ATMG] %s: ", argv[1]);
ConfigDebugInfo = 0;
for(i=0; i<(cnts*2); i+=2){
pin = NC;
port = argv[2][i];
num = argv[2][i+1];
if(port >= 'a' && port <= 'z')
port -= ('a' - 'A');
if(num >= 'a' && num <= 'z')
num -= ('a' - 'A');
switch(port){
case 'A':
switch(num){
case '0': pin = PA_0; break; case '1': pin = PA_1; break; case '2': pin = PA_2; break; case '3': pin = PA_3; break;
case '4': pin = PA_4; break; case '5': pin = PA_5; break; case '6': pin = PA_6; break; case '7': pin = PA_7; break;
}
break;
case 'B':
switch(num){
case '0': pin = PB_0; break; case '1': pin = PB_1; break; case '2': pin = PB_2; break; case '3': pin = PB_3; break;
case '4': pin = PB_4; break; case '5': pin = PB_5; break; case '6': pin = PB_6; break; case '7': pin = PB_7; break;
}
break;
case 'C':
switch(num){
case '0': pin = PC_0; break; case '1': pin = PC_1; break; case '2': pin = PC_2; break; case '3': pin = PC_3; break;
case '4': pin = PC_4; break; case '5': pin = PC_5; break; case '6': pin = PC_6; break; case '7': pin = PC_7; break;
case '8': pin = PC_8; break; case '9': pin = PC_9; break;
}
break;
case 'D':
switch(num){
case '0': pin = PD_0; break; case '1': pin = PD_1; break; case '2': pin = PD_2; break; case '3': pin = PD_3; break;
case '4': pin = PD_4; break; case '5': pin = PD_5; break; case '6': pin = PD_6; break; case '7': pin = PD_7; break;
case '8': pin = PD_8; break; case '9': pin = PD_9; break;
}
break;
case 'E':
switch(num){
case '0': pin = PE_0; break; case '1': pin = PE_1; break; case '2': pin = PE_2; break; case '3': pin = PE_3; break;
case '4': pin = PE_4; break; case '5': pin = PE_5; break; case '6': pin = PE_6; break; case '7': pin = PE_7; break;
case '8': pin = PE_8; break; case '9': pin = PE_9; break; case 'A': pin = PE_A; break;
}
break;
case 'F':
switch(num){
case '0': pin = PF_0; break; case '1': pin = PF_1; break; case '2': pin = PF_2; break; case '3': pin = PF_3; break;
case '4': pin = PF_4; break; case '5': pin = PF_5; break;
}
break;
case 'G':
switch(num){
case '0': pin = PG_0; break; case '1': pin = PG_1; break; case '2': pin = PG_2; break; case '3': pin = PG_3; break;
case '4': pin = PG_4; break; case '5': pin = PG_5; break; case '6': pin = PG_6; break; case '7': pin = PG_7; break;
}
break;
case 'H':
switch(num){
case '0': pin = PH_0; break; case '1': pin = PH_1; break; case '2': pin = PH_2; break; case '3': pin = PH_3; break;
case '4': pin = PH_4; break; case '5': pin = PH_5; break; case '6': pin = PH_6; break; case '7': pin = PH_7; break;
}
break;
case 'I':
switch(num){
case '0': pin = PI_0; break; case '1': pin = PI_1; break; case '2': pin = PI_2; break; case '3': pin = PI_3; break;
case '4': pin = PI_4; break; case '5': pin = PI_5; break; case '6': pin = PI_6; break; case '7': pin = PI_7; break;
}
break;
case 'J':
switch(num){
case '0': pin = PJ_0; break; case '1': pin = PJ_1; break; case '2': pin = PJ_2; break; case '3': pin = PJ_3; break;
case '4': pin = PJ_4; break; case '5': pin = PJ_5; break; case '6': pin = PJ_6; break;
}
break;
case 'K':
switch(num){
case '0': pin = PK_0; break; case '1': pin = PK_1; break; case '2': pin = PK_2; break; case '3': pin = PK_3; break;
case '4': pin = PK_4; break; case '5': pin = PK_5; break; case '6': pin = PK_6; break;
}
break;
}
if(pin == NC){
_AT_DBG_MSG(AT_FLAG_GPIO, AT_DBG_ALWAYS, "X,");
continue;
}
// Initial input control pin
gpio_init(&gpio_test, pin);
if(write){
gpio_dir(&gpio_test, PIN_OUTPUT); // Direction: Output
gpio_mode(&gpio_test, PullNone); // No pull
gpio_write(&gpio_test, data);
_AT_DBG_MSG(AT_FLAG_GPIO, AT_DBG_ALWAYS, "%d,", data);
}else{
gpio_dir(&gpio_test, PIN_INPUT); // Direction: Input
gpio_mode(&gpio_test, PullUp); // Pull-High
val = gpio_read(&gpio_test);
_AT_DBG_MSG(AT_FLAG_GPIO, AT_DBG_ALWAYS, "%d,", val);
}
}
_AT_DBG_MSG(AT_FLAG_GPIO, AT_DBG_ALWAYS, "\n");
// Recover debug info massage
ConfigDebugInfo = tConfigDebugInfo;
}
void fATMR(void *arg)
{
u32 idx;
AT_PRINTK("[ATMR]: _AT_MP_SDR_TEST_");
#ifdef CONFIG_SDR_EN
for (idx = 0; idx < 0x200000; idx = idx+4){
HAL_WRITE32(0x30000000, idx, 0x12345678);
if (HAL_READ32(0x30000000, idx) != 0x12345678) {
AT_PRINTK("[ATMR]: SDR test fail addr 0x08x, value 0x08%x",(0x30000000+idx),HAL_READ32(0x30000000, idx));
return;
}
}
AT_PRINTK("[ATMR]: SDR test success");
#endif
}
void fATMt(void *arg)
{
int argc = 0;
char *argv[MAX_ARGC] = {0};
AT_PRINTK("[ATM#]: _AT_MP_TEST_");
argc = parse_param(arg, argv);
}
void fATMx(void *arg)
{
AT_PRINTK("[ATM?]: _AT_MP_HELP_");
}
log_item_t at_mp_items[] = {
{"ATMG", fATMG,}, // MP GPIO test
{"ATMR", fATMR,}, // MP SDR test
{"ATM#", fATMt,}, // test command
{"ATM?", fATMx,}, // Help
#if CONFIG_ATCMD_MP_EXT0
{"ATM0", fATM0,}, // MP ext0 AT command
#endif
};
void at_mp_init(void)
{
log_service_add_table(at_mp_items, sizeof(at_mp_items)/sizeof(at_mp_items[0]));
}
#if SUPPORT_LOG_SERVICE
log_module_init(at_mp_init);
#endif
#endif // #if CONFIG_ATCMD_MP

View file

@ -0,0 +1,12 @@
#ifndef __ATCMD_MP_H__
#define __ATCMD_MP_H__
#define CONFIG_ATCMD_MP_EXT0 0 //support MP ext0 AT command
typedef struct _at_command_mp_ext_item_{
char *mp_ext_cmd;
int (*mp_ext_fun)(void **argv, int argc);
char *mp_ext_usage;
}at_mp_ext_item_t;
#endif

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,5 @@
#ifndef __ATCMD_SYS_H__
#define __ATCMD_SYS_H__
#endif

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,161 @@
#ifndef __ATCMD_WIFI_H__
#define __ATCMD_WIFI_H__
#include "main.h"
#include "lwip_netconf.h"
#ifndef WLAN0_NAME
#define WLAN0_NAME "wlan0"
#endif
#ifndef WLAN1_NAME
#define WLAN1_NAME "wlan1"
#endif
/* Give default value if not defined */
#ifndef NET_IF_NUM
#ifdef CONFIG_CONCURRENT_MODE
#define NET_IF_NUM ((CONFIG_ETHERNET) + (CONFIG_WLAN) + 1)
#else
#define NET_IF_NUM ((CONFIG_ETHERNET) + (CONFIG_WLAN))
#endif // end of CONFIG_CONCURRENT_MODE
#endif // end of NET_IF_NUM
/*Static IP ADDRESS*/
#ifndef IP_ADDR0
#define IP_ADDR0 192
#define IP_ADDR1 168
#define IP_ADDR2 1
#define IP_ADDR3 80
#endif
/*NETMASK*/
#ifndef NETMASK_ADDR0
#define NETMASK_ADDR0 255
#define NETMASK_ADDR1 255
#define NETMASK_ADDR2 255
#define NETMASK_ADDR3 0
#endif
/*Gateway Address*/
#ifndef GW_ADDR0
#define GW_ADDR0 192
#define GW_ADDR1 168
#define GW_ADDR2 1
#define GW_ADDR3 1
#endif
/*Static IP ADDRESS*/
#ifndef AP_IP_ADDR0
#define AP_IP_ADDR0 192
#define AP_IP_ADDR1 168
#define AP_IP_ADDR2 43
#define AP_IP_ADDR3 1
#endif
/*NETMASK*/
#ifndef AP_NETMASK_ADDR0
#define AP_NETMASK_ADDR0 255
#define AP_NETMASK_ADDR1 255
#define AP_NETMASK_ADDR2 255
#define AP_NETMASK_ADDR3 0
#endif
/*Gateway Address*/
#ifndef AP_GW_ADDR0
#define AP_GW_ADDR0 192
#define AP_GW_ADDR1 168
#define AP_GW_ADDR2 43
#define AP_GW_ADDR3 1
#endif
#if CONFIG_EXAMPLE_UART_ATCMD
#include "wifi_structures.h"
#include <wlan_fast_connect/example_wlan_fast_connect.h>
typedef struct _UART_LOG_CONF_{
u32 BaudRate;
u8 DataBits;
u8 StopBits;
u8 Parity;
u8 FlowControl;
}UART_LOG_CONF, *PUART_LOG_CONF;
#define ATCMD_WIFI_CONN_STORE_MAX_NUM (1)
struct atcmd_wifi_conf{
int32_t auto_enable;
rtw_wifi_setting_t setting;
int32_t reconn_num;
int32_t reconn_last_index;
struct wlan_fast_reconnect reconn[ATCMD_WIFI_CONN_STORE_MAX_NUM];
};
#define ATCMD_LWIP_CONN_STORE_MAX_NUM (1)
struct atcmd_lwip_conn_info{
int32_t role; //client, server or seed
uint32_t protocol; //tcp or udp
uint32_t remote_addr; //remote ip
uint32_t remote_port; //remote port
uint32_t local_addr; //locale ip, not used yet
uint32_t local_port; //locale port, not used yet
uint32_t reserved; //reserve for further use
};
struct atcmd_lwip_conf {
int32_t enable; //enable or not
int32_t conn_num;
int32_t last_index;
int32_t reserved; //reserve for further use
struct atcmd_lwip_conn_info conn[ATCMD_LWIP_CONN_STORE_MAX_NUM];
};
typedef enum {
AT_PARTITION_ALL = 0,
AT_PARTITION_UART = 1,
AT_PARTITION_WIFI = 2,
AT_PARTITION_LWIP = 3
} AT_PARTITION;
typedef enum {
AT_PARTITION_READ = 0,
AT_PARTITION_WRITE = 1,
AT_PARTITION_ERASE = 2
} AT_PARTITION_OP;
//first segment for uart
#define UART_SETTING_BACKUP_SECTOR (0x8000)
#define UART_CONF_DATA_OFFSET (0)
#define UART_CONF_DATA_SIZE ((((sizeof(UART_LOG_CONF)-1)>>2) + 1)<<2)
//second segment for wifi config
#define WIFI_CONF_DATA_OFFSET (UART_CONF_DATA_OFFSET+UART_CONF_DATA_SIZE)
#define WIFI_CONF_DATA_SIZE ((((sizeof(struct atcmd_wifi_conf)-1)>>2) + 1)<<2)
//fouth segment for lwip config
#define LWIP_CONF_DATA_OFFSET (WIFI_CONF_DATA_OFFSET+WIFI_CONF_DATA_SIZE)
#define LWIP_CONF_DATA_SIZE ((((sizeof(struct atcmd_lwip_conf)-1)>>2) + 1)<<2)
extern void atcmd_update_partition_info(AT_PARTITION id, AT_PARTITION_OP ops, u8 *data, u16 len);
#define ATSTRING_LEN (LOG_SERVICE_BUFLEN)
extern char at_string[ATSTRING_LEN];
extern unsigned char gAT_Echo; // default echo on
//extern void uart_at_lock(void);
//extern void uart_at_unlock(void);
extern void uart_at_send_string(char *str);
extern void uart_at_send_buf(u8 *buf, u32 len);
#define at_printf(fmt, args...) do{\
/*uart_at_lock();*/\
snprintf(at_string, ATSTRING_LEN, fmt, ##args); \
uart_at_send_string(at_string);\
/*uart_at_unlock();*/\
}while(0)
#define at_print_data(data, size) do{\
/*uart_at_lock();*/\
uart_at_send_buf(data, size);\
/*uart_at_unlock();*/\
}while(0)
#else
#define at_printf(fmt, args...) do{printf(fmt, ##args);}while(0)
#define at_print_data(data, size) do{__rtl_memDump(data, size, NULL);}while(0)
#endif//#if CONFIG_EXAMPLE_UART_ATCMD
#endif

View file

@ -0,0 +1,489 @@
#include <stdarg.h>
#include <string.h>
#include <stdio.h>
//#include "FreeRTOS.h"
#include <aos_osdep.h>
#if defined(configUSE_WAKELOCK_PMU) && (configUSE_WAKELOCK_PMU == 1)
#include "freertos_pmu.h"
#endif
#include "log_service.h"
//#include "task.h"
//#include "semphr.h"
#include "main.h"
//#include "wifi_util.h"
#include "atcmd_wifi.h"
#if CONFIG_EXAMPLE_UART_ATCMD || CONFIG_EXAMPLE_SPI_ATCMD
#include "atcmd_lwip.h"
#endif
#include "osdep_service.h"
#if SUPPORT_LOG_SERVICE
//======================================================
struct list_head log_hash[ATC_INDEX_NUM];
extern void at_wifi_init(void);
extern void at_fs_init(void);
extern void at_sys_init(void);
extern void at_ethernet_init(void);
extern void at_google_init(void);
extern void at_transport_init(void);
//extern void at_app_init(void);
extern void at_mp_init(void);
void at_log_init(void);
char log_buf[LOG_SERVICE_BUFLEN];
#if CONFIG_LOG_HISTORY
char log_history[LOG_HISTORY_LEN][LOG_SERVICE_BUFLEN];
static unsigned int log_history_count = 0;
#endif
_sema log_rx_interrupt_sema;
#if CONFIG_LOG_SERVICE_LOCK
_sema log_service_sema;
#endif
extern _sema uart_rx_interrupt_sema;
#if CONFIG_INIC_EN
extern unsigned char inic_cmd_ioctl;
#endif
//#if defined (__ICCARM__)
//#pragma section=".data.log_init"
//
//unsigned int __log_init_begin__;
//unsigned int __log_init_end__;
//#elif defined ( __CC_ARM ) || defined(__GNUC__)
#if defined (__ICCARM__) || defined ( __CC_ARM ) || defined(__GNUC__)
//#pragma section=".data.log_init"
log_init_t* __log_init_begin__;
log_init_t* __log_init_end__;
log_init_t log_init_table[] = {
at_wifi_init,
// at_fs_init,
//at_sys_init,
at_log_init,
// at_app_init,
#if CONFIG_ETHERNET
at_ethernet_init,
#endif
#if CONFIG_GOOGLE_NEST
at_google_init,
#endif
#if CONFIG_TRANSPORT
at_transport_init,
#endif
#if CONFIG_ATCMD_MP
at_mp_init,
#endif
};
#else
#error "not implement, add to linker script"
extern unsigned int __log_init_begin__;
extern unsigned int __log_init_end__;
#endif
#if defined(__GNUC__)
#define USE_STRSEP
#endif
//======================================================
int hash_index(char *str)
{
unsigned int seed = 131; // 31 131 1313 13131 131313 etc..
unsigned int hash = 0;
while (*str)
{
hash = hash * seed + (*str++);
}
return (hash & 0x7FFFFFFF);
}
void log_add_new_command(log_item_t *new)
{
int index = hash_index(new->log_cmd)%ATC_INDEX_NUM;
list_add(&new->node, &log_hash[index]);
}
void start_log_service(void);
void log_service_init(void)
{
int i;
//#if defined (__ICCARM__)
// log_init_t *log_init_table;
// __log_init_begin__ = (unsigned int)__section_begin(".data.log_init");
// __log_init_end__ = (unsigned int)__section_end(".data.log_init");
// log_init_table = (log_init_t *)__log_init_begin__;
//#elif defined(__CC_ARM) || defined(__GNUC__)
#if defined (__ICCARM__) || defined(__CC_ARM) || defined(__GNUC__)
__log_init_begin__ = log_init_table;
__log_init_end__ = __log_init_begin__ + sizeof(log_init_table);
#else
#error "not implement"
#endif
for(i=0;i<ATC_INDEX_NUM;i++)
INIT_LIST_HEAD(&log_hash[i]);
for(i=0;i<(__log_init_end__-__log_init_begin__)/sizeof(log_init_t); i++)
log_init_table[i]();
/* Initial uart rx swmaphore*/
rtw_init_sema(&log_rx_interrupt_sema, 1);
rtw_down_sema(&log_rx_interrupt_sema);
#if CONFIG_LOG_SERVICE_LOCK
log_service_lock_init();
#endif
start_log_service();
}
//sizeof(log_items)/sizeof(log_items[0])
void log_service_add_table(log_item_t *tbl, int len)
{
int i;
for(i=0;i<len;i++)
log_add_new_command(&tbl[i]);
}
void* log_action(char *cmd)
{
int search_cnt=0;
int index = hash_index(cmd)%ATC_INDEX_NUM;
struct list_head *head = &log_hash[index];
struct list_head *iterator;
log_item_t *item;
void *act = NULL;
list_for_each(iterator, head) {
item = list_entry(iterator, log_item_t, node);
search_cnt++;
if( strcmp(item->log_cmd, cmd) == 0){
//printf("%s match %s, search cnt %d\n\r", cmd, item->log_cmd, search_cnt);
act = (void*)item->at_act;
break;
}
}
return act;
}
void* log_handler(char *cmd)
{
log_act_t action=NULL;
char buf[LOG_SERVICE_BUFLEN];
memset(buf, 0, LOG_SERVICE_BUFLEN);
char *copy=buf;
char *token = NULL;
char *param = NULL;
char tok[5] = {0};//'\0'
#if CONFIG_LOG_HISTORY
strcpy(log_history[((log_history_count++)%LOG_HISTORY_LEN)], log_buf);
#endif
strncpy(copy, cmd,LOG_SERVICE_BUFLEN-1);
#if defined(USE_STRSEP)
token = _strsep(&copy, "=");
param = copy;
#else
token = strtok(copy, "=");
param = strtok(NULL, NULL);
#endif
if(token && (strlen(token) <= 4))
strcpy(tok, token);
else{
//printf("\n\rAT Cmd format error!\n");
return NULL;
};
//printf(" Command %s \n\r ", tok);
//printf(" Param %s \n\r", param);
action = (log_act_t)log_action(tok);
if(action){
action(param);
}
return (void*)action;
}
int parse_param(char *buf, char **argv)
{
int argc = 1;
char str_buf[LOG_SERVICE_BUFLEN];
memset(str_buf, 0, LOG_SERVICE_BUFLEN);
int str_count = 0;
int buf_cnt = 0;
if(buf == NULL)
goto exit;
while((argc < MAX_ARGC) && (*buf != '\0')) {
while((*buf == ',') || (*buf == '[') || (*buf == ']')){
if((*buf == ',') && (*(buf+1) == ',')){
argv[argc] = NULL;
argc++;
}
*buf = '\0';
buf++;
}
if(*buf == '\0')
break;
else if(*buf == '"'){
memset(str_buf,'\0',LOG_SERVICE_BUFLEN);
str_count = 0;
buf_cnt = 0;
*buf = '\0';
buf ++;
if(*buf == '\0')
break;
argv[argc] = buf;
while((*buf != '"')&&(*buf != '\0')){
if(*buf == '\\'){
buf ++;
buf_cnt++;
}
str_buf[str_count] = *buf;
str_count++;
buf_cnt++;
buf ++;
}
*buf = '\0';
memcpy(buf-buf_cnt,str_buf,buf_cnt);
}
else{
argv[argc] = buf;
}
argc++;
buf++;
while( (*buf != ',')&&(*buf != '\0')&&(*buf != '[')&&(*buf != ']') )
buf++;
}
exit:
return argc;
}
unsigned char gDbgLevel = AT_DBG_ERROR;
unsigned int gDbgFlag = 0xFFFFFFFF;
void at_set_debug_level(unsigned char newDbgLevel)
{
gDbgLevel = newDbgLevel;
}
void at_set_debug_mask(unsigned int newDbgFlag)
{
gDbgFlag = newDbgFlag;
}
#if SUPPORT_INTERACTIVE_MODE
extern char uart_buf[64];
void legency_interactive_handler(unsigned char argc, unsigned char **argv)
{
#if 0 //defined(CONFIG_PLATFORM_8195A)
if(argc<1)
{
DiagPrintf("Wrong argument number!\r\n");
return;
}
DiagPrintf("Wlan Normal Mode\n");
WlanNormal( argc, argv);
#else
strncpy(uart_buf, log_buf, 63);//uart_buf[64]
rtw_up_sema(&uart_rx_interrupt_sema);
#endif
}
#endif
#if CONFIG_WLAN
#ifndef WLAN0_NAME
#define WLAN0_NAME "wlan0"
#endif
#ifndef WLAN1_NAME
#define WLAN1_NAME "wlan1"
#endif
int mp_commnad_handler(char *cmd)
{
char buf[64];
char *token = NULL;
memset(buf, 0, 64);
//strcpy(buf, cmd);
strncpy(buf, cmd, (64-1));
token = strtok(buf, " ");
if(token && (strcmp(buf, "iwpriv") == 0)){
token = strtok(NULL, "");
wext_private_command(WLAN0_NAME, token, 1);
return 0;
}
return -1;
}
#endif
void print_help_msg(void){
#if CONFIG_WLAN
extern void print_wlan_help(void);
print_wlan_help();
#endif
//add other help message print here
}
int print_help_handler(char *cmd){
if(strcmp(cmd, "help") == 0){
print_help_msg();
return 0;
}
return -1;
}
#if CONFIG_LOG_SERVICE_LOCK
void log_service_lock(void)
{
rtw_down_sema(&log_service_sema);
}
u32 log_service_lock_timeout(u32 ms)
{
return rtw_down_timeout_sema(&log_service_sema, ms);
}
void log_service_unlock(void)
{
rtw_up_sema(&log_service_sema);
}
void log_service_lock_init(void){
rtw_init_sema(&log_service_sema, 1);
}
#endif
void log_service(void *param)
{
_AT_DBG_MSG(AT_FLAG_COMMON, AT_DBG_ALWAYS, "\n\rStart LOG SERVICE MODE\n\r");
_AT_DBG_MSG(AT_FLAG_COMMON, AT_DBG_ALWAYS, "\n\r# ");
while(1){
while(rtw_down_sema(&log_rx_interrupt_sema) != pdTRUE);
#if CONFIG_LOG_SERVICE_LOCK
log_service_lock();
#endif
if(log_handler((char *)log_buf) == NULL){
#if CONFIG_WLAN
if(mp_commnad_handler((char *)log_buf) < 0)
#endif
{
#if SUPPORT_INTERACTIVE_MODE
print_help_handler((char *)log_buf);
legency_interactive_handler(NULL, NULL);
#else
if(print_help_handler((char *)log_buf) < 0){
at_printf("\r\nunknown command '%s'", log_buf);
}
#endif
}
}
log_buf[0] = '\0';
#if CONFIG_INIC_EN
inic_cmd_ioctl = 0;
#endif
_AT_DBG_MSG(AT_FLAG_COMMON, AT_DBG_ALWAYS, "\n\r[MEM] After do cmd, available heap %d\n\r", rtw_getFreeHeapSize());
_AT_DBG_MSG(AT_FLAG_COMMON, AT_DBG_ALWAYS, "\r\n\n# "); //"#" is needed for mp tool
#if CONFIG_EXAMPLE_UART_ATCMD
if(atcmd_lwip_is_tt_mode())
at_printf(STR_END_OF_ATDATA_RET);
else
at_printf(STR_END_OF_ATCMD_RET);
#endif
#if CONFIG_LOG_SERVICE_LOCK
log_service_unlock();
#endif
#if defined(configUSE_WAKELOCK_PMU) && (configUSE_WAKELOCK_PMU == 1)
pmu_release_wakelock(BIT(PMU_LOGUART_DEVICE));
#endif
}
}
#define STACKSIZE 1280
ktask_t *g_log_service_task;
void start_log_service(void)
{
//xTaskHandle CreatedTask;
int result;
#if CONFIG_USE_TCM_HEAP
/*********************************************************************
*
* ATCMD V2 supports commands for SSL
* It will cause problems while doing SSL operations if the stack is placed in TCM region
*
*********************************************************************/
void *stack_addr = NULL;
#if (ATCMD_VER == ATVER_1) || ((ATCMD_VER == ATVER_2)&&(ATCMD_SUPPORT_SSL == 0))
extern void *tcm_heap_malloc(int size);
stack_addr = tcm_heap_malloc(STACKSIZE * sizeof(int));
if(stack_addr == NULL){
}
#endif
result = xTaskGenericCreate(
log_service,
( signed portCHAR * ) "log_service",
STACKSIZE,
NULL,
tskIDLE_PRIORITY + 5,
&CreatedTask,
stack_addr,
NULL);
#else
//result = krhino_task_dyn_create( log_service, ( signed portCHAR * ) "log_service", STACKSIZE, NULL, tskIDLE_PRIORITY + 5, &CreatedTask );
result = krhino_task_dyn_create(&g_log_service_task, "log_service", 0, 6, 0, STACKSIZE, (task_entry_t)log_service, 1);
#endif
if(result != 0) {
printf("\n\r%s xTaskCreate failed", __FUNCTION__);
}
}
void fAT_exit(void *arg){
printf("\n\rLeave LOG SERVICE");
krhino_task_dyn_del(NULL);
}
#if CONFIG_LOG_HISTORY
void fAT_log(void *arg){
int i = 0;
printf("[AT]log history:\n\n\r");
if(log_history_count > LOG_HISTORY_LEN){
for(i=0; i<4; i++)
printf(" %s\n\r", log_history[((log_history_count+i)%LOG_HISTORY_LEN)]);
}
else{
for(i=0; i<(log_history_count-1); i++)
printf(" %s\n\r", log_history[i]);
}
}
#endif
log_item_t at_log_items[ ] = {
{"AT--", fAT_exit,},
#if CONFIG_LOG_HISTORY
{"AT??", fAT_log,},
#endif
{"ATxx", fAT_exit,}
};
void at_log_init(void)
{
log_service_add_table(at_log_items, sizeof(at_log_items)/sizeof(at_log_items[0]));
}
log_module_init(at_log_init);
#endif

View file

@ -0,0 +1,127 @@
#ifndef LOG_SERVICE_H
#define LOG_SERVICE_H
#include "dlist.h"
/*
* Include user defined options first. Anything not defined in these files
* will be set to standard values. Override anything you dont like!
*/
#if defined(CONFIG_PLATFORM_8195A) || defined(CONFIG_PLATFORM_8711B)
#include "platform_opts.h"
#include "platform_stdlib.h"
#endif
//#ifdef __ICCARM__
//#define STRINGIFY(s) #s
//#define SECTION(_name) _Pragma( STRINGIFY(location=_name))
//#define log_module_init(fn) \
// SECTION(".data.log_init") __root static void* log_##fn = (void*)fn
//#elif defined(__CC_ARM)
//#define log_module_init(fn) \
//static void* log_##fn __attribute__((section(".data.log_init"))) = (void*)fn;
//#define DiagPrintf printf
//#elif defined(__GNUC__)
//#define log_module_init(fn) \
//static void* log_##fn __attribute__((section(".data.log_init"))) = (void*)fn;
//#else
//#error "not implement"
//#endif
#define log_module_init(fn)
#define ATC_INDEX_NUM 32
#ifndef SUPPORT_LOG_SERVICE
#define SUPPORT_LOG_SERVICE 1
#endif
//LOG_SERVICE_BUFLEN: default, only 63 bytes could be used for keeping input
// cmd, the last byte is for string end ('\0').
#ifndef LOG_SERVICE_BUFLEN
#define LOG_SERVICE_BUFLEN 64
#endif
#ifndef CONFIG_LOG_HISTORY
#define CONFIG_LOG_HISTORY 0
#if CONFIG_LOG_HISTORY
#define LOG_HISTORY_LEN 5
#endif
#endif //#ifndef CONFIG_LOG_HISTORY
#ifndef MAX_ARGC
#define MAX_ARGC 12
#endif
#ifndef CONFIG_LOG_SERVICE_LOCK
#define CONFIG_LOG_SERVICE_LOCK 0 // //to protect log_buf[], only one command processed per time
#endif
#define AT_BIT(n) (1<<n)
#define AT_FLAG_DUMP AT_BIT(0)
#define AT_FLAG_EDIT AT_BIT(1)
#define AT_FLAG_ADC AT_BIT(2)
#define AT_FLAG_GPIO AT_BIT(3)
#define AT_FLAG_OTA AT_BIT(4)
#define AT_FLAG_NFC AT_BIT(5)
#define AT_FLAG_OS AT_BIT(6)
#define AT_FLAG_LWIP AT_BIT(7)
#define AT_FLAG_COMMON AT_BIT(8)
#define AT_FLAG_WIFI AT_BIT(9)
#define AT_FLAG_RDP AT_BIT(10)
enum{
AT_DBG_OFF = 0,
AT_DBG_ALWAYS,
AT_DBG_ERROR,
AT_DBG_WARNING,
AT_DBG_INFO
};
extern unsigned char gDbgLevel;
extern unsigned int gDbgFlag;
#define AT_PRINTK(...) \
do{ \
printf(__VA_ARGS__); \
printf("\r\n"); \
}while(0)
#define _AT_PRINTK(...) printf(__VA_ARGS__)
#define AT_DBG_MSG(flag, level, ...) \
do{ \
if(((flag) & gDbgFlag) && (level <= gDbgLevel)){ \
AT_PRINTK(__VA_ARGS__); \
} \
}while(0)
#define _AT_DBG_MSG(flag, level, ...) \
do{ \
if(((flag) & gDbgFlag) && (level <= gDbgLevel)){ \
_AT_PRINTK(__VA_ARGS__); \
} \
}while(0)
#ifndef SUPPORT_INTERACTIVE_MODE
#define SUPPORT_INTERACTIVE_MODE 0
#endif //#ifndef SUPPORT_INTERACTIVE_MODE
typedef void (*log_init_t)(void);
typedef void (*log_act_t)(void*);
typedef struct _at_command_item_{
char *log_cmd;
log_act_t at_act;
struct list_head node;
}log_item_t;
void log_service_add_table(log_item_t *tbl, int len);
int parse_param(char *buf, char **argv);
#if CONFIG_LOG_SERVICE_LOCK
void log_service_lock_init(void);
void log_service_lock(void);
u32 log_service_lock_timeout(u32 ms);
void log_service_unlock(void);
#endif
#define C_NUM_AT_CMD 4 //"ATxx", 4 characters
#define C_NUM_AT_CMD_DLT 1 //"=", 1 charater
#define STR_END_OF_ATCMD_RET "\r\n\n# " //each AT command response will end with this string
#define STR_END_OF_ATDATA_RET "\r\n\n> " //data transparent transmission indicator
#endif

View file

@ -0,0 +1,465 @@
/* Includes ------------------------------------------------------------------*/
#include "lwip/mem.h"
#include "lwip/memp.h"
#include "lwip/dhcp.h"
#include "lwip/dns.h"
#include "lwip/tcpip.h"
#include "ethernetif.h"
#include "main.h"
#include "lwip_netconf.h"
#if CONFIG_WLAN
#include "wifi_ind.h"
#endif
#if defined(STM32F2XX)
#include "stm322xg_eval_lcd.h"
#elif defined(STM32F4XX)
#include "stm324xg_eval_lcd.h"
#endif
#include <platform/platform_stdlib.h>
/*Static IP ADDRESS*/
#ifndef IP_ADDR0
#define IP_ADDR0 192
#define IP_ADDR1 168
#define IP_ADDR2 1
#define IP_ADDR3 80
#endif
/*NETMASK*/
#ifndef NETMASK_ADDR0
#define NETMASK_ADDR0 255
#define NETMASK_ADDR1 255
#define NETMASK_ADDR2 255
#define NETMASK_ADDR3 0
#endif
/*Gateway Address*/
#ifndef GW_ADDR0
#define GW_ADDR0 192
#define GW_ADDR1 168
#define GW_ADDR2 1
#define GW_ADDR3 1
#endif
/*Static IP ADDRESS*/
#ifndef AP_IP_ADDR0
#define AP_IP_ADDR0 192
#define AP_IP_ADDR1 168
#define AP_IP_ADDR2 43
#define AP_IP_ADDR3 1
#endif
/*NETMASK*/
#ifndef AP_NETMASK_ADDR0
#define AP_NETMASK_ADDR0 255
#define AP_NETMASK_ADDR1 255
#define AP_NETMASK_ADDR2 255
#define AP_NETMASK_ADDR3 0
#endif
/*Gateway Address*/
#ifndef AP_GW_ADDR0
#define AP_GW_ADDR0 192
#define AP_GW_ADDR1 168
#define AP_GW_ADDR2 43
#define AP_GW_ADDR3 1
#endif
/*Static IP ADDRESS FOR ETHERNET*/
#ifndef ETH_IP_ADDR0
#define ETH_IP_ADDR0 192
#define ETH_IP_ADDR1 168
#define ETH_IP_ADDR2 0
#define ETH_IP_ADDR3 80
#endif
/*NETMASK FOR ETHERNET*/
#ifndef ETH_NETMASK_ADDR0
#define ETH_NETMASK_ADDR0 255
#define ETH_NETMASK_ADDR1 255
#define ETH_NETMASK_ADDR2 255
#define ETH_NETMASK_ADDR3 0
#endif
/*Gateway address for ethernet*/
#ifndef ETH_GW_ADDR0
#define ETH_GW_ADDR0 192
#define ETH_GW_ADDR1 168
#define ETH_GW_ADDR2 0
#define ETH_GW_ADDR3 1
#endif
/* Private define ------------------------------------------------------------*/
#define MAX_DHCP_TRIES 10
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
struct netif xnetif[NET_IF_NUM]; /* network interface structure */
/* Private functions ---------------------------------------------------------*/
/**
* @brief Initializes the lwIP stack
* @param None
* @retval None
*/
#if CONFIG_WLAN
extern int error_flag;
extern rtw_mode_t wifi_mode;
#endif
int lwip_init_done = 0;
void LwIP_Init(void)
{
ip_addr_t ipaddr;
ip_addr_t netmask;
ip_addr_t gw;
int8_t idx = 0;
/* Create tcp_ip stack thread */
tcpip_init( NULL, NULL );
/* - netif_add(struct netif *netif, struct ip_addr *ipaddr,
struct ip_addr *netmask, struct ip_addr *gw,
void *state, err_t (* init)(struct netif *netif),
err_t (* input)(struct pbuf *p, struct netif *netif))
Adds your network interface to the netif_list. Allocate a struct
netif and pass a pointer to this structure as the first argument.
Give pointers to cleared ip_addr structures when using DHCP,
or fill them with sane numbers otherwise. The state pointer may be NULL.
The init function pointer must point to a initialization function for
your ethernet netif interface. The following code illustrates it's use.*/
//printf("NET_IF_NUM:%d\n\r",NET_IF_NUM);
for(idx=0;idx<NET_IF_NUM;idx++){
if(idx==0){
IP4_ADDR((&ipaddr), IP_ADDR0, IP_ADDR1, IP_ADDR2, IP_ADDR3);
IP4_ADDR((&netmask), NETMASK_ADDR0, NETMASK_ADDR1 , NETMASK_ADDR2, NETMASK_ADDR3);
IP4_ADDR((&gw), GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3);
}
else{
IP4_ADDR((&ipaddr), AP_IP_ADDR0, AP_IP_ADDR1, AP_IP_ADDR2, AP_IP_ADDR3);
IP4_ADDR((&netmask), AP_NETMASK_ADDR0, AP_NETMASK_ADDR1 , AP_NETMASK_ADDR2, AP_NETMASK_ADDR3);
IP4_ADDR((&gw), AP_GW_ADDR0, AP_GW_ADDR1, AP_GW_ADDR2, AP_GW_ADDR3);
}
#if CONFIG_ETHERNET
if(idx == NET_IF_NUM - 1)
{
IP4_ADDR(&ipaddr, ETH_IP_ADDR0, ETH_IP_ADDR1, ETH_IP_ADDR2, ETH_IP_ADDR3);
IP4_ADDR(&netmask, ETH_NETMASK_ADDR0, ETH_NETMASK_ADDR1 , ETH_NETMASK_ADDR2, ETH_NETMASK_ADDR3);
IP4_ADDR(&gw, ETH_GW_ADDR0, ETH_GW_ADDR1, ETH_GW_ADDR2, ETH_GW_ADDR3);
}
#endif
xnetif[idx].name[0] = 'r';
xnetif[idx].name[1] = '0'+idx;
#if CONFIG_ETHERNET
if(idx == NET_IF_NUM - 1)
netif_add(&xnetif[idx], &ipaddr, &netmask, &gw, NULL, &ethernetif_mii_init, &tcpip_input);
else
netif_add(&xnetif[idx], &ipaddr, &netmask, &gw, NULL, &ethernetif_init, &tcpip_input);
#else
netif_add(&xnetif[idx], &ipaddr, &netmask, &gw, NULL, &ethernetif_init, &tcpip_input);
#endif
printf("interface %d is initialized\n", idx);
}
/* Registers the default network interface. */
netif_set_default(&xnetif[0]);
/*move these operations to wifi_on/wifi_off*/
#if 0
/* When the netif is fully configured this function must be called.*/
for(idx = 0;idx < NET_IF_NUM;idx++)
netif_set_up(&xnetif[idx]);
#endif
lwip_init_done = 1;
}
/**
* @brief LwIP_DHCP_Process_Handle
* @param None
* @retval None
*/
uint8_t LwIP_DHCP(uint8_t idx, uint8_t dhcp_state)
{
ip_addr_t ipaddr;
ip_addr_t netmask;
ip_addr_t gw;
uint32_t IPaddress;
uint8_t iptab[4];
uint8_t DHCP_state;
int mscnt = 0;
struct netif *pnetif = NULL;
DHCP_state = dhcp_state;
#if !CONFIG_ETHERNET
if(idx > 1)
idx = 1;
#endif
pnetif = &xnetif[idx];
struct dhcp *dhcp = netif_dhcp_data(pnetif);
if(DHCP_state == 0){
pnetif->ip_addr.addr = 0;
pnetif->netmask.addr = 0;
pnetif->gw.addr = 0;
}
for (;;)
{
//printf("\n\r ========DHCP_state:%d============\n\r",DHCP_state);
switch (DHCP_state)
{
case DHCP_START:
{
#if CONFIG_WLAN
wifi_unreg_event_handler(WIFI_EVENT_BEACON_AFTER_DHCP, wifi_rx_beacon_hdl);
#endif
dhcp_start(pnetif);
IPaddress = 0;
DHCP_state = DHCP_WAIT_ADDRESS;
}
break;
case DHCP_WAIT_ADDRESS:
{
/* If DHCP stopped by wifi_disconn_hdl*/
if(dhcp->state == 0)
{
printf("\n\rLwIP_DHCP: dhcp stop.");
return DHCP_STOP;
}
/* Read the new IP address */
IPaddress = pnetif->ip_addr.addr;
if (IPaddress!=0)
{
DHCP_state = DHCP_ADDRESS_ASSIGNED;
#if CONFIG_WLAN
wifi_reg_event_handler(WIFI_EVENT_BEACON_AFTER_DHCP, wifi_rx_beacon_hdl, NULL);
#endif
/* Stop DHCP */
// dhcp_stop(pnetif); /* can not stop, need to renew, Robbie*/
iptab[0] = (uint8_t)(IPaddress >> 24);
iptab[1] = (uint8_t)(IPaddress >> 16);
iptab[2] = (uint8_t)(IPaddress >> 8);
iptab[3] = (uint8_t)(IPaddress);
printf("\n\rInterface %d IP address : %d.%d.%d.%d", idx, iptab[3], iptab[2], iptab[1], iptab[0]);
#if CONFIG_WLAN
error_flag = RTW_NO_ERROR;
#endif
return DHCP_ADDRESS_ASSIGNED;
}
else
{
/* DHCP timeout */
if (dhcp->tries > MAX_DHCP_TRIES)
{
DHCP_state = DHCP_TIMEOUT;
/* Stop DHCP */
dhcp_stop(pnetif);
/* Static address used */
IP4_ADDR(&ipaddr, IP_ADDR0 ,IP_ADDR1 , IP_ADDR2 , IP_ADDR3 );
IP4_ADDR(&netmask, NETMASK_ADDR0, NETMASK_ADDR1, NETMASK_ADDR2, NETMASK_ADDR3);
IP4_ADDR(&gw, GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3);
netif_set_addr(pnetif, &ipaddr , &netmask, &gw);
iptab[0] = IP_ADDR3;
iptab[1] = IP_ADDR2;
iptab[2] = IP_ADDR1;
iptab[3] = IP_ADDR0;
printf("\n\rInterface %d DHCP timeout",idx);
printf("\n\rStatic IP address : %d.%d.%d.%d", iptab[3], iptab[2], iptab[1], iptab[0]);
#if CONFIG_WLAN
error_flag = RTW_DHCP_FAIL;
#endif
#if CONFIG_ETHERNET
if(idx == NET_IF_NUM -1) // This is the ethernet interface, set it up for static ip address
netif_set_up(pnetif);
#endif
return DHCP_TIMEOUT;
}else
{
//sys_msleep(DHCP_FINE_TIMER_MSECS);
rtw_msleep_os(DHCP_FINE_TIMER_MSECS);
dhcp_fine_tmr();
mscnt += DHCP_FINE_TIMER_MSECS;
if (mscnt >= DHCP_COARSE_TIMER_SECS*1000)
{
dhcp_coarse_tmr();
mscnt = 0;
}
}
}
}
break;
case DHCP_RELEASE_IP:
#if CONFIG_WLAN
wifi_unreg_event_handler(WIFI_EVENT_BEACON_AFTER_DHCP, wifi_rx_beacon_hdl);
#endif
printf("\n\rLwIP_DHCP: Release ip");
dhcp_release(pnetif);
return DHCP_RELEASE_IP;
case DHCP_STOP:
#if CONFIG_WLAN
wifi_unreg_event_handler(WIFI_EVENT_BEACON_AFTER_DHCP, wifi_rx_beacon_hdl);
#endif
printf("\n\rLwIP_DHCP: dhcp stop.");
dhcp_stop(pnetif);
return DHCP_STOP;
default:
break;
}
}
}
void LwIP_ReleaseIP(uint8_t idx)
{
ip_addr_t ipaddr;
ip_addr_t netmask;
ip_addr_t gw;
struct netif *pnetif = &xnetif[idx];
IP4_ADDR(&ipaddr, 0, 0, 0, 0);
IP4_ADDR(&netmask, 255, 255, 255, 0);
IP4_ADDR(&gw, 0, 0, 0, 0);
netif_set_addr(pnetif, &ipaddr , &netmask, &gw);
}
uint8_t* LwIP_GetMAC(struct netif *pnetif)
{
return (uint8_t *) (pnetif->hwaddr);
}
uint8_t* LwIP_GetIP(struct netif *pnetif)
{
return (uint8_t *) &(pnetif->ip_addr);
}
uint8_t* LwIP_GetGW(struct netif *pnetif)
{
return (uint8_t *) &(pnetif->gw);
}
uint8_t* LwIP_GetMASK(struct netif *pnetif)
{
return (uint8_t *) &(pnetif->netmask);
}
uint8_t* LwIP_GetBC(struct netif *pnetif)
{
return NULL;
}
#if LWIP_DNS
void LwIP_GetDNS(ip_addr_t* dns)
{
return;
}
void LwIP_SetDNS(ip_addr_t* dns)
{
//dns_setserver(0, (const ip_addr_t *)dns);
return;
}
#endif
void LwIP_UseStaticIP(struct netif *pnetif)
{
ip_addr_t ipaddr;
ip_addr_t netmask;
ip_addr_t gw;
/* Static address used */
if(pnetif->name[1] == '0'){
#if CONFIG_WLAN
if(wifi_mode == RTW_MODE_STA){
IP4_ADDR(&ipaddr, IP_ADDR0 ,IP_ADDR1 , IP_ADDR2 , IP_ADDR3 );
IP4_ADDR(&netmask, NETMASK_ADDR0, NETMASK_ADDR1, NETMASK_ADDR2, NETMASK_ADDR3);
IP4_ADDR(&gw, GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3);
}
else if(wifi_mode == RTW_MODE_AP){
IP4_ADDR(&ipaddr, AP_IP_ADDR0, AP_IP_ADDR1, AP_IP_ADDR2, AP_IP_ADDR3);
IP4_ADDR(&netmask, AP_NETMASK_ADDR0, AP_NETMASK_ADDR1 , AP_NETMASK_ADDR2, AP_NETMASK_ADDR3);
IP4_ADDR(&gw, AP_GW_ADDR0, AP_GW_ADDR1, AP_GW_ADDR2, AP_GW_ADDR3);
}
#endif
}else{
IP4_ADDR(&ipaddr, AP_IP_ADDR0, AP_IP_ADDR1, AP_IP_ADDR2, AP_IP_ADDR3);
IP4_ADDR(&netmask, AP_NETMASK_ADDR0, AP_NETMASK_ADDR1 , AP_NETMASK_ADDR2, AP_NETMASK_ADDR3);
IP4_ADDR(&gw, AP_GW_ADDR0, AP_GW_ADDR1, AP_GW_ADDR2, AP_GW_ADDR3);
}
netif_set_addr(pnetif, &ipaddr , &netmask, &gw);
}
#if LWIP_AUTOIP
#include <lwip/autoip.h>
void LwIP_AUTOIP(struct netif *pnetif)
{
uint8_t *ip = LwIP_GetIP(pnetif);
autoip_start(pnetif);
while((pnetif->autoip->state == AUTOIP_STATE_PROBING) || (pnetif->autoip->state == AUTOIP_STATE_ANNOUNCING)) {
rtw_msleep_os(1000);
}
if(*((uint32_t *) ip) == 0) {
ip_addr_t ipaddr;
ip_addr_t netmask;
ip_addr_t gw;
printf("AUTOIP timeout\n");
/* Static address used */
IP4_ADDR(&ipaddr, IP_ADDR0 ,IP_ADDR1 , IP_ADDR2 , IP_ADDR3 );
IP4_ADDR(&netmask, NETMASK_ADDR0, NETMASK_ADDR1, NETMASK_ADDR2, NETMASK_ADDR3);
IP4_ADDR(&gw, GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3);
netif_set_addr(pnetif, &ipaddr , &netmask, &gw);
printf("Static IP address : %d.%d.%d.%d\n", ip[0], ip[1], ip[2], ip[3]);
}
else {
printf("\nLink-local address: %d.%d.%d.%d\n", ip[0], ip[1], ip[2], ip[3]);
}
}
#endif
#if LWIP_IPV6
/* Get IPv6 address with lwip 1.5.0 */
void LwIP_AUTOIP_IPv6(struct netif *pnetif)
{
uint8_t *ipv6 = (uint8_t *) &(pnetif->ip6_addr[0].addr[0]);
netif_create_ip6_linklocal_address(pnetif, 1);
printf("\nIPv6 link-local address: %02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x\n",
ipv6[0], ipv6[1], ipv6[2], ipv6[3], ipv6[4], ipv6[5], ipv6[6], ipv6[7],
ipv6[8], ipv6[9], ipv6[10], ipv6[11], ipv6[12], ipv6[13], ipv6[14], ipv6[15]);
}
#endif
uint32_t LWIP_Get_Dynamic_Sleep_Interval()
{
#ifdef DYNAMIC_TICKLESS_SLEEP_INTERVAL
return DYNAMIC_TICKLESS_SLEEP_INTERVAL;
#else
return 0;
#endif
}

View file

@ -0,0 +1,92 @@
/**
******************************************************************************
* @file netconf.h
* @author MCD Application Team
* @version V1.1.0
* @date 07-October-2011
* @brief This file contains all the functions prototypes for the netconf.c
* file.
******************************************************************************
* @attention
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>&copy; COPYRIGHT 2011 STMicroelectronics</center></h2>
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __NETCONF_H
#define __NETCONF_H
#ifdef __cplusplus
extern "C" {
#endif
#include "tcpip.h"
/* Includes ------------------------------------------------------------------*/
#include <platform/platform_stdlib.h>
#include "platform_opts.h"
#include "autoconf.h"
// macros
/* Give default value if not defined */
#ifndef NET_IF_NUM
#ifdef CONFIG_CONCURRENT_MODE
#define NET_IF_NUM ((CONFIG_ETHERNET) + (CONFIG_WLAN) + 1)
#else
#define NET_IF_NUM ((CONFIG_ETHERNET) + (CONFIG_WLAN))
#endif // end of CONFIG_CONCURRENT_MODE
#endif // end of NET_IF_NUM
/* Private typedef -----------------------------------------------------------*/
typedef enum
{
DHCP_START=0,
DHCP_WAIT_ADDRESS,
DHCP_ADDRESS_ASSIGNED,
DHCP_RELEASE_IP,
DHCP_STOP,
DHCP_TIMEOUT
} DHCP_State_TypeDef;
/* Extern functions ------------------------------------------------------------*/
void wifi_rx_beacon_hdl( char* buf, int buf_len, int flags, void* userdata);
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
void LwIP_Init(void);
uint8_t LwIP_DHCP(uint8_t idx, uint8_t dhcp_state);
unsigned char* LwIP_GetMAC(struct netif *pnetif);
unsigned char* LwIP_GetIP(struct netif *pnetif);
unsigned char* LwIP_GetGW(struct netif *pnetif);
uint8_t* LwIP_GetMASK(struct netif *pnetif);
uint8_t* LwIP_GetBC(struct netif *pnetif);
#if LWIP_DNS
void LwIP_GetDNS(ip_addr_t* dns);
void LwIP_SetDNS(ip_addr_t* dns);
#endif
void LwIP_UseStaticIP(struct netif *pnetif);
#if LWIP_AUTOIP
void LwIP_AUTOIP(struct netif *pnetif);
#endif
#if LWIP_IPV6
void LwIP_AUTOIP_IPv6(struct netif *pnetif);
#endif
uint32_t LWIP_Get_Dynamic_Sleep_Interval();
#ifdef __cplusplus
}
#endif
#endif /* __NETCONF_H */
/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/

View file

@ -0,0 +1,258 @@
//#include "FreeRTOS.h"
//#include "task.h"
#include "main.h"
#include <lwip/sockets.h>
#include <lwip/raw.h>
#include <lwip/icmp.h>
#include <lwip/inet_chksum.h>
#include <lwip/netdb.h>
#include <platform/platform_stdlib.h>
#include "osdep_service.h"
#define PING_IP "192.168.159.1"
#define PING_TO 1000
#define PING_ID 0xABCD
#define BUF_SIZE 10000
#define STACKSIZE 1024
static unsigned short ping_seq = 0;
static int infinite_loop, ping_count, data_size, ping_interval, ping_call;
static char ping_ip[16];
static char host[64];
static int ping_total_time = 0, ping_received_count = 0;
struct task_struct g_ping_test_task;
static void generate_ping_echo(unsigned char *buf, int size)
{
int i;
struct icmp_echo_hdr *pecho;
for(i = 0; i < size; i ++) {
buf[sizeof(struct icmp_echo_hdr) + i] = (unsigned char) i;
}
pecho = (struct icmp_echo_hdr *) buf;
ICMPH_TYPE_SET(pecho, ICMP_ECHO);
ICMPH_CODE_SET(pecho, 0);
pecho->chksum = 0;
pecho->id = PING_ID;
pecho->seqno = htons(++ ping_seq);
//Checksum includes icmp header and data. Need to calculate after fill up icmp header
pecho->chksum = inet_chksum(pecho, sizeof(struct icmp_echo_hdr) + size);
}
void ping_test(void *param)
{
int i, ping_socket;
int pint_timeout = PING_TO;
struct sockaddr_in to_addr, from_addr;
int from_addr_len = sizeof(struct sockaddr);
int ping_size, reply_size;
unsigned char *ping_buf, *reply_buf;
unsigned int ping_time, reply_time;
struct ip_hdr *iphdr;
struct icmp_echo_hdr *pecho;
unsigned int min_time = 1000, max_time = 0;
struct hostent *server_host;
ping_total_time = 0;
ping_received_count = 0;
if(data_size > BUF_SIZE){
printf("\n\r[ERROR] %s: data size error, can't exceed %d",__func__,BUF_SIZE);
return;
}
//Ping size = icmp header(8 bytes) + data size
ping_size = sizeof(struct icmp_echo_hdr) + data_size;
ping_buf = rtw_zmalloc(ping_size);
if(NULL == ping_buf){
printf("\n\r[ERROR] %s: Allocate ping_buf failed",__func__);
return;
}
reply_buf = rtw_zmalloc(ping_size);
if(NULL == reply_buf){
rtw_free(ping_buf);
printf("\n\r[ERROR] %s: Allocate reply_buf failed",__func__);
return;
}
printf("\n\r[%s] PING %s %d(%d) bytes of data\n", __FUNCTION__, host, data_size, sizeof(struct ip_hdr) + sizeof(struct icmp_echo_hdr) + data_size);
for(i = 0; (i < ping_count) || (infinite_loop == 1); i ++) {
ping_socket = socket(AF_INET, SOCK_RAW, IP_PROTO_ICMP);
#if defined(LWIP_SO_SNDRCVTIMEO_NONSTANDARD) && (LWIP_SO_SNDRCVTIMEO_NONSTANDARD == 0) // lwip 1.5.0
struct timeval timeout;
timeout.tv_sec = pint_timeout / 1000;
timeout.tv_usec = pint_timeout % 1000 * 1000;
setsockopt(ping_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
#else // lwip 1.4.1
setsockopt(ping_socket, SOL_SOCKET, SO_RCVTIMEO, &pint_timeout, sizeof(pint_timeout));
#endif
to_addr.sin_len = sizeof(to_addr);
to_addr.sin_family = AF_INET;
if (inet_aton(host, &to_addr.sin_addr) == 0) {
server_host = gethostbyname(host);
printf("\r\n host name %s, server %x\r\n", host, server_host);
if(server_host == NULL){
printf("\n\r[%s] Get host name failed in the %d ping test\n", __FUNCTION__, (i + 1));
close(ping_socket);
rtw_msleep_os(ping_interval * configTICK_RATE_HZ);
continue;
}
memcpy((void *) &to_addr.sin_addr, (void *) server_host->h_addr, server_host->h_length);
}
else
to_addr.sin_addr.s_addr = inet_addr(host);
generate_ping_echo(ping_buf, data_size);
sendto(ping_socket, ping_buf, ping_size, 0, (struct sockaddr *) &to_addr, sizeof(to_addr));
ping_time = rtw_get_current_time();
if((reply_size = recvfrom(ping_socket, reply_buf, ping_size, 0, (struct sockaddr *) &from_addr, (socklen_t *) &from_addr_len))
>= (int)(sizeof(struct ip_hdr) + sizeof(struct icmp_echo_hdr)) && (from_addr.sin_addr.s_addr == to_addr.sin_addr.s_addr)) {
reply_time = rtw_get_current_time();
iphdr = (struct ip_hdr *)reply_buf;
pecho = (struct icmp_echo_hdr *)(reply_buf + (IPH_HL(iphdr) * 4));
if((pecho->id == PING_ID) && (pecho->seqno == htons(ping_seq))) {
printf("\n\r[%s] %d bytes from %s: icmp_seq=%d time=%d ms", __FUNCTION__, reply_size - sizeof(struct icmp_echo_hdr), inet_ntoa(from_addr.sin_addr), htons(pecho->seqno), (reply_time - ping_time));
ping_received_count++;
ping_total_time += (reply_time - ping_time);
if((reply_time - ping_time) > max_time) max_time = (reply_time - ping_time);
if((reply_time - ping_time) < min_time) min_time = (reply_time - ping_time);
}
}
else
printf("\n\r[%s] Request timeout for icmp_seq %d\n", __FUNCTION__, ping_seq);
close(ping_socket);
rtw_msleep_os(ping_interval * configTICK_RATE_HZ);
}
printf("\n\r[%s] %d packets transmitted, %d received, %d%% packet loss, average %d ms", __FUNCTION__, ping_count, ping_received_count, (ping_count-ping_received_count)*100/ping_count, ping_total_time/ping_received_count);
printf("\n\r[%s] min: %d ms, max: %d ms\n\r", __FUNCTION__, min_time, max_time);
rtw_free(ping_buf);
rtw_free(reply_buf);
if(!ping_call)
rtw_delete_task(&g_ping_test_task);
}
void do_ping_call(char *ip, int loop, int count)
{
ping_call = 1;
ping_seq = 0;
data_size = 120;
ping_interval = 1;
infinite_loop = loop;
ping_count = count;
strcpy(ping_ip, ip);
ping_test(NULL);
}
int get_ping_report(int *ping_lost){
*ping_lost = ping_count - ping_received_count;
return 0;
}
void cmd_ping(int argc, char **argv)
{
int argv_count = 2;
printf("\n\r[ATWI] argc %d, argv, 1 %s, 2 %s, 3 %s\n", argc, argv[0], argv[1], argv[2]);
if(argc < 2)
goto Exit;
//ping cmd default value
infinite_loop = 0;
ping_count = 4;
data_size = 32;
ping_interval = 1;
ping_call = 1;
ping_seq = 0;
while(argv_count<=argc){
//first operation
if(argv_count == 2){
memset(host, 0, sizeof(host));
strncpy(host, argv[argv_count-1], strlen(argv[argv_count-1]));
argv_count++;
}
else{
if(strcmp(argv[argv_count-1], "-t") == 0){
infinite_loop = 1;
argv_count++;
}
else if(strcmp(argv[argv_count-1], "-n") == 0){
if(argc < (argv_count+1))
goto Exit;
ping_count = (int) atoi(argv[argv_count]);
argv_count+=2;
}
else if(strcmp(argv[argv_count-1], "-l") == 0){
if(argc < (argv_count+1))
goto Exit;
data_size = (int) atoi(argv[argv_count]);
argv_count+=2;
}
else{
goto Exit;
}
}
}
ping_test(NULL);
return;
Exit:
printf("\n\r[ATWI] Usage: ATWI=[host],[options]\n");
printf("\n\r -t Ping the specified host until stopped\n");
printf(" \r -n # Number of echo requests to send (default 4 times)\n");
printf(" \r -l # Send buffer size (default 32 bytes)\n");
printf("\n\r Example:\n");
printf(" \r ATWI=192.168.1.2,-n,100,-l,5000\n");
return;
}
void do_ping_test(char *ip, int size, int count, int interval)
{
if((sizeof(struct icmp_echo_hdr) + size) > BUF_SIZE) {
printf("\n\r%s BUF_SIZE(%d) is too small", __FUNCTION__, BUF_SIZE);
return;
}
if(ip == NULL)
strcpy(ping_ip, PING_IP);
else
strcpy(ping_ip, ip);
ping_call = 0;
ping_seq = 0;
data_size = size;
ping_interval = interval;
if(count == 0) {
infinite_loop = 1;
ping_count = 0;
}
else {
infinite_loop = 0;
ping_count = count;
}
//if(xTaskCreate(ping_test, ((const signed char*)"ping_test"), STACKSIZE, NULL, tskIDLE_PRIORITY + 1, NULL) != pdPASS)
// printf("\n\r%s xTaskCreate failed", __FUNCTION__);
if(rtw_create_task(&g_ping_test_task, "ping_test", STACKSIZE, 5, ping_test, NULL) != pdPASS)
printf("\r\nUDP ERROR: Create ping test task failed.");
}

View file

@ -0,0 +1,75 @@
/*
* Hello World
*
* Copyright (c) 2013 Realtek Semiconductor Corp.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*/
//#include "FreeRTOS.h"
//#include "task.h"
//#include "semphr.h"
#include "main.h"
//#include "main_test.h"
#if CONFIG_WLAN
#include "wifi_conf.h"
#include "wlan_intf.h"
#include "wifi_constants.h"
#endif
#include "lwip_netconf.h"
#include <platform/platform_stdlib.h>
#include "osdep_service.h"
#ifndef CONFIG_INIT_NET
#define CONFIG_INIT_NET 1
#endif
#ifndef CONFIG_INTERACTIVE_MODE
#define CONFIG_INTERACTIVE_MODE 1
#endif
#define STACKSIZE (512 + 768)
//xSemaphoreHandle uart_rx_interrupt_sema = NULL;
void init_thread(void *param)
{
#if CONFIG_INIT_NET
#if CONFIG_LWIP_LAYER
/* Initilaize the LwIP stack */
LwIP_Init();
#endif
#endif
#if CONFIG_WIFI_IND_USE_THREAD
wifi_manager_init();
#endif
#if CONFIG_WLAN
wifi_on(RTW_MODE_STA);
#if CONFIG_AUTO_RECONNECT
//setup reconnection flag
wifi_set_autoreconnect(RTW_AUTORECONNECT_INFINITE);
#endif
printf("\n\r%s(%d), Available heap 0x%x", __FUNCTION__, __LINE__, rtw_getFreeHeapSize());
#endif
#if CONFIG_INTERACTIVE_MODE
/* Initial uart rx swmaphore*/
//vSemaphoreCreateBinary(uart_rx_interrupt_sema);
//xSemaphoreTake(uart_rx_interrupt_sema, 1/portTICK_RATE_MS);
//start_interactive_mode();
#endif
/* Kill init thread after all init tasks done */
krhino_task_dyn_del(NULL);
}
void wlan_network()
{
ktask_t *g_wlan_init_task;
if(krhino_task_dyn_create(&g_wlan_init_task, "wlan_init", 0, 6, 0, STACKSIZE, (task_entry_t)init_thread, 1) != RHINO_SUCCESS)
printf("\n\r%s xTaskCreate(init_thread) failed", __FUNCTION__);
}

View file

@ -0,0 +1,262 @@
#ifndef __LIST_H
#define __LIST_H
#if defined ( __CC_ARM )
#ifndef inline
#define inline __inline
#endif
#endif
/* This file is from Linux Kernel (include/linux/list.h)
* and modified by simply removing hardware prefetching of list items.
* Here by copyright, credits attributed to wherever they belong.
* Kulesh Shanmugasundaram (kulesh [squiggly] isis.poly.edu)
*/
/*
* Simple doubly linked list implementation.
*
* Some of the internal functions ("__xxx") are useful when
* manipulating whole lists rather than single entries, as
* sometimes we already know the next/prev entries and we can
* generate better code by using them directly rather than
* using the generic single-entry routines.
*/
struct list_head {
struct list_head *next, *prev;
};
#define LIST_HEAD_INIT(name) { &(name), &(name) }
#define LIST_HEAD(name) \
struct list_head name = LIST_HEAD_INIT(name)
#define INIT_LIST_HEAD(ptr) do { \
(ptr)->next = (ptr); (ptr)->prev = (ptr); \
} while (0)
/*
* Insert a new entry between two known consecutive entries.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
static inline void __list_add(struct list_head *newitem,
struct list_head *prev,
struct list_head *next)
{
next->prev = newitem;
newitem->next = next;
newitem->prev = prev;
prev->next = newitem;
}
/**
* list_add - add a new entry
* @new: new entry to be added
* @head: list head to add it after
*
* Insert a new entry after the specified head.
* This is good for implementing stacks.
*/
static inline void list_add(struct list_head *newitem, struct list_head *head)
{
__list_add(newitem, head, head->next);
}
/**
* list_add_tail - add a new entry
* @new: new entry to be added
* @head: list head to add it before
*
* Insert a new entry before the specified head.
* This is useful for implementing queues.
*/
static inline void list_add_tail(struct list_head *newitem, struct list_head *head)
{
__list_add(newitem, head->prev, head);
}
/*
* Delete a list entry by making the prev/next entries
* point to each other.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
static inline void __list_del(struct list_head *prev, struct list_head *next)
{
next->prev = prev;
prev->next = next;
}
/**
* list_del - deletes entry from list.
* @entry: the element to delete from the list.
* Note: list_empty on entry does not return true after this, the entry is in an undefined state.
*/
static inline void list_del(struct list_head *entry)
{
__list_del(entry->prev, entry->next);
entry->next = (struct list_head *) 0;
entry->prev = (struct list_head *) 0;
}
/**
* list_del_init - deletes entry from list and reinitialize it.
* @entry: the element to delete from the list.
*/
static inline void list_del_init(struct list_head *entry)
{
__list_del(entry->prev, entry->next);
INIT_LIST_HEAD(entry);
}
/**
* list_move - delete from one list and add as another's head
* @list: the entry to move
* @head: the head that will precede our entry
*/
static inline void list_move(struct list_head *list, struct list_head *head)
{
__list_del(list->prev, list->next);
list_add(list, head);
}
/**
* list_move_tail - delete from one list and add as another's tail
* @list: the entry to move
* @head: the head that will follow our entry
*/
static inline void list_move_tail(struct list_head *list,
struct list_head *head)
{
__list_del(list->prev, list->next);
list_add_tail(list, head);
}
/**
* list_empty - tests whether a list is empty
* @head: the list to test.
*/
static inline int list_empty(struct list_head *head)
{
return head->next == head;
}
static inline void __list_splice(struct list_head *list,
struct list_head *head)
{
struct list_head *first = list->next;
struct list_head *last = list->prev;
struct list_head *at = head->next;
first->prev = head;
head->next = first;
last->next = at;
at->prev = last;
}
/**
* list_splice - join two lists
* @list: the new list to add.
* @head: the place to add it in the first list.
*/
static inline void list_splice(struct list_head *list, struct list_head *head)
{
if (!list_empty(list))
__list_splice(list, head);
}
/**
* list_splice_init - join two lists and reinitialise the emptied list.
* @list: the new list to add.
* @head: the place to add it in the first list.
*
* The list at @list is reinitialised
*/
static inline void list_splice_init(struct list_head *list,
struct list_head *head)
{
if (!list_empty(list)) {
__list_splice(list, head);
INIT_LIST_HEAD(list);
}
}
/**
* list_entry - get the struct for this entry
* @ptr: the &struct list_head pointer.
* @type: the type of the struct this is embedded in.
* @member: the name of the list_struct within the struct.
*/
#define list_entry(ptr, type, member) \
((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))
/**
* list_first_entry - get the first element from a list
* @ptr: the list head to take the element from.
* @type: the type of the struct this is embedded in.
* @member: the name of the list_head within the struct.
*
* Note, that list is expected to be not empty.
*/
#define list_first_entry(ptr, type, member) \
list_entry((ptr)->next, type, member)
/**
* list_for_each - iterate over a list
* @pos: the &struct list_head to use as a loop counter.
* @head: the head for your list.
*/
#define list_for_each(pos, head) \
for (pos = (head)->next; pos != (head); \
pos = pos->next)
/**
* list_for_each_prev - iterate over a list backwards
* @pos: the &struct list_head to use as a loop counter.
* @head: the head for your list.
*/
#define list_for_each_prev(pos, head) \
for (pos = (head)->prev; pos != (head); \
pos = pos->prev)
/**
* list_for_each_safe - iterate over a list safe against removal of list entry
* @pos: the &struct list_head to use as a loop counter.
* @n: another &struct list_head to use as temporary storage
* @head: the head for your list.
*/
#define list_for_each_safe(pos, n, head) \
for (pos = (head)->next, n = pos->next; pos != (head); \
pos = n, n = pos->next)
/**
* list_for_each_entry - iterate over list of given type
* @pos: the type * to use as a loop counter.
* @head: the head for your list.
* @member: the name of the list_struct within the struct.
*/
#define list_for_each_entry(pos, head, member, type) \
for (pos = list_entry((head)->next, type, member); \
&pos->member != (head); \
pos = list_entry(pos->member.next, type, member))
/**
* list_for_each_entry_safe - iterate over list of given type safe against removal of list entry
* @pos: the type * to use as a loop counter.
* @n: another type * to use as temporary storage
* @head: the head for your list.
* @member: the name of the list_struct within the struct.
*/
#define list_for_each_entry_safe(pos, n, head, member, type) \
for (pos = list_entry((head)->next, type, member), \
n = list_entry(pos->member.next, type, member); \
&pos->member != (head); \
pos = n, n = list_entry(n->member.next, type, member))
#endif

View file

@ -0,0 +1,261 @@
/******************************************************************************
*
* Copyright(c) 2007 - 2014 Realtek Corporation. All rights reserved.
*
*
******************************************************************************/
#ifndef __PLATFORM_STDLIB_H__
#define __PLATFORM_STDLIB_H__
#define USE_CLIB_PATCH 0
#if defined (__GNUC__)
/* build rom should set USE_RTL_ROM_CLIB=0 */
#include <rt_lib_rom.h>
#endif
#ifdef CONFIG_BUILD_ROM
#define USE_RTL_ROM_CLIB 0
#else
#define BUFFERED_PRINTF 0
#define USE_RTL_ROM_CLIB 1
#endif
#if defined(CONFIG_PLATFORM_8195A)
#if defined (__IARSTDLIB__)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "diag.h"
#define strsep(str, delim) _strsep(str, delim)
#else
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "diag.h"
#include "strproc.h"
#include "basic_types.h"
#include "hal_misc.h"
#if USE_RTL_ROM_CLIB
#include "rtl_lib.h"
#endif
#undef printf
#undef sprintf
#undef snprintf
#undef atoi
#undef memcmp
#undef memcpy
#undef memset
#undef strcmp
#undef strcpy
#undef strlen
#undef strncmp
#undef strncpy
#undef strsep
#undef strtok
#if USE_RTL_ROM_CLIB
#undef memchr
#undef memmove
#undef strcat
#undef strchr
#undef strncat
#undef strstr
#endif
#if USE_RTL_ROM_CLIB
#if BUFFERED_PRINTF
extern int buffered_printf(const char* fmt, ...);
#define printf buffered_printf
#else
#define printf rtl_printf
#endif
#define sprintf rtl_sprintf
#define snprintf rtl_snprintf
#define memchr rtl_memchr
#define memcmp rtl_memcmp
#define memcpy rtl_memcpy
#define memmove rtl_memmove
#define memset rtl_memset
#define strcat rtl_strcat
#define strchr rtl_strchr
#define strcmp(s1, s2) rtl_strcmp((const char *)s1, (const char *)s2)
#define strcpy rtl_strcpy
#define strlen(str) rtl_strlen((const char *)str)
#define strncat rtl_strncat
#define strncmp(s1, s2, n) rtl_strncmp((const char *)s1, (const char *)s2, n)
#define strncpy rtl_strncpy
#define strstr rtl_strstr
#define strsep rtl_strsep
#define strtok rtl_strtok
#else
#if USE_CLIB_PATCH
extern int DiagSscanfPatch(const char *buf, const char *fmt, ...);
extern char* DiagStrtokPatch(char *str, const char* delim);
extern char* DiagStrstrPatch(char *string, char *substring);
extern int DiagSnPrintfPatch(char *buf, size_t size, const char *fmt, ...);
extern u32 DiagPrintfPatch(const char *fmt, ...);
extern u32 DiagSPrintfPatch(u8 *buf, const char *fmt, ...);
#define printf DiagPrintfPatch
#define sprintf DiagSPrintfPatch
#define snprintf DiagSnPrintfPatch
#define strstr(a, b) DiagStrstrPatch((char *)(a), (char *)(b))
#define strtok DiagStrtokPatch
#else
#define printf DiagPrintf
#define sprintf(fmt, arg...) DiagSPrintf((u8*)fmt, ##arg)
#if defined (__GNUC__)
#define snprintf DiagSnPrintf // NULL function
#define strstr(str1, str2) prvStrStr(str1, str2) // NULL function
#endif
#define strtok(str, delim) _strsep(str, delim)
#endif
#define memcmp(dst, src, sz) _memcmp(dst, src, sz)
#define memcpy(dst, src, sz) _memcpy(dst, src, sz)
#define memset(dst, val, sz) _memset(dst, val, sz)
#define strchr(s, c) _strchr(s, c) // for B-cut ROM
#define strcmp(str1, str2) prvStrCmp((const unsigned char *) str1, (const unsigned char *) str2)
#define strcpy(dest, src) _strcpy(dest, src)
#define strlen(str) prvStrLen((const unsigned char *) str)
#define strncmp(str1, str2, cnt) _strncmp(str1, str2, cnt)
#define strncpy(dest, src, count) _strncpy(dest, src, count)
#define strsep(str, delim) _strsep(str, delim)
#endif
#define atoi(str) prvAtoi(str)
#define strpbrk(cs, ct) _strpbrk(cs, ct) // for B-cut ROM
#if USE_CLIB_PATCH
#undef sscanf
#define sscanf DiagSscanfPatch
#else
#if defined (__GNUC__)
#undef sscanf //_sscanf
//extern int DiagSscanfPatch(const char *buf, const char *fmt, ...);
//#define sscanf DiagSscanfPatch
#define sscanf sscanf // use libc sscanf
#endif
#endif
#endif // defined (__IARSTDLIB__)
//
// memory management
//
extern void *pvPortMalloc( size_t xWantedSize );
extern void vPortFree( void *pv );
#define malloc pvPortMalloc
#define free vPortFree
#elif defined (CONFIG_PLATFORM_8711B)
#if defined (__IARSTDLIB__)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdarg.h> /* va_list */
#include "diag.h"
#define strsep(str, delim) _strsep(str, delim)
#else
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h> /* va_list */
#include "diag.h"
#include "strproc.h"
#include "memproc.h"
#include "basic_types.h"
#if USE_RTL_ROM_CLIB
#include "rtl_lib.h"
#include "rom_libc_string.h"
#endif
#undef printf
#undef sprintf
#undef snprintf
#undef memchr
#undef memcmp
#undef memcpy
#undef memset
#undef memmove
#undef strcmp
#undef strcpy
#undef strlen
#undef strncmp
#undef strncpy
#undef strsep
#undef strtok
#undef strcat
#undef strchr
#undef strncat
#undef strstr
#undef atol
#undef atoi
#undef strpbrk
#if USE_RTL_ROM_CLIB
#if BUFFERED_PRINTF
extern int buffered_printf(const char* fmt, ...);
#define printf buffered_printf
#else
#define printf DiagPrintf
#endif
#define sprintf rtl_sprintf
#define snprintf rtl_snprintf
#define vsnprintf rtl_vsnprintf
#else
#define printf DiagPrintf
#define sprintf(fmt, arg...) DiagSPrintf((u8*)fmt, ##arg)
#define snprintf DiagSnPrintf // NULL function
#define vsnprintf(buf, size, fmt, ap) VSprintf(buf, fmt, ap)
#endif
#define memchr __rtl_memchr_v1_00
#define memcmp(dst, src, sz) _memcmp(dst, src, sz)
#define memcpy(dst, src, sz) _memcpy(dst, src, sz)
#define memmove __rtl_memmove_v1_00
#define memset(dst, val, sz) _memset(dst, val, sz)
#define strchr(s, c) _strchr(s, c) // for B-cut ROM
#define strcmp(str1, str2) prvStrCmp((const unsigned char *) str1, (const unsigned char *) str2)
#define strcpy(dest, src) _strcpy(dest, src)
#define strlen(str) prvStrLen((const unsigned char *) str)
#define strsep(str, delim) _strsep(str, delim)
#define strstr(str1, str2) prvStrStr(str1, str2) // NULL function
#define strtok(str, delim) prvStrtok(str, delim)//_strsep(str, delim)
#define strcat __rtl_strcat_v1_00
#define strncmp(str1, str2, cnt) _strncmp(str1, str2, cnt)
#define strncpy(dest, src, count) _strncpy(dest, src, count)
#define strncat __rtl_strncat_v1_00
#define atol(str) strtol(str,NULL,10)
#define atoi(str) prvAtoi(str)
#define strpbrk(cs, ct) _strpbrk(cs, ct) // for B-cut ROM
#if defined (__GNUC__)
#undef sscanf
#define sscanf _sscanf_patch
#define rand Rand
#endif
//extern int _sscanf_patch(const char *buf, const char *fmt, ...);
//#define sscanf _sscanf_patch
#endif // defined (__IARSTDLIB__)
//
// memory management
//
extern void *pvPortMalloc( size_t xWantedSize );
extern void vPortFree( void *pv );
#define malloc pvPortMalloc
#define free vPortFree
#elif defined(USE_STM322xG_EVAL) || defined(USE_STM324xG_EVAL) || defined(STM32F10X_XL)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#endif
#endif //__PLATFORM_STDLIB_H__

View file

@ -0,0 +1,918 @@
/*
this is the c lib patch, It can help when the clib provided by IAR
does not work well.
How to use this:
1.You must include platform_stdlib.h in you source file
2.There is a macro USE_CLIB_PATCH in platform_stdlib.h should be opened.
If there is some problems using this patch,
You'd better check if you code runs into these functions:
DiagSscanfPatch
DiagStrtokPatch
DiagStrstrPatch
DiagSnPrintfPatch
DiagPrintfPatch
DiagSPrintfPatch
DiagPrintfPatch
DiagSPrintfPatch
DiagSnPrintfPatch
DiagStrstrPatch
DiagStrtokPatch
*/
#ifndef CONFIG_PLATFORM_8711B
#include <stdarg.h>
#define DiagPutChar HalSerialPutcRtl8195a
#define IN
#define NULL 0
typedef unsigned int size_t;
typedef unsigned int SIZE_T;
typedef unsigned long long u64;
typedef unsigned int u32;
typedef unsigned short int u16;
typedef unsigned char u8;
typedef signed long long s64;
typedef signed int s32;
typedef signed short int s16;
typedef unsigned char bool;
#define in_range(c, lo, up) ((u8)c >= lo && (u8)c <= up)
#define isprint(c) in_range(c, 0x20, 0x7f)
#define isdigit(c) in_range(c, '0', '9')
#define isxdigit(c) (isdigit(c) || in_range(c, 'a', 'f') || in_range(c, 'A', 'F'))
#define islower(c) in_range(c, 'a', 'z')
#define isspace(c) (c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v' || c == ',')
#define ULLONG_MAX (~0ULL)
#define USHRT_MAX ((u16)(~0U))
#define KSTRTOX_OVERFLOW (1U << 31)
#define SHRT_MAX ((s16)(USHRT_MAX>>1))
static inline char _tolower(const char c)
{
return c | 0x20;
}
extern s64 div_s64_rem(s64 dividend, s32 divisor, s32 *remainder);
extern s64 div_s64(s64 dividend, s32 divisor);
extern inline char _tolower(const char c);
extern u64 div_u64_rem(u64 dividend, u32 divisor, u32 *remainder);
extern u64 div_u64(u64 dividend, u32 divisor);
extern unsigned int _parse_integer(const char *s, unsigned int base, unsigned long long *p);
extern const char *_parse_integer_fixup_radix(const char *s, unsigned int *base);
extern char *skip_spaces(const char *str);
extern int skip_atoi(const char **s);
extern void HalSerialPutcRtl8195a(u8 c);
static unsigned long long simple_strtoull_patch(const char *cp, char **endp, unsigned int base)
{
unsigned long long result;
unsigned int rv;
cp = _parse_integer_fixup_radix(cp, &base);
rv = _parse_integer(cp, base, &result);
return result;
}
static long long simple_strtoll_patch(const char *cp, char **endp, unsigned int base)
{
if(*cp == '-')
return -simple_strtoull_patch(cp + 1, endp, base);
return simple_strtoull_patch(cp, endp, base);
}
static unsigned long simple_strtoul_patch(const char *cp, char **endp, unsigned int base)
{
return simple_strtoull_patch(cp, endp, base);
}
static long simple_strtol_patch(const char *cp, char **endp, unsigned int base)
{
if(*cp == '-')
return -simple_strtoul_patch(cp + 1, endp, base);
return simple_strtoul_patch(cp, endp, base);
}
static int judge_digit_width(const char *str)
{
int width = 0;
while(isdigit(*str)) {
width++;
str++;
}
return width;
}
static int _vsscanf_patch(const char *buf, const char *fmt, va_list args)
{
const char *str = buf;
char *next;
char digit;
int num = 0;
int i =0;
u8 qualifier;
unsigned int base;
union {
long long s;
unsigned long long u;
} val;
s16 field_width;
bool is_sign;
char str_store[20] = {0};
while(*fmt) {
/* skip any white space in format */
/* white space in format matchs any amount of
* white space, including none, in the input.
*/
if(isspace(*fmt)) {
fmt = skip_spaces(++fmt);
str = skip_spaces(str);
}
/* anything that is not a conversion must match exactly */
if(*fmt != '%' && *fmt) {
if(*fmt++ != *str++) {
break;
}
continue;
}
if(!*fmt) {
break;
}
++fmt;
/* skip this conversion.
* advance both strings to next white space
*/
if(*fmt == '*') {
if(!*str) {
break;
}
while(!isspace(*fmt) && *fmt != '%' && *fmt)
fmt++;
while(!isspace(*str) && *str)
str++;
continue;
}
/* get field width */
field_width = -1;
if(isdigit(*fmt)) {
field_width = skip_atoi(&fmt);
if(field_width <= 0) {
break;
}
}
/* get conversion qualifier */
qualifier = -1;
if(*fmt == 'h' || _tolower(*fmt) == 'l' ||
_tolower(*fmt) == 'z') {
qualifier = *fmt++;
if(qualifier == *fmt) {
if(qualifier == 'h') {
qualifier = 'H';
fmt++;
} else if(qualifier == 'l') {
qualifier = 'L';
fmt++;
}
}
}
if(!*fmt) {
break;
}
if(*fmt == 'n') {
/* return number of characters read so far */
*va_arg(args, int *) = str - buf;
++fmt;
continue;
}
if(!*str) {
break;
}
base = 10;
is_sign = 0;
switch(*fmt++) {
case 'c': {
char *s = (char *)va_arg(args, char*);
if(field_width == -1)
field_width = 1;
do {
*s++ = *str++;
} while(--field_width > 0 && *str);
num++;
}
continue;
case 's': {
char *s = (char *)va_arg(args, char *);
if(field_width == -1)
field_width = SHRT_MAX;
/* first, skip leading white space in buffer */
str = skip_spaces(str);
/* now copy until next white space */
while(*str && !isspace(*str) && field_width--) {
*s++ = *str++;
}
*s = '\0';
num++;
}
continue;
case 'o':
base = 8;
break;
case 'x':
case 'X':
base = 16;
break;
case 'i':
base = 0;
case 'd':
is_sign = 1;
case 'u':
break;
case '%':
/* looking for '%' in str */
if(*str++ != '%') {
return num;
}
continue;
default:
/* invalid format; stop here */
return num;
}
/* have some sort of integer conversion.
* first, skip white space in buffer.
*/
str = skip_spaces(str);
digit = *str;
if(is_sign && digit == '-')
digit = *(str + 1);
if(!digit
|| (base == 16 && !isxdigit(digit))
|| (base == 10 && !isdigit(digit))
|| (base == 8 && (!isdigit(digit) || digit > '7'))
|| (base == 0 && !isdigit(digit))) {
break;
}
//here problem *******************************************
//troy add ,fix support %2d, but not support %d
if(field_width <= 0) {
field_width = judge_digit_width(str);
}
/////troy add, fix str passed inwidth wrong
for(i = 0; i<field_width ; i++)
str_store[i] = str[i];
next = (char*)str + field_width;
if(is_sign) {
val.s = qualifier != 'L' ?
simple_strtol_patch(str_store, &next, base) :
simple_strtoll_patch(str_store, &next, base);
} else {
val.u = qualifier != 'L' ?
simple_strtoul_patch(str_store, &next, base) :
simple_strtoull_patch(str_store, &next, base);
}
////troy add
for(i = 0; i<20 ; i++)
str_store[i] = 0;
//判断转换的字符串的宽度是否大于 %2d
if(field_width > 0 && next - str > field_width) {
if(base == 0)
_parse_integer_fixup_radix(str, &base);
while(next - str > field_width) {
if(is_sign) {
val.s = div_s64(val.s, base);
} else {
val.u = div_u64(val.u, base);
}
--next;
}
}
switch(qualifier) {
case 'H': /* that's 'hh' in format */
if(is_sign)
*va_arg(args, signed char *) = val.s;
else
*va_arg(args, unsigned char *) = val.u;
break;
case 'h':
if(is_sign)
*va_arg(args, short *) = val.s;
else
*va_arg(args, unsigned short *) = val.u;
break;
case 'l':
if(is_sign)
*va_arg(args, long *) = val.s;
else
*va_arg(args, unsigned long *) = val.u;
break;
case 'L':
if(is_sign)
*va_arg(args, long long *) = val.s;
else
*va_arg(args, unsigned long long *) = val.u;
break;
case 'Z':
case 'z':
*va_arg(args, size_t *) = val.u;
break;
default:
if(is_sign)
*va_arg(args, int *) = val.s;
else
*va_arg(args, unsigned int *) = val.u;
break;
}
num++;
if(!next) {
break;
}
str = next;
}
return num;
}
int DiagSscanfPatch(const char *buf, const char *fmt, ...)
{
va_list args;
int i;
va_start(args, fmt);
i = _vsscanf_patch(buf, fmt, args);
va_end(args);
return i;
}
/*********************************************************/
char* DiagStrtokPatch(char *str, const char* delim) {
static char* _buffer;
if(str != NULL) _buffer = str;
if(_buffer[0] == '\0') return NULL;
char *ret = _buffer, *b;
const char *d;
for(b = _buffer; *b !='\0'; b++) {
for(d = delim; *d != '\0'; d++) {
if(*b == *d) {
*b = '\0';
_buffer = b+1;
// skip the beginning delimiters
if(b == ret) {
ret++;
continue;
}
return ret;
}
}
}
return ret;
}
/*********************************************************/
char *DiagStrstrPatch(char *string, char *substring)
{
register char *a, *b;
/* First scan quickly through the two strings looking for a
* single-character match. When it's found, then compare the
* rest of the substring.
*/
b = substring;
if(*b == 0) {
return string;
}
for(; *string != 0; string += 1) {
if(*string != *b) {
continue;
}
a = string;
while(1) {
if(*b == 0) {
return string;
}
if(*a++ != *b++) {
break;
}
}
b = substring;
}
return (char *) 0;
}
/*********************************************************/
int DiagSnPrintfPatch(char *buf, size_t size, const char *fmt, ...)
{
va_list ap;
char *p, *s, *buf_end = NULL;
const int *dp = ((const int *)&fmt)+1;
if(buf == NULL)
return 0;
va_start(ap, fmt);
s = buf;
buf_end = size? (buf + size):(char*)~0;
for(; *fmt != '\0'; ++fmt) {
if(*fmt != '%') {
*s++ = *fmt;
if(s >= buf_end) {
goto Exit;
}
continue;
}
if(*++fmt == 's') {
for(p = (char *)*dp++; *p != '\0'; p++) {
*s++ = *p;
if(s >= buf_end) {
goto Exit;
}
}
}
else { /* Length of item is bounded */
char tmp[20], *q = tmp;
int alt = 0;
int shift = 0;// = 12;
const long *lpforchk = (const long *)dp;
if((*lpforchk) < 0x10) {
shift = 0;
}
else if(((*lpforchk) >= 0x10) && ((*lpforchk) < 0x100)) {
shift = 4;
}
else if(((*lpforchk) >= 0x100) && ((*lpforchk) < 0x1000)) {
shift = 8;
}
else if(((*lpforchk) >= 0x1000) && ((*lpforchk) < 0x10000)) {
shift = 12;
}
else if(((*lpforchk) >= 0x10000) && ((*lpforchk) < 0x100000)) {
shift = 16;
}
else if(((*lpforchk) >= 0x100000) && ((*lpforchk) < 0x1000000)) {
shift = 20;
}
else if(((*lpforchk) >= 0x1000000) && ((*lpforchk) < 0x10000000)) {
shift = 24;
}
else if((*lpforchk) >= 0x10000000) {
shift = 28;
}
else {
shift = 28;
}
if((*fmt >= '0') && (*fmt <= '9'))
{
int width;
unsigned char fch = *fmt;
for(width=0; (fch>='0') && (fch<='9'); fch=*++fmt)
{ width = width * 10 + fch - '0';
}
shift=(width-1)*4;
}
/*
* Before each format q points to tmp buffer
* After each format q points past end of item
*/
if((*fmt == 'x')||(*fmt == 'X') || (*fmt == 'p') || (*fmt == 'P')) {
/* With x86 gcc, sizeof(long) == sizeof(int) */
const long *lp = (const long *)dp;
long h = *lp++;
int hex_count = 0;
unsigned long h_back = h;
int ncase = (*fmt & 0x20);
dp = (const int *)lp;
if((*fmt == 'p') || (*fmt == 'P'))
alt=1;
if(alt) {
*q++ = '0';
*q++ = 'X' | ncase;
}
while(h_back) {
hex_count += (h_back & 0xF) ? 1 : 0;
h_back = h_back >> 4;
}
if(shift < (hex_count - 1)*4)
shift = (hex_count - 1)*4;
for(; shift >= 0; shift -= 4)
*q++ = "0123456789ABCDEF"[(h >> shift) & 0xF] | ncase;
}
else if(*fmt == 'd') {
int i = *dp++;
char *r;
int digit_space = 0;
if(i < 0) {
*q++ = '-';
i = -i;
digit_space++;
}
p = q; /* save beginning of digits */
do {
*q++ = '0' + (i % 10);
i /= 10;
digit_space++;
} while(i);
for(; shift >= 0; shift -= 4) {
if(digit_space-- > 0) {
; //do nothing
} else {
*q++ = '0';
}
}
/* reverse digits, stop in middle */
r = q; /* don't alter q */
while(--r > p) {
i = *r;
*r = *p;
*p++ = i;
}
}
else if(*fmt == 'c')
*q++ = *dp++;
else
*q++ = *fmt;
/* now output the saved string */
for(p = tmp; p < q; ++p) {
*s++ = *p;
if(s >= buf_end) {
goto Exit;
}
}
}
}
Exit:
if(buf)
*s = '\0';
va_end(ap);
return(s-buf);
}
/*********************************************************/
static int VSprintfPatch(char *buf, const char *fmt, const int *dp)
{
char *p, *s;
s = buf;
for(; *fmt != '\0'; ++fmt) {
if(*fmt != '%') {
if(buf) {
*s++ = *fmt;
} else {
DiagPutChar(*fmt);
}
continue;
}
if(*++fmt == 's') {
for(p = (char *)*dp++; *p != '\0'; p++) {
if(buf) {
*s++ = *p;
} else {
DiagPutChar(*p);
}
}
}
else { /* Length of item is bounded */
char tmp[20], *q = tmp;
int alt = 0;
int shift = 0;// = 12;
const long *lpforchk = (const long *)dp;
if((*lpforchk) < 0x10) {
shift = 0;
}
else if(((*lpforchk) >= 0x10) && ((*lpforchk) < 0x100)) {
shift = 4;
}
else if(((*lpforchk) >= 0x100) && ((*lpforchk) < 0x1000)) {
shift = 8;
}
else if(((*lpforchk) >= 0x1000) && ((*lpforchk) < 0x10000)) {
shift = 12;
}
else if(((*lpforchk) >= 0x10000) && ((*lpforchk) < 0x100000)) {
shift = 16;
}
else if(((*lpforchk) >= 0x100000) && ((*lpforchk) < 0x1000000)) {
shift = 20;
}
else if(((*lpforchk) >= 0x1000000) && ((*lpforchk) < 0x10000000)) {
shift = 24;
}
else if((*lpforchk) >= 0x10000000) {
shift = 28;
}
else {
shift = 28;
}
#if 1 //wei patch for %02x
if((*fmt >= '0') && (*fmt <= '9'))
{
int width;
unsigned char fch = *fmt;
for(width=0; (fch>='0') && (fch<='9'); fch=*++fmt)
{ width = width * 10 + fch - '0';
}
shift=(width-1)*4;
}
#endif
/*
* Before each format q points to tmp buffer
* After each format q points past end of item
*/
if((*fmt == 'x')||(*fmt == 'X') || (*fmt == 'p') || (*fmt == 'P')) {
/* With x86 gcc, sizeof(long) == sizeof(int) */
const long *lp = (const long *)dp;
long h = *lp++;
int hex_count = 0;
unsigned long h_back = h;
int ncase = (*fmt & 0x20);
dp = (const int *)lp;
if((*fmt == 'p') || (*fmt == 'P'))
alt=1;
if(alt) {
*q++ = '0';
*q++ = 'X' | ncase;
}
//hback 是实际得到的数据hex_count是统计数据的HEX字符个数
while(h_back) {
hex_count += (h_back & 0xF) ? 1 : 0;
h_back = h_back >> 4;
}
//这里修复 example 字符有4个但是用了%02x导致字符被截断的情况
if(shift < (hex_count - 1)*4)
shift = (hex_count - 1)*4;
//printf("(%d,%d)", hex_count, shift);
for(; shift >= 0; shift -= 4) {
*q++ = "0123456789ABCDEF"[(h >> shift) & 0xF] | ncase;
}
}
else if(*fmt == 'd') {
int i = *dp++;
char *r;
int digit_space = 0;
if(i < 0) {
*q++ = '-';
i = -i;
digit_space++;
}
p = q; /* save beginning of digits */
do {
*q++ = '0' + (i % 10);
i /= 10;
digit_space++;
} while(i);
//这里修复 example用了%08d后在数字前面没有0的情况
for(; shift >= 0; shift -= 4) {
if(digit_space-- > 0) {
; //do nothing
} else {
*q++ = '0';
}
}
/* reverse digits, stop in middle */
r = q; /* don't alter q */
while(--r > p) {
i = *r;
*r = *p;
*p++ = i;
}
}
else if(*fmt == 'c')
*q++ = *dp++;
else
*q++ = *fmt;
/* now output the saved string */
for(p = tmp; p < q; ++p) {
if(buf) {
*s++ = *p;
} else {
DiagPutChar(*p);
}
if((*p) == '\n') {
DiagPutChar('\r');
}
}
}
}
if(buf)
*s = '\0';
return (s - buf);
}
u32 DiagPrintfPatch(
IN const char *fmt, ...
)
{
(void)VSprintfPatch(0, fmt, ((const int *)&fmt)+1);
return 1;
}
u32 DiagSPrintfPatch(
IN u8 *buf,
IN const char *fmt, ...
)
{
(void)VSprintfPatch((char*)buf, fmt, ((const int *)&fmt)+1);
return 1;
}
#endif

View file

@ -0,0 +1,149 @@
#include <PinNames.h>
#include <pinmap.h>
#include <gpio_api.h>
#include <wifi_wowlan.h>
#include <freertos_pmu.h>
#include <wifi_conf.h>
#define CONFIG_WOWLAN_DEV_NT96658 //build for Nova NT96658
//#define CONFIG_WOWLAN_DEV_OV788 //build for OmniVision OV788
#if defined(CONFIG_WOWLAN_DEV_NT96658) && defined(CONFIG_WOWLAN_DEV_OV788)
#error "CONFIG_WOWLAN_DEV_NT96658 and CONFIG_WOWLAN_DEV_OV788 are mutually exclusive. "
#endif
#ifdef CONFIG_WOWLAN_DEV_NT96658
#define WOW_WIFI_IN_PIN PE_4 //JTAG pin, so JTAG must be disable before using this pin as wakeup pin
#define WOW_TRIGGER_INTERVAL 500
#elif defined(CONFIG_WOWLAN_DEV_OV788)
#define WOW_WIFI_IN_PIN PD_5
#define WOW_WLAN_ON_PIN PB_3
#define WOW_TRIGGER_INTERVAL 200
#else
#error "Either CONFIG_WOWLAN_DEV_NT96658 or CONFIG_WOWLAN_DEV_OV788 should be defined, but not both. "
#endif
//pin assignment for SDIO, default pull high
#define SD_D2 PA_0
#define SD_D3 PA_1
#define SD_CMD PA_2
#define SD_CLK PA_3
#define SD_D0 PA_4
#define SD_D1 PA_5
#define SD_CD PA_6
gpio_t wow_gpio_wifi_in; //WOWLAN WAKEUP TRIGGER PORT
gpio_t wow_gpio_wlan_on; //RECORD WOWLAN STATUS: 1:OFF, 0:ON
int dev_wowlan_init(void){
WOWLAN_PRINTK("WOWLAN: device init!");
#ifdef CONFIG_WOWLAN_DEV_OV788
// Initial WLAN_ON pin
gpio_init(&wow_gpio_wlan_on, WOW_WLAN_ON_PIN);
gpio_dir(&wow_gpio_wlan_on, PIN_OUTPUT);
gpio_mode(&wow_gpio_wlan_on, PullNone);
gpio_write(&wow_gpio_wlan_on, 1);
#endif
return 0;
}
int dev_wowlan_enable(void){
WOWLAN_PRINTK("WOWLAN: device enable!");
// Init WIFI_IN pin (wakeup pin)
gpio_init(&wow_gpio_wifi_in, WOW_WIFI_IN_PIN);
gpio_dir(&wow_gpio_wifi_in, PIN_OUTPUT);
gpio_mode(&wow_gpio_wifi_in, PullNone);
gpio_write(&wow_gpio_wifi_in, 0);
#ifdef CONFIG_WOWLAN_DEV_OV788
gpio_write(&wow_gpio_wlan_on, 0);
#endif
#if CONFIG_WLAN
wifi_set_power_mode(0xff, 1);
#endif
return 0;
}
int dev_wowlan_wakeup_process(void){
WOWLAN_PRINTK("WOWLAN: device wake up!");
#if defined(CONFIG_WOWLAN_DEV_NT96658) || defined(CONFIG_WOWLAN_DEV_OV788)
#if defined(configUSE_WAKELOCK_PMU) && (configUSE_WAKELOCK_PMU == 1)
//acquire wakelock to keep system awake
pmu_acquire_wakelock(PMU_SDIO_DEVICE);
#endif
#endif
#ifdef CONFIG_WOWLAN_DEV_OV788
//record wowlan status
gpio_write(&wow_gpio_wlan_on, 1);
#endif
#if defined(CONFIG_WOWLAN_DEV_NT96658)
//restore SDIO pin status for bus communication
pin_mode(SD_D0, PullUp);
pin_mode(SD_D1, PullUp);
pin_mode(SD_D2, PullUp);
pin_mode(SD_D3, PullUp);
pin_mode(SD_CMD, PullUp);
pin_mode(SD_CLK, PullDown);
#endif
//send signal to awake host
gpio_write(&wow_gpio_wifi_in, 0);
wowlan_mdelay_os(WOW_TRIGGER_INTERVAL);
gpio_write(&wow_gpio_wifi_in, 1);
wowlan_mdelay_os(WOW_TRIGGER_INTERVAL);
gpio_write(&wow_gpio_wifi_in, 0);
wowlan_mdelay_os(WOW_TRIGGER_INTERVAL);
return 0;
}
int dev_wowlan_sleep_process(void){
#if defined(CONFIG_WOWLAN_DEV_NT96658)
//pull control for SDIO pin only when host is already power off
if(rtw_wowlan_is_enabled() && (rtw_wowlan_get_wk_reason() == 0)){
WOWLAN_PRINTK("pull control");
//configure SDIO pin status for avoiding current leakage
pin_mode(SD_D0, PullNone);
pin_mode(SD_D1, PullNone);
pin_mode(SD_D2, PullNone);
pin_mode(SD_D3, PullNone);
pin_mode(SD_CMD, PullNone);
pin_mode(SD_CLK, PullNone);
}
#endif
return 0;
}
int dev_wowlan_disable(void){
WOWLAN_PRINTK("WOWLAN: device disable!");
#if CONFIG_WLAN
wifi_set_power_mode(0xff, 0);
#endif
#ifdef CONFIG_WOWLAN_DEV_OV788
gpio_write(&wow_gpio_wlan_on, 1);
#endif
return 0;
}
void dev_wowlan_ops_init(void *dev_ops){
struct rtw_wowlan_ops *ops = (struct rtw_wowlan_ops *)dev_ops;
WOWLAN_PRINTK("WOWLAN: device ops init!");
ops->DevWowlanInit = dev_wowlan_init;
ops->DevWowlanEnable = dev_wowlan_enable;
ops->DevWowlanDisable = dev_wowlan_disable;
ops->DevWowlanWakeUp = dev_wowlan_wakeup_process;
ops->DevWowlanSleep = dev_wowlan_sleep_process;
}

View file

@ -0,0 +1,385 @@
#ifndef _WIFI_WOWLAN_H_
#define _WIFI_WOWLAN_H_
#include <platform_stdlib.h>
#include <osdep_service.h>
#define WOWLAN_DBG 1
enum{
WOWLAN_DBG_OFF = 0,
WOWLAN_DBG_ALWAYS,
WOWLAN_DBG_ERROR,
WOWLAN_DBG_WARNING,
WOWLAN_DBG_INFO
};
#if WOWLAN_DBG
//#define WOWLAN_DUMP_MSG
#define WOWLAN_DUMP_MSG_1 //dump packet when setting
static unsigned char gWowlanDbgLevel = WOWLAN_DBG_ERROR;
#define WOWLAN_PRINTK(fmt, args...) printf(fmt"\r\n",## args)
#define _WOWLAN_PRINTK(fmt, args...) printf(fmt,## args)
#define WOWLAN_DBG_MSG(level, fmt, args...) \
do{ \
if(level <= gWowlanDbgLevel){ \
WOWLAN_PRINTK(fmt,## args); \
} \
}while(0)
#else
#define WOWLAN_PRINTK(fmt, args...)
#define WOWLAN_DBG_MSG(level, fmt, args...)
#endif
#ifndef u8
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;
#endif
#ifndef BIT
#define BIT(x) ((u32)1 << (x))
#endif
#ifndef le16_to_cpu //need a general definition for the whole system
#define cpu_to_le32(x) ((u32)(x))
#define le32_to_cpu(x) ((u32)(x))
#define cpu_to_le16(x) ((u16)(x))
#define le16_to_cpu(x) ((u16)(x))
#endif
#ifndef IP_FMT
#define IP_FMT "%d.%d.%d.%d"
#endif
#ifndef IP_ARG
#define IP_ARG(x) ((u8*)(x))[0],((u8*)(x))[1],((u8*)(x))[2],((u8*)(x))[3]
#endif
#ifndef MAC_FMT
#define MAC_FMT "%02x:%02x:%02x:%02x:%02x:%02x"
#endif
#ifndef MAC_ARG
#define MAC_ARG(x) ((u8*)(x))[0],((u8*)(x))[1],((u8*)(x))[2],((u8*)(x))[3],((u8*)(x))[4],((u8*)(x))[5]
#endif
#ifndef ETH_ALEN
#define ETH_ALEN 6
#endif
#ifndef ethhdr
struct ethhdr
{
unsigned char h_dest[ETH_ALEN]; /* destination eth addr */
unsigned char h_source[ETH_ALEN]; /* source ether addr */
unsigned short h_proto; /* packet type ID field */
};
#endif
#ifndef wowlan_memcpy
#define wowlan_memcpy(d, s, n) rtw_memcpy((void*)(d), ((void*)(s)), (n))
#endif
#ifndef wowlan_malloc
#define wowlan_malloc(sz) rtw_malloc(sz)
#endif
#ifndef wowlan_zmalloc
#define wowlan_zmalloc(sz) rtw_zmalloc(sz)
#endif
#ifndef wowlan_memset
#define wowlan_memset(pbuf, c, sz) rtw_memset(pbuf, c, sz)
#endif
#ifndef wowlan_mfree
#define wowlan_mfree(p, sz) rtw_mfree(((u8*)(p)), (sz))
#endif
#ifndef wowlan_memcmp
#define wowlan_memcmp(s1, s2, n) rtw_memcmp(((void*)(s1)), ((void*)(s2)), (n))
#endif
#ifndef wowlan_mdelay_os
#define wowlan_mdelay_os(ms) rtw_mdelay_os(ms)
#endif
/*Mutex services*/
typedef _mutex _wowlock;
__inline static void _init_wowlock(_wowlock *plock)
{
rtw_mutex_init(plock);
}
__inline static void _free_wowlock(_wowlock *plock)
{
rtw_mutex_free(plock);
}
__inline static void _enter_wowlock(_wowlock *plock)
{
rtw_mutex_get(plock);
}
__inline static void _exit_wowlock(_wowlock *plock)
{
rtw_mutex_put(plock);
}
/*Timer services*/
typedef _timerHandle _wowTimer;
#define TMR_AUTO_RELOAD_EN _TRUE
#define TMR_AUTO_RELOAD_DIS _FALSE
__inline static void
_wowlan_init_timer(_wowTimer *ptimer, void *adapter, TIMER_FUN pfunc,void* cntx, const char *name, u32 auto_reload)
{
*ptimer = rtw_timerCreate(
(signed const char *)name, // Just a text name, not used by the RTOS kernel.
TIMER_MAX_DELAY, // Timer Period, not 0
auto_reload, // Whether timer will auto-load themselves when expires
cntx, // Uniq id used to identify which timer expire..
pfunc // Timer callback
);
}
__inline static void
_wowlan_set_timer(_wowTimer *ptimer, u32 delay_time_ms)
{
if(rtw_timerChangePeriod(*ptimer, rtw_ms_to_systime(delay_time_ms), TIMER_MAX_DELAY) == _FAIL)
WOWLAN_PRINTK("Fail to set timer period");
}
__inline static void
_wowlan_cancel_timer(_wowTimer *ptimer)
{
rtw_timerStop(*ptimer, TIMER_MAX_DELAY);
}
__inline static void
_wowlan_del_timer(_wowTimer *ptimer)
{
rtw_timerDelete(*ptimer, TIMER_MAX_DELAY);
}
__inline static void *
_wowlan_get_timer_cntx(_wowTimer timer)
{
#ifdef PLATFORM_FREERTOS
#include <FreeRTOS.h>
#include <timers.h>
return pvTimerGetTimerID(timer);
#else
#error "_wowlan_get_timer_cntx is not defined"
#endif
}
enum rtw_wowlan_wakeup_reason {
RTW_WOWLAN_WAKEUP_BY_PATTERN = BIT(0),
RTW_WOWLAN_WAKEUP_BY_DISCONNECTION = BIT(1),
RTW_WOWLAN_WAKEUP_MAX = 0x7FFFFFFF
};
enum rtw_wowlan_cmd_id{
RTW_WOWLAN_CMD_ENABLE = 0x01, // enable wowlan service
RTW_WOWLAN_CMD_PATTERNS = 0x02, // wowlan pattern setting
RTW_WOWLAN_CMD_PROT_OFFLOAD_CONFIG = 0x03, //ARP offload setting
RTW_WOWLAN_CMD_GET_STATUS = 0x04, // get rtw_wowlan_status
RTW_WOWLAN_CMD_CLEAR_ALL = 0x05, //clear wowlan content
RTW_WOWLAN_CMD_KEEPALIVE = 0x06, //for keep alive packet setting
RTW_WOWLAN_CMD_MAX = 0xff
};
#define RTW_WOWLAN_MAX_RX_FILTERS (5)
#define RTW_WOWLAN_RX_FILTER_MAX_FIELDS (8)
#define RTW_WOWLAN_ID_OFFSET (100) //to match some application, ID starts from 100
#define RTW_WOWLAN_MIN_FILTERS_ID (RTW_WOWLAN_ID_OFFSET)
#define RTW_WOWLAN_MAX_FILTERS_ID (RTW_WOWLAN_ID_OFFSET+RTW_WOWLAN_MAX_RX_FILTERS-1)
struct rtw_wowlan_rx_filter_field {
u16 offset;
u8 len;
u8 flags;
u8 *mask;
u8 *pattern;
};
struct rtw_wowlan_rx_filter {
u8 action;
u8 offset;
u8 num_fields;
struct rtw_wowlan_rx_filter_field fields[RTW_WOWLAN_RX_FILTER_MAX_FIELDS];
};
#if defined(__IAR_SYSTEMS_ICC__)|| defined (__GNUC__)
#pragma pack(1)
#else
#error "this structure needs to be packed!"
#endif
struct rtw_wowlan_status {
u32 wakeup_reasons; //record wake up reason
u32 filter_id; //record which pattern is matched
};
#if defined(__IAR_SYSTEMS_ICC__)|| defined (__GNUC__)
#pragma pack()
#else
#error "this structure needs to be packed!"
#endif
/**
* struct rtw_wowlan_keepalive_packet
*
* @payload_len: data payload length
* @payload: data payload buffer
* @data_interval: interval at which to send data packets
**/
#define RTW_WOWLAN_MAX_KPALIVE_PKT 3
#define RTW_WOWLAN_MAX_KPALIVE_PKT_SZ 512
struct rtw_wowlan_keepalive_packet{
u8 packet_id;
int payload_len;
u8 *payload;
u32 data_interval;
_wowTimer keepalive_tmr;
};
struct rtw_wowlan_ops {
int (*DevWowlanInit)(void);
int (*DevWowlanEnable)(void);
int (*DevWowlanDisable)(void);
int (*DevWowlanWakeUp)(void);
int (*DevWowlanSleep)(void);
};
/**
* enum rtw_wowlan_proto_offloads - enabled protocol offloads
* @RTW_WOWLAN_PROTO_OFFLOAD_ARP: ARP data is enabled
*/
enum rtw_wowlan_proto_offloads {
RTW_WOWLAN_PROTO_OFFLOAD_ARP = BIT(0),
RTW_WOWLAN_PROTO_OFFLOAD_MAX = 0x7FFFFFFF
};
/**
* struct rtw_wowlan_proto_offload_common - ARP/NS offload common part
* @enabled: enable flags
* @remote_ipv4_addr: remote address to answer to (or zero if all)
* @host_ipv4_addr: our IPv4 address to respond to queries for
* @arp_mac_addr: our MAC address for ARP responses
* @reserved: unused
*/
struct rtw_wowlan_proto_offload_common{
int proto_enabled;
u32 remote_ipv4_addr;
u32 host_ipv4_addr;
u8 host_mac_addr[ETH_ALEN];
u16 reserved;
};
struct rtw_wowlan {
_wowlock wow_mutex;
bool enabled;
struct rtw_wowlan_status status;
struct rtw_wowlan_ops ops;
struct rtw_wowlan_proto_offload_common proto;
bool proto_offload_enabled;
struct rtw_wowlan_rx_filter *rx_filter[RTW_WOWLAN_MAX_RX_FILTERS];
bool rx_filter_enabled[RTW_WOWLAN_MAX_RX_FILTERS];/* RX Data filter rule state - enabled/disabled */
struct rtw_wowlan_keepalive_packet *tx_keepalive[RTW_WOWLAN_MAX_KPALIVE_PKT];
bool tx_keepalive_enabled[RTW_WOWLAN_MAX_KPALIVE_PKT];/* TX keep avlive rule state - enabled/disabled */
};
#define eqMacAddr(a,b) ( ((a)[0]==(b)[0] && (a)[1]==(b)[1] && (a)[2]==(b)[2] && (a)[3]==(b)[3] && (a)[4]==(b)[4] && (a)[5]==(b)[5]) ? 1:0 )
#define cpMacAddr(des,src) ((des)[0]=(src)[0],(des)[1]=(src)[1],(des)[2]=(src)[2],(des)[3]=(src)[3],(des)[4]=(src)[4],(des)[5]=(src)[5])
#define cpIpAddr(des,src) ((des)[0]=(src)[0],(des)[1]=(src)[1],(des)[2]=(src)[2],(des)[3]=(src)[3])
#define RTW_WOWLAN_GET_ARP_PKT_OPERATION(__pHeader) ReadEF2Byte( ((u8*)(__pHeader)) + 6)
#define RTW_WOWLAN_GET_ARP_PKT_SENDER_MAC_ADDR(__pHeader, _val) cpMacAddr((u8*)(_val), ((u8*)(__pHeader))+8)
#define RTW_WOWLAN_GET_ARP_PKT_SENDER_IP_ADDR(__pHeader, _val) cpIpAddr((u8*)(_val), ((u8*)(__pHeader))+14)
#define RTW_WOWLAN_GET_ARP_PKT_TARGET_MAC_ADDR(__pHeader, _val) cpMacAddr((u8*)(_val), ((u8*)(__pHeader))+18)
#define RTW_WOWLAN_GET_ARP_PKT_TARGET_IP_ADDR(__pHeader, _val) cpIpAddr((u8*)(_val), ((u8*)(__pHeader))+24)
#define RTW_WOWLAN_SET_ARP_PKT_HW(__pHeader, __Value) WriteEF2Byte( ((u8*)(__pHeader)) + 0, __Value)
#define RTW_WOWLAN_SET_ARP_PKT_PROTOCOL(__pHeader, __Value) WriteEF2Byte( ((u8*)(__pHeader)) + 2, __Value)
#define RTW_WOWLAN_SET_ARP_PKT_HW_ADDR_LEN(__pHeader, __Value) WriteEF1Byte( ((u8*)(__pHeader)) + 4, __Value)
#define RTW_WOWLAN_SET_ARP_PKT_PROTOCOL_ADDR_LEN(__pHeader, __Value) WriteEF1Byte( ((u8*)(__pHeader)) + 5, __Value)
#define RTW_WOWLAN_SET_ARP_PKT_OPERATION(__pHeader, __Value) WriteEF2Byte( ((u8*)(__pHeader)) + 6, __Value)
#define RTW_WOWLAN_SET_ARP_PKT_SENDER_MAC_ADDR(__pHeader, _val) cpMacAddr(((u8*)(__pHeader))+8, (u8*)(_val))
#define RTW_WOWLAN_SET_ARP_PKT_SENDER_IP_ADDR(__pHeader, _val) cpIpAddr(((u8*)(__pHeader))+14, (u8*)(_val))
#define RTW_WOWLAN_SET_ARP_PKT_TARGET_MAC_ADDR(__pHeader, _val) cpMacAddr(((u8*)(__pHeader))+18, (u8*)(_val))
#define RTW_WOWLAN_SET_ARP_PKT_TARGET_IP_ADDR(__pHeader, _val) cpIpAddr(((u8*)(__pHeader))+24, (u8*)(_val))
#define RTW_WOWLAN_ARP_PKT_LEN 0x2A
#define RTW_WOWLAN_ARP_PKT_OPERATION_REQ 0x0100 //arp request
#define RTW_WOWLAN_ARP_PKT_OPERATION_RSP 0x0200 //arp response
extern u8 key_2char2num(u8 hch, u8 lch);
extern _LONG_CALL_ void __rtl_memDump_v1_00(const u8 *start, u32 size, char * strHeader);
#define rtw_wowlan_DumpForBytes(pData, Len) __rtl_memDump_v1_00(pData, Len, NULL)
#define PWOWLAN_TO_STATUS(pwowlan) (&pwowlan->status)
#define PWOWLAN_TO_OPS(pwowlan) (&pwowlan->ops)
#define PWOWLAN_TO_PROTO(pwowlan) (&pwowlan->proto)
#define PWOWLAN_TO_RX_FILTER(pwowlan) (pwowlan->rx_filter)
#define PWOWLAN_TO_TX_KEEPALIVE(pwowlan) (pwowlan->tx_keepalive)
/**
* rtw_wowlan_init: initialize wowlan service
* arg: None
* return: _SUCCESS or _FAIL
*/
extern int rtw_wowlan_init(void);
/**
* cmd_wowlan_service: input commands to configure wowlan service
* arg:
* @argc: number of input parameter
* @argv: content of input string
* return: None
*/
extern void cmd_wowlan_service(int argc, char **argv);
/**
* rtw_wowlan_process_rx_packet: entry for packet process in wowlan service once it starts
* arg:
* @rx_pkt: receive packet from wlan/ethernet
* @pkt_len: receive packet length
* return: _SUCCESS or _FAIL
*/
extern int rtw_wowlan_process_rx_packet(char *rx_pkt, u16 pkt_len);
/**
* rtw_wowlan_wakeup_process: wake up process once the reasons are matched,
* refer to enum rtw_wowlan_wakeup_reason
* arg:
* @reason: wake up reason, refer to enum rtw_wowlan_wakeup_reason
* return: None
*/
extern void rtw_wowlan_wakeup_process(int reason);
/**
* rtw_wowlan_is_enabled: if wowlan service is already enabled
* this function is called in rx path and wifi_inidication when wowlan service is running
* arg: None
* return: _True if enable or _False if disable
*/
extern int rtw_wowlan_is_enabled(void);
/**
* rtw_wowlan_get_wk_reason: query wake up reason, refer to enum rtw_wowlan_wakeup_reason
* arg: None
* return: wakeup_reason
*/
extern int rtw_wowlan_get_wk_reason(void);
/**
* rtw_wowlan_dev_sleep: sleep process on Ameba side, pull control for example
* this function is linked to dev_wowlan_sleep_process() in dev_wowlan.c
* arg: None
* return: None
*/
extern void rtw_wowlan_dev_sleep(void);
#endif

View file

@ -0,0 +1,593 @@
/*
* SSL/TLS interface definition
* Copyright (c) 2004-2013, Jouni Malinen <j@w1.fi>
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
*/
#ifndef TLS_H
#define TLS_H
#include <polarssl/config.h>
#include <polarssl/memory.h>
#include <polarssl/ssl.h>
struct tls_connection;
struct tls_random {
const u8 *client_random;
size_t client_random_len;
const u8 *server_random;
size_t server_random_len;
};
enum tls_event {
TLS_CERT_CHAIN_SUCCESS,
TLS_CERT_CHAIN_FAILURE,
TLS_PEER_CERTIFICATE,
TLS_ALERT
};
/*
* Note: These are used as identifier with external programs and as such, the
* values must not be changed.
*/
enum tls_fail_reason {
TLS_FAIL_UNSPECIFIED = 0,
TLS_FAIL_UNTRUSTED = 1,
TLS_FAIL_REVOKED = 2,
TLS_FAIL_NOT_YET_VALID = 3,
TLS_FAIL_EXPIRED = 4,
TLS_FAIL_SUBJECT_MISMATCH = 5,
TLS_FAIL_ALTSUBJECT_MISMATCH = 6,
TLS_FAIL_BAD_CERTIFICATE = 7,
TLS_FAIL_SERVER_CHAIN_PROBE = 8,
TLS_FAIL_DOMAIN_SUFFIX_MISMATCH = 9,
TLS_FAIL_DOMAIN_MISMATCH = 10,
};
#define TLS_MAX_ALT_SUBJECT 10
union tls_event_data {
struct {
int depth;
const char *subject;
enum tls_fail_reason reason;
const char *reason_txt;
const struct wpabuf *cert;
} cert_fail;
struct {
int depth;
const char *subject;
const struct wpabuf *cert;
const u8 *hash;
size_t hash_len;
const char *altsubject[TLS_MAX_ALT_SUBJECT];
int num_altsubject;
} peer_cert;
struct {
int is_local;
const char *type;
const char *description;
} alert;
};
struct tls_config {
const char *opensc_engine_path;
const char *pkcs11_engine_path;
const char *pkcs11_module_path;
int fips_mode;
int cert_in_cb;
const char *openssl_ciphers;
unsigned int tls_session_lifetime;
void (*event_cb)(void *ctx, enum tls_event ev,
union tls_event_data *data);
void *cb_ctx;
};
#define TLS_CONN_ALLOW_SIGN_RSA_MD5 BIT(0)
#define TLS_CONN_DISABLE_TIME_CHECKS BIT(1)
#define TLS_CONN_DISABLE_SESSION_TICKET BIT(2)
#define TLS_CONN_REQUEST_OCSP BIT(3)
#define TLS_CONN_REQUIRE_OCSP BIT(4)
#define TLS_CONN_DISABLE_TLSv1_1 BIT(5)
#define TLS_CONN_DISABLE_TLSv1_2 BIT(6)
#define TLS_CONN_EAP_FAST BIT(7)
#define TLS_CONN_DISABLE_TLSv1_0 BIT(8)
/**
* struct tls_connection_params - Parameters for TLS connection
* @ca_cert: File or reference name for CA X.509 certificate in PEM or DER
* format
* @ca_cert_blob: ca_cert as inlined data or %NULL if not used
* @ca_cert_blob_len: ca_cert_blob length
* @ca_path: Path to CA certificates (OpenSSL specific)
* @subject_match: String to match in the subject of the peer certificate or
* %NULL to allow all subjects
* @altsubject_match: String to match in the alternative subject of the peer
* certificate or %NULL to allow all alternative subjects
* @suffix_match: String to suffix match in the dNSName or CN of the peer
* certificate or %NULL to allow all domain names. This may allow subdomains an
* wildcard certificates. Each domain name label must have a full match.
* @domain_match: String to match in the dNSName or CN of the peer
* certificate or %NULL to allow all domain names. This requires a full,
* case-insensitive match.
* @client_cert: File or reference name for client X.509 certificate in PEM or
* DER format
* @client_cert_blob: client_cert as inlined data or %NULL if not used
* @client_cert_blob_len: client_cert_blob length
* @private_key: File or reference name for client private key in PEM or DER
* format (traditional format (RSA PRIVATE KEY) or PKCS#8 (PRIVATE KEY)
* @private_key_blob: private_key as inlined data or %NULL if not used
* @private_key_blob_len: private_key_blob length
* @private_key_passwd: Passphrase for decrypted private key, %NULL if no
* passphrase is used.
* @dh_file: File name for DH/DSA data in PEM format, or %NULL if not used
* @dh_blob: dh_file as inlined data or %NULL if not used
* @dh_blob_len: dh_blob length
* @engine: 1 = use engine (e.g., a smartcard) for private key operations
* (this is OpenSSL specific for now)
* @engine_id: engine id string (this is OpenSSL specific for now)
* @ppin: pointer to the pin variable in the configuration
* (this is OpenSSL specific for now)
* @key_id: the private key's id when using engine (this is OpenSSL
* specific for now)
* @cert_id: the certificate's id when using engine
* @ca_cert_id: the CA certificate's id when using engine
* @openssl_ciphers: OpenSSL cipher configuration
* @flags: Parameter options (TLS_CONN_*)
* @ocsp_stapling_response: DER encoded file with cached OCSP stapling response
* or %NULL if OCSP is not enabled
*
* TLS connection parameters to be configured with tls_connection_set_params()
* and tls_global_set_params().
*
* Certificates and private key can be configured either as a reference name
* (file path or reference to certificate store) or by providing the same data
* as a pointer to the data in memory. Only one option will be used for each
* field.
*/
struct tls_connection_params {
const char *ca_cert;
const u8 *ca_cert_blob;
size_t ca_cert_blob_len;
const char *ca_path;
const char *subject_match;
const char *altsubject_match;
const char *suffix_match;
const char *domain_match;
const char *client_cert;
const u8 *client_cert_blob;
size_t client_cert_blob_len;
const char *private_key;
const u8 *private_key_blob;
size_t private_key_blob_len;
const char *private_key_passwd;
const char *dh_file;
const u8 *dh_blob;
size_t dh_blob_len;
/* OpenSSL specific variables */
int engine;
const char *engine_id;
const char *pin;
const char *key_id;
const char *cert_id;
const char *ca_cert_id;
const char *openssl_ciphers;
unsigned int flags;
const char *ocsp_stapling_response;
};
/**
* tls_init - Initialize TLS library
* @conf: Configuration data for TLS library
* Returns: Context data to be used as tls_ctx in calls to other functions,
* or %NULL on failure.
*
* Called once during program startup and once for each RSN pre-authentication
* session. In other words, there can be two concurrent TLS contexts. If global
* library initialization is needed (i.e., one that is shared between both
* authentication types), the TLS library wrapper should maintain a reference
* counter and do global initialization only when moving from 0 to 1 reference.
*/
//ssl_context * tls_init(const struct tls_config *conf);
void * tls_init(const struct tls_config *conf);
/**
* tls_deinit - Deinitialize TLS library
* @tls_ctx: TLS context data from tls_init()
*
* Called once during program shutdown and once for each RSN pre-authentication
* session. If global library deinitialization is needed (i.e., one that is
* shared between both authentication types), the TLS library wrapper should
* maintain a reference counter and do global deinitialization only when moving
* from 1 to 0 references.
*/
void tls_deinit(void *tls_ctx);
/**
* tls_get_errors - Process pending errors
* @tls_ctx: TLS context data from tls_init()
* Returns: Number of found error, 0 if no errors detected.
*
* Process all pending TLS errors.
*/
int tls_get_errors(void *tls_ctx);
/**
* tls_connection_init - Initialize a new TLS connection
* @tls_ctx: TLS context data from tls_init()
* Returns: Connection context data, conn for other function calls
*/
struct tls_connection * tls_connection_init(void *tls_ctx);
/**
* tls_connection_deinit - Free TLS connection data
* @tls_ctx: TLS context data from tls_init()
* @conn: Connection context data from tls_connection_init()
*
* Release all resources allocated for TLS connection.
*/
void tls_connection_deinit(void *tls_ctx, struct tls_connection *conn);
/**
* tls_connection_established - Has the TLS connection been completed?
* @tls_ctx: TLS context data from tls_init()
* @conn: Connection context data from tls_connection_init()
* Returns: 1 if TLS connection has been completed, 0 if not.
*/
int tls_connection_established(void *tls_ctx, struct tls_connection *conn);
/**
* tls_connection_shutdown - Shutdown TLS connection
* @tls_ctx: TLS context data from tls_init()
* @conn: Connection context data from tls_connection_init()
* Returns: 0 on success, -1 on failure
*
* Shutdown current TLS connection without releasing all resources. New
* connection can be started by using the same conn without having to call
* tls_connection_init() or setting certificates etc. again. The new
* connection should try to use session resumption.
*/
int tls_connection_shutdown(void *tls_ctx, struct tls_connection *conn);
enum {
TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN = -4,
TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED = -3,
TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED = -2
};
/**
* tls_connection_set_params - Set TLS connection parameters
* @tls_ctx: TLS context data from tls_init()
* @conn: Connection context data from tls_connection_init()
* @params: Connection parameters
* Returns: 0 on success, -1 on failure,
* TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED (-2) on error causing PKCS#11 engine
* failure, or
* TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED (-3) on failure to verify the
* PKCS#11 engine private key, or
* TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN (-4) on PIN error causing PKCS#11 engine
* failure.
*/
int __must_check
tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
const struct tls_connection_params *params);
/**
* tls_global_set_params - Set TLS parameters for all TLS connection
* @tls_ctx: TLS context data from tls_init()
* @params: Global TLS parameters
* Returns: 0 on success, -1 on failure,
* TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED (-2) on error causing PKCS#11 engine
* failure, or
* TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED (-3) on failure to verify the
* PKCS#11 engine private key, or
* TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN (-4) on PIN error causing PKCS#11 engine
* failure.
*/
int __must_check tls_global_set_params(
void *tls_ctx, const struct tls_connection_params *params);
/**
* tls_global_set_verify - Set global certificate verification options
* @tls_ctx: TLS context data from tls_init()
* @check_crl: 0 = do not verify CRLs, 1 = verify CRL for the user certificate,
* 2 = verify CRL for all certificates
* Returns: 0 on success, -1 on failure
*/
int __must_check tls_global_set_verify(void *tls_ctx, int check_crl);
/**
* tls_connection_set_verify - Set certificate verification options
* @tls_ctx: TLS context data from tls_init()
* @conn: Connection context data from tls_connection_init()
* @verify_peer: 1 = verify peer certificate
* @flags: Connection flags (TLS_CONN_*)
* @session_ctx: Session caching context or %NULL to use default
* @session_ctx_len: Length of @session_ctx in bytes.
* Returns: 0 on success, -1 on failure
*/
int __must_check tls_connection_set_verify(void *tls_ctx,
struct tls_connection *conn,
int verify_peer,
unsigned int flags,
const u8 *session_ctx,
size_t session_ctx_len);
/**
* tls_connection_get_random - Get random data from TLS connection
* @tls_ctx: TLS context data from tls_init()
* @conn: Connection context data from tls_connection_init()
* @data: Structure of client/server random data (filled on success)
* Returns: 0 on success, -1 on failure
*/
int __must_check tls_connection_get_random(void *tls_ctx,
struct tls_connection *conn,
struct tls_random *data);
/**
* tls_connection_prf - Use TLS-PRF to derive keying material
* @tls_ctx: TLS context data from tls_init()
* @conn: Connection context data from tls_connection_init()
* @label: Label (e.g., description of the key) for PRF
* @server_random_first: seed is 0 = client_random|server_random,
* 1 = server_random|client_random
* @skip_keyblock: Skip TLS key block from the beginning of PRF output
* @out: Buffer for output data from TLS-PRF
* @out_len: Length of the output buffer
* Returns: 0 on success, -1 on failure
*
* tls_connection_prf() is required so that further keying material can be
* derived from the master secret. Example implementation of this function is in
* tls_prf_sha1_md5() when it is called with seed set to
* client_random|server_random (or server_random|client_random). For TLSv1.2 and
* newer, a different PRF is needed, though.
*/
int __must_check tls_connection_prf(void *tls_ctx,
struct tls_connection *conn,
const char *label,
int server_random_first,
int skip_keyblock,
u8 *out, size_t out_len);
/**
* tls_connection_handshake - Process TLS handshake (client side)
* @tls_ctx: TLS context data from tls_init()
* @conn: Connection context data from tls_connection_init()
* @in_data: Input data from TLS server
* @appl_data: Pointer to application data pointer, or %NULL if dropped
* Returns: Output data, %NULL on failure
*
* The caller is responsible for freeing the returned output data. If the final
* handshake message includes application data, this is decrypted and
* appl_data (if not %NULL) is set to point this data. The caller is
* responsible for freeing appl_data.
*
* This function is used during TLS handshake. The first call is done with
* in_data == %NULL and the library is expected to return ClientHello packet.
* This packet is then send to the server and a response from server is given
* to TLS library by calling this function again with in_data pointing to the
* TLS message from the server.
*
* If the TLS handshake fails, this function may return %NULL. However, if the
* TLS library has a TLS alert to send out, that should be returned as the
* output data. In this case, tls_connection_get_failed() must return failure
* (> 0).
*
* tls_connection_established() should return 1 once the TLS handshake has been
* completed successfully.
*/
struct wpabuf * tls_connection_handshake(void *tls_ctx,
struct tls_connection *conn,
const struct wpabuf *in_data,
struct wpabuf **appl_data);
struct wpabuf * tls_connection_handshake2(void *tls_ctx,
struct tls_connection *conn,
const struct wpabuf *in_data,
struct wpabuf **appl_data,
int *more_data_needed);
/**
* tls_connection_server_handshake - Process TLS handshake (server side)
* @tls_ctx: TLS context data from tls_init()
* @conn: Connection context data from tls_connection_init()
* @in_data: Input data from TLS peer
* @appl_data: Pointer to application data pointer, or %NULL if dropped
* Returns: Output data, %NULL on failure
*
* The caller is responsible for freeing the returned output data.
*/
struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
struct tls_connection *conn,
const struct wpabuf *in_data,
struct wpabuf **appl_data);
/**
* tls_connection_encrypt - Encrypt data into TLS tunnel
* @tls_ctx: TLS context data from tls_init()
* @conn: Connection context data from tls_connection_init()
* @in_data: Plaintext data to be encrypted
* Returns: Encrypted TLS data or %NULL on failure
*
* This function is used after TLS handshake has been completed successfully to
* send data in the encrypted tunnel. The caller is responsible for freeing the
* returned output data.
*/
struct wpabuf * tls_connection_encrypt(void *tls_ctx,
struct tls_connection *conn,
const struct wpabuf *in_data);
/**
* tls_connection_decrypt - Decrypt data from TLS tunnel
* @tls_ctx: TLS context data from tls_init()
* @conn: Connection context data from tls_connection_init()
* @in_data: Encrypted TLS data
* Returns: Decrypted TLS data or %NULL on failure
*
* This function is used after TLS handshake has been completed successfully to
* receive data from the encrypted tunnel. The caller is responsible for
* freeing the returned output data.
*/
struct wpabuf * tls_connection_decrypt(void *tls_ctx,
struct tls_connection *conn,
const struct wpabuf *in_data);
struct wpabuf * tls_connection_decrypt2(void *tls_ctx,
struct tls_connection *conn,
const struct wpabuf *in_data,
int *more_data_needed);
/**
* tls_connection_resumed - Was session resumption used
* @tls_ctx: TLS context data from tls_init()
* @conn: Connection context data from tls_connection_init()
* Returns: 1 if current session used session resumption, 0 if not
*/
int tls_connection_resumed(void *tls_ctx, struct tls_connection *conn);
enum {
TLS_CIPHER_NONE,
TLS_CIPHER_RC4_SHA /* 0x0005 */,
TLS_CIPHER_AES128_SHA /* 0x002f */,
TLS_CIPHER_RSA_DHE_AES128_SHA /* 0x0031 */,
TLS_CIPHER_ANON_DH_AES128_SHA /* 0x0034 */
};
/**
* tls_connection_set_cipher_list - Configure acceptable cipher suites
* @tls_ctx: TLS context data from tls_init()
* @conn: Connection context data from tls_connection_init()
* @ciphers: Zero (TLS_CIPHER_NONE) terminated list of allowed ciphers
* (TLS_CIPHER_*).
* Returns: 0 on success, -1 on failure
*/
int __must_check tls_connection_set_cipher_list(void *tls_ctx,
struct tls_connection *conn,
u8 *ciphers);
/**
* tls_get_version - Get the current TLS version number
* @tls_ctx: TLS context data from tls_init()
* @conn: Connection context data from tls_connection_init()
* @buf: Buffer for returning the TLS version number
* @buflen: buf size
* Returns: 0 on success, -1 on failure
*
* Get the currently used TLS version number.
*/
int __must_check tls_get_version(void *tls_ctx, struct tls_connection *conn,
char *buf, size_t buflen);
/**
* tls_get_cipher - Get current cipher name
* @tls_ctx: TLS context data from tls_init()
* @conn: Connection context data from tls_connection_init()
* @buf: Buffer for the cipher name
* @buflen: buf size
* Returns: 0 on success, -1 on failure
*
* Get the name of the currently used cipher.
*/
int __must_check tls_get_cipher(void *tls_ctx, struct tls_connection *conn,
char *buf, size_t buflen);
/**
* tls_connection_enable_workaround - Enable TLS workaround options
* @tls_ctx: TLS context data from tls_init()
* @conn: Connection context data from tls_connection_init()
* Returns: 0 on success, -1 on failure
*
* This function is used to enable connection-specific workaround options for
* buffer SSL/TLS implementations.
*/
int __must_check tls_connection_enable_workaround(void *tls_ctx,
struct tls_connection *conn);
/**
* tls_connection_client_hello_ext - Set TLS extension for ClientHello
* @tls_ctx: TLS context data from tls_init()
* @conn: Connection context data from tls_connection_init()
* @ext_type: Extension type
* @data: Extension payload (%NULL to remove extension)
* @data_len: Extension payload length
* Returns: 0 on success, -1 on failure
*/
int __must_check tls_connection_client_hello_ext(void *tls_ctx,
struct tls_connection *conn,
int ext_type, const u8 *data,
size_t data_len);
/**
* tls_connection_get_failed - Get connection failure status
* @tls_ctx: TLS context data from tls_init()
* @conn: Connection context data from tls_connection_init()
*
* Returns >0 if connection has failed, 0 if not.
*/
int tls_connection_get_failed(void *tls_ctx, struct tls_connection *conn);
/**
* tls_connection_get_read_alerts - Get connection read alert status
* @tls_ctx: TLS context data from tls_init()
* @conn: Connection context data from tls_connection_init()
* Returns: Number of times a fatal read (remote end reported error) has
* happened during this connection.
*/
int tls_connection_get_read_alerts(void *tls_ctx, struct tls_connection *conn);
/**
* tls_connection_get_write_alerts - Get connection write alert status
* @tls_ctx: TLS context data from tls_init()
* @conn: Connection context data from tls_connection_init()
* Returns: Number of times a fatal write (locally detected error) has happened
* during this connection.
*/
int tls_connection_get_write_alerts(void *tls_ctx,
struct tls_connection *conn);
typedef int (*tls_session_ticket_cb)
(void *ctx, const u8 *ticket, size_t len, const u8 *client_random,
const u8 *server_random, u8 *master_secret);
int __must_check tls_connection_set_session_ticket_cb(
void *tls_ctx, struct tls_connection *conn,
tls_session_ticket_cb cb, void *ctx);
void tls_connection_set_log_cb(struct tls_connection *conn,
void (*log_cb)(void *ctx, const char *msg),
void *ctx);
#define TLS_BREAK_VERIFY_DATA BIT(0)
#define TLS_BREAK_SRV_KEY_X_HASH BIT(1)
#define TLS_BREAK_SRV_KEY_X_SIGNATURE BIT(2)
#define TLS_DHE_PRIME_511B BIT(3)
#define TLS_DHE_PRIME_767B BIT(4)
#define TLS_DHE_PRIME_15 BIT(5)
#define TLS_DHE_PRIME_58B BIT(6)
#define TLS_DHE_NON_PRIME BIT(7)
void tls_connection_set_test_flags(struct tls_connection *conn, u32 flags);
int tls_get_library_version(char *buf, size_t buf_len);
void tls_connection_set_success_data(struct tls_connection *conn,
struct wpabuf *data);
void tls_connection_set_success_data_resumed(struct tls_connection *conn);
const struct wpabuf *
tls_connection_get_success_data(struct tls_connection *conn);
void tls_connection_remove_session(struct tls_connection *conn);
#endif /* TLS_H */

View file

@ -0,0 +1,548 @@
/*
* wpa_supplicant/hostapd / common helper functions, etc.
* Copyright (c) 2002-2007, Jouni Malinen <j@w1.fi>
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
*/
#ifndef COMMON_H
#define COMMON_H
#include "utils/os.h"
#define TO_TEST_WPS 0
#define ETH_ALEN 6
#if defined(__linux__) || defined(__GLIBC__)
#include <endian.h>
#include <byteswap.h>
#endif /* __linux__ */
#if defined(PLATFORM_FREERTOS)
//#include "little_endian.h"
//#include "basic_types.h"
#endif /* PLATFORM_FREERTOS */
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || \
defined(__OpenBSD__)
#include <sys/types.h>
#include <sys/endian.h>
#define __BYTE_ORDER _BYTE_ORDER
#define __LITTLE_ENDIAN _LITTLE_ENDIAN
#define __BIG_ENDIAN _BIG_ENDIAN
#ifdef __OpenBSD__
#define bswap_16 swap16
#define bswap_32 swap32
#define bswap_64 swap64
#else /* __OpenBSD__ */
#define bswap_16 bswap16
#define bswap_32 bswap32
#define bswap_64 bswap64
#endif /* __OpenBSD__ */
#endif /* defined(__FreeBSD__) || defined(__NetBSD__) || * defined(__DragonFly__) || defined(__OpenBSD__) */
#ifdef __APPLE__
#include <sys/types.h>
#include <machine/endian.h>
#define __BYTE_ORDER _BYTE_ORDER
#define __LITTLE_ENDIAN _LITTLE_ENDIAN
#define __BIG_ENDIAN _BIG_ENDIAN
static inline unsigned short bswap_16(unsigned short v)
{
return ((v & 0xff) << 8) | (v >> 8);
}
static inline unsigned int bswap_32(unsigned int v)
{
return ((v & 0xff) << 24) | ((v & 0xff00) << 8) |
((v & 0xff0000) >> 8) | (v >> 24);
}
#endif /* __APPLE__ */
#ifdef CONFIG_TI_COMPILER
#define __BIG_ENDIAN 4321
#define __LITTLE_ENDIAN 1234
#ifdef __big_endian__
#define __BYTE_ORDER __BIG_ENDIAN
#else
#define __BYTE_ORDER __LITTLE_ENDIAN
#endif
#endif /* CONFIG_TI_COMPILER */
#ifdef CONFIG_NATIVE_WINDOWS
#include <winsock.h>
typedef int socklen_t;
#ifndef MSG_DONTWAIT
#define MSG_DONTWAIT 0 /* not supported */
#endif
#endif /* CONFIG_NATIVE_WINDOWS */
#ifdef _MSC_VER
#define inline __inline
#undef vsnprintf
#define vsnprintf _vsnprintf
#undef close
#define close closesocket
#endif /* _MSC_VER */
/* Define platform specific integer types */
#ifdef _MSC_VER
typedef UINT64 u64;
typedef UINT32 u32;
typedef UINT16 u16;
typedef UINT8 u8;
typedef INT64 s64;
typedef INT32 s32;
typedef INT16 s16;
typedef INT8 s8;
#define WPA_TYPES_DEFINED
#endif /* _MSC_VER */
#ifdef __vxworks
typedef unsigned long long u64;
typedef UINT32 u32;
typedef UINT16 u16;
typedef UINT8 u8;
typedef long long s64;
typedef INT32 s32;
typedef INT16 s16;
typedef INT8 s8;
#define WPA_TYPES_DEFINED
#endif /* __vxworks */
#ifdef CONFIG_TI_COMPILER
#ifdef _LLONG_AVAILABLE
typedef unsigned long long u64;
#else
/*
* TODO: 64-bit variable not available. Using long as a workaround to test the
* build, but this will likely not work for all operations.
*/
typedef unsigned long u64;
#endif
typedef unsigned int u32;
typedef unsigned short u16;
typedef unsigned char u8;
#define WPA_TYPES_DEFINED
#endif /* CONFIG_TI_COMPILER */
#ifndef WPA_TYPES_DEFINED
#ifdef CONFIG_USE_INTTYPES_H
#include <inttypes.h>
#else
//#include <stdint.h>
#endif
#if 0
typedef uint64_t u64;
typedef uint32_t u32;
typedef uint16_t u16;
typedef uint8_t u8;
typedef int64_t s64;
typedef int32_t s32;
typedef int16_t s16;
typedef int8_t s8;
#endif
#define WPA_TYPES_DEFINED
#endif /* !WPA_TYPES_DEFINED */
/* Define platform specific byte swapping macros */
#if defined(__CYGWIN__) || defined(CONFIG_NATIVE_WINDOWS)
static inline unsigned short wpa_swap_16(unsigned short v)
{
return ((v & 0xff) << 8) | (v >> 8);
}
static inline unsigned int wpa_swap_32(unsigned int v)
{
return ((v & 0xff) << 24) | ((v & 0xff00) << 8) |
((v & 0xff0000) >> 8) | (v >> 24);
}
#define le_to_host16(n) (n)
#define host_to_le16(n) (n)
#define be_to_host16(n) wpa_swap_16(n)
#define host_to_be16(n) wpa_swap_16(n)
#define le_to_host32(n) (n)
#define be_to_host32(n) wpa_swap_32(n)
#define host_to_be32(n) wpa_swap_32(n)
#define WPA_BYTE_SWAP_DEFINED
#endif /* __CYGWIN__ || CONFIG_NATIVE_WINDOWS */
#ifndef WPA_BYTE_SWAP_DEFINED
#if 0
#ifndef __BYTE_ORDER
#ifndef __LITTLE_ENDIAN
#ifndef __BIG_ENDIAN
#define __LITTLE_ENDIAN 1234
#define __BIG_ENDIAN 4321
#if defined(sparc)
#define __BYTE_ORDER __BIG_ENDIAN
#endif
#endif /* __BIG_ENDIAN */
#endif /* __LITTLE_ENDIAN */
#endif /* __BYTE_ORDER */
#else
#ifndef __LITTLE_ENDIAN
#define __LITTLE_ENDIAN 1234
#endif
#ifndef __BIG_ENDIAN
#define __BIG_ENDIAN 4321
#endif
#ifndef __BYTE_ORDER
#define __BYTE_ORDER __LITTLE_ENDIAN
#endif
#endif
#if __BYTE_ORDER == __LITTLE_ENDIAN
#define le_to_host16(n) ((__force u16) (le16) (n))
#define host_to_le16(n) ((__force le16) (u16) (n))
#define be_to_host16(n) bswap_16((__force u16) (be16) (n))
#define host_to_be16(n) ((__force be16) bswap_16((n)))
#define le_to_host32(n) ((__force u32) (le32) (n))
#define host_to_le32(n) ((__force le32) (u32) (n))
#define be_to_host32(n) bswap_32((__force u32) (be32) (n))
#define host_to_be32(n) ((__force be32) bswap_32((n)))
#define le_to_host64(n) ((__force u64) (le64) (n))
#define host_to_le64(n) ((__force le64) (u64) (n))
#define be_to_host64(n) bswap_64((__force u64) (be64) (n))
#define host_to_be64(n) ((__force be64) bswap_64((n)))
#elif __BYTE_ORDER == __BIG_ENDIAN
#define le_to_host16(n) bswap_16(n)
#define host_to_le16(n) bswap_16(n)
#define be_to_host16(n) (n)
#define host_to_be16(n) (n)
#define le_to_host32(n) bswap_32(n)
#define be_to_host32(n) (n)
#define host_to_be32(n) (n)
#define le_to_host64(n) bswap_64(n)
#define host_to_le64(n) bswap_64(n)
#define be_to_host64(n) (n)
#define host_to_be64(n) (n)
#ifndef WORDS_BIGENDIAN
#define WORDS_BIGENDIAN
#endif
#else
//#error Could not determine CPU byte order
#endif
#define WPA_BYTE_SWAP_DEFINED
#endif /* !WPA_BYTE_SWAP_DEFINED */
/* Macros for handling unaligned memory accesses */
#define WPA_GET_BE16(a) ((u16) (((a)[0] << 8) | (a)[1]))
#define WPA_PUT_BE16(a, val) \
do { \
(a)[0] = ((u16) (val)) >> 8; \
(a)[1] = ((u16) (val)) & 0xff; \
} while (0)
#define WPA_GET_LE16(a) ((u16) (((a)[1] << 8) | (a)[0]))
#define WPA_PUT_LE16(a, val) \
do { \
(a)[1] = ((u16) (val)) >> 8; \
(a)[0] = ((u16) (val)) & 0xff; \
} while (0)
#define WPA_GET_BE24(a) ((((u32) (a)[0]) << 16) | (((u32) (a)[1]) << 8) | \
((u32) (a)[2]))
#define WPA_PUT_BE24(a, val) \
do { \
(a)[0] = (u8) ((((u32) (val)) >> 16) & 0xff); \
(a)[1] = (u8) ((((u32) (val)) >> 8) & 0xff); \
(a)[2] = (u8) (((u32) (val)) & 0xff); \
} while (0)
#define WPA_GET_BE32(a) ((((u32) (a)[0]) << 24) | (((u32) (a)[1]) << 16) | \
(((u32) (a)[2]) << 8) | ((u32) (a)[3]))
#define WPA_PUT_BE32(a, val) \
do { \
(a)[0] = (u8) ((((u32) (val)) >> 24) & 0xff); \
(a)[1] = (u8) ((((u32) (val)) >> 16) & 0xff); \
(a)[2] = (u8) ((((u32) (val)) >> 8) & 0xff); \
(a)[3] = (u8) (((u32) (val)) & 0xff); \
} while (0)
#define WPA_GET_LE32(a) ((((u32) (a)[3]) << 24) | (((u32) (a)[2]) << 16) | \
(((u32) (a)[1]) << 8) | ((u32) (a)[0]))
#define WPA_PUT_LE32(a, val) \
do { \
(a)[3] = (u8) ((((u32) (val)) >> 24) & 0xff); \
(a)[2] = (u8) ((((u32) (val)) >> 16) & 0xff); \
(a)[1] = (u8) ((((u32) (val)) >> 8) & 0xff); \
(a)[0] = (u8) (((u32) (val)) & 0xff); \
} while (0)
#define WPA_GET_BE64(a) ((((u64) (a)[0]) << 56) | (((u64) (a)[1]) << 48) | \
(((u64) (a)[2]) << 40) | (((u64) (a)[3]) << 32) | \
(((u64) (a)[4]) << 24) | (((u64) (a)[5]) << 16) | \
(((u64) (a)[6]) << 8) | ((u64) (a)[7]))
#define WPA_PUT_BE64(a, val) \
do { \
(a)[0] = (u8) (((u64) (val)) >> 56); \
(a)[1] = (u8) (((u64) (val)) >> 48); \
(a)[2] = (u8) (((u64) (val)) >> 40); \
(a)[3] = (u8) (((u64) (val)) >> 32); \
(a)[4] = (u8) (((u64) (val)) >> 24); \
(a)[5] = (u8) (((u64) (val)) >> 16); \
(a)[6] = (u8) (((u64) (val)) >> 8); \
(a)[7] = (u8) (((u64) (val)) & 0xff); \
} while (0)
#define WPA_GET_LE64(a) ((((u64) (a)[7]) << 56) | (((u64) (a)[6]) << 48) | \
(((u64) (a)[5]) << 40) | (((u64) (a)[4]) << 32) | \
(((u64) (a)[3]) << 24) | (((u64) (a)[2]) << 16) | \
(((u64) (a)[1]) << 8) | ((u64) (a)[0]))
#ifndef ETH_ALEN
#define ETH_ALEN 6
#endif
#ifndef IFNAMSIZ
#define IFNAMSIZ 16
#endif
#ifndef ETH_P_ALL
#define ETH_P_ALL 0x0003
#endif
#ifndef ETH_P_80211_ENCAP
#define ETH_P_80211_ENCAP 0x890d /* TDLS comes under this category */
#endif
#ifndef ETH_P_PAE
#define ETH_P_PAE 0x888E /* Port Access Entity (IEEE 802.1X) */
#endif /* ETH_P_PAE */
#ifndef ETH_P_EAPOL
#define ETH_P_EAPOL ETH_P_PAE
#endif /* ETH_P_EAPOL */
#ifndef ETH_P_RSN_PREAUTH
#define ETH_P_RSN_PREAUTH 0x88c7
#endif /* ETH_P_RSN_PREAUTH */
#ifndef ETH_P_RRB
#define ETH_P_RRB 0x890D
#endif /* ETH_P_RRB */
#if 0 //#ifdef __GNUC__
#define PRINTF_FORMAT(a,b) __attribute__ ((format (printf, (a), (b))))
#define STRUCT_PACKED __attribute__ ((packed))
#else
#define PRINTF_FORMAT(a,b)
#define STRUCT_PACKED
#endif
#ifdef CONFIG_ANSI_C_EXTRA
#if !defined(_MSC_VER) || _MSC_VER < 1400
/* snprintf - used in number of places; sprintf() is _not_ a good replacement
* due to possible buffer overflow; see, e.g.,
* http://www.ijs.si/software/snprintf/ for portable implementation of
* snprintf. */
int snprintf(char *str, size_t size, const char *format, ...);
/* vsnprintf - only used for wpa_msg() in wpa_supplicant.c */
int vsnprintf(char *str, size_t size, const char *format, va_list ap);
#endif /* !defined(_MSC_VER) || _MSC_VER < 1400 */
/* getopt - only used in main.c */
int getopt(int argc, char *const argv[], const char *optstring);
extern char *optarg;
extern int optind;
#ifndef CONFIG_NO_SOCKLEN_T_TYPEDEF
#ifndef __socklen_t_defined
typedef int socklen_t;
#endif
#endif
/* inline - define as __inline or just define it to be empty, if needed */
#ifdef CONFIG_NO_INLINE
#define inline
#else
#define inline __inline
#endif
#ifndef __func__
#define __func__ "__func__ not defined"
#endif
#ifndef bswap_16
#define bswap_16(a) ((((u16) (a) << 8) & 0xff00) | (((u16) (a) >> 8) & 0xff))
#endif
#ifndef bswap_32
#define bswap_32(a) ((((u32) (a) << 24) & 0xff000000) | \
(((u32) (a) << 8) & 0xff0000) | \
(((u32) (a) >> 8) & 0xff00) | \
(((u32) (a) >> 24) & 0xff))
#endif
#ifndef MSG_DONTWAIT
#define MSG_DONTWAIT 0
#endif
#ifdef _WIN32_WCE
void perror(const char *s);
#endif /* _WIN32_WCE */
#endif /* CONFIG_ANSI_C_EXTRA */
#ifndef MAC2STR
#define MAC2STR(a) (a)[0], (a)[1], (a)[2], (a)[3], (a)[4], (a)[5]
#define MACSTR "%02x:%02x:%02x:%02x:%02x:%02x"
/*
* Compact form for string representation of MAC address
* To be used, e.g., for constructing dbus paths for P2P Devices
*/
#define COMPACT_MACSTR "%02x%02x%02x%02x%02x%02x"
#endif
#ifndef BIT
#define BIT(x) (1 << (x))
#endif
/*
* Definitions for sparse validation
* (http://kernel.org/pub/linux/kernel/people/josh/sparse/)
*/
#ifdef __CHECKER__
#define __force __attribute__((force))
#define __bitwise __attribute__((bitwise))
#else
#define __force
#define __bitwise
#endif
typedef u16 __bitwise be16;
typedef u16 __bitwise le16;
typedef u32 __bitwise be32;
typedef u32 __bitwise le32;
typedef u64 __bitwise be64;
typedef u64 __bitwise le64;
#ifndef __must_check
#if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
#define __must_check __attribute__((__warn_unused_result__))
#else
#define __must_check
#endif /* __GNUC__ */
#endif /* __must_check */
//int hwaddr_aton(const char *txt, u8 *addr);
int hwaddr_compact_aton(const char *txt, u8 *addr);
int hwaddr_aton2(const char *txt, u8 *addr);
int hex2byte(const char *hex);
int hexstr2bin(const char *hex, u8 *buf, size_t len);
void inc_byte_array(u8 *counter, size_t len);
void wpa_get_ntp_timestamp(u8 *buf);
//int wpa_snprintf_hex(char *buf, size_t buf_size, const u8 *data, size_t len);
int wpa_snprintf_hex_uppercase(char *buf, size_t buf_size, const u8 *data,
size_t len);
#ifdef CONFIG_NATIVE_WINDOWS
void wpa_unicode2ascii_inplace(TCHAR *str);
TCHAR * wpa_strdup_tchar(const char *str);
#else /* CONFIG_NATIVE_WINDOWS */
#define wpa_unicode2ascii_inplace(s) do { } while (0)
#define wpa_strdup_tchar(s) strdup((s))
#endif /* CONFIG_NATIVE_WINDOWS */
void printf_encode(char *txt, size_t maxlen, const u8 *data, size_t len);
size_t printf_decode(u8 *buf, size_t maxlen, const char *str);
const char * wpa_ssid_txt(const u8 *ssid, size_t ssid_len);
char * wpa_config_parse_string(const char *value, size_t *len);
int is_hex(const u8 *data, size_t len);
size_t merge_byte_arrays(u8 *res, size_t res_len,
const u8 *src1, size_t src1_len,
const u8 *src2, size_t src2_len);
static inline int is_zero_ether_addr(const u8 *a)
{
return !(a[0] | a[1] | a[2] | a[3] | a[4] | a[5]);
}
static inline int is_broadcast_ether_addr(const u8 *a)
{
return (a[0] & a[1] & a[2] & a[3] & a[4] & a[5]) == 0xff;
}
#define broadcast_ether_addr (const u8 *) "\xff\xff\xff\xff\xff\xff"
#include "wpa_debug.h"
char * dup_binstr(const void *src, size_t len);
struct wpa_freq_range_list {
struct wpa_freq_range {
unsigned int min;
unsigned int max;
} *range;
unsigned int num;
};
int freq_range_list_parse(struct wpa_freq_range_list *res, const char *value);
int freq_range_list_includes(const struct wpa_freq_range_list *list,
unsigned int freq);
char * freq_range_list_str(const struct wpa_freq_range_list *list);
int int_array_len(const int *a);
void int_array_concat(int **res, const int *a);
void int_array_sort_unique(int *a);
void int_array_add_unique(int **res, int a);
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
void str_clear_free(char *str);
void bin_clear_free(void *bin, size_t len);
int random_mac_addr(u8 *addr);
int random_mac_addr_keep_oui(u8 *addr);
const char * cstr_token(const char *str, const char *delim, const char **last);
char * str_token(char *str, const char *delim, char **context);
size_t utf8_escape(const char *inp, size_t in_size,
char *outp, size_t out_size);
size_t utf8_unescape(const char *inp, size_t in_size,
char *outp, size_t out_size);
int is_ctrl_char(char c);
#ifndef bswap_16
#define bswap_16(a) ((((u16) (a) << 8) & 0xff00) | (((u16) (a) >> 8) & 0xff))
#endif
/*
* gcc 4.4 ends up generating strict-aliasing warnings about some very common
* networking socket uses that do not really result in a real problem and
* cannot be easily avoided with union-based type-punning due to struct
* definitions including another struct in system header files. To avoid having
* to fully disable strict-aliasing warnings, provide a mechanism to hide the
* typecast from aliasing for now. A cleaner solution will hopefully be found
* in the future to handle these cases.
*/
void * __hide_aliasing_typecast(void *foo);
#define aliasing_hide_typecast(a,t) (t *) __hide_aliasing_typecast((a))
#ifdef CONFIG_VALGRIND
#include <valgrind/memcheck.h>
#define WPA_MEM_DEFINED(ptr, len) VALGRIND_MAKE_MEM_DEFINED((ptr), (len))
#else /* CONFIG_VALGRIND */
#define WPA_MEM_DEFINED(ptr, len) do { } while (0)
#endif /* CONFIG_VALGRIND */
#endif /* COMMON_H */

View file

@ -0,0 +1,119 @@
#ifndef INCLUDES_H
#define INCLUDES_H
#define CONFIG_NO_STDOUT_DEBUG
#ifndef CONFIG_NO_STDOUT_DEBUG
/* Event messages with fixed prefix */
/** Authentication completed successfully and data connection enabled */
#define WPA_EVENT_CONNECTED "CTRL-EVENT-CONNECTED "
/** Disconnected, data connection is not available */
#define WPA_EVENT_DISCONNECTED "CTRL-EVENT-DISCONNECTED "
/** Association rejected during connection attempt */
#define WPA_EVENT_ASSOC_REJECT "CTRL-EVENT-ASSOC-REJECT "
/** Authentication rejected during connection attempt */
#define WPA_EVENT_AUTH_REJECT "CTRL-EVENT-AUTH-REJECT "
/** wpa_supplicant is exiting */
#define WPA_EVENT_TERMINATING "CTRL-EVENT-TERMINATING "
/** Password change was completed successfully */
#define WPA_EVENT_PASSWORD_CHANGED "CTRL-EVENT-PASSWORD-CHANGED "
/** EAP-Request/Notification received */
#define WPA_EVENT_EAP_NOTIFICATION "CTRL-EVENT-EAP-NOTIFICATION "
/** EAP authentication started (EAP-Request/Identity received) */
#define WPA_EVENT_EAP_STARTED "CTRL-EVENT-EAP-STARTED "
/** EAP method proposed by the server */
#define WPA_EVENT_EAP_PROPOSED_METHOD "CTRL-EVENT-EAP-PROPOSED-METHOD "
/** EAP method selected */
#define WPA_EVENT_EAP_METHOD "CTRL-EVENT-EAP-METHOD "
/** EAP peer certificate from TLS */
#define WPA_EVENT_EAP_PEER_CERT "CTRL-EVENT-EAP-PEER-CERT "
/** EAP peer certificate alternative subject name component from TLS */
#define WPA_EVENT_EAP_PEER_ALT "CTRL-EVENT-EAP-PEER-ALT "
/** EAP TLS certificate chain validation error */
#define WPA_EVENT_EAP_TLS_CERT_ERROR "CTRL-EVENT-EAP-TLS-CERT-ERROR "
/** EAP status */
#define WPA_EVENT_EAP_STATUS "CTRL-EVENT-EAP-STATUS "
/** EAP authentication completed successfully */
#define WPA_EVENT_EAP_SUCCESS "CTRL-EVENT-EAP-SUCCESS "
/** EAP authentication failed (EAP-Failure received) */
#define WPA_EVENT_EAP_FAILURE "CTRL-EVENT-EAP-FAILURE "
/** Network block temporarily disabled (e.g., due to authentication failure) */
#define WPA_EVENT_TEMP_DISABLED "CTRL-EVENT-SSID-TEMP-DISABLED "
/** Temporarily disabled network block re-enabled */
#define WPA_EVENT_REENABLED "CTRL-EVENT-SSID-REENABLED "
/** New scan started */
#define WPA_EVENT_SCAN_STARTED "CTRL-EVENT-SCAN-STARTED "
/** New scan results available */
#define WPA_EVENT_SCAN_RESULTS "CTRL-EVENT-SCAN-RESULTS "
/** Scan command failed */
#define WPA_EVENT_SCAN_FAILED "CTRL-EVENT-SCAN-FAILED "
/** wpa_supplicant state change */
#define WPA_EVENT_STATE_CHANGE "CTRL-EVENT-STATE-CHANGE "
/** A new BSS entry was added (followed by BSS entry id and BSSID) */
#define WPA_EVENT_BSS_ADDED "CTRL-EVENT-BSS-ADDED "
/** A BSS entry was removed (followed by BSS entry id and BSSID) */
#define WPA_EVENT_BSS_REMOVED "CTRL-EVENT-BSS-REMOVED "
/** No suitable network was found */
#define WPA_EVENT_NETWORK_NOT_FOUND "CTRL-EVENT-NETWORK-NOT-FOUND "
/** Change in the signal level was reported by the driver */
#define WPA_EVENT_SIGNAL_CHANGE "CTRL-EVENT-SIGNAL-CHANGE "
/** Regulatory domain channel */
#define WPA_EVENT_REGDOM_CHANGE "CTRL-EVENT-REGDOM-CHANGE "
/** RSN IBSS 4-way handshakes completed with specified peer */
#define IBSS_RSN_COMPLETED "IBSS-RSN-COMPLETED "
/** Notification of frequency conflict due to a concurrent operation.
*
* The indicated network is disabled and needs to be re-enabled before it can
* be used again.
*/
#define WPA_EVENT_FREQ_CONFLICT "CTRL-EVENT-FREQ-CONFLICT "
/** Frequency ranges that the driver recommends to avoid */
#define WPA_EVENT_AVOID_FREQ "CTRL-EVENT-AVOID-FREQ "
/** WPS overlap detected in PBC mode */
#define WPS_EVENT_OVERLAP "WPS-OVERLAP-DETECTED "
/** Available WPS AP with active PBC found in scan results */
#define WPS_EVENT_AP_AVAILABLE_PBC "WPS-AP-AVAILABLE-PBC "
/** Available WPS AP with our address as authorized in scan results */
#define WPS_EVENT_AP_AVAILABLE_AUTH "WPS-AP-AVAILABLE-AUTH "
/** Available WPS AP with recently selected PIN registrar found in scan results
*/
#define WPS_EVENT_AP_AVAILABLE_PIN "WPS-AP-AVAILABLE-PIN "
/** Available WPS AP found in scan results */
#define WPS_EVENT_AP_AVAILABLE "WPS-AP-AVAILABLE "
/** A new credential received */
#define WPS_EVENT_CRED_RECEIVED "WPS-CRED-RECEIVED "
/** M2D received */
#define WPS_EVENT_M2D "WPS-M2D "
/** WPS registration failed after M2/M2D */
#define WPS_EVENT_FAIL "WPS-FAIL "
/** WPS registration completed successfully */
#define WPS_EVENT_SUCCESS "WPS-SUCCESS "
/** WPS enrollment attempt timed out and was terminated */
#define WPS_EVENT_TIMEOUT "WPS-TIMEOUT "
/* PBC mode was activated */
#define WPS_EVENT_ACTIVE "WPS-PBC-ACTIVE "
/* PBC mode was disabled */
#define WPS_EVENT_DISABLE "WPS-PBC-DISABLE "
#define WPS_EVENT_ENROLLEE_SEEN "WPS-ENROLLEE-SEEN "
#define WPS_EVENT_OPEN_NETWORK "WPS-OPEN-NETWORK "
/* WPS ER events */
#define WPS_EVENT_ER_AP_ADD "WPS-ER-AP-ADD "
#define WPS_EVENT_ER_AP_REMOVE "WPS-ER-AP-REMOVE "
#define WPS_EVENT_ER_ENROLLEE_ADD "WPS-ER-ENROLLEE-ADD "
#define WPS_EVENT_ER_ENROLLEE_REMOVE "WPS-ER-ENROLLEE-REMOVE "
#define WPS_EVENT_ER_AP_SETTINGS "WPS-ER-AP-SETTINGS "
#define WPS_EVENT_ER_SET_SEL_REG "WPS-ER-AP-SET-SEL-REG "
#endif /* CONFIG_NO_STDOUT_DEBUG */
//#define DBG_871X(...) vTaskDelay(100)
//DBG_871X_LEVEL(_drv_always_, "no beacon for a long time, disconnect or roaming\n");
//#define DBG_871X(...) DBG_871X_LEVEL(_drv_always_,...)
#endif /* INCLUDES_H */

View file

@ -0,0 +1,594 @@
/*
* OS specific functions
* Copyright (c) 2005-2009, Jouni Malinen <j@w1.fi>
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
*/
#ifndef OS_H
#define OS_H
//#include "basic_types.h"
#include <autoconf.h>
#include "osdep_service.h"
#include "freertos/wrapper.h"
#include "utils/rom/rom_wps_os.h"
typedef void* xqueue_handle_t;
typedef long os_time_t;
typedef _timer os_timer;
/**
* os_sleep - Sleep (sec, usec)
* @sec: Number of seconds to sleep
* @usec: Number of microseconds to sleep
*/
void os_sleep(os_time_t sec, os_time_t usec);
struct os_time {
os_time_t sec;
os_time_t usec;
};
struct os_reltime {
os_time_t sec;
os_time_t usec;
};
/**
* os_get_time - Get current time (sec, usec)
* @t: Pointer to buffer for the time
* Returns: 0 on success, -1 on failure
*/
int os_get_time(struct os_time *t);
int os_get_reltime(struct os_reltime *t);
/* Helper macros for handling struct os_time */
/* (&timeout->time, &tmp->time) */
#define os_time_before(a, b) \
((a)->sec < (b)->sec || \
((a)->sec == (b)->sec && (a)->usec < (b)->usec))
#define os_time_sub(a, b, res) do { \
(res)->sec = (a)->sec - (b)->sec; \
(res)->usec = (a)->usec - (b)->usec; \
if ((res)->usec < 0) { \
(res)->sec--; \
(res)->usec += 1000000; \
} \
} while (0)
/**
* os_mktime - Convert broken-down time into seconds since 1970-01-01
* @year: Four digit year
* @month: Month (1 .. 12)
* @day: Day of month (1 .. 31)
* @hour: Hour (0 .. 23)
* @min: Minute (0 .. 59)
* @sec: Second (0 .. 60)
* @t: Buffer for returning calendar time representation (seconds since
* 1970-01-01 00:00:00)
* Returns: 0 on success, -1 on failure
*
* Note: The result is in seconds from Epoch, i.e., in UTC, not in local time
* which is used by POSIX mktime().
*/
int os_mktime(int year, int month, int day, int hour, int min, int sec,
os_time_t *t);
struct os_tm {
int sec; /* 0..59 or 60 for leap seconds */
int min; /* 0..59 */
int hour; /* 0..23 */
int day; /* 1..31 */
int month; /* 1..12 */
int year; /* Four digit year */
};
int os_gmtime(os_time_t t, struct os_tm *tm);
/* Helpers for handling struct os_time */
/* Helpers for handling struct os_reltime */
static inline int os_reltime_before(struct os_reltime *a,
struct os_reltime *b)
{
return os_time_before(a,b);
}
static inline void os_reltime_sub(struct os_reltime *a, struct os_reltime *b,
struct os_reltime *res)
{
os_time_sub(a,b,res);
}
static inline void os_reltime_age(struct os_reltime *start,
struct os_reltime *age)
{
struct os_reltime now;
os_get_time((struct os_time *)&now);
os_reltime_sub(&now, start, age);
}
static inline int os_reltime_expired(struct os_reltime *now,
struct os_reltime *ts,
os_time_t timeout_secs)
{
struct os_reltime age;
os_reltime_sub(now, ts, &age);
return (age.sec > timeout_secs) ||
(age.sec == timeout_secs && age.usec > 0);
}
/**
* os_daemonize - Run in the background (detach from the controlling terminal)
* @pid_file: File name to write the process ID to or %NULL to skip this
* Returns: 0 on success, -1 on failure
*/
int os_daemonize(const char *pid_file);
/**
* os_daemonize_terminate - Stop running in the background (remove pid file)
* @pid_file: File name to write the process ID to or %NULL to skip this
*/
void os_daemonize_terminate(const char *pid_file);
/**
* os_get_random - Get cryptographically strong pseudo random data
* @buf: Buffer for pseudo random data
* @len: Length of the buffer
* Returns: 0 on success, -1 on failure
*/
int os_get_random(unsigned char *buf, size_t len);
/**
* os_random - Get pseudo random value (not necessarily very strong)
* Returns: Pseudo random value
*/
unsigned long os_random(void);
/**
* os_rel2abs_path - Get an absolute path for a file
* @rel_path: Relative path to a file
* Returns: Absolute path for the file or %NULL on failure
*
* This function tries to convert a relative path of a file to an absolute path
* in order for the file to be found even if current working directory has
* changed. The returned value is allocated and caller is responsible for
* freeing it. It is acceptable to just return the same path in an allocated
* buffer, e.g., return strdup(rel_path). This function is only used to find
* configuration files when os_daemonize() may have changed the current working
* directory and relative path would be pointing to a different location.
*/
char * os_rel2abs_path(const char *rel_path);
/**
* os_program_init - Program initialization (called at start)
* Returns: 0 on success, -1 on failure
*
* This function is called when a programs starts. If there are any OS specific
* processing that is needed, it can be placed here. It is also acceptable to
* just return 0 if not special processing is needed.
*/
int os_program_init(void);
/**
* os_program_deinit - Program deinitialization (called just before exit)
*
* This function is called just before a program exists. If there are any OS
* specific processing, e.g., freeing resourced allocated in os_program_init(),
* it should be done here. It is also acceptable for this function to do
* nothing.
*/
void os_program_deinit(void);
/**
* os_setenv - Set environment variable
* @name: Name of the variable
* @value: Value to set to the variable
* @overwrite: Whether existing variable should be overwritten
* Returns: 0 on success, -1 on error
*
* This function is only used for wpa_cli action scripts. OS wrapper does not
* need to implement this if such functionality is not needed.
*/
int os_setenv(const char *name, const char *value, int overwrite);
/**
* os_unsetenv - Delete environent variable
* @name: Name of the variable
* Returns: 0 on success, -1 on error
*
* This function is only used for wpa_cli action scripts. OS wrapper does not
* need to implement this if such functionality is not needed.
*/
int os_unsetenv(const char *name);
/**
* os_readfile - Read a file to an allocated memory buffer
* @name: Name of the file to read
* @len: For returning the length of the allocated buffer
* Returns: Pointer to the allocated buffer or %NULL on failure
*
* This function allocates memory and reads the given file to this buffer. Both
* binary and text files can be read with this function. The caller is
* responsible for freeing the returned buffer with os_free().
*/
char * os_readfile(const char *name, size_t *len);
//#if 0
/**
* os_zalloc - Allocate and zero memory
* @size: Number of bytes to allocate
* Returns: Pointer to allocated and zeroed memory or %NULL on failure
*
* Caller is responsible for freeing the returned buffer with os_free().
*/
void * os_zalloc(size_t size);
/**
* os_calloc - Allocate and zero memory for an array
* @nmemb: Number of members in the array
* @size: Number of bytes in each member
* Returns: Pointer to allocated and zeroed memory or %NULL on failure
*
* This function can be used as a wrapper for os_zalloc(nmemb * size) when an
* allocation is used for an array. The main benefit over os_zalloc() is in
* having an extra check to catch integer overflows in multiplication.
*
* Caller is responsible for freeing the returned buffer with os_free().
*/
static inline void * os_calloc(size_t nmemb, size_t size)
{
if (size && nmemb > (~(size_t) 0) / size)
return NULL;
return os_zalloc(nmemb * size);
}
//#endif
static inline int os_memcmp_const(const void *a, const void *b, size_t len)
{
const u8 *aa = a;
const u8 *bb = b;
size_t i;
u8 res;
for (res = 0, i = 0; i < len; i++)
res |= aa[i] ^ bb[i];
return res;
}
/*
* The following functions are wrapper for standard ANSI C or POSIX functions.
* By default, they are just defined to use the standard function name and no
* os_*.c implementation is needed for them. This avoids extra function calls
* by allowing the C pre-processor take care of the function name mapping.
*
* If the target system uses a C library that does not provide these functions,
* build_config.h can be used to define the wrappers to use a different
* function name. This can be done on function-by-function basis since the
* defines here are only used if build_config.h does not define the os_* name.
* If needed, os_*.c file can be used to implement the functions that are not
* included in the C library on the target system. Alternatively,
* OS_NO_C_LIB_DEFINES can be defined to skip all defines here in which case
* these functions need to be implemented in os_*.c file for the target system.
*/
#ifdef OS_NO_C_LIB_DEFINES
/**
* os_malloc - Allocate dynamic memory
* @size: Size of the buffer to allocate
* Returns: Allocated buffer or %NULL on failure
*
* Caller is responsible for freeing the returned buffer with os_free().
*/
void * os_malloc(size_t size);
/**
* os_realloc - Re-allocate dynamic memory
* @ptr: Old buffer from os_malloc() or os_realloc()
* @size: Size of the new buffer
* Returns: Allocated buffer or %NULL on failure
*
* Caller is responsible for freeing the returned buffer with os_free().
* If re-allocation fails, %NULL is returned and the original buffer (ptr) is
* not freed and caller is still responsible for freeing it.
*/
void * os_realloc(void *ptr, size_t size);
/**
* os_free - Free dynamic memory
* @ptr: Old buffer from os_malloc() or os_realloc(); can be %NULL
*/
void os_free(void *ptr);
/**
* os_memcpy - Copy memory area
* @dest: Destination
* @src: Source
* @n: Number of bytes to copy
* Returns: dest
*
* The memory areas src and dst must not overlap. os_memmove() can be used with
* overlapping memory.
*/
void * os_memcpy(void *dest, const void *src, size_t n);
/**
* os_memmove - Copy memory area
* @dest: Destination
* @src: Source
* @n: Number of bytes to copy
* Returns: dest
*
* The memory areas src and dst may overlap.
*/
void *os_memmove(void *dest, const void *src, size_t n);
/**
* os_memset - Fill memory with a constant byte
* @s: Memory area to be filled
* @c: Constant byte
* @n: Number of bytes started from s to fill with c
* Returns: s
*/
void *os_memset(void *s, int c, size_t n);
/**
* os_memcmp - Compare memory areas
* @s1: First buffer
* @s2: Second buffer
* @n: Maximum numbers of octets to compare
* Returns: An integer less than, equal to, or greater than zero if s1 is
* found to be less than, to match, or be greater than s2. Only first n
* characters will be compared.
*/
int os_memcmp(const void *s1, const void *s2, size_t n);
/**
* os_strdup - Duplicate a string
* @s: Source string
* Returns: Allocated buffer with the string copied into it or %NULL on failure
*
* Caller is responsible for freeing the returned buffer with os_free().
*/
char *os_strdup(const char *s);
/**
* os_strlen - Calculate the length of a string
* @s: '\0' terminated string
* Returns: Number of characters in s (not counting the '\0' terminator)
*/
size_t os_strlen(const char *s);
/**
* os_strcasecmp - Compare two strings ignoring case
* @s1: First string
* @s2: Second string
* Returns: An integer less than, equal to, or greater than zero if s1 is
* found to be less than, to match, or be greatred than s2
*/
int os_strcasecmp(const char *s1, const char *s2);
/**
* os_strncasecmp - Compare two strings ignoring case
* @s1: First string
* @s2: Second string
* @n: Maximum numbers of characters to compare
* Returns: An integer less than, equal to, or greater than zero if s1 is
* found to be less than, to match, or be greater than s2. Only first n
* characters will be compared.
*/
int os_strncasecmp(const char *s1, const char *s2, size_t n);
/**
* os_strchr - Locate the first occurrence of a character in string
* @s: String
* @c: Character to search for
* Returns: Pointer to the matched character or %NULL if not found
*/
char *os_strchr(const char *s, int c);
/**
* os_strrchr - Locate the last occurrence of a character in string
* @s: String
* @c: Character to search for
* Returns: Pointer to the matched character or %NULL if not found
*/
char *os_strrchr(const char *s, int c);
/**
* os_strcmp - Compare two strings
* @s1: First string
* @s2: Second string
* Returns: An integer less than, equal to, or greater than zero if s1 is
* found to be less than, to match, or be greatred than s2
*/
int os_strcmp(const char *s1, const char *s2);
/**
* os_strncmp - Compare two strings
* @s1: First string
* @s2: Second string
* @n: Maximum numbers of characters to compare
* Returns: An integer less than, equal to, or greater than zero if s1 is
* found to be less than, to match, or be greater than s2. Only first n
* characters will be compared.
*/
int os_strncmp(const char *s1, const char *s2, size_t n);
/**
* os_strncpy - Copy a string
* @dest: Destination
* @src: Source
* @n: Maximum number of characters to copy
* Returns: dest
*/
char *os_strncpy(char *dest, const char *src, size_t n);
/**
* os_strstr - Locate a substring
* @haystack: String (haystack) to search from
* @needle: Needle to search from haystack
* Returns: Pointer to the beginning of the substring or %NULL if not found
*/
char *os_strstr(const char *haystack, const char *needle);
/**
* os_snprintf - Print to a memory buffer
* @str: Memory buffer to print into
* @size: Maximum length of the str buffer
* @format: printf format
* Returns: Number of characters printed (not including trailing '\0').
*
* If the output buffer is truncated, number of characters which would have
* been written is returned. Since some C libraries return -1 in such a case,
* the caller must be prepared on that value, too, to indicate truncation.
*
* Note: Some C library implementations of snprintf() may not guarantee null
* termination in case the output is truncated. The OS wrapper function of
* os_snprintf() should provide this guarantee, i.e., to null terminate the
* output buffer if a C library version of the function is used and if that
* function does not guarantee null termination.
*
* If the target system does not include snprintf(), see, e.g.,
* http://www.ijs.si/software/snprintf/ for an example of a portable
* implementation of snprintf.
*/
int os_snprintf(char *str, size_t size, const char *format, ...);
#else /* OS_NO_C_LIB_DEFINES */
#if !defined(CONFIG_PLATFORM_8195A) && !defined(CONFIG_PLATFORM_8711B)
#ifdef CONFIG_MEM_MONITOR
u8* os_malloc(u32 sz);
void os_mfree(u8 *pbuf, u32 sz);
#ifndef os_free
#define os_free(p, sz) os_mfree(((u8*)(p)), (sz))
#endif
#else
#ifndef os_malloc
#define os_malloc(sz) _rtw_malloc(sz)
#endif
#ifndef os_free
#define os_free(p, sz) _rtw_mfree(((u8*)(p)), (sz))
#endif
#endif
#endif
extern void *os_zalloc(size_t size);
extern char *os_strdup(const char *string_copy_from);
#ifndef os_sleep
#define os_sleep(s, us) rtw_mdelay_os((s)*1000 + (us)/1000)
#endif
#ifndef os_memcpy
#define os_memcpy(d, s, n) rtw_memcpy((void*)(d), ((void*)(s)), (n))
#endif
#ifndef os_memmove
#define os_memmove(d, s, n) memmove((d), (s), (n))
#endif
#ifndef os_memset
#define os_memset(pbuf, c, sz) rtw_memset(pbuf, c, sz)
#endif
#ifndef os_memcmp
#define os_memcmp(s1, s2, n) rtw_memcmp(((void*)(s1)), ((void*)(s2)), (n))
#endif
#ifndef os_memcmp_p2p
#define os_memcmp_p2p(s1, s2, n) memcmp((s1), (s2), (n))
#endif
#ifndef os_get_random_bytes
#define os_get_random_bytes(d,sz) rtw_get_random_bytes(((void*)(d)), (sz))
#endif
#ifndef os_strlen
#define os_strlen(s) strlen(s)
#endif
#ifndef os_strcasecmp
#ifdef _MSC_VER
#define os_strcasecmp(s1, s2) _stricmp((s1), (s2))
#else
#define os_strcasecmp(s1, s2) strcasecmp((s1), (s2))
#endif
#endif
#ifndef os_strncasecmp
#ifdef _MSC_VER
#define os_strncasecmp(s1, s2, n) _strnicmp((s1), (s2), (n))
#else
#define os_strncasecmp(s1, s2, n) strncasecmp((s1), (s2), (n))
#endif
#endif
#ifndef os_init_timer
#define os_init_timer(t, p, f, x, n) rtw_init_timer((t), (p), (f), (x), (n))
#endif
#ifndef os_set_timer
#define os_set_timer(t, d) rtw_set_timer((t), (d))
#endif
#ifndef os_cancel_timer
#define os_cancel_timer(t) rtw_cancel_timer(t)
#endif
#ifndef os_del_timer
#define os_del_timer(t) rtw_del_timer(t)
#endif
#ifndef os_atoi
#define os_atoi(s) rtw_atoi(s)
#endif
#ifndef os_strchr
#define os_strchr(s, c) strchr((s), (c))
#endif
#ifndef os_strcmp
#define os_strcmp(s1, s2) strcmp((s1), (s2))
#endif
#ifndef os_strncmp
#define os_strncmp(s1, s2, n) strncmp((s1), (s2), (n))
#endif
#ifndef os_strncpy
#define os_strncpy(d, s, n) strncpy((d), (s), (n))
#endif
#ifndef os_strrchr
#define os_strrchr(s, c) strrchr((s), (c))
#endif
#ifndef os_strstr
#define os_strstr(h, n) strstr((h), (n))
#endif
#ifndef os_snprintf
#ifdef _MSC_VER
#define os_snprintf _snprintf
#else
#define os_snprintf snprintf
#endif
#endif
#endif /* OS_NO_C_LIB_DEFINES */
static inline void * os_realloc_array(void *ptr, size_t nmemb, size_t size)
{
if (size && nmemb > (~(size_t) 0) / size)
return NULL;
return os_realloc(ptr, nmemb * size, nmemb * size);
}
void *os_xqueue_create(unsigned long uxQueueLength, unsigned long uxItemSize) ;
int os_xqueue_receive(xqueue_handle_t xQueue, void * const pvBuffer, unsigned long xSecsToWait);
void os_xqueue_delete(xqueue_handle_t xQueue );
int os_xqueue_send(xqueue_handle_t xQueue, const void * const pvItemToQueue, unsigned long xSecsToWait);
#endif /* OS_H */

View file

@ -0,0 +1,119 @@
/*
* OS specific functions for UNIX/POSIX systems
* Copyright (c) 2005-2009, Jouni Malinen <j@w1.fi>
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
*/
#include "utils/os.h"
//#ifdef CONFIG_WPS
#if !defined(CONFIG_PLATFORM_8195A) && !defined(CONFIG_PLATFORM_8711B)
#ifdef CONFIG_MEM_MONITOR
#if CONFIG_MEM_MONITOR & MEM_MONITOR_LEAK
_list wpa_mem_table;
int wpa_mem_used_num;
//int wpa_mem_used_size;
#endif
extern int min_free_heap_size;
u8* os_malloc(u32 sz)
{
int free_heap_size = rtw_getFreeHeapSize();
u8 *pbuf = _rtw_malloc(sz);
#if CONFIG_MEM_MONITOR & MEM_MONITOR_LEAK
add_mem_usage(&wpa_mem_table, pbuf, sz, &wpa_mem_used_num, MEM_MONITOR_FLAG_WPAS);
#else
add_mem_usage(NULL, pbuf, sz, NULL, MEM_MONITOR_FLAG_WPAS);
#endif
if(min_free_heap_size > free_heap_size)
min_free_heap_size = free_heap_size;
return pbuf;
}
void os_mfree(u8 *pbuf, u32 sz)
{
_rtw_mfree(pbuf, sz);
#if CONFIG_MEM_MONITOR & MEM_MONITOR_LEAK
del_mem_usage(&wpa_mem_table, pbuf, &wpa_mem_used_num, MEM_MONITOR_FLAG_WPAS);
#else
del_mem_usage(NULL, pbuf, NULL, MEM_MONITOR_FLAG_WPAS);
#endif
}
#endif//CONFIG_MEM_MONITOR
#endif// !defined(CONFIG_PLATFORM_8195A)
#ifndef OS_NO_C_LIB_DEFINES
char *os_strdup(const char *string_copy_from)
{
char *string_copy_to = NULL;
string_copy_to = os_zalloc(strlen(string_copy_from) + 1);
os_memcpy((void *)string_copy_to, string_copy_from, strlen(string_copy_from));
string_copy_to[strlen(string_copy_from)] = '\0';
return string_copy_to;
}
#endif
int os_get_random(unsigned char *buf, size_t len)
{
//TODO implement it
rtw_get_random_bytes(buf, len);
return 0;
}
int os_get_time(struct os_time *t){
unsigned int tt = rtw_get_current_time();
t->sec = (os_time_t) (tt / 1000);
t->usec = (os_time_t) (tt % 1000)*1000;
return 0;
}
int os_get_reltime(struct os_reltime *t){
os_get_time((struct os_time *)t);
return 0;
}
#if 0
void *os_xqueue_create(unsigned long uxQueueLength, unsigned long uxItemSize)
{
return xQueueCreate( uxQueueLength, uxItemSize );
}
int os_xqueue_receive(xqueue_handle_t xQueue, void * const pvBuffer, unsigned long xSecsToWait)
{
return xQueueReceive((xQueueHandle)xQueue, pvBuffer, (portTickType)(xSecsToWait*configTICK_RATE_HZ));
}
void os_xqueue_delete(xqueue_handle_t xQueue )
{
vQueueDelete((xQueueHandle)xQueue);
}
int os_xqueue_send(xqueue_handle_t xQueue, const void * const pvItemToQueue, unsigned long xSecsToWait)
{
return xQueueSendToBack((xQueueHandle)xQueue, pvItemToQueue, (portTickType)(xSecsToWait*configTICK_RATE_HZ));
}
#else
void *os_xqueue_create(unsigned long uxQueueLength, unsigned long uxItemSize)
{
void* xQueue = NULL;
rtw_init_xqueue(&xQueue, "queue", uxItemSize, uxQueueLength);
return xQueue;
}
int os_xqueue_receive(xqueue_handle_t xQueue, void * const pvBuffer, unsigned long xSecsToWait)
{
return rtw_pop_from_xqueue(&xQueue, pvBuffer, xSecsToWait*1000);
}
void os_xqueue_delete(xqueue_handle_t xQueue )
{
rtw_deinit_xqueue(&xQueue);
}
int os_xqueue_send(xqueue_handle_t xQueue, const void * const pvItemToQueue, unsigned long xSecsToWait)
{
return rtw_push_to_xqueue(&xQueue, (void*)pvItemToQueue, xSecsToWait*1000);
}
#endif
//#endif

View file

@ -0,0 +1,24 @@
/*
* OS specific functions
* Copyright (c) 2005-2009, Jouni Malinen <j@w1.fi>
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
*/
#ifndef ROM_WPS_OS_H
#define ROM_WPS_OS_H
#if defined(CONFIG_PLATFORM_8195A) || defined(CONFIG_PLATFORM_8711B)
#include <rom_wlan_ram_map.h>
extern struct _rom_wlan_ram_map rom_wlan_ram_map;
#define os_malloc(sz) rom_wlan_ram_map.rtw_malloc(sz)
#define os_free(p, sz) rom_wlan_ram_map.rtw_mfree(((u8*)(p)), (sz))
#endif
extern u8 *WPS_realloc(u8 *old_buf, u32 old_sz, u32 new_sz);
#define os_realloc(p, os, ns) WPS_realloc(((u8*)(p)),(os),(ns))
#endif /* ROM_WPS_OS_H */

Some files were not shown because too many files have changed in this diff Show more