单片机裸机之实现任务调度+软timer(含源码)

一、实现目的

        在某些应用场景下,我们不需要使用操作系统,但是也希望能使用操作系统的api一样去调用自己的逻辑任务。如创建一个10ms的任务或定时器,只需要调用类似task_create或timer_create的接口就可以了。这样的好处一是我们只关心业务逻辑实现,不用关心什么时候要去执行这个任务,二是这样能促进各个模块独立解耦,代码结构也会很清晰。

二、实现

        1.采用系统的定时器来提供系统时间粒度,一般为1ms。

void SysTick_Handler(void)
{
	g_systick_cnt++;
	timer_check();
}
/**
  * @brief  This function handles SysTick Handler.
  * @param  None
  * @retval None
  */
uint32_t get_ticks(void)
{
	return g_systick_cnt;
}

/**
  * @brief  initialize systick interrupt every 1ms
  * @param  none
  * @retval none
  */
void systick_init(void)
{
  /*
  systick_clock_source_config(SYSTICK_CLOCK_SOURCE_AHBCLK_NODIV);
  SysTick->LOAD = (uint32_t)(system_core_clock / 1000);
  SysTick->VAL = 0x00;
  SysTick->CTRL |= SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk;
  NVIC_SetPriority(SysTick_IRQn, 3);
*/
    /* setup systick timer for 1000Hz interrupts */
    if(SysTick_Config(SystemCoreClock / 1000U)) {
        /* capture error */
        while(1) {
        }
    }
    /* configure the systick handler priority */
    NVIC_SetPriority(SysTick_IRQn, 0x00U);
}

        你可能会有疑问,不用担心g_systick_cnt会溢出吗?后面解答。

        2.然后在main的while(1)中实现调度器,它就跟根据你创建的任务开始调度了。

int main(void)
{
	
    /* 任务初始化 */
    //task_create(...);
	
	while(1)
	{
		task_schedule();
	}
}

/**
 * @brief 任务调度
 * @param None
 * @retval none
 */
void task_schedule(void)
{
	uint32_t current_ticks = 0;
	uint32_t prio_grop = 0;
	struct task_t* task;
	struct task_t* n;
	
	if (!g_priority_group)
	{
		// 没有任务需要执行 
		return;
	}
	
	// 获取最高优先级任务组
	prio_grop = get_highest_prio();
	// 循环执行任务组中的任务
	list_for_each_entry_safe(task, n, &task_priority_table[prio_grop], node)
	{
		current_ticks = get_ticks();
		// 任务执行周期到了,防止tick溢出
		if (current_ticks - task->ticks < (TIME_TICKS_MAX / 2))
		{
			// 改变任务状态
			task->state = TASK_RUNNING;
			if (task->func)
			{
				task->func(task->param);
			}
			else
			{
				task->err_code = TASK_ERR_NOFUNC;
			}
			
			// 更新任务下一个执行时间
			task->ticks = get_ticks() + task->period;
			// 改变任务状态为suspend
			task->state = TASK_SUSPEND;
		}	
	}
}

       其中if (current_ticks - task->ticks < (TIME_TICKS_MAX / 2))就是为了防止溢出,就是当前时间片已经超过了0xffffffff,溢出会重新从0开始计数,此时减出来是负数,负数转为无符号。比如当前时间是10,任务到期时间是task->ticks是0xffffffff,10-0xffffffff相减最后就是11,条件成立,就任务任务已经到期,需要执行。注意有个前提是任务周期不能大于(0xffffffff/2)。Rtthread就是这样判断超时的,感兴趣的靓仔可以review一下rtthread的源码。

三、完整源码

        1.所有任务都是挂在一条链表上的,链表是根据linux内核链表来的,下面粘贴一下内核链表完整文件。

/*
 *  list.h
 *
 *  Created on: 2020.11.20
 *  Author: 
 *  brief: linux kernel list, refer to https://blog.csdn.net/qq153471503/article/details/79180659
 */

#ifndef LIST_H_
#define LIST_H_

#include <stdio.h>

#define prefetch(x) __builtin_prefetch(x)

#ifndef container_of
/**
* container_of - cast a member of a structure out to the containing structure
*
* @ptr:        the pointer to the member.
* @type:       the type of the container struct this is embedded in.
* @member:     the name of the member within the struct.
*
*/
#define container_of(ptr, type, member) ({                      \
         const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
          (type *)( (char *)__mptr - offsetof(type,member) );})
#endif

#undef offsetof
#ifdef __compiler_offsetof
#define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER)
#else
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#endif

/*
* Simple doubly linked list implementation.
*
* Some of the internal functions ("__xxx") are useful when
* manipulating whole lists rather than single entries, as
* sometimes we already know the next/prev entries and we can
* generate better code by using them directly rather than
* using the generic single-entry routines.
*/

struct list_head
{
    struct list_head *next, *prev;
};

#define LIST_HEAD_INIT(name) { &(name), &(name) }

#define LIST_HEAD(name) \
    struct list_head name = LIST_HEAD_INIT(name)

static inline void INIT_LIST_HEAD(struct list_head *list)
{
    list->next = list;
    list->prev = list;
}

/*
* Insert a new entry between two known consecutive entries.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next)
{
    next->prev = new;
    new->next = next;
    new->prev = prev;
    prev->next = new;
}

/**
* list_add - add a new entry
* @new: new entry to be added
* @head: list head to add it after
*
* Insert a new entry after the specified head.
* This is good for implementing stacks.
*/
static inline void list_add(struct list_head *new, struct list_head *head)
{
    __list_add(new, head, head->next);
}

/**
* list_add_tail - add a new entry
* @new: new entry to be added
* @head: list head to add it before
*
* Insert a new entry before the specified head.
* This is useful for implementing queues.
*/
static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
    __list_add(new, head->prev, head);
}

/*
* Delete a list entry by making the prev/next entries
* point to each other.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
static inline void __list_del(struct list_head *prev, struct list_head *next)
{
    next->prev = prev;
    prev->next = next;
}

/**
* list_del - deletes entry from list.
* @entry: the element to delete from the list.
* Note: list_empty() on entry does not return true after this, the entry is
* in an undefined state.
*/
static inline void list_del(struct list_head *entry)
{
    __list_del(entry->prev, entry->next);
    entry->next = NULL;
    entry->prev = NULL;
}

/**
* list_replace - replace old entry by new one
* @old : the element to be replaced
* @new : the new element to insert
*
* If @old was empty, it will be overwritten.
*/
static inline void list_replace(struct list_head *old, struct list_head *new)
{
    new->next = old->next;
    new->next->prev = new;
    new->prev = old->prev;
    new->prev->next = new;
}

static inline void list_replace_init(struct list_head *old, struct list_head *new)
{
    list_replace(old, new);
    INIT_LIST_HEAD(old);
}

/**
* list_del_init - deletes entry from list and reinitialize it.
* @entry: the element to delete from the list.
*/
static inline void list_del_init(struct list_head *entry)
{
    __list_del(entry->prev, entry->next);
    INIT_LIST_HEAD(entry);
}

/**
* list_move - delete from one list and add as another's head
* @list: the entry to move
* @head: the head that will precede our entry
*/
static inline void list_move(struct list_head *list, struct list_head *head)
{
    __list_del(list->prev, list->next);
    list_add(list, head);
}

/**
* list_move_tail - delete from one list and add as another's tail
* @list: the entry to move
* @head: the head that will follow our entry
*/
static inline void list_move_tail(struct list_head *list, struct list_head *head)
{
    __list_del(list->prev, list->next);
    list_add_tail(list, head);
}

/**
* list_is_last - tests whether @list is the last entry in list @head
* @list: the entry to test
* @head: the head of the list
*/
static inline int list_is_last(const struct list_head *list, const struct list_head *head)
{
    return list->next == head;
}

/**
* list_empty - tests whether a list is empty
* @head: the list to test.
*/
static inline int list_empty(const struct list_head *head)
{
    return head->next == head;
}

/**
* list_empty_careful - tests whether a list is empty and not being modified
* @head: the list to test
*
* Description:
* tests whether a list is empty _and_ checks that no other CPU might be
* in the process of modifying either member (next or prev)
*
* NOTE: using list_empty_careful() without synchronization
* can only be safe if the only activity that can happen
* to the list entry is list_del_init(). Eg. it cannot be used
* if another CPU could re-list_add() it.
*/
static inline int list_empty_careful(const struct list_head *head)
{
    struct list_head *next = head->next;
    return (next == head) && (next == head->prev);
}

/**
* list_is_singular - tests whether a list has just one entry.
* @head: the list to test.
*/
static inline int list_is_singular(const struct list_head *head)
{
    return !list_empty(head) && (head->next == head->prev);
}

static inline void __list_cut_position(struct list_head *list, struct list_head *head, struct list_head *entry)
{
    struct list_head *new_first = entry->next;
    list->next = head->next;
    list->next->prev = list;
    list->prev = entry;
    entry->next = list;
    head->next = new_first;
    new_first->prev = head;
}

/**
* list_cut_position - cut a list into two
* @list: a new list to add all removed entries
* @head: a list with entries
* @entry: an entry within head, could be the head itself
*  and if so we won't cut the list
*
* This helper moves the initial part of @head, up to and
* including @entry,from @head to @list. You should
* pass on @entry an element you know is on @head. @list
* should be an empty list or a list you do not care about
* losing its data.
*
*/
static inline void list_cut_position(struct list_head *list, struct list_head *head, struct list_head *entry)
{
    if (list_empty(head))
        return;
    if (list_is_singular(head) &&
        (head->next != entry && head != entry))
        return;
    if (entry == head)
        INIT_LIST_HEAD(list);
    else
        __list_cut_position(list, head, entry);
}

static inline void __list_splice(const struct list_head *list, struct list_head *prev, struct list_head *next)
{
    struct list_head *first = list->next;
    struct list_head *last = list->prev;

    first->prev = prev;
    prev->next = first;

    last->next = next;
    next->prev = last;
}

/**
* list_splice - join two lists, this is designed for stacks
* @list: the new list to add.
* @head: the place to add it in the first list.
*/
static inline void list_splice(const struct list_head *list, struct list_head *head)
{
    if (!list_empty(list))
        __list_splice(list, head, head->next);
}

/**
* list_splice_tail - join two lists, each list being a queue
* @list: the new list to add.
* @head: the place to add it in the first list.
*/
static inline void list_splice_tail(struct list_head *list, struct list_head *head)
{
    if (!list_empty(list))
        __list_splice(list, head->prev, head);
}

/**
* list_splice_init - join two lists and reinitialise the emptied list.
* @list: the new list to add.
* @head: the place to add it in the first list.
*
* The list at @list is reinitialised
*/
static inline void list_splice_init(struct list_head *list, struct list_head *head)
{
    if (!list_empty(list))
    {
        __list_splice(list, head, head->next);
        INIT_LIST_HEAD(list);
    }
}

/**
* list_splice_tail_init - join two lists and reinitialise the emptied list
* @list: the new list to add.
* @head: the place to add it in the first list.
*
* Each of the lists is a queue.
* The list at @list is reinitialised
*/
static inline void list_splice_tail_init(struct list_head *list, struct list_head *head)
{
    if (!list_empty(list))
    {
        __list_splice(list, head->prev, head);
        INIT_LIST_HEAD(list);
    }
}

/**
* list_entry - get the struct for this entry
* @ptr:    the &struct list_head pointer.
* @type:   the type of the struct this is embedded in.
* @member: the name of the list_struct within the struct.
*/
#define list_entry(ptr, type, member) \
    container_of(ptr, type, member)

/**
* list_first_entry - get the first element from a list
* @ptr:    the list head to take the element from.
* @type:   the type of the struct this is embedded in.
* @member: the name of the list_struct within the struct.
*
* Note, that list is expected to be not empty.
*/
#define list_first_entry(ptr, type, member) \
    list_entry((ptr)->next, type, member)

/**
* list_for_each    -   iterate over a list
* @pos:    the &struct list_head to use as a loop cursor.
* @head:   the head for your list.
*/
#define list_for_each(pos, head) \
    for (pos = (head)->next; prefetch(pos->next), pos != (head); \
            pos = pos->next)

/**
* __list_for_each  -   iterate over a list
* @pos:    the &struct list_head to use as a loop cursor.
* @head:   the head for your list.
*
* This variant differs from list_for_each() in that it's the
* simplest possible list iteration code, no prefetching is done.
* Use this for code that knows the list to be very short (empty
* or 1 entry) most of the time.
*/
#define __list_for_each(pos, head) \
    for (pos = (head)->next; pos != (head); pos = pos->next)

/**
* list_for_each_prev   -   iterate over a list backwards
* @pos:    the &struct list_head to use as a loop cursor.
* @head:   the head for your list.
*/
#define list_for_each_prev(pos, head) \
    for (pos = (head)->prev; prefetch(pos->prev), pos != (head); \
            pos = pos->prev)

/**
* list_for_each_safe - iterate over a list safe against removal of list entry
* @pos:    the &struct list_head to use as a loop cursor.
* @n:      another &struct list_head to use as temporary storage
* @head:   the head for your list.
*/
#define list_for_each_safe(pos, n, head) \
    for (pos = (head)->next, n = pos->next; pos != (head); \
        pos = n, n = pos->next)

/**
* list_for_each_prev_safe - iterate over a list backwards safe against removal of list entry
* @pos:    the &struct list_head to use as a loop cursor.
* @n:      another &struct list_head to use as temporary storage
* @head:   the head for your list.
*/
#define list_for_each_prev_safe(pos, n, head) \
    for (pos = (head)->prev, n = pos->prev; \
         prefetch(pos->prev), pos != (head); \
         pos = n, n = pos->prev)

/**
* list_for_each_entry  -   iterate over list of given type
* @pos:    the type * to use as a loop cursor.
* @head:   the head for your list.
* @member: the name of the list_struct within the struct.
*/
#define list_for_each_entry(pos, head, member)              \
    for (pos = list_entry((head)->next, typeof(*pos), member);   \
         prefetch(pos->member.next), &pos->member != (head);  \
         pos = list_entry(pos->member.next, typeof(*pos), member))

/**
* list_for_each_entry_reverse - iterate backwards over list of given type.
* @pos:    the type * to use as a loop cursor.
* @head:   the head for your list.
* @member: the name of the list_struct within the struct.
*/
#define list_for_each_entry_reverse(pos, head, member)          \
    for (pos = list_entry((head)->prev, typeof(*pos), member);   \
         prefetch(pos->member.prev), &pos->member != (head);  \
         pos = list_entry(pos->member.prev, typeof(*pos), member))

/**
* list_prepare_entry - prepare a pos entry for use in list_for_each_entry_continue()
* @pos:    the type * to use as a start point
* @head:   the head of the list
* @member: the name of the list_struct within the struct.
*
* Prepares a pos entry for use as a start point in list_for_each_entry_continue().
*/
#define list_prepare_entry(pos, head, member) \
    ((pos) ? : list_entry(head, typeof(*pos), member))

/**
* list_for_each_entry_continue - continue iteration over list of given type
* @pos:    the type * to use as a loop cursor.
* @head:   the head for your list.
* @member: the name of the list_struct within the struct.
*
* Continue to iterate over list of given type, continuing after
* the current position.
*/
#define list_for_each_entry_continue(pos, head, member)         \
    for (pos = list_entry(pos->member.next, typeof(*pos), member);   \
         prefetch(pos->member.next), &pos->member != (head);  \
         pos = list_entry(pos->member.next, typeof(*pos), member))

/**
* list_for_each_entry_continue_reverse - iterate backwards from the given point
* @pos:    the type * to use as a loop cursor.
* @head:   the head for your list.
* @member: the name of the list_struct within the struct.
*
* Start to iterate over list of given type backwards, continuing aftafter
* the current position.
*/
#define list_for_each_entry_continue_reverse(pos, head, member)     \
    for (pos = list_entry(pos->member.prev, typeof(*pos), member);   \
         prefetch(pos->member.prev), &pos->member != (head);  \
         pos = list_entry(pos->member.prev, typeof(*pos), member))

/**
* list_for_each_entry_from - iterate over list of given type from the current point
* @pos:    the type * to use as a loop cursor.
* @head:   the head for your list.
* @member: the name of the list_struct within the struct.
*
* Iterate over list of given type, continuing from current position.
*/
#define list_for_each_entry_from(pos, head, member)             \
    for (; prefetch(pos->member.next), &pos->member != (head);    \
         pos = list_entry(pos->member.next, typeof(*pos), member))

/**
* list_for_each_entry_safe - iterate over list of given type safe against removal of list entry
* @pos:    the type * to use as a loop cursor.
* @n:      another type * to use as temporary storage
* @head:   the head for your list.
* @member: the name of the list_struct within the struct.
*/
#define list_for_each_entry_safe(pos, n, head, member)          \
    for (pos = list_entry((head)->next, typeof(*pos), member),   \
        n = list_entry(pos->member.next, typeof(*pos), member);  \
         &pos->member != (head);                     \
         pos = n, n = list_entry(n->member.next, typeof(*n), member))

/**
* list_for_each_entry_safe_continue
* @pos:    the type * to use as a loop cursor.
* @n:      another type * to use as temporary storage
* @head:   the head for your list.
* @member: the name of the list_struct within the struct.
*
* Iterate over list of given type, continuing after current point,
* safe against removal of list entry.
*/
#define list_for_each_entry_safe_continue(pos, n, head, member)         \
    for (pos = list_entry(pos->member.next, typeof(*pos), member),       \
        n = list_entry(pos->member.next, typeof(*pos), member);      \
         &pos->member != (head);                     \
         pos = n, n = list_entry(n->member.next, typeof(*n), member))

/**
* list_for_each_entry_safe_from
* @pos:    the type * to use as a loop cursor.
* @n:      another type * to use as temporary storage
* @head:   the head for your list.
* @member: the name of the list_struct within the struct.
*
* Iterate over list of given type from current point, safe against
* removal of list entry.
*/
#define list_for_each_entry_safe_from(pos, n, head, member)             \
    for (n = list_entry(pos->member.next, typeof(*pos), member);     \
         &pos->member != (head);                     \
         pos = n, n = list_entry(n->member.next, typeof(*n), member))

/**
* list_for_each_entry_safe_reverse
* @pos:    the type * to use as a loop cursor.
* @n:      another type * to use as temporary storage
* @head:   the head for your list.
* @member: the name of the list_struct within the struct.
*
* Iterate backwards over list of given type, safe against removal
* of list entry.
*/
#define list_for_each_entry_safe_reverse(pos, n, head, member)      \
    for (pos = list_entry((head)->prev, typeof(*pos), member),   \
        n = list_entry(pos->member.prev, typeof(*pos), member);  \
         &pos->member != (head);                     \
      pos = n, n = list_entry(n->member.prev, typeof(*n), member))

/*
* Double linked lists with a single pointer list head.
* Mostly useful for hash tables where the two pointer list head is
* too wasteful.
* You lose the ability to access the tail in O(1).
*/
struct hlist_head
{
    struct hlist_node *first;
};

struct hlist_node
{
    struct hlist_node *next, * *pprev;
};

#define HLIST_HEAD_INIT { .first = NULL }
#define HLIST_HEAD(name) struct hlist_head name = {  .first = NULL }
#define INIT_HLIST_HEAD(ptr) ((ptr)->first = NULL)
static inline void INIT_HLIST_NODE(struct hlist_node *h)
{
    h->next = NULL;
    h->pprev = NULL;
}

static inline int hlist_unhashed(const struct hlist_node *h)
{
    return !h->pprev;
}

static inline int hlist_empty(const struct hlist_head *h)
{
    return !h->first;
}

static inline void __hlist_del(struct hlist_node *n)
{
    struct hlist_node *next = n->next;
    struct hlist_node **pprev = n->pprev;
    *pprev = next;
    if (next)
        next->pprev = pprev;
}

static inline void hlist_del(struct hlist_node *n)
{
    __hlist_del(n);
    n->next = NULL;
    n->pprev = NULL;
}

static inline void hlist_del_init(struct hlist_node *n)
{
    if (!hlist_unhashed(n))
    {
        __hlist_del(n);
        INIT_HLIST_NODE(n);
    }
}

static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h)
{
    struct hlist_node *first = h->first;
    n->next = first;
    if (first)
        first->pprev = &n->next;
    h->first = n;
    n->pprev = &h->first;
}

static inline void hlist_add_before(struct hlist_node *n, struct hlist_node *next)
{
    n->pprev = next->pprev;
    n->next = next;
    next->pprev = &n->next;
    *(n->pprev) = n;
}

static inline void hlist_add_after(struct hlist_node *n, struct hlist_node *next)
{
    next->next = n->next;
    n->next = next;
    next->pprev = &n->next;

    if (next->next)
        next->next->pprev = &next->next;
}

/*
* Move a list from one list head to another. Fixup the pprev
* reference of the first entry if it exists.
*/
static inline void hlist_move_list(struct hlist_head *old, struct hlist_head *new)
{
    new->first = old->first;
    if (new->first)
        new->first->pprev = &new->first;
    old->first = NULL;
}

#define hlist_entry(ptr, type, member) container_of(ptr,type,member)

#define hlist_for_each(pos, head) \
    for (pos = (head)->first; pos && ({ prefetch(pos->next); 1; }); \
         pos = pos->next)

#define hlist_for_each_safe(pos, n, head) \
    for (pos = (head)->first; pos && ({ n = pos->next; 1; }); \
         pos = n)

/**
* hlist_for_each_entry - iterate over list of given type
* @tpos:   the type * to use as a loop cursor.
* @pos:    the &struct hlist_node to use as a loop cursor.
* @head:   the head for your list.
* @member: the name of the hlist_node within the struct.
*/
#define hlist_for_each_entry(tpos, pos, head, member)            \
    for (pos = (head)->first;                     \
         pos && ({ prefetch(pos->next); 1;}) &&           \
        ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \
         pos = pos->next)

/**
* hlist_for_each_entry_continue - iterate over a hlist continuing after current point
* @tpos:   the type * to use as a loop cursor.
* @pos:    the &struct hlist_node to use as a loop cursor.
* @member: the name of the hlist_node within the struct.
*/
#define hlist_for_each_entry_continue(tpos, pos, member)         \
    for (pos = (pos)->next;                       \
         pos && ({ prefetch(pos->next); 1;}) &&           \
        ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \
         pos = pos->next)

/**
* hlist_for_each_entry_from - iterate over a hlist continuing from current point
* @tpos:   the type * to use as a loop cursor.
* @pos:    the &struct hlist_node to use as a loop cursor.
* @member: the name of the hlist_node within the struct.
*/
#define hlist_for_each_entry_from(tpos, pos, member)             \
    for (; pos && ({ prefetch(pos->next); 1;}) &&             \
        ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \
         pos = pos->next)

/**
* hlist_for_each_entry_safe - iterate over list of given type safe against removal of list entry
* @tpos:   the type * to use as a loop cursor.
* @pos:    the &struct hlist_node to use as a loop cursor.
* @n:      another &struct hlist_node to use as temporary storage
* @head:   the head for your list.
* @member: the name of the hlist_node within the struct.
*/
#define hlist_for_each_entry_safe(tpos, pos, n, head, member)        \
    for (pos = (head)->first;                     \
         pos && ({ n = pos->next; 1; }) &&                \
        ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \
         pos = n)

#endif /* LIST_H_ */

2.剩下的内容不用过多介绍了,直接上完整源码。

task.c

/*
 * Copyright (c) 2023, UP3D system I team
 *
 * @brief 任务管理中心
 *
 * Change Logs:
 * Date           Author       			Notes
 * 2023-03-24     lj          the first version
 */

#include <stdlib.h>
#include <string.h>
#include "task.h"

#include "mc_delay.h"
#include "common/common.h"


#define PRIORITY_MAX    32

#define TIME_TICKS_MAX	(0xffffffff)



// 任务链表
struct list_head g_task_list; 
struct list_head task_priority_table[PRIORITY_MAX];

// 控制优先级
static uint32_t g_priority_group = 0;

// 位图优先级表
const uint8_t __lowest_bit_bitmap[] =
{
    /* 00 */ 0, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
    /* 10 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
    /* 20 */ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
    /* 30 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
    /* 40 */ 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
    /* 50 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
    /* 60 */ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
    /* 70 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
    /* 80 */ 7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
    /* 90 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
    /* A0 */ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
    /* B0 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
    /* C0 */ 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
    /* D0 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
    /* E0 */ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
    /* F0 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0
};

// 位图获取最高优先级
int __rt_ffs(int value)
{
    if (value == 0) return 0;

    if (value & 0xff)
        return __lowest_bit_bitmap[value & 0xff] + 1;

    if (value & 0xff00)
        return __lowest_bit_bitmap[(value & 0xff00) >> 8] + 9;

    if (value & 0xff0000)
        return __lowest_bit_bitmap[(value & 0xff0000) >> 16] + 17;

    return __lowest_bit_bitmap[(value & 0xff000000) >> 24] + 25;
}

/**
 * @brief 获取最高优先级线程
 * @param None
 * @retval none
 */

uint32_t get_highest_prio(void)
{
    register uint32_t highest_ready_priority;

    highest_ready_priority = __rt_ffs(g_priority_group) - 1;

    return highest_ready_priority;
}

/**
 * @brief 初始化任务管理器
 * @param None
 * @retval none
 */
void task_init(void)
{
	int i;
	
	for (i=0; i<PRIORITY_MAX; i++)
	{
		INIT_LIST_HEAD(&task_priority_table[i]);
	}
	
	g_priority_group = 0;
}

/**
 * @brief 初始化任务管理器
 * @param None
 * @retval none
 */
void task_set_period(struct task_t* task, uint32_t period)
{
	if (NULL == task)
		return;
	
	task->period = period;
}

/**
 * @brief 创建任务
 * @param name:任务名
 * @param param:任务回调参数
 * @param func:任务回调函数
 * @param prio:任务优先级
 * @param period:任务周期
 * @retval 任务结构体
 */
struct task_t* task_create(char *name, task_func_t func, void *param, uint8_t prio, uint32_t period)
{
	uint16_t tmp_len = 0;
	struct task_t* task;
	
	if (0 == period)
		return NULL;
	
	task = malloc(sizeof(struct task_t));
	if (NULL == task)
		return NULL;
	
	if (NULL != name)
	{
		tmp_len = strlen(name);
		memcpy(task->name, name, tmp_len);
		task->name[tmp_len] = '\0';
	}
	else
	{
		memcpy(task->name, "unknown", 7);
		task->name[7] = '\0';
	}
	
	task->func = func;
	task->prio = prio;
	task->period = period;
	task->param = param;
	task->state = TASK_INIT;
	task->ticks = get_ticks() + task->period;
	task->err_code = 0;
	
	// 将任务添加至优先级调度链表
	list_add_tail(&task->node, &task_priority_table[task->prio]);
	
	if (prio > (PRIORITY_MAX-1))
		prio = PRIORITY_MAX-1;
	
	g_priority_group |= (1<< prio);
	
	return task;
}

/**
 * @brief 删除任务
 * @param task:要删除的任务
 * @retval none
 */
void task_delete(struct task_t *task)
{
	if (NULL == task)
		return;
	
	list_del(&task->node);
	
	free(task);
}

/**
 * @brief 任务调度
 * @param None
 * @retval none
 */
void task_schedule(void)
{
	uint32_t current_ticks = 0;
	uint32_t prio_grop = 0;
	struct task_t* task;
	struct task_t* n;
	
	if (!g_priority_group)
	{
		// 没有任务需要执行 
		return;
	}
	
	// 获取最高优先级任务组
	prio_grop = get_highest_prio();
	// 循环执行任务组中的任务
	list_for_each_entry_safe(task, n, &task_priority_table[prio_grop], node)
	{
		current_ticks = get_ticks();
		// 任务执行周期到了,防止tick溢出
		if (current_ticks - task->ticks < (TIME_TICKS_MAX / 2))
		{
			// 改变任务状态
			task->state = TASK_RUNNING;
			if (task->func)
			{
				task->func(task->param);
			}
			else
			{
				task->err_code = TASK_ERR_NOFUNC;
			}
			
			// 更新任务下一个执行时间
			task->ticks = get_ticks() + task->period;
			// 改变任务状态为suspend
			task->state = TASK_SUSPEND;
		}	
	}
}

/**
 * @brief 显示任务信息
 * @param None
 * @retval none
 */
void list_task(void)
{
		/* need modify */
//	uint32_t prio_grop = 0;
//	struct task_t* task;
//	struct task_t* n;
//	
//	prio_grop = get_highest_prio();
//	
//	PRINTF("\r\nname\tprio\tticks\terror\tstate\r\n");
//	PRINTF("---\t---\t---\t---\t---\r\n");
//	
//	list_for_each_entry_safe(task, n, &task_priority_table[prio_grop], node)
//	{
//		PRINTF("%s\t%d\t%d\t%d\t", task->name, task->prio, task->ticks, task->err_code);
//		if (task->state == TASK_SUSPEND)
//			PRINTF(" suspend \r\n");
//		else if (task->state == TASK_RUNNING)
//			PRINTF(" running \r\n");
//		else if (task->state == TASK_INIT)
//			PRINTF(" init \r\n");	
//	}
//	PRINTF("current ticks:%d\r\n", get_ticks());
	
	/* need modify */
}

//========================================timer
// 定时器链表
struct list_head g_timer_list;

/**
 * @brief 初始化定时器
 * @param None
 * @retval none
 */
void timer_init(void)
{
	INIT_LIST_HEAD(&g_timer_list);
}

/**
 * @brief 创建任务
 * @param name:任务名
 * @param param:任务回调参数
 * @param func:任务回调函数
 * @param prio:任务优先级
 * @param period:任务周期
 * @retval 任务结构体
 */
struct timer_t* timer_create(char *name, task_func_t func, void *param, uint32_t time, uint8_t flag)
{
	uint16_t tmp_len = 0;
	struct timer_t* timer;
	
	
	timer = malloc(sizeof(struct timer_t));
	if (NULL == timer)
		return NULL;
	
	if (NULL != name)
	{
		tmp_len = strlen(name);
		memcpy(timer->name, name, tmp_len);
		timer->name[tmp_len] = '\0';
	}
	else
	{
		memcpy(timer->name, "unknown", 7);
		timer->name[7] = '\0';
	}
	
	timer->flag = flag;  
	timer->flag &= ~RT_TIMER_FLAG_ACTIVATED;
	timer->func = func;
	timer->param = param;
	timer->init_tick = time;
	timer->timeout_tick = 0;
	
	// 将任务添加至定时器链表
	list_add_tail(&timer->node, &g_timer_list);

	return timer;
}

/**
 * @brief 删除任务
 * @param task:要删除的任务
 * @retval none
 */
void timer_delete(struct timer_t *timer)
{
	if (NULL == timer)
		return;
	
	list_del(&timer->node);
	
	free(timer);
}

/**
 * @brief 停止定时器
 * @param task:要停止的定时器
 * @retval none
 */
void timer_start(struct timer_t *timer)
{
	if (NULL == timer)
		return;
	
	__disable_irq();
	timer->timeout_tick = get_ticks() + timer->init_tick;
	timer->flag |= RT_TIMER_FLAG_ACTIVATED;
	
	if ((timer->rflag & RT_TIMER_FLAG_PERIODIC))
	{
			timer->flag |= RT_TIMER_FLAG_PERIODIC;
	}
	__enable_irq();
}

/**
 * @brief 开始定时器
 * @param task:要开始的定时器
 * @retval none
 */
void timer_stop(struct timer_t *timer)
{
	if (NULL == timer)
		return;
	
	__disable_irq();
	timer->flag &= ~RT_TIMER_FLAG_ACTIVATED;
	if ((timer->flag & RT_TIMER_FLAG_PERIODIC))
	{
			timer->flag &= ~RT_TIMER_FLAG_PERIODIC;
			timer->rflag |= RT_TIMER_FLAG_PERIODIC;
	}
	__enable_irq();
}

void timer_check(void)
{
	struct timer_t* timer;
	struct timer_t* n;
	uint32_t current_tick = get_ticks();
	
	list_for_each_entry_safe(timer, n, &g_timer_list, node)
	{
		if (current_tick - timer->timeout_tick < (TIME_TICKS_MAX / 2))
		{
			if (timer->flag & RT_TIMER_FLAG_ACTIVATED)
			{				
				//timer->flag &= ~RT_TIMER_FLAG_ACTIVATED;
				timer->func(timer->param);
				timer->timeout_tick = get_ticks() + timer->init_tick;
/*				
				if ((timer->flag & RT_TIMER_FLAG_PERIODIC))
				{
						timer->timeout_tick = get_ticks() + timer->init_tick;
						timer->flag |= RT_TIMER_FLAG_ACTIVATED;
				}*/
			}
		}
	}
}

        task.h

/*
 * Copyright (c) 2023, UP3D system I team
 *
 * @brief 任务管理中心
 *
 * Change Logs:
 * Date           Author       			Notes
 * 2023-03-24     lj          the first version
 */
 
#ifndef APPLICATION_TASK_H
#define APPLICATION_TASK_H

#include <stdint.h>
#include "list.h"

#define TASK_NAME_MAX	10

/**
 * @brief 任务状态
 */
typedef enum {
	TASK_INIT,
	TASK_SUSPEND,
	TASK_RUNNING,
	TASK_ERR
}task_state;

/**
 * @brief 任务状态
 */
typedef enum {
	TASK_ERR_NOFUNC,	//没有执行函数
	TASK_ERR_TIMEOUT,	
}task_err_code_t;


typedef void (*task_func_t) (void *);

struct task_t{
	char name[TASK_NAME_MAX];	// 任务名称
	uint8_t state;				// 任务状态
	uint8_t prio;				// 任务优先级 0~255
	uint32_t ticks;				// 任务运行时间
	uint32_t period;			// 任务运行周期
	task_func_t func;			// 任务回调函数
	void *param;				// 任务参数
	uint8_t err_code;			// 任务错误码
	struct list_head node; 
};
typedef struct task_t* task_type_t;


/**
 * @brief 初始化任务管理器
 * @param None
 * @retval none
 */
void task_init(void);

/**
 * @brief 创建任务
 * @param name:任务名
 * @param param:任务回调参数
 * @param func:任务回调函数
 * @param prio:任务优先级
 * @param period:任务周期
 * @retval 任务结构体
 */
struct task_t* task_create(char *name, task_func_t func, void *param, uint8_t prio, uint32_t period);

/**
 * @brief 任务删除
 * @param task:要删除的任务
 * @retval none
 */
void task_delete(struct task_t *task);

/**
 * @brief 任务调度
 * @param None
 * @retval none
 */
void task_schedule(void);

/**
 * @brief 初始化任务管理器
 * @param None
 * @retval none
 */
void task_set_period(struct task_t* task, uint32_t period);

/**
 * @brief 显示任务信息
 * @param None
 * @retval none
 */
void list_task(void);

#define RT_TIMER_FLAG_DEACTIVATED       0x0             /**< timer is deactive */
#define RT_TIMER_FLAG_ACTIVATED         0x1             /**< timer is active */
#define RT_TIMER_FLAG_ONE_SHOT          0x0             /**< one shot timer */
#define RT_TIMER_FLAG_PERIODIC          0x2             /**< periodic timer */

struct timer_t{
	char name[TASK_NAME_MAX];	// 任务名称
//	uint8_t state;				// 任务状态
	uint8_t flag;				// 任务优先级 0~255
    uint8_t rflag;
	uint32_t timeout_tick;				// 任务运行时间
	uint32_t init_tick;			// 任务运行周期
	task_func_t func;			// 任务回调函数
	void *param;				// 任务参数
	struct list_head node; 
};
typedef struct timer_t* timer_type_t;

/**
 * @brief 初始化定时器
 * @param None
 * @retval none
 */
void timer_init(void);

/**
 * @brief 创建任务
 * @param name:任务名
 * @param param:任务回调参数
 * @param func:任务回调函数
 * @param prio:任务优先级
 * @param period:任务周期
 * @retval 任务结构体
 */
struct timer_t* timer_create(char *name, task_func_t func, void *param, uint32_t time, uint8_t flag);

/**
 * @brief 删除任务
 * @param task:要删除的任务
 * @retval none
 */
void timer_delete(struct timer_t *timer);


 /**
 * @brief 开始定时器
 * @param task:要开始的定时器
 * @retval none
 */
void timer_start(struct timer_t *timer);

/**
 * @brief 停止定时器
 * @param task:要停止的定时器
 * @retval none
 */
void timer_stop(struct timer_t *timer);
#endif /* task.h */

四、使用例子

    timer_type_t m_key_timer = NULL;
    task_type_t lk_tid = NULL;    

    // 创建一个5ms的周期定时器,RT_TIMER_FLAG_PERIODIC:周期
    m_key_timer= timer_create("key_timer", key_timer_timeout, NULL, 5, RT_TIMER_FLAG_PERIODIC);
    // 开始定时器
    timer_start(m_key_timer);
    // 创建一个名为lk,入口函数为lk_dis_task,优先级为1,执行周期为10ms的任务
    lk_tid = task_create("lk", lk_dis_task, NULL, 1, 10);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值