From eff767a0742b25116f4d0ac766107d4a21ed19cb Mon Sep 17 00:00:00 2001 From: shaojinchun Date: Mon, 17 Dec 2018 10:21:40 +0800 Subject: remove rt_hw_mb define sync smp skeleton --- include/rtdef.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'include/rtdef.h') diff --git a/include/rtdef.h b/include/rtdef.h index 253ec36968..8ae4e2ad4f 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -507,8 +507,8 @@ typedef siginfo_t rt_siginfo_t; #define RT_CPU_DETACHED RT_CPUS_NR /**< The thread not running on cpu. */ #define RT_CPU_MASK ((1 << RT_CPUS_NR) - 1) /**< All CPUs mask bit. */ -#ifndef RT_SCHEDULE_IPI_IRQ -#define RT_SCHEDULE_IPI_IRQ 0 +#ifndef RT_SCHEDULE_IPI +#define RT_SCHEDULE_IPI 0 #endif /** -- cgit v1.3.1 From e716bbfa22a735f5496c9a63f3e84f993bbc9c2f Mon Sep 17 00:00:00 2001 From: Owen Date: Wed, 26 Dec 2018 10:13:26 +0800 Subject: Update rtdef.h MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 更正为正确的Doxygen组定义语法 --- include/rtdef.h | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) (limited to 'include/rtdef.h') diff --git a/include/rtdef.h b/include/rtdef.h index 49551de9ee..f4949c2dff 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -45,7 +45,7 @@ extern "C" { * @addtogroup BasicDef */ -/*@{*/ +/**@{*/ /* RT-Thread version information */ #define RT_VERSION 4L /**< major version number */ @@ -88,7 +88,7 @@ typedef rt_base_t rt_off_t; /**< Type for offset */ #define RT_TRUE 1 /**< boolean true */ #define RT_FALSE 0 /**< boolean fails */ -/*@}*/ +/**@}*/ /* maximum value of base type */ #define RT_UINT8_MAX 0xff /**< Maxium number of UINT8 */ @@ -259,7 +259,7 @@ typedef int (*init_fn_t)(void); * @addtogroup Error */ -/*@{*/ +/**@{*/ /* RT-Thread error code definitions */ #define RT_EOK 0 /**< There is no error */ @@ -274,7 +274,7 @@ typedef int (*init_fn_t)(void); #define RT_EINTR 9 /**< Interrupted system call */ #define RT_EINVAL 10 /**< Invalid argument */ -/*@}*/ +/**@}*/ /** * @ingroup BasicDef @@ -325,7 +325,7 @@ typedef struct rt_slist_node rt_slist_t; /**< Type for single lis * @addtogroup KernelObject */ -/*@{*/ +/**@{*/ /* * kernel object macros @@ -402,13 +402,13 @@ struct rt_object_information #define RT_OBJECT_HOOK_CALL(func, argv) #endif -/*@}*/ +/**@}*/ /** * @addtogroup Clock */ -/*@{*/ +/**@{*/ /** * clock & timer macros @@ -452,7 +452,7 @@ struct rt_timer }; typedef struct rt_timer *rt_timer_t; -/*@}*/ +/**@}*/ /** * @addtogroup Signal @@ -465,13 +465,13 @@ typedef siginfo_t rt_siginfo_t; #define RT_SIG_MAX 32 #endif -/*@}*/ +/**@}*/ /** * @addtogroup Thread */ -/*@{*/ +/**@{*/ /* * Thread @@ -613,13 +613,13 @@ struct rt_thread }; typedef struct rt_thread *rt_thread_t; -/*@}*/ +/**@}*/ /** * @addtogroup IPC */ -/*@{*/ +/**@{*/ /** * IPC flags and control command definitions @@ -737,13 +737,13 @@ struct rt_messagequeue typedef struct rt_messagequeue *rt_mq_t; #endif -/*@}*/ +/**@}*/ /** * @addtogroup MM */ -/*@{*/ +/**@{*/ /* * memory management @@ -811,14 +811,14 @@ struct rt_mempool typedef struct rt_mempool *rt_mp_t; #endif -/*@}*/ +/**@}*/ #ifdef RT_USING_DEVICE /** * @addtogroup Device */ -/*@{*/ +/**@{*/ /** * device (I/O) class type @@ -1063,7 +1063,7 @@ struct rt_device_graphic_ops }; #define rt_graphix_ops(device) ((struct rt_device_graphic_ops *)(device->user_data)) -/*@}*/ +/**@}*/ #endif /* definitions for libc */ -- cgit v1.3.1 From ed9a558da979035c38fac68d715bfa3ea553822d Mon Sep 17 00:00:00 2001 From: shaojinchun Date: Thu, 27 Dec 2018 16:31:22 +0800 Subject: list_*时,提供对第一层object的原子保护 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- components/finsh/cmd.c | 946 ++++++++++++++++++++++++++++++------------------- include/rtdef.h | 3 +- 2 files changed, 574 insertions(+), 375 deletions(-) (limited to 'include/rtdef.h') diff --git a/components/finsh/cmd.c b/components/finsh/cmd.c index 1adefea652..aa6ee6c2fc 100644 --- a/components/finsh/cmd.c +++ b/components/finsh/cmd.c @@ -26,6 +26,8 @@ * 2012-10-22 Bernard add MS VC++ patch. * 2016-06-02 armink beautify the list_thread command * 2018-11-22 Jesven list_thread add smp support + * 2018-12-27 Jesven Fix the problem that disable interrupt too long in list_thread + * Provide protection for the "first layer of objects" when list_* */ #include @@ -35,6 +37,8 @@ #include "finsh.h" +#define LIST_FIND_OBJ_NR 8 + long hello(void) { rt_kprintf("Hello RT-Thread!\n"); @@ -53,45 +57,51 @@ long version(void) FINSH_FUNCTION_EXPORT(version, show RT-Thread version information); MSH_CMD_EXPORT(version, show RT-Thread version information); -static int object_name_maxlen(const char *type_name, struct rt_list_node *list) +rt_inline void object_split(int len) { - struct rt_list_node *node; - struct rt_object *object = NULL; - int max_length = rt_strlen(type_name), length; - - rt_enter_critical(); - for (node = list->next; node != list; node = node->next) - { - object = rt_list_entry(node, struct rt_object, list); - - length = rt_strlen(object->name); - if (length > max_length) max_length = length; - } - rt_exit_critical(); - - if (max_length > RT_NAME_MAX || max_length == 0) max_length = RT_NAME_MAX; - - return max_length; + while (len--) rt_kprintf("-"); } -rt_inline void object_split(int len) +typedef struct { - while (len--) rt_kprintf("-"); + rt_list_t *list; + rt_list_t **array; + rt_uint8_t type; + int nr; /* input: max nr, can't be 0 */ + int nr_out; /* out: got nr */ +} list_get_next_t; + +static void list_find_init(list_get_next_t *p, rt_uint8_t type, rt_list_t **array, int nr) +{ + struct rt_object_information *info; + rt_list_t *list; + + info = rt_object_get_information(type); + list = &info->object_list; + + p->list = list; + p->type = type; + p->array = array; + p->nr = nr; + p->nr_out = 0; } -static rt_list_t *list_thread_next(rt_list_t *current, int *max_name_len) +static rt_list_t *list_get_next(rt_list_t *current, list_get_next_t *arg) { int first_flag = 0; rt_ubase_t level; - struct rt_object_information *info; - rt_list_t *node, *iter, *list; - struct rt_thread *thread; - const char *item_title = "thread"; - int maxlen; - struct rt_thread thread_info; + rt_list_t *node, *list; + rt_list_t **array; + int nr; - info = rt_object_get_information(RT_Object_Class_Thread); - list = &info->object_list; + arg->nr_out = 0; + + if (!arg->nr || !arg->type) + { + return (rt_list_t *)RT_NULL; + } + + list = arg->list; if (!current) /* find first */ { @@ -105,112 +115,132 @@ static rt_list_t *list_thread_next(rt_list_t *current, int *max_name_len) level = rt_hw_interrupt_disable(); - if (first_flag) - { - /* is find first */ - maxlen = object_name_maxlen(item_title, list); - *max_name_len = maxlen; - } - else + if (!first_flag) { + struct rt_object *obj; /* The node in the list? */ - for (iter = list->next; iter != list; iter = iter->next) - { - if (iter == node) - { - break; - } - } - if (iter == list) + obj = rt_list_entry(node, struct rt_object, list); + if ((obj->type & ~RT_Object_Class_Static) != arg->type) { - /* not found , error! */ rt_hw_interrupt_enable(level); return (rt_list_t *)RT_NULL; } - maxlen = *max_name_len; } - node = node->next; - if (node == list) + nr = 0; + array = arg->array; + while (1) { - /* At the end of list */ - rt_hw_interrupt_enable(level); - return (rt_list_t *)RT_NULL; + node = node->next; + + if (node == list) + { + node = (rt_list_t *)RT_NULL; + break; + } + nr++; + *array++ = node; + if (nr == arg->nr) + { + break; + } } + + rt_hw_interrupt_enable(level); + arg->nr_out = nr; + return node; +} - /* ok, found a thread */ - thread = rt_list_entry(node, struct rt_thread, list); - /* copy info */ - memcpy(&thread_info, thread, sizeof thread_info); +long list_thread(void) +{ + rt_ubase_t level; + list_get_next_t find_arg; + rt_list_t *obj_list[LIST_FIND_OBJ_NR]; + rt_list_t *next = (rt_list_t*)RT_NULL; + const char *item_title = "thread"; + int maxlen; - rt_hw_interrupt_enable(level); + list_find_init(&find_arg, RT_Object_Class_Thread, obj_list, sizeof(obj_list)/sizeof(obj_list[0])); - /* now output thread info */ - { - rt_uint8_t stat; - rt_uint8_t *ptr; + maxlen = RT_NAME_MAX; - if (first_flag) - { #ifdef RT_USING_SMP - rt_kprintf("%-*.s cpu pri status sp stack size max used left tick error\n", maxlen, item_title); object_split(maxlen); - rt_kprintf( " --- --- ------- ---------- ---------- ------ ---------- ---\n"); + rt_kprintf("%-*.s cpu pri status sp stack size max used left tick error\n", maxlen, item_title); object_split(maxlen); + rt_kprintf( " --- --- ------- ---------- ---------- ------ ---------- ---\n"); #else - rt_kprintf("%-*.s pri status sp stack size max used left tick error\n", maxlen, item_title); object_split(maxlen); - rt_kprintf( " --- ------- ---------- ---------- ------ ---------- ---\n"); + rt_kprintf("%-*.s pri status sp stack size max used left tick error\n", maxlen, item_title); object_split(maxlen); + rt_kprintf( " --- ------- ---------- ---------- ------ ---------- ---\n"); #endif /*RT_USING_SMP*/ - } + + do + { + next = list_get_next(next, &find_arg); + { + int i; + for (i = 0; i < find_arg.nr_out; i++) + { + struct rt_object *obj; + struct rt_thread thread_info, *thread; + + obj = rt_list_entry(obj_list[i], struct rt_object, list); + level = rt_hw_interrupt_disable(); + + if ((obj->type & ~RT_Object_Class_Static) != find_arg.type) + { + rt_hw_interrupt_enable(level); + continue; + } + /* copy info */ + memcpy(&thread_info, obj, sizeof thread_info); + rt_hw_interrupt_enable(level); + + thread = (struct rt_thread*)obj; + { + rt_uint8_t stat; + rt_uint8_t *ptr; + #ifdef RT_USING_SMP - if (thread_info.oncpu != RT_CPU_DETACHED) - rt_kprintf("%-*.*s %3d %3d ", maxlen, RT_NAME_MAX, thread_info.name, thread_info.oncpu, thread_info.current_priority); - else - rt_kprintf("%-*.*s N/A %3d ", maxlen, RT_NAME_MAX, thread_info.name, thread_info.current_priority); + if (thread->oncpu != RT_CPU_DETACHED) + rt_kprintf("%-*.*s %3d %3d ", maxlen, RT_NAME_MAX, thread->name, thread->oncpu, thread->current_priority); + else + rt_kprintf("%-*.*s N/A %3d ", maxlen, RT_NAME_MAX, thread->name, thread->current_priority); #else - rt_kprintf("%-*.*s %3d ", maxlen, RT_NAME_MAX, thread_info.name, thread_info.current_priority); + rt_kprintf("%-*.*s %3d ", maxlen, RT_NAME_MAX, thread->name, thread->current_priority); #endif /*RT_USING_SMP*/ - stat = (thread_info.stat & RT_THREAD_STAT_MASK); - if (stat == RT_THREAD_READY) rt_kprintf(" ready "); - else if (stat == RT_THREAD_SUSPEND) rt_kprintf(" suspend"); - else if (stat == RT_THREAD_INIT) rt_kprintf(" init "); - else if (stat == RT_THREAD_CLOSE) rt_kprintf(" close "); + stat = (thread->stat & RT_THREAD_STAT_MASK); + if (stat == RT_THREAD_READY) rt_kprintf(" ready "); + else if (stat == RT_THREAD_SUSPEND) rt_kprintf(" suspend"); + else if (stat == RT_THREAD_INIT) rt_kprintf(" init "); + else if (stat == RT_THREAD_CLOSE) rt_kprintf(" close "); #if defined(ARCH_CPU_STACK_GROWS_UPWARD) - ptr = (rt_uint8_t *)thread_info.stack_addr + thread_info.stack_size - 1; - while (*ptr == '#')ptr --; - - rt_kprintf(" 0x%08x 0x%08x %02d%% 0x%08x %03d\n", - ((rt_ubase_t)thread_info.sp - (rt_ubase_t)thread_info.stack_addr), - thread_info.stack_size, - ((rt_ubase_t)ptr - (rt_ubase_t)thread_info.stack_addr) * 100 / thread_info.stack_size, - thread_info.remaining_tick, - thread_info.error); + ptr = (rt_uint8_t *)thread->stack_addr + thread->stack_size - 1; + while (*ptr == '#')ptr --; + + rt_kprintf(" 0x%08x 0x%08x %02d%% 0x%08x %03d\n", + ((rt_ubase_t)thread->sp - (rt_ubase_t)thread->stack_addr), + thread->stack_size, + ((rt_ubase_t)ptr - (rt_ubase_t)thread->stack_addr) * 100 / thread->stack_size, + thread->remaining_tick, + thread->error); #else - ptr = (rt_uint8_t *)thread_info.stack_addr; - while (*ptr == '#')ptr ++; - - rt_kprintf(" 0x%08x 0x%08x %02d%% 0x%08x %03d\n", - thread_info.stack_size + ((rt_ubase_t)thread_info.stack_addr - (rt_ubase_t)thread_info.sp), - thread_info.stack_size, - (thread_info.stack_size - ((rt_ubase_t) ptr - (rt_ubase_t) thread_info.stack_addr)) * 100 - / thread_info.stack_size, - thread_info.remaining_tick, - thread_info.error); + ptr = (rt_uint8_t *)thread->stack_addr; + while (*ptr == '#')ptr ++; + + rt_kprintf(" 0x%08x 0x%08x %02d%% 0x%08x %03d\n", + thread->stack_size + ((rt_ubase_t)thread->stack_addr - (rt_ubase_t)thread->sp), + thread->stack_size, + (thread->stack_size - ((rt_ubase_t) ptr - (rt_ubase_t) thread->stack_addr)) * 100 + / thread->stack_size, + thread->remaining_tick, + thread->error); #endif + } + } + } } - return node; -} - -long list_thread(void) -{ - int maxlen; - rt_list_t *thread_list = (rt_list_t*)RT_NULL; - - do - { - thread_list = list_thread_next(thread_list, &maxlen); - } - while (thread_list != (rt_list_t*)RT_NULL); + while (next != (rt_list_t*)RT_NULL); return 0; } @@ -233,427 +263,595 @@ static void show_wait_queue(struct rt_list_node *list) } #ifdef RT_USING_SEMAPHORE -static long _list_sem(struct rt_list_node *list) +long list_sem(void) { + rt_ubase_t level; + list_get_next_t find_arg; + rt_list_t *obj_list[LIST_FIND_OBJ_NR]; + rt_list_t *next = (rt_list_t*)RT_NULL; + int maxlen; - struct rt_semaphore *sem; - struct rt_list_node *node; const char *item_title = "semaphore"; - maxlen = object_name_maxlen(item_title, list); + list_find_init(&find_arg, RT_Object_Class_Semaphore, obj_list, sizeof(obj_list)/sizeof(obj_list[0])); + + maxlen = RT_NAME_MAX; rt_kprintf("%-*.s v suspend thread\n", maxlen, item_title); object_split(maxlen); rt_kprintf( " --- --------------\n"); - for (node = list->next; node != list; node = node->next) + + do { - sem = (struct rt_semaphore *)(rt_list_entry(node, struct rt_object, list)); - if (!rt_list_isempty(&sem->parent.suspend_thread)) - { - rt_kprintf("%-*.*s %03d %d:", - maxlen, RT_NAME_MAX, - sem->parent.parent.name, - sem->value, - rt_list_len(&sem->parent.suspend_thread)); - show_wait_queue(&(sem->parent.suspend_thread)); - rt_kprintf("\n"); - } - else + next = list_get_next(next, &find_arg); { - rt_kprintf("%-*.*s %03d %d\n", - maxlen, RT_NAME_MAX, - sem->parent.parent.name, - sem->value, - rt_list_len(&sem->parent.suspend_thread)); + int i; + for (i = 0; i < find_arg.nr_out; i++) + { + struct rt_object *obj; + struct rt_semaphore *sem; + + obj = rt_list_entry(obj_list[i], struct rt_object, list); + level = rt_hw_interrupt_disable(); + if ((obj->type & ~RT_Object_Class_Static) != find_arg.type) + { + rt_hw_interrupt_enable(level); + continue; + } + rt_hw_interrupt_enable(level); + + sem = (struct rt_semaphore*)obj; + if (!rt_list_isempty(&sem->parent.suspend_thread)) + { + rt_kprintf("%-*.*s %03d %d:", + maxlen, RT_NAME_MAX, + sem->parent.parent.name, + sem->value, + rt_list_len(&sem->parent.suspend_thread)); + show_wait_queue(&(sem->parent.suspend_thread)); + rt_kprintf("\n"); + } + else + { + rt_kprintf("%-*.*s %03d %d\n", + maxlen, RT_NAME_MAX, + sem->parent.parent.name, + sem->value, + rt_list_len(&sem->parent.suspend_thread)); + } + } } } + while (next != (rt_list_t*)RT_NULL); return 0; } - -long list_sem(void) -{ - struct rt_object_information *info; - - info = rt_object_get_information(RT_Object_Class_Semaphore); - - return _list_sem(&info->object_list); -} -FINSH_FUNCTION_EXPORT(list_sem, list semaphone in system); +FINSH_FUNCTION_EXPORT(list_sem, list semaphore in system); MSH_CMD_EXPORT(list_sem, list semaphore in system); #endif #ifdef RT_USING_EVENT -static long _list_event(struct rt_list_node *list) +long list_event(void) { + rt_ubase_t level; + list_get_next_t find_arg; + rt_list_t *obj_list[LIST_FIND_OBJ_NR]; + rt_list_t *next = (rt_list_t*)RT_NULL; + int maxlen; - struct rt_event *e; - struct rt_list_node *node; const char *item_title = "event"; - maxlen = object_name_maxlen(item_title, list); + list_find_init(&find_arg, RT_Object_Class_Event, obj_list, sizeof(obj_list)/sizeof(obj_list[0])); + + maxlen = RT_NAME_MAX; rt_kprintf("%-*.s set suspend thread\n", maxlen, item_title); object_split(maxlen); rt_kprintf( " ---------- --------------\n"); - for (node = list->next; node != list; node = node->next) + + do { - e = (struct rt_event *)(rt_list_entry(node, struct rt_object, list)); - if (!rt_list_isempty(&e->parent.suspend_thread)) - { - rt_kprintf("%-*.*s 0x%08x %03d:", - maxlen, RT_NAME_MAX, - e->parent.parent.name, - e->set, - rt_list_len(&e->parent.suspend_thread)); - show_wait_queue(&(e->parent.suspend_thread)); - rt_kprintf("\n"); - } - else + next = list_get_next(next, &find_arg); { - rt_kprintf("%-*.*s 0x%08x 0\n", - maxlen, RT_NAME_MAX, e->parent.parent.name, e->set); + int i; + for (i = 0; i < find_arg.nr_out; i++) + { + struct rt_object *obj; + struct rt_event *e; + + obj = rt_list_entry(obj_list[i], struct rt_object, list); + level = rt_hw_interrupt_disable(); + if ((obj->type & ~RT_Object_Class_Static) != find_arg.type) + { + rt_hw_interrupt_enable(level); + continue; + } + + rt_hw_interrupt_enable(level); + + e = (struct rt_event *)obj; + if (!rt_list_isempty(&e->parent.suspend_thread)) + { + rt_kprintf("%-*.*s 0x%08x %03d:", + maxlen, RT_NAME_MAX, + e->parent.parent.name, + e->set, + rt_list_len(&e->parent.suspend_thread)); + show_wait_queue(&(e->parent.suspend_thread)); + rt_kprintf("\n"); + } + else + { + rt_kprintf("%-*.*s 0x%08x 0\n", + maxlen, RT_NAME_MAX, e->parent.parent.name, e->set); + } + } } } + while (next != (rt_list_t*)RT_NULL); return 0; } - -long list_event(void) -{ - struct rt_object_information *info; - - info = rt_object_get_information(RT_Object_Class_Event); - return _list_event(&info->object_list); -} FINSH_FUNCTION_EXPORT(list_event, list event in system); MSH_CMD_EXPORT(list_event, list event in system); #endif #ifdef RT_USING_MUTEX -static long _list_mutex(struct rt_list_node *list) +long list_mutex(void) { + rt_ubase_t level; + list_get_next_t find_arg; + rt_list_t *obj_list[LIST_FIND_OBJ_NR]; + rt_list_t *next = (rt_list_t*)RT_NULL; + int maxlen; - struct rt_mutex *m; - struct rt_list_node *node; const char *item_title = "mutex"; - maxlen = object_name_maxlen(item_title, list); + list_find_init(&find_arg, RT_Object_Class_Mutex, obj_list, sizeof(obj_list)/sizeof(obj_list[0])); + + maxlen = RT_NAME_MAX; rt_kprintf("%-*.s owner hold suspend thread\n", maxlen, item_title); object_split(maxlen); rt_kprintf( " -------- ---- --------------\n"); - for (node = list->next; node != list; node = node->next) + + do { - m = (struct rt_mutex *)(rt_list_entry(node, struct rt_object, list)); - rt_kprintf("%-*.*s %-8.*s %04d %d\n", - maxlen, RT_NAME_MAX, - m->parent.parent.name, - RT_NAME_MAX, - m->owner->name, - m->hold, - rt_list_len(&m->parent.suspend_thread)); - } + next = list_get_next(next, &find_arg); + { + int i; + for (i = 0; i < find_arg.nr_out; i++) + { + struct rt_object *obj; + struct rt_mutex *m; - return 0; -} + obj = rt_list_entry(obj_list[i], struct rt_object, list); + level = rt_hw_interrupt_disable(); + if ((obj->type & ~RT_Object_Class_Static) != find_arg.type) + { + rt_hw_interrupt_enable(level); + continue; + } -long list_mutex(void) -{ - struct rt_object_information *info; + rt_hw_interrupt_enable(level); - info = rt_object_get_information(RT_Object_Class_Mutex); + m = (struct rt_mutex *)obj; + rt_kprintf("%-*.*s %-8.*s %04d %d\n", + maxlen, RT_NAME_MAX, + m->parent.parent.name, + RT_NAME_MAX, + m->owner->name, + m->hold, + rt_list_len(&m->parent.suspend_thread)); + + } + } + } + while (next != (rt_list_t*)RT_NULL); - return _list_mutex(&info->object_list); + return 0; } FINSH_FUNCTION_EXPORT(list_mutex, list mutex in system); MSH_CMD_EXPORT(list_mutex, list mutex in system); #endif #ifdef RT_USING_MAILBOX -static long _list_mailbox(struct rt_list_node *list) +long list_mailbox(void) { + rt_ubase_t level; + list_get_next_t find_arg; + rt_list_t *obj_list[LIST_FIND_OBJ_NR]; + rt_list_t *next = (rt_list_t*)RT_NULL; + int maxlen; - struct rt_mailbox *m; - struct rt_list_node *node; const char *item_title = "mailbox"; - maxlen = object_name_maxlen(item_title, list); + list_find_init(&find_arg, RT_Object_Class_MailBox, obj_list, sizeof(obj_list)/sizeof(obj_list[0])); + + maxlen = RT_NAME_MAX; rt_kprintf("%-*.s entry size suspend thread\n", maxlen, item_title); object_split(maxlen); rt_kprintf( " ---- ---- --------------\n"); - for (node = list->next; node != list; node = node->next) + + do { - m = (struct rt_mailbox *)(rt_list_entry(node, struct rt_object, list)); - if (!rt_list_isempty(&m->parent.suspend_thread)) - { - rt_kprintf("%-*.*s %04d %04d %d:", - maxlen, RT_NAME_MAX, - m->parent.parent.name, - m->entry, - m->size, - rt_list_len(&m->parent.suspend_thread)); - show_wait_queue(&(m->parent.suspend_thread)); - rt_kprintf("\n"); - } - else + next = list_get_next(next, &find_arg); { - rt_kprintf("%-*.*s %04d %04d %d\n", - maxlen, RT_NAME_MAX, - m->parent.parent.name, - m->entry, - m->size, - rt_list_len(&m->parent.suspend_thread)); + int i; + for (i = 0; i < find_arg.nr_out; i++) + { + struct rt_object *obj; + struct rt_mailbox *m; + + obj = rt_list_entry(obj_list[i], struct rt_object, list); + level = rt_hw_interrupt_disable(); + if ((obj->type & ~RT_Object_Class_Static) != find_arg.type) + { + rt_hw_interrupt_enable(level); + continue; + } + + rt_hw_interrupt_enable(level); + + m = (struct rt_mailbox *)obj; + if (!rt_list_isempty(&m->parent.suspend_thread)) + { + rt_kprintf("%-*.*s %04d %04d %d:", + maxlen, RT_NAME_MAX, + m->parent.parent.name, + m->entry, + m->size, + rt_list_len(&m->parent.suspend_thread)); + show_wait_queue(&(m->parent.suspend_thread)); + rt_kprintf("\n"); + } + else + { + rt_kprintf("%-*.*s %04d %04d %d\n", + maxlen, RT_NAME_MAX, + m->parent.parent.name, + m->entry, + m->size, + rt_list_len(&m->parent.suspend_thread)); + } + + } } } + while (next != (rt_list_t*)RT_NULL); return 0; } - -long list_mailbox(void) -{ - struct rt_object_information *info; - - info = rt_object_get_information(RT_Object_Class_MailBox); - return _list_mailbox(&info->object_list); -} FINSH_FUNCTION_EXPORT(list_mailbox, list mail box in system); MSH_CMD_EXPORT(list_mailbox, list mail box in system); #endif #ifdef RT_USING_MESSAGEQUEUE -static long _list_msgqueue(struct rt_list_node *list) +long list_msgqueue(void) { + rt_ubase_t level; + list_get_next_t find_arg; + rt_list_t *obj_list[LIST_FIND_OBJ_NR]; + rt_list_t *next = (rt_list_t*)RT_NULL; + int maxlen; - struct rt_messagequeue *m; - struct rt_list_node *node; const char *item_title = "msgqueue"; - maxlen = object_name_maxlen(item_title, list); + list_find_init(&find_arg, RT_Object_Class_MessageQueue, obj_list, sizeof(obj_list)/sizeof(obj_list[0])); + + maxlen = RT_NAME_MAX; rt_kprintf("%-*.s entry suspend thread\n", maxlen, item_title); object_split(maxlen); rt_kprintf( " ---- --------------\n"); - for (node = list->next; node != list; node = node->next) + do { - m = (struct rt_messagequeue *)(rt_list_entry(node, struct rt_object, list)); - if (!rt_list_isempty(&m->parent.suspend_thread)) - { - rt_kprintf("%-*.*s %04d %d:", - maxlen, RT_NAME_MAX, - m->parent.parent.name, - m->entry, - rt_list_len(&m->parent.suspend_thread)); - show_wait_queue(&(m->parent.suspend_thread)); - rt_kprintf("\n"); - } - else + next = list_get_next(next, &find_arg); { - rt_kprintf("%-*.*s %04d %d\n", - maxlen, RT_NAME_MAX, - m->parent.parent.name, - m->entry, - rt_list_len(&m->parent.suspend_thread)); + int i; + for (i = 0; i < find_arg.nr_out; i++) + { + struct rt_object *obj; + struct rt_messagequeue *m; + + obj = rt_list_entry(obj_list[i], struct rt_object, list); + level = rt_hw_interrupt_disable(); + if ((obj->type & ~RT_Object_Class_Static) != find_arg.type) + { + rt_hw_interrupt_enable(level); + continue; + } + + rt_hw_interrupt_enable(level); + + m = (struct rt_messagequeue *)obj; + if (!rt_list_isempty(&m->parent.suspend_thread)) + { + rt_kprintf("%-*.*s %04d %d:", + maxlen, RT_NAME_MAX, + m->parent.parent.name, + m->entry, + rt_list_len(&m->parent.suspend_thread)); + show_wait_queue(&(m->parent.suspend_thread)); + rt_kprintf("\n"); + } + else + { + rt_kprintf("%-*.*s %04d %d\n", + maxlen, RT_NAME_MAX, + m->parent.parent.name, + m->entry, + rt_list_len(&m->parent.suspend_thread)); + } + } } } + while (next != (rt_list_t*)RT_NULL); return 0; } - -long list_msgqueue(void) -{ - struct rt_object_information *info; - - info = rt_object_get_information(RT_Object_Class_MessageQueue); - return _list_msgqueue(&info->object_list); -} FINSH_FUNCTION_EXPORT(list_msgqueue, list message queue in system); MSH_CMD_EXPORT(list_msgqueue, list message queue in system); #endif #ifdef RT_USING_MEMHEAP -static long _list_memheap(struct rt_list_node *list) +long list_memheap(void) { + rt_ubase_t level; + list_get_next_t find_arg; + rt_list_t *obj_list[LIST_FIND_OBJ_NR]; + rt_list_t *next = (rt_list_t*)RT_NULL; + int maxlen; - struct rt_memheap *mh; - struct rt_list_node *node; const char *item_title = "memheap"; - maxlen = object_name_maxlen(item_title, list); + list_find_init(&find_arg, RT_Object_Class_MemHeap, obj_list, sizeof(obj_list)/sizeof(obj_list[0])); + + maxlen = RT_NAME_MAX; rt_kprintf("%-*.s pool size max used size available size\n", maxlen, item_title); object_split(maxlen); rt_kprintf( " ---------- ------------- --------------\n"); - for (node = list->next; node != list; node = node->next) + do { - mh = (struct rt_memheap *)rt_list_entry(node, struct rt_object, list); - - rt_kprintf("%-*.*s %-010d %-013d %-05d\n", - maxlen, RT_NAME_MAX, - mh->parent.name, - mh->pool_size, - mh->max_used_size, - mh->available_size); - } + next = list_get_next(next, &find_arg); + { + int i; + for (i = 0; i < find_arg.nr_out; i++) + { + struct rt_object *obj; + struct rt_memheap *mh; - return 0; -} + obj = rt_list_entry(obj_list[i], struct rt_object, list); + level = rt_hw_interrupt_disable(); + if ((obj->type & ~RT_Object_Class_Static) != find_arg.type) + { + rt_hw_interrupt_enable(level); + continue; + } -long list_memheap(void) -{ - struct rt_object_information *info; + rt_hw_interrupt_enable(level); + + mh = (struct rt_memheap *)obj; + + rt_kprintf("%-*.*s %-010d %-013d %-05d\n", + maxlen, RT_NAME_MAX, + mh->parent.name, + mh->pool_size, + mh->max_used_size, + mh->available_size); + + } + } + } + while (next != (rt_list_t*)RT_NULL); - info = rt_object_get_information(RT_Object_Class_MemHeap); - return _list_memheap(&info->object_list); + return 0; } FINSH_FUNCTION_EXPORT(list_memheap, list memory heap in system); MSH_CMD_EXPORT(list_memheap, list memory heap in system); #endif #ifdef RT_USING_MEMPOOL -static long _list_mempool(struct rt_list_node *list) +long list_mempool(void) { + rt_ubase_t level; + list_get_next_t find_arg; + rt_list_t *obj_list[LIST_FIND_OBJ_NR]; + rt_list_t *next = (rt_list_t*)RT_NULL; + int maxlen; - struct rt_mempool *mp; - struct rt_list_node *node; const char *item_title = "mempool"; - maxlen = object_name_maxlen(item_title, list); + list_find_init(&find_arg, RT_Object_Class_MemPool, obj_list, sizeof(obj_list)/sizeof(obj_list[0])); + + maxlen = RT_NAME_MAX; rt_kprintf("%-*.s block total free suspend thread\n", maxlen, item_title); object_split(maxlen); rt_kprintf( " ---- ---- ---- --------------\n"); - for (node = list->next; node != list; node = node->next) + do { - mp = (struct rt_mempool *)rt_list_entry(node, struct rt_object, list); - if (mp->suspend_thread_count > 0) - { - rt_kprintf("%-*.*s %04d %04d %04d %d:", - maxlen, RT_NAME_MAX, - mp->parent.name, - mp->block_size, - mp->block_total_count, - mp->block_free_count, - mp->suspend_thread_count); - show_wait_queue(&(mp->suspend_thread)); - rt_kprintf("\n"); - } - else + next = list_get_next(next, &find_arg); { - rt_kprintf("%-*.*s %04d %04d %04d %d\n", - maxlen, RT_NAME_MAX, - mp->parent.name, - mp->block_size, - mp->block_total_count, - mp->block_free_count, - mp->suspend_thread_count); + int i; + for (i = 0; i < find_arg.nr_out; i++) + { + struct rt_object *obj; + struct rt_mempool *mp; + + obj = rt_list_entry(obj_list[i], struct rt_object, list); + level = rt_hw_interrupt_disable(); + if ((obj->type & ~RT_Object_Class_Static) != find_arg.type) + { + rt_hw_interrupt_enable(level); + continue; + } + + rt_hw_interrupt_enable(level); + + mp = (struct rt_mempool *)obj; + if (mp->suspend_thread_count > 0) + { + rt_kprintf("%-*.*s %04d %04d %04d %d:", + maxlen, RT_NAME_MAX, + mp->parent.name, + mp->block_size, + mp->block_total_count, + mp->block_free_count, + mp->suspend_thread_count); + show_wait_queue(&(mp->suspend_thread)); + rt_kprintf("\n"); + } + else + { + rt_kprintf("%-*.*s %04d %04d %04d %d\n", + maxlen, RT_NAME_MAX, + mp->parent.name, + mp->block_size, + mp->block_total_count, + mp->block_free_count, + mp->suspend_thread_count); + } + } } } + while (next != (rt_list_t*)RT_NULL); return 0; } - -long list_mempool(void) -{ - struct rt_object_information *info; - - info = rt_object_get_information(RT_Object_Class_MemPool); - return _list_mempool(&info->object_list); -} FINSH_FUNCTION_EXPORT(list_mempool, list memory pool in system) MSH_CMD_EXPORT(list_mempool, list memory pool in system); #endif -static long _list_timer(struct rt_list_node *list) +long list_timer(void) { + rt_ubase_t level; + list_get_next_t find_arg; + rt_list_t *obj_list[LIST_FIND_OBJ_NR]; + rt_list_t *next = (rt_list_t*)RT_NULL; + int maxlen; - struct rt_timer *timer; - struct rt_list_node *node; const char *item_title = "timer"; - maxlen = object_name_maxlen(item_title, list); + list_find_init(&find_arg, RT_Object_Class_Timer, obj_list, sizeof(obj_list)/sizeof(obj_list[0])); + + maxlen = RT_NAME_MAX; rt_kprintf("%-*.s periodic timeout flag\n", maxlen, item_title); object_split(maxlen); rt_kprintf( " ---------- ---------- -----------\n"); - for (node = list->next; node != list; node = node->next) - { - timer = (struct rt_timer *)(rt_list_entry(node, struct rt_object, list)); - rt_kprintf("%-*.*s 0x%08x 0x%08x ", - maxlen, RT_NAME_MAX, - timer->parent.name, - timer->init_tick, - timer->timeout_tick); - if (timer->parent.flag & RT_TIMER_FLAG_ACTIVATED) - rt_kprintf("activated\n"); - else - rt_kprintf("deactivated\n"); + do { + next = list_get_next(next, &find_arg); + { + int i; + for (i = 0; i < find_arg.nr_out; i++) + { + struct rt_object *obj; + struct rt_timer *timer; + + obj = rt_list_entry(obj_list[i], struct rt_object, list); + level = rt_hw_interrupt_disable(); + if ((obj->type & ~RT_Object_Class_Static) != find_arg.type) + { + rt_hw_interrupt_enable(level); + continue; + } + + rt_hw_interrupt_enable(level); + + timer = (struct rt_timer *)obj; + rt_kprintf("%-*.*s 0x%08x 0x%08x ", + maxlen, RT_NAME_MAX, + timer->parent.name, + timer->init_tick, + timer->timeout_tick); + if (timer->parent.flag & RT_TIMER_FLAG_ACTIVATED) + rt_kprintf("activated\n"); + else + rt_kprintf("deactivated\n"); + + } + } } + while (next != (rt_list_t*)RT_NULL); rt_kprintf("current tick:0x%08x\n", rt_tick_get()); return 0; } - -long list_timer(void) -{ - struct rt_object_information *info; - - info = rt_object_get_information(RT_Object_Class_Timer); - return _list_timer(&info->object_list); -} FINSH_FUNCTION_EXPORT(list_timer, list timer in system); MSH_CMD_EXPORT(list_timer, list timer in system); #ifdef RT_USING_DEVICE -static long _list_device(struct rt_list_node *list) +static char *const device_type_str[] = +{ + "Character Device", + "Block Device", + "Network Interface", + "MTD Device", + "CAN Device", + "RTC", + "Sound Device", + "Graphic Device", + "I2C Bus", + "USB Slave Device", + "USB Host Bus", + "SPI Bus", + "SPI Device", + "SDIO Bus", + "PM Pseudo Device", + "Pipe", + "Portal Device", + "Timer Device", + "Miscellaneous Device", + "Unknown" +}; + +long list_device(void) { + rt_ubase_t level; + list_get_next_t find_arg; + rt_list_t *obj_list[LIST_FIND_OBJ_NR]; + rt_list_t *next = (rt_list_t*)RT_NULL; + int maxlen; - struct rt_device *device; - struct rt_list_node *node; - char *const device_type_str[] = - { - "Character Device", - "Block Device", - "Network Interface", - "MTD Device", - "CAN Device", - "RTC", - "Sound Device", - "Graphic Device", - "I2C Bus", - "USB Slave Device", - "USB Host Bus", - "SPI Bus", - "SPI Device", - "SDIO Bus", - "PM Pseudo Device", - "Pipe", - "Portal Device", - "Timer Device", - "Miscellaneous Device", - "Unknown" - }; const char *item_title = "device"; - maxlen = object_name_maxlen(item_title, list); + list_find_init(&find_arg, RT_Object_Class_Device, obj_list, sizeof(obj_list)/sizeof(obj_list[0])); + + maxlen = RT_NAME_MAX; rt_kprintf("%-*.s type ref count\n", maxlen, item_title); object_split(maxlen); rt_kprintf( " -------------------- ----------\n"); - for (node = list->next; node != list; node = node->next) + do { - device = (struct rt_device *)(rt_list_entry(node, struct rt_object, list)); - rt_kprintf("%-*.*s %-20s %-8d\n", - maxlen, RT_NAME_MAX, - device->parent.name, - (device->type <= RT_Device_Class_Unknown) ? - device_type_str[device->type] : - device_type_str[RT_Device_Class_Unknown], - device->ref_count); - } + next = list_get_next(next, &find_arg); + { + int i; + for (i = 0; i < find_arg.nr_out; i++) + { + struct rt_object *obj; + struct rt_device *device; - return 0; -} + obj = rt_list_entry(obj_list[i], struct rt_object, list); + level = rt_hw_interrupt_disable(); + if ((obj->type & ~RT_Object_Class_Static) != find_arg.type) + { + rt_hw_interrupt_enable(level); + continue; + } -long list_device(void) -{ - struct rt_object_information *info; + rt_hw_interrupt_enable(level); - info = rt_object_get_information(RT_Object_Class_Device); - return _list_device(&info->object_list); + device = (struct rt_device *)obj; + rt_kprintf("%-*.*s %-20s %-8d\n", + maxlen, RT_NAME_MAX, + device->parent.name, + (device->type <= RT_Device_Class_Unknown) ? + device_type_str[device->type] : + device_type_str[RT_Device_Class_Unknown], + device->ref_count); + + } + } + } + while (next != (rt_list_t*)RT_NULL); + + return 0; } FINSH_FUNCTION_EXPORT(list_device, list device in system); MSH_CMD_EXPORT(list_device, list device in system); diff --git a/include/rtdef.h b/include/rtdef.h index 49551de9ee..ecdabd4490 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -367,7 +367,8 @@ typedef struct rt_object *rt_object_t; /**< Type for kernel obj */ enum rt_object_class_type { - RT_Object_Class_Thread = 0, /**< The object is a thread. */ + RT_Object_Class_Null = 0, /**< The object is not used. */ + RT_Object_Class_Thread, /**< The object is a thread. */ RT_Object_Class_Semaphore, /**< The object is a semaphore. */ RT_Object_Class_Mutex, /**< The object is a mutex. */ RT_Object_Class_Event, /**< The object is a event. */ -- cgit v1.3.1 From d68c0f225dc50bcc0d4d1935f6609c3e2c874cae Mon Sep 17 00:00:00 2001 From: Bernard Xiong Date: Sun, 27 Jan 2019 21:58:07 +0800 Subject: Update rtdef.h Update version number to v4.0.1 --- include/rtdef.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'include/rtdef.h') diff --git a/include/rtdef.h b/include/rtdef.h index 39deb47d9f..859278e849 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -29,6 +29,7 @@ * 2018-11-22 Jesven add smp member to struct rt_thread * add struct rt_cpu * add smp relevant macros + * 2019-01-27 Bernard change version number to v4.0.1 */ #ifndef __RT_DEF_H__ @@ -50,7 +51,7 @@ extern "C" { /* RT-Thread version information */ #define RT_VERSION 4L /**< major version number */ #define RT_SUBVERSION 0L /**< minor version number */ -#define RT_REVISION 0L /**< revise version number */ +#define RT_REVISION 1L /**< revise version number */ /* RT-Thread version */ #define RTTHREAD_VERSION ((RT_VERSION * 10000) + \ -- cgit v1.3.1 From 64813b6b07f32bbee1a5f0743c5ea08458294d13 Mon Sep 17 00:00:00 2001 From: guozhanxin Date: Tue, 12 Feb 2019 10:15:26 +0800 Subject: add first version --- components/drivers/Kconfig | 11 + components/drivers/sensors/SConscript | 9 +- components/drivers/sensors/bmi055_sensor.cpp | 451 --------- components/drivers/sensors/bmi055_sensor.h | 334 ------- components/drivers/sensors/mpu6050_sensor.cpp | 458 --------- components/drivers/sensors/mpu6050_sensor.h | 189 ---- components/drivers/sensors/sensor.c | 449 +++++++++ components/drivers/sensors/sensor.cpp | 228 ----- components/drivers/sensors/sensor.h | 1243 +++---------------------- components/drivers/sensors/sensor_test.c | 361 +++++++ components/finsh/cmd.c | 1 + include/rtdef.h | 1 + 12 files changed, 979 insertions(+), 2756 deletions(-) delete mode 100644 components/drivers/sensors/bmi055_sensor.cpp delete mode 100644 components/drivers/sensors/bmi055_sensor.h delete mode 100644 components/drivers/sensors/mpu6050_sensor.cpp delete mode 100644 components/drivers/sensors/mpu6050_sensor.h create mode 100644 components/drivers/sensors/sensor.c delete mode 100644 components/drivers/sensors/sensor.cpp create mode 100644 components/drivers/sensors/sensor_test.c (limited to 'include/rtdef.h') diff --git a/components/drivers/Kconfig b/components/drivers/Kconfig index 8f66738260..6246a97160 100755 --- a/components/drivers/Kconfig +++ b/components/drivers/Kconfig @@ -239,6 +239,17 @@ config RT_USING_AUDIO bool "Using Audio device drivers" default n +config RT_USING_SENSOR + bool "Using Sensor device drivers" + select RT_USING_PIN + default n + +if RT_USING_SENSOR + config RT_USING_SENSOR_TEST + bool "Use Sensor test" + default y +endif + menu "Using WiFi" config RT_USING_WIFI bool "Using Wi-Fi framework" diff --git a/components/drivers/sensors/SConscript b/components/drivers/sensors/SConscript index db409cfd2b..e727b14136 100644 --- a/components/drivers/sensors/SConscript +++ b/components/drivers/sensors/SConscript @@ -3,14 +3,11 @@ from building import * cwd = GetCurrentDir() -src = ['sensor.cpp'] +src = ['sensor.c'] CPPPATH = [cwd, cwd + '/../include'] -if GetDepend('SENSOR_USING_MPU6050') and GetDepend('RT_USING_I2C'): - src += ['mpu6050_sensor.cpp']; - -if GetDepend('SENSOR_USING_BMI055') and GetDepend('RT_USING_I2C'): - src += ['bmi055_sensor.cpp'] +if GetDepend('RT_USING_SENSOR_TEST'): + src += ['sensor_test.c']; group = DefineGroup('Sensors', src, depend = ['RT_USING_SENSOR', 'RT_USING_DEVICE'], CPPPATH = CPPPATH) diff --git a/components/drivers/sensors/bmi055_sensor.cpp b/components/drivers/sensors/bmi055_sensor.cpp deleted file mode 100644 index b6e7f99da5..0000000000 --- a/components/drivers/sensors/bmi055_sensor.cpp +++ /dev/null @@ -1,451 +0,0 @@ -/* - * Copyright (c) 2006-2018, RT-Thread Development Team - * - * SPDX-License-Identifier: Apache-2.0 - * - * Change Logs: - * Date Author Notes - * 2015-1-11 RT_learning the first version - */ - -#include -#include -#include -#include "bmi055_sensor.h" - - -const static sensor_t _BMI055_sensor[] = -{ - { - .name = "Accelerometer", - .vendor = "Bosch", - .version = sizeof(sensor_t), - .handle = 0, - .type = SENSOR_TYPE_ACCELEROMETER, - .maxRange = SENSOR_ACCEL_RANGE_16G, - .resolution = 1.0f, - .power = 0.5f, - .minDelay = 10000, - .fifoReservedEventCount = 0, - .fifoMaxEventCount = 64, - }, - { - .name = "Gyroscope", - .vendor = "Bosch", - .version = sizeof(sensor_t), - .handle = 0, - .type = SENSOR_TYPE_GYROSCOPE, - .maxRange = SENSOR_GYRO_RANGE_2000DPS, - .resolution = 1.0f, - .power = 0.5f, - .minDelay = 10000, - .fifoReservedEventCount = 0, - .fifoMaxEventCount = 64, - } -}; - -BMI055::BMI055(int sensor_type, const char* iic_bus, int addr) - : SensorBase(sensor_type) -{ - this->i2c_bus = (struct rt_i2c_bus_device *)rt_device_find(iic_bus); - if (this->i2c_bus == NULL) - { - printf("BMI055: No IIC device:%s\n", iic_bus); - return; - } - - this->i2c_addr = addr; - - /* register to sensor manager */ - SensorManager::registerSensor(this); -} - -int BMI055::read_reg(rt_uint8_t reg, rt_uint8_t *value) -{ - struct rt_i2c_msg msgs[2]; - - msgs[0].addr = this->i2c_addr; - msgs[0].flags = RT_I2C_WR; - msgs[0].buf = ® - msgs[0].len = 1; - - msgs[1].addr = this->i2c_addr; - msgs[1].flags = RT_I2C_RD; /* Read from slave */ - msgs[1].buf = (rt_uint8_t *)value; - msgs[1].len = 1; - - if (rt_i2c_transfer(this->i2c_bus, msgs, 2) == 2) - return RT_EOK; - - return -RT_ERROR; -} - -int BMI055::read_buffer(rt_uint8_t reg, rt_uint8_t* value, rt_size_t size) -{ - struct rt_i2c_msg msgs[2]; - - msgs[0].addr = this->i2c_addr; - msgs[0].flags = RT_I2C_WR; - msgs[0].buf = ® - msgs[0].len = 1; - - msgs[1].addr = this->i2c_addr; - msgs[1].flags = RT_I2C_RD; /* Read from slave */ - msgs[1].buf = (rt_uint8_t *)value; - msgs[1].len = size; - - if (rt_i2c_transfer(this->i2c_bus, msgs, 2) == 2) - return RT_EOK; - - return -RT_ERROR; -} - -int BMI055::write_reg(rt_uint8_t reg, rt_uint8_t value) -{ - struct rt_i2c_msg msgs[2]; - - msgs[0].addr = this->i2c_addr; - msgs[0].flags = RT_I2C_WR; - msgs[0].buf = ® - msgs[0].len = 1; - - msgs[1].addr = this->i2c_addr; - msgs[1].flags = RT_I2C_WR | RT_I2C_NO_START; - msgs[1].buf = (rt_uint8_t *)&value; - msgs[1].len = 1; - - if (rt_i2c_transfer(this->i2c_bus, msgs, 2) == 2) - return RT_EOK; - - return -RT_ERROR; -} - - -BMI055_Accelerometer::BMI055_Accelerometer(const char* iic_name, int addr) - : BMI055(SENSOR_TYPE_ACCELEROMETER, iic_name, addr) -{ - int index; - uint8_t id; - rt_uint8_t value[6] = {0}; - rt_int32_t x, y, z; - SensorConfig config = {SENSOR_MODE_NORMAL, SENSOR_DATARATE_400HZ, SENSOR_ACCEL_RANGE_2G}; - - write_reg(BMI055_BGW_SOFTRESET, 0xB6); /* reset of the sensor P57 */ - write_reg(BMI055_PMU_LPW, 0x00); /* PMU_LPW NORMAL mode P55 */ - write_reg(BMI055_PMU_BW, 0x0A); /* 01010b 31.25 Hz P55 */ - write_reg(BMI055_PMU_RANGE, 0x05); /* 0101b 卤4g range PMU_RANGE set acc +-4g/s P54 */ - - - x_offset = y_offset = z_offset = 0; - x = y = z = 0; - - /* read BMI055 id */ - read_buffer(BMI055_ACC_BGW_CHIPID, &id, 1); /* BGW_CHIPID P47*/ - if (id != BMI055_ACC_BGW_CHIPID_VALUE) - { - printf("Warning: not found BMI055 id: %02x\n", id); - } - - /* get offset */ - for (index = 0; index < 200; index ++) - { - read_buffer(BMI055_ACCD_X_LSB, value, 6); /*ACCD_X_LSB P47 */ - - x += (((rt_int16_t)value[1] << 8) | value[0]); - y += (((rt_int16_t)value[3] << 8) | value[2]); - z += (((rt_int16_t)value[5] << 8) | value[4]); - } - x_offset = x / 200; - y_offset = y / 200; - z_offset = z / 200; - - this->enable = RT_FALSE; - this->sensitivity = SENSOR_ACCEL_SENSITIVITY_2G; - this->config = config; -} - -int -BMI055_Accelerometer::configure(SensorConfig *config) -{ - int range; - uint8_t value; - - if (config == RT_NULL) return -1; - - /* TODO: set datarate */ - - /* get range and calc the sensitivity */ - range = config->range.accel_range; - switch (range) - { - case SENSOR_ACCEL_RANGE_2G: - this->sensitivity = SENSOR_ACCEL_SENSITIVITY_2G; - range = 0x03; //0011b - break; - case SENSOR_ACCEL_RANGE_4G: - this->sensitivity = SENSOR_ACCEL_SENSITIVITY_4G; - range = 0x05; //0101b - break; - case SENSOR_ACCEL_RANGE_8G: - this->sensitivity = SENSOR_ACCEL_SENSITIVITY_8G; - range = 0x01 << 3; //1000b - break; - case SENSOR_ACCEL_RANGE_16G: - this->sensitivity = SENSOR_ACCEL_SENSITIVITY_16G; - range = 0x03 << 2; //1100b - break; - default: - return -1; - } - - /* set range to sensor */ - read_reg(BMI055_PMU_RANGE, &value); /* PMU_RANGE P54 */ - value &= 0xF0; - value |= range; - write_reg(BMI055_PMU_RANGE, value); - - return 0; -} - -int -BMI055_Accelerometer::activate(int enable) -{ - uint8_t value; - - if (enable && this->enable == RT_FALSE) - { - /* enable accelerometer */ - read_reg(BMI055_PMU_LPW, &value); /* P55 */ - value &= ~(0x07 << 7); - write_reg(BMI055_PMU_LPW, value); - } - - if (!enable && this->enable == RT_TRUE) - { - /* disable accelerometer */ - read_reg(BMI055_PMU_LPW, &value); - value &= ~(0x07 << 7); - value |= (0x01 << 7); - write_reg(BMI055_PMU_LPW, value); - } - - if (enable) this->enable = RT_TRUE; - else this->enable = RT_FALSE; - - return 0; -} - -int -BMI055_Accelerometer::poll(sensors_event_t *event) -{ - rt_uint8_t value[6]; - rt_int16_t x, y, z; - - /* parameters check */ - if (event == NULL) return -1; - - /* get event data */ - event->version = sizeof(sensors_event_t); - event->sensor = (int32_t) this; - event->timestamp = rt_tick_get(); - event->type = SENSOR_TYPE_ACCELEROMETER; - - read_buffer(0x02, value, 6); - - /* get raw data */ - x = (((rt_int16_t)value[1] << 8) | value[0]); - y = (((rt_int16_t)value[3] << 8) | value[2]); - z = (((rt_int16_t)value[5] << 8) | value[4]); - - if (config.mode == SENSOR_MODE_RAW) - { - event->raw_acceleration.x = x; - event->raw_acceleration.y = y; - event->raw_acceleration.z = z; - } - else - { - - x -= x_offset; y -= y_offset; z -= z_offset; - event->acceleration.x = x * this->sensitivity * SENSORS_GRAVITY_STANDARD; - event->acceleration.y = y * this->sensitivity * SENSORS_GRAVITY_STANDARD; - event->acceleration.z = z * this->sensitivity * SENSORS_GRAVITY_STANDARD; - } - - return 0; -} - -void -BMI055_Accelerometer::getSensor(sensor_t *sensor) -{ - /* get sensor description */ - if (sensor) - { - memcpy(sensor, &_BMI055_sensor[0], sizeof(sensor_t)); - } -} - -BMI055_Gyroscope::BMI055_Gyroscope(const char* iic_name, int addr) - : BMI055(SENSOR_TYPE_GYROSCOPE, iic_name, addr) -{ - int index; - uint8_t id; - rt_uint8_t value[6]; - rt_int32_t x, y, z; - - /* initialize BMI055 */ - write_reg(BMI055_MODE_LPM1_ADDR, 0x00); /* normal mode */ - write_reg(BMI055_MODE_LPM2_ADDR, 0x80); /* fast powerup */ - write_reg(BMI055_BW_ADDR, 0x03); /* ODR:400Hz Filter Bandwidth:47Hz */ - write_reg(BMI055_RANGE_ADDR, 0x00); /* 2000dps */ - - - x_offset = y_offset = z_offset = 0; - x = y = z = 0; - - /* read BMI055 id */ - read_buffer(BMI055_CHIP_ID_ADDR, &id, 1); - if (id != BMI055_GRRO_CHIP_ID) - { - printf("Warning: not found BMI055 id: %02x\n", id); - } - - /* get offset */ - for (index = 0; index < 200; index ++) - { - read_buffer(BMI055_RATE_X_LSB_ADDR, value, 6); - - x += (((rt_int16_t)value[1] << 8) | value[0]); - y += (((rt_int16_t)value[3] << 8) | value[2]); - z += (((rt_int16_t)value[5] << 8) | value[4]); - } - x_offset = x / 200; - y_offset = y / 200; - z_offset = z / 200; - - this->enable = RT_FALSE; - this->sensitivity = SENSOR_GYRO_SENSITIVITY_250DPS; -} - -int -BMI055_Gyroscope::configure(SensorConfig *config) -{ - int range; - uint8_t value; - - if (config == RT_NULL) return -1; - - /* TODO: set datarate */ - - /* get range and calc the sensitivity */ - range = config->range.gyro_range; - switch (range) - { - //to do add more range e.g 125DPS - //case - case SENSOR_GYRO_RANGE_250DPS: - this->sensitivity = SENSOR_GYRO_SENSITIVITY_250DPS; - range = 0x11; - break; - case SENSOR_GYRO_RANGE_500DPS: - this->sensitivity = SENSOR_GYRO_SENSITIVITY_500DPS; - range = 0x10; - break; - case SENSOR_GYRO_RANGE_1000DPS: - this->sensitivity = SENSOR_GYRO_SENSITIVITY_1000DPS; - range = 0x01; - break; - case SENSOR_GYRO_RANGE_2000DPS: - this->sensitivity = SENSOR_GYRO_SENSITIVITY_2000DPS; - range = 0x00; - break; - default: - return -1; - } - - /* set range to sensor */ - read_reg(BMI055_RANGE_ADDR, &value); - value &= ~0x07; - value |= range; - write_reg(BMI055_RANGE_ADDR, value); - - return 0; -} - -int -BMI055_Gyroscope::activate(int enable) -{ - uint8_t value; - - if (enable && this->enable == RT_FALSE) - { - /* enable gyroscope */ - read_reg(BMI055_MODE_LPM1_ADDR, &value); - value &= ~(0x1010 << 4); //{0; 0} NORMAL mode - write_reg(BMI055_MODE_LPM1_ADDR, value); //P101 NORMAL mode - } - - if (!enable && this->enable == RT_TRUE) - { - /* disable gyroscope */ - read_reg(BMI055_MODE_LPM1_ADDR, &value); - value &= ~(0x01 << 5); //set bit5 deep_suspend 0 - value |= (0x01 << 7); //set bit1 suspend 1 - write_reg(BMI055_MODE_LPM1_ADDR, value); //{1; 0} SUSPEND mode - } - - if (enable) this->enable = RT_TRUE; - else this->enable = RT_FALSE; - - return 0; -} - -int -BMI055_Gyroscope::poll(sensors_event_t *event) -{ - rt_uint8_t value[6]; - rt_int16_t x, y, z; - - /* parameters check */ - if (event == NULL) return -1; - - /* get event data */ - event->version = sizeof(sensors_event_t); - event->sensor = (int32_t) this; - event->timestamp = rt_tick_get(); - event->type = SENSOR_TYPE_GYROSCOPE; - - read_buffer(BMI055_RATE_X_LSB_ADDR, value, 6); - - /* get raw data */ - x = (((rt_int16_t)value[1] << 8) | value[0]); - y = (((rt_int16_t)value[3] << 8) | value[2]); - z = (((rt_int16_t)value[5] << 8) | value[4]); - - - if (config.mode == SENSOR_MODE_RAW) - { - event->raw_gyro.x = x; - event->raw_gyro.y = y; - event->raw_gyro.z = z; - } - else - { - x -= x_offset; y -= y_offset; z -= z_offset; - event->gyro.x = x * this->sensitivity * SENSORS_DPS_TO_RADS; - event->gyro.y = y * this->sensitivity * SENSORS_DPS_TO_RADS; - event->gyro.z = z * this->sensitivity * SENSORS_DPS_TO_RADS; - } - - return 0; -} - -void -BMI055_Gyroscope::getSensor(sensor_t *sensor) -{ - /* get sensor description */ - if (sensor) - { - memcpy(sensor, &_BMI055_sensor[1], sizeof(sensor_t)); - } -} diff --git a/components/drivers/sensors/bmi055_sensor.h b/components/drivers/sensors/bmi055_sensor.h deleted file mode 100644 index 713aa74ad0..0000000000 --- a/components/drivers/sensors/bmi055_sensor.h +++ /dev/null @@ -1,334 +0,0 @@ -/* - * Copyright (c) 2006-2018, RT-Thread Development Team - * - * SPDX-License-Identifier: Apache-2.0 - * - * Change Logs: - * Date Author Notes - * 2015-1-11 RT_learning the first version - */ -#ifndef __BMI055_H__ -#define __BMI055_H__ - -#include - -/**************************************************************************************************/ -/************************************Register map accelerometer************************************/ - -#define BMI055_ACC_I2C_ADDR1 0x18 //SDO is low(GND) -#define BMI055_ACC_I2C_ADDR2 0x19 //SDO is high(VCC) - -#define BMI055_ACC_DEFAULT_ADDRESS BMI055_ACC_I2C_ADDR2 //in the LPC54102 SPM-S - -#define BMI055_ACC_BGW_CHIPID_VALUE 0xFA - -#define BMI055_ACC_BGW_CHIPID 0x00 -/**
-#include -#include - -#include "mpu6050_sensor.h" - - -const static sensor_t _MPU6050_sensor[] = -{ - { - .name = "Accelerometer", - .vendor = "Invensense", - .version = sizeof(sensor_t), - .handle = 0, - .type = SENSOR_TYPE_ACCELEROMETER, - .maxRange = SENSOR_ACCEL_RANGE_16G, - .resolution = 1.0f, - .power = 0.5f, - .minDelay = 10000, - .fifoReservedEventCount = 0, - .fifoMaxEventCount = 64, - }, - { - .name = "Gyroscope", - .vendor = "Invensense", - .version = sizeof(sensor_t), - .handle = 0, - .type = SENSOR_TYPE_GYROSCOPE, - .maxRange = SENSOR_GYRO_RANGE_2000DPS, - .resolution = 1.0f, - .power = 0.5f, - .minDelay = 10000, - .fifoReservedEventCount = 0, - .fifoMaxEventCount = 64, - } -}; - -MPU6050::MPU6050(int sensor_type, const char* iic_bus, int addr) - : SensorBase(sensor_type) -{ - this->i2c_bus = (struct rt_i2c_bus_device *)rt_device_find(iic_bus); - if (this->i2c_bus == NULL) - { - printf("MPU6050: No IIC device:%s\n", iic_bus); - return; - } - - this->i2c_addr = addr; - - /* register to sensor manager */ - SensorManager::registerSensor(this); -} - -int MPU6050::read_reg(rt_uint8_t reg, rt_uint8_t *value) -{ - struct rt_i2c_msg msgs[2]; - - msgs[0].addr = this->i2c_addr; - msgs[0].flags = RT_I2C_WR; - msgs[0].buf = ® - msgs[0].len = 1; - - msgs[1].addr = this->i2c_addr; - msgs[1].flags = RT_I2C_RD; /* Read from slave */ - msgs[1].buf = (rt_uint8_t *)value; - msgs[1].len = 1; - - if (rt_i2c_transfer(this->i2c_bus, msgs, 2) == 2) - return RT_EOK; - - return -RT_ERROR; -} - -int MPU6050::read_buffer(rt_uint8_t reg, rt_uint8_t* value, rt_size_t size) -{ - struct rt_i2c_msg msgs[2]; - - msgs[0].addr = this->i2c_addr; - msgs[0].flags = RT_I2C_WR; - msgs[0].buf = ® - msgs[0].len = 1; - - msgs[1].addr = this->i2c_addr; - msgs[1].flags = RT_I2C_RD; /* Read from slave */ - msgs[1].buf = (rt_uint8_t *)value; - msgs[1].len = size; - - if (rt_i2c_transfer(this->i2c_bus, msgs, 2) == 2) - return RT_EOK; - - return -RT_ERROR; -} - -int MPU6050::write_reg(rt_uint8_t reg, rt_uint8_t value) -{ - struct rt_i2c_msg msgs[2]; - - msgs[0].addr = this->i2c_addr; - msgs[0].flags = RT_I2C_WR; - msgs[0].buf = ® - msgs[0].len = 1; - - msgs[1].addr = this->i2c_addr; - msgs[1].flags = RT_I2C_WR | RT_I2C_NO_START; - msgs[1].buf = (rt_uint8_t *)&value; - msgs[1].len = 1; - - if (rt_i2c_transfer(this->i2c_bus, msgs, 2) == 2) - return RT_EOK; - - return -RT_ERROR; -} - - -MPU6050_Accelerometer::MPU6050_Accelerometer(const char* iic_name, int addr) - : MPU6050(SENSOR_TYPE_ACCELEROMETER, iic_name, addr) -{ - int index; - uint8_t id; - rt_uint8_t value[6] = {0}; - rt_int32_t x, y, z; - SensorConfig config = {SENSOR_MODE_NORMAL, SENSOR_DATARATE_400HZ, SENSOR_ACCEL_RANGE_2G}; - - /* initialize MPU6050 */ - write_reg(MPU6050_PWR_MGMT_1, 0x80); /* reset mpu6050 device */ - write_reg(MPU6050_SMPLRT_DIV, 0x00); /* Sample Rate = Gyroscope Output Rate / (1 + SMPLRT_DIV) */ - write_reg(MPU6050_PWR_MGMT_1, 0x03); /* Wake up device , set device clock Z axis gyroscope */ - write_reg(MPU6050_CONFIG, 0x03); /* set DLPF_CFG 42Hz */ - write_reg(MPU6050_GYRO_CONFIG, 0x18); /* set gyro 2000deg/s */ - write_reg(MPU6050_ACCEL_CONFIG, 0x08); /* set acc +-4g/s */ - - - x_offset = y_offset = z_offset = 0; - x = y = z = 0; - - /* read MPU6050 id */ - read_buffer(MPU6050_WHOAMI, &id, 1); - if (id != MPU6050_ID) - { - printf("Warning: not found MPU6050 id: %02x\n", id); - } - - /* get offset */ - for (index = 0; index < 200; index ++) - { - read_buffer(MPU6050_ACCEL_XOUT_H, value, 6); - - x += (((rt_int16_t)value[0] << 8) | value[1]); - y += (((rt_int16_t)value[2] << 8) | value[3]); - z += (((rt_int16_t)value[4] << 8) | value[5]); - } - x_offset = x / 200; - y_offset = y / 200; - z_offset = z / 200; - - this->enable = RT_FALSE; - this->sensitivity = SENSOR_ACCEL_SENSITIVITY_2G; - this->config = config; -} - -int -MPU6050_Accelerometer::configure(SensorConfig *config) -{ - int range; - uint8_t value; - - if (config == RT_NULL) return -1; - - /* TODO: set datarate */ - - /* get range and calc the sensitivity */ - range = config->range.accel_range; - switch (range) - { - case SENSOR_ACCEL_RANGE_2G: - this->sensitivity = SENSOR_ACCEL_SENSITIVITY_2G; - range = 0; - break; - case SENSOR_ACCEL_RANGE_4G: - this->sensitivity = SENSOR_ACCEL_SENSITIVITY_4G; - range = 0x01 << 2; - break; - case SENSOR_ACCEL_RANGE_8G: - this->sensitivity = SENSOR_ACCEL_SENSITIVITY_8G; - range = 0x02 << 2; - break; - case SENSOR_ACCEL_RANGE_16G: - this->sensitivity = SENSOR_ACCEL_SENSITIVITY_16G; - range = 0x03 << 2; - break; - default: - return -1; - } - - /* set range to sensor */ - read_reg(MPU6050_ACCEL_CONFIG, &value); - value &= ~(0x3 << 2); - value |= range; - write_reg(MPU6050_ACCEL_CONFIG, value); - - return 0; -} - -int -MPU6050_Accelerometer::activate(int enable) -{ - uint8_t value; - - if (enable && this->enable == RT_FALSE) - { - /* enable accelerometer */ - read_reg(MPU6050_PWR_MGMT_2, &value); - value &= ~(0x07 << 2); - write_reg(MPU6050_PWR_MGMT_2, value); - } - - if (!enable && this->enable == RT_TRUE) - { - /* disable accelerometer */ - read_reg(MPU6050_PWR_MGMT_2, &value); - value |= (0x07 << 2); - write_reg(MPU6050_PWR_MGMT_2, value); - } - - if (enable) this->enable = RT_TRUE; - else this->enable = RT_FALSE; - - return 0; -} - -int -MPU6050_Accelerometer::poll(sensors_event_t *event) -{ - rt_uint8_t value[6]; - rt_int16_t x, y, z; - - /* parameters check */ - if (event == NULL) return -1; - - /* get event data */ - event->version = sizeof(sensors_event_t); - event->sensor = (int32_t) this; - event->timestamp = rt_tick_get(); - event->type = SENSOR_TYPE_ACCELEROMETER; - - read_buffer(MPU6050_ACCEL_XOUT_H, value, 6); - - /* get raw data */ - x = (((rt_int16_t)value[0] << 8) | value[1]); - y = (((rt_int16_t)value[2] << 8) | value[3]); - z = (((rt_int16_t)value[4] << 8) | value[5]); - - if (config.mode == SENSOR_MODE_RAW) - { - event->raw_acceleration.x = x; - event->raw_acceleration.y = y; - event->raw_acceleration.z = z; - } - else - { - - x -= x_offset; y -= y_offset; z -= z_offset; - event->acceleration.x = x * this->sensitivity * SENSORS_GRAVITY_STANDARD; - event->acceleration.y = y * this->sensitivity * SENSORS_GRAVITY_STANDARD; - event->acceleration.z = z * this->sensitivity * SENSORS_GRAVITY_STANDARD; - } - - return 0; -} - -void -MPU6050_Accelerometer::getSensor(sensor_t *sensor) -{ - /* get sensor description */ - if (sensor) - { - memcpy(sensor, &_MPU6050_sensor[0], sizeof(sensor_t)); - } -} - -MPU6050_Gyroscope::MPU6050_Gyroscope(const char* iic_name, int addr) - : MPU6050(SENSOR_TYPE_GYROSCOPE, iic_name, addr) -{ - int index; - uint8_t id; - rt_uint8_t value[6]; - rt_int32_t x, y, z; - - /* initialize MPU6050 */ - write_reg(MPU6050_PWR_MGMT_1, 0x80); /* reset mpu6050 device */ - write_reg(MPU6050_SMPLRT_DIV, 0x00); /* Sample Rate = Gyroscope Output Rate / (1 + SMPLRT_DIV) */ - write_reg(MPU6050_PWR_MGMT_1, 0x03); /* Wake up device , set device clock Z axis gyroscope */ - write_reg(MPU6050_CONFIG, 0x03); /* set DLPF_CFG 42Hz */ - write_reg(MPU6050_GYRO_CONFIG, 0x18); /* set gyro 2000deg/s */ - write_reg(MPU6050_ACCEL_CONFIG, 0x08); /* set acc +-4g/s */ - - x_offset = y_offset = z_offset = 0; - x = y = z = 0; - - /* read MPU6050 id */ - read_reg(MPU6050_WHOAMI, &id); - if (id != MPU6050_ID) - { - printf("Warning: not found MPU6050 id: %02x\n", id); - } - - /* get offset */ - for (index = 0; index < 200; index ++) - { - read_buffer(MPU6050_GYRO_XOUT_H, value, 6); - - x += (((rt_int16_t)value[0] << 8) | value[1]); - y += (((rt_int16_t)value[2] << 8) | value[3]); - z += (((rt_int16_t)value[4] << 8) | value[5]); - } - x_offset = x / 200; - y_offset = y / 200; - z_offset = z / 200; - - this->enable = RT_FALSE; - this->sensitivity = SENSOR_GYRO_SENSITIVITY_250DPS; -} - -int -MPU6050_Gyroscope::configure(SensorConfig *config) -{ - int range; - uint8_t value; - - if (config == RT_NULL) return -1; - - /* TODO: set datarate */ - - /* get range and calc the sensitivity */ - range = config->range.gyro_range; - switch (range) - { - case SENSOR_GYRO_RANGE_250DPS: - this->sensitivity = SENSOR_GYRO_SENSITIVITY_250DPS; - range = 0; - break; - case SENSOR_GYRO_RANGE_500DPS: - this->sensitivity = SENSOR_GYRO_SENSITIVITY_500DPS; - range = 0x01 << 2; - break; - case SENSOR_GYRO_RANGE_1000DPS: - this->sensitivity = SENSOR_GYRO_SENSITIVITY_1000DPS; - range = 0x02 << 2; - break; - case SENSOR_GYRO_RANGE_2000DPS: - this->sensitivity = SENSOR_GYRO_SENSITIVITY_2000DPS; - range = 0x03 << 2; - break; - default: - return -1; - } - - /* set range to sensor */ - read_reg(MPU6050_GYRO_CONFIG, &value); - value &= ~(0x3 << 2); - value |= range; - write_reg(MPU6050_GYRO_CONFIG, value); - - return 0; -} - -int -MPU6050_Gyroscope::activate(int enable) -{ - uint8_t value; - - if (enable && this->enable == RT_FALSE) - { - /* enable gyroscope */ - read_reg(MPU6050_PWR_MGMT_1, &value); - value &= ~(0x01 << 4); - write_reg(MPU6050_PWR_MGMT_1, value); - - read_reg(MPU6050_PWR_MGMT_2, &value); - value &= ~(0x07 << 0); - write_reg(MPU6050_PWR_MGMT_2, value); - } - - if (!enable && this->enable == RT_TRUE) - { - /* disable gyroscope */ - read_reg(MPU6050_PWR_MGMT_2, &value); - value |= (0x07 << 0); - write_reg(MPU6050_PWR_MGMT_2, value); - } - - if (enable) this->enable = RT_TRUE; - else this->enable = RT_FALSE; - - return 0; -} - -int -MPU6050_Gyroscope::poll(sensors_event_t *event) -{ - rt_uint8_t value[6]; - rt_int16_t x, y, z; - - /* parameters check */ - if (event == NULL) return -1; - - /* get event data */ - event->version = sizeof(sensors_event_t); - event->sensor = (int32_t) this; - event->timestamp = rt_tick_get(); - event->type = SENSOR_TYPE_GYROSCOPE; - - read_buffer(MPU6050_GYRO_XOUT_H, value, 6); - - /* get raw data */ - x = (((rt_int16_t)value[0] << 8) | value[1]); - y = (((rt_int16_t)value[2] << 8) | value[3]); - z = (((rt_int16_t)value[4] << 8) | value[5]); - - - if (config.mode == SENSOR_MODE_RAW) - { - event->raw_gyro.x = x; - event->raw_gyro.y = y; - event->raw_gyro.z = z; - } - else - { - x -= x_offset; y -= y_offset; z -= z_offset; - event->gyro.x = x * this->sensitivity * SENSORS_DPS_TO_RADS; - event->gyro.y = y * this->sensitivity * SENSORS_DPS_TO_RADS; - event->gyro.z = z * this->sensitivity * SENSORS_DPS_TO_RADS; - } - - return 0; -} - -void -MPU6050_Gyroscope::getSensor(sensor_t *sensor) -{ - /* get sensor description */ - if (sensor) - { - memcpy(sensor, &_MPU6050_sensor[1], sizeof(sensor_t)); - } -} - diff --git a/components/drivers/sensors/mpu6050_sensor.h b/components/drivers/sensors/mpu6050_sensor.h deleted file mode 100644 index 8f70c3e5ed..0000000000 --- a/components/drivers/sensors/mpu6050_sensor.h +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright (c) 2006-2018, RT-Thread Development Team - * - * SPDX-License-Identifier: Apache-2.0 - * - * Change Logs: - * Date Author Notes - * 2014-12-20 Bernard the first version - * 2015-1-11 RT_learning modify the mpu6050 ID - */ - -#ifndef MPU6050_SENSOR_H__ -#define MPU6050_SENSOR_H__ - -#include - -#define MPU6050_ADDRESS_AD0_LOW 0x68 // address pin low (GND), default for InvenSense evaluation board -#define MPU6050_ADDRESS_AD0_HIGH 0x69 // address pin high (VCC) -#define MPU6050_DEFAULT_ADDRESS MPU6050_ADDRESS_AD0_LOW - -#define MPU6050_XG_OFFS_TC 0x00 -#define MPU6050_YG_OFFS_TC 0x01 -#define MPU6050_ZG_OFFS_TC 0x02 -#define MPU6050_X_FINE_GAIN 0x03 -#define MPU6050_Y_FINE_GAIN 0x04 -#define MPU6050_Z_FINE_GAIN 0x05 -#define MPU6050_XA_OFFS_H 0x06 -#define MPU6050_XA_OFFS_L 0x07 -#define MPU6050_YA_OFFS_H 0x08 -#define MPU6050_YA_OFFS_L 0x09 -#define MPU6050_ZA_OFFS_H 0x0A -#define MPU6050_ZA_OFFS_L 0x0B -#define MPU6050_PRODUCT_ID 0x0C -#define MPU6050_SELF_TEST_X 0x0D -#define MPU6050_SELF_TEST_Y 0x0E -#define MPU6050_SELF_TEST_Z 0x0F -#define MPU6050_SELF_TEST_A 0x10 -#define MPU6050_XG_OFFS_USRH 0x13 -#define MPU6050_XG_OFFS_USRL 0x14 -#define MPU6050_YG_OFFS_USRH 0x15 -#define MPU6050_YG_OFFS_USRL 0x16 -#define MPU6050_ZG_OFFS_USRH 0x17 -#define MPU6050_ZG_OFFS_USRL 0x18 -#define MPU6050_SMPLRT_DIV 0x19 -#define MPU6050_CONFIG 0x1A -#define MPU6050_GYRO_CONFIG 0x1B -#define MPU6050_ACCEL_CONFIG 0x1C -#define MPU6050_ACCEL_CONFIG_2 0x1D -#define MPU6050_LP_ACCEL_ODR 0x1E -#define MPU6050_MOT_THR 0x1F -#define MPU6050_FIFO_EN 0x23 -#define MPU6050_I2C_MST_CTRL 0x24 -#define MPU6050_I2C_SLV0_ADDR 0x25 -#define MPU6050_I2C_SLV0_REG 0x26 -#define MPU6050_I2C_SLV0_CTRL 0x27 -#define MPU6050_I2C_SLV1_ADDR 0x28 -#define MPU6050_I2C_SLV1_REG 0x29 -#define MPU6050_I2C_SLV1_CTRL 0x2A -#define MPU6050_I2C_SLV2_ADDR 0x2B -#define MPU6050_I2C_SLV2_REG 0x2C -#define MPU6050_I2C_SLV2_CTRL 0x2D -#define MPU6050_I2C_SLV3_ADDR 0x2E -#define MPU6050_I2C_SLV3_REG 0x2F -#define MPU6050_I2C_SLV3_CTRL 0x30 -#define MPU6050_I2C_SLV4_ADDR 0x31 -#define MPU6050_I2C_SLV4_REG 0x32 -#define MPU6050_I2C_SLV4_DO 0x33 -#define MPU6050_I2C_SLV4_CTRL 0x34 -#define MPU6050_I2C_SLV4_DI 0x35 -#define MPU6050_I2C_MST_STATUS 0x36 -#define MPU6050_INT_PIN_CFG 0x37 -#define MPU6050_INT_ENABLE 0x38 -#define MPU6050_ACCEL_XOUT_H 0x3B -#define MPU6050_ACCEL_XOUT_L 0x3C -#define MPU6050_ACCEL_YOUT_H 0x3D -#define MPU6050_ACCEL_YOUT_L 0x3E -#define MPU6050_ACCEL_ZOUT_H 0x3F -#define MPU6050_ACCEL_ZOUT_L 0x40 -#define MPU6050_TEMP_OUT_H 0x41 -#define MPU6050_TEMP_OUT_L 0x42 -#define MPU6050_GYRO_XOUT_H 0x43 -#define MPU6050_GYRO_XOUT_L 0x44 -#define MPU6050_GYRO_YOUT_H 0x45 -#define MPU6050_GYRO_YOUT_L 0x46 -#define MPU6050_GYRO_ZOUT_H 0x47 -#define MPU6050_GYRO_ZOUT_L 0x48 -#define MPU6050_EXT_SENS_DATA_00 0x49 -#define MPU6050_EXT_SENS_DATA_01 0x4A -#define MPU6050_EXT_SENS_DATA_02 0x4B -#define MPU6050_EXT_SENS_DATA_03 0x4C -#define MPU6050_EXT_SENS_DATA_04 0x4D -#define MPU6050_EXT_SENS_DATA_05 0x4E -#define MPU6050_EXT_SENS_DATA_06 0x4F -#define MPU6050_EXT_SENS_DATA_07 0x50 -#define MPU6050_EXT_SENS_DATA_08 0x51 -#define MPU6050_EXT_SENS_DATA_09 0x52 -#define MPU6050_EXT_SENS_DATA_10 0x53 -#define MPU6050_EXT_SENS_DATA_11 0x54 -#define MPU6050_EXT_SENS_DATA_12 0x55 -#define MPU6050_EXT_SENS_DATA_13 0x56 -#define MPU6050_EXT_SENS_DATA_14 0x57 -#define MPU6050_EXT_SENS_DATA_15 0x58 -#define MPU6050_EXT_SENS_DATA_16 0x59 -#define MPU6050_EXT_SENS_DATA_17 0x5A -#define MPU6050_EXT_SENS_DATA_18 0x5B -#define MPU6050_EXT_SENS_DATA_19 0x5C -#define MPU6050_EXT_SENS_DATA_20 0x5D -#define MPU6050_EXT_SENS_DATA_21 0x5E -#define MPU6050_EXT_SENS_DATA_22 0x5F -#define MPU6050_EXT_SENS_DATA_23 0x60 -#define MPU6050_I2C_SLV0_DO 0x63 -#define MPU6050_I2C_SLV1_DO 0x64 -#define MPU6050_I2C_SLV2_DO 0x65 -#define MPU6050_I2C_SLV3_DO 0x66 -#define MPU6050_I2C_MST_DELAY_CTRL 0x67 -#define MPU6050_SIGNAL_PATH_RESET 0x68 -#define MPU6050_MOT_DETECT_CTRL 0x69 -#define MPU6050_USER_CTRL 0x6A -#define MPU6050_PWR_MGMT_1 0x6B -#define MPU6050_PWR_MGMT_2 0x6C -#define MPU6050_BANK_SEL 0x6D -#define MPU6050_MEM_START_ADDR 0x6E -#define MPU6050_MEM_R_W 0x6F -#define MPU6050_DMP_CFG_1 0x70 -#define MPU6050_DMP_CFG_2 0x71 -#define MPU6050_FIFO_COUNTH 0x72 -#define MPU6050_FIFO_COUNTL 0x73 -#define MPU6050_FIFO_R_W 0x74 -#define MPU6050_WHOAMI 0x75 -#define MPU6050_XA_OFFSET_H 0x77 -#define MPU6050_XA_OFFSET_L 0x78 -#define MPU6050_YA_OFFSET_H 0x7A -#define MPU6050_YA_OFFSET_L 0x7B -#define MPU6050_ZA_OFFSET_H 0x7D -#define MPU6050_ZA_OFFSET_L 0x7E - -#define MPU6050_ID 0x68 - -class MPU6050 :public SensorBase -{ -public: - MPU6050(int sensor_type, const char* iic_bus, int addr); - - int read_reg(rt_uint8_t reg, rt_uint8_t* value); - int write_reg(rt_uint8_t reg, rt_uint8_t value); - int read_buffer(rt_uint8_t reg, rt_uint8_t* value, rt_size_t size); - -private: - struct rt_i2c_bus_device *i2c_bus; - int i2c_addr; -}; - -class MPU6050_Accelerometer:public MPU6050 -{ -public: - MPU6050_Accelerometer(const char* iic_name, int addr); - - virtual int configure(SensorConfig *config); - virtual int activate(int enable); - - virtual int poll(sensors_event_t *event); - virtual void getSensor(sensor_t *sensor); - -private: - rt_int16_t x_offset, y_offset, z_offset; - - rt_bool_t enable; - float sensitivity; -}; - -class MPU6050_Gyroscope:public MPU6050 -{ -public: - MPU6050_Gyroscope(const char* iic_name, int addr); - - virtual int configure(SensorConfig *config); - virtual int activate(int enable); - - virtual int poll(sensors_event_t *event); - virtual void getSensor(sensor_t *sensor); - -private: - rt_int16_t x_offset, y_offset, z_offset; - - rt_bool_t enable; - float sensitivity; -}; - -#endif diff --git a/components/drivers/sensors/sensor.c b/components/drivers/sensors/sensor.c new file mode 100644 index 0000000000..80c9a60ae0 --- /dev/null +++ b/components/drivers/sensors/sensor.c @@ -0,0 +1,449 @@ +/* + * Copyright (c) 2006-2018, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2019-01-31 flybreak first version + */ + +#include "sensor.h" + +#define DBG_ENABLE +#define DBG_LEVEL DBG_INFO +#define DBG_SECTION_NAME "sensor" +#define DBG_COLOR +#include + +#include + +static char *const sensor_name_str[] = +{ + "none", + "acce_", /* Accelerometer */ + "gyro_", /* Gyroscope */ + "mag_", /* Magnetometer */ + "temp_", /* Temperature */ + "humi_", /* Relative Humidity */ + "baro_", /* Barometer */ + "li_", /* Ambient light */ + "pr_", /* Proximity */ + "hr_", /* Heart Rate */ + "tvoc_", /* TVOC Level */ + "noi_", /* Noise Loudness */ + "step_" /* Step sensor */ +}; + +/* Sensor interrupt correlation function */ +/* + * Sensor interrupt handler function + */ +void rt_sensor_cb(rt_sensor_t sen) +{ + if (sen->parent.rx_indicate == RT_NULL) + { + return; + } + + /* The buffer is not empty. Read the data in the buffer first */ + if (sen->data_len > 0) + { + sen->parent.rx_indicate(&sen->parent, sen->data_len / sizeof(struct rt_sensor_data)); + } + else if (sen->config.mode == RT_SEN_MODE_INT) + { + /* The interrupt mode only produces one data at a time */ + sen->parent.rx_indicate(&sen->parent, 1); + } + else if (sen->config.mode == RT_SEN_MODE_FIFO) + { + sen->parent.rx_indicate(&sen->parent, sen->info.fifo_max); + } +} + +/* ISR for sensor interrupt */ +static void irq_callback(void *args) +{ + rt_sensor_t sensor = args; + rt_uint8_t i; + + if (sensor->module) + { + /* Invoke a callback for all sensors in the module */ + for (i = 0; i < sensor->module->sen_num; i++) + { + rt_sensor_cb(sensor->module->sen[i]); + } + } + else + { + rt_sensor_cb(sensor); + } +} + +/* Sensor interrupt initialization function */ +static rt_err_t rt_sensor_irq_init(rt_sensor_t sensor) +{ + if (sensor->config.irq_pin.pin == RT_PIN_NONE) + { + return -RT_EINVAL; + } + + rt_pin_mode(sensor->config.irq_pin.pin, sensor->config.irq_pin.mode); + + if (sensor->config.irq_pin.mode == PIN_MODE_INPUT_PULLDOWN) + { + rt_pin_attach_irq(sensor->config.irq_pin.pin, PIN_IRQ_MODE_RISING, irq_callback, (void *)sensor); + } + else if (sensor->config.irq_pin.mode == PIN_MODE_INPUT_PULLUP) + { + rt_pin_attach_irq(sensor->config.irq_pin.pin, PIN_IRQ_MODE_FALLING, irq_callback, (void *)sensor); + } + else if (sensor->config.irq_pin.mode == PIN_MODE_INPUT) + { + rt_pin_attach_irq(sensor->config.irq_pin.pin, PIN_IRQ_MODE_RISING_FALLING, irq_callback, (void *)sensor); + } + + rt_pin_irq_enable(sensor->config.irq_pin.pin, RT_TRUE); + + LOG_I("interrupt init success"); + + return 0; +} + +/* Sensor interrupt enable */ +static void rt_sensor_irq_enable(rt_sensor_t sensor) +{ + if (sensor->config.irq_pin.pin != RT_PIN_NONE) + { + rt_pin_irq_enable(sensor->config.irq_pin.pin, RT_TRUE); + } +} + +/* Sensor interrupt disable */ +static void rt_sensor_irq_disable(rt_sensor_t sensor) +{ + if (sensor->config.irq_pin.pin != RT_PIN_NONE) + { + rt_pin_irq_enable(sensor->config.irq_pin.pin, RT_FALSE); + } +} + +/* RT-Thread Device Interface */ + +static rt_err_t rt_sensor_init(rt_device_t dev) +{ + rt_sensor_t sensor = (rt_sensor_t)dev; + RT_ASSERT(dev != RT_NULL); + + if (sensor->module != RT_NULL && sensor->info.fifo_max > 0 && sensor->data_buf == RT_NULL) + { + /* Allocate memory for the sensor buffer */ + sensor->data_buf = rt_malloc(sizeof(struct rt_sensor_data) * sensor->info.fifo_max); + if (sensor->data_buf == RT_NULL) + { + return -RT_ENOMEM; + } + } + + return RT_EOK; +} + +static rt_err_t rt_sensor_open(rt_device_t dev, rt_uint16_t oflag) +{ + rt_sensor_t sensor = (rt_sensor_t)dev; + RT_ASSERT(dev != RT_NULL); + + if (sensor->module) + { + /* take the module mutex */ + rt_mutex_take(sensor->module->lock, RT_WAITING_FOREVER); + } + + if (oflag & RT_DEVICE_FLAG_RDONLY && dev->flag & RT_DEVICE_FLAG_RDONLY) + { + /* If polling mode is supported, configure it to polling mode */ + if (sensor->ops->control(sensor, RT_SEN_CTRL_SET_MODE, (void *)RT_SEN_MODE_POLLING) == RT_EOK) + { + sensor->config.mode = RT_SEN_MODE_POLLING; + } + } + else if (oflag & RT_DEVICE_FLAG_INT_RX && dev->flag & RT_DEVICE_FLAG_INT_RX) + { + /* If interrupt mode is supported, configure it to interrupt mode */ + if (sensor->ops->control(sensor, RT_SEN_CTRL_SET_MODE, (void *)RT_SEN_MODE_INT) == RT_EOK) + { + sensor->config.mode = RT_SEN_MODE_INT; + /* Initialization sensor interrupt */ + rt_sensor_irq_init(sensor); + } + } + else if (oflag & RT_SEN_FLAG_FIFO && dev->flag & RT_SEN_FLAG_FIFO) + { + /* If fifo mode is supported, configure it to fifo mode */ + if (sensor->ops->control(sensor, RT_SEN_CTRL_SET_MODE, (void *)RT_SEN_MODE_FIFO) == RT_EOK) + { + sensor->config.mode = RT_SEN_MODE_FIFO; + /* Initialization sensor interrupt */ + rt_sensor_irq_init(sensor); + } + } + else + { + return -RT_EINVAL; + } + + /* Configure power mode to normal mode */ + if (sensor->ops->control(sensor, RT_SEN_CTRL_SET_POWER, (void *)RT_SEN_POWER_NORMAL) == RT_EOK) + { + sensor->config.power = RT_SEN_POWER_NORMAL; + } + + if (sensor->module) + { + /* release the module mutex */ + rt_mutex_release(sensor->module->lock); + } + + return RT_EOK; +} + +static rt_err_t rt_sensor_close(rt_device_t dev) +{ + rt_sensor_t sensor = (rt_sensor_t)dev; + RT_ASSERT(dev != RT_NULL); + + if (sensor->module) + { + rt_mutex_take(sensor->module->lock, RT_WAITING_FOREVER); + } + + /* Configure power mode to power down mode */ + if (sensor->ops->control(sensor, RT_SEN_CTRL_SET_POWER, (void *)RT_SEN_POWER_DOWN) == RT_EOK) + { + sensor->config.power = RT_SEN_POWER_DOWN; + } + + /* Sensor disable interrupt */ + rt_sensor_irq_disable(sensor); + + if (sensor->module) + { + rt_mutex_release(sensor->module->lock); + } + + return RT_EOK; +} + +static rt_size_t rt_sensor_read(rt_device_t dev, rt_off_t pos, void *buf, rt_size_t len) +{ + rt_sensor_t sensor = (rt_sensor_t)dev; + rt_size_t result = 0; + RT_ASSERT(dev != RT_NULL); + + if (buf == NULL || len == 0) + { + return 0; + } + + if (sensor->module) + { + rt_mutex_take(sensor->module->lock, RT_WAITING_FOREVER); + } + + /* The buffer is not empty. Read the data in the buffer first */ + if (sensor->data_len > 0) + { + if (len > sensor->data_len / sizeof(struct rt_sensor_data)) + { + len = sensor->data_len / sizeof(struct rt_sensor_data); + } + + rt_memcpy(buf, sensor->data_buf, len * sizeof(struct rt_sensor_data)); + + /* Clear the buffer */ + sensor->data_len = 0; + result = len; + } + else + { + /* If the buffer is empty read the data */ + result = sensor->ops->fetch_data(sensor, buf, len); + } + + if (sensor->module) + { + rt_mutex_release(sensor->module->lock); + } + + return result; +} + +static rt_err_t rt_sensor_control(rt_device_t dev, int cmd, void *args) +{ + rt_sensor_t sensor = (rt_sensor_t)dev; + rt_err_t result = RT_EOK; + RT_ASSERT(dev != RT_NULL); + + if (sensor->module) + { + rt_mutex_take(sensor->module->lock, RT_WAITING_FOREVER); + } + + switch (cmd) + { + case RT_SEN_CTRL_GET_ID: + if (args) + { + sensor->ops->control(sensor, RT_SEN_CTRL_GET_ID, args); + } + break; + case RT_SEN_CTRL_GET_INFO: + if (args) + { + rt_memcpy(args, &sensor->info, sizeof(struct rt_sensor_info)); + } + break; + case RT_SEN_CTRL_SET_RANGE: + + /* Configuration measurement range */ + result = sensor->ops->control(sensor, RT_SEN_CTRL_SET_RANGE, args); + if (result == RT_EOK) + { + sensor->config.range = (rt_int32_t)args; + LOG_D("set range %d", sensor->config.range); + } + break; + case RT_SEN_CTRL_SET_ODR: + + /* Configuration data output rate */ + result = sensor->ops->control(sensor, RT_SEN_CTRL_SET_ODR, args); + if (result == RT_EOK) + { + sensor->config.odr = (rt_uint32_t)args & 0xFFFF; + LOG_D("set odr %d", sensor->config.odr); + } + break; + case RT_SEN_CTRL_SET_MODE: + + /* Configuration sensor work mode */ + result = sensor->ops->control(sensor, RT_SEN_CTRL_SET_MODE, args); + if (result == RT_EOK) + { + sensor->config.mode = (rt_uint32_t)args & 0xFF; + LOG_D("set work mode code:", sensor->config.mode); + + if (sensor->config.mode == RT_SEN_MODE_POLLING) + { + rt_sensor_irq_disable(sensor); + } + else if (sensor->config.mode == RT_SEN_MODE_INT || sensor->config.mode == RT_SEN_MODE_FIFO) + { + rt_sensor_irq_enable(sensor); + } + } + break; + case RT_SEN_CTRL_SET_POWER: + + /* Configuration sensor power mode */ + result = sensor->ops->control(sensor, RT_SEN_CTRL_SET_POWER, args); + if (result == RT_EOK) + { + sensor->config.power = (rt_uint32_t)args & 0xFF; + LOG_D("set power mode code:", sensor->config.power); + } + break; + case RT_SEN_CTRL_SELF_TEST: + + /* Device self-test */ + result = sensor->ops->control(sensor, RT_SEN_CTRL_SELF_TEST, args); + break; + default: + return -RT_ERROR; + } + + if (sensor->module) + { + rt_mutex_release(sensor->module->lock); + } + + return result; +} + +#ifdef RT_USING_DEVICE_OPS +const static struct rt_device_ops rt_sensor_ops = +{ + rt_sensor_init, + rt_sensor_open, + rt_sensor_close, + rt_sensor_read, + RT_NULL, + rt_sensor_control +}; +#endif + +/* + * sensor register + */ +int rt_hw_sensor_register(rt_sensor_t sensor, + const char *name, + rt_uint32_t flag, + void *data) +{ + rt_int8_t result; + rt_device_t device; + RT_ASSERT(sensor != RT_NULL); + + char *sensor_name = RT_NULL, *device_name = RT_NULL; + + /* Add a type name for the sensor device */ + sensor_name = sensor_name_str[sensor->info.type]; + device_name = rt_calloc(1, rt_strlen(sensor_name) + 1 + rt_strlen(name)); + if (device_name == RT_NULL) + { + LOG_E("device_name calloc failed!"); + return -RT_ERROR; + } + + rt_memcpy(device_name, sensor_name, rt_strlen(sensor_name) + 1); + strcat(device_name, name); + + if (sensor->module != RT_NULL && sensor->module->lock == RT_NULL) + { + /* Create a mutex lock for the module */ + sensor->module->lock = rt_mutex_create(name, RT_IPC_FLAG_FIFO); + if (sensor->module->lock == RT_NULL) + { + rt_free(device_name); + return -RT_ERROR; + } + } + + device = &sensor->parent; + +#ifdef RT_USING_DEVICE_OPS + device->ops = &rt_sensor_ops; +#else + device->init = rt_sensor_init; + device->open = rt_sensor_open; + device->close = rt_sensor_close; + device->read = rt_sensor_read; + device->write = RT_NULL; + device->control = rt_sensor_control; +#endif + device->type = RT_Device_Class_Sensor; + device->rx_indicate = RT_NULL; + device->tx_complete = RT_NULL; + device->user_data = data; + + result = rt_device_register(device, device_name, flag | RT_DEVICE_FLAG_STANDALONE); + if (result != RT_EOK) + { + LOG_E("rt_sensor register err code: %d", result); + return result; + } + + LOG_I("rt_sensor init success"); + return RT_EOK; +} diff --git a/components/drivers/sensors/sensor.cpp b/components/drivers/sensors/sensor.cpp deleted file mode 100644 index f986510f63..0000000000 --- a/components/drivers/sensors/sensor.cpp +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (c) 2006-2018, RT-Thread Development Team - * - * SPDX-License-Identifier: Apache-2.0 - * - * Change Logs: - * Date Author Notes - * 2014-08-03 Bernard the first version - */ - -#include -#include - -#include "sensor.h" - -/** - * SensorBase - */ -SensorBase::SensorBase(int type) -{ - memset(&(this->config), 0x0, sizeof(SensorConfig)); - - this->type = type; - this->next = this->prev = NULL; - subscribe(NULL, NULL); -} - -SensorBase::~SensorBase() -{ -} - -int SensorBase::getType(void) -{ - return this->type; -} - -int SensorBase::setConfig(SensorConfig *config) -{ - int result; - - /* configure to the low level sensor */ - result = this->configure(config); - if (result == 0) - { - this->config = *config; - } - - return result; -} - -int SensorBase::getConfig(SensorConfig *config) -{ - *config = this->config; - return 0; -} - -int SensorBase::subscribe(SensorEventHandler_t handler, void *user_data) -{ - this->evtHandler = handler; - this->userData = user_data; - - return 0; -} - -int SensorBase::publish(void) -{ - if (this->evtHandler != NULL) - { - /* invoke subscribed handler */ - (*evtHandler)(this->userData); - } - - return 0; -} - -/** - * Sensor Manager - */ -/* sensors list */ -static SensorBase *sensor_list = NULL; - -SensorManager::SensorManager() -{ -} - -SensorManager::~SensorManager() -{ -} - -int SensorManager::registerSensor(SensorBase *sensor) -{ - RT_ASSERT(sensor != RT_NULL); - - /* add sensor into the list */ - if (sensor_list == NULL) - { - sensor->prev = sensor->next = sensor; - } - else - { - sensor_list->prev->next = sensor; - sensor->prev = sensor_list->prev; - - sensor_list->prev = sensor; - sensor->next = sensor_list; - } - - /* point the sensorList to this sensor */ - sensor_list = sensor; - - return 0; -} - -int SensorManager::unregisterSensor(SensorBase *sensor) -{ - /* disconnect sensor list */ - sensor->next->prev = sensor->prev; - sensor->prev->next = sensor->next; - - /* check the sensorList */ - if (sensor == sensor_list) - { - if (sensor->next == sensor) sensor_list = NULL; /* empty list */ - else sensor_list = sensor->next; - } - - /* re-initialize sensor node */ - sensor->next = sensor->prev = sensor; - - return 0; -} - -SensorBase *SensorManager::getDefaultSensor(int type) -{ - SensorBase *sensor = sensor_list; - - if (sensor == NULL) return NULL; - - do - { - /* find the same type */ - if (sensor->getType() == type) return sensor; - - sensor = sensor->next; - }while (sensor != sensor_list); - - return NULL; -} - -int SensorManager::subscribe(int type, SensorEventHandler_t handler, void *user_data) -{ - SensorBase *sensor; - - sensor = SensorManager::getDefaultSensor(type); - if (sensor != NULL) - { - sensor->subscribe(handler, user_data); - return 0; - } - - return -1; -} - -int SensorManager::sensorEventReady(SensorBase *sensor) -{ - return 0; -} - -int SensorManager::pollSensor(SensorBase *sensor, sensors_event_t *events, int number, int duration) -{ - rt_tick_t tick; - int result, index; - - if (sensor == NULL) return -1; - - tick = rt_tick_get(); - for (index = 0; index < number; index ++) - { - result = sensor->poll(&events[index]); - if (result < 0) break; - - if (rt_tick_get() - tick > duration) break; - } - - return index; -} - -rt_sensor_t rt_sensor_get_default(int type) -{ - return (rt_sensor_t)SensorManager::getDefaultSensor(type); -} - -int rt_sensor_subscribe(rt_sensor_t sensor, SensorEventHandler_t handler, void *user_data) -{ - SensorBase *sensor_base; - if (sensor == NULL) return -1; - - sensor_base = (SensorBase*)sensor; - - return sensor_base->subscribe(handler, user_data); -} - -int rt_sensor_poll(rt_sensor_t sensor, sensors_event_t *event) -{ - SensorBase *sensor_base; - if (sensor == NULL || event == NULL) return -1; - - sensor_base = (SensorBase*)sensor; - return sensor_base->poll(event); -} - -int rt_sensor_configure(rt_sensor_t sensor, SensorConfig *config) -{ - SensorBase *sensor_base; - if (sensor == NULL || config == NULL) return -1; - - sensor_base = (SensorBase*)sensor; - return sensor_base->setConfig(config); -} - -int rt_sensor_activate(rt_sensor_t sensor, int enable) -{ - SensorBase *sensor_base; - if (sensor == NULL) return -1; - - sensor_base = (SensorBase*)sensor; - return sensor_base->activate(enable); -} diff --git a/components/drivers/sensors/sensor.h b/components/drivers/sensors/sensor.h index 916360d34b..15dd79ccdf 100644 --- a/components/drivers/sensors/sensor.h +++ b/components/drivers/sensors/sensor.h @@ -5,1125 +5,188 @@ * * Change Logs: * Date Author Notes - * 2014-08-03 Bernard the first version + * 2019-01-31 flybreak first version */ + +#ifndef __SENSOR_H__ +#define __SENSOR_H__ -/* Modified from: https://github.com/android/platform_hardware_libhardware/blob/master/include/hardware/sensors.h */ - -/* - * Copyright (C) 2012 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef SENSORS_H__ -#define SENSORS_H__ - +#include #include -#include -#ifdef __CC_ARM /* skip warning in armcc */ -#pragma anon_unions +#ifdef RT_USING_RTC +#define rt_sen_get_timestamp() time() /* API for the sensor to get the timestamp */ +#else +#define rt_sen_get_timestamp() rt_tick_get() /* API for the sensor to get the timestamp */ #endif -/** - * Handles must be higher than SENSORS_HANDLE_BASE and must be unique. - * A Handle identifies a given sensors. The handle is used to activate - * and/or deactivate sensors. - * In this version of the API there can only be 256 handles. - */ -#define SENSORS_HANDLE_BASE 0 -#define SENSORS_HANDLE_BITS 8 -#define SENSORS_HANDLE_COUNT (1<0 - * ^ - * | - * +-----------+--> y>0 - * | | - * | | - * | | - * | | / z<0 - * | | / - * | | / - * O-----------+/ - * |[] [ ] []/ - * +----------/+ y<0 - * / - * / - * |/ z>0 (toward the sky) - * - * O: Origin (x=0,y=0,z=0) - * - */ - -/* - * Interaction with suspend mode - * - * Unless otherwise noted, an enabled sensor shall not prevent the - * SoC to go into suspend mode. It is the responsibility of applications - * to keep a partial wake-lock should they wish to receive sensor - * events while the screen is off. While in suspend mode, and unless - * otherwise noted (batch mode, sensor particularities, ...), enabled sensors' - * events are lost. - * - * Note that conceptually, the sensor itself is not de-activated while in - * suspend mode -- it's just that the data it returns are lost. As soon as - * the SoC gets out of suspend mode, operations resume as usual. Of course, - * in practice sensors shall be disabled while in suspend mode to - * save power, unless batch mode is active, in which case they must - * continue fill their internal FIFO (see the documentation of batch() to - * learn how suspend interacts with batch mode). - * - * In batch mode, and only when the flag SENSORS_BATCH_WAKE_UPON_FIFO_FULL is - * set and supported, the specified sensor must be able to wake-up the SoC and - * be able to buffer at least 10 seconds worth of the requested sensor events. - * - * There are notable exceptions to this behavior, which are sensor-dependent - * (see sensor types definitions below) - * - * - * The sensor type documentation below specifies the wake-up behavior of - * each sensor: - * wake-up: yes this sensor must wake-up the SoC to deliver events - * wake-up: no this sensor shall not wake-up the SoC, events are dropped - * - */ - -/* - * Sensor type - * - * Each sensor has a type which defines what this sensor measures and how - * measures are reported. All types are defined below. - * - * Device manufacturers (OEMs) can define their own sensor types, for - * their private use by applications or services provided by them. Such - * sensor types are specific to an OEM and can't be exposed in the SDK. - * These types must start at SENSOR_TYPE_DEVICE_PRIVATE_BASE. - */ - -/* - * Base for device manufacturers private sensor types. - * These sensor types can't be exposed in the SDK. - */ -#define SENSOR_TYPE_DEVICE_PRIVATE_BASE 0x10000 - -/* - * Sensor fusion and virtual sensors - * - * Many sensor types are or can be implemented as virtual sensors from - * physical sensors on the device. For instance the rotation vector sensor, - * orientation sensor, step-detector, step-counter, etc... - * - * From the point of view of this API these virtual sensors MUST appear as - * real, individual sensors. It is the responsibility of the driver and HAL - * to make sure this is the case. - * - * In particular, all sensors must be able to function concurrently. - * For example, if defining both an accelerometer and a step counter, - * then both must be able to work concurrently. - */ - -/* - * Trigger modes - * - * Sensors can report events in different ways called trigger modes, - * each sensor type has one and only one trigger mode associated to it. - * Currently there are four trigger modes defined: - * - * continuous: events are reported at a constant rate defined by setDelay(). - * eg: accelerometers, gyroscopes. - * on-change: events are reported only if the sensor's value has changed. - * setDelay() is used to set a lower limit to the reporting - * period (minimum time between two events). - * The HAL must return an event immediately when an on-change - * sensor is activated. - * eg: proximity, light sensors - * one-shot: upon detection of an event, the sensor deactivates itself and - * then sends a single event. Order matters to avoid race - * conditions. No other event is sent until the sensor get - * reactivated. setDelay() is ignored. - * eg: significant motion sensor - * special: see details in the sensor type specification below - * - */ - -/* - * SENSOR_TYPE_META_DATA - * trigger-mode: n/a - * wake-up sensor: n/a - * - * NO SENSOR OF THAT TYPE MUST BE RETURNED (*get_sensors_list)() - * - * SENSOR_TYPE_META_DATA is a special token used to populate the - * sensors_meta_data_event structure. It doesn't correspond to a physical - * sensor. sensors_meta_data_event are special, they exist only inside - * the HAL and are generated spontaneously, as opposed to be related to - * a physical sensor. - * - * sensors_meta_data_event_t.version must be META_DATA_VERSION - * sensors_meta_data_event_t.sensor must be 0 - * sensors_meta_data_event_t.type must be SENSOR_TYPE_META_DATA - * sensors_meta_data_event_t.reserved must be 0 - * sensors_meta_data_event_t.timestamp must be 0 - * - * The payload is a meta_data_event_t, where: - * meta_data_event_t.what can take the following values: - * - * META_DATA_FLUSH_COMPLETE - * This event indicates that a previous (*flush)() call has completed for the sensor - * handle specified in meta_data_event_t.sensor. - * see (*flush)() for more details - * - * All other values for meta_data_event_t.what are reserved and - * must not be used. - * - */ -#define SENSOR_TYPE_META_DATA (0) - -/* - * SENSOR_TYPE_ACCELEROMETER - * trigger-mode: continuous - * wake-up sensor: no - * - * All values are in SI units (m/s^2) and measure the acceleration of the - * device minus the force of gravity. - * - * Acceleration sensors return sensor events for all 3 axes at a constant - * rate defined by setDelay(). - * - * x: Acceleration on the x-axis - * y: Acceleration on the y-axis - * z: Acceleration on the z-axis - * - * Note that the readings from the accelerometer include the acceleration - * due to gravity (which is opposite to the direction of the gravity vector). - * - * Examples: - * The norm of should be close to 0 when in free fall. - * - * When the device lies flat on a table and is pushed on its left side - * toward the right, the x acceleration value is positive. - * - * When the device lies flat on a table, the acceleration value is +9.81, - * which correspond to the acceleration of the device (0 m/s^2) minus the - * force of gravity (-9.81 m/s^2). - * - * When the device lies flat on a table and is pushed toward the sky, the - * acceleration value is greater than +9.81, which correspond to the - * acceleration of the device (+A m/s^2) minus the force of - * gravity (-9.81 m/s^2). - */ -#define SENSOR_TYPE_ACCELEROMETER (1) - -/* - * SENSOR_TYPE_GEOMAGNETIC_FIELD - * trigger-mode: continuous - * wake-up sensor: no - * - * All values are in micro-Tesla (uT) and measure the geomagnetic - * field in the X, Y and Z axis. - * - * Returned values include calibration mechanisms such that the vector is - * aligned with the magnetic declination and heading of the earth's - * geomagnetic field. - * - * Magnetic Field sensors return sensor events for all 3 axes at a constant - * rate defined by setDelay(). - */ -#define SENSOR_TYPE_GEOMAGNETIC_FIELD (2) -#define SENSOR_TYPE_MAGNETIC_FIELD SENSOR_TYPE_GEOMAGNETIC_FIELD - -/* - * SENSOR_TYPE_ORIENTATION - * trigger-mode: continuous - * wake-up sensor: no - * - * All values are angles in degrees. - * - * Orientation sensors return sensor events for all 3 axes at a constant - * rate defined by setDelay(). - * - * azimuth: angle between the magnetic north direction and the Y axis, around - * the Z axis (0<=azimuth<360). - * 0=North, 90=East, 180=South, 270=West - * - * pitch: Rotation around X axis (-180<=pitch<=180), with positive values when - * the z-axis moves toward the y-axis. - * - * roll: Rotation around Y axis (-90<=roll<=90), with positive values when - * the x-axis moves towards the z-axis. - * - * Note: For historical reasons the roll angle is positive in the clockwise - * direction (mathematically speaking, it should be positive in the - * counter-clockwise direction): - * - * Z - * ^ - * (+roll) .--> | - * / | - * | | roll: rotation around Y axis - * X <-------(.) - * Y - * note that +Y == -roll - * - * - * - * Note: This definition is different from yaw, pitch and roll used in aviation - * where the X axis is along the long side of the plane (tail to nose). - */ -#define SENSOR_TYPE_ORIENTATION (3) - -/* - * SENSOR_TYPE_GYROSCOPE - * trigger-mode: continuous - * wake-up sensor: no - * - * All values are in radians/second and measure the rate of rotation - * around the X, Y and Z axis. The coordinate system is the same as is - * used for the acceleration sensor. Rotation is positive in the - * counter-clockwise direction (right-hand rule). That is, an observer - * looking from some positive location on the x, y or z axis at a device - * positioned on the origin would report positive rotation if the device - * appeared to be rotating counter clockwise. Note that this is the - * standard mathematical definition of positive rotation and does not agree - * with the definition of roll given earlier. - * The range should at least be 17.45 rad/s (ie: ~1000 deg/s). - * - * automatic gyro-drift compensation is allowed but not required. - */ -#define SENSOR_TYPE_GYROSCOPE (4) - -/* - * SENSOR_TYPE_LIGHT - * trigger-mode: on-change - * wake-up sensor: no - * - * The light sensor value is returned in SI lux units. - */ -#define SENSOR_TYPE_LIGHT (5) - -/* - * SENSOR_TYPE_PRESSURE - * trigger-mode: continuous - * wake-up sensor: no - * - * The pressure sensor return the athmospheric pressure in hectopascal (hPa) - */ -#define SENSOR_TYPE_PRESSURE (6) - -/* SENSOR_TYPE_TEMPERATURE is deprecated in the HAL */ -#define SENSOR_TYPE_TEMPERATURE (7) - -/* - * SENSOR_TYPE_PROXIMITY - * trigger-mode: on-change - * wake-up sensor: yes - * - * The distance value is measured in centimeters. Note that some proximity - * sensors only support a binary "close" or "far" measurement. In this case, - * the sensor should report its maxRange value in the "far" state and a value - * less than maxRange in the "near" state. - */ -#define SENSOR_TYPE_PROXIMITY (8) - -/* - * SENSOR_TYPE_GRAVITY - * trigger-mode: continuous - * wake-up sensor: no - * - * A gravity output indicates the direction of and magnitude of gravity in - * the devices's coordinates. On Earth, the magnitude is 9.8 m/s^2. - * Units are m/s^2. The coordinate system is the same as is used for the - * acceleration sensor. When the device is at rest, the output of the - * gravity sensor should be identical to that of the accelerometer. - */ -#define SENSOR_TYPE_GRAVITY (9) - -/* - * SENSOR_TYPE_LINEAR_ACCELERATION - * trigger-mode: continuous - * wake-up sensor: no - * - * Indicates the linear acceleration of the device in device coordinates, - * not including gravity. - * - * The output is conceptually: - * output of TYPE_ACCELERATION - output of TYPE_GRAVITY - * - * Readings on all axes should be close to 0 when device lies on a table. - * Units are m/s^2. - * The coordinate system is the same as is used for the acceleration sensor. - */ -#define SENSOR_TYPE_LINEAR_ACCELERATION (10) - -/* - * SENSOR_TYPE_ROTATION_VECTOR - * trigger-mode: continuous - * wake-up sensor: no - * - * The rotation vector symbolizes the orientation of the device relative to the - * East-North-Up coordinates frame. It is usually obtained by integration of - * accelerometer, gyroscope and magnetometer readings. - * - * The East-North-Up coordinate system is defined as a direct orthonormal basis - * where: - * - X points east and is tangential to the ground. - * - Y points north and is tangential to the ground. - * - Z points towards the sky and is perpendicular to the ground. - * - * The orientation of the phone is represented by the rotation necessary to - * align the East-North-Up coordinates with the phone's coordinates. That is, - * applying the rotation to the world frame (X,Y,Z) would align them with the - * phone coordinates (x,y,z). - * - * The rotation can be seen as rotating the phone by an angle theta around - * an axis rot_axis to go from the reference (East-North-Up aligned) device - * orientation to the current device orientation. - * - * The rotation is encoded as the 4 (reordered) components of a unit quaternion: - * sensors_event_t.data[0] = rot_axis.x*sin(theta/2) - * sensors_event_t.data[1] = rot_axis.y*sin(theta/2) - * sensors_event_t.data[2] = rot_axis.z*sin(theta/2) - * sensors_event_t.data[3] = cos(theta/2) - * where - * - rot_axis.x,y,z are the North-East-Up coordinates of a unit length vector - * representing the rotation axis - * - theta is the rotation angle - * - * The quaternion must be of norm 1 (it is a unit quaternion). Failure to ensure - * this will cause erratic client behaviour. - * - * In addition, this sensor reports an estimated heading accuracy. - * sensors_event_t.data[4] = estimated_accuracy (in radians) - * The heading error must be less than estimated_accuracy 95% of the time - * - * This sensor must use a gyroscope and an accelerometer as main orientation - * change input. - * - * This sensor can also include magnetometer input to make up for gyro drift, - * but it cannot be implemented using only a magnetometer. - */ -#define SENSOR_TYPE_ROTATION_VECTOR (11) - -/* - * SENSOR_TYPE_RELATIVE_HUMIDITY - * trigger-mode: on-change - * wake-up sensor: no - * - * A relative humidity sensor measures relative ambient air humidity and - * returns a value in percent. - */ -#define SENSOR_TYPE_RELATIVE_HUMIDITY (12) - -/* - * SENSOR_TYPE_AMBIENT_TEMPERATURE - * trigger-mode: on-change - * wake-up sensor: no - * - * The ambient (room) temperature in degree Celsius. - */ -#define SENSOR_TYPE_AMBIENT_TEMPERATURE (13) - -/* - * SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED - * trigger-mode: continuous - * wake-up sensor: no - * - * Similar to SENSOR_TYPE_MAGNETIC_FIELD, but the hard iron calibration is - * reported separately instead of being included in the measurement. - * Factory calibration and temperature compensation should still be applied to - * the "uncalibrated" measurement. - * Separating away the hard iron calibration estimation allows the system to - * better recover from bad hard iron estimation. - * - * All values are in micro-Tesla (uT) and measure the ambient magnetic - * field in the X, Y and Z axis. Assumptions that the the magnetic field - * is due to the Earth's poles should be avoided. - * - * The uncalibrated_magnetic event contains - * - 3 fields for uncalibrated measurement: x_uncalib, y_uncalib, z_uncalib. - * Each is a component of the measured magnetic field, with soft iron - * and temperature compensation applied, but not hard iron calibration. - * These values should be continuous (no re-calibration should cause a jump). - * - 3 fields for hard iron bias estimates: x_bias, y_bias, z_bias. - * Each field is a component of the estimated hard iron calibration. - * They represent the offsets to apply to the calibrated readings to obtain - * uncalibrated readings (x_uncalib ~= x_calibrated + x_bias) - * These values are expected to jump as soon as the estimate of the hard iron - * changes, and they should be stable the rest of the time. - * - * If this sensor is present, then the corresponding - * SENSOR_TYPE_MAGNETIC_FIELD must be present and both must return the - * same sensor_t::name and sensor_t::vendor. - * - * Minimum filtering should be applied to this sensor. In particular, low pass - * filters should be avoided. - * - * See SENSOR_TYPE_MAGNETIC_FIELD for more information - */ -#define SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED (14) - -/* - * SENSOR_TYPE_GAME_ROTATION_VECTOR - * trigger-mode: continuous - * wake-up sensor: no - * - * Similar to SENSOR_TYPE_ROTATION_VECTOR, but not using the geomagnetic - * field. Therefore the Y axis doesn't point north, but instead to some other - * reference. That reference is allowed to drift by the same order of - * magnitude than the gyroscope drift around the Z axis. - * - * This sensor does not report an estimated heading accuracy: - * sensors_event_t.data[4] is reserved and should be set to 0 - * - * In the ideal case, a phone rotated and returning to the same real-world - * orientation should report the same game rotation vector - * (without using the earth's geomagnetic field). - * - * This sensor must be based on a gyroscope. It cannot be implemented using - * a magnetometer. - * - * see SENSOR_TYPE_ROTATION_VECTOR for more details - */ -#define SENSOR_TYPE_GAME_ROTATION_VECTOR (15) - -/* - * SENSOR_TYPE_GYROSCOPE_UNCALIBRATED - * trigger-mode: continuous - * wake-up sensor: no - * - * All values are in radians/second and measure the rate of rotation - * around the X, Y and Z axis. An estimation of the drift on each axis is - * reported as well. - * - * No gyro-drift compensation shall be performed. - * Factory calibration and temperature compensation should still be applied - * to the rate of rotation (angular speeds). - * - * The coordinate system is the same as is - * used for the acceleration sensor. Rotation is positive in the - * counter-clockwise direction (right-hand rule). That is, an observer - * looking from some positive location on the x, y or z axis at a device - * positioned on the origin would report positive rotation if the device - * appeared to be rotating counter clockwise. Note that this is the - * standard mathematical definition of positive rotation and does not agree - * with the definition of roll given earlier. - * The range should at least be 17.45 rad/s (ie: ~1000 deg/s). - * - * Content of an uncalibrated_gyro event: (units are rad/sec) - * x_uncalib : angular speed (w/o drift compensation) around the X axis - * y_uncalib : angular speed (w/o drift compensation) around the Y axis - * z_uncalib : angular speed (w/o drift compensation) around the Z axis - * x_bias : estimated drift around X axis in rad/s - * y_bias : estimated drift around Y axis in rad/s - * z_bias : estimated drift around Z axis in rad/s - * - * IMPLEMENTATION NOTES: - * - * If the implementation is not able to estimate the drift, then this - * sensor MUST NOT be reported by this HAL. Instead, the regular - * SENSOR_TYPE_GYROSCOPE is used without drift compensation. - * - * If this sensor is present, then the corresponding - * SENSOR_TYPE_GYROSCOPE must be present and both must return the - * same sensor_t::name and sensor_t::vendor. - */ -#define SENSOR_TYPE_GYROSCOPE_UNCALIBRATED (16) - -/* - * SENSOR_TYPE_SIGNIFICANT_MOTION - * trigger-mode: one-shot - * wake-up sensor: yes - * - * A sensor of this type triggers an event each time significant motion - * is detected and automatically disables itself. - * The only allowed value to return is 1.0. - * - * A significant motion is a motion that might lead to a change in the user - * location. - * Examples of such motions are: - * walking, biking, sitting in a moving car, coach or train. - * Examples of situations that should not trigger significant motion: - * - phone in pocket and person is not moving - * - phone is on a table, even if the table shakes a bit due to nearby traffic - * or washing machine - * - * A note on false positive / false negative / power consumption tradeoff - * - The goal of this sensor is to save power. - * - Triggering an event when the user is not moving (false positive) is costly - * in terms of power, so it should be avoided. - * - Not triggering an event when the user is moving (false negative) is - * acceptable as long as it is not done repeatedly. If the user has been - * walking for 10 seconds, not triggering an event within those 10 seconds - * is not acceptable. - * - * IMPORTANT NOTE: this sensor type is very different from other types - * in that it must work when the screen is off without the need of - * holding a partial wake-lock and MUST allow the SoC to go into suspend. - * When significant motion is detected, the sensor must awaken the SoC and - * the event be reported. - * - * If a particular hardware cannot support this mode of operation then this - * sensor type MUST NOT be reported by the HAL. ie: it is not acceptable - * to "emulate" this sensor in the HAL. - * - * The whole point of this sensor type is to save power by keeping the - * SoC in suspend mode when the device is at rest. - * - * When the sensor is not activated, it must also be deactivated in the - * hardware: it must not wake up the SoC anymore, even in case of - * significant motion. - * - * setDelay() has no effect and is ignored. - * Once a "significant motion" event is returned, a sensor of this type - * must disables itself automatically, as if activate(..., 0) had been called. - */ - -#define SENSOR_TYPE_SIGNIFICANT_MOTION (17) - -/* - * SENSOR_TYPE_STEP_DETECTOR - * trigger-mode: special - * wake-up sensor: no - * - * A sensor of this type triggers an event each time a step is taken - * by the user. The only allowed value to return is 1.0 and an event is - * generated for each step. Like with any other event, the timestamp - * indicates when the event (here the step) occurred, this corresponds to when - * the foot hit the ground, generating a high variation in acceleration. - * - * While this sensor operates, it shall not disrupt any other sensors, in - * particular, but not limited to, the accelerometer; which might very well - * be in use as well. - * - * This sensor must be low power. That is, if the step detection cannot be - * done in hardware, this sensor should not be defined. Also, when the - * step detector is activated and the accelerometer is not, only steps should - * trigger interrupts (not accelerometer data). - * - * setDelay() has no impact on this sensor type - */ - -#define SENSOR_TYPE_STEP_DETECTOR (18) - -/* - * SENSOR_TYPE_STEP_COUNTER - * trigger-mode: on-change - * wake-up sensor: no - * - * A sensor of this type returns the number of steps taken by the user since - * the last reboot while activated. The value is returned as a uint64_t and is - * reset to zero only on a system / android reboot. - * - * The timestamp of the event is set to the time when the first step - * for that event was taken. - * See SENSOR_TYPE_STEP_DETECTOR for the signification of the time of a step. - * - * The minimum size of the hardware's internal counter shall be 16 bits - * (this restriction is here to avoid too frequent wake-ups when the - * delay is very large). - * - * IMPORTANT NOTE: this sensor type is different from other types - * in that it must work when the screen is off without the need of - * holding a partial wake-lock and MUST allow the SoC to go into suspend. - * Unlike other sensors, while in suspend mode this sensor must stay active, - * no events are reported during that time but, steps continue to be - * accounted for; an event will be reported as soon as the SoC resumes if - * the timeout has expired. - * - * In other words, when the screen is off and the device allowed to - * go into suspend mode, we don't want to be woken up, regardless of the - * setDelay() value, but the steps shall continue to be counted. - * - * The driver must however ensure that the internal step count never - * overflows. It is allowed in this situation to wake the SoC up so the - * driver can do the counter maintenance. - * - * While this sensor operates, it shall not disrupt any other sensors, in - * particular, but not limited to, the accelerometer; which might very well - * be in use as well. - * - * If a particular hardware cannot support these modes of operation then this - * sensor type MUST NOT be reported by the HAL. ie: it is not acceptable - * to "emulate" this sensor in the HAL. - * - * This sensor must be low power. That is, if the step detection cannot be - * done in hardware, this sensor should not be defined. Also, when the - * step counter is activated and the accelerometer is not, only steps should - * trigger interrupts (not accelerometer data). - * - * The whole point of this sensor type is to save power by keeping the - * SoC in suspend mode when the device is at rest. - */ - -#define SENSOR_TYPE_STEP_COUNTER (19) - -/* - * SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR - * trigger-mode: continuous - * wake-up sensor: no - * - * Similar to SENSOR_TYPE_ROTATION_VECTOR, but using a magnetometer instead - * of using a gyroscope. - * - * This sensor must be based on a magnetometer. It cannot be implemented using - * a gyroscope, and gyroscope input cannot be used by this sensor, as the - * goal of this sensor is to be low power. - * The accelerometer can be (and usually is) used. - * - * Just like SENSOR_TYPE_ROTATION_VECTOR, this sensor reports an estimated - * heading accuracy: - * sensors_event_t.data[4] = estimated_accuracy (in radians) - * The heading error must be less than estimated_accuracy 95% of the time - * - * see SENSOR_TYPE_ROTATION_VECTOR for more details - */ -#define SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR (20) - -/** - * Values returned by the accelerometer in various locations in the universe. - * all values are in SI units (m/s^2) - */ -#define SENSORS_GRAVITY_SUN (275.0f) -#define SENSORS_GRAVITY_MOON (1.6f) -#define SENSORS_GRAVITY_EARTH (9.80665f) -#define SENSORS_GRAVITY_STANDARD (SENSORS_GRAVITY_EARTH) - -/** Maximum magnetic field on Earth's surface */ -#define MAGNETIC_FIELD_EARTH_MAX (60.0f) - -/** Minimum magnetic field on Earth's surface */ -#define MAGNETIC_FIELD_EARTH_MIN (30.0f) - -/** Average sea level pressure is 1013.25 hPa */ -#define SENSORS_PRESSURE_SEALEVELHPA (1013.25F) - -/** Degrees/s to rad/s multiplier */ -#define SENSORS_DPS_TO_RADS (0.017453293F) -/** Gauss to micro-Tesla multiplier */ -#define SENSORS_GAUSS_TO_MICROTESLA (100) - -/** - * status of orientation sensor - */ -#define SENSOR_STATUS_UNRELIABLE 0 -#define SENSOR_STATUS_ACCURACY_LOW 1 -#define SENSOR_STATUS_ACCURACY_MEDIUM 2 -#define SENSOR_STATUS_ACCURACY_HIGH 3 - -/** - * sensor event data - */ -typedef struct +struct rt_sensor_config { - union - { - float v[3]; - struct - { - float x; - float y; - float z; - }; - struct - { - float azimuth; - float pitch; - float roll; - }; - }; - int8_t status; - uint8_t reserved[3]; -} sensors_vec_t; - -/** - * sensor raw vector data - */ -typedef struct -{ - struct - { - int16_t x; - int16_t y; - int16_t z; - }; - - int8_t status; - uint8_t reserved[1]; -} sensors_raw_vec_t; - -/** - * uncalibrated gyroscope and magnetometer event data - */ -typedef struct -{ - union - { - float uncalib[3]; - struct - { - float x_uncalib; - float y_uncalib; - float z_uncalib; - }; - }; - union - { - float bias[3]; - struct - { - float x_bias; - float y_bias; - float z_bias; - }; - }; -} uncalibrated_event_t; - -typedef struct meta_data_event -{ - int32_t what; - int32_t sensor; -} meta_data_event_t; - -/** - * Union of the various types of sensor data - * that can be returned. - */ -typedef struct sensors_event_t -{ - /* must be sizeof(struct sensors_event_t) */ - int32_t version; - - /* sensor identifier */ - int32_t sensor; - - /* sensor type */ - int32_t type; - - /* reserved */ - int32_t reserved0; - - /* time is in nanosecond */ - int64_t timestamp; - - union - { - union - { - float data[16]; - - /* acceleration values are in meter per second per second (m/s^2) */ - sensors_vec_t acceleration; - /* raw acceleration data */ - sensors_raw_vec_t raw_acceleration; - - /* magnetic vector values are in micro-Tesla (uT) */ - sensors_vec_t magnetic; - /* raw magnetic data */ - sensors_raw_vec_t raw_magnetic; - - /* orientation values are in degrees */ - sensors_vec_t orientation; - - /* gyroscope values are in rad/s */ - sensors_vec_t gyro; - /* raw gyroscope data */ - sensors_raw_vec_t raw_gyro; - - /* temperature is in degrees centigrade (Celsius) */ - float temperature; - - /* distance in centimeters */ - float distance; - - /* light in SI lux units */ - float light; - - /* pressure in hectopascal (hPa) */ - float pressure; - - /* relative humidity in percent */ - float relative_humidity; - - /* uncalibrated gyroscope values are in rad/s */ - uncalibrated_event_t uncalibrated_gyro; - - /* uncalibrated magnetometer values are in micro-Teslas */ - uncalibrated_event_t uncalibrated_magnetic; - - /* this is a special event. see SENSOR_TYPE_META_DATA above. - * sensors_meta_data_event_t events are all reported with a type of - * SENSOR_TYPE_META_DATA. The handle is ignored and must be zero. - */ - meta_data_event_t meta_data; - }; - - union - { - uint64_t data[8]; - - /* step-counter */ - uint64_t step_counter; - } u64; - }; - uint32_t reserved1[4]; -} sensors_event_t; - -/* see SENSOR_TYPE_META_DATA */ -typedef sensors_event_t sensors_meta_data_event_t; - -typedef struct sensor_t -{ - /* Name of this sensor. - * All sensors of the same "type" must have a different "name". - */ - const char *name; - - /* vendor of the hardware part */ - const char *vendor; - - /* version of the hardware part + driver. The value of this field - * must increase when the driver is updated in a way that changes the - * output of this sensor. This is important for fused sensors when the - * fusion algorithm is updated. - */ - int version; - - /* handle that identifies this sensors. This handle is used to reference - * this sensor throughout the HAL API. - */ - int handle; - - /* this sensor's type. */ - int type; - - /* maximum range of this sensor's value in SI units */ - float maxRange; - - /* smallest difference between two values reported by this sensor */ - float resolution; - - /* rough estimate of this sensor's power consumption in mA */ - float power; - - /* this value depends on the trigger mode: - * - * continuous: minimum sample period allowed in microseconds - * on-change : 0 - * one-shot :-1 - * special : 0, unless otherwise noted - */ - int32_t minDelay; - - /* number of events reserved for this sensor in the batch mode FIFO. - * If there is a dedicated FIFO for this sensor, then this is the - * size of this FIFO. If the FIFO is shared with other sensors, - * this is the size reserved for that sensor and it can be zero. - */ - uint32_t fifoReservedEventCount; - - /* maximum number of events of this sensor that could be batched. - * This is especially relevant when the FIFO is shared between - * several sensors; this value is then set to the size of that FIFO. - */ - uint32_t fifoMaxEventCount; - - /* reserved fields, must be zero */ - void *reserved[6]; -} sensor_t; - -enum SensorMode -{ - SENSOR_MODE_RAW, - SENSOR_MODE_CALIBRATED, - SENSOR_MODE_NORMAL, + struct rt_sensor_intf intf; /* sensor interface config */ + struct rt_device_pin_mode irq_pin; /* Interrupt pin, The purpose of this pin is to notification read data */ + rt_uint8_t mode; /* sensor work mode */ + rt_uint8_t power; /* sensor power mode */ + rt_uint16_t odr; /* sensor out data rate */ + rt_int32_t range; /* sensor range of measurement */ }; -enum SensorAccelRange +struct rt_sensor_device { - SENSOR_ACCEL_RANGE_2G, - SENSOR_ACCEL_RANGE_4G, - SENSOR_ACCEL_RANGE_8G, - SENSOR_ACCEL_RANGE_16G, + struct rt_device parent; /* The standard device */ + + struct rt_sensor_info info; /* The sensor info data */ + struct rt_sensor_config config; /* The sensor config data */ + + void *data_buf; /* The buf of the data received */ + rt_size_t data_len; /* The size of the data received */ + + struct rt_sensor_ops *ops; /* The sensor ops */ + + struct rt_sensor_module *module; /* The sensor module */ }; -#define SENSOR_ACCEL_SENSITIVITY_2G ((float)2/32768) -#define SENSOR_ACCEL_SENSITIVITY_4G ((float)4/32768) -#define SENSOR_ACCEL_SENSITIVITY_8G ((float)8/32768) -#define SENSOR_ACCEL_SENSITIVITY_16G ((float)16/32768) +typedef struct rt_sensor_device *rt_sensor_t; -enum SensorGyroRange +struct rt_sensor_module { - SENSOR_GYRO_RANGE_250DPS, - SENSOR_GYRO_RANGE_500DPS, - SENSOR_GYRO_RANGE_1000DPS, - SENSOR_GYRO_RANGE_2000DPS, + rt_mutex_t lock; /* The module lock */ + + rt_sensor_t sen[RT_SEN_MODULE_MAX]; /* The module contains a list of sensors */ + rt_uint8_t sen_num; /* Number of sensors contained in the module */ }; -#define SENSOR_GYRO_SENSITIVITY_250DPS (0.00875F) -#define SENSOR_GYRO_SENSITIVITY_500DPS (0.0175F) -#define SENSOR_GYRO_SENSITIVITY_1000DPS (0.035F) -#define SENSOR_GYRO_SENSITIVITY_2000DPS (0.070F) -enum SensorDataRate +/* 3-axis Data Type */ +struct sensor_3_axis { - SENSOR_DATARATE_3200HZ, - SENSOR_DATARATE_1600HZ, - SENSOR_DATARATE_800HZ, - SENSOR_DATARATE_400HZ, - SENSOR_DATARATE_200HZ, - SENSOR_DATARATE_100HZ, - SENSOR_DATARATE_50HZ, - SENSOR_DATARATE_25HZ, - SENSOR_DATARATE_12_5HZ, - SENSOR_DATARATE_6_25HZ, - SENSOR_DATARATE_3_13HZ, - SENSOR_DATARATE_1_56HZ, - SENSOR_DATARATE_0_78HZ, - SENSOR_DATARATE_0_39HZ, - SENSOR_DATARATE_0_20HZ, - SENSOR_DATARATE_0_10HZ, + rt_int32_t x; + rt_int32_t y; + rt_int32_t z; }; -/** - * Sensor Configuration - */ -typedef struct SensorConfig +struct rt_sensor_data { - int mode; - - enum SensorDataRate data_rate; - - union range + rt_uint32_t timestamp; /* The timestamp when the data was received */ + rt_uint8_t type; /* The sensor type of the data */ + union { - int range; - enum SensorAccelRange accel_range; - enum SensorGyroRange gyro_range; - } range; -}SensorConfig; - -typedef void (*SensorEventHandler_t)(void *user_data); - -#ifdef __cplusplus -class SensorBase; -class SensorManager; - -/** - * Sensor Base Class - */ -class SensorBase -{ -private: - int type; - -public: - SensorBase(int type); - ~SensorBase(); - - virtual int configure(SensorConfig *config) = 0; - virtual int activate(int enable) = 0; - - virtual int poll(sensors_event_t *events) = 0; - virtual void getSensor(struct sensor_t *sensor) = 0; - - int getType(void); - - int setConfig(SensorConfig *config); - int getConfig(SensorConfig *config); - - int subscribe(SensorEventHandler_t handler, void *user_data); - int publish(void); - -protected: - SensorBase *next; - SensorBase *prev; - - /* sensor configuration */ - SensorConfig config; - - SensorEventHandler_t evtHandler; - void *userData; - - friend class SensorManager; + struct sensor_3_axis acce; /* Accelerometer. unit: mG */ + struct sensor_3_axis gyro; /* Gyroscope. unit: mdps */ + struct sensor_3_axis mag; /* Magnetometer. unit: mGauss */ + rt_int32_t temp; /* Temperature. unit: dCelsius */ + rt_int32_t humi; /* Relative humidity. unit: permillage */ + rt_int32_t baro; /* Pressure. unit: pascal (Pa) */ + rt_int32_t light; /* Light. unit: lux */ + rt_int32_t proximity; /* Distance. unit: centimeters */ + rt_int32_t hr; /* Heat rate. unit: HZ */ + rt_int32_t tvoc; /* TVOC. unit: permillage */ + rt_int32_t noise; /* Noise Loudness. unit: HZ */ + rt_uint32_t step; /* Step sensor. unit: 1 */ + }data; }; -/** - * Sensor Manager - */ -class SensorManager +struct rt_sensor_ops { -public: - SensorManager(); - ~SensorManager(); - - static int registerSensor(SensorBase *sensor); - static int unregisterSensor(SensorBase *sensor); - - static SensorBase *getDefaultSensor(int type); - static int subscribe(int type, SensorEventHandler_t handler, void *user_data); - - static int sensorEventReady(SensorBase *sensor); - static int pollSensor(SensorBase *sensor, sensors_event_t *events, int number, int duration); + rt_size_t (*fetch_data)(struct rt_sensor_device *sensor, void *buf, rt_size_t len); + rt_err_t (*control)(struct rt_sensor_device *sensor, int cmd, void *arg); }; -#endif - -/* C programming language APIs */ -/* rt_sensor_t is a C typedef for SensorBase */ -typedef void* rt_sensor_t; - -#ifdef __cplusplus -extern "C" { -#endif - -rt_sensor_t rt_sensor_get_default(int type); - -int rt_sensor_subscribe(rt_sensor_t sensor, SensorEventHandler_t handler, void *user_data); -int rt_sensor_activate (rt_sensor_t sensor, int enable); -int rt_sensor_configure(rt_sensor_t sensor, SensorConfig *config); -int rt_sensor_poll(rt_sensor_t sensor, sensors_event_t *event); - -#ifdef __cplusplus -} -#endif +int rt_hw_sensor_register(rt_sensor_t sensor, + const char *name, + rt_uint32_t flag, + void *data); #endif diff --git a/components/drivers/sensors/sensor_test.c b/components/drivers/sensors/sensor_test.c new file mode 100644 index 0000000000..0221167e83 --- /dev/null +++ b/components/drivers/sensors/sensor_test.c @@ -0,0 +1,361 @@ +/* + * Copyright (c) 2006-2018, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2019-01-31 flybreak first version + */ + +#include "sensor.h" + +#define DBG_ENABLE +#define DBG_LEVEL DBG_INFO +#define DBG_SECTION_NAME "sensor.test" +#define DBG_COLOR +#include + +#include +#include + +static rt_sem_t sensor_rx_sem = RT_NULL; + +static void sensor_show_data(rt_size_t num, rt_sensor_t sensor, struct rt_sensor_data *sensor_data) +{ + switch (sensor->info.type) + { + case RT_SEN_CLASS_ACCE: + LOG_I("num:%3d, x:%5d, y:%5d, z:%5d, timestamp:%5d", num, sensor_data->data.acce.x, sensor_data->data.acce.y, sensor_data->data.acce.z, sensor_data->timestamp); + break; + case RT_SEN_CLASS_GYRO: + LOG_I("num:%3d, x:%8d, y:%8d, z:%8d, timestamp:%5d", num, sensor_data->data.gyro.x, sensor_data->data.gyro.y, sensor_data->data.gyro.z, sensor_data->timestamp); + break; + case RT_SEN_CLASS_MAG: + LOG_I("num:%3d, x:%5d, y:%5d, z:%5d, timestamp:%5d", num, sensor_data->data.mag.x, sensor_data->data.mag.y, sensor_data->data.mag.z, sensor_data->timestamp); + break; + case RT_SEN_CLASS_HUMI: + LOG_I("num:%3d, humi:%3d.%d%%, timestamp:%5d", num, sensor_data->data.humi / 10, sensor_data->data.humi % 10, sensor_data->timestamp); + break; + case RT_SEN_CLASS_TEMP: + LOG_I("num:%3d, temp:%3d.%dC, timestamp:%5d", num, sensor_data->data.temp / 10, sensor_data->data.temp % 10, sensor_data->timestamp); + break; + case RT_SEN_CLASS_BARO: + LOG_I("num:%3d, press:%5d, timestamp:%5d", num, sensor_data->data.baro, sensor_data->timestamp); + break; + case RT_SEN_CLASS_STEP: + LOG_I("num:%3d, step:%5d, timestamp:%5d", num, sensor_data->data.step, sensor_data->timestamp); + break; + default: + break; + } +} + +rt_err_t rx_callback(rt_device_t dev, rt_size_t size) +{ + rt_sem_release(sensor_rx_sem); + return 0; +} + +static void sensor_fifo_rx_entry(void *parameter) +{ + rt_device_t dev = parameter; + rt_sensor_t sensor = parameter; + struct rt_sensor_data *data = RT_NULL; + struct rt_sensor_info info; + rt_size_t res, i; + + rt_device_control(dev, RT_SEN_CTRL_GET_INFO, &info); + + data = rt_malloc(sizeof(struct rt_sensor_data) * info.fifo_max); + if (data == RT_NULL) + { + LOG_E("Memory allocation failed!"); + } + + while (1) + { + rt_sem_take(sensor_rx_sem, RT_WAITING_FOREVER); + + res = rt_device_read(dev, 0, data, info.fifo_max); + for (i = 0; i < res; i++) + { + sensor_show_data(i, sensor, &data[i]); + } + } +} + +static void sensor_fifo(int argc, char **argv) +{ + static rt_thread_t tid1 = RT_NULL; + rt_device_t dev = RT_NULL; + rt_sensor_t sensor; + + dev = rt_device_find(argv[1]); + if (dev == RT_NULL) + { + LOG_E("Can't find device:%s", argv[1]); + return; + } + sensor = (rt_sensor_t)dev; + + if (sensor_rx_sem == RT_NULL) + { + sensor_rx_sem = rt_sem_create("sen_rx_sem", 0, RT_IPC_FLAG_FIFO); + } + else + { + LOG_E("The thread is running, please reboot and try again"); + return; + } + + tid1 = rt_thread_create("sen_rx_thread", + sensor_fifo_rx_entry, sensor, + 1024, + 15, 5); + + if (tid1 != RT_NULL) + rt_thread_startup(tid1); + + rt_device_set_rx_indicate(dev, rx_callback); + + if (rt_device_open(dev, RT_SEN_FLAG_FIFO) != RT_EOK) + { + LOG_E("open device failed!"); + return; + } + rt_device_control(dev, RT_SEN_CTRL_SET_ODR, (void *)20); +} +#ifdef FINSH_USING_MSH +MSH_CMD_EXPORT(sensor_fifo, Sensor fifo mode test function); +#endif + +static void sensor_irq_rx_entry(void *parameter) +{ + rt_device_t dev = parameter; + rt_sensor_t sensor = parameter; + struct rt_sensor_data data; + rt_size_t res, i = 0; + + while (1) + { + rt_sem_take(sensor_rx_sem, RT_WAITING_FOREVER); + + res = rt_device_read(dev, 0, &data, 1); + if (res == 1) + { + sensor_show_data(i++, sensor, &data); + } + } +} + +static void sensor_int(int argc, char **argv) +{ + static rt_thread_t tid1 = RT_NULL; + rt_device_t dev = RT_NULL; + rt_sensor_t sensor; + + dev = rt_device_find(argv[1]); + if (dev == RT_NULL) + { + LOG_E("Can't find device:%s", argv[1]); + return; + } + sensor = (rt_sensor_t)dev; + + if (sensor_rx_sem == RT_NULL) + { + sensor_rx_sem = rt_sem_create("sen_rx_sem", 0, RT_IPC_FLAG_FIFO); + } + else + { + LOG_E("The thread is running, please reboot and try again"); + return; + } + + tid1 = rt_thread_create("sen_rx_thread", + sensor_irq_rx_entry, sensor, + 1024, + 15, 5); + + if (tid1 != RT_NULL) + rt_thread_startup(tid1); + + rt_device_set_rx_indicate(dev, rx_callback); + + if (rt_device_open(dev, RT_DEVICE_FLAG_INT_RX) != RT_EOK) + { + LOG_E("open device failed!"); + return; + } + rt_device_control(dev, RT_SEN_CTRL_SET_ODR, (void *)20); +} +#ifdef FINSH_USING_MSH +MSH_CMD_EXPORT(sensor_int, Sensor interrupt mode test function); +#endif + +static void sensor_polling(int argc, char **argv) +{ + uint16_t num = 10; + rt_device_t dev = RT_NULL; + rt_sensor_t sensor; + struct rt_sensor_data data; + rt_size_t res, i; + + dev = rt_device_find(argv[1]); + if (dev == RT_NULL) + { + LOG_E("Can't find device:%s", argv[1]); + return; + } + if (argc > 2) + num = atoi(argv[2]); + + sensor = (rt_sensor_t)dev; + + if (rt_device_open(dev, RT_DEVICE_FLAG_RDWR) != RT_EOK) + { + LOG_E("open device failed!"); + return; + } + rt_device_control(dev, RT_SEN_CTRL_SET_ODR, (void *)100); + + for (i = 0; i < num; i++) + { + res = rt_device_read(dev, 0, &data, 1); + if (res != 1) + { + LOG_E("read data failed!size is %d", res); + } + else + { + sensor_show_data(i, sensor, &data); + } + rt_thread_mdelay(100); + } + rt_device_close(dev); +} +#ifdef FINSH_USING_MSH +MSH_CMD_EXPORT(sensor_polling, Sensor polling mode test function); +#endif + +static void sensor(int argc, char **argv) +{ + static rt_device_t dev = RT_NULL; + struct rt_sensor_data data; + rt_size_t res, i; + + /* If the number of arguments less than 2 */ + if (argc < 2) + { + rt_kprintf("\n"); + rt_kprintf("sensor [OPTION] [PARAM]\n"); + rt_kprintf(" probe Probe sensor by given name\n"); + rt_kprintf(" info Get sensor info\n"); + rt_kprintf(" sr Set range to var\n"); + rt_kprintf(" sm Set work mode to var\n"); + rt_kprintf(" sp Set power mode to var\n"); + rt_kprintf(" sodr Set output date rate to var\n"); + rt_kprintf(" read [num] Read [num] times sensor\n"); + rt_kprintf(" num default 5\n"); + return ; + } + else if (!strcmp(argv[1], "info")) + { + struct rt_sensor_info info; + rt_device_control(dev, RT_SEN_CTRL_GET_INFO, &info); + rt_kprintf("vendor :%d\n", info.vendor); + rt_kprintf("model :%s\n", info.model); + rt_kprintf("unit :%d\n", info.unit); + rt_kprintf("range_max :%d\n", info.range_max); + rt_kprintf("range_min :%d\n", info.range_min); + rt_kprintf("period_min:%d\n", info.period_min); + rt_kprintf("fifo_max :%d\n", info.fifo_max); + } + else if (!strcmp(argv[1], "read")) + { + uint16_t num = 5; + + if (dev == RT_NULL) + { + LOG_W("Please probe sensor device first!"); + return ; + } + if (argc == 3) + { + num = atoi(argv[2]); + } + + for (i = 0; i < num; i++) + { + res = rt_device_read(dev, 0, &data, 1); + if (res != 1) + { + LOG_E("read data failed!size is %d", res); + } + else + { + sensor_show_data(i, (rt_sensor_t)dev, &data); + } + rt_thread_mdelay(100); + } + } + else if (argc == 3) + { + if (!strcmp(argv[1], "probe")) + { + rt_uint8_t reg = 0xFF; + if (dev) + { + rt_device_close(dev); + } + + dev = rt_device_find(argv[2]); + if (dev == RT_NULL) + { + LOG_E("Can't find device:%s", argv[1]); + return; + } + if (rt_device_open(dev, RT_DEVICE_FLAG_RDWR) != RT_EOK) + { + LOG_E("open device failed!"); + return; + } + rt_device_control(dev, RT_SEN_CTRL_GET_ID, ®); + LOG_I("device id: 0x%x!", reg); + + } + else if (dev == RT_NULL) + { + LOG_W("Please probe sensor first!"); + return ; + } + else if (!strcmp(argv[1], "sr")) + { + rt_device_control(dev, RT_SEN_CTRL_SET_RANGE, (void *)atoi(argv[2])); + } + else if (!strcmp(argv[1], "sm")) + { + rt_device_control(dev, RT_SEN_CTRL_SET_MODE, (void *)atoi(argv[2])); + } + else if (!strcmp(argv[1], "sp")) + { + rt_device_control(dev, RT_SEN_CTRL_SET_POWER, (void *)atoi(argv[2])); + } + else if (!strcmp(argv[1], "sodr")) + { + rt_device_control(dev, RT_SEN_CTRL_SET_ODR, (void *)atoi(argv[2])); + } + else + { + LOG_W("Unknown command, please enter 'sensor' get help information!"); + } + } + else + { + LOG_W("Unknown command, please enter 'sensor' get help information!"); + } +} +#ifdef FINSH_USING_MSH +MSH_CMD_EXPORT(sensor, sensor test function); +#endif diff --git a/components/finsh/cmd.c b/components/finsh/cmd.c index 0a30aee809..680d9d01d7 100644 --- a/components/finsh/cmd.c +++ b/components/finsh/cmd.c @@ -800,6 +800,7 @@ static char *const device_type_str[] = "Portal Device", "Timer Device", "Miscellaneous Device", + "Sensor Device", "Unknown" }; diff --git a/include/rtdef.h b/include/rtdef.h index 859278e849..bb11bf88ff 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -846,6 +846,7 @@ enum rt_device_class_type RT_Device_Class_Portal, /**< Portal device */ RT_Device_Class_Timer, /**< Timer device */ RT_Device_Class_Miscellaneous, /**< Miscellaneous device */ + RT_Device_Class_Sensor, /**< Sensor device */ RT_Device_Class_Unknown /**< unknown device */ }; -- cgit v1.3.1 From 1487a4f732d9fa5382d979a5b08f981d93a58aee Mon Sep 17 00:00:00 2001 From: BernardXiong Date: Tue, 26 Mar 2019 01:03:39 +0000 Subject: [Kernel] Support ARCH data types definitions --- include/rtdef.h | 2 ++ src/Kconfig | 9 +++++++++ 2 files changed, 11 insertions(+) (limited to 'include/rtdef.h') diff --git a/include/rtdef.h b/include/rtdef.h index bb11bf88ff..9af4320112 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -58,6 +58,7 @@ extern "C" { (RT_SUBVERSION * 100) + RT_REVISION) /* RT-Thread basic data type definitions */ +#ifndef RT_USING_ARCH_DATA_TYPE typedef signed char rt_int8_t; /**< 8bit integer type */ typedef signed short rt_int16_t; /**< 16bit integer type */ typedef signed int rt_int32_t; /**< 32bit integer type */ @@ -72,6 +73,7 @@ typedef unsigned long rt_uint64_t; /**< 64bit unsigned inte typedef signed long long rt_int64_t; /**< 64bit integer type */ typedef unsigned long long rt_uint64_t; /**< 64bit unsigned integer type */ #endif +#endif typedef int rt_bool_t; /**< boolean type */ typedef long rt_base_t; /**< Nbit CPU related date type */ diff --git a/src/Kconfig b/src/Kconfig index fbfae65882..c123f53b92 100644 --- a/src/Kconfig +++ b/src/Kconfig @@ -8,6 +8,15 @@ config RT_NAME_MAX Each kernel object, such as thread, timer, semaphore etc, has a name, the RT_NAME_MAX is the maximal size of this object name. +config RT_USING_ARCH_DATA_TYPE + bool "Use the data types defined in ARCH_CPU" + default n + help + For the data type like, `rt_uint8/int8_t, rt_uint16/int16_t, rt_uint32/int32_t`, + BSP can define these basic data types in ARCH_CPU level. + + Please re-define these data types in bsp_project.h file. + config RT_USING_SMP bool "Enable SMP(Symmetric multiprocessing)" default n -- cgit v1.3.1 From fde1346d5b55845fa6dee9da6de489b4f66d977a Mon Sep 17 00:00:00 2001 From: yangfasheng Date: Sun, 14 Apr 2019 13:33:29 +0800 Subject: add RTGRAPHIC_PIXEL_FORMAT_COLOR to graphic deice Signed-off-by: yangfasheng --- include/rtdef.h | 1 + 1 file changed, 1 insertion(+) (limited to 'include/rtdef.h') diff --git a/include/rtdef.h b/include/rtdef.h index 9af4320112..9b12093dc7 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -1020,6 +1020,7 @@ enum RTGRAPHIC_PIXEL_FORMAT_ABGR888, RTGRAPHIC_PIXEL_FORMAT_ARGB565, RTGRAPHIC_PIXEL_FORMAT_ALPHA, + RTGRAPHIC_PIXEL_FORMAT_COLOR, }; /** -- cgit v1.3.1 From fa697a763f5cbece6b886cf2eca54b2dd28f718d Mon Sep 17 00:00:00 2001 From: shaojinchun Date: Fri, 19 Apr 2019 14:57:50 +0800 Subject: 修改sem中的value成员变量和赋值参数类型相同 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/rtdef.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include/rtdef.h') diff --git a/include/rtdef.h b/include/rtdef.h index 9b12093dc7..8c7e6e8c43 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -655,7 +655,7 @@ struct rt_semaphore { struct rt_ipc_object parent; /**< inherit from ipc_object */ - rt_uint16_t value; /**< value of semaphore. */ + rt_uint32_t value; /**< value of semaphore. */ }; typedef struct rt_semaphore *rt_sem_t; #endif -- cgit v1.3.1 From 7bcee9bcb14f337efb6fcacecc1501d01624c0a3 Mon Sep 17 00:00:00 2001 From: shaojinchun Date: Wed, 24 Apr 2019 09:14:00 +0800 Subject: semaphore结构中value仍改为uint16_t,加入对其设置范围的检测,加入对齐变量 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/rtdef.h | 3 ++- src/ipc.c | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) (limited to 'include/rtdef.h') diff --git a/include/rtdef.h b/include/rtdef.h index 8c7e6e8c43..743b91d959 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -655,7 +655,8 @@ struct rt_semaphore { struct rt_ipc_object parent; /**< inherit from ipc_object */ - rt_uint32_t value; /**< value of semaphore. */ + rt_uint16_t value; /**< value of semaphore. */ + rt_uint16_t reserved; /**< reserved field */ }; typedef struct rt_semaphore *rt_sem_t; #endif diff --git a/src/ipc.c b/src/ipc.c index 7f603cfc4d..74faf6ac7e 100644 --- a/src/ipc.c +++ b/src/ipc.c @@ -201,6 +201,7 @@ rt_err_t rt_sem_init(rt_sem_t sem, rt_uint8_t flag) { RT_ASSERT(sem != RT_NULL); + RT_ASSERT(value < 0x10000U); /* init object */ rt_object_init(&(sem->parent.parent), RT_Object_Class_Semaphore, name); @@ -209,7 +210,7 @@ rt_err_t rt_sem_init(rt_sem_t sem, rt_ipc_object_init(&(sem->parent)); /* set init value */ - sem->value = value; + sem->value = (rt_uint16_t)value; /* set parent */ sem->parent.parent.flag = flag; @@ -261,6 +262,7 @@ rt_sem_t rt_sem_create(const char *name, rt_uint32_t value, rt_uint8_t flag) rt_sem_t sem; RT_DEBUG_NOT_IN_INTERRUPT; + RT_ASSERT(value < 0x10000U); /* allocate object */ sem = (rt_sem_t)rt_object_allocate(RT_Object_Class_Semaphore, name); -- cgit v1.3.1 From 6cdfb2ac92d8422136f926024b2c2f969fce6b9e Mon Sep 17 00:00:00 2001 From: shaojinchun Date: Thu, 9 May 2019 19:28:52 +0800 Subject: fix signal code --- include/rtdef.h | 3 + libcpu/arm/cortex-a/context_gcc.S | 81 ++++++------------ libcpu/arm/cortex-a/start_gcc.S | 39 +++++++-- src/scheduler.c | 84 +++++++++++++----- src/signal.c | 176 ++++++++++++++++++++++++++++++-------- src/thread.c | 2 + 6 files changed, 267 insertions(+), 118 deletions(-) (limited to 'include/rtdef.h') diff --git a/include/rtdef.h b/include/rtdef.h index 743b91d959..253333253a 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -495,6 +495,7 @@ typedef siginfo_t rt_siginfo_t; #define RT_THREAD_STAT_SIGNAL 0x10 #define RT_THREAD_STAT_SIGNAL_READY (RT_THREAD_STAT_SIGNAL | RT_THREAD_READY) #define RT_THREAD_STAT_SIGNAL_WAIT 0x20 +#define RT_THREAD_STAT_SIGNAL_PENDING 0x40 #define RT_THREAD_STAT_SIGNAL_MASK 0xf0 /** @@ -596,7 +597,9 @@ struct rt_thread rt_sigset_t sig_pending; /**< the pending signals */ rt_sigset_t sig_mask; /**< the mask bits of signal */ +#ifndef RT_USING_SMP void *sig_ret; /**< the return stack pointer from signal */ +#endif rt_sighandler_t *sig_vectors; /**< vectors of signal handler */ void *si_list; /**< the signal infor list */ #endif diff --git a/libcpu/arm/cortex-a/context_gcc.S b/libcpu/arm/cortex-a/context_gcc.S index af5c516e4d..dff7a1de68 100644 --- a/libcpu/arm/cortex-a/context_gcc.S +++ b/libcpu/arm/cortex-a/context_gcc.S @@ -46,16 +46,7 @@ rt_hw_context_switch_to: mov r0, r1 bl rt_cpus_lock_status_restore #endif /*RT_USING_SMP*/ - -#ifdef RT_USING_LWP - ldmfd sp, {r13, r14}^ @ pop usr_sp usr_lr - add sp, #8 -#endif - - ldmfd sp!, {r4} @ pop new task spsr - msr spsr_cxsf, r4 - - ldmfd sp!, {r0-r12, lr, pc}^ @ pop new task r0-r12, lr & pc + b rt_hw_context_switch_exit .section .bss.share.isr _guest_switch_lvl: @@ -93,15 +84,7 @@ rt_hw_context_switch: mov r0, r2 bl rt_cpus_lock_status_restore #endif /*RT_USING_SMP*/ - -#ifdef RT_USING_LWP - ldmfd sp, {r13, r14}^ @ pop usr_sp usr_lr - add sp, #8 -#endif - - ldmfd sp!, {r4} @ pop new task cpsr to spsr - msr spsr_cxsf, r4 - ldmfd sp!, {r0-r12, lr, pc}^ @ pop new task r0-r12, lr & pc, copy spsr to cpsr + b rt_hw_context_switch_exit /* * void rt_hw_context_switch_interrupt(rt_uint32 from, rt_uint32 to); @@ -123,51 +106,19 @@ rt_hw_context_switch: .globl rt_hw_context_switch_interrupt rt_hw_context_switch_interrupt: #ifdef RT_USING_SMP - /* r0 :irq_mod context + /* r0 :svc_mod context * r1 :addr of from_thread's sp * r2 :addr of to_thread's sp * r3 :to_thread's tcb */ - @ r0 point to {r0-r3} in stack - push {r1 - r3} - mov r1, r0 - add r0, r0, #4*4 - ldmfd r0!, {r4-r12,lr}@ reload saved registers - mrs r3, spsr @ get cpsr of interrupt thread - sub r2, lr, #4 @ save old task's pc to r2 - msr cpsr_c, #I_Bit|F_Bit|Mode_SVC - - stmfd sp!, {r2} @ push old task's pc - stmfd sp!, {r4-r12,lr}@ push old task's lr,r12-r4 - ldmfd r1, {r4-r7} @ restore r0-r3 of the interrupt thread - stmfd sp!, {r4-r7} @ push old task's r0-r3 - stmfd sp!, {r3} @ push old task's cpsr - -#ifdef RT_USING_LWP - stmfd sp, {r13,r14}^ @push usr_sp usr_lr - sub sp, #8 -#endif - - msr cpsr_c, #I_Bit|F_Bit|Mode_IRQ - pop {r1 - r3} - mov sp, r0 - msr cpsr_c, #I_Bit|F_Bit|Mode_SVC - str sp, [r1] + str r0, [r1] ldr sp, [r2] mov r0, r3 bl rt_cpus_lock_status_restore -#ifdef RT_USING_LWP - ldmfd sp, {r13,r14}^ @pop usr_sp usr_lr - add sp, #8 -#endif - - ldmfd sp!, {r4} @ pop new task's cpsr to spsr - msr spsr_cxsf, r4 - - ldmfd sp!, {r0-r12,lr,pc}^ @ pop new task's r0-r12,lr & pc, copy spsr to cpsr + b rt_hw_context_switch_exit #else /*RT_USING_SMP*/ ldr r2, =rt_thread_switch_interrupt_flag @@ -183,3 +134,25 @@ _reswitch: str r1, [r2] bx lr #endif /*RT_USING_SMP*/ + +.global rt_hw_context_switch_exit +rt_hw_context_switch_exit: + +#ifdef RT_USING_SMP +#ifdef RT_USING_SIGNALS + mov r0, sp + cps #Mode_IRQ + bl rt_signal_check + cps #Mode_SVC + mov sp, r0 +#endif +#endif + +#ifdef RT_USING_LWP + ldmfd sp, {r13, r14}^ /* usr_sp, usr_lr */ + add sp, #8 +#endif + ldmfd sp!, {r1} + msr spsr_cxsf, r1 /* original mode */ + ldmfd sp!, {r0-r12,lr,pc}^ /* irq return */ + diff --git a/libcpu/arm/cortex-a/start_gcc.S b/libcpu/arm/cortex-a/start_gcc.S index 51026b7ed5..014846f3aa 100644 --- a/libcpu/arm/cortex-a/start_gcc.S +++ b/libcpu/arm/cortex-a/start_gcc.S @@ -11,7 +11,6 @@ */ #include "rtconfig.h" - .equ Mode_USR, 0x10 .equ Mode_FIQ, 0x11 .equ Mode_IRQ, 0x12 @@ -158,20 +157,48 @@ vector_fiq: vector_irq: #ifdef RT_USING_SMP clrex + + stmfd sp!, {r0, r1} + cps #Mode_SVC + mov r0, sp /* svc_sp */ + mov r1, lr /* svc_lr */ + + cps #Mode_IRQ + sub lr, #4 + stmfd r0!, {r1, lr} /* svc_lr, svc_pc */ + stmfd r0!, {r2 - r12} + ldmfd sp!, {r1, r2} /* original r0, r1 */ + stmfd r0!, {r1 - r2} + mrs r1, spsr /* original mode */ + stmfd r0!, {r1} + +#ifdef RT_USING_LWP + stmfd r0, {r13, r14}^ /* usr_sp, usr_lr */ + sub r0, #8 #endif - stmfd sp!, {r0-r12,lr} + /* now irq stack is clean */ + /* r0 is task svc_sp */ + /* backup r0 -> r8 */ + mov r8, r0 bl rt_interrupt_enter bl rt_hw_trap_irq bl rt_interrupt_leave -#ifdef RT_USING_SMP - mov r0, sp + cps #Mode_SVC + mov sp, r8 + mov r0, r8 bl rt_scheduler_do_irq_switch - ldmfd sp!, {r0-r12,lr} - subs pc, lr, #4 + b rt_hw_context_switch_exit + #else + stmfd sp!, {r0-r12,lr} + + bl rt_interrupt_enter + bl rt_hw_trap_irq + bl rt_interrupt_leave + @ if rt_thread_switch_interrupt_flag set, jump to @ rt_hw_context_switch_interrupt_do and don't return ldr r0, =rt_thread_switch_interrupt_flag diff --git a/src/scheduler.c b/src/scheduler.c index be29d9a7e0..3da723687c 100644 --- a/src/scheduler.c +++ b/src/scheduler.c @@ -322,8 +322,23 @@ void rt_schedule(void) if (pcpu->irq_nest) { pcpu->irq_switch_flag = 1; + rt_hw_interrupt_enable(level); + goto __exit; } - else if (current_thread->scheduler_lock_nest == 1) /* whether lock scheduler */ + +#ifdef RT_USING_SIGNALS + if ((current_thread->stat & RT_THREAD_STAT_MASK) == RT_THREAD_SUSPEND) + { + /* if current_thread signal is in pending */ + + if ((current_thread->stat & RT_THREAD_STAT_SIGNAL_MASK) & RT_THREAD_STAT_SIGNAL_PENDING) + { + rt_thread_resume(current_thread); + } + } +#endif + + if (current_thread->scheduler_lock_nest == 1) /* whether lock scheduler */ { rt_ubase_t highest_ready_priority; @@ -366,27 +381,32 @@ void rt_schedule(void) _rt_scheduler_stack_check(to_thread); #endif - { - extern void rt_thread_handle_sig(rt_bool_t clean_state); - - rt_hw_context_switch((rt_ubase_t)¤t_thread->sp, - (rt_ubase_t)&to_thread->sp, to_thread); - - /* enable interrupt */ - rt_hw_interrupt_enable(level); - -#ifdef RT_USING_SIGNALS - /* check signal status */ - rt_thread_handle_sig(RT_TRUE); -#endif - goto __exit; - } + rt_hw_context_switch((rt_ubase_t)¤t_thread->sp, + (rt_ubase_t)&to_thread->sp, to_thread); } } } +#ifdef RT_USING_SIGNALS + if (current_thread->stat & RT_THREAD_STAT_SIGNAL_PENDING) + { + extern void rt_thread_handle_sig(rt_bool_t clean_state); + + current_thread->stat &= ~RT_THREAD_STAT_SIGNAL_PENDING; + + rt_hw_interrupt_enable(level); + + /* check signal status */ + rt_thread_handle_sig(RT_TRUE); + } + else + { + rt_hw_interrupt_enable(level); + } +#else /* enable interrupt */ rt_hw_interrupt_enable(level); +#endif __exit: return ; @@ -465,13 +485,25 @@ void rt_schedule(void) rt_hw_context_switch((rt_ubase_t)&from_thread->sp, (rt_ubase_t)&to_thread->sp); +#ifdef RT_USING_SIGNALS + if (rt_current_thread->stat & RT_THREAD_STAT_SIGNAL_PENDING) + { + extern void rt_thread_handle_sig(rt_bool_t clean_state); + + rt_current_thread->stat &= ~RT_THREAD_STAT_SIGNAL_PENDING; + rt_hw_interrupt_enable(level); + + /* check signal status */ + rt_thread_handle_sig(RT_TRUE); + } + else + { + rt_hw_interrupt_enable(level); + } +#else /* enable interrupt */ rt_hw_interrupt_enable(level); - -#ifdef RT_USING_SIGNALS - /* check signal status */ - rt_thread_handle_sig(RT_TRUE); #endif goto __exit; } @@ -519,6 +551,18 @@ void rt_scheduler_do_irq_switch(void *context) pcpu = rt_cpu_index(cpu_id); current_thread = pcpu->current_thread; +#ifdef RT_USING_SIGNALS + if ((current_thread->stat & RT_THREAD_STAT_MASK) == RT_THREAD_SUSPEND) + { + /* if current_thread signal is in pending */ + + if ((current_thread->stat & RT_THREAD_STAT_SIGNAL_MASK) & RT_THREAD_STAT_SIGNAL_PENDING) + { + rt_thread_resume(current_thread); + } + } +#endif + if (pcpu->irq_switch_flag == 0) { rt_hw_interrupt_enable(level); diff --git a/src/signal.c b/src/signal.c index 06c2055d26..0cab6215af 100644 --- a/src/signal.c +++ b/src/signal.c @@ -52,17 +52,27 @@ static void _signal_entry(void *parameter) /* handle signal */ rt_thread_handle_sig(RT_FALSE); - /* never come back... */ - rt_hw_interrupt_disable(); +#ifdef RT_USING_SMP + { + struct rt_cpu* pcpu = rt_cpu_self(); + + if (--pcpu->current_thread->cpus_lock_nest == 0) + { + pcpu->current_thread->scheduler_lock_nest--; + } + + } +#else /* return to thread */ tid->sp = tid->sig_ret; tid->sig_ret = RT_NULL; +#endif LOG_D("switch back to: 0x%08x\n", tid->sp); tid->stat &= ~RT_THREAD_STAT_SIGNAL; #ifdef RT_USING_SMP - rt_hw_context_switch_to((rt_ubase_t)&(tid->sp), tid); + rt_hw_context_switch_to((rt_base_t)¶meter, tid); #else rt_hw_context_switch_to((rt_ubase_t)&(tid->sp)); #endif /*RT_USING_SMP*/ @@ -82,16 +92,21 @@ static void _signal_deliver(rt_thread_t tid) { rt_ubase_t level; + level = rt_hw_interrupt_disable(); + /* thread is not interested in pended signals */ - if (!(tid->sig_pending & tid->sig_mask)) return; + if (!(tid->sig_pending & tid->sig_mask)) + { + rt_hw_interrupt_enable(level); + return; + } - level = rt_hw_interrupt_disable(); if ((tid->stat & RT_THREAD_STAT_MASK) == RT_THREAD_SUSPEND) { /* resume thread to handle signal */ rt_thread_resume(tid); /* add signal state */ - tid->stat |= RT_THREAD_STAT_SIGNAL; + tid->stat |= (RT_THREAD_STAT_SIGNAL | RT_THREAD_STAT_SIGNAL_PENDING); rt_hw_interrupt_enable(level); @@ -108,17 +123,36 @@ static void _signal_deliver(rt_thread_t tid) rt_hw_interrupt_enable(level); /* do signal action in self thread context */ - rt_thread_handle_sig(RT_TRUE); + if (rt_interrupt_get_nest() == 0) + { + rt_thread_handle_sig(RT_TRUE); + } } else if (!((tid->stat & RT_THREAD_STAT_SIGNAL_MASK) & RT_THREAD_STAT_SIGNAL)) { /* add signal state */ - tid->stat |= RT_THREAD_STAT_SIGNAL; + tid->stat |= (RT_THREAD_STAT_SIGNAL | RT_THREAD_STAT_SIGNAL_PENDING); +#ifdef RT_USING_SMP + { + int cpu_id; + + cpu_id = tid->oncpu; + if ((cpu_id != RT_CPU_DETACHED) && (cpu_id != rt_hw_cpu_id())) + { + rt_uint32_t cpu_mask; + + cpu_mask = RT_CPU_MASK ^ (1 << cpu_id); + rt_hw_ipi_send(RT_SCHEDULE_IPI, cpu_mask); + } + } +#else /* point to the signal handle entry */ + tid->stat &= ~RT_THREAD_STAT_SIGNAL_PENDING; tid->sig_ret = tid->sp; tid->sp = rt_hw_stack_init((void *)_signal_entry, RT_NULL, (void *)((char *)tid->sig_ret - 32), RT_NULL); +#endif rt_hw_interrupt_enable(level); LOG_D("signal stack pointer @ 0x%08x", tid->sp); @@ -133,14 +167,53 @@ static void _signal_deliver(rt_thread_t tid) } } +#ifdef RT_USING_SMP +void *rt_signal_check(void* context) +{ + rt_base_t level; + int cpu_id; + struct rt_cpu* pcpu; + struct rt_thread *current_thread; + + level = rt_hw_interrupt_disable(); + cpu_id = rt_hw_cpu_id(); + pcpu = rt_cpu_index(cpu_id); + current_thread = pcpu->current_thread; + + if (pcpu->irq_nest) + { + rt_hw_interrupt_enable(level); + return context; + } + + if (current_thread->cpus_lock_nest == 1) + { + if (current_thread->stat & RT_THREAD_STAT_SIGNAL_PENDING) + { + void *sig_context; + + current_thread->stat &= ~RT_THREAD_STAT_SIGNAL_PENDING; + + rt_hw_interrupt_enable(level); + sig_context = rt_hw_stack_init((void *)_signal_entry, context, + (void *)(context - 32), RT_NULL); + return sig_context; + } + } + rt_hw_interrupt_enable(level); + return context; +} +#endif + rt_sighandler_t rt_signal_install(int signo, rt_sighandler_t handler) { + rt_base_t level; rt_sighandler_t old = RT_NULL; rt_thread_t tid = rt_thread_self(); if (!sig_valid(signo)) return SIG_ERR; - rt_enter_critical(); + level = rt_hw_interrupt_disable(); if (tid->sig_vectors == RT_NULL) { rt_thread_alloc_sig(tid); @@ -154,7 +227,7 @@ rt_sighandler_t rt_signal_install(int signo, rt_sighandler_t handler) else if (handler == SIG_DFL) tid->sig_vectors[signo] = _signal_default_handler; else tid->sig_vectors[signo] = handler; } - rt_exit_critical(); + rt_hw_interrupt_enable(level); return old; } @@ -272,7 +345,20 @@ __done: LOG_D("sigwait: %d sig raised!", signo); if (si_prev) si_prev->list.next = si_node->list.next; - else tid->si_list = si_node->list.next; + else + { + struct siginfo_node *node_next; + + if (si_node->list.next) + { + node_next = (void *)rt_slist_entry(si_node->list.next, struct siginfo_node, list); + tid->si_list = node_next; + } + else + { + tid->si_list = RT_NULL; + } + } /* clear pending */ tid->sig_pending &= ~sig_mask(signo); @@ -281,7 +367,14 @@ __done: } si_prev = si_node; - si_node = (void *)rt_slist_entry(si_node->list.next, struct siginfo_node, list); + if (si_node->list.next) + { + si_node = (void *)rt_slist_entry(si_node->list.next, struct siginfo_node, list); + } + else + { + si_node = RT_NULL; + } } __done_int: @@ -320,13 +413,13 @@ void rt_thread_handle_sig(rt_bool_t clean_state) signo = si_node->si.si_signo; handler = tid->sig_vectors[signo]; + tid->sig_pending &= ~sig_mask(signo); rt_hw_interrupt_enable(level); LOG_D("handle signal: %d, handler 0x%08x", signo, handler); if (handler) handler(signo); level = rt_hw_interrupt_disable(); - tid->sig_pending &= ~sig_mask(signo); error = -RT_EINTR; rt_mp_free(si_node); /* release this siginfo node */ @@ -335,10 +428,16 @@ void rt_thread_handle_sig(rt_bool_t clean_state) } /* whether clean signal status */ - if (clean_state == RT_TRUE) tid->stat &= ~RT_THREAD_STAT_SIGNAL; + if (clean_state == RT_TRUE) + { + tid->stat &= ~RT_THREAD_STAT_SIGNAL; + } + else + { + return; + } } } - rt_hw_interrupt_enable(level); } @@ -364,30 +463,30 @@ void rt_thread_alloc_sig(rt_thread_t tid) void rt_thread_free_sig(rt_thread_t tid) { rt_base_t level; - struct siginfo_node *si_list; + struct siginfo_node *si_node; rt_sighandler_t *sig_vectors; level = rt_hw_interrupt_disable(); - si_list = (struct siginfo_node *)tid->si_list; + si_node = (struct siginfo_node *)tid->si_list; tid->si_list = RT_NULL; sig_vectors = tid->sig_vectors; tid->sig_vectors = RT_NULL; rt_hw_interrupt_enable(level); - if (si_list) + if (si_node) { struct rt_slist_node *node; - struct siginfo_node *si_node; + struct rt_slist_node *node_to_free; LOG_D("free signal info list"); - node = &(si_list->list); + node = &(si_node->list); do { - si_node = rt_slist_entry(node, struct siginfo_node, list); - rt_mp_free(si_node); - + node_to_free = node; node = node->next; + si_node = rt_slist_entry(node_to_free, struct siginfo_node, list); + rt_mp_free(si_node); } while (node); } @@ -418,30 +517,23 @@ int rt_thread_kill(rt_thread_t tid, int sig) struct rt_slist_node *node; struct siginfo_node *entry; - node = (struct rt_slist_node *)tid->si_list; - rt_hw_interrupt_enable(level); + si_node = (struct siginfo_node *)tid->si_list; + if (si_node) + node = (struct rt_slist_node *)&si_node->list; + else + node = RT_NULL; /* update sig info */ - rt_enter_critical(); for (; (node) != RT_NULL; node = node->next) { entry = rt_slist_entry(node, struct siginfo_node, list); if (entry->si.si_signo == sig) { memcpy(&(entry->si), &si, sizeof(siginfo_t)); - rt_exit_critical(); + rt_hw_interrupt_enable(level); return 0; } } - rt_exit_critical(); - - /* disable interrupt to protect tcb */ - level = rt_hw_interrupt_disable(); - } - else - { - /* a new signal */ - tid->sig_pending |= sig_mask(sig); } rt_hw_interrupt_enable(level); @@ -452,14 +544,22 @@ int rt_thread_kill(rt_thread_t tid, int sig) memcpy(&(si_node->si), &si, sizeof(siginfo_t)); level = rt_hw_interrupt_disable(); - if (!tid->si_list) tid->si_list = si_node; - else + + if (tid->si_list) { struct siginfo_node *si_list; si_list = (struct siginfo_node *)tid->si_list; rt_slist_append(&(si_list->list), &(si_node->list)); } + else + { + tid->si_list = si_node; + } + + /* a new signal */ + tid->sig_pending |= sig_mask(sig); + rt_hw_interrupt_enable(level); } else diff --git a/src/thread.c b/src/thread.c index 0f2e1dc3d0..276bba9938 100644 --- a/src/thread.c +++ b/src/thread.c @@ -191,7 +191,9 @@ static rt_err_t _rt_thread_init(struct rt_thread *thread, thread->sig_mask = 0x00; thread->sig_pending = 0x00; +#ifndef RT_USING_SMP thread->sig_ret = RT_NULL; +#endif thread->sig_vectors = RT_NULL; thread->si_list = RT_NULL; #endif -- cgit v1.3.1 From c5249157d7b92ed29cee9df440b4a9928e1a4e4f Mon Sep 17 00:00:00 2001 From: shaojinchun Date: Fri, 10 May 2019 10:41:03 +0800 Subject: 增加signal的状态位说明及一处代码修改,以防止编译警告 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/rtdef.h | 6 +++--- src/signal.c | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) (limited to 'include/rtdef.h') diff --git a/include/rtdef.h b/include/rtdef.h index 253333253a..2aff4afdb0 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -492,10 +492,10 @@ typedef siginfo_t rt_siginfo_t; #define RT_THREAD_CLOSE 0x04 /**< Closed status */ #define RT_THREAD_STAT_MASK 0x0f -#define RT_THREAD_STAT_SIGNAL 0x10 +#define RT_THREAD_STAT_SIGNAL 0x10 /**< task hold signals */ #define RT_THREAD_STAT_SIGNAL_READY (RT_THREAD_STAT_SIGNAL | RT_THREAD_READY) -#define RT_THREAD_STAT_SIGNAL_WAIT 0x20 -#define RT_THREAD_STAT_SIGNAL_PENDING 0x40 +#define RT_THREAD_STAT_SIGNAL_WAIT 0x20 /**< task is waiting for signals */ +#define RT_THREAD_STAT_SIGNAL_PENDING 0x40 /**< signals is held and it has not been procressed */ #define RT_THREAD_STAT_SIGNAL_MASK 0xf0 /** diff --git a/src/signal.c b/src/signal.c index 0cab6215af..0c0f990f46 100644 --- a/src/signal.c +++ b/src/signal.c @@ -56,7 +56,8 @@ static void _signal_entry(void *parameter) { struct rt_cpu* pcpu = rt_cpu_self(); - if (--pcpu->current_thread->cpus_lock_nest == 0) + pcpu->current_thread->cpus_lock_nest--; + if (pcpu->current_thread->cpus_lock_nest == 0) { pcpu->current_thread->scheduler_lock_nest--; } -- cgit v1.3.1 From b4e141fee15d21c53c6f22fde6e33aed37732e13 Mon Sep 17 00:00:00 2001 From: Bernard Xiong Date: Fri, 17 May 2019 08:34:10 +0800 Subject: Update rtdef.h --- include/rtdef.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'include/rtdef.h') diff --git a/include/rtdef.h b/include/rtdef.h index 2aff4afdb0..94c9b5f413 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -30,6 +30,7 @@ * add struct rt_cpu * add smp relevant macros * 2019-01-27 Bernard change version number to v4.0.1 + * 2019-05-17 Bernard change version number to v4.0.2 */ #ifndef __RT_DEF_H__ @@ -51,7 +52,7 @@ extern "C" { /* RT-Thread version information */ #define RT_VERSION 4L /**< major version number */ #define RT_SUBVERSION 0L /**< minor version number */ -#define RT_REVISION 1L /**< revise version number */ +#define RT_REVISION 2L /**< revise version number */ /* RT-Thread version */ #define RTTHREAD_VERSION ((RT_VERSION * 10000) + \ -- cgit v1.3.1 From 89b90592ee0d2db6a5c1fc8b38e5904751754ffe Mon Sep 17 00:00:00 2001 From: tyustli <1225613647@qq.com> Date: Wed, 12 Jun 2019 09:38:32 +0800 Subject: add touch framework --- components/drivers/include/drivers/i2c.h | 7 + components/drivers/touch/SConscript | 11 ++ components/drivers/touch/touch.c | 275 +++++++++++++++++++++++++++++++ components/drivers/touch/touch.h | 105 ++++++++++++ components/finsh/cmd.c | 1 + include/rtdef.h | 1 + 6 files changed, 400 insertions(+) create mode 100644 components/drivers/touch/SConscript create mode 100644 components/drivers/touch/touch.c create mode 100644 components/drivers/touch/touch.h (limited to 'include/rtdef.h') diff --git a/components/drivers/include/drivers/i2c.h b/components/drivers/include/drivers/i2c.h index e2a9e7d0b8..c6376efa89 100644 --- a/components/drivers/include/drivers/i2c.h +++ b/components/drivers/include/drivers/i2c.h @@ -60,6 +60,13 @@ struct rt_i2c_bus_device void *priv; }; +struct rt_i2c_client +{ + struct rt_device parent; + struct rt_i2c_bus_device *bus; + rt_uint16_t client_addr; +}; + #ifdef RT_I2C_DEBUG #define i2c_dbg(fmt, ...) rt_kprintf(fmt, ##__VA_ARGS__) #else diff --git a/components/drivers/touch/SConscript b/components/drivers/touch/SConscript new file mode 100644 index 0000000000..f370b2aba6 --- /dev/null +++ b/components/drivers/touch/SConscript @@ -0,0 +1,11 @@ +# SConscript for touch framework + +from building import * + +cwd = GetCurrentDir() +src = ['touch.c'] +CPPPATH = [cwd, cwd + '/../include'] + +group = DefineGroup('Touch', src, depend = ['RT_USING_TOUCH', 'RT_USING_DEVICE'], CPPPATH = CPPPATH) + +Return('group') diff --git a/components/drivers/touch/touch.c b/components/drivers/touch/touch.c new file mode 100644 index 0000000000..37456609dc --- /dev/null +++ b/components/drivers/touch/touch.c @@ -0,0 +1,275 @@ +/* + * Copyright (c) 2006-2018, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2019-05-20 tyustli the first version + */ + +#include "touch.h" +#include + +#define DBG_TAG "touch" +#define DBG_LVL DBG_INFO +#include + +/* touch interrupt handler function */ +void rt_touch_cb(rt_touch_t touch) +{ + if (touch->parent.rx_indicate == RT_NULL) + { + return; + } + + if (touch->irq_handle != RT_NULL) + { + touch->irq_handle(touch); + } + + touch->parent.rx_indicate(&touch->parent, 1); +} + +/* ISR for touch interrupt */ +static void irq_callback(void *args) +{ + rt_touch_t touch; + + touch = (rt_touch_t)args; + + rt_touch_cb(touch); +} + +/* touch interrupt initialization function */ +static rt_err_t rt_touch_irq_init(rt_touch_t touch) +{ + if (touch->config.irq_pin.pin == RT_PIN_NONE) + { + return -RT_EINVAL; + } + + rt_pin_mode(touch->config.irq_pin.pin, touch->config.irq_pin.mode); + + if (touch->config.irq_pin.mode == PIN_MODE_INPUT_PULLDOWN) + { + rt_pin_attach_irq(touch->config.irq_pin.pin, PIN_IRQ_MODE_RISING, irq_callback, (void *)touch); + } + else if (touch->config.irq_pin.mode == PIN_MODE_INPUT_PULLUP) + { + rt_pin_attach_irq(touch->config.irq_pin.pin, PIN_IRQ_MODE_FALLING, irq_callback, (void *)touch); + } + else if (touch->config.irq_pin.mode == PIN_MODE_INPUT) + { + rt_pin_attach_irq(touch->config.irq_pin.pin, PIN_IRQ_MODE_RISING_FALLING, irq_callback, (void *)touch); + } + + rt_pin_irq_enable(touch->config.irq_pin.pin, PIN_IRQ_ENABLE); + + LOG_I("interrupt init success"); + + return 0; +} + +/* touch interrupt enable */ +static void rt_touch_irq_enable(rt_touch_t touch) +{ + if (touch->config.irq_pin.pin != RT_PIN_NONE) + { + rt_pin_irq_enable(touch->config.irq_pin.pin, RT_TRUE); + } +} + +/* touch interrupt disable */ +static void rt_touch_irq_disable(rt_touch_t touch) +{ + if (touch->config.irq_pin.pin != RT_PIN_NONE) + { + rt_pin_irq_enable(touch->config.irq_pin.pin, RT_FALSE); + } +} + +static rt_err_t rt_touch_open(rt_device_t dev, rt_uint16_t oflag) +{ + rt_touch_t touch; + RT_ASSERT(dev != RT_NULL); + touch = (rt_touch_t)dev; + + if (oflag & RT_DEVICE_FLAG_INT_RX && dev->flag & RT_DEVICE_FLAG_INT_RX) + { + /* Initialization touch interrupt */ + rt_touch_irq_init(touch); + } + + return RT_EOK; +} + +static rt_err_t rt_touch_close(rt_device_t dev) +{ + rt_touch_t touch; + RT_ASSERT(dev != RT_NULL); + touch = (rt_touch_t)dev; + + /* touch disable interrupt */ + rt_touch_irq_disable(touch); + + return RT_EOK; +} + +static rt_size_t rt_touch_read(rt_device_t dev, rt_off_t pos, void *buf, rt_size_t len) +{ + rt_touch_t touch; + rt_size_t result = 0; + RT_ASSERT(dev != RT_NULL); + touch = (rt_touch_t)dev; + + if (buf == NULL || len == 0) + { + return 0; + } + + result = touch->ops->touch_readpoint(touch, buf, len); + + return result; +} + +static rt_err_t rt_touch_control(rt_device_t dev, int cmd, void *args) +{ + rt_touch_t touch; + rt_err_t result = RT_EOK; + RT_ASSERT(dev != RT_NULL); + touch = (rt_touch_t)dev; + + switch (cmd) + { + case RT_TOUCH_CTRL_GET_ID: + if (args) + { + result = touch->ops->touch_control(touch, RT_TOUCH_CTRL_GET_ID, args); + } + else + { + result = RT_ERROR; + } + + break; + case RT_TOUCH_CTRL_GET_INFO: + if (args) + { + result = touch->ops->touch_control(touch, RT_TOUCH_CTRL_GET_INFO, args); + } + else + { + result = RT_ERROR; + } + + break; + case RT_TOUCH_CTRL_SET_MODE: + result = touch->ops->touch_control(touch, RT_TOUCH_CTRL_SET_MODE, args); + + if (result == RT_EOK) + { + rt_uint16_t mode; + mode = *(rt_uint16_t*)args; + if (mode == RT_DEVICE_FLAG_INT_RX) + { + rt_touch_irq_enable(touch); /* enable interrupt */ + } + } + + break; + case RT_TOUCH_CTRL_SET_X_RANGE: + result = touch->ops->touch_control(touch, RT_TOUCH_CTRL_SET_X_RANGE, args); + + if (result == RT_EOK) + { + touch->info.range_x = *(rt_int32_t *)args; + LOG_D("set x coordinate range :%d\n", touch->info.range_x); + } + + break; + case RT_TOUCH_CTRL_SET_Y_RANGE: + result = touch->ops->touch_control(touch, RT_TOUCH_CTRL_SET_Y_RANGE, args); + + if (result == RT_EOK) + { + touch->info.range_y = *(rt_uint32_t *)args; + LOG_D("set y coordinate range :%d \n", touch->info.range_x); + } + + break; + default: + return -RT_ERROR; + } + + return result; +} + +#ifdef RT_USING_DEVICE_OPS +const static struct rt_device_ops rt_touch_ops = +{ + RT_NULL, + rt_touch_open, + rt_touch_close, + rt_touch_read, + RT_NULL, + rt_touch_control +}; +#endif + +/* + * touch register + */ +int rt_hw_touch_register(rt_touch_t touch, + const char *name, + rt_uint32_t flag, + void *data) +{ + rt_int8_t result; + rt_device_t device; + RT_ASSERT(touch != RT_NULL); + + char *touch_name = RT_NULL; + char *device_name = RT_NULL; + + touch_name = "touch_"; + device_name = rt_calloc(1, rt_strlen(touch_name) + 1 + rt_strlen(name)); + + if (device_name == RT_NULL) + { + LOG_E("device_name calloc failed!"); + return -RT_ERROR; + } + + rt_memcpy(device_name, touch_name, rt_strlen(touch_name) + 1); + strcat(device_name, name); + + device = &touch->parent; + +#ifdef RT_USING_DEVICE_OPS + device->ops = &rt_touch_ops; +#else + device->init = RT_NULL; + device->open = rt_touch_open; + device->close = rt_touch_close; + device->read = rt_touch_read; + device->write = RT_NULL; + device->control = rt_touch_control; +#endif + device->type = RT_Device_Class_Touch; + device->rx_indicate = RT_NULL; + device->tx_complete = RT_NULL; + device->user_data = data; + + result = rt_device_register(device, device_name, flag | RT_DEVICE_FLAG_STANDALONE); + + if (result != RT_EOK) + { + LOG_E("rt_touch register err code: %d", result); + return result; + } + + LOG_I("rt_touch init success"); + + return RT_EOK; +} diff --git a/components/drivers/touch/touch.h b/components/drivers/touch/touch.h new file mode 100644 index 0000000000..4fa19aed47 --- /dev/null +++ b/components/drivers/touch/touch.h @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2006-2018, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2019-05-20 tyustli the first version + */ + +#ifndef __TOUCH_H__ +#define __TOUCH_H__ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef RT_USING_RTC +#define rt_touch_get_ts() time(RT_NULL) /* API for the touch to get the timestamp */ +#else +#define rt_touch_get_ts() rt_tick_get() /* API for the touch to get the timestamp */ +#endif + +#define RT_PIN_NONE 0xFFFF /* RT PIN NONE */ + +/* Touch vendor types */ +#define RT_TOUCH_VENDOR_UNKNOWN (0) /* unknown */ +#define RT_TOUCH_VENDOR_GT (1) /* GTxx series */ +#define RT_TOUCH_VENDOR_FT (2) /* FTxx series */ + +/* Touch ic type*/ +#define RT_TOUCH_TYPE_NONE (0) /* touch ic none */ +#define RT_TOUCH_TYPE_CAPACITANCE (1) /* capacitance ic */ +#define RT_TOUCH_TYPE_RESISTANCE (2) /* resistance ic */ + +/* Touch control cmd types */ +#define RT_TOUCH_CTRL_GET_ID (0) /* Get device id */ +#define RT_TOUCH_CTRL_GET_INFO (1) /* Get touch info */ +#define RT_TOUCH_CTRL_SET_MODE (2) /* Set touch's work mode. ex. RT_TOUCH_MODE_POLLING,RT_TOUCH_MODE_INT */ +#define RT_TOUCH_CTRL_SET_X_RANGE (3) /* Set x coordinate range */ +#define RT_TOUCH_CTRL_SET_Y_RANGE (4) /* Set y coordinate range */ +#define RT_TOUCH_CTRL_SET_X_TO_Y (5) /* Set X Y coordinate exchange */ + +/* Touch event */ +#define RT_TOUCH_EVENT_NONE (0) /* Touch none */ +#define RT_TOUCH_EVENT_UP (1) /* Touch up event */ +#define RT_TOUCH_EVENT_DOWN (2) /* Touch down event */ +#define RT_TOUCH_EVENT_MOVE (3) /* Touch move event */ + +struct rt_touch_info +{ + rt_uint8_t type; /* The touch type */ + rt_uint8_t vendor; /* Vendor of touchs */ + rt_uint8_t point_num; /* Support point num */ + rt_int32_t range_x; /* X coordinate range */ + rt_int32_t range_y; /* Y coordinate range */ +}; + +struct rt_touch_config +{ + struct rt_device_pin_mode irq_pin; /* Interrupt pin, The purpose of this pin is to notification read data */ + char *dev_name; /* The name of the communication device */ + void *user_data; +}; + +typedef struct rt_touch_device *rt_touch_t; +struct rt_touch_device +{ + struct rt_device parent; /* The standard device */ + struct rt_touch_info info; /* The touch info data */ + struct rt_touch_config config; /* The touch config data */ + + const struct rt_touch_ops *ops; /* The touch ops */ + rt_err_t (*irq_handle)(rt_touch_t touch); /* Called when an interrupt is generated, registered by the driver */ +}; + +struct rt_touch_data +{ + rt_uint8_t event; /* The touch event of the data */ + rt_uint8_t track_id; /* Track id of point */ + rt_uint8_t width; /* Point of width */ + rt_uint16_t x_coordinate; /* Point of x coordinate */ + rt_uint16_t y_coordinate; /* Point of y coordinate */ + rt_tick_t timestamp; /* The timestamp when the data was received */ +}; + +struct rt_touch_ops +{ + rt_size_t (*touch_readpoint)(struct rt_touch_device *touch, void *buf, rt_size_t touch_num); + rt_err_t (*touch_control)(struct rt_touch_device *touch, int cmd, void *arg); +}; + +int rt_hw_touch_register(rt_touch_t touch, + const char *name, + rt_uint32_t flag, + void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* __TOUCH_H__ */ diff --git a/components/finsh/cmd.c b/components/finsh/cmd.c index 680d9d01d7..608e962f6c 100644 --- a/components/finsh/cmd.c +++ b/components/finsh/cmd.c @@ -801,6 +801,7 @@ static char *const device_type_str[] = "Timer Device", "Miscellaneous Device", "Sensor Device", + "Touch Device", "Unknown" }; diff --git a/include/rtdef.h b/include/rtdef.h index 94c9b5f413..c97e938f75 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -854,6 +854,7 @@ enum rt_device_class_type RT_Device_Class_Timer, /**< Timer device */ RT_Device_Class_Miscellaneous, /**< Miscellaneous device */ RT_Device_Class_Sensor, /**< Sensor device */ + RT_Device_Class_Touch, /**< Touch device */ RT_Device_Class_Unknown /**< unknown device */ }; -- cgit v1.3.1 From ae1fdc70f0086c0e12bfe02c9b69153e7743dc22 Mon Sep 17 00:00:00 2001 From: shaojinchun Date: Mon, 16 Sep 2019 16:55:40 +0800 Subject: 修正rt_mp_free有可能唤醒一个错误任务指针的问题 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- components/finsh/cmd.c | 15 ++++++++++++--- include/rtdef.h | 1 - src/mempool.c | 14 +------------- 3 files changed, 13 insertions(+), 17 deletions(-) (limited to 'include/rtdef.h') diff --git a/components/finsh/cmd.c b/components/finsh/cmd.c index 680d9d01d7..f8b774bd6f 100644 --- a/components/finsh/cmd.c +++ b/components/finsh/cmd.c @@ -675,6 +675,8 @@ long list_mempool(void) { struct rt_object *obj; struct rt_mempool *mp; + int suspend_thread_count; + rt_list_t *node; obj = rt_list_entry(obj_list[i], struct rt_object, list); level = rt_hw_interrupt_disable(); @@ -687,7 +689,14 @@ long list_mempool(void) rt_hw_interrupt_enable(level); mp = (struct rt_mempool *)obj; - if (mp->suspend_thread_count > 0) + + suspend_thread_count = 0; + for (node = mp->suspend_thread.next; node != &mp->suspend_thread; node = node->next) + { + suspend_thread_count++; + } + + if (suspend_thread_count > 0) { rt_kprintf("%-*.*s %04d %04d %04d %d:", maxlen, RT_NAME_MAX, @@ -695,7 +704,7 @@ long list_mempool(void) mp->block_size, mp->block_total_count, mp->block_free_count, - mp->suspend_thread_count); + suspend_thread_count); show_wait_queue(&(mp->suspend_thread)); rt_kprintf("\n"); } @@ -707,7 +716,7 @@ long list_mempool(void) mp->block_size, mp->block_total_count, mp->block_free_count, - mp->suspend_thread_count); + suspend_thread_count); } } } diff --git a/include/rtdef.h b/include/rtdef.h index 94c9b5f413..4ac9209231 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -815,7 +815,6 @@ struct rt_mempool rt_size_t block_free_count; /**< numbers of free memory block */ rt_list_t suspend_thread; /**< threads pended on this resource */ - rt_size_t suspend_thread_count; /**< numbers of thread pended on this resource */ }; typedef struct rt_mempool *rt_mp_t; #endif diff --git a/src/mempool.c b/src/mempool.c index 2184586aba..62cdb69269 100644 --- a/src/mempool.c +++ b/src/mempool.c @@ -103,7 +103,6 @@ rt_err_t rt_mp_init(struct rt_mempool *mp, /* initialize suspended thread list */ rt_list_init(&(mp->suspend_thread)); - mp->suspend_thread_count = 0; /* initialize free block list */ block_ptr = (rt_uint8_t *)mp->start_address; @@ -157,9 +156,6 @@ rt_err_t rt_mp_detach(struct rt_mempool *mp) */ rt_thread_resume(thread); - /* decrease suspended thread count */ - mp->suspend_thread_count --; - /* enable interrupt */ rt_hw_interrupt_enable(temp); } @@ -219,7 +215,6 @@ rt_mp_t rt_mp_create(const char *name, /* initialize suspended thread list */ rt_list_init(&(mp->suspend_thread)); - mp->suspend_thread_count = 0; /* initialize free block list */ block_ptr = (rt_uint8_t *)mp->start_address; @@ -275,9 +270,6 @@ rt_err_t rt_mp_delete(rt_mp_t mp) */ rt_thread_resume(thread); - /* decrease suspended thread count */ - mp->suspend_thread_count --; - /* enable interrupt */ rt_hw_interrupt_enable(temp); } @@ -334,7 +326,6 @@ void *rt_mp_alloc(rt_mp_t mp, rt_int32_t time) /* need suspend thread */ rt_thread_suspend(thread); rt_list_insert_after(&(mp->suspend_thread), &(thread->tlist)); - mp->suspend_thread_count++; if (time > 0) { @@ -418,7 +409,7 @@ void rt_mp_free(void *block) *block_ptr = mp->block_list; mp->block_list = (rt_uint8_t *)block_ptr; - if (mp->suspend_thread_count > 0) + if (!rt_list_isempty(&(mp->suspend_thread))) { /* get the suspended thread */ thread = rt_list_entry(mp->suspend_thread.next, @@ -431,9 +422,6 @@ void rt_mp_free(void *block) /* resume thread */ rt_thread_resume(thread); - /* decrease suspended thread count */ - mp->suspend_thread_count --; - /* enable interrupt */ rt_hw_interrupt_enable(level); -- cgit v1.3.1 From e4671d291689e71967afa5dec4ff25d310faa3fb Mon Sep 17 00:00:00 2001 From: tangyuxin <462747508@qq.com> Date: Mon, 16 Sep 2019 15:12:42 +0800 Subject: [kernel][ipc] add send wait support for message queue --- include/rtdef.h | 2 + include/rtthread.h | 4 ++ src/ipc.c | 130 ++++++++++++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 131 insertions(+), 5 deletions(-) (limited to 'include/rtdef.h') diff --git a/include/rtdef.h b/include/rtdef.h index 7c05178e3c..b25a6a87d5 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -742,6 +742,8 @@ struct rt_messagequeue void *msg_queue_head; /**< list head */ void *msg_queue_tail; /**< list tail */ void *msg_queue_free; /**< pointer indicated the free node of queue */ + + rt_list_t suspend_sender_thread; /**< sender thread suspended on this message queue */ }; typedef struct rt_messagequeue *rt_mq_t; #endif diff --git a/include/rtthread.h b/include/rtthread.h index 04db77da46..d703f36268 100644 --- a/include/rtthread.h +++ b/include/rtthread.h @@ -379,6 +379,10 @@ rt_mq_t rt_mq_create(const char *name, rt_err_t rt_mq_delete(rt_mq_t mq); rt_err_t rt_mq_send(rt_mq_t mq, const void *buffer, rt_size_t size); +rt_err_t rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout); rt_err_t rt_mq_urgent(rt_mq_t mq, const void *buffer, rt_size_t size); rt_err_t rt_mq_recv(rt_mq_t mq, void *buffer, diff --git a/src/ipc.c b/src/ipc.c index c6a05e96a4..16d714b3f4 100644 --- a/src/ipc.c +++ b/src/ipc.c @@ -33,6 +33,7 @@ * 2011-12-18 Bernard add more parameter checking in message queue * 2013-09-14 Grissiom add an option check in rt_event_recv * 2018-10-02 Bernard add 64bit support for mailbox + * 2019-09-16 tyx add send wait support for message queue */ #include @@ -1823,6 +1824,9 @@ rt_err_t rt_mq_init(rt_mq_t mq, /* the initial entry is zero */ mq->entry = 0; + /* init an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + return RT_EOK; } RTM_EXPORT(rt_mq_init); @@ -1843,6 +1847,8 @@ rt_err_t rt_mq_detach(rt_mq_t mq) /* resume all suspended thread */ rt_ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + rt_ipc_list_resume_all(&(mq->suspend_sender_thread)); /* detach message queue object */ rt_object_detach(&(mq->parent.parent)); @@ -1916,6 +1922,9 @@ rt_mq_t rt_mq_create(const char *name, /* the initial entry is zero */ mq->entry = 0; + /* init an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + return mq; } RTM_EXPORT(rt_mq_create); @@ -1938,6 +1947,8 @@ rt_err_t rt_mq_delete(rt_mq_t mq) /* resume all suspended thread */ rt_ipc_list_resume_all(&(mq->parent.suspend_thread)); + /* also resume all message queue private suspended thread */ + rt_ipc_list_resume_all(&(mq->suspend_sender_thread)); /* free message queue pool */ RT_KERNEL_FREE(mq->msg_pool); @@ -1951,19 +1962,25 @@ RTM_EXPORT(rt_mq_delete); #endif /** - * This function will send a message to message queue object, if there are - * threads suspended on message queue object, it will be waked up. + * This function will send a message to message queue object. If the message queue is full, + * current thread will be suspended until timeout. * * @param mq the message queue object * @param buffer the message * @param size the size of buffer + * @param timeout the waiting time * * @return the error code */ -rt_err_t rt_mq_send(rt_mq_t mq, const void *buffer, rt_size_t size) +rt_err_t rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) { register rt_ubase_t temp; struct rt_mq_message *msg; + rt_uint32_t tick_delta; + struct rt_thread *thread; /* parameter check */ RT_ASSERT(mq != RT_NULL); @@ -1975,6 +1992,11 @@ rt_err_t rt_mq_send(rt_mq_t mq, const void *buffer, rt_size_t size) if (size > mq->msg_size) return -RT_ERROR; + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent))); /* disable interrupt */ @@ -1982,14 +2004,78 @@ rt_err_t rt_mq_send(rt_mq_t mq, const void *buffer, rt_size_t size) /* get a free list, there must be an empty item */ msg = (struct rt_mq_message *)mq->msg_queue_free; - /* message queue is full */ - if (msg == RT_NULL) + /* for non-blocking call */ + if (msg == RT_NULL && timeout == 0) { /* enable interrupt */ rt_hw_interrupt_enable(temp); return -RT_EFULL; } + + /* message queue is full */ + while ((msg = mq->msg_queue_free) == RT_NULL) + { + /* reset error number in thread */ + thread->error = RT_EOK; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(temp); + + return -RT_EFULL; + } + + RT_DEBUG_IN_THREAD_CONTEXT; + /* suspend current thread */ + rt_ipc_list_suspend(&(mq->suspend_sender_thread), + thread, + mq->parent.parent.flag); + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mq_send_wait: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(temp); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + temp = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + /* move free list pointer */ mq->msg_queue_free = msg->next; @@ -2037,6 +2123,22 @@ rt_err_t rt_mq_send(rt_mq_t mq, const void *buffer, rt_size_t size) return RT_EOK; } +RTM_EXPORT(rt_mq_send_wait) + +/** + * This function will send a message to message queue object, if there are + * threads suspended on message queue object, it will be waked up. + * + * @param mq the message queue object + * @param buffer the message + * @param size the size of buffer + * + * @return the error code + */ +rt_err_t rt_mq_send(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait(mq, buffer, size, 0); +} RTM_EXPORT(rt_mq_send); /** @@ -2257,6 +2359,22 @@ rt_err_t rt_mq_recv(rt_mq_t mq, /* put message to free list */ msg->next = (struct rt_mq_message *)mq->msg_queue_free; mq->msg_queue_free = msg; + + /* resume suspended thread */ + if (!rt_list_isempty(&(mq->suspend_sender_thread))) + { + rt_ipc_list_resume(&(mq->suspend_sender_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(temp); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent))); + + rt_schedule(); + + return RT_EOK; + } + /* enable interrupt */ rt_hw_interrupt_enable(temp); @@ -2292,6 +2410,8 @@ rt_err_t rt_mq_control(rt_mq_t mq, int cmd, void *arg) /* resume all waiting thread */ rt_ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + rt_ipc_list_resume_all(&(mq->suspend_sender_thread)); /* release all message in the queue */ while (mq->msg_queue_head != RT_NULL) -- cgit v1.3.1 From cb07e5fb24afebdf233847da551d3ede80727345 Mon Sep 17 00:00:00 2001 From: shaojinchun Date: Thu, 26 Sep 2019 18:13:07 +0800 Subject: 开放spinlock相关函数 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/rtdef.h | 1 + include/rthw.h | 14 +++++ libcpu/arm/cortex-a/cpu.c | 6 +++ libcpu/risc-v/k210/cpuport_smp.c | 5 ++ src/cpu.c | 113 +++++++++++++++++++++++++++++++++++++++ src/scheduler.c | 11 ++-- src/thread.c | 1 + 7 files changed, 148 insertions(+), 3 deletions(-) (limited to 'include/rtdef.h') diff --git a/include/rtdef.h b/include/rtdef.h index b25a6a87d5..3dc8a2a2a9 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -577,6 +577,7 @@ struct rt_thread rt_uint16_t scheduler_lock_nest; /**< scheduler lock count */ rt_uint16_t cpus_lock_nest; /**< cpus lock count */ + rt_uint16_t critical_lock_nest; /**< critical lock count */ #endif /*RT_USING_SMP*/ /* priority */ diff --git a/include/rthw.h b/include/rthw.h index ef3dc087ad..a77f2c1e46 100644 --- a/include/rthw.h +++ b/include/rthw.h @@ -143,6 +143,12 @@ typedef union { } tickets; } rt_hw_spinlock_t; +typedef struct +{ + rt_hw_spinlock_t lock; +} rt_spinlock_t; + +void rt_hw_spin_lock_init(rt_hw_spinlock_t *lock); void rt_hw_spin_lock(rt_hw_spinlock_t *lock); void rt_hw_spin_unlock(rt_hw_spinlock_t *lock); @@ -181,8 +187,16 @@ void rt_hw_secondary_cpu_idle_exec(void); #define rt_hw_spin_lock(lock) *(lock) = rt_hw_interrupt_disable() #define rt_hw_spin_unlock(lock) rt_hw_interrupt_enable(*(lock)) +typedef int rt_spinlock_t; + #endif +void rt_spin_lock_init(rt_spinlock_t *lock); +void rt_spin_lock(rt_spinlock_t *lock); +void rt_spin_unlock(rt_spinlock_t *lock); +rt_base_t rt_spin_lock_irqsave(rt_spinlock_t *lock); +void rt_spin_unlock_irqrestore(rt_spinlock_t *lock, rt_base_t level); + #ifdef __cplusplus } #endif diff --git a/libcpu/arm/cortex-a/cpu.c b/libcpu/arm/cortex-a/cpu.c index 6b129f89ee..7c6bf58a4b 100644 --- a/libcpu/arm/cortex-a/cpu.c +++ b/libcpu/arm/cortex-a/cpu.c @@ -14,6 +14,7 @@ #include #ifdef RT_USING_SMP + int rt_hw_cpu_id(void) { int cpu_id; @@ -25,6 +26,11 @@ int rt_hw_cpu_id(void) return cpu_id; }; +void rt_hw_spin_lock_init(rt_hw_spinlock_t *lock) +{ + lock->slock = 0; +} + void rt_hw_spin_lock(rt_hw_spinlock_t *lock) { unsigned long tmp; diff --git a/libcpu/risc-v/k210/cpuport_smp.c b/libcpu/risc-v/k210/cpuport_smp.c index a31314a13f..8c57dfeafc 100644 --- a/libcpu/risc-v/k210/cpuport_smp.c +++ b/libcpu/risc-v/k210/cpuport_smp.c @@ -25,6 +25,11 @@ int rt_hw_cpu_id(void) return read_csr(mhartid); } +void rt_hw_spin_lock_init(rt_hw_spinlock_t *lock) +{ + ((spinlock_t *)lock)->lock = 0; +} + void rt_hw_spin_lock(rt_hw_spinlock_t *lock) { spinlock_lock((spinlock_t *)lock); diff --git a/src/cpu.c b/src/cpu.c index fe3ba21bb0..a4075108e1 100644 --- a/src/cpu.c +++ b/src/cpu.c @@ -11,6 +11,119 @@ #include #include +#ifdef RT_USING_SMP +/*********************************** + * disable scheduler + ***********************************/ +static void rt_preempt_disable(void) +{ + register rt_base_t level; + struct rt_thread *current_thread; + + /* disable interrupt */ + level = rt_hw_local_irq_disable(); + + current_thread = rt_cpu_self()->current_thread; + if (!current_thread) + { + rt_hw_local_irq_enable(level); + return; + } + + /* lock scheduler for local cpu */ + current_thread->scheduler_lock_nest ++; + + /* enable interrupt */ + rt_hw_local_irq_enable(level); +} + +/*********************************** + * restore scheduler + ***********************************/ +static void rt_preempt_enable(void) +{ + register rt_base_t level; + struct rt_thread *current_thread; + + /* disable interrupt */ + level = rt_hw_local_irq_disable(); + + current_thread = rt_cpu_self()->current_thread; + if (!current_thread) + { + rt_hw_local_irq_enable(level); + return; + } + + /* unlock scheduler for local cpu */ + current_thread->scheduler_lock_nest --; + + rt_schedule(); + /* enable interrupt */ + rt_hw_local_irq_enable(level); +} +#endif + +void rt_spin_lock_init(rt_spinlock_t *lock) +{ +#ifdef RT_USING_SMP + rt_hw_spin_lock_init(&lock->lock); +#endif +} +RTM_EXPORT(rt_spin_lock_init) + +void rt_spin_lock(rt_spinlock_t *lock) +{ +#ifdef RT_USING_SMP + rt_preempt_disable(); + rt_hw_spin_lock(&lock->lock); +#else + rt_enter_critical(); +#endif +} +RTM_EXPORT(rt_spin_lock) + +void rt_spin_unlock(rt_spinlock_t *lock) +{ +#ifdef RT_USING_SMP + rt_hw_spin_unlock(&lock->lock); + rt_preempt_enable(); +#else + rt_exit_critical(); +#endif +} +RTM_EXPORT(rt_spin_unlock) + +rt_base_t rt_spin_lock_irqsave(rt_spinlock_t *lock) +{ + unsigned long level; + +#ifdef RT_USING_SMP + rt_preempt_disable(); + + level = rt_hw_local_irq_disable(); + rt_hw_spin_lock(&lock->lock); + + return level; +#else + return rt_hw_interrupt_disable(); +#endif +} +RTM_EXPORT(rt_spin_lock_irqsave) + +void rt_spin_unlock_irqrestore(rt_spinlock_t *lock, rt_base_t level) +{ +#ifdef RT_USING_SMP + rt_hw_spin_unlock(&lock->lock); + rt_hw_local_irq_enable(level); + + rt_preempt_enable(); +#else + rt_hw_interrupt_enable(level); +#endif +} +RTM_EXPORT(rt_spin_unlock_irqrestore) + #ifdef RT_USING_SMP static struct rt_cpu rt_cpus[RT_CPUS_NR]; diff --git a/src/scheduler.c b/src/scheduler.c index b487bd4b60..0faafaa2fc 100644 --- a/src/scheduler.c +++ b/src/scheduler.c @@ -840,11 +840,14 @@ void rt_enter_critical(void) */ /* lock scheduler for all cpus */ - if (current_thread->scheduler_lock_nest == !!current_thread->cpus_lock_nest) + if (current_thread->critical_lock_nest == 0) { rt_hw_spin_lock(&_rt_critical_lock); } + /* critical for local cpu */ + current_thread->critical_lock_nest ++; + /* lock scheduler for local cpu */ current_thread->scheduler_lock_nest ++; @@ -892,7 +895,9 @@ void rt_exit_critical(void) current_thread->scheduler_lock_nest --; - if (current_thread->scheduler_lock_nest == !!current_thread->cpus_lock_nest) + current_thread->critical_lock_nest --; + + if (current_thread->critical_lock_nest == 0) { rt_hw_spin_unlock(&_rt_critical_lock); } @@ -951,7 +956,7 @@ rt_uint16_t rt_critical_level(void) #ifdef RT_USING_SMP struct rt_thread *current_thread = rt_cpu_self()->current_thread; - return current_thread->scheduler_lock_nest; + return current_thread->critical_lock_nest; #else return rt_scheduler_lock_nest; #endif /*RT_USING_SMP*/ diff --git a/src/thread.c b/src/thread.c index ab203b1d49..a88729e52c 100644 --- a/src/thread.c +++ b/src/thread.c @@ -172,6 +172,7 @@ static rt_err_t _rt_thread_init(struct rt_thread *thread, /* lock init */ thread->scheduler_lock_nest = 0; thread->cpus_lock_nest = 0; + thread->critical_lock_nest = 0; #endif /*RT_USING_SMP*/ /* initialize cleanup function and user data */ -- cgit v1.3.1 From 234af6aaa2ec2fd5c8c758a8f9fa29553ddeaf3f Mon Sep 17 00:00:00 2001 From: shaojinchun Date: Fri, 11 Oct 2019 09:13:40 +0800 Subject: 修正相同优先级任务切换太频繁的问题 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/rtdef.h | 1 + src/clock.c | 2 ++ src/scheduler.c | 15 +++++++++++++++ src/thread.c | 1 + 4 files changed, 19 insertions(+) (limited to 'include/rtdef.h') diff --git a/include/rtdef.h b/include/rtdef.h index 3dc8a2a2a9..90604e9b1d 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -608,6 +608,7 @@ struct rt_thread rt_ubase_t init_tick; /**< thread's initialized tick */ rt_ubase_t remaining_tick; /**< remaining tick */ + rt_ubase_t can_yield; /**< indicate whether remaining_tick has been reloaded since last schedule */ struct rt_timer thread_timer; /**< built-in thread timer */ diff --git a/src/clock.c b/src/clock.c index a652282b6e..d56f4b00f3 100644 --- a/src/clock.c +++ b/src/clock.c @@ -89,6 +89,8 @@ void rt_tick_increase(void) /* change to initialized tick */ thread->remaining_tick = thread->init_tick; + thread->can_yield = 1; + /* yield */ rt_thread_yield(); } diff --git a/src/scheduler.c b/src/scheduler.c index f671a49623..a4b4800d76 100644 --- a/src/scheduler.c +++ b/src/scheduler.c @@ -344,8 +344,13 @@ void rt_schedule(void) { to_thread = current_thread; } + else if (current_thread->current_priority == highest_ready_priority && current_thread->can_yield == 0) + { + to_thread = current_thread; + } else { + current_thread->can_yield = 0; rt_schedule_insert_thread(current_thread); } } @@ -435,8 +440,13 @@ void rt_schedule(void) { to_thread = rt_current_thread; } + else if (current_thread->current_priority == highest_ready_priority && current_thread->can_yield == 0) + { + to_thread = current_thread; + } else { + current_thread->can_yield = 0; need_insert_from_thread = 1; } } @@ -578,8 +588,13 @@ void rt_scheduler_do_irq_switch(void *context) { to_thread = current_thread; } + else if (current_thread->current_priority == highest_ready_priority && current_thread->can_yield == 0) + { + to_thread = current_thread; + } else { + current_thread->can_yield = 0; rt_schedule_insert_thread(current_thread); } } diff --git a/src/thread.c b/src/thread.c index a88729e52c..cf42c72a1b 100644 --- a/src/thread.c +++ b/src/thread.c @@ -159,6 +159,7 @@ static rt_err_t _rt_thread_init(struct rt_thread *thread, /* tick init */ thread->init_tick = tick; thread->remaining_tick = tick; + thread->can_yield = 0; /* error and flags */ thread->error = RT_EOK; -- cgit v1.3.1 From baeda71eaa8c00b7741365dd5fef09207ce4d743 Mon Sep 17 00:00:00 2001 From: Dryad <513205481@qq.com> Date: Mon, 28 Oct 2019 10:38:05 +0800 Subject: 修复了g++编译器无法展开自动初始化宏的错误 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/rtdef.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'include/rtdef.h') diff --git a/include/rtdef.h b/include/rtdef.h index 3dc8a2a2a9..ca7887e40d 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -200,11 +200,11 @@ typedef int (*init_fn_t)(void); }; #define INIT_EXPORT(fn, level) \ const char __rti_##fn##_name[] = #fn; \ - RT_USED const struct rt_init_desc __rt_init_desc_##fn SECTION(".rti_fn."level) = \ + RT_USED const struct rt_init_desc __rt_init_desc_##fn SECTION(".rti_fn." level) = \ { __rti_##fn##_name, fn}; #else #define INIT_EXPORT(fn, level) \ - RT_USED const init_fn_t __rt_init_##fn SECTION(".rti_fn."level) = fn + RT_USED const init_fn_t __rt_init_##fn SECTION(".rti_fn." level) = fn #endif #endif #else -- cgit v1.3.1 From e03ac83ad3d22c578e367550d2ff714b53e79799 Mon Sep 17 00:00:00 2001 From: shaojinchun Date: Tue, 5 Nov 2019 08:41:38 +0800 Subject: 将yield状态置于tcb的stat位域中 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/rtdef.h | 6 ++++-- src/clock.c | 2 +- src/scheduler.c | 12 ++++++------ src/thread.c | 1 - 4 files changed, 11 insertions(+), 10 deletions(-) (limited to 'include/rtdef.h') diff --git a/include/rtdef.h b/include/rtdef.h index 90604e9b1d..119e9d7893 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -491,7 +491,10 @@ typedef siginfo_t rt_siginfo_t; #define RT_THREAD_RUNNING 0x03 /**< Running status */ #define RT_THREAD_BLOCK RT_THREAD_SUSPEND /**< Blocked status */ #define RT_THREAD_CLOSE 0x04 /**< Closed status */ -#define RT_THREAD_STAT_MASK 0x0f +#define RT_THREAD_STAT_MASK 0x07 + +#define RT_THREAD_STAT_YIELD 0x08 /**< indicate whether remaining_tick has been reloaded since last schedule */ +#define RT_THREAD_STAT_YIELD_MASK RT_THREAD_STAT_YIELD #define RT_THREAD_STAT_SIGNAL 0x10 /**< task hold signals */ #define RT_THREAD_STAT_SIGNAL_READY (RT_THREAD_STAT_SIGNAL | RT_THREAD_READY) @@ -608,7 +611,6 @@ struct rt_thread rt_ubase_t init_tick; /**< thread's initialized tick */ rt_ubase_t remaining_tick; /**< remaining tick */ - rt_ubase_t can_yield; /**< indicate whether remaining_tick has been reloaded since last schedule */ struct rt_timer thread_timer; /**< built-in thread timer */ diff --git a/src/clock.c b/src/clock.c index e288ff58a9..9b54101363 100644 --- a/src/clock.c +++ b/src/clock.c @@ -89,7 +89,7 @@ void rt_tick_increase(void) /* change to initialized tick */ thread->remaining_tick = thread->init_tick; - thread->can_yield = RT_TRUE; + thread->stat |= RT_THREAD_STAT_YIELD; /* yield */ rt_thread_yield(); diff --git a/src/scheduler.c b/src/scheduler.c index c58ecf6209..edcf11dba5 100644 --- a/src/scheduler.c +++ b/src/scheduler.c @@ -344,13 +344,13 @@ void rt_schedule(void) { to_thread = current_thread; } - else if (current_thread->current_priority == highest_ready_priority && current_thread->can_yield == RT_FALSE) + else if (current_thread->current_priority == highest_ready_priority && (current_thread->stat & RT_THREAD_STAT_YIELD_MASK) == 0) { to_thread = current_thread; } else { - current_thread->can_yield = RT_FALSE; + current_thread->stat &= ~RT_THREAD_STAT_YIELD_MASK; rt_schedule_insert_thread(current_thread); } } @@ -440,13 +440,13 @@ void rt_schedule(void) { to_thread = rt_current_thread; } - else if (rt_current_thread->current_priority == highest_ready_priority && rt_current_thread->can_yield == RT_FALSE) + else if (rt_current_thread->current_priority == highest_ready_priority && (rt_current_thread->stat & RT_THREAD_STAT_YIELD_MASK) == 0) { to_thread = rt_current_thread; } else { - rt_current_thread->can_yield = RT_FALSE; + rt_current_thread->stat &= ~RT_THREAD_STAT_YIELD_MASK; need_insert_from_thread = 1; } } @@ -588,13 +588,13 @@ void rt_scheduler_do_irq_switch(void *context) { to_thread = current_thread; } - else if (current_thread->current_priority == highest_ready_priority && current_thread->can_yield == RT_FALSE) + else if (current_thread->current_priority == highest_ready_priority && (current_thread->stat & RT_THREAD_STAT_YIELD_MASK) == 0) { to_thread = current_thread; } else { - current_thread->can_yield = RT_FALSE; + current_thread->stat &= ~RT_THREAD_STAT_YIELD_MASK; rt_schedule_insert_thread(current_thread); } } diff --git a/src/thread.c b/src/thread.c index 6f6fa1029a..a88729e52c 100644 --- a/src/thread.c +++ b/src/thread.c @@ -159,7 +159,6 @@ static rt_err_t _rt_thread_init(struct rt_thread *thread, /* tick init */ thread->init_tick = tick; thread->remaining_tick = tick; - thread->can_yield = RT_FALSE; /* error and flags */ thread->error = RT_EOK; -- cgit v1.3.1 From 992d3af3aee1e8567080e33e27011170f60dfab9 Mon Sep 17 00:00:00 2001 From: Bernard Xiong Date: Mon, 16 Dec 2019 13:59:46 +0800 Subject: [kernel] code and comments cleanup --- include/libc/libc_signal.h | 6 +-- include/rtdef.h | 2 +- include/rthw.h | 2 +- src/clock.c | 2 +- src/device.c | 16 ++++---- src/ipc.c | 94 +++++++++++++++++++++++----------------------- src/kservice.c | 2 +- src/signal.c | 4 +- src/thread.c | 6 +-- 9 files changed, 67 insertions(+), 67 deletions(-) (limited to 'include/rtdef.h') diff --git a/include/libc/libc_signal.h b/include/libc/libc_signal.h index 71f8de125d..c77f36798c 100644 --- a/include/libc/libc_signal.h +++ b/include/libc/libc_signal.h @@ -24,7 +24,7 @@ extern "C" { NOTE: P1003.1c/D10, p. 34 adds sigev_notify_function and sigev_notify_attributes to the sigevent structure. */ -union sigval +union sigval { int sival_int; /* Integer signal value */ void *sival_ptr; /* Pointer signal value */ @@ -107,7 +107,7 @@ typedef unsigned long sigset_t; typedef void (*_sig_func_ptr)(int); -struct sigaction +struct sigaction { _sig_func_ptr sa_handler; sigset_t sa_mask; @@ -163,7 +163,7 @@ typedef unsigned long sigset_t; typedef void (*_sig_func_ptr)(int); -struct sigaction +struct sigaction { _sig_func_ptr sa_handler; sigset_t sa_mask; diff --git a/include/rtdef.h b/include/rtdef.h index 3f0b116785..b3aa38d3af 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -522,7 +522,7 @@ typedef siginfo_t rt_siginfo_t; /** * CPUs definitions - * + * */ struct rt_cpu { diff --git a/include/rthw.h b/include/rthw.h index 2a602dcfe7..89877faf90 100644 --- a/include/rthw.h +++ b/include/rthw.h @@ -37,7 +37,7 @@ extern "C" { #endif #ifndef RT_CPU_CACHE_LINE_SZ -#define RT_CPU_CACHE_LINE_SZ 32 +#define RT_CPU_CACHE_LINE_SZ 32 #endif enum RT_HW_CACHE_OPS diff --git a/src/clock.c b/src/clock.c index 9b54101363..97a09ddeaf 100644 --- a/src/clock.c +++ b/src/clock.c @@ -25,7 +25,7 @@ static rt_tick_t rt_tick = 0; #endif /** - * This function will init system tick and set it to zero. + * This function will initialize system tick and set it to zero. * @ingroup SystemInit * * @deprecated since 1.1.0, this function does not need to be invoked diff --git a/src/device.c b/src/device.c index 51fc6176a6..32c06b380c 100644 --- a/src/device.c +++ b/src/device.c @@ -95,7 +95,7 @@ RTM_EXPORT(rt_device_unregister); * @return the error code, RT_EOK on successfully. * * @deprecated since 1.2.x, this function is not needed because the initialization - * of a device is performed when applicaiton opens it. + * of a device is performed when application opens it. */ rt_err_t rt_device_init_all(void) { @@ -162,7 +162,7 @@ rt_device_t rt_device_create(int type, int attach_size) size = RT_ALIGN(sizeof(struct rt_device), RT_ALIGN_SIZE); attach_size = RT_ALIGN(attach_size, RT_ALIGN_SIZE); - /* use the totoal size */ + /* use the total size */ size += attach_size; device = (rt_device_t)rt_malloc(size); @@ -208,7 +208,7 @@ rt_err_t rt_device_init(rt_device_t dev) RT_ASSERT(dev != RT_NULL); - /* get device init handler */ + /* get device_init handler */ if (device_init != RT_NULL) { if (!(dev->flag & RT_DEVICE_FLAG_ACTIVATED)) @@ -269,7 +269,7 @@ rt_err_t rt_device_open(rt_device_t dev, rt_uint16_t oflag) return -RT_EBUSY; } - /* call device open interface */ + /* call device_open interface */ if (device_open != RT_NULL) { result = device_open(dev, oflag); @@ -317,7 +317,7 @@ rt_err_t rt_device_close(rt_device_t dev) if (dev->ref_count != 0) return RT_EOK; - /* call device close interface */ + /* call device_close interface */ if (device_close != RT_NULL) { result = device_close(dev); @@ -357,7 +357,7 @@ rt_size_t rt_device_read(rt_device_t dev, return 0; } - /* call device read interface */ + /* call device_read interface */ if (device_read != RT_NULL) { return device_read(dev, pos, buffer, size); @@ -396,7 +396,7 @@ rt_size_t rt_device_write(rt_device_t dev, return 0; } - /* call device write interface */ + /* call device_write interface */ if (device_write != RT_NULL) { return device_write(dev, pos, buffer, size); @@ -423,7 +423,7 @@ rt_err_t rt_device_control(rt_device_t dev, int cmd, void *arg) RT_ASSERT(dev != RT_NULL); RT_ASSERT(rt_object_get_type(&dev->parent) == RT_Object_Class_Device); - /* call device write interface */ + /* call device_write interface */ if (device_control != RT_NULL) { return device_control(dev, cmd, arg); diff --git a/src/ipc.c b/src/ipc.c index 6a8234a747..e6955bae37 100644 --- a/src/ipc.c +++ b/src/ipc.c @@ -60,7 +60,7 @@ extern void (*rt_object_put_hook)(struct rt_object *object); */ rt_inline rt_err_t rt_ipc_object_init(struct rt_ipc_object *ipc) { - /* init ipc object */ + /* initialize ipc object */ rt_list_init(&(ipc->suspend_thread)); return RT_EOK; @@ -159,13 +159,13 @@ rt_inline rt_err_t rt_ipc_list_resume_all(rt_list_t *list) struct rt_thread *thread; register rt_ubase_t temp; - /* wakeup all suspend threads */ + /* wakeup all suspended threads */ while (!rt_list_isempty(list)) { /* disable interrupt */ temp = rt_hw_interrupt_disable(); - /* get next suspend thread */ + /* get next suspended thread */ thread = rt_list_entry(list->next, struct rt_thread, tlist); /* set error code to RT_ERROR */ thread->error = -RT_ERROR; @@ -173,7 +173,7 @@ rt_inline rt_err_t rt_ipc_list_resume_all(rt_list_t *list) /* * resume thread * In rt_thread_resume function, it will remove current thread from - * suspend list + * suspended list */ rt_thread_resume(thread); @@ -191,7 +191,7 @@ rt_inline rt_err_t rt_ipc_list_resume_all(rt_list_t *list) * * @param sem the semaphore object * @param name the name of semaphore - * @param value the init value of semaphore + * @param value the initial value of semaphore * @param flag the flag of semaphore * * @return the operation status, RT_EOK on successful @@ -204,13 +204,13 @@ rt_err_t rt_sem_init(rt_sem_t sem, RT_ASSERT(sem != RT_NULL); RT_ASSERT(value < 0x10000U); - /* init object */ + /* initialize object */ rt_object_init(&(sem->parent.parent), RT_Object_Class_Semaphore, name); - /* init ipc object */ + /* initialize ipc object */ rt_ipc_object_init(&(sem->parent)); - /* set init value */ + /* set initial value */ sem->value = (rt_uint16_t)value; /* set parent */ @@ -236,7 +236,7 @@ rt_err_t rt_sem_detach(rt_sem_t sem) RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent)); - /* wakeup all suspend threads */ + /* wakeup all suspended threads */ rt_ipc_list_resume_all(&(sem->parent.suspend_thread)); /* detach semaphore object */ @@ -251,7 +251,7 @@ RTM_EXPORT(rt_sem_detach); * This function will create a semaphore from system resource * * @param name the name of semaphore - * @param value the init value of semaphore + * @param value the initial value of semaphore * @param flag the flag of semaphore * * @return the created semaphore, RT_NULL on error happen @@ -270,10 +270,10 @@ rt_sem_t rt_sem_create(const char *name, rt_uint32_t value, rt_uint8_t flag) if (sem == RT_NULL) return sem; - /* init ipc object */ + /* initialize ipc object */ rt_ipc_object_init(&(sem->parent)); - /* set init value */ + /* set initial value */ sem->value = value; /* set parent */ @@ -301,7 +301,7 @@ rt_err_t rt_sem_delete(rt_sem_t sem) RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent) == RT_FALSE); - /* wakeup all suspend threads */ + /* wakeup all suspended threads */ rt_ipc_list_resume_all(&(sem->parent.suspend_thread)); /* delete semaphore object */ @@ -532,10 +532,10 @@ rt_err_t rt_mutex_init(rt_mutex_t mutex, const char *name, rt_uint8_t flag) /* parameter check */ RT_ASSERT(mutex != RT_NULL); - /* init object */ + /* initialize object */ rt_object_init(&(mutex->parent.parent), RT_Object_Class_Mutex, name); - /* init ipc object */ + /* initialize ipc object */ rt_ipc_object_init(&(mutex->parent)); mutex->value = 1; @@ -566,10 +566,10 @@ rt_err_t rt_mutex_detach(rt_mutex_t mutex) RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent)); - /* wakeup all suspend threads */ + /* wakeup all suspended threads */ rt_ipc_list_resume_all(&(mutex->parent.suspend_thread)); - /* detach mutex object */ + /* detach semaphore object */ rt_object_detach(&(mutex->parent.parent)); return RT_EOK; @@ -598,7 +598,7 @@ rt_mutex_t rt_mutex_create(const char *name, rt_uint8_t flag) if (mutex == RT_NULL) return mutex; - /* init ipc object */ + /* initialize ipc object */ rt_ipc_object_init(&(mutex->parent)); mutex->value = 1; @@ -631,7 +631,7 @@ rt_err_t rt_mutex_delete(rt_mutex_t mutex) RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent) == RT_FALSE); - /* wakeup all suspend threads */ + /* wakeup all suspended threads */ rt_ipc_list_resume_all(&(mutex->parent.suspend_thread)); /* delete mutex object */ @@ -917,16 +917,16 @@ rt_err_t rt_event_init(rt_event_t event, const char *name, rt_uint8_t flag) /* parameter check */ RT_ASSERT(event != RT_NULL); - /* init object */ + /* initialize object */ rt_object_init(&(event->parent.parent), RT_Object_Class_Event, name); /* set parent flag */ event->parent.parent.flag = flag; - /* init ipc object */ + /* initialize ipc object */ rt_ipc_object_init(&(event->parent)); - /* init event */ + /* initialize event */ event->set = 0; return RT_EOK; @@ -980,10 +980,10 @@ rt_event_t rt_event_create(const char *name, rt_uint8_t flag) /* set parent */ event->parent.parent.flag = flag; - /* init ipc object */ + /* initialize ipc object */ rt_ipc_object_init(&(event->parent)); - /* init event */ + /* initialize event */ event->set = 0; return event; @@ -1050,7 +1050,7 @@ rt_err_t rt_event_send(rt_event_t event, rt_uint32_t set) event->set |= set; RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(event->parent.parent))); - + if (!rt_list_isempty(&event->parent.suspend_thread)) { /* search thread list to resume thread */ @@ -1073,7 +1073,7 @@ rt_err_t rt_event_send(rt_event_t event, rt_uint32_t set) { if (thread->event_set & event->set) { - /* save recieved event set */ + /* save the received event set */ thread->event_set = thread->event_set & event->set; /* received an OR event */ @@ -1143,7 +1143,7 @@ rt_err_t rt_event_recv(rt_event_t event, if (set == 0) return -RT_ERROR; - /* init status */ + /* initialize status */ status = -RT_ERROR; /* get current thread */ thread = rt_thread_self(); @@ -1253,7 +1253,7 @@ rt_err_t rt_event_control(rt_event_t event, int cmd, void *arg) /* parameter check */ RT_ASSERT(event != RT_NULL); RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); - + if (cmd == RT_IPC_CMD_RESET) { /* disable interrupt */ @@ -1262,7 +1262,7 @@ rt_err_t rt_event_control(rt_event_t event, int cmd, void *arg) /* resume all waiting thread */ rt_ipc_list_resume_all(&event->parent.suspend_thread); - /* init event set */ + /* initialize event set */ event->set = 0; /* enable interrupt */ @@ -1299,23 +1299,23 @@ rt_err_t rt_mb_init(rt_mailbox_t mb, { RT_ASSERT(mb != RT_NULL); - /* init object */ + /* initialize object */ rt_object_init(&(mb->parent.parent), RT_Object_Class_MailBox, name); /* set parent flag */ mb->parent.parent.flag = flag; - /* init ipc object */ + /* initialize ipc object */ rt_ipc_object_init(&(mb->parent)); - /* init mailbox */ + /* initialize mailbox */ mb->msg_pool = (rt_ubase_t *)msgpool; mb->size = size; mb->entry = 0; mb->in_offset = 0; mb->out_offset = 0; - /* init an additional list of sender suspend thread */ + /* initialize an additional list of sender suspend thread */ rt_list_init(&(mb->suspend_sender_thread)); return RT_EOK; @@ -1372,10 +1372,10 @@ rt_mailbox_t rt_mb_create(const char *name, rt_size_t size, rt_uint8_t flag) /* set parent */ mb->parent.parent.flag = flag; - /* init ipc object */ + /* initialize ipc object */ rt_ipc_object_init(&(mb->parent)); - /* init mailbox */ + /* initialize mailbox */ mb->size = size; mb->msg_pool = (rt_ubase_t *)RT_KERNEL_MALLOC(mb->size * sizeof(rt_ubase_t)); if (mb->msg_pool == RT_NULL) @@ -1389,7 +1389,7 @@ rt_mailbox_t rt_mb_create(const char *name, rt_size_t size, rt_uint8_t flag) mb->in_offset = 0; mb->out_offset = 0; - /* init an additional list of sender suspend thread */ + /* initialize an additional list of sender suspend thread */ rt_list_init(&(mb->suspend_sender_thread)); return mb; @@ -1791,27 +1791,27 @@ rt_err_t rt_mq_init(rt_mq_t mq, /* parameter check */ RT_ASSERT(mq != RT_NULL); - /* init object */ + /* initialize object */ rt_object_init(&(mq->parent.parent), RT_Object_Class_MessageQueue, name); /* set parent flag */ mq->parent.parent.flag = flag; - /* init ipc object */ + /* initialize ipc object */ rt_ipc_object_init(&(mq->parent)); - /* set messasge pool */ + /* set message pool */ mq->msg_pool = msgpool; /* get correct message size */ mq->msg_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); mq->max_msgs = pool_size / (mq->msg_size + sizeof(struct rt_mq_message)); - /* init message list */ + /* initialize message list */ mq->msg_queue_head = RT_NULL; mq->msg_queue_tail = RT_NULL; - /* init message empty list */ + /* initialize message empty list */ mq->msg_queue_free = RT_NULL; for (temp = 0; temp < mq->max_msgs; temp ++) { @@ -1824,7 +1824,7 @@ rt_err_t rt_mq_init(rt_mq_t mq, /* the initial entry is zero */ mq->entry = 0; - /* init an additional list of sender suspend thread */ + /* initialize an additional list of sender suspend thread */ rt_list_init(&(mq->suspend_sender_thread)); return RT_EOK; @@ -1887,10 +1887,10 @@ rt_mq_t rt_mq_create(const char *name, /* set parent */ mq->parent.parent.flag = flag; - /* init ipc object */ + /* initialize ipc object */ rt_ipc_object_init(&(mq->parent)); - /* init message queue */ + /* initialize message queue */ /* get correct message size */ mq->msg_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); @@ -1905,11 +1905,11 @@ rt_mq_t rt_mq_create(const char *name, return RT_NULL; } - /* init message list */ + /* initialize message list */ mq->msg_queue_head = RT_NULL; mq->msg_queue_tail = RT_NULL; - /* init message empty list */ + /* initialize message empty list */ mq->msg_queue_free = RT_NULL; for (temp = 0; temp < mq->max_msgs; temp ++) { @@ -1922,7 +1922,7 @@ rt_mq_t rt_mq_create(const char *name, /* the initial entry is zero */ mq->entry = 0; - /* init an additional list of sender suspend thread */ + /* initialize an additional list of sender suspend thread */ rt_list_init(&(mq->suspend_sender_thread)); return mq; diff --git a/src/kservice.c b/src/kservice.c index 202bd97f83..58f04330f1 100644 --- a/src/kservice.c +++ b/src/kservice.c @@ -316,7 +316,7 @@ RTM_EXPORT(rt_memmove); * This function will compare two areas of memory * * @param cs one area of memory - * @param ct znother area of memory + * @param ct another area of memory * @param count the size of the area * * @return the result diff --git a/src/signal.c b/src/signal.c index bea3615d34..bb9339ab6c 100644 --- a/src/signal.c +++ b/src/signal.c @@ -22,8 +22,8 @@ #define RT_SIG_INFO_MAX 32 #endif -#define DBG_TAG "SIGN" -#define DBG_LVL DBG_WARNING +#define DBG_TAG "SIGN" +#define DBG_LVL DBG_WARNING #include #define sig_mask(sig_no) (1u << sig_no) diff --git a/src/thread.c b/src/thread.c index c5f75a1176..7596906fae 100644 --- a/src/thread.c +++ b/src/thread.c @@ -179,7 +179,7 @@ static rt_err_t _rt_thread_init(struct rt_thread *thread, thread->cleanup = 0; thread->user_data = 0; - /* init thread timer */ + /* initialize thread timer */ rt_timer_init(&(thread->thread_timer), thread->name, rt_thread_timeout, @@ -242,7 +242,7 @@ rt_err_t rt_thread_init(struct rt_thread *thread, RT_ASSERT(thread != RT_NULL); RT_ASSERT(stack_start != RT_NULL); - /* init thread object */ + /* initialize thread object */ rt_object_init((rt_object_t)thread, RT_Object_Class_Thread, name); return _rt_thread_init(thread, @@ -293,7 +293,7 @@ rt_err_t rt_thread_startup(rt_thread_t thread) RT_ASSERT((thread->stat & RT_THREAD_STAT_MASK) == RT_THREAD_INIT); RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); - /* set current priority to init priority */ + /* set current priority to initialize priority */ thread->current_priority = thread->init_priority; /* calculate priority attribute */ -- cgit v1.3.1 From 64945ba882d651a14933eb4e7b3d93d10d6daae1 Mon Sep 17 00:00:00 2001 From: Bernard Xiong Date: Fri, 20 Dec 2019 08:24:45 +0800 Subject: [Kernel] Update version number. --- include/rtdef.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'include/rtdef.h') diff --git a/include/rtdef.h b/include/rtdef.h index b3aa38d3af..c8184a5a4b 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -31,6 +31,7 @@ * add smp relevant macros * 2019-01-27 Bernard change version number to v4.0.1 * 2019-05-17 Bernard change version number to v4.0.2 + * 2019-12-20 Bernard change version number to v4.0.3 */ #ifndef __RT_DEF_H__ @@ -52,7 +53,7 @@ extern "C" { /* RT-Thread version information */ #define RT_VERSION 4L /**< major version number */ #define RT_SUBVERSION 0L /**< minor version number */ -#define RT_REVISION 2L /**< revise version number */ +#define RT_REVISION 3L /**< revise version number */ /* RT-Thread version */ #define RTTHREAD_VERSION ((RT_VERSION * 10000) + \ -- cgit v1.3.1 From 720d8479a574746020747ef36bc33a8159206289 Mon Sep 17 00:00:00 2001 From: longtengmcu Date: Fri, 7 Feb 2020 16:43:39 +0800 Subject: 给软件定时器增加定时器工作状态查询的功能 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/rtdef.h | 1 + src/timer.c | 13 +++++++++++++ 2 files changed, 14 insertions(+) (limited to 'include/rtdef.h') diff --git a/include/rtdef.h b/include/rtdef.h index c8184a5a4b..8b86213082 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -431,6 +431,7 @@ struct rt_object_information #define RT_TIMER_CTRL_GET_TIME 0x1 /**< get timer control command */ #define RT_TIMER_CTRL_SET_ONESHOT 0x2 /**< change timer to one shot */ #define RT_TIMER_CTRL_SET_PERIODIC 0x3 /**< change timer to periodic */ +#define RT_TIMER_CTRL_GET_STATE 0x4 /**< get timer run state active or deactive*/ #ifndef RT_TIMER_SKIP_LIST_LEVEL #define RT_TIMER_SKIP_LIST_LEVEL 1 diff --git a/src/timer.c b/src/timer.c index d85ee080b5..0034f0246c 100644 --- a/src/timer.c +++ b/src/timer.c @@ -488,6 +488,19 @@ rt_err_t rt_timer_control(rt_timer_t timer, int cmd, void *arg) case RT_TIMER_CTRL_SET_PERIODIC: timer->parent.flag |= RT_TIMER_FLAG_PERIODIC; break; + /* zhaoshimin 20191204 add query the timer state */ + case RT_TIMER_CTRL_GET_STATE: + if(timer->parent.flag & RT_TIMER_FLAG_ACTIVATED) + { + /*timer is start and run*/ + *(rt_tick_t *)arg = RT_TIMER_FLAG_ACTIVATED; + } + else + { + /*timer is stop*/ + *(rt_tick_t *)arg = RT_TIMER_FLAG_DEACTIVATED; + } + break; } return RT_EOK; -- cgit v1.3.1 From e5c1183350966cd242093c626f2f2c3944122498 Mon Sep 17 00:00:00 2001 From: SummerGift Date: Mon, 23 Mar 2020 15:35:27 +0800 Subject: [optimize] stm32 uart driver --- bsp/stm32/libraries/HAL_Drivers/drv_usart.c | 288 ++++++++++++++++------------ bsp/stm32/libraries/HAL_Drivers/drv_usart.h | 4 +- components/drivers/serial/serial.c | 14 +- include/rtdef.h | 1 + 4 files changed, 182 insertions(+), 125 deletions(-) (limited to 'include/rtdef.h') diff --git a/bsp/stm32/libraries/HAL_Drivers/drv_usart.c b/bsp/stm32/libraries/HAL_Drivers/drv_usart.c index 64ca8fe4b3..faf010c138 100644 --- a/bsp/stm32/libraries/HAL_Drivers/drv_usart.c +++ b/bsp/stm32/libraries/HAL_Drivers/drv_usart.c @@ -6,6 +6,8 @@ * Change Logs: * Date Author Notes * 2018-10-30 SummerGift first version + * 2020-03-16 SummerGift add device close feature + * 2020-03-20 SummerGift fix bug caused by ORE */ #include "board.h" @@ -21,12 +23,12 @@ #if !defined(BSP_USING_UART1) && !defined(BSP_USING_UART2) && !defined(BSP_USING_UART3) && \ !defined(BSP_USING_UART4) && !defined(BSP_USING_UART5) && !defined(BSP_USING_UART6) && \ !defined(BSP_USING_UART7) && !defined(BSP_USING_UART8) && !defined(BSP_USING_LPUART1) - #error "Please define at least one BSP_USING_UARTx" - /* this driver can be disabled at menuconfig -> RT-Thread Components -> Device Drivers */ +#error "Please define at least one BSP_USING_UARTx" +/* this driver can be disabled at menuconfig -> RT-Thread Components -> Device Drivers */ #endif #ifdef RT_SERIAL_USING_DMA - static void stm32_dma_config(struct rt_serial_device *serial, rt_ubase_t flag); +static void stm32_dma_config(struct rt_serial_device *serial, rt_ubase_t flag); #endif enum @@ -100,12 +102,12 @@ static rt_err_t stm32_configure(struct rt_serial_device *serial, struct serial_c RT_ASSERT(cfg != RT_NULL); uart = rt_container_of(serial, struct stm32_uart, serial); - uart->handle.Instance = uart->config->Instance; uart->handle.Init.BaudRate = cfg->baud_rate; uart->handle.Init.HwFlowCtl = UART_HWCONTROL_NONE; uart->handle.Init.Mode = UART_MODE_TX_RX; uart->handle.Init.OverSampling = UART_OVERSAMPLING_16; + switch (cfg->data_bits) { case DATA_BITS_8: @@ -118,6 +120,7 @@ static rt_err_t stm32_configure(struct rt_serial_device *serial, struct serial_c uart->handle.Init.WordLength = UART_WORDLENGTH_8B; break; } + switch (cfg->stop_bits) { case STOP_BITS_1: @@ -130,6 +133,7 @@ static rt_err_t stm32_configure(struct rt_serial_device *serial, struct serial_c uart->handle.Init.StopBits = UART_STOPBITS_1; break; } + switch (cfg->parity) { case PARITY_NONE: @@ -146,6 +150,10 @@ static rt_err_t stm32_configure(struct rt_serial_device *serial, struct serial_c break; } +#ifdef RT_SERIAL_USING_DMA + uart->dma_rx.last_index = 0; +#endif + if (HAL_UART_Init(&uart->handle) != HAL_OK) { return -RT_ERROR; @@ -172,7 +180,33 @@ static rt_err_t stm32_control(struct rt_serial_device *serial, int cmd, void *ar NVIC_DisableIRQ(uart->config->irq_type); /* disable interrupt */ __HAL_UART_DISABLE_IT(&(uart->handle), UART_IT_RXNE); + +#ifdef RT_SERIAL_USING_DMA + /* disable DMA */ + if (ctrl_arg == RT_DEVICE_FLAG_DMA_RX) + { + HAL_NVIC_DisableIRQ(uart->config->dma_rx->dma_irq); + if (HAL_DMA_Abort(&(uart->dma_rx.handle)) != HAL_OK) + { + RT_ASSERT(0); + } + + if (HAL_DMA_DeInit(&(uart->dma_rx.handle)) != HAL_OK) + { + RT_ASSERT(0); + } + } + else if(ctrl_arg == RT_DEVICE_FLAG_DMA_TX) + { + HAL_NVIC_DisableIRQ(uart->config->dma_tx->dma_irq); + if (HAL_DMA_DeInit(&(uart->dma_tx.handle)) != HAL_OK) + { + RT_ASSERT(0); + } + } +#endif break; + /* enable interrupt */ case RT_DEVICE_CTRL_SET_INT: /* enable rx irq */ @@ -186,6 +220,14 @@ static rt_err_t stm32_control(struct rt_serial_device *serial, int cmd, void *ar stm32_dma_config(serial, ctrl_arg); break; #endif + + case RT_DEVICE_CTRL_CLOSE: + if (HAL_UART_DeInit(&(uart->handle)) != HAL_OK ) + { + RT_ASSERT(0) + } + break; + } return RT_EOK; } @@ -233,13 +275,14 @@ static rt_size_t stm32_dma_transmit(struct rt_serial_device *serial, rt_uint8_t { struct stm32_uart *uart; RT_ASSERT(serial != RT_NULL); + RT_ASSERT(buf != RT_NULL); uart = rt_container_of(serial, struct stm32_uart, serial); - + if (size == 0) { return 0; } - + if (RT_SERIAL_DMA_TX == direction) { if (HAL_UART_Transmit_DMA(&uart->handle, buf, size) == HAL_OK) @@ -254,15 +297,6 @@ static rt_size_t stm32_dma_transmit(struct rt_serial_device *serial, rt_uint8_t return 0; } -static const struct rt_uart_ops stm32_uart_ops = -{ - .configure = stm32_configure, - .control = stm32_control, - .putc = stm32_putc, - .getc = stm32_getc, - .dma_transmit = stm32_dma_transmit -}; - /** * Uart common interrupt process. This need add to uart ISR. * @@ -301,16 +335,14 @@ static void uart_isr(struct rt_serial_device *serial) } __HAL_UART_CLEAR_IDLEFLAG(&uart->handle); } - else if (__HAL_UART_GET_FLAG(&(uart->handle), UART_FLAG_TC) != RESET) + else if (__HAL_UART_GET_FLAG(&(uart->handle), UART_FLAG_TC) && + (__HAL_UART_GET_IT_SOURCE(&(uart->handle), UART_IT_TC) != RESET)) { if ((serial->parent.open_flag & RT_DEVICE_FLAG_DMA_TX) != 0) { HAL_UART_IRQHandler(&(uart->handle)); } - else - { - UART_INSTANCE_CLEAR_FUNCTION(&(uart->handle), UART_FLAG_TC); - } + UART_INSTANCE_CLEAR_FUNCTION(&(uart->handle), UART_FLAG_TC); } #endif else @@ -714,6 +746,93 @@ void LPUART1_DMA_RX_IRQHandler(void) #endif /* defined(RT_SERIAL_USING_DMA) && defined(BSP_LPUART1_RX_USING_DMA) */ #endif /* BSP_USING_LPUART1*/ +static void stm32_uart_get_dma_config(void) +{ +#ifdef BSP_USING_UART1 + uart_obj[UART1_INDEX].uart_dma_flag = 0; +#ifdef BSP_UART1_RX_USING_DMA + uart_obj[UART1_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_RX; + static struct dma_config uart1_dma_rx = UART1_DMA_RX_CONFIG; + uart_config[UART1_INDEX].dma_rx = &uart1_dma_rx; +#endif +#ifdef BSP_UART1_TX_USING_DMA + uart_obj[UART1_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_TX; + static struct dma_config uart1_dma_tx = UART1_DMA_TX_CONFIG; + uart_config[UART1_INDEX].dma_tx = &uart1_dma_tx; +#endif +#endif + +#ifdef BSP_USING_UART2 + uart_obj[UART2_INDEX].uart_dma_flag = 0; +#ifdef BSP_UART2_RX_USING_DMA + uart_obj[UART2_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_RX; + static struct dma_config uart2_dma_rx = UART2_DMA_RX_CONFIG; + uart_config[UART2_INDEX].dma_rx = &uart2_dma_rx; +#endif +#ifdef BSP_UART2_TX_USING_DMA + uart_obj[UART2_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_TX; + static struct dma_config uart2_dma_tx = UART2_DMA_TX_CONFIG; + uart_config[UART2_INDEX].dma_tx = &uart2_dma_tx; +#endif +#endif + +#ifdef BSP_USING_UART3 + uart_obj[UART3_INDEX].uart_dma_flag = 0; +#ifdef BSP_UART3_RX_USING_DMA + uart_obj[UART3_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_RX; + static struct dma_config uart3_dma_rx = UART3_DMA_RX_CONFIG; + uart_config[UART3_INDEX].dma_rx = &uart3_dma_rx; +#endif +#ifdef BSP_UART3_TX_USING_DMA + uart_obj[UART3_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_TX; + static struct dma_config uart3_dma_tx = UART3_DMA_TX_CONFIG; + uart_config[UART3_INDEX].dma_tx = &uart3_dma_tx; +#endif +#endif + +#ifdef BSP_USING_UART4 + uart_obj[UART4_INDEX].uart_dma_flag = 0; +#ifdef BSP_UART4_RX_USING_DMA + uart_obj[UART4_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_RX; + static struct dma_config uart4_dma_rx = UART4_DMA_RX_CONFIG; + uart_config[UART4_INDEX].dma_rx = &uart4_dma_rx; +#endif +#ifdef BSP_UART4_TX_USING_DMA + uart_obj[UART4_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_TX; + static struct dma_config uart4_dma_tx = UART4_DMA_TX_CONFIG; + uart_config[UART4_INDEX].dma_tx = &uart4_dma_tx; +#endif +#endif + +#ifdef BSP_USING_UART5 + uart_obj[UART5_INDEX].uart_dma_flag = 0; +#ifdef BSP_UART5_RX_USING_DMA + uart_obj[UART5_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_RX; + static struct dma_config uart5_dma_rx = UART5_DMA_RX_CONFIG; + uart_config[UART5_INDEX].dma_rx = &uart5_dma_rx; +#endif +#ifdef BSP_UART5_TX_USING_DMA + uart_obj[UART5_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_TX; + static struct dma_config uart5_dma_tx = UART5_DMA_TX_CONFIG; + uart_config[UART5_INDEX].dma_tx = &uart5_dma_tx; +#endif +#endif + +#ifdef BSP_USING_UART6 + uart_obj[UART6_INDEX].uart_dma_flag = 0; +#ifdef BSP_UART6_RX_USING_DMA + uart_obj[UART6_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_RX; + static struct dma_config uart6_dma_rx = UART6_DMA_RX_CONFIG; + uart_config[UART6_INDEX].dma_rx = &uart6_dma_rx; +#endif +#ifdef BSP_UART6_TX_USING_DMA + uart_obj[UART6_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_TX; + static struct dma_config uart6_dma_tx = UART6_DMA_TX_CONFIG; + uart_config[UART6_INDEX].dma_tx = &uart6_dma_tx; +#endif +#endif +} + #ifdef RT_SERIAL_USING_DMA static void stm32_dma_config(struct rt_serial_device *serial, rt_ubase_t flag) { @@ -721,7 +840,7 @@ static void stm32_dma_config(struct rt_serial_device *serial, rt_ubase_t flag) DMA_HandleTypeDef *DMA_Handle; struct dma_config *dma_config; struct stm32_uart *uart; - + RT_ASSERT(serial != RT_NULL); uart = rt_container_of(serial, struct stm32_uart, serial); @@ -781,7 +900,7 @@ static void stm32_dma_config(struct rt_serial_device *serial, rt_ubase_t flag) DMA_Handle->Init.MemInc = DMA_MINC_ENABLE; DMA_Handle->Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; DMA_Handle->Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; - + if (RT_DEVICE_FLAG_DMA_RX == flag) { DMA_Handle->Init.Direction = DMA_PERIPH_TO_MEMORY; @@ -792,7 +911,7 @@ static void stm32_dma_config(struct rt_serial_device *serial, rt_ubase_t flag) DMA_Handle->Init.Direction = DMA_MEMORY_TO_PERIPH; DMA_Handle->Init.Mode = DMA_NORMAL; } - + DMA_Handle->Init.Priority = DMA_PRIORITY_MEDIUM; #if defined(SOC_SERIES_STM32F4) || defined(SOC_SERIES_STM32F7) DMA_Handle->Init.FIFOMode = DMA_FIFOMODE_DISABLE; @@ -820,8 +939,8 @@ static void stm32_dma_config(struct rt_serial_device *serial, rt_ubase_t flag) CLEAR_BIT(uart->handle.Instance->CR3, USART_CR3_EIE); __HAL_UART_ENABLE_IT(&(uart->handle), UART_IT_IDLE); } - - /* enable irq */ + + /* DMA irq should set in DMA TX mode, or HAL_UART_TxCpltCallback function will not be called */ HAL_NVIC_SetPriority(dma_config->dma_irq, 0, 0); HAL_NVIC_EnableIRQ(dma_config->dma_irq); @@ -865,7 +984,7 @@ void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) /** * @brief Rx Half transfer completed callback * @param huart: UART handle - * @note This example shows a simple way to report end of DMA Rx Half transfer, + * @note This example shows a simple way to report end of DMA Rx Half transfer, * and you can add your own implementation. * @retval None */ @@ -886,20 +1005,23 @@ static void _dma_tx_complete(struct rt_serial_device *serial) RT_ASSERT(serial != RT_NULL); uart = rt_container_of(serial, struct stm32_uart, serial); - if ((__HAL_DMA_GET_IT_SOURCE(&(uart->dma_tx.handle), DMA_IT_TC) != RESET) || - (__HAL_DMA_GET_IT_SOURCE(&(uart->dma_tx.handle), DMA_IT_HT) != RESET)) - { - level = rt_hw_interrupt_disable(); - trans_total_index = __HAL_DMA_GET_COUNTER(&(uart->dma_tx.handle)); - rt_hw_interrupt_enable(level); + level = rt_hw_interrupt_disable(); + trans_total_index = __HAL_DMA_GET_COUNTER(&(uart->dma_tx.handle)); + rt_hw_interrupt_enable(level); - if (trans_total_index == 0) - { - rt_hw_serial_isr(serial, RT_SERIAL_EVENT_TX_DMADONE); - } + if (trans_total_index == 0) + { + rt_hw_serial_isr(serial, RT_SERIAL_EVENT_TX_DMADONE); } } +/** + * @brief HAL_UART_TxCpltCallback + * @param huart: UART handle + * @note This callback can be called by two functions, first in UART_EndTransmit_IT when + * UART Tx complete and second in UART_DMATransmitCplt function in DMA Circular mode. + * @retval None + */ void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) { struct stm32_uart *uart; @@ -909,92 +1031,14 @@ void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) } #endif /* RT_SERIAL_USING_DMA */ -static void stm32_uart_get_dma_config(void) +static const struct rt_uart_ops stm32_uart_ops = { -#ifdef BSP_USING_UART1 - uart_obj[UART1_INDEX].uart_dma_flag = 0; -#ifdef BSP_UART1_RX_USING_DMA - uart_obj[UART1_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_RX; - static struct dma_config uart1_dma_rx = UART1_DMA_RX_CONFIG; - uart_config[UART1_INDEX].dma_rx = &uart1_dma_rx; -#endif -#ifdef BSP_UART1_TX_USING_DMA - uart_obj[UART1_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_TX; - static struct dma_config uart1_dma_tx = UART1_DMA_TX_CONFIG; - uart_config[UART1_INDEX].dma_tx = &uart1_dma_tx; -#endif -#endif - -#ifdef BSP_USING_UART2 - uart_obj[UART2_INDEX].uart_dma_flag = 0; -#ifdef BSP_UART2_RX_USING_DMA - uart_obj[UART2_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_RX; - static struct dma_config uart2_dma_rx = UART2_DMA_RX_CONFIG; - uart_config[UART2_INDEX].dma_rx = &uart2_dma_rx; -#endif -#ifdef BSP_UART2_TX_USING_DMA - uart_obj[UART2_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_TX; - static struct dma_config uart2_dma_tx = UART2_DMA_TX_CONFIG; - uart_config[UART2_INDEX].dma_tx = &uart2_dma_tx; -#endif -#endif - -#ifdef BSP_USING_UART3 - uart_obj[UART3_INDEX].uart_dma_flag = 0; -#ifdef BSP_UART3_RX_USING_DMA - uart_obj[UART3_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_RX; - static struct dma_config uart3_dma_rx = UART3_DMA_RX_CONFIG; - uart_config[UART3_INDEX].dma_rx = &uart3_dma_rx; -#endif -#ifdef BSP_UART3_TX_USING_DMA - uart_obj[UART3_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_TX; - static struct dma_config uart3_dma_tx = UART3_DMA_TX_CONFIG; - uart_config[UART3_INDEX].dma_tx = &uart3_dma_tx; -#endif -#endif - -#ifdef BSP_USING_UART4 - uart_obj[UART4_INDEX].uart_dma_flag = 0; -#ifdef BSP_UART4_RX_USING_DMA - uart_obj[UART4_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_RX; - static struct dma_config uart4_dma_rx = UART4_DMA_RX_CONFIG; - uart_config[UART4_INDEX].dma_rx = &uart4_dma_rx; -#endif -#ifdef BSP_UART4_TX_USING_DMA - uart_obj[UART4_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_TX; - static struct dma_config uart4_dma_tx = UART4_DMA_TX_CONFIG; - uart_config[UART4_INDEX].dma_tx = &uart4_dma_tx; -#endif -#endif - -#ifdef BSP_USING_UART5 - uart_obj[UART5_INDEX].uart_dma_flag = 0; -#ifdef BSP_UART5_RX_USING_DMA - uart_obj[UART5_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_RX; - static struct dma_config uart5_dma_rx = UART5_DMA_RX_CONFIG; - uart_config[UART5_INDEX].dma_rx = &uart5_dma_rx; -#endif -#ifdef BSP_UART5_TX_USING_DMA - uart_obj[UART5_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_TX; - static struct dma_config uart5_dma_tx = UART5_DMA_TX_CONFIG; - uart_config[UART5_INDEX].dma_tx = &uart5_dma_tx; -#endif -#endif - -#ifdef BSP_USING_UART6 - uart_obj[UART6_INDEX].uart_dma_flag = 0; -#ifdef BSP_UART6_RX_USING_DMA - uart_obj[UART6_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_RX; - static struct dma_config uart6_dma_rx = UART6_DMA_RX_CONFIG; - uart_config[UART6_INDEX].dma_rx = &uart6_dma_rx; -#endif -#ifdef BSP_UART6_TX_USING_DMA - uart_obj[UART6_INDEX].uart_dma_flag |= RT_DEVICE_FLAG_DMA_TX; - static struct dma_config uart6_dma_tx = UART6_DMA_TX_CONFIG; - uart_config[UART6_INDEX].dma_tx = &uart6_dma_tx; -#endif -#endif -} + .configure = stm32_configure, + .control = stm32_control, + .putc = stm32_putc, + .getc = stm32_getc, + .dma_transmit = stm32_dma_transmit +}; int rt_hw_usart_init(void) { @@ -1006,9 +1050,11 @@ int rt_hw_usart_init(void) for (int i = 0; i < obj_num; i++) { + /* init UART object */ uart_obj[i].config = &uart_config[i]; uart_obj[i].serial.ops = &stm32_uart_ops; uart_obj[i].serial.config = config; + /* register UART device */ result = rt_hw_serial_register(&uart_obj[i].serial, uart_obj[i].config->name, RT_DEVICE_FLAG_RDWR diff --git a/bsp/stm32/libraries/HAL_Drivers/drv_usart.h b/bsp/stm32/libraries/HAL_Drivers/drv_usart.h index f8b0703a33..b6e4060288 100644 --- a/bsp/stm32/libraries/HAL_Drivers/drv_usart.h +++ b/bsp/stm32/libraries/HAL_Drivers/drv_usart.h @@ -6,7 +6,7 @@ * Change Logs: * Date Author Notes * 2018.10.30 SummerGift first version - * 2019.03.05 whj4674672 add stm32h7 + * 2019.03.05 whj4674672 add stm32h7 */ #ifndef __DRV_USART_H__ @@ -50,7 +50,7 @@ struct stm32_uart { UART_HandleTypeDef handle; struct stm32_uart_config *config; - + #ifdef RT_SERIAL_USING_DMA struct { diff --git a/components/drivers/serial/serial.c b/components/drivers/serial/serial.c index d1c04dec6f..7dd2918b9b 100644 --- a/components/drivers/serial/serial.c +++ b/components/drivers/serial/serial.c @@ -733,6 +733,7 @@ static rt_err_t rt_serial_close(struct rt_device *dev) rt_free(rx_fifo); serial->serial_rx = RT_NULL; dev->open_flag &= ~RT_DEVICE_FLAG_INT_RX; + /* configure low level device */ serial->ops->control(serial, RT_DEVICE_CTRL_CLR_INT, (void*)RT_DEVICE_FLAG_INT_RX); } @@ -754,10 +755,11 @@ static rt_err_t rt_serial_close(struct rt_device *dev) rt_free(rx_fifo); } - /* configure low level device */ - serial->ops->control(serial, RT_DEVICE_CTRL_CLR_INT, (void *) RT_DEVICE_FLAG_DMA_RX); serial->serial_rx = RT_NULL; dev->open_flag &= ~RT_DEVICE_FLAG_DMA_RX; + + /* configure low level device */ + serial->ops->control(serial, RT_DEVICE_CTRL_CLR_INT, (void *) RT_DEVICE_FLAG_DMA_RX); } #endif /* RT_SERIAL_USING_DMA */ @@ -771,6 +773,7 @@ static rt_err_t rt_serial_close(struct rt_device *dev) rt_free(tx_fifo); serial->serial_tx = RT_NULL; dev->open_flag &= ~RT_DEVICE_FLAG_INT_TX; + /* configure low level device */ serial->ops->control(serial, RT_DEVICE_CTRL_CLR_INT, (void*)RT_DEVICE_FLAG_INT_TX); } @@ -785,7 +788,14 @@ static rt_err_t rt_serial_close(struct rt_device *dev) rt_free(tx_dma); serial->serial_tx = RT_NULL; dev->open_flag &= ~RT_DEVICE_FLAG_DMA_TX; + + /* configure low level device */ + serial->ops->control(serial, RT_DEVICE_CTRL_CLR_INT, (void *) RT_DEVICE_FLAG_DMA_TX); } + + serial->ops->control(serial, RT_DEVICE_CTRL_CLOSE, RT_NULL); + dev->flag &= ~RT_DEVICE_FLAG_ACTIVATED; + #endif /* RT_SERIAL_USING_DMA */ return RT_EOK; } diff --git a/include/rtdef.h b/include/rtdef.h index 8b86213082..f2b546f75e 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -898,6 +898,7 @@ enum rt_device_class_type #define RT_DEVICE_CTRL_RESUME 0x01 /**< resume device */ #define RT_DEVICE_CTRL_SUSPEND 0x02 /**< suspend device */ #define RT_DEVICE_CTRL_CONFIG 0x03 /**< configure device */ +#define RT_DEVICE_CTRL_CLOSE 0x04 /**< close device */ #define RT_DEVICE_CTRL_SET_INT 0x10 /**< set interrupt */ #define RT_DEVICE_CTRL_CLR_INT 0x11 /**< clear interrupt */ -- cgit v1.3.1 From fe2e9e924e8c08865254f26dd1c763ced4784b1d Mon Sep 17 00:00:00 2001 From: Bernard Xiong Date: Sat, 6 Jun 2020 13:21:32 +0800 Subject: [libc] fix 64bit issue for pthreads --- components/libc/pthreads/pthread.c | 2 +- include/rtdef.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) mode change 100755 => 100644 components/libc/pthreads/pthread.c (limited to 'include/rtdef.h') diff --git a/components/libc/pthreads/pthread.c b/components/libc/pthreads/pthread.c old mode 100755 new mode 100644 index 5d3bc0796a..19a511b45b --- a/components/libc/pthreads/pthread.c +++ b/components/libc/pthreads/pthread.c @@ -277,7 +277,7 @@ int pthread_create(pthread_t *pid, /* set pthread cleanup function and ptd data */ ptd->tid->cleanup = _pthread_cleanup; - ptd->tid->user_data = (rt_uint32_t)ptd; + ptd->tid->user_data = (rt_ubase_t)ptd; /* start thread */ if (rt_thread_startup(ptd->tid) == RT_EOK) diff --git a/include/rtdef.h b/include/rtdef.h index f2b546f75e..b391ff7685 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -623,7 +623,7 @@ struct rt_thread void *lwp; #endif - rt_uint32_t user_data; /**< private user data beyond this thread */ + rt_ubase_t user_data; /**< private user data beyond this thread */ }; typedef struct rt_thread *rt_thread_t; -- cgit v1.3.1 From 224c3224c7d1bea2f52bb51aca505812a12b9255 Mon Sep 17 00:00:00 2001 From: chenchaoqun Date: Mon, 27 Jul 2020 14:11:35 +0800 Subject: [format] enumeration define two styles: define first or all. --- include/rtdef.h | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) (limited to 'include/rtdef.h') diff --git a/include/rtdef.h b/include/rtdef.h index b391ff7685..747643bb82 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -372,20 +372,20 @@ typedef struct rt_object *rt_object_t; /**< Type for kernel obj */ enum rt_object_class_type { - RT_Object_Class_Null = 0, /**< The object is not used. */ - RT_Object_Class_Thread, /**< The object is a thread. */ - RT_Object_Class_Semaphore, /**< The object is a semaphore. */ - RT_Object_Class_Mutex, /**< The object is a mutex. */ - RT_Object_Class_Event, /**< The object is a event. */ - RT_Object_Class_MailBox, /**< The object is a mail box. */ - RT_Object_Class_MessageQueue, /**< The object is a message queue. */ - RT_Object_Class_MemHeap, /**< The object is a memory heap */ - RT_Object_Class_MemPool, /**< The object is a memory pool. */ - RT_Object_Class_Device, /**< The object is a device */ - RT_Object_Class_Timer, /**< The object is a timer. */ - RT_Object_Class_Module, /**< The object is a module. */ - RT_Object_Class_Unknown, /**< The object is unknown. */ - RT_Object_Class_Static = 0x80 /**< The object is a static object. */ + RT_Object_Class_Null = 0x00, /**< The object is not used. */ + RT_Object_Class_Thread = 0x01, /**< The object is a thread. */ + RT_Object_Class_Semaphore = 0x02, /**< The object is a semaphore. */ + RT_Object_Class_Mutex = 0x03, /**< The object is a mutex. */ + RT_Object_Class_Event = 0x04, /**< The object is a event. */ + RT_Object_Class_MailBox = 0x05, /**< The object is a mail box. */ + RT_Object_Class_MessageQueue = 0x06, /**< The object is a message queue. */ + RT_Object_Class_MemHeap = 0x07, /**< The object is a memory heap. */ + RT_Object_Class_MemPool = 0x08, /**< The object is a memory pool. */ + RT_Object_Class_Device = 0x09, /**< The object is a device. */ + RT_Object_Class_Timer = 0x0a, /**< The object is a timer. */ + RT_Object_Class_Module = 0x0b, /**< The object is a module. */ + RT_Object_Class_Unknown = 0x0c, /**< The object is unknown. */ + RT_Object_Class_Static = 0x80 /**< The object is a static object. */ }; /** -- cgit v1.3.1 From 5e92521e0d0e6f73cafe5fe8b5c2e7e0d852863e Mon Sep 17 00:00:00 2001 From: Meco <920369182@qq.com> Date: Mon, 10 Aug 2020 04:35:08 +0800 Subject: struct rt_device_ops 结构体增加宏定义 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/rtdef.h | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'include/rtdef.h') diff --git a/include/rtdef.h b/include/rtdef.h index 747643bb82..5543b80ab7 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -32,6 +32,7 @@ * 2019-01-27 Bernard change version number to v4.0.1 * 2019-05-17 Bernard change version number to v4.0.2 * 2019-12-20 Bernard change version number to v4.0.3 + * 2020-08-10 Meco Man add macro for struct rt_device_ops */ #ifndef __RT_DEF_H__ @@ -920,6 +921,8 @@ enum rt_device_class_type #define RT_DEVICE_CTRL_RTC_SET_ALARM 0x13 /**< set alarm */ typedef struct rt_device *rt_device_t; + +#ifdef RT_USING_DEVICE_OPS /** * operations set for device object */ @@ -933,6 +936,7 @@ struct rt_device_ops rt_size_t (*write) (rt_device_t dev, rt_off_t pos, const void *buffer, rt_size_t size); rt_err_t (*control)(rt_device_t dev, int cmd, void *args); }; +#endif /** * WaitQueue structure -- cgit v1.3.1 From 502378cf93bf780035316d594c80dd9b027efa17 Mon Sep 17 00:00:00 2001 From: WangQiang Date: Mon, 12 Oct 2020 18:15:01 +0800 Subject: 1. 抽象了PHY的设备模型,在components中增加了PHY设备的相关代码以及KCONFIG配置和SConscript脚本 2. 在IMXRT的Libraries中增加了peripherals目录,用于具体型号的设备驱动相关的代码的实现,不应与MCU的平台相关,实现PHY的设备对象中的相关接口。 3. 修改了BSP中的Sconstruct文件,增加了peripherals目录的构建 4. 修改了KEIL环境的SCT文件,用于实现以太网功能 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bsp/imxrt/imxrt1064-nxp-evk/SConstruct | 3 + bsp/imxrt/imxrt1064-nxp-evk/board/Kconfig | 35 +- bsp/imxrt/imxrt1064-nxp-evk/board/SConscript | 4 - bsp/imxrt/imxrt1064-nxp-evk/board/board.c | 26 ++ bsp/imxrt/imxrt1064-nxp-evk/board/board.h | 2 +- .../board/linker_scripts/link.sct | 4 +- .../board/ports/phyksz8081/fsl_phy.c | 315 ------------------ .../board/ports/phyksz8081/fsl_phy.h | 200 ----------- bsp/imxrt/libraries/drivers/SConscript | 3 + bsp/imxrt/libraries/drivers/drv_eth.c | 94 +++--- bsp/imxrt/libraries/drivers/drv_mdio.c | 160 +++++++++ bsp/imxrt/libraries/drivers/drv_mdio.h | 25 ++ bsp/imxrt/libraries/peripherals/SConscript | 16 + bsp/imxrt/libraries/peripherals/phyksz8081.c | 367 +++++++++++++++++++++ bsp/imxrt/tools/sdk_dist.py | 3 + components/drivers/Kconfig | 4 + components/drivers/include/drivers/phy.h | 79 +++++ components/drivers/include/drivers/phy_mdio.h | 35 ++ components/drivers/include/rtdevice.h | 5 + components/drivers/phy/SConscript | 8 + components/drivers/phy/phy.c | 78 +++++ components/finsh/cmd.c | 1 + include/rtdef.h | 1 + 23 files changed, 903 insertions(+), 565 deletions(-) delete mode 100644 bsp/imxrt/imxrt1064-nxp-evk/board/ports/phyksz8081/fsl_phy.c delete mode 100644 bsp/imxrt/imxrt1064-nxp-evk/board/ports/phyksz8081/fsl_phy.h create mode 100644 bsp/imxrt/libraries/drivers/drv_mdio.c create mode 100644 bsp/imxrt/libraries/drivers/drv_mdio.h create mode 100644 bsp/imxrt/libraries/peripherals/SConscript create mode 100644 bsp/imxrt/libraries/peripherals/phyksz8081.c create mode 100644 components/drivers/include/drivers/phy.h create mode 100644 components/drivers/include/drivers/phy_mdio.h create mode 100644 components/drivers/phy/SConscript create mode 100644 components/drivers/phy/phy.c (limited to 'include/rtdef.h') diff --git a/bsp/imxrt/imxrt1064-nxp-evk/SConstruct b/bsp/imxrt/imxrt1064-nxp-evk/SConstruct index 01c823f118..92ab729ed1 100644 --- a/bsp/imxrt/imxrt1064-nxp-evk/SConstruct +++ b/bsp/imxrt/imxrt1064-nxp-evk/SConstruct @@ -66,5 +66,8 @@ objs.extend(SConscript(os.path.join(libraries_path_prefix, imxrt_library, 'SCons # include drivers objs.extend(SConscript(os.path.join(libraries_path_prefix, 'drivers', 'SConscript'))) +# include peripherals +objs.extend(SConscript(os.path.join(libraries_path_prefix, 'peripherals', 'SConscript'))) + # make a building DoBuilding(TARGET, objs) diff --git a/bsp/imxrt/imxrt1064-nxp-evk/board/Kconfig b/bsp/imxrt/imxrt1064-nxp-evk/board/Kconfig index 4c7caa2d53..5c660b91c7 100644 --- a/bsp/imxrt/imxrt1064-nxp-evk/board/Kconfig +++ b/bsp/imxrt/imxrt1064-nxp-evk/board/Kconfig @@ -44,20 +44,41 @@ menu "Onboard Peripheral Drivers" menuconfig BSP_USING_ETH bool "Enable Ethernet" - select PHY_USING_KSZ8081 select RT_USING_NETDEV default n if BSP_USING_ETH - config PHY_USING_KSZ8081 - bool "i.MX RT1064EVK uses ksz8081 phy" + config BSP_USING_PHY + select RT_USING_PHY + bool "Enable ethernet phy" default y - config FSL_FEATURE_PHYKSZ8081_USE_RMII50M_MODE - bool "Enable the PHY ksz8081 RMII50M mode" - depends on PHY_USING_KSZ8081 - default y + if BSP_USING_PHY + config PHY_DEVICE_ADDRESS + int "Specify address of phy device" + default 2 + + config PHY_USING_KSZ8081 + bool "i.MX RT1064EVK uses ksz8081 phy" + default y + + if PHY_USING_KSZ8081 + config PHY_RESET_PORT + int "indicate port of reset" + default 1 + + config PHY_RESET_PIN + int "indicate pin of reset" + default 9 + + config FSL_FEATURE_PHYKSZ8081_USE_RMII50M_MODE + bool "Enable the PHY ksz8081 RMII50M mode" + depends on PHY_USING_KSZ8081 + default y + endif + + endif endif endmenu diff --git a/bsp/imxrt/imxrt1064-nxp-evk/board/SConscript b/bsp/imxrt/imxrt1064-nxp-evk/board/SConscript index 6afc7c3ae4..050a6c10bc 100644 --- a/bsp/imxrt/imxrt1064-nxp-evk/board/SConscript +++ b/bsp/imxrt/imxrt1064-nxp-evk/board/SConscript @@ -15,10 +15,6 @@ CPPPATH = [cwd,cwd + '/MCUX_Config',cwd + '/ports'] CPPDEFINES = ['CPU_MIMXRT1064DVL6A', 'SKIP_SYSCLK_INIT', 'EVK_MCIMXRM', 'FSL_SDK_ENABLE_DRIVER_CACHE_CONTROL=1','XIP_EXTERNAL_FLASH=1', 'XIP_BOOT_HEADER_ENABLE=1', 'XIP_BOOT_HEADER_DCD_ENABLE=1'] -if GetDepend(['PHY_USING_KSZ8081']): - src += Glob('ports/phyksz8081/fsl_phy.c') - CPPPATH += [cwd + '/ports/phyksz8081'] - if rtconfig.CROSS_TOOL == 'keil': CPPDEFINES.append('__FPU_PRESENT=1') diff --git a/bsp/imxrt/imxrt1064-nxp-evk/board/board.c b/bsp/imxrt/imxrt1064-nxp-evk/board/board.c index 0ef8769e0e..603cd856c5 100644 --- a/bsp/imxrt/imxrt1064-nxp-evk/board/board.c +++ b/bsp/imxrt/imxrt1064-nxp-evk/board/board.c @@ -416,6 +416,7 @@ void imxrt_enet_pins_init(void) Hyst. Enable Field: Hysteresis Disabled */ } +#ifndef BSP_USING_PHY void imxrt_enet_phy_reset_by_gpio(void) { gpio_pin_config_t gpio_config = {kGPIO_DigitalOutput, 0, kGPIO_NoIntmode}; @@ -428,8 +429,29 @@ void imxrt_enet_phy_reset_by_gpio(void) rt_thread_delay(100); GPIO_WritePinOutput(GPIO1, 9, 1); } +#endif /* BSP_USING_PHY */ + #endif /* BSP_USING_ETH */ +#ifdef BSP_USING_PHY +void imxrt_phy_pins_init( void ) +{ + IOMUXC_SetPinMux( + IOMUXC_GPIO_AD_B0_09_GPIO1_IO09, /* GPIO_AD_B0_09 is configured as GPIO1_IO09 */ + 0U); /* Software Input On Field: Input Path is determined by functionality */ + IOMUXC_SetPinConfig( + IOMUXC_GPIO_AD_B0_09_GPIO1_IO09, /* GPIO_B0_00 PAD functional properties : */ + 0x10B0u); /* Slew Rate Field: Slow Slew Rate + Drive Strength Field: R0/6 + Speed Field: medium(100MHz) + Open Drain Enable Field: Open Drain Disabled + Pull / Keep Enable Field: Pull/Keeper Enabled + Pull / Keep Select Field: Keeper + Pull Up / Down Config. Field: 100K Ohm Pull Down + Hyst. Enable Field: Hysteresis Disabled */ +} +#endif /* BSP_USING_PHY */ + /** * This function will initial rt1050 board. */ @@ -450,6 +472,10 @@ void rt_hw_board_init() imxrt_enet_pins_init(); #endif +#ifdef BSP_USING_PHY + imxrt_phy_pins_init(); +#endif + #ifdef BSP_USING_DMA imxrt_dma_init(); #endif diff --git a/bsp/imxrt/imxrt1064-nxp-evk/board/board.h b/bsp/imxrt/imxrt1064-nxp-evk/board/board.h index 500cc62450..dd7b7d3e56 100644 --- a/bsp/imxrt/imxrt1064-nxp-evk/board/board.h +++ b/bsp/imxrt/imxrt1064-nxp-evk/board/board.h @@ -48,7 +48,7 @@ void rt_hw_board_init(void); #ifdef BSP_USING_ETH void imxrt_enet_pins_init(void); void imxrt_enet_phy_reset_by_gpio(void); -#define PHY_ADDRESS 0x02u + #endif #endif diff --git a/bsp/imxrt/imxrt1064-nxp-evk/board/linker_scripts/link.sct b/bsp/imxrt/imxrt1064-nxp-evk/board/linker_scripts/link.sct index 7b7bf4fbba..f36201c200 100644 --- a/bsp/imxrt/imxrt1064-nxp-evk/board/linker_scripts/link.sct +++ b/bsp/imxrt/imxrt1064-nxp-evk/board/linker_scripts/link.sct @@ -66,6 +66,8 @@ #define m_data3_start 0x00000000 ; ITCM 128KB #define m_data3_size 0x00020000 +#define m_ncache_start 0x81E00000 +#define m_ncache_size 0x00200000 /* Sizes */ #if (defined(__stack_size__)) @@ -124,7 +126,7 @@ LR_IROM1 m_text_start m_text_size RTT_HEAP +0 EMPTY RTT_HEAP_SIZE{} ; ncache RW data - RW_m_ncache m_data2_start m_data2_size + RW_m_ncache m_ncache_start m_ncache_size { * (NonCacheable.init) * (NonCacheable) diff --git a/bsp/imxrt/imxrt1064-nxp-evk/board/ports/phyksz8081/fsl_phy.c b/bsp/imxrt/imxrt1064-nxp-evk/board/ports/phyksz8081/fsl_phy.c deleted file mode 100644 index 4197514aa5..0000000000 --- a/bsp/imxrt/imxrt1064-nxp-evk/board/ports/phyksz8081/fsl_phy.c +++ /dev/null @@ -1,315 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * All rights reserved. - * - * SPDX-License-Identifier: BSD-3-Clause - */ - -#include "fsl_phy.h" -#include -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @brief Defines the timeout macro. */ -#define PHY_TIMEOUT_COUNT 0x3FFFFFFU - -/******************************************************************************* - * Prototypes - ******************************************************************************/ - -/*! - * @brief Get the ENET instance from peripheral base address. - * - * @param base ENET peripheral base address. - * @return ENET instance. - */ -extern uint32_t ENET_GetInstance(ENET_Type *base); - -/******************************************************************************* - * Variables - ******************************************************************************/ - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) -/*! @brief Pointers to enet clocks for each instance. */ -extern clock_ip_name_t s_enetClock[FSL_FEATURE_SOC_ENET_COUNT]; -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - -/******************************************************************************* - * Code - ******************************************************************************/ - -status_t PHY_Init(ENET_Type *base, uint32_t phyAddr, uint32_t srcClock_Hz) -{ - uint32_t bssReg; - uint32_t counter = PHY_TIMEOUT_COUNT; - uint32_t idReg = 0; - status_t result = kStatus_Success; - uint32_t instance = ENET_GetInstance(base); - uint32_t timeDelay; - uint32_t ctlReg = 0; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Set SMI first. */ - CLOCK_EnableClock(s_enetClock[instance]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - ENET_SetSMI(base, srcClock_Hz, false); - - /* Initialization after PHY stars to work. */ - while ((idReg != PHY_CONTROL_ID1) && (counter != 0)) - { - PHY_Read(base, phyAddr, PHY_ID1_REG, &idReg); - counter --; - } - - if (!counter) - { - return kStatus_Fail; - } - - /* Reset PHY. */ - counter = PHY_TIMEOUT_COUNT; - result = PHY_Write(base, phyAddr, PHY_BASICCONTROL_REG, PHY_BCTL_RESET_MASK); - if (result == kStatus_Success) - { - -#if defined(FSL_FEATURE_PHYKSZ8081_USE_RMII50M_MODE) - uint32_t data = 0; - result = PHY_Read(base, phyAddr, PHY_CONTROL2_REG, &data); - if ( result != kStatus_Success) - { - return result; - } - result = PHY_Write(base, phyAddr, PHY_CONTROL2_REG, (data | PHY_CTL2_REFCLK_SELECT_MASK)); - if (result != kStatus_Success) - { - return result; - } -#endif /* FSL_FEATURE_PHYKSZ8081_USE_RMII50M_MODE */ - - /* Set the negotiation. */ - result = PHY_Write(base, phyAddr, PHY_AUTONEG_ADVERTISE_REG, - (PHY_100BASETX_FULLDUPLEX_MASK | PHY_100BASETX_HALFDUPLEX_MASK | - PHY_10BASETX_FULLDUPLEX_MASK | PHY_10BASETX_HALFDUPLEX_MASK | 0x1U)); - if (result == kStatus_Success) - { - result = PHY_Write(base, phyAddr, PHY_BASICCONTROL_REG, - (PHY_BCTL_AUTONEG_MASK | PHY_BCTL_RESTART_AUTONEG_MASK)); - if (result == kStatus_Success) - { - /* Check auto negotiation complete. */ - while (counter --) - { - result = PHY_Read(base, phyAddr, PHY_BASICSTATUS_REG, &bssReg); - if ( result == kStatus_Success) - { - PHY_Read(base, phyAddr, PHY_CONTROL1_REG, &ctlReg); - if (((bssReg & PHY_BSTATUS_AUTONEGCOMP_MASK) != 0) && (ctlReg & PHY_LINK_READY_MASK)) - { - /* Wait a moment for Phy status stable. */ - for (timeDelay = 0; timeDelay < PHY_TIMEOUT_COUNT; timeDelay ++) - { - __ASM("nop"); - } - break; - } - } - - if (!counter) - { - return kStatus_PHY_AutoNegotiateFail; - } - } - } - } - } - - return result; -} - -status_t PHY_Write(ENET_Type *base, uint32_t phyAddr, uint32_t phyReg, uint32_t data) -{ - uint32_t counter; - - /* Clear the SMI interrupt event. */ - ENET_ClearInterruptStatus(base, ENET_EIR_MII_MASK); - - /* Starts a SMI write command. */ - ENET_StartSMIWrite(base, phyAddr, phyReg, kENET_MiiWriteValidFrame, data); - - /* Wait for SMI complete. */ - for (counter = PHY_TIMEOUT_COUNT; counter > 0; counter--) - { - if (ENET_GetInterruptStatus(base) & ENET_EIR_MII_MASK) - { - break; - } - } - - /* Check for timeout. */ - if (!counter) - { - return kStatus_PHY_SMIVisitTimeout; - } - - /* Clear MII interrupt event. */ - ENET_ClearInterruptStatus(base, ENET_EIR_MII_MASK); - - return kStatus_Success; -} - -status_t PHY_Read(ENET_Type *base, uint32_t phyAddr, uint32_t phyReg, uint32_t *dataPtr) -{ - assert(dataPtr); - - uint32_t counter; - - /* Clear the MII interrupt event. */ - ENET_ClearInterruptStatus(base, ENET_EIR_MII_MASK); - - /* Starts a SMI read command operation. */ - ENET_StartSMIRead(base, phyAddr, phyReg, kENET_MiiReadValidFrame); - - /* Wait for MII complete. */ - for (counter = PHY_TIMEOUT_COUNT; counter > 0; counter--) - { - if (ENET_GetInterruptStatus(base) & ENET_EIR_MII_MASK) - { - break; - } - } - - /* Check for timeout. */ - if (!counter) - { - return kStatus_PHY_SMIVisitTimeout; - } - - /* Get data from MII register. */ - *dataPtr = ENET_ReadSMIData(base); - - /* Clear MII interrupt event. */ - ENET_ClearInterruptStatus(base, ENET_EIR_MII_MASK); - - return kStatus_Success; -} - -status_t PHY_EnableLoopback(ENET_Type *base, uint32_t phyAddr, phy_loop_t mode, phy_speed_t speed, bool enable) -{ - status_t result; - uint32_t data = 0; - - /* Set the loop mode. */ - if (enable) - { - if (mode == kPHY_LocalLoop) - { - if (speed == kPHY_Speed100M) - { - data = PHY_BCTL_SPEED_100M_MASK | PHY_BCTL_DUPLEX_MASK | PHY_BCTL_LOOP_MASK; - } - else - { - data = PHY_BCTL_DUPLEX_MASK | PHY_BCTL_LOOP_MASK; - } - return PHY_Write(base, phyAddr, PHY_BASICCONTROL_REG, data); - } - else - { - /* First read the current status in control register. */ - result = PHY_Read(base, phyAddr, PHY_CONTROL2_REG, &data); - if (result == kStatus_Success) - { - return PHY_Write(base, phyAddr, PHY_CONTROL2_REG, (data | PHY_CTL2_REMOTELOOP_MASK)); - } - } - } - else - { - /* Disable the loop mode. */ - if (mode == kPHY_LocalLoop) - { - /* First read the current status in control register. */ - result = PHY_Read(base, phyAddr, PHY_BASICCONTROL_REG, &data); - if (result == kStatus_Success) - { - data &= ~PHY_BCTL_LOOP_MASK; - return PHY_Write(base, phyAddr, PHY_BASICCONTROL_REG, (data | PHY_BCTL_RESTART_AUTONEG_MASK)); - } - } - else - { - /* First read the current status in control one register. */ - result = PHY_Read(base, phyAddr, PHY_CONTROL2_REG, &data); - if (result == kStatus_Success) - { - return PHY_Write(base, phyAddr, PHY_CONTROL2_REG, (data & ~PHY_CTL2_REMOTELOOP_MASK)); - } - } - } - return result; -} - -status_t PHY_GetLinkStatus(ENET_Type *base, uint32_t phyAddr, bool *status) -{ - assert(status); - - status_t result = kStatus_Success; - uint32_t data; - - /* Read the basic status register. */ - result = PHY_Read(base, phyAddr, PHY_BASICSTATUS_REG, &data); - if (result == kStatus_Success) - { - if (!(PHY_BSTATUS_LINKSTATUS_MASK & data)) - { - /* link down. */ - *status = false; - } - else - { - /* link up. */ - *status = true; - } - } - return result; -} - -status_t PHY_GetLinkSpeedDuplex(ENET_Type *base, uint32_t phyAddr, phy_speed_t *speed, phy_duplex_t *duplex) -{ - assert(duplex); - - status_t result = kStatus_Success; - uint32_t data, ctlReg; - - /* Read the control two register. */ - result = PHY_Read(base, phyAddr, PHY_CONTROL1_REG, &ctlReg); - if (result == kStatus_Success) - { - data = ctlReg & PHY_CTL1_SPEEDUPLX_MASK; - if ((PHY_CTL1_10FULLDUPLEX_MASK == data) || (PHY_CTL1_100FULLDUPLEX_MASK == data)) - { - /* Full duplex. */ - *duplex = kPHY_FullDuplex; - } - else - { - /* Half duplex. */ - *duplex = kPHY_HalfDuplex; - } - - data = ctlReg & PHY_CTL1_SPEEDUPLX_MASK; - if ((PHY_CTL1_100HALFDUPLEX_MASK == data) || (PHY_CTL1_100FULLDUPLEX_MASK == data)) - { - /* 100M speed. */ - *speed = kPHY_Speed100M; - } - else - { /* 10M speed. */ - *speed = kPHY_Speed10M; - } - } - - return result; -} diff --git a/bsp/imxrt/imxrt1064-nxp-evk/board/ports/phyksz8081/fsl_phy.h b/bsp/imxrt/imxrt1064-nxp-evk/board/ports/phyksz8081/fsl_phy.h deleted file mode 100644 index a1eff6d723..0000000000 --- a/bsp/imxrt/imxrt1064-nxp-evk/board/ports/phyksz8081/fsl_phy.h +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * All rights reserved. - * - * SPDX-License-Identifier: BSD-3-Clause - */ -#ifndef _FSL_PHY_H_ -#define _FSL_PHY_H_ - -#include "fsl_enet.h" - -/*! - * @addtogroup phy_driver - * @{ - */ - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @brief PHY driver version */ -#define FSL_PHY_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) /*!< Version 2.0.0. */ - -/*! @brief Defines the PHY registers. */ -#define PHY_BASICCONTROL_REG 0x00U /*!< The PHY basic control register. */ -#define PHY_BASICSTATUS_REG 0x01U /*!< The PHY basic status register. */ -#define PHY_ID1_REG 0x02U /*!< The PHY ID one register. */ -#define PHY_ID2_REG 0x03U /*!< The PHY ID two register. */ -#define PHY_AUTONEG_ADVERTISE_REG 0x04U /*!< The PHY auto-negotiate advertise register. */ -#define PHY_CONTROL1_REG 0x1EU /*!< The PHY control one register. */ -#define PHY_CONTROL2_REG 0x1FU /*!< The PHY control two register. */ - -#define PHY_CONTROL_ID1 0x22U /*!< The PHY ID1*/ - -/*! @brief Defines the mask flag in basic control register. */ -#define PHY_BCTL_DUPLEX_MASK 0x0100U /*!< The PHY duplex bit mask. */ -#define PHY_BCTL_RESTART_AUTONEG_MASK 0x0200U /*!< The PHY restart auto negotiation mask. */ -#define PHY_BCTL_AUTONEG_MASK 0x1000U /*!< The PHY auto negotiation bit mask. */ -#define PHY_BCTL_SPEED_MASK 0x2000U /*!< The PHY speed bit mask. */ -#define PHY_BCTL_LOOP_MASK 0x4000U /*!< The PHY loop bit mask. */ -#define PHY_BCTL_RESET_MASK 0x8000U /*!< The PHY reset bit mask. */ -#define PHY_BCTL_SPEED_100M_MASK 0x2000U /*!< The PHY 100M speed mask. */ - -/*!@brief Defines the mask flag of operation mode in control two register*/ -#define PHY_CTL2_REMOTELOOP_MASK 0x0004U /*!< The PHY remote loopback mask. */ -#define PHY_CTL2_REFCLK_SELECT_MASK 0x0080U /*!< The PHY RMII reference clock select. */ -#define PHY_CTL1_10HALFDUPLEX_MASK 0x0001U /*!< The PHY 10M half duplex mask. */ -#define PHY_CTL1_100HALFDUPLEX_MASK 0x0002U /*!< The PHY 100M half duplex mask. */ -#define PHY_CTL1_10FULLDUPLEX_MASK 0x0005U /*!< The PHY 10M full duplex mask. */ -#define PHY_CTL1_100FULLDUPLEX_MASK 0x0006U /*!< The PHY 100M full duplex mask. */ -#define PHY_CTL1_SPEEDUPLX_MASK 0x0007U /*!< The PHY speed and duplex mask. */ -#define PHY_CTL1_ENERGYDETECT_MASK 0x10U /*!< The PHY signal present on rx differential pair. */ -#define PHY_CTL1_LINKUP_MASK 0x100U /*!< The PHY link up. */ -#define PHY_LINK_READY_MASK (PHY_CTL1_ENERGYDETECT_MASK | PHY_CTL1_LINKUP_MASK) - -/*! @brief Defines the mask flag in basic status register. */ -#define PHY_BSTATUS_LINKSTATUS_MASK 0x0004U /*!< The PHY link status mask. */ -#define PHY_BSTATUS_AUTONEGABLE_MASK 0x0008U /*!< The PHY auto-negotiation ability mask. */ -#define PHY_BSTATUS_AUTONEGCOMP_MASK 0x0020U /*!< The PHY auto-negotiation complete mask. */ - -/*! @brief Defines the mask flag in PHY auto-negotiation advertise register. */ -#define PHY_100BaseT4_ABILITY_MASK 0x200U /*!< The PHY have the T4 ability. */ -#define PHY_100BASETX_FULLDUPLEX_MASK 0x100U /*!< The PHY has the 100M full duplex ability.*/ -#define PHY_100BASETX_HALFDUPLEX_MASK 0x080U /*!< The PHY has the 100M full duplex ability.*/ -#define PHY_10BASETX_FULLDUPLEX_MASK 0x040U /*!< The PHY has the 10M full duplex ability.*/ -#define PHY_10BASETX_HALFDUPLEX_MASK 0x020U /*!< The PHY has the 10M full duplex ability.*/ - -/*! @brief Defines the PHY status. */ -enum _phy_status -{ - kStatus_PHY_SMIVisitTimeout = MAKE_STATUS(kStatusGroup_PHY, 1), /*!< ENET PHY SMI visit timeout. */ - kStatus_PHY_AutoNegotiateFail = MAKE_STATUS(kStatusGroup_PHY, 2) /*!< ENET PHY AutoNegotiate Fail. */ -}; - -/*! @brief Defines the PHY link speed. This is align with the speed for ENET MAC. */ -typedef enum _phy_speed -{ - kPHY_Speed10M = 0U, /*!< ENET PHY 10M speed. */ - kPHY_Speed100M /*!< ENET PHY 100M speed. */ -} phy_speed_t; - -/*! @brief Defines the PHY link duplex. */ -typedef enum _phy_duplex -{ - kPHY_HalfDuplex = 0U, /*!< ENET PHY half duplex. */ - kPHY_FullDuplex /*!< ENET PHY full duplex. */ -} phy_duplex_t; - -/*! @brief Defines the PHY loopback mode. */ -typedef enum _phy_loop -{ - kPHY_LocalLoop = 0U, /*!< ENET PHY local loopback. */ - kPHY_RemoteLoop /*!< ENET PHY remote loopback. */ -} phy_loop_t; - -/******************************************************************************* - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif - -/*! - * @name PHY Driver - * @{ - */ - -/*! - * @brief Initializes PHY. - * - * This function initialize the SMI interface and initialize PHY. - * The SMI is the MII management interface between PHY and MAC, which should be - * firstly initialized before any other operation for PHY. The PHY initialize with auto-negotiation. - * - * @param base ENET peripheral base address. - * @param phyAddr The PHY address. - * @param srcClock_Hz The module clock frequency - system clock for MII management interface - SMI. - * @retval kStatus_Success PHY initialize success - * @retval kStatus_PHY_SMIVisitTimeout PHY SMI visit time out - * @retval kStatus_PHY_AutoNegotiateFail PHY auto negotiate fail - */ -status_t PHY_Init(ENET_Type *base, uint32_t phyAddr, uint32_t srcClock_Hz); - -/*! - * @brief PHY Write function. This function write data over the SMI to - * the specified PHY register. This function is called by all PHY interfaces. - * - * @param base ENET peripheral base address. - * @param phyAddr The PHY address. - * @param phyReg The PHY register. - * @param data The data written to the PHY register. - * @retval kStatus_Success PHY write success - * @retval kStatus_PHY_SMIVisitTimeout PHY SMI visit time out - */ -status_t PHY_Write(ENET_Type *base, uint32_t phyAddr, uint32_t phyReg, uint32_t data); - -/*! - * @brief PHY Read function. This interface read data over the SMI from the - * specified PHY register. This function is called by all PHY interfaces. - * - * @param base ENET peripheral base address. - * @param phyAddr The PHY address. - * @param phyReg The PHY register. - * @param dataPtr The address to store the data read from the PHY register. - * @retval kStatus_Success PHY read success - * @retval kStatus_PHY_SMIVisitTimeout PHY SMI visit time out - */ -status_t PHY_Read(ENET_Type *base, uint32_t phyAddr, uint32_t phyReg, uint32_t *dataPtr); - -/*! - * @brief Enables/disables PHY loopback. - * - * @param base ENET peripheral base address. - * @param phyAddr The PHY address. - * @param mode The loopback mode to be enabled, please see "phy_loop_t". - * the two loopback mode should not be both set. when one loopback mode is set - * the other one should be disabled. - * @param speed PHY speed for loopback mode. - * @param enable True to enable, false to disable. - * @retval kStatus_Success PHY loopback success - * @retval kStatus_PHY_SMIVisitTimeout PHY SMI visit time out - */ -status_t PHY_EnableLoopback(ENET_Type *base, uint32_t phyAddr, phy_loop_t mode, phy_speed_t speed, bool enable); - -/*! - * @brief Gets the PHY link status. - * - * @param base ENET peripheral base address. - * @param phyAddr The PHY address. - * @param status The link up or down status of the PHY. - * - true the link is up. - * - false the link is down. - * @retval kStatus_Success PHY get link status success - * @retval kStatus_PHY_SMIVisitTimeout PHY SMI visit time out - */ -status_t PHY_GetLinkStatus(ENET_Type *base, uint32_t phyAddr, bool *status); - -/*! - * @brief Gets the PHY link speed and duplex. - * - * @param base ENET peripheral base address. - * @param phyAddr The PHY address. - * @param speed The address of PHY link speed. - * @param duplex The link duplex of PHY. - * @retval kStatus_Success PHY get link speed and duplex success - * @retval kStatus_PHY_SMIVisitTimeout PHY SMI visit time out - */ -status_t PHY_GetLinkSpeedDuplex(ENET_Type *base, uint32_t phyAddr, phy_speed_t *speed, phy_duplex_t *duplex); - -/* @} */ - -#if defined(__cplusplus) -} -#endif - -/*! @}*/ - -#endif /* _FSL_PHY_H_ */ diff --git a/bsp/imxrt/libraries/drivers/SConscript b/bsp/imxrt/libraries/drivers/SConscript index c806dada25..c610fcd082 100644 --- a/bsp/imxrt/libraries/drivers/SConscript +++ b/bsp/imxrt/libraries/drivers/SConscript @@ -44,6 +44,9 @@ if GetDepend('BSP_USING_LCD'): if GetDepend('BSP_USING_ETH'): src += ['drv_eth.c'] + +if GetDepend('BSP_USING_PHY'): + src += ['drv_mdio.c'] if GetDepend('BSP_USING_USB_DEVICE'): src += ['drv_usbd.c'] diff --git a/bsp/imxrt/libraries/drivers/drv_eth.c b/bsp/imxrt/libraries/drivers/drv_eth.c index 4558312be8..665886f936 100644 --- a/bsp/imxrt/libraries/drivers/drv_eth.c +++ b/bsp/imxrt/libraries/drivers/drv_eth.c @@ -19,7 +19,6 @@ #include "fsl_enet.h" #include "fsl_gpio.h" -#include "fsl_phy.h" #include "fsl_cache.h" #include "fsl_iomuxc.h" #include "fsl_common.h" @@ -537,31 +536,52 @@ struct pbuf *rt_imxrt_eth_rx(rt_device_t dev) return NULL; } +#ifdef BSP_USING_PHY +static struct rt_phy_device *phy_dev = RT_NULL; static void phy_monitor_thread_entry(void *parameter) { - phy_speed_t speed; - phy_duplex_t duplex; - bool link = false; + rt_uint32_t speed; + rt_uint32_t duplex; + rt_bool_t link = RT_FALSE; - imxrt_enet_phy_reset_by_gpio(); - - PHY_Init(imxrt_eth_device.enet_base, PHY_ADDRESS, CLOCK_GetFreq(kCLOCK_AhbClk)); + phy_dev = (struct rt_phy_device *)rt_device_find("rtt-phy"); + if ((RT_NULL == phy_dev) || (RT_NULL == phy_dev->ops)) + { + // TODO print warning information + LOG_E("Can not find phy device called \"rtt-phy\""); + return ; + } + LOG_I("start to initialize phy device!"); + if (RT_NULL == phy_dev->ops->init) + { + LOG_E("phy driver error!"); + return ; + } + rt_phy_status status = phy_dev->ops->init(imxrt_eth_device.enet_base, PHY_DEVICE_ADDRESS, CLOCK_GetFreq(kCLOCK_AhbClk)); + if (PHY_STATUS_OK != status) + { + LOG_E("Phy device initialize unsuccessful!\n"); + return ; + } + else + { + LOG_I("Phy device initialize successful!\n"); + } while (1) { - bool new_link = false; - status_t status = PHY_GetLinkStatus(imxrt_eth_device.enet_base, PHY_ADDRESS, &new_link); + rt_bool_t new_link = RT_FALSE; + rt_phy_status status = phy_dev->ops->get_link_status(&new_link); - if ((status == kStatus_Success) && (link != new_link)) + if ((PHY_STATUS_OK == status) && (link != new_link)) { link = new_link; - if (link) // link up + if (link) // link up { - PHY_GetLinkSpeedDuplex(imxrt_eth_device.enet_base, - PHY_ADDRESS, &speed, &duplex); + phy_dev->ops->get_link_speed_duplex(&speed, &duplex); - if (kPHY_Speed10M == speed) + if (PHY_SPEED_10M == speed) { dbg_log(DBG_LOG, "10M\n"); } @@ -570,7 +590,7 @@ static void phy_monitor_thread_entry(void *parameter) dbg_log(DBG_LOG, "100M\n"); } - if (kPHY_HalfDuplex == duplex) + if (PHY_HALF_DUPLEX == duplex) { dbg_log(DBG_LOG, "half dumplex\n"); } @@ -579,8 +599,7 @@ static void phy_monitor_thread_entry(void *parameter) dbg_log(DBG_LOG, "full dumplex\n"); } - if ((imxrt_eth_device.speed != (enet_mii_speed_t)speed) - || (imxrt_eth_device.duplex != (enet_mii_duplex_t)duplex)) + if ((imxrt_eth_device.speed != (enet_mii_speed_t)speed) || (imxrt_eth_device.duplex != (enet_mii_duplex_t)duplex)) { imxrt_eth_device.speed = (enet_mii_speed_t)speed; imxrt_eth_device.duplex = (enet_mii_duplex_t)duplex; @@ -605,6 +624,7 @@ static void phy_monitor_thread_entry(void *parameter) rt_thread_delay(RT_TICK_PER_SECOND * 2); } } +#endif static int rt_hw_imxrt_eth_init(void) { @@ -657,6 +677,7 @@ static int rt_hw_imxrt_eth_init(void) /* start phy monitor */ { + #ifdef BSP_USING_PHY rt_thread_t tid; tid = rt_thread_create("phy", phy_monitor_thread_entry, @@ -666,6 +687,7 @@ static int rt_hw_imxrt_eth_init(void) 2); if (tid != RT_NULL) rt_thread_startup(tid); + #endif } return state; @@ -673,50 +695,47 @@ static int rt_hw_imxrt_eth_init(void) INIT_DEVICE_EXPORT(rt_hw_imxrt_eth_init); #endif -#ifdef RT_USING_FINSH +#if defined(RT_USING_FINSH) && defined(RT_USING_PHY) #include -void phy_read(uint32_t phyReg) +void phy_read(rt_uint32_t phy_reg) { - uint32_t data; - status_t status; + rt_uint32_t data; - status = PHY_Read(imxrt_eth_device.enet_base, PHY_ADDRESS, phyReg, &data); - if (kStatus_Success == status) + rt_phy_status status = phy_dev->ops->read(phy_reg, &data); + if (PHY_STATUS_OK == status) { - rt_kprintf("PHY_Read: %02X --> %08X", phyReg, data); + rt_kprintf("PHY_Read: %02X --> %08X", phy_reg, data); } else { - rt_kprintf("PHY_Read: %02X --> faild", phyReg); + rt_kprintf("PHY_Read: %02X --> faild", phy_reg); } } -void phy_write(uint32_t phyReg, uint32_t data) +void phy_write(rt_uint32_t phy_reg, rt_uint32_t data) { - status_t status; - - status = PHY_Write(imxrt_eth_device.enet_base, PHY_ADDRESS, phyReg, data); - if (kStatus_Success == status) + rt_phy_status status = phy_dev->ops->write(phy_reg, data); + if (PHY_STATUS_OK == status) { - rt_kprintf("PHY_Write: %02X --> %08X\n", phyReg, data); + rt_kprintf("PHY_Write: %02X --> %08X\n", phy_reg, data); } else { - rt_kprintf("PHY_Write: %02X --> faild\n", phyReg); + rt_kprintf("PHY_Write: %02X --> faild\n", phy_reg); } } void phy_dump(void) { - uint32_t data; - status_t status; + rt_uint32_t data; + rt_phy_status status; int i; for (i = 0; i < 32; i++) { - status = PHY_Read(imxrt_eth_device.enet_base, PHY_ADDRESS, i, &data); - if (kStatus_Success != status) + status = phy_dev->ops->read(i, &data); + if (PHY_STATUS_OK != status) { rt_kprintf("phy_dump: %02X --> faild", i); break; @@ -730,10 +749,11 @@ void phy_dump(void) { rt_kprintf("%02X --> %08X\n", i, data); } - } } +#endif +#if defined(RT_USING_FINSH) && defined(RT_USING_LWIP) void enet_reg_dump(void) { ENET_Type *enet_base = imxrt_eth_device.enet_base; diff --git a/bsp/imxrt/libraries/drivers/drv_mdio.c b/bsp/imxrt/libraries/drivers/drv_mdio.c new file mode 100644 index 0000000000..3e98d57f29 --- /dev/null +++ b/bsp/imxrt/libraries/drivers/drv_mdio.c @@ -0,0 +1,160 @@ + +/* + * Copyright (c) 2006-2020, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2020-09-29 WangQiang the first version + * + */ + +#include + +#ifdef BSP_USING_PHY + +#define LOG_TAG "drv.mdio" +#include + +#include +#include "drv_mdio.h" + + + +/*! @brief Defines the timeout macro. */ +#define PHY_TIMEOUT_COUNT 0x3FFFFFFU + +/*! + * @brief Get the ENET instance from peripheral base address. + * + * @param base ENET peripheral base address. + * @return ENET instance. + */ +extern uint32_t ENET_GetInstance(ENET_Type *base); + +#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) +/*! @brief Pointers to enet clocks for each instance. */ +extern clock_ip_name_t s_enetClock[FSL_FEATURE_SOC_ENET_COUNT]; +#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ + +static rt_bool_t rt_hw_mdio_init(void *bus, rt_uint32_t src_clock_hz) +{ + struct rt_mdio_bus *bus_obj = (struct rt_mdio_bus *)bus; + uint32_t instance = ENET_GetInstance((ENET_Type *)(bus_obj->hw_obj)); +#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) + /* Set SMI first. */ + CLOCK_EnableClock(s_enetClock[instance]); +#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ + ENET_SetSMI((ENET_Type *)(bus_obj->hw_obj), src_clock_hz, RT_FALSE); + + return RT_TRUE; +} + +static rt_size_t rt_hw_mdio_read(void *bus, rt_uint32_t addr, rt_uint32_t reg, void *data, rt_uint32_t size) +{ + RT_ASSERT(data); + struct rt_mdio_bus *bus_obj = (struct rt_mdio_bus *)bus; + + rt_uint32_t counter; + rt_uint32_t *data_ptr = (rt_uint32_t *)data; + + if (4 != size) + { + return 0; + } + + /* Clear the MII interrupt event. */ + ENET_ClearInterruptStatus((ENET_Type *)(bus_obj->hw_obj), ENET_EIR_MII_MASK); + + /* Starts a SMI read command operation. */ + ENET_StartSMIRead((ENET_Type *)(bus_obj->hw_obj), addr, reg, kENET_MiiReadValidFrame); + + /* Wait for MII complete. */ + for (counter = PHY_TIMEOUT_COUNT; counter > 0; counter--) + { + if (ENET_GetInterruptStatus((ENET_Type *)(bus_obj->hw_obj)) & ENET_EIR_MII_MASK) + { + break; + } + } + + /* Check for timeout. */ + if (!counter) + { + // return kStatus_PHY_SMIVisitTimeout; + return 0; + } + + /* Get data from MII register. */ + *data_ptr = ENET_ReadSMIData((ENET_Type *)(bus_obj->hw_obj)); + + /* Clear MII interrupt event. */ + ENET_ClearInterruptStatus((ENET_Type *)bus_obj->hw_obj, ENET_EIR_MII_MASK); + + return 4; +} + + +static rt_size_t rt_hw_mdio_write(void *bus, rt_uint32_t addr, rt_uint32_t reg, void *data, rt_uint32_t size) +{ + struct rt_mdio_bus *bus_obj = (struct rt_mdio_bus *)bus; + uint32_t counter; + rt_uint32_t *data_ptr = (rt_uint32_t *)data; + + if (4 != size) + { + return 0; + } + + /* Clear the SMI interrupt event. */ + ENET_ClearInterruptStatus((ENET_Type *)(bus_obj->hw_obj), ENET_EIR_MII_MASK); + + /* Starts a SMI write command. */ + ENET_StartSMIWrite((ENET_Type *)(bus_obj->hw_obj), addr, reg, kENET_MiiWriteValidFrame, *data_ptr); + + /* Wait for SMI complete. */ + for (counter = PHY_TIMEOUT_COUNT; counter > 0; counter--) + { + if (ENET_GetInterruptStatus((ENET_Type *)(bus_obj->hw_obj)) & ENET_EIR_MII_MASK) + { + break; + } + } + + /* Check for timeout. */ + if (!counter) + { + return 0; + } + + /* Clear MII interrupt event. */ + ENET_ClearInterruptStatus((ENET_Type *)(bus_obj->hw_obj), ENET_EIR_MII_MASK); + + return size; +} + +static struct rt_mdio_bus_ops imxrt_mdio_ops = +{ + .init = rt_hw_mdio_init, + .read = rt_hw_mdio_read, + .write = rt_hw_mdio_write, + .uninit = RT_NULL, +}; + +static rt_mdio_t mdio_bus; + +rt_mdio_t *rt_hw_mdio_register(void *hw_obj, char *name) +{ + mdio_bus.hw_obj = hw_obj; + mdio_bus.name = name; + mdio_bus.ops = &imxrt_mdio_ops; + return &mdio_bus; +} + +rt_mdio_t *rt_hw_mdio_get(void) +{ + return &mdio_bus; +} + +#endif diff --git a/bsp/imxrt/libraries/drivers/drv_mdio.h b/bsp/imxrt/libraries/drivers/drv_mdio.h new file mode 100644 index 0000000000..a1623cfc2c --- /dev/null +++ b/bsp/imxrt/libraries/drivers/drv_mdio.h @@ -0,0 +1,25 @@ + +/* + * Copyright (c) 2006-2020, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2020-09-29 WangQiang the first version + * + */ + +#ifndef DRV_MDIO_H__ +#define DRV_MDIO_H__ + +#include + +#include "fsl_enet.h" + + +rt_mdio_t *rt_hw_mdio_register(void *hw_obj, char *name); + +rt_mdio_t *rt_hw_mdio_get(void); + +#endif /*DRV_MDIO_H__*/ diff --git a/bsp/imxrt/libraries/peripherals/SConscript b/bsp/imxrt/libraries/peripherals/SConscript new file mode 100644 index 0000000000..13d040cf2b --- /dev/null +++ b/bsp/imxrt/libraries/peripherals/SConscript @@ -0,0 +1,16 @@ +from building import * + +src = [] +cwd = [] +CPPDEFINES = [] + +cwd = GetCurrentDir() + +if GetDepend('BSP_USING_PHY') and GetDepend('PHY_USING_KSZ8081'): + src += ['phyksz8081.c'] + +path = [cwd] + +group = DefineGroup('Peripherals', src, depend = [''], CPPPATH = path, CPPDEFINES=CPPDEFINES) + +Return('group') diff --git a/bsp/imxrt/libraries/peripherals/phyksz8081.c b/bsp/imxrt/libraries/peripherals/phyksz8081.c new file mode 100644 index 0000000000..88c041f4d1 --- /dev/null +++ b/bsp/imxrt/libraries/peripherals/phyksz8081.c @@ -0,0 +1,367 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +#ifdef PHY_USING_KSZ8081 + +#include +#include "drv_gpio.h" +#include "drv_mdio.h" + + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @brief Defines the PHY registers. */ +#define PHY_BASICCONTROL_REG 0x00U /*!< The PHY basic control register. */ +#define PHY_BASICSTATUS_REG 0x01U /*!< The PHY basic status register. */ +#define PHY_ID1_REG 0x02U /*!< The PHY ID one register. */ +#define PHY_ID2_REG 0x03U /*!< The PHY ID two register. */ +#define PHY_AUTONEG_ADVERTISE_REG 0x04U /*!< The PHY auto-negotiate advertise register. */ +#define PHY_CONTROL1_REG 0x1EU /*!< The PHY control one register. */ +#define PHY_CONTROL2_REG 0x1FU /*!< The PHY control two register. */ + +#define PHY_CONTROL_ID1 0x22U /*!< The PHY ID1*/ + +/*! @brief Defines the mask flag in basic control register. */ +#define PHY_BCTL_DUPLEX_MASK 0x0100U /*!< The PHY duplex bit mask. */ +#define PHY_BCTL_RESTART_AUTONEG_MASK 0x0200U /*!< The PHY restart auto negotiation mask. */ +#define PHY_BCTL_AUTONEG_MASK 0x1000U /*!< The PHY auto negotiation bit mask. */ +#define PHY_BCTL_SPEED_MASK 0x2000U /*!< The PHY speed bit mask. */ +#define PHY_BCTL_LOOP_MASK 0x4000U /*!< The PHY loop bit mask. */ +#define PHY_BCTL_RESET_MASK 0x8000U /*!< The PHY reset bit mask. */ +#define PHY_BCTL_SPEED_100M_MASK 0x2000U /*!< The PHY 100M speed mask. */ + +/*!@brief Defines the mask flag of operation mode in control two register*/ +#define PHY_CTL2_REMOTELOOP_MASK 0x0004U /*!< The PHY remote loopback mask. */ +#define PHY_CTL2_REFCLK_SELECT_MASK 0x0080U /*!< The PHY RMII reference clock select. */ +#define PHY_CTL1_10HALFDUPLEX_MASK 0x0001U /*!< The PHY 10M half duplex mask. */ +#define PHY_CTL1_100HALFDUPLEX_MASK 0x0002U /*!< The PHY 100M half duplex mask. */ +#define PHY_CTL1_10FULLDUPLEX_MASK 0x0005U /*!< The PHY 10M full duplex mask. */ +#define PHY_CTL1_100FULLDUPLEX_MASK 0x0006U /*!< The PHY 100M full duplex mask. */ +#define PHY_CTL1_SPEEDUPLX_MASK 0x0007U /*!< The PHY speed and duplex mask. */ +#define PHY_CTL1_ENERGYDETECT_MASK 0x10U /*!< The PHY signal present on rx differential pair. */ +#define PHY_CTL1_LINKUP_MASK 0x100U /*!< The PHY link up. */ +#define PHY_LINK_READY_MASK (PHY_CTL1_ENERGYDETECT_MASK | PHY_CTL1_LINKUP_MASK) + +/*! @brief Defines the mask flag in basic status register. */ +#define PHY_BSTATUS_LINKSTATUS_MASK 0x0004U /*!< The PHY link status mask. */ +#define PHY_BSTATUS_AUTONEGABLE_MASK 0x0008U /*!< The PHY auto-negotiation ability mask. */ +#define PHY_BSTATUS_AUTONEGCOMP_MASK 0x0020U /*!< The PHY auto-negotiation complete mask. */ + +/*! @brief Defines the mask flag in PHY auto-negotiation advertise register. */ +#define PHY_100BaseT4_ABILITY_MASK 0x200U /*!< The PHY have the T4 ability. */ +#define PHY_100BASETX_FULLDUPLEX_MASK 0x100U /*!< The PHY has the 100M full duplex ability.*/ +#define PHY_100BASETX_HALFDUPLEX_MASK 0x080U /*!< The PHY has the 100M full duplex ability.*/ +#define PHY_10BASETX_FULLDUPLEX_MASK 0x040U /*!< The PHY has the 10M full duplex ability.*/ +#define PHY_10BASETX_HALFDUPLEX_MASK 0x020U /*!< The PHY has the 10M full duplex ability.*/ + + + +/*! @brief Defines the timeout macro. */ +#define PHY_TIMEOUT_COUNT 0x3FFFFFFU + +/* defined the Reset pin, PORT and PIN config by menuconfig */ +#define RESET_PIN GET_PIN(PHY_RESET_PORT, PHY_RESET_PIN) + +/******************************************************************************* + * Prototypes + ******************************************************************************/ + + +/******************************************************************************* + * Variables + ******************************************************************************/ +static struct rt_phy_device phy_ksz8081; + +/******************************************************************************* + * Code + ******************************************************************************/ + + + +static inline rt_bool_t read_reg(rt_mdio_t *bus, rt_uint32_t addr, rt_uint32_t reg_id, rt_uint32_t *value) +{ + if (4 != bus->ops->read(bus, addr, reg_id, value, 4)) + { + return RT_FALSE; + } + return RT_TRUE; +} + +static inline rt_bool_t write_reg(rt_mdio_t *bus, rt_uint32_t addr, rt_uint32_t reg_id, rt_uint32_t value) +{ + if (4 != bus->ops->write(bus, addr, reg_id, &value, 4)) + { + return RT_FALSE; + } + return RT_TRUE; +} + +static rt_phy_status rt_phy_init(void *object, rt_uint32_t phy_addr, rt_uint32_t src_clock_hz) +{ + rt_bool_t ret; + rt_phy_status result; + rt_uint32_t counter = PHY_TIMEOUT_COUNT; + rt_uint32_t id_reg = 0; + rt_uint32_t time_delay; + rt_uint32_t bss_reg; + rt_uint32_t ctl_reg = 0; + + // reset phy device by gpio + rt_pin_mode(RESET_PIN, PIN_MODE_OUTPUT); + rt_pin_write(RESET_PIN, PIN_LOW); + rt_thread_mdelay(100); + rt_pin_write(RESET_PIN, PIN_HIGH); + + rt_mdio_t *mdio_bus = rt_hw_mdio_register(object, "phy_mdio"); + if (RT_NULL == mdio_bus) + { + return PHY_STATUS_FAIL; + } + phy_ksz8081.bus = mdio_bus; + phy_ksz8081.addr = phy_addr; + ret = mdio_bus->ops->init(mdio_bus, src_clock_hz); + if ( !ret ) + { + return PHY_STATUS_FAIL; + } + + /* Initialization after PHY stars to work. */ + while ((id_reg != PHY_CONTROL_ID1) && (counter != 0)) + { + phy_ksz8081.ops->read(PHY_ID1_REG, &id_reg); + counter--; + } + + if (!counter) + { + return PHY_STATUS_FAIL; + } + + /* Reset PHY. */ + counter = PHY_TIMEOUT_COUNT; + result = phy_ksz8081.ops->write(PHY_BASICCONTROL_REG, PHY_BCTL_RESET_MASK); + if (PHY_STATUS_OK == result) + { + #if defined(FSL_FEATURE_PHYKSZ8081_USE_RMII50M_MODE) + rt_uint32_t data = 0; + result = phy_ksz8081.ops->read(PHY_CONTROL2_REG, &data); + if (PHY_STATUS_FAIL == result) + { + return PHY_STATUS_FAIL; + } + result = phy_ksz8081.ops->write(PHY_CONTROL2_REG, (data | PHY_CTL2_REFCLK_SELECT_MASK)); + if (PHY_STATUS_FAIL == result) + { + return PHY_STATUS_FAIL; + } + #endif /* FSL_FEATURE_PHYKSZ8081_USE_RMII50M_MODE */ + + /* Set the negotiation. */ + result = phy_ksz8081.ops->write(PHY_AUTONEG_ADVERTISE_REG, + (PHY_100BASETX_FULLDUPLEX_MASK | PHY_100BASETX_HALFDUPLEX_MASK | + PHY_10BASETX_FULLDUPLEX_MASK | PHY_10BASETX_HALFDUPLEX_MASK | 0x1U)); + if (PHY_STATUS_OK == result) + { + result = phy_ksz8081.ops->write(PHY_BASICCONTROL_REG, (PHY_BCTL_AUTONEG_MASK | PHY_BCTL_RESTART_AUTONEG_MASK)); + if (PHY_STATUS_OK == result) + { + /* Check auto negotiation complete. */ + while (counter--) + { + result = phy_ksz8081.ops->read(PHY_BASICSTATUS_REG, &bss_reg); + if (PHY_STATUS_OK == result) + { + phy_ksz8081.ops->read(PHY_CONTROL1_REG, &ctl_reg); + if (((bss_reg & PHY_BSTATUS_AUTONEGCOMP_MASK) != 0) && (ctl_reg & PHY_LINK_READY_MASK)) + { + /* Wait a moment for Phy status stable. */ + for (time_delay = 0; time_delay < PHY_TIMEOUT_COUNT; time_delay++) + { + __ASM("nop"); + } + break; + } + } + + if (!counter) + { + return PHY_STATUS_FAIL; + } + } + } + } + } + + return PHY_STATUS_OK; +} + + +static rt_phy_status rt_phy_read(rt_uint32_t reg, rt_uint32_t *data) +{ + rt_mdio_t *mdio_bus = phy_ksz8081.bus; + rt_uint32_t device_id = phy_ksz8081.addr; + + if (read_reg(mdio_bus, device_id, reg, data)) + { + return PHY_STATUS_OK; + } + return PHY_STATUS_FAIL; +} + +static rt_phy_status rt_phy_write(rt_uint32_t reg, rt_uint32_t data) +{ + rt_mdio_t *mdio_bus = phy_ksz8081.bus; + rt_uint32_t device_id = phy_ksz8081.addr; + + if (write_reg(mdio_bus, device_id, reg, data)) + { + return PHY_STATUS_OK; + } + return PHY_STATUS_FAIL; +} + +static rt_phy_status rt_phy_loopback(rt_uint32_t mode, rt_uint32_t speed, rt_bool_t enable) +{ + rt_uint32_t data = 0; + rt_phy_status result; + + /* Set the loop mode. */ + if (enable) + { + if (PHY_LOCAL_LOOP == mode) + { + if (PHY_SPEED_100M == speed) + { + data = PHY_BCTL_SPEED_100M_MASK | PHY_BCTL_DUPLEX_MASK | PHY_BCTL_LOOP_MASK; + } + else + { + data = PHY_BCTL_DUPLEX_MASK | PHY_BCTL_LOOP_MASK; + } + return phy_ksz8081.ops->write(PHY_BASICCONTROL_REG, data); + } + else + { + /* First read the current status in control register. */ + result = phy_ksz8081.ops->read(PHY_CONTROL2_REG, &data); + if (PHY_STATUS_OK == result) + { + return phy_ksz8081.ops->write(PHY_CONTROL2_REG, (data | PHY_CTL2_REMOTELOOP_MASK)); + } + } + } + else + { + /* Disable the loop mode. */ + if (PHY_LOCAL_LOOP == mode) + { + /* First read the current status in control register. */ + result = phy_ksz8081.ops->read(PHY_BASICCONTROL_REG, &data); + if (PHY_STATUS_OK == result) + { + data &= ~PHY_BCTL_LOOP_MASK; + return phy_ksz8081.ops->write(PHY_BASICCONTROL_REG, (data | PHY_BCTL_RESTART_AUTONEG_MASK)); + } + } + else + { + /* First read the current status in control one register. */ + result = phy_ksz8081.ops->read(PHY_CONTROL2_REG, &data); + if (PHY_STATUS_OK == result) + { + return phy_ksz8081.ops->write(PHY_CONTROL2_REG, (data & ~PHY_CTL2_REMOTELOOP_MASK)); + } + } + } + return result; +} + +static rt_phy_status get_link_status(rt_bool_t *status) +{ + rt_phy_status result; + rt_uint32_t data; + + /* Read the basic status register. */ + result = phy_ksz8081.ops->read(PHY_BASICSTATUS_REG, &data); + if (PHY_STATUS_OK == result) + { + if (!(PHY_BSTATUS_LINKSTATUS_MASK & data)) + { + /* link down. */ + *status = RT_FALSE; + } + else + { + /* link up. */ + *status = RT_TRUE; + } + } + return result; +} +static rt_phy_status get_link_speed_duplex(rt_uint32_t *speed, rt_uint32_t *duplex) +{ + rt_phy_status result = PHY_STATUS_OK; + rt_uint32_t data, ctl_reg; + + /* Read the control two register. */ + result = phy_ksz8081.ops->read(PHY_CONTROL1_REG, &ctl_reg); + if (PHY_STATUS_OK == result) + { + data = ctl_reg & PHY_CTL1_SPEEDUPLX_MASK; + if ((PHY_CTL1_10FULLDUPLEX_MASK == data) || (PHY_CTL1_100FULLDUPLEX_MASK == data)) + { + /* Full duplex. */ + *duplex = PHY_FULL_DUPLEX; + } + else + { + /* Half duplex. */ + *duplex = PHY_HALF_DUPLEX; + } + + data = ctl_reg & PHY_CTL1_SPEEDUPLX_MASK; + if ((PHY_CTL1_100HALFDUPLEX_MASK == data) || (PHY_CTL1_100FULLDUPLEX_MASK == data)) + { + /* 100M speed. */ + *speed = PHY_SPEED_100M; + } + else + { /* 10M speed. */ + *speed = PHY_SPEED_10M; + } + } + + return result; +} + +static struct rt_phy_ops phy_ops = +{ + .init = rt_phy_init, + .read = rt_phy_read, + .write = rt_phy_write, + .loopback = rt_phy_loopback, + .get_link_status = get_link_status, + .get_link_speed_duplex = get_link_speed_duplex, +}; + +static int rt_phy_ksz8081_register( void ) +{ + phy_ksz8081.ops = &phy_ops; + rt_hw_phy_register(&phy_ksz8081, "rtt-phy"); + return 1; +} + +INIT_DEVICE_EXPORT(rt_phy_ksz8081_register); + + + +#endif /* PHY_USING_KSZ8081 */ diff --git a/bsp/imxrt/tools/sdk_dist.py b/bsp/imxrt/tools/sdk_dist.py index 89b7da4356..b663628504 100644 --- a/bsp/imxrt/tools/sdk_dist.py +++ b/bsp/imxrt/tools/sdk_dist.py @@ -21,3 +21,6 @@ def dist_do_building(BSP_ROOT, dist_dir=None): print("=> copy bsp drivers") bsp_copy_files(os.path.join(library_path, 'drivers'), os.path.join(library_dir, 'drivers')) shutil.copyfile(os.path.join(library_path, 'Kconfig'), os.path.join(library_dir, 'Kconfig')) + + print("=> copy bsp peripherals") + bsp_copy_files(os.path.join(library_path, 'peripherals'), os.path.join(library_dir, 'peripherals')) diff --git a/components/drivers/Kconfig b/components/drivers/Kconfig index 457b8751fe..db4455160e 100755 --- a/components/drivers/Kconfig +++ b/components/drivers/Kconfig @@ -103,6 +103,10 @@ if RT_USING_I2C endif endif +config RT_USING_PHY + bool "Using ethernet phy device drivers" + default n + config RT_USING_PIN bool "Using generic GPIO device drivers" default y diff --git a/components/drivers/include/drivers/phy.h b/components/drivers/include/drivers/phy.h new file mode 100644 index 0000000000..9a9eaeb5dd --- /dev/null +++ b/components/drivers/include/drivers/phy.h @@ -0,0 +1,79 @@ + + +#ifndef __PHY_H___ +#define __PHY_H___ + +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* Defines the PHY link speed. This is align with the speed for MAC. */ +enum phy_speed +{ + PHY_SPEED_10M = 0U, /* PHY 10M speed. */ + PHY_SPEED_100M /* PHY 100M speed. */ +}; + +/* Defines the PHY link duplex. */ +enum phy_duplex +{ + PHY_HALF_DUPLEX = 0U, /* PHY half duplex. */ + PHY_FULL_DUPLEX /* PHY full duplex. */ +}; + +/*! @brief Defines the PHY loopback mode. */ +enum phy_loop +{ + PHY_LOCAL_LOOP = 0U, /* PHY local loopback. */ + PHY_REMOTE_LOOP /* PHY remote loopback. */ +}; + + +struct rt_phy_msg +{ + rt_uint32_t reg; + rt_uint32_t value; +}; + +typedef struct rt_phy_msg rt_phy_msg_t; + + +struct rt_phy_device +{ + struct rt_device parent; + struct rt_mdio_bus *bus; + rt_uint32_t addr; + struct rt_phy_ops *ops; +}; + +typedef struct rt_phy_device rt_phy_t; + + +enum { + PHY_STATUS_OK = 0, + PHY_STATUS_FAIL, + PHY_STATUS_TIMEOUT, +}; + +typedef rt_int32_t rt_phy_status; + +struct rt_phy_ops +{ + rt_phy_status (*init)(void *object, rt_uint32_t phy_addr, rt_uint32_t src_clock_hz); + rt_phy_status (*read)(rt_uint32_t reg, rt_uint32_t *data); + rt_phy_status (*write)(rt_uint32_t reg, rt_uint32_t data); + rt_phy_status (*loopback)(rt_uint32_t mode, rt_uint32_t speed, rt_bool_t enable); + rt_phy_status (*get_link_status)(rt_bool_t *status); + rt_phy_status (*get_link_speed_duplex)(rt_uint32_t *speed, rt_uint32_t *duplex); +}; + +rt_err_t rt_hw_phy_register(struct rt_phy_device *phy, const char *name); + +#ifdef __cplusplus +} +#endif + +#endif /* __PHY_H__*/ diff --git a/components/drivers/include/drivers/phy_mdio.h b/components/drivers/include/drivers/phy_mdio.h new file mode 100644 index 0000000000..a4a79f6e7a --- /dev/null +++ b/components/drivers/include/drivers/phy_mdio.h @@ -0,0 +1,35 @@ + + +#ifndef __MDIO_H___ +#define __MDIO_H___ + +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + +struct rt_mdio_bus_ops +{ + rt_bool_t (*init)(void *bus, rt_uint32_t src_clock_hz); + rt_size_t (*read)(void *bus, rt_uint32_t addr, rt_uint32_t reg, void *data, rt_uint32_t size); + rt_size_t (*write)(void *bus, rt_uint32_t addr, rt_uint32_t reg, void *data, rt_uint32_t size); + rt_bool_t (*uninit)(void *bus); +}; + +struct rt_mdio_bus +{ + void *hw_obj; + char *name; + struct rt_mdio_bus_ops *ops; +}; + +typedef struct rt_mdio_bus rt_mdio_t; + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/components/drivers/include/rtdevice.h b/components/drivers/include/rtdevice.h index f54290097c..f0fa2f5b4a 100644 --- a/components/drivers/include/rtdevice.h +++ b/components/drivers/include/rtdevice.h @@ -69,6 +69,11 @@ extern "C" { #endif /* RT_USING_I2C_BITOPS */ #endif /* RT_USING_I2C */ +#ifdef RT_USING_PHY +#include "drivers/phy.h" +#include "drivers/phy_mdio.h" +#endif /* RT_USING_PHY */ + #ifdef RT_USING_SDIO #include "drivers/mmcsd_core.h" #include "drivers/sd.h" diff --git a/components/drivers/phy/SConscript b/components/drivers/phy/SConscript new file mode 100644 index 0000000000..ec12ed24c2 --- /dev/null +++ b/components/drivers/phy/SConscript @@ -0,0 +1,8 @@ +from building import * + +cwd = GetCurrentDir() +src = Glob('*.c') +CPPPATH = [cwd + '/../include'] +group = DefineGroup('DeviceDrivers', src, depend = ['RT_USING_PHY'], CPPPATH = CPPPATH) + +Return('group') diff --git a/components/drivers/phy/phy.c b/components/drivers/phy/phy.c new file mode 100644 index 0000000000..3ed4a1a265 --- /dev/null +++ b/components/drivers/phy/phy.c @@ -0,0 +1,78 @@ + +/* + * Copyright (c) 2006-2020, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2020-09-27 wangqiang first version + */ + +#include +#include +#include + +#define DBG_TAG "PHY" +#define DBG_LVL DBG_INFO +#include + + +static rt_size_t phy_device_read(rt_device_t dev, rt_off_t pos, void *buffer, rt_size_t count) +{ + struct rt_phy_device *phy = (struct rt_phy_device *)dev->user_data; + struct rt_phy_msg *msg = (struct rt_phy_msg *)buffer; + return phy->bus->ops->read(phy->bus, phy->addr, msg->reg, &(msg->value), 4); +} +static rt_size_t phy_device_write(rt_device_t dev, rt_off_t pos, const void *buffer, rt_size_t count) +{ + struct rt_phy_device *phy = (struct rt_phy_device *)dev->user_data; + struct rt_phy_msg *msg = (struct rt_phy_msg *)buffer; + return phy->bus->ops->write(phy->bus, phy->addr, msg->reg, &(msg->value), 4); +} + + + +#ifdef RT_USING_DEVICE_OPS +const static struct rt_device_ops phy_ops = +{ + RT_NULL, + RT_NULL, + RT_NULL, + phy_device_read, + phy_device_write, + RT_NULL, +}; +#endif + +/* +* phy device register +*/ +rt_err_t rt_hw_phy_register(struct rt_phy_device *phy, const char *name) +{ + rt_err_t ret; + struct rt_device *device; + + device = &(phy->parent); + + device->type = RT_Device_Class_PHY; + device->rx_indicate = RT_NULL; + device->tx_complete = RT_NULL; + +#ifdef RT_USING_DEVICE_OPS + device->ops = phy_ops; +#else + device->init = NULL; + device->open = NULL; + device->close = NULL; + device->read = phy_device_read; + device->write = phy_device_write; + device->control = NULL; +#endif + device->user_data = phy; + + /* register a character device */ + ret = rt_device_register(device, name, RT_DEVICE_FLAG_RDWR); + + return ret; +} diff --git a/components/finsh/cmd.c b/components/finsh/cmd.c index d764ea4231..afbda59e90 100644 --- a/components/finsh/cmd.c +++ b/components/finsh/cmd.c @@ -821,6 +821,7 @@ static char *const device_type_str[] = "Miscellaneous Device", "Sensor Device", "Touch Device", + "Phy Device", "Unknown" }; diff --git a/include/rtdef.h b/include/rtdef.h index 5543b80ab7..100cd5c2d6 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -863,6 +863,7 @@ enum rt_device_class_type RT_Device_Class_Miscellaneous, /**< Miscellaneous device */ RT_Device_Class_Sensor, /**< Sensor device */ RT_Device_Class_Touch, /**< Touch device */ + RT_Device_Class_PHY, /**< PHY device */ RT_Device_Class_Unknown /**< unknown device */ }; -- cgit v1.3.1 From 98f0cfbf6e37a072ddf3aa2ae6a600c5dee964aa Mon Sep 17 00:00:00 2001 From: mysterywolf <920369182@qq.com> Date: Fri, 23 Oct 2020 01:04:06 +0800 Subject: define maximum value of ipc type --- include/rtdef.h | 8 ++++++++ src/ipc.c | 16 ++++++++-------- 2 files changed, 16 insertions(+), 8 deletions(-) (limited to 'include/rtdef.h') diff --git a/include/rtdef.h b/include/rtdef.h index 5543b80ab7..0690371c6d 100644 --- a/include/rtdef.h +++ b/include/rtdef.h @@ -33,6 +33,7 @@ * 2019-05-17 Bernard change version number to v4.0.2 * 2019-12-20 Bernard change version number to v4.0.3 * 2020-08-10 Meco Man add macro for struct rt_device_ops + * 2020-10-23 Meco Man define maximum value of ipc type */ #ifndef __RT_DEF_H__ @@ -102,6 +103,13 @@ typedef rt_base_t rt_off_t; /**< Type for offset */ #define RT_UINT32_MAX 0xffffffff /**< Maxium number of UINT32 */ #define RT_TICK_MAX RT_UINT32_MAX /**< Maxium number of tick */ +/* maximum value of ipc type */ +#define RT_SEM_VALUE_MAX RT_UINT16_MAX /**< Maxium number of semaphore .value */ +#define RT_MUTEX_VALUE_MAX RT_UINT16_MAX /**< Maxium number of mutex .value */ +#define RT_MUTEX_HOLD_MAX RT_UINT8_MAX /**< Maxium number of mutex .hold */ +#define RT_MB_ENTRY_MAX RT_UINT16_MAX /**< Maxium number of mailbox .entry */ +#define RT_MQ_ENTRY_MAX RT_UINT16_MAX /**< Maxium number of message queue .entry */ + #if defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) #define __CLANG_ARM #endif diff --git a/src/ipc.c b/src/ipc.c index 9cd2b8846d..454fcb5439 100644 --- a/src/ipc.c +++ b/src/ipc.c @@ -465,7 +465,7 @@ rt_err_t rt_sem_release(rt_sem_t sem) } else { - if(sem->value < 65535u) + if(sem->value < RT_SEM_VALUE_MAX) { sem->value ++; /* increase value */ } @@ -696,7 +696,7 @@ rt_err_t rt_mutex_take(rt_mutex_t mutex, rt_int32_t time) if (mutex->owner == thread) { - if(mutex->hold < 255u) + if(mutex->hold < RT_MUTEX_HOLD_MAX) { /* it's the same thread */ mutex->hold ++; @@ -723,7 +723,7 @@ __again: /* set mutex owner and original priority */ mutex->owner = thread; mutex->original_priority = thread->current_priority; - if(mutex->hold < 255u) + if(mutex->hold < RT_MUTEX_HOLD_MAX) { mutex->hold ++; } @@ -888,7 +888,7 @@ rt_err_t rt_mutex_release(rt_mutex_t mutex) /* set new owner and priority */ mutex->owner = thread; mutex->original_priority = thread->current_priority; - if(mutex->hold < 255u) + if(mutex->hold < RT_MUTEX_HOLD_MAX) { mutex->hold ++; } @@ -905,7 +905,7 @@ rt_err_t rt_mutex_release(rt_mutex_t mutex) } else { - if(mutex->value < 65535u) + if(mutex->value < RT_MUTEX_VALUE_MAX) { /* increase value */ mutex->value ++; @@ -1607,7 +1607,7 @@ rt_err_t rt_mb_send_wait(rt_mailbox_t mb, if (mb->in_offset >= mb->size) mb->in_offset = 0; - if(mb->entry < 65535u) + if(mb->entry < RT_MB_ENTRY_MAX) { /* increase message entry */ mb->entry ++; @@ -2179,7 +2179,7 @@ rt_err_t rt_mq_send_wait(rt_mq_t mq, if (mq->msg_queue_head == RT_NULL) mq->msg_queue_head = msg; - if(mq->entry < 65535u) + if(mq->entry < RT_MQ_ENTRY_MAX) { /* increase message entry */ mq->entry ++; @@ -2287,7 +2287,7 @@ rt_err_t rt_mq_urgent(rt_mq_t mq, const void *buffer, rt_size_t size) if (mq->msg_queue_tail == RT_NULL) mq->msg_queue_tail = msg; - if(mq->entry < 65535u) + if(mq->entry < RT_MQ_ENTRY_MAX) { /* increase message entry */ mq->entry ++; -- cgit v1.3.1