code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "k_api.h" #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) #if (RHINO_CONFIG_USER_SPACE > 0) void krhino_utask_free_res(ktask_t *task); #endif void dyn_mem_proc_task(void *arg) { CPSR_ALLOC(); size_t i; kstat_t ret; res_free_t *res_free; res_free_t tmp; (void)arg; while (1) { ret = krhino_sem_take(&g_res_sem, RHINO_WAIT_FOREVER); if (ret != RHINO_SUCCESS) { k_err_proc(RHINO_DYN_MEM_PROC_ERR); } while (1) { RHINO_CRITICAL_ENTER(); if (!is_klist_empty(&g_res_list)) { res_free = krhino_list_entry(g_res_list.next, res_free_t, res_list); klist_rm(&res_free->res_list); RHINO_CRITICAL_EXIT(); #if (RHINO_CONFIG_USER_SPACE > 0) krhino_utask_free_res((ktask_t *)(res_free->res[1])); #endif memcpy(&tmp, res_free, sizeof(res_free_t)); for (i = 0; i < tmp.cnt; i++) { krhino_mm_free(tmp.res[i]); } } else { RHINO_CRITICAL_EXIT(); break; } } } } __attribute__((weak)) void dyn_mem_proc_task_start(void) { krhino_task_create(&g_dyn_task, "dyn_mem_proc_task", 0, RHINO_CONFIG_K_DYN_MEM_TASK_PRI, 0, g_dyn_task_stack, RHINO_CONFIG_K_DYN_TASK_STACK, dyn_mem_proc_task, 1); } #endif
YifuLiu/AliOS-Things
kernel/rhino/k_dyn_mem_proc.c
C
apache-2.0
1,478
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "k_api.h" #if AOS_COMP_DEBUG #include "aos/debug.h" #endif void k_err_proc_debug(kstat_t err, char *file, int line) { #if AOS_COMP_DEBUG aos_debug_fatal_error(err, file, line); #endif if (g_err_proc != NULL) { g_err_proc(err); } }
YifuLiu/AliOS-Things
kernel/rhino/k_err.c
C
apache-2.0
328
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "k_api.h" #if (RHINO_CONFIG_EVENT_FLAG > 0) static kstat_t event_create(kevent_t *event, const name_t *name, uint32_t flags, uint8_t mm_alloc_flag) { #if (RHINO_CONFIG_KOBJ_LIST > 0) CPSR_ALLOC(); #endif NULL_PARA_CHK(event); NULL_PARA_CHK(name); memset(event, 0, sizeof(kevent_t)); /* init the list */ klist_init(&event->blk_obj.blk_list); event->blk_obj.blk_policy = BLK_POLICY_PRI; event->blk_obj.name = name; event->flags = flags; event->mm_alloc_flag = mm_alloc_flag; #if (RHINO_CONFIG_TASK_DEL > 0) event->blk_obj.cancel = 1u; #endif #if (RHINO_CONFIG_KOBJ_LIST > 0) RHINO_CRITICAL_ENTER(); klist_insert(&(g_kobj_list.event_head), &event->event_item); RHINO_CRITICAL_EXIT(); #endif TRACE_EVENT_CREATE(krhino_cur_task_get(), event, name, flags); event->blk_obj.obj_type = RHINO_EVENT_OBJ_TYPE; return RHINO_SUCCESS; } kstat_t krhino_event_create(kevent_t *event, const name_t *name, uint32_t flags) { return event_create(event, name, flags, K_OBJ_STATIC_ALLOC); } kstat_t krhino_event_del(kevent_t *event) { CPSR_ALLOC(); klist_t *blk_list_head; NULL_PARA_CHK(event); RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); if (event->blk_obj.obj_type != RHINO_EVENT_OBJ_TYPE) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_TYPE_ERR; } if (event->mm_alloc_flag != K_OBJ_STATIC_ALLOC) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_DEL_ERR; } blk_list_head = &event->blk_obj.blk_list; event->blk_obj.obj_type = RHINO_OBJ_TYPE_NONE; while (!is_klist_empty(blk_list_head)) { pend_task_rm(krhino_list_entry(blk_list_head->next, ktask_t, task_list)); } event->flags = 0u; #if (RHINO_CONFIG_KOBJ_LIST > 0) klist_rm(&event->event_item); #endif TRACE_EVENT_DEL(g_active_task[cpu_cur_get()], event); RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) kstat_t krhino_event_dyn_create(kevent_t **event, const name_t *name, uint32_t flags) { kstat_t stat; kevent_t *event_obj; if (event == NULL) { return RHINO_NULL_PTR; } event_obj = krhino_mm_alloc(sizeof(kevent_t)); if (event_obj == NULL) { return RHINO_NO_MEM; } stat = event_create(event_obj, name, flags, K_OBJ_DYN_ALLOC); if (stat != RHINO_SUCCESS) { krhino_mm_free(event_obj); return stat; } *event = event_obj; return stat; } kstat_t krhino_event_dyn_del(kevent_t *event) { CPSR_ALLOC(); klist_t *blk_list_head; NULL_PARA_CHK(event); RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); if (event->blk_obj.obj_type != RHINO_EVENT_OBJ_TYPE) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_TYPE_ERR; } if (event->mm_alloc_flag != K_OBJ_DYN_ALLOC) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_DEL_ERR; } blk_list_head = &event->blk_obj.blk_list; event->blk_obj.obj_type = RHINO_OBJ_TYPE_NONE; while (!is_klist_empty(blk_list_head)) { pend_task_rm(krhino_list_entry(blk_list_head->next, ktask_t, task_list)); } event->flags = 0u; #if (RHINO_CONFIG_KOBJ_LIST > 0) klist_rm(&event->event_item); #endif RHINO_CRITICAL_EXIT_SCHED(); krhino_mm_free(event); return RHINO_SUCCESS; } #endif kstat_t krhino_event_get(kevent_t *event, uint32_t flags, uint8_t opt, uint32_t *actl_flags, tick_t ticks) { CPSR_ALLOC(); kstat_t stat; uint8_t status; uint8_t cur_cpu_num; NULL_PARA_CHK(event); NULL_PARA_CHK(actl_flags); if ((opt != RHINO_AND) && (opt != RHINO_OR) && (opt != RHINO_AND_CLEAR) && (opt != RHINO_OR_CLEAR)) { return RHINO_NO_THIS_EVENT_OPT; } RHINO_CRITICAL_ENTER(); cur_cpu_num = cpu_cur_get(); TASK_CANCEL_CHK(event); INTRPT_NESTED_LEVEL_CHK(); if (event->blk_obj.obj_type != RHINO_EVENT_OBJ_TYPE) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_TYPE_ERR; } /* if option is AND MASK or OR MASK */ if (opt & RHINO_FLAGS_AND_MASK) { if ((event->flags & flags) == flags) { status = RHINO_TRUE; } else { status = RHINO_FALSE; } } else { if ((event->flags & flags) > 0u) { status = RHINO_TRUE; } else { status = RHINO_FALSE; } } if (status == RHINO_TRUE) { *actl_flags = event->flags; if (opt & RHINO_FLAGS_CLEAR_MASK) { event->flags &= ~flags; } TRACE_EVENT_GET(g_active_task[cur_cpu_num], event); RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } /* can't get event, and return immediately if wait_option is RHINO_NO_WAIT */ if (ticks == RHINO_NO_WAIT) { RHINO_CRITICAL_EXIT(); return RHINO_NO_PEND_WAIT; } /* system is locked so task can not be blocked just return immediately */ if (g_sched_lock[cur_cpu_num] > 0u) { RHINO_CRITICAL_EXIT(); return RHINO_SCHED_DISABLE; } /* remember the passed information */ g_active_task[cur_cpu_num]->pend_option = opt; g_active_task[cur_cpu_num]->pend_flags = flags; g_active_task[cur_cpu_num]->pend_info = actl_flags; pend_to_blk_obj(&event->blk_obj, g_active_task[cur_cpu_num], ticks); TRACE_EVENT_GET_BLK(g_active_task[cur_cpu_num], event, ticks); RHINO_CRITICAL_EXIT_SCHED(); RHINO_CPU_INTRPT_DISABLE(); /* so the task is waked up, need know which reason cause wake up */ stat = pend_state_end_proc(g_active_task[cpu_cur_get()], &event->blk_obj); RHINO_CPU_INTRPT_ENABLE(); return stat; } static kstat_t event_set(kevent_t *event, uint32_t flags, uint8_t opt) { CPSR_ALLOC(); klist_t *iter; klist_t *event_head; klist_t *iter_temp; ktask_t *task; uint8_t status; uint32_t cur_event_flags; status = RHINO_FALSE; RHINO_CRITICAL_ENTER(); if (event->blk_obj.obj_type != RHINO_EVENT_OBJ_TYPE) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_TYPE_ERR; } event_head = &event->blk_obj.blk_list; /* if the set_option is AND_MASK, it just clears the flags and will return immediately */ if (opt & RHINO_FLAGS_AND_MASK) { event->flags &= flags; RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } else { event->flags |= flags; } cur_event_flags = event->flags; iter = event_head->next; /* if list is not empty */ while (iter != event_head) { task = krhino_list_entry(iter, ktask_t, task_list); iter_temp = iter->next; if (task->pend_option & RHINO_FLAGS_AND_MASK) { if ((cur_event_flags & task->pend_flags) == task->pend_flags) { status = RHINO_TRUE; } else { status = RHINO_FALSE; } } else { if (cur_event_flags & task->pend_flags) { status = RHINO_TRUE; } else { status = RHINO_FALSE; } } if (status == RHINO_TRUE) { (*(uint32_t *)(task->pend_info)) = cur_event_flags; /* the task condition is met, just wake this task */ pend_task_wakeup(task); TRACE_EVENT_TASK_WAKE(g_active_task[cpu_cur_get()], task, event); /* does it need to clear the flags */ if (task->pend_option & RHINO_FLAGS_CLEAR_MASK) { event->flags &= ~(task->pend_flags); } } iter = iter_temp; } RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } kstat_t krhino_event_set(kevent_t *event, uint32_t flags, uint8_t opt) { NULL_PARA_CHK(event); if ((opt != RHINO_AND) && (opt != RHINO_OR)) { return RHINO_NO_THIS_EVENT_OPT; } return event_set(event, flags, opt); } #endif /* RHINO_CONFIG_EVENT_FLAG */
YifuLiu/AliOS-Things
kernel/rhino/k_event.c
C
apache-2.0
8,087
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdio.h> #include "k_api.h" #if (RHINO_CONFIG_CPU_USAGE_STATS > 0) void idle_count_set(idle_count_t value) { CPSR_ALLOC(); RHINO_CPU_INTRPT_DISABLE(); g_idle_count[cpu_cur_get()] = value; RHINO_CPU_INTRPT_ENABLE(); } idle_count_t idle_count_get(void) { CPSR_ALLOC(); idle_count_t idle_count; RHINO_CPU_INTRPT_DISABLE(); idle_count = g_idle_count[cpu_cur_get()]; RHINO_CPU_INTRPT_ENABLE(); return idle_count; } #endif void idle_task(void *arg) { uint8_t cpu_num; #if (RHINO_CONFIG_CPU_NUM > 1) CPSR_ALLOC(); klist_t *head; ktask_t *task_del; head = &g_task_del_head; #endif /* avoid warning */ (void)arg; cpu_num = cpu_cur_get(); #if (RHINO_CONFIG_USER_HOOK > 0) krhino_idle_pre_hook(); #endif while (RHINO_TRUE) { #if (RHINO_CONFIG_CPU_NUM > 1) RHINO_CPU_INTRPT_DISABLE(); if (head->next != head) { task_del = krhino_list_entry(head->next, ktask_t, task_del_item); if (task_del->cur_exc == 0) { klist_rm(&task_del->task_del_item); if (task_del->mm_alloc_flag == K_OBJ_DYN_ALLOC) { krhino_task_dyn_del(task_del); } else { krhino_task_del(task_del); } } } RHINO_CPU_INTRPT_ENABLE(); #endif /* type conversion is used to avoid compiler optimization */ *(volatile idle_count_t *)(&g_idle_count[cpu_num]) = g_idle_count[cpu_num] + 1; #if (RHINO_CONFIG_USER_HOOK > 0) krhino_idle_hook(); #endif #if (RHINO_CONFIG_PWRMGMT > 0) cpu_pwr_down(); #endif } }
YifuLiu/AliOS-Things
kernel/rhino/k_idle.c
C
apache-2.0
1,727
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include "k_api.h" #if AOS_COMP_DEBUG #include "aos/debug.h" extern uint32_t debug_task_id_now(); extern void debug_cpu_stop(void); #endif #if (RHINO_CONFIG_MM_TLF > 0) extern k_mm_region_t g_mm_region[]; extern int g_region_num; #if RHINO_CONFIG_MM_DEBUG #if (RHINO_CONFIG_MM_TRACE_LVL > 0) volatile uint32_t g_kmm_bt = 0; int backtrace_now_get(void *trace[], int size, int offset); void kmm_bt_disable(void) { g_kmm_bt = KMM_BT_SET_BY_KV; } /* check bt status * ret 0 : enable * ret 1 : disable * */ int kmm_bt_check(void) { return (g_kmm_bt == KMM_BT_SET_BY_KV); } #endif void kmm_error(uint32_t mm_status_locked) { dumpsys_mm_info_func(mm_status_locked); k_err_proc(RHINO_SYS_FATAL_ERR); } #endif void k_mm_init(void) { uint32_t e = 0; /* init memory region */ (void)krhino_init_mm_head(&g_kmm_head, g_mm_region[0].start, g_mm_region[0].len); for (e = 1 ; e < g_region_num ; e++) { krhino_add_mm_region(g_kmm_head, g_mm_region[e].start, g_mm_region[e].len); } } /* init a region, contain 3 mmblk * ------------------------------------------------------------------- * | k_mm_list_t | k_mm_region_info_t | k_mm_list_t | free space |k_mm_list_t| * ------------------------------------------------------------------- * * "regionaddr" and "len" is aligned by caller */ RHINO_INLINE k_mm_list_t *init_mm_region(void *regionaddr, size_t len) { k_mm_list_t *midblk, *lastblk, *firstblk; k_mm_region_info_t *region; /* first mmblk for region info */ firstblk = (k_mm_list_t *) regionaddr; firstblk->prev = NULL; firstblk->buf_size = MM_ALIGN_UP(sizeof(k_mm_region_info_t)) | MM_BUFF_USED | MM_BUFF_PREV_USED; #if (RHINO_CONFIG_MM_DEBUG > 0u) firstblk->dye = MM_DYE_USED; firstblk->owner_id = MM_OWNER_ID_SELF; firstblk->trace_id = 0; firstblk->owner = 0; #endif /*last mmblk for stop merge */ lastblk = (k_mm_list_t *)((char *)regionaddr + len - MMLIST_HEAD_SIZE); /*middle mmblk for heap use */ midblk = MM_GET_NEXT_BLK(firstblk); midblk->buf_size = ((char *)lastblk - (char *)midblk->mbinfo.buffer) | MM_BUFF_USED | MM_BUFF_PREV_USED; midblk->mbinfo.free_ptr.prev = midblk->mbinfo.free_ptr.next = 0; /*last mmblk for stop merge */ lastblk->prev = midblk; /* set alloced, can't be merged */ lastblk->buf_size = 0 | MM_BUFF_USED | MM_BUFF_PREV_FREE; #if (RHINO_CONFIG_MM_DEBUG > 0u) lastblk->dye = MM_DYE_USED; lastblk->owner_id = MM_OWNER_ID_SELF; lastblk->trace_id = 0; lastblk->owner = MM_LAST_BLK_MAGIC; #endif region = (k_mm_region_info_t *)firstblk->mbinfo.buffer; region->next = 0; region->end = lastblk; return firstblk; } /* 2^(N + MM_MIN_BIT) <= size < 2^(1 + N + MM_MIN_BIT) */ static int32_t size_to_level(size_t size) { size_t cnt = 32 - krhino_clz32(size); if (cnt < MM_MIN_BIT) { return 0; } if (cnt > MM_MAX_BIT) { return -1; } return cnt - MM_MIN_BIT; } #if (K_MM_STATISTIC > 0) static void addsize(k_mm_head *mmhead, size_t size, size_t req_size) { int32_t level; if (mmhead->free_size > size) { mmhead->free_size -= size; } else { mmhead->free_size = 0; } mmhead->used_size += size; if (mmhead->used_size > mmhead->maxused_size) { mmhead->maxused_size = mmhead->used_size; } if (req_size > 0) { level = size_to_level(req_size); if (level != -1) { mmhead->alloc_times[level]++; } } } static void removesize(k_mm_head *mmhead, size_t size) { if (mmhead->used_size > size) { mmhead->used_size -= size; } else { mmhead->used_size = 0; } mmhead->free_size += size; } /* used_size++, free_size--, maybe maxused_size++ */ #define stats_addsize(mmhead, size, req_size) addsize(mmhead, size, req_size) /* used_size--, free_size++ */ #define stats_removesize(mmhead, size) removesize(mmhead, size) #else #define stats_addsize(mmhead, size, req_size) do {} while (0) #define stats_removesize(mmhead, size) do {} while (0) #endif kstat_t krhino_init_mm_head(k_mm_head **ppmmhead, void *addr, size_t len) { k_mm_list_t *nextblk; k_mm_list_t *firstblk; k_mm_head *pmmhead; void *orig_addr; #if (RHINO_CONFIG_MM_BLK > 0) mblk_pool_t *mmblk_pool; kstat_t stat; #endif NULL_PARA_CHK(ppmmhead); NULL_PARA_CHK(addr); memset(addr, 0, len); /* check paramters, addr and len need algin * 1. the length at least need RHINO_CONFIG_MM_TLF_BLK_SIZE for fixed size memory block * 2. and also ast least have 1k for user alloced */ orig_addr = addr; addr = (void *) MM_ALIGN_UP((size_t)addr); len -= (size_t)addr - (size_t)orig_addr; len = MM_ALIGN_DOWN(len); if (len == 0 || len < MM_MIN_HEAP_SIZE + RHINO_CONFIG_MM_TLF_BLK_SIZE || len > MM_MAX_SIZE) { return RHINO_MM_POOL_SIZE_ERR; } pmmhead = (k_mm_head *)addr; /* Zeroing the memory head */ memset(pmmhead, 0, sizeof(k_mm_head)); #if (RHINO_CONFIG_MM_REGION_MUTEX > 0) krhino_mutex_create(&pmmhead->mm_mutex, "mm_mutex"); #else krhino_spin_lock_init(&pmmhead->mm_lock); #endif firstblk = init_mm_region((void *)((size_t)addr + MM_ALIGN_UP(sizeof(k_mm_head))), MM_ALIGN_DOWN(len - sizeof(k_mm_head))); pmmhead->regioninfo = (k_mm_region_info_t *)firstblk->mbinfo.buffer; nextblk = MM_GET_NEXT_BLK(firstblk); *ppmmhead = pmmhead; /*mark it as free and set it to bitmap*/ #if (RHINO_CONFIG_MM_DEBUG > 0u) nextblk->dye = MM_DYE_USED; nextblk->owner_id = MM_OWNER_ID_SELF; nextblk->trace_id = 0; nextblk->owner = 0; #endif /* release free blk */ k_mm_free(pmmhead, nextblk->mbinfo.buffer); #if (K_MM_STATISTIC > 0) pmmhead->free_size = MM_GET_BUF_SIZE(nextblk); pmmhead->used_size = len - MM_GET_BUF_SIZE(nextblk); pmmhead->maxused_size = pmmhead->used_size; #endif #if (RHINO_CONFIG_MM_BLK > 0) pmmhead->fix_pool = NULL; mmblk_pool = k_mm_alloc(pmmhead, RHINO_CONFIG_MM_TLF_BLK_SIZE + MM_ALIGN_UP(sizeof(mblk_pool_t))); if (mmblk_pool) { stat = krhino_mblk_pool_init(mmblk_pool, "fixed_mm_blk", (void *)((size_t)mmblk_pool + MM_ALIGN_UP(sizeof(mblk_pool_t))), RHINO_CONFIG_MM_TLF_BLK_SIZE); if (stat == RHINO_SUCCESS) { pmmhead->fix_pool = mmblk_pool; } else { k_mm_free(pmmhead, mmblk_pool); } } #endif return RHINO_SUCCESS; } kstat_t krhino_deinit_mm_head(k_mm_head *mmhead) { #if (RHINO_CONFIG_MM_REGION_MUTEX > 0) krhino_mutex_del(&mmhead->mm_mutex); #endif memset(mmhead, 0, sizeof(k_mm_head)); return RHINO_SUCCESS; } kstat_t krhino_add_mm_region(k_mm_head *mmhead, void *addr, size_t len) { void *orig_addr; k_mm_region_info_t *region; k_mm_list_t *firstblk; k_mm_list_t *nextblk; cpu_cpsr_t flags_cpsr; (void)flags_cpsr; NULL_PARA_CHK(mmhead); NULL_PARA_CHK(addr); orig_addr = addr; addr = (void *) MM_ALIGN_UP((size_t)addr); len -= (size_t)addr - (size_t)orig_addr; len = MM_ALIGN_DOWN(len); if (!len || len < sizeof(k_mm_region_info_t) + MMLIST_HEAD_SIZE * 3 + MM_MIN_SIZE) { return RHINO_MM_POOL_SIZE_ERR; } memset(addr, 0, len); MM_CRITICAL_ENTER(mmhead, flags_cpsr); firstblk = init_mm_region(addr, len); nextblk = MM_GET_NEXT_BLK(firstblk); /* Inserting the area in the list of linked areas */ region = (k_mm_region_info_t *)firstblk->mbinfo.buffer; region->next = mmhead->regioninfo; mmhead->regioninfo = region; #if (RHINO_CONFIG_MM_DEBUG > 0u) nextblk->dye = MM_DYE_USED; nextblk->owner_id = MM_OWNER_ID_SELF; nextblk->trace_id = 0; nextblk->owner = 0; #endif #if (K_MM_STATISTIC > 0) /* keep "used_size" not changed. * change "used_size" here then k_mm_free will decrease it. */ mmhead->used_size += MM_GET_BLK_SIZE(nextblk); #endif MM_CRITICAL_EXIT(mmhead, flags_cpsr); /*mark nextblk as free*/ k_mm_free(mmhead, nextblk->mbinfo.buffer); return RHINO_SUCCESS; } /* insert blk to freelist[level], and set freebitmap */ static void k_mm_freelist_insert(k_mm_head *mmhead, k_mm_list_t *blk) { int32_t level; level = size_to_level(MM_GET_BUF_SIZE(blk)); if (level < 0 || level >= MM_BIT_LEVEL) { return; } blk->mbinfo.free_ptr.prev = NULL; blk->mbinfo.free_ptr.next = mmhead->freelist[level]; if (mmhead->freelist[level] != NULL) { mmhead->freelist[level]->mbinfo.free_ptr.prev = blk; } mmhead->freelist[level] = blk; /* freelist not null, so set the bit */ mmhead->free_bitmap |= (1 << level); } static void k_mm_freelist_delete(k_mm_head *mmhead, k_mm_list_t *blk) { int32_t level; level = size_to_level(MM_GET_BUF_SIZE(blk)); if (level < 0 || level >= MM_BIT_LEVEL) { return; } if (blk->mbinfo.free_ptr.next != NULL) { blk->mbinfo.free_ptr.next->mbinfo.free_ptr.prev = blk->mbinfo.free_ptr.prev; } if (blk->mbinfo.free_ptr.prev != NULL) { blk->mbinfo.free_ptr.prev->mbinfo.free_ptr.next = blk->mbinfo.free_ptr.next; } if (mmhead->freelist[level] == blk) { /* first blk in this freelist */ mmhead->freelist[level] = blk->mbinfo.free_ptr.next; if (mmhead->freelist[level] == NULL) { /* freelist null, so clear the bit */ mmhead->free_bitmap &= (~(1 << level)); } } blk->mbinfo.free_ptr.prev = NULL; blk->mbinfo.free_ptr.next = NULL; } static k_mm_list_t *find_up_level(k_mm_head *mmhead, int32_t level) { uint32_t bitmap; bitmap = mmhead->free_bitmap & (0xfffffffful << (level + 1)); level = krhino_ctz32(bitmap); if (level < MM_BIT_LEVEL) { return mmhead->freelist[level]; } return NULL; } void *k_mm_alloc(k_mm_head *mmhead, size_t size) { void *retptr; k_mm_list_t *get_b, *new_b, *next_b; int32_t level; size_t left_size; size_t req_size = size; cpu_cpsr_t flags_cpsr; if (!mmhead) { return NULL; } if (size == 0) { return NULL; } MM_CRITICAL_ENTER(mmhead, flags_cpsr); #if (RHINO_CONFIG_MM_BLK > 0) /* little blk, try to get from mm_pool */ if (mmhead->fix_pool != NULL && size <= RHINO_CONFIG_MM_BLK_SIZE) { retptr = krhino_mblk_alloc_nolock((mblk_pool_t *)mmhead->fix_pool, size); if (retptr) { MM_CRITICAL_EXIT(mmhead, flags_cpsr); return retptr; } } #endif retptr = NULL; size = MM_ALIGN_UP(size); size = size < MM_MIN_SIZE ? MM_MIN_SIZE : size; if ((level = size_to_level(size)) == -1) { goto ALLOCEXIT; } #if (RHINO_CONFIG_MM_QUICK > 0) /* try to find in higher level */ get_b = find_up_level(mmhead, level); if (get_b == NULL) { /* try to find in same level */ get_b = mmhead->freelist[level]; while (get_b != NULL) { if (MM_GET_BUF_SIZE(get_b) >= size) { break; } get_b = get_b->mbinfo.free_ptr.next; } if (get_b == NULL) { /* do not find availalbe freeblk */ goto ALLOCEXIT; } } #else /* try to find in same level */ get_b = mmhead->freelist[level]; while (get_b != NULL) { if (MM_GET_BUF_SIZE(get_b) >= size) { break; } get_b = get_b->mbinfo.free_ptr.next; } if (get_b == NULL) { /* try to find in higher level */ get_b = find_up_level(mmhead, level); if (get_b == NULL) { /* do not find availalbe freeblk */ goto ALLOCEXIT; } } #endif k_mm_freelist_delete(mmhead, get_b); next_b = MM_GET_NEXT_BLK(get_b); /* Should the block be split? */ if (MM_GET_BUF_SIZE(get_b) >= size + MMLIST_HEAD_SIZE + MM_MIN_SIZE) { left_size = MM_GET_BUF_SIZE(get_b) - size - MMLIST_HEAD_SIZE; get_b->buf_size = size | (get_b->buf_size & MM_PRESTAT_MASK); new_b = MM_GET_NEXT_BLK(get_b); new_b->prev = get_b; new_b->buf_size = left_size | MM_BUFF_FREE | MM_BUFF_PREV_USED; #if (RHINO_CONFIG_MM_DEBUG > 0u) new_b->dye = MM_DYE_FREE; new_b->owner_id = 0; new_b->trace_id = 0; new_b->owner = 0; #endif next_b->prev = new_b; k_mm_freelist_insert(mmhead, new_b); } else { next_b->buf_size &= (~MM_BUFF_PREV_FREE); } get_b->buf_size &= (~MM_BUFF_FREE); /* Now it's used */ #if (RHINO_CONFIG_MM_DEBUG > 0u) get_b->dye = MM_DYE_USED; get_b->owner_id = (uint8_t)debug_task_id_now(); get_b->trace_id = g_mmlk_cnt; get_b->owner = 0; #endif retptr = (void *)get_b->mbinfo.buffer; if (retptr != NULL) { stats_addsize(mmhead, MM_GET_BLK_SIZE(get_b), req_size); } ALLOCEXIT: MM_CRITICAL_EXIT(mmhead, flags_cpsr); return retptr ; } void k_mm_free(k_mm_head *mmhead, void *ptr) { k_mm_list_t *free_b, *next_b, *prev_b; cpu_cpsr_t flags_cpsr; (void)flags_cpsr; if (!ptr || !mmhead) { return; } MM_CRITICAL_ENTER(mmhead, flags_cpsr); #if (RHINO_CONFIG_MM_BLK > 0) if (krhino_mblk_check(mmhead->fix_pool, ptr)) { (void)krhino_mblk_free_nolock((mblk_pool_t *)mmhead->fix_pool, ptr); MM_CRITICAL_EXIT(mmhead, flags_cpsr); return; } #endif free_b = MM_GET_THIS_BLK(ptr); #if (RHINO_CONFIG_MM_DEBUG > 0u) if (free_b->dye == MM_DYE_FREE) { /* step 1 : do not call mm_critical_exit to stop malloc by other core */ //MM_CRITICAL_EXIT(mmhead, flags_cpsr); /* step 2 : freeze other core */ debug_cpu_stop(); /* step 3 :printk(do not use printf, maybe malloc) log */ printk("WARNING, memory maybe double free!! 0x%x\r\n", (unsigned int)free_b); /* setp 4 :dumpsys memory and then go to fatal error */ kmm_error(KMM_ERROR_LOCKED); } if (free_b->dye != MM_DYE_USED) { //MM_CRITICAL_EXIT(mmhead, flags_cpsr); debug_cpu_stop(); printk("WARNING, memory maybe corrupt!! 0x%x\r\n", (unsigned int)free_b); kmm_error(KMM_ERROR_LOCKED); } free_b->dye = MM_DYE_FREE; free_b->owner_id = 0; free_b->trace_id = 0; free_b->owner = 0; #endif free_b->buf_size |= MM_BUFF_FREE; stats_removesize(mmhead, MM_GET_BLK_SIZE(free_b)); /* if the blk after this freed one is freed too, merge them */ next_b = MM_GET_NEXT_BLK(free_b); #if (RHINO_CONFIG_MM_DEBUG > 0u) if (next_b->dye != MM_DYE_FREE && next_b->dye != MM_DYE_USED) { //MM_CRITICAL_EXIT(mmhead, flags_cpsr); debug_cpu_stop(); printk("WARNING, memory overwritten!! 0x%x 0x%x\r\n", (unsigned int)free_b, (unsigned int)next_b); kmm_error(KMM_ERROR_LOCKED); } else if (MM_LAST_BLK_MAGIC != next_b->owner) { k_mm_list_t *nnext_b = MM_GET_NEXT_BLK(next_b); if (nnext_b->dye != MM_DYE_FREE && nnext_b->dye != MM_DYE_USED) { debug_cpu_stop(); printk("WARNING, nnext memory overwritten!! 0x%x 0x%x 0x%x\r\n", (unsigned int)free_b, (unsigned int)next_b, (unsigned int)nnext_b); kmm_error(KMM_ERROR_LOCKED); } } #endif if (next_b->buf_size & MM_BUFF_FREE) { k_mm_freelist_delete(mmhead, next_b); free_b->buf_size += MM_GET_BLK_SIZE(next_b); } /* if the blk before this freed one is freed too, merge them */ if (free_b->buf_size & MM_BUFF_PREV_FREE) { prev_b = free_b->prev; k_mm_freelist_delete(mmhead, prev_b); prev_b->buf_size += MM_GET_BLK_SIZE(free_b); free_b = prev_b; } /* after merge, free to list */ k_mm_freelist_insert(mmhead, free_b); next_b = MM_GET_NEXT_BLK(free_b); next_b->prev = free_b; next_b->buf_size |= MM_BUFF_PREV_FREE; MM_CRITICAL_EXIT(mmhead, flags_cpsr); } void *k_mm_realloc(k_mm_head *mmhead, void *oldmem, size_t new_size) { void *ptr_aux = NULL; uint32_t cpsize; k_mm_list_t *this_b, *split_b, *next_b; size_t old_size, split_size; size_t req_size = 0; cpu_cpsr_t flags_cpsr; (void)flags_cpsr; (void)req_size; if (oldmem == NULL) { if (new_size > 0) { return (void *)k_mm_alloc(mmhead, new_size); } else { return NULL; } } else if (new_size == 0) { k_mm_free(mmhead, oldmem); return NULL; } req_size = new_size; #if (RHINO_CONFIG_MM_BLK > 0) if (krhino_mblk_check(mmhead->fix_pool, oldmem)) { ptr_aux = k_mm_alloc(mmhead, new_size); if (ptr_aux) { int cp_len = krhino_mblk_get_size(mmhead->fix_pool, oldmem); cp_len = cp_len > new_size ? new_size : cp_len; memcpy(ptr_aux, oldmem, cp_len); MM_CRITICAL_ENTER(mmhead, flags_cpsr); (void)krhino_mblk_free_nolock((mblk_pool_t *)mmhead->fix_pool, oldmem); MM_CRITICAL_EXIT(mmhead, flags_cpsr); } return ptr_aux; } #endif MM_CRITICAL_ENTER(mmhead, flags_cpsr); this_b = MM_GET_THIS_BLK(oldmem); old_size = MM_GET_BUF_SIZE(this_b); next_b = MM_GET_NEXT_BLK(this_b); new_size = MM_ALIGN_UP(new_size); new_size = new_size < MM_MIN_SIZE ? MM_MIN_SIZE : new_size; if (new_size <= old_size) { /* shrink blk */ stats_removesize(mmhead, MM_GET_BLK_SIZE(this_b)); if (next_b->buf_size & MM_BUFF_FREE) { /* merge next free */ k_mm_freelist_delete(mmhead, next_b); old_size += MM_GET_BLK_SIZE(next_b); next_b = MM_GET_NEXT_BLK(next_b); } if (old_size >= new_size + MMLIST_HEAD_SIZE + MM_MIN_SIZE) { /* split blk */ split_size = old_size - new_size - MMLIST_HEAD_SIZE; this_b->buf_size = new_size | (this_b->buf_size & MM_PRESTAT_MASK); split_b = MM_GET_NEXT_BLK(this_b); split_b->prev = this_b; split_b->buf_size = split_size | MM_BUFF_FREE | MM_BUFF_PREV_USED; #if (RHINO_CONFIG_MM_DEBUG > 0u) split_b->dye = MM_DYE_FREE; split_b->owner_id = 0; split_b->trace_id = 0; split_b->owner = 0; #endif next_b->prev = split_b; next_b->buf_size |= MM_BUFF_PREV_FREE; k_mm_freelist_insert(mmhead, split_b); } stats_addsize(mmhead, MM_GET_BLK_SIZE(this_b), req_size); ptr_aux = (void *)this_b->mbinfo.buffer; } else if ((next_b->buf_size & MM_BUFF_FREE)) { /* enlarge blk */ if (new_size <= (old_size + MM_GET_BLK_SIZE(next_b))) { stats_removesize(mmhead, MM_GET_BLK_SIZE(this_b)); /* delete next blk from freelist */ k_mm_freelist_delete(mmhead, next_b); /* enlarge this blk */ this_b->buf_size += MM_GET_BLK_SIZE(next_b); next_b = MM_GET_NEXT_BLK(this_b); next_b->prev = this_b; next_b->buf_size &= ~MM_BUFF_PREV_FREE; if (MM_GET_BUF_SIZE(this_b) >= new_size + MMLIST_HEAD_SIZE + MM_MIN_SIZE) { /* split blk */ split_size = MM_GET_BUF_SIZE(this_b) - new_size - MMLIST_HEAD_SIZE; this_b->buf_size = new_size | (this_b->buf_size & MM_PRESTAT_MASK); split_b = MM_GET_NEXT_BLK(this_b); split_b->prev = this_b; split_b->buf_size = split_size | MM_BUFF_FREE | MM_BUFF_PREV_USED; #if (RHINO_CONFIG_MM_DEBUG > 0u) split_b->dye = MM_DYE_FREE; split_b->owner_id = 0; split_b->trace_id = 0; split_b->owner = 0; #endif next_b->prev = split_b; next_b->buf_size |= MM_BUFF_PREV_FREE; k_mm_freelist_insert(mmhead, split_b); } stats_addsize(mmhead, MM_GET_BLK_SIZE(this_b), req_size); ptr_aux = (void *)this_b->mbinfo.buffer; } } if (ptr_aux) { #if (RHINO_CONFIG_MM_DEBUG > 0u) this_b->dye = MM_DYE_USED; this_b->owner_id = (uint8_t)debug_task_id_now(); this_b->trace_id = g_mmlk_cnt; #endif MM_CRITICAL_EXIT(mmhead, flags_cpsr); return ptr_aux; } MM_CRITICAL_EXIT(mmhead, flags_cpsr); /* re alloc blk */ ptr_aux = k_mm_alloc(mmhead, new_size); if (!ptr_aux) { return NULL; } cpsize = (MM_GET_BUF_SIZE(this_b) > new_size) ? new_size : MM_GET_BUF_SIZE(this_b); memcpy(ptr_aux, oldmem, cpsize); k_mm_free(mmhead, oldmem); return ptr_aux; } #if (RHINO_CONFIG_MM_DEBUG > 0u) void krhino_owner_attach(void *addr, size_t allocator) { k_mm_list_t *blk; char *PC; int *SP; __asm__ volatile("mov %0, sp\n" : "=r"(SP)); __asm__ volatile("mov %0, pc\n" : "=r"(PC)); if (NULL == addr) { return; } #if (RHINO_CONFIG_MM_BLK > 0) /* fix blk, do not support debug info */ if (krhino_mblk_check(g_kmm_head->fix_pool, addr)) { return; } #endif blk = MM_GET_THIS_BLK(addr); #if (RHINO_CONFIG_MM_TRACE_LVL > 0) if ((g_sys_stat == RHINO_RUNNING) && (kmm_bt_check() == 0)) { backtrace_now_get((void **) blk->trace, RHINO_CONFIG_MM_TRACE_LVL, 2); } else { memset(blk->trace, 0, sizeof(blk->trace)); } #endif blk->owner = allocator; } #endif void *krhino_mm_alloc(size_t size) { void *tmp; #if (RHINO_CONFIG_MM_DEBUG > 0u) uint32_t app_malloc = size & AOS_UNSIGNED_INT_MSB; size = size & (~AOS_UNSIGNED_INT_MSB); #endif if (size == 0) { printf("WARNING, malloc size = 0\r\n"); return NULL; } tmp = k_mm_alloc(g_kmm_head, size); if (tmp == NULL) { #if (RHINO_CONFIG_MM_DEBUG > 0) static int32_t dumped; int32_t freesize; freesize = g_kmm_head->free_size; printf("WARNING, malloc failed!!!! need size:%d, but free size:%d\r\n", size, freesize); if (dumped) { return tmp; } dumped = 1; debug_cpu_stop(); kmm_error(KMM_ERROR_UNLOCKED); #endif } #if (RHINO_CONFIG_USER_HOOK > 0) krhino_mm_alloc_hook(tmp, size); #endif #if (RHINO_CONFIG_MM_DEBUG > 0u) if (app_malloc == 0) { krhino_owner_return_addr(tmp); } #endif return tmp; } void krhino_mm_free(void *ptr) { k_mm_free(g_kmm_head, ptr); } void *krhino_mm_realloc(void *oldmem, size_t newsize) { void *tmp; #if (RHINO_CONFIG_MM_DEBUG > 0u) uint32_t app_malloc = newsize & AOS_UNSIGNED_INT_MSB; newsize = newsize & (~AOS_UNSIGNED_INT_MSB); #endif tmp = k_mm_realloc(g_kmm_head, oldmem, newsize); #if (RHINO_CONFIG_MM_DEBUG > 0u) if (app_malloc == 0) { krhino_owner_return_addr(tmp); } #endif if (tmp == NULL && newsize != 0) { #if (RHINO_CONFIG_MM_DEBUG > 0) static int32_t reallocdumped; printf("WARNING, realloc failed!!!! newsize : %d\r\n", newsize); if (reallocdumped) { return tmp; } reallocdumped = 1; debug_cpu_stop(); kmm_error(KMM_ERROR_UNLOCKED); #endif } return tmp; } size_t krhino_mm_max_free_size_get(void) { int32_t index; k_mm_list_t *max, *tmp; size_t max_free_block_size = 0; /* In order to avoid getting stuck after the exception, the critical zone protection is removed. Currently, this interface can only be invoked in exception handling. */ //cpu_cpsr_t flags_cpsr; //MM_CRITICAL_ENTER(g_kmm_head,flags_cpsr); index = krhino_clz32(g_kmm_head->free_bitmap); if (index > 31) { return 0; } max = g_kmm_head->freelist[31 - index]; while (max) { if (max_free_block_size < MM_GET_BUF_SIZE(max)) { max_free_block_size = MM_GET_BUF_SIZE(max); } tmp = max->mbinfo.free_ptr.next; max = tmp; } return max_free_block_size; } #endif
YifuLiu/AliOS-Things
kernel/rhino/k_mm.c
C
apache-2.0
24,550
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "k_api.h" kstat_t krhino_mblk_pool_init(mblk_pool_t *pool, const name_t *name, void *pool_start, size_t pool_size) { uint32_t blk_type; /* max blocks mem pool offers */ uint8_t align_mask; /* address alignment */ mblk_list_t *blk_list; NULL_PARA_CHK(pool); NULL_PARA_CHK(name); NULL_PARA_CHK(pool_start); memset(pool_start, 0, pool_size); /* check address & size alignment */ align_mask = sizeof(uintptr_t) - 1u; if (((size_t)pool_start & align_mask) || (pool_size & align_mask)) { return RHINO_INV_ALIGN; } if (pool_size % MM_BLK_SLICE_SIZE) { return RHINO_MM_POOL_SIZE_ERR; } krhino_spin_lock_init(&pool->blk_lock); pool->pool_name = name; pool->pool_start = (uintptr_t)pool_start; pool->pool_end = (uintptr_t)(pool_start + pool_size); pool->slice_cnt = 0; memset(pool->slice_type, 0, sizeof(pool->slice_type)); for (blk_type = 0 ; blk_type < MM_BLK_SLICE_BIT ; blk_type++) { blk_list = &pool->blk_list[blk_type]; memset(blk_list, 0, sizeof(*blk_list)); blk_list->blk_size = MM_BLK_TYPE2SIZE(blk_type); } TRACE_MBLK_POOL_CREATE(krhino_cur_task_get(), pool); return RHINO_SUCCESS; } void *krhino_mblk_alloc_nolock(mblk_pool_t *pool, uint32_t size) { uint32_t blk_type; mblk_list_t *blk_list = NULL; uintptr_t avail_blk = (uintptr_t)NULL; if (pool == NULL) { return NULL; } size = size < sizeof(uintptr_t) ? sizeof(uintptr_t) : size; blk_type = MM_BLK_SIZE2TYPE(size); while (blk_type < MM_BLK_SLICE_BIT) { blk_list = &(pool->blk_list[blk_type]); /* try to get from freelist */ if ((avail_blk = blk_list->free_head) != (uintptr_t)NULL) { blk_list->free_head = *(uintptr_t *)avail_blk; blk_list->freelist_cnt--; break; } /* check if need new slice */ if (blk_list->slice_addr == 0 || blk_list->slice_offset == MM_BLK_SLICE_SIZE) { if (pool->slice_cnt == MM_BLK_SLICE_NUM) { blk_type++; continue; } /* get new slice for this type blks */ blk_list->slice_addr = pool->pool_start + pool->slice_cnt * MM_BLK_SLICE_SIZE; pool->slice_type[pool->slice_cnt] = blk_type; blk_list->slice_offset = 0; pool->slice_cnt++; blk_list->slice_cnt++; } /* cut blk from slice */ avail_blk = blk_list->slice_addr + blk_list->slice_offset; blk_list->slice_offset += blk_list->blk_size; break; }; if (blk_list) { (avail_blk == (uintptr_t)0) ? blk_list->fail_cnt++ : blk_list->nofree_cnt++; } return (void *)avail_blk; } kstat_t krhino_mblk_free_nolock(mblk_pool_t *pool, void *blk) { uint32_t slice_idx; uint32_t blk_type; mblk_list_t *blk_list; NULL_PARA_CHK(pool); NULL_PARA_CHK(blk); slice_idx = ((uintptr_t)blk - pool->pool_start) >> MM_BLK_SLICE_BIT; if (slice_idx >= MM_BLK_SLICE_NUM) { return RHINO_MM_FREE_ADDR_ERR; } blk_type = pool->slice_type[slice_idx]; if (blk_type >= MM_BLK_SLICE_BIT) { return RHINO_MM_FREE_ADDR_ERR; } blk_list = &(pool->blk_list[blk_type]); /* use the first 4 byte of the free block point to head of free list */ *((uintptr_t *)blk) = blk_list->free_head; blk_list->free_head = (uintptr_t)blk; blk_list->nofree_cnt--; blk_list->freelist_cnt++; return RHINO_SUCCESS; } kstat_t krhino_mblk_info_nolock(mblk_pool_t *pool, mblk_info_t *info) { size_t blk_size = 0; uint32_t idx; mblk_list_t *blk_list; uint32_t size_in_list = 0; uint32_t size_in_slice = 0; NULL_PARA_CHK(pool); NULL_PARA_CHK(info); /* no data changed, no lock needed. The info may be not absolutely precise */ for (idx = 0 ; idx < MM_BLK_SLICE_BIT ; idx++) { blk_list = &(pool->blk_list[idx]); size_in_list += blk_list->nofree_cnt * blk_list->blk_size; if (blk_list->slice_cnt > 0) { size_in_slice += (blk_list->slice_cnt - 1) * MM_BLK_SLICE_SIZE + blk_list->slice_offset; blk_size = blk_list->blk_size; } } info->pool_name = pool->pool_name; info->pool_size = pool->pool_end - pool->pool_start; info->used_size = size_in_list; info->max_used_size = size_in_slice; info->max_blk_size = blk_size; return RHINO_SUCCESS; } void *krhino_mblk_alloc(mblk_pool_t *pool, uint32_t size) { uintptr_t avail_blk; cpu_cpsr_t flags_cpsr; if (pool == NULL) { return NULL; } krhino_spin_lock_irq_save(&pool->blk_lock, flags_cpsr); avail_blk = (uintptr_t)krhino_mblk_alloc_nolock(pool, size); krhino_spin_unlock_irq_restore(&pool->blk_lock, flags_cpsr); return (void *)avail_blk; } kstat_t krhino_mblk_free(mblk_pool_t *pool, void *blk) { kstat_t ret; cpu_cpsr_t flags_cpsr; NULL_PARA_CHK(pool); NULL_PARA_CHK(blk); krhino_spin_lock_irq_save(&pool->blk_lock, flags_cpsr); ret = krhino_mblk_free_nolock(pool, blk); krhino_spin_unlock_irq_restore(&pool->blk_lock, flags_cpsr); return ret; } kstat_t krhino_mblk_info(mblk_pool_t *pool, mblk_info_t *info) { kstat_t ret; cpu_cpsr_t flags_cpsr; NULL_PARA_CHK(pool); NULL_PARA_CHK(info); krhino_spin_lock_irq_save(&pool->blk_lock, flags_cpsr); ret = krhino_mblk_info_nolock(pool, info); krhino_spin_unlock_irq_restore(&pool->blk_lock, flags_cpsr); return ret; }
YifuLiu/AliOS-Things
kernel/rhino/k_mm_blk.c
C
apache-2.0
5,726
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdio.h> #include "k_api.h" #if AOS_COMP_DEBUG #include "aos/debug.h" #endif #define KMM_CRITICAL_ENTER(head, cpsr) MM_CRITICAL_ENTER(head, cpsr) #define KMM_CRITICAL_EXIT(head, cpsr) MM_CRITICAL_EXIT(head, cpsr) typedef int (*KMM_PRINT)(const char *fmt, ...); KMM_PRINT print = printf; #if (RHINO_CONFIG_MM_DEBUG > 0) uint8_t g_mmlk_cnt; #define MM_CHK 0xff #if (RHINO_CONFIG_MM_TLF > 0) void print_block(k_mm_list_t *b) { if (!b) { return; } print("%p ", (void *)b); if (b->buf_size & MM_BUFF_FREE) { if (b->dye != MM_DYE_FREE) { print("!"); } else { print(" "); } print("free "); } else { if (b->dye != MM_DYE_USED) { print("!"); } else { print(" "); } print("used "); } if (MM_GET_BUF_SIZE(b)) { print(" %6lu ", (unsigned long)MM_GET_BUF_SIZE(b)); } else { print(" sentinel "); } if (b->buf_size & MM_BUFF_FREE) { if (b->dye != MM_DYE_FREE) { print(" %8x ", b->dye); } else { print(" OK "); } } else { if (b->dye != MM_DYE_USED) { print(" %8x ", b->dye); } else { print(" OK "); } } print(" 0x%-8x ", b->owner); #if (RHINO_CONFIG_MM_TRACE_LVL > 0) /* If double free, print last alloc trace maybe useful. This info is not useful if this mem alloc-and-freed by another module between. */ //if ((b->buf_size & MM_BUFF_FREE) == 0) { int idx; print(" (%p", b->trace[0]); for (idx = 1 ; idx < RHINO_CONFIG_MM_TRACE_LVL ; idx++) { print(" <- %p", b->trace[idx]); } print(")"); } #endif print("\r\n"); } void check_block(k_mm_list_t *b) { if (!b) { return; } if (b->buf_size & MM_BUFF_FREE) { if (b->dye != MM_DYE_FREE) { print("%p ", (void *)b); } } else { if (b->dye != MM_DYE_USED) { print("%p ", (void *)b); } } } void dump_kmm_free_map(k_mm_head *mmhead) { int i; k_mm_list_t *next; k_mm_list_t *tmp; if (!mmhead) { return; } print("freelist bitmap: 0x%x\r\n", (unsigned)mmhead->free_bitmap); print(" Address Stat Len Chk Caller\r\n"); for (i = 0; i < MM_BIT_LEVEL; i++) { next = mmhead->freelist[i]; while (next) { print_block(next); tmp = next->mbinfo.free_ptr.next; next = tmp; } } } void dump_kmm_map(k_mm_head *mmhead) { k_mm_region_info_t *reginfo, *nextreg; k_mm_list_t *next, *cur; if (!mmhead) { return; } print("ALL BLOCKS\r\n"); print("Blk_Addr Stat Len Chk Caller Point\r\n"); reginfo = mmhead->regioninfo; while (reginfo) { cur = MM_GET_THIS_BLK(reginfo); while (cur) { print_block(cur); if (MM_GET_BUF_SIZE(cur)) { next = MM_GET_NEXT_BLK(cur); } else { next = NULL; } cur = next; } nextreg = reginfo->next; reginfo = nextreg; } } void dump_kmm_statistic_info(k_mm_head *mmhead) { #if (K_MM_STATISTIC > 0) int i; #endif if (!mmhead) { return; } #if (K_MM_STATISTIC > 0) for (i = 0; i < MM_BIT_LEVEL; i++) { if (i % 4 == 0 && i != 0) { print("\r\n"); } print("[2^%02d] bytes: %5d |", (i + MM_MIN_BIT), mmhead->alloc_times[i]); } print("\r\n"); #endif } #if (RHINO_CONFIG_MM_BLK > 0) void dump_kmm_mblk_info(k_mm_head *mmhead) { uint32_t idx; uint32_t slice = 0; mblk_list_t *blk_list; mblk_pool_t *mm_pool; size_t UsedSize = 0; size_t FreeSize = 0; size_t MaxUsedSz = 0; size_t AllocFail = 0; print( "---------------------------------------------------------------------------\r\n"); print( "[POOL]| BlkSize | UsedSize | FreeSize | MaxUsedSz | AllocFail |\r\n"); mm_pool = mmhead->fix_pool; if (mm_pool != NULL) { for (idx = 0 ; idx < MM_BLK_SLICE_BIT ; idx++) { blk_list = &(mm_pool->blk_list[idx]); if (blk_list->slice_cnt > 0) { print(" | %-10d | %-10d | %-10d | %-10d | %-10d |\r\n", blk_list->blk_size, \ (int)blk_list->nofree_cnt * blk_list->blk_size, (int)blk_list->freelist_cnt * blk_list->blk_size, (blk_list->slice_cnt - 1)*MM_BLK_SLICE_SIZE + blk_list->slice_offset, (int)blk_list->fail_cnt); UsedSize += blk_list->nofree_cnt * blk_list->blk_size; FreeSize += blk_list->freelist_cnt * blk_list->blk_size; MaxUsedSz += (blk_list->slice_cnt - 1) * MM_BLK_SLICE_SIZE + blk_list->slice_offset; AllocFail += blk_list->fail_cnt; slice += blk_list->slice_cnt; } } print("Total | | %-10d | %-10d | %-10d | %-10d |\r\n", UsedSize, FreeSize, MaxUsedSz, AllocFail); print("Pool Size %d, Free Slice size %p.\r\n", mm_pool->pool_end - mm_pool->pool_start, (intptr_t)(mm_pool->pool_end - mm_pool->pool_start - mm_pool->slice_cnt * MM_BLK_SLICE_SIZE)); } print( "---------------------------------------------------------------------------\r\n"); } #endif #if (RHINO_CONFIG_KOBJ_LIST > 0) void dump_kmm_task_info(k_mm_head *mmhead) { k_mm_region_info_t *reginfo; k_mm_list_t *next, *cur; ktask_t *task_owner; uint32_t isr_alloc_size = 0; uint32_t unk_alloc_size = 0; uint32_t buff_size; klist_t *listnode; ktask_t *task; if (!mmhead) { return; } reginfo = mmhead->regioninfo; while (reginfo) { cur = MM_GET_THIS_BLK(reginfo); while (cur) { buff_size = MM_GET_BUF_SIZE(cur); if (cur->dye == MM_DYE_USED) { if (cur->owner_id == 0) { isr_alloc_size += buff_size; } else if (cur->owner_id != MM_OWNER_ID_SELF) { task_owner = debug_task_find_by_id(cur->owner_id); if (task_owner != NULL) { task_owner->task_alloc_size += buff_size; } else { unk_alloc_size += buff_size; } } } if (buff_size) { next = MM_GET_NEXT_BLK(cur); } else { next = NULL; } cur = next; } reginfo = reginfo->next; } print("TaskName Prio StackSize HeapAllocSize\r\n"); /* Traversing all task */ for (listnode = g_kobj_list.task_head.next; listnode != &g_kobj_list.task_head; listnode = listnode->next) { task = krhino_list_entry(listnode, ktask_t, task_stats_item); if (task->task_alloc_size != 0) { print("%-24s %-5d %-10d %-10d\r\n", task->task_name, task->prio, (int)task->stack_size, (int)task->task_alloc_size); task->task_alloc_size = 0; } } #if (RHINO_CONFIG_MM_BLK > 0) isr_alloc_size -= (RHINO_CONFIG_MM_TLF_BLK_SIZE + MM_ALIGN_UP(sizeof(mblk_pool_t))); #endif print("Allocated in ISR %d, Allocated by deleted task %d\r\n", (int)isr_alloc_size, (int)unk_alloc_size); } #else void dump_kmm_task_info(k_mm_head *mmhead) { print("need config RHINO_CONFIG_KOBJ_LIST > 0\r\n"); } #endif uint32_t dumpsys_mm_info_func(uint32_t mm_status) { cpu_cpsr_t flags_cpsr = 0; if (mm_status != KMM_ERROR_LOCKED) { KMM_CRITICAL_ENTER(g_kmm_head, flags_cpsr); } print = printk; print("\r\n"); print("------------------------------- all memory blocks --------------------------------- \r\n"); print("g_kmm_head = %8x\r\n", (unsigned int)g_kmm_head); dump_kmm_map(g_kmm_head); print("\r\n"); print("----------------------------- all free memory blocks ------------------------------ \r\n"); dump_kmm_free_map(g_kmm_head); print("\r\n"); print("--------------------------- memory allocation statistic --------------------------- \r\n"); dump_kmm_statistic_info(g_kmm_head); print("\r\n"); print("-------------------------------[kernel] heap size overview -------------------------------- \r\n"); debug_mm_overview(print); #if (RHINO_CONFIG_MM_BLK > 0) print("\r\n"); print("--------------------------- mmblk allocation statistic ---------------------------- \r\n"); dump_kmm_mblk_info(g_kmm_head); #endif print("\r\n"); print("--------------------------- task allocation statistic ----------------------------- \r\n"); dump_kmm_task_info(g_kmm_head); print("\r\n"); print("----------------------------------------------------------------------------------- \r\n"); print = printf; if (mm_status != KMM_ERROR_LOCKED) { KMM_CRITICAL_EXIT(g_kmm_head, flags_cpsr); } return RHINO_SUCCESS; } uint32_t dumpsys_mm_overview_func(uint32_t len) { cpu_cpsr_t flags_cpsr = 0; KMM_CRITICAL_ENTER(g_kmm_head, flags_cpsr); print = printk; print("\r\n"); print("-------------------------------[kernel] heap size overview -------------------------------- \r\n"); debug_mm_overview(print); #if (RHINO_CONFIG_MM_BLK > 0) print("\r\n"); print("--------------------------- mmblk allocation statistic ---------------------------- \r\n"); dump_kmm_mblk_info(g_kmm_head); #endif print("\r\n"); print("--------------------------- task allocation statistic ----------------------------- \r\n"); dump_kmm_task_info(g_kmm_head); print = printf; KMM_CRITICAL_EXIT(g_kmm_head, flags_cpsr); print("\r\n"); print("----------------------------------------------------------------------------------- \r\n"); return RHINO_SUCCESS; } void dump_kmm_chk(k_mm_head *mmhead, uint8_t care_cnt) { k_mm_region_info_t *reginfo, *nextreg; k_mm_list_t *next, *cur; if (!mmhead || care_cnt == 0) { return; } reginfo = mmhead->regioninfo; while (reginfo) { cur = MM_GET_THIS_BLK(reginfo); while (cur) { if (cur->trace_id == care_cnt) { print_block(cur); } else if (care_cnt == MM_CHK) { check_block(cur); } if (MM_GET_BUF_SIZE(cur)) { next = MM_GET_NEXT_BLK(cur); } else { next = NULL; } cur = next; } nextreg = reginfo->next; reginfo = nextreg; } } uint32_t dumpsys_mm_leakcheck(uint32_t call_cnt, int32_t query_index) { cpu_cpsr_t flags_cpsr = 0; KMM_CRITICAL_ENTER(g_kmm_head, flags_cpsr); print = printk; if (query_index < 0) { query_index = g_mmlk_cnt; g_mmlk_cnt = (uint8_t)call_cnt; } else if (query_index > g_mmlk_cnt) { print("query_index should be less than %d\r\n", g_mmlk_cnt); return -1; } print("-----------------All new alloced blocks:----------------\r\n"); print("Blk_Addr Stat Len Chk Caller Point\r\n"); dump_kmm_chk(g_kmm_head, query_index); print("--------------New alloced blocks info ends.-------------\r\n"); print("\r\n"); print = printf; KMM_CRITICAL_EXIT(g_kmm_head, flags_cpsr); return RHINO_SUCCESS; } void dumpsys_mm_header_check(void) { cpu_cpsr_t flags_cpsr = 0; print("-----------------All error blocks:----------------\r\n"); KMM_CRITICAL_ENTER(g_kmm_head, flags_cpsr); dump_kmm_chk(g_kmm_head, MM_CHK); KMM_CRITICAL_EXIT(g_kmm_head, flags_cpsr); print("\r\n"); } #endif /* #if (RHINO_CONFIG_MM_TLF > 0) */ #endif /* #if (RHINO_CONFIG_MM_DEBUG > 0) */
YifuLiu/AliOS-Things
kernel/rhino/k_mm_debug.c
C
apache-2.0
12,130
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "k_api.h" kstat_t mutex_create(kmutex_t *mutex, const name_t *name, uint8_t mm_alloc_flag) { #if (RHINO_CONFIG_KOBJ_LIST > 0) CPSR_ALLOC(); #endif NULL_PARA_CHK(mutex); NULL_PARA_CHK(name); memset(mutex, 0, sizeof(kmutex_t)); /* init the list */ klist_init(&mutex->blk_obj.blk_list); mutex->blk_obj.blk_policy = BLK_POLICY_PRI; mutex->blk_obj.name = name; mutex->mutex_task = NULL; mutex->mutex_list = NULL; mutex->mm_alloc_flag = mm_alloc_flag; #if (RHINO_CONFIG_TASK_DEL > 0) mutex->blk_obj.cancel = 0u; #endif #if (RHINO_CONFIG_KOBJ_LIST > 0) RHINO_CRITICAL_ENTER(); klist_insert(&(g_kobj_list.mutex_head), &mutex->mutex_item); RHINO_CRITICAL_EXIT(); #endif mutex->blk_obj.obj_type = RHINO_MUTEX_OBJ_TYPE; TRACE_MUTEX_CREATE(krhino_cur_task_get(), mutex, name); return RHINO_SUCCESS; } kstat_t krhino_mutex_create(kmutex_t *mutex, const name_t *name) { return mutex_create(mutex, name, K_OBJ_STATIC_ALLOC); } static void mutex_release(ktask_t *task, kmutex_t *mutex_rel) { uint8_t new_pri; /* find suitable task prio */ new_pri = mutex_pri_look(task, mutex_rel); if (new_pri != task->prio) { /* change prio */ task_pri_change(task, new_pri); TRACE_MUTEX_RELEASE(g_active_task[cpu_cur_get()], task, new_pri); } } kstat_t krhino_mutex_del(kmutex_t *mutex) { CPSR_ALLOC(); klist_t *blk_list_head; if (mutex == NULL) { return RHINO_NULL_PTR; } NULL_PARA_CHK(mutex); RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); if (mutex->blk_obj.obj_type != RHINO_MUTEX_OBJ_TYPE) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_TYPE_ERR; } if (mutex->mm_alloc_flag != K_OBJ_STATIC_ALLOC) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_DEL_ERR; } blk_list_head = &mutex->blk_obj.blk_list; mutex->blk_obj.obj_type = RHINO_OBJ_TYPE_NONE; if (mutex->mutex_task != NULL) { mutex_release(mutex->mutex_task, mutex); } /* all task blocked on this mutex is waken up */ while (!is_klist_empty(blk_list_head)) { pend_task_rm(krhino_list_entry(blk_list_head->next, ktask_t, task_list)); } #if (RHINO_CONFIG_KOBJ_LIST > 0) klist_rm(&mutex->mutex_item); #endif TRACE_MUTEX_DEL(g_active_task[cpu_cur_get()], mutex); RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) kstat_t krhino_mutex_dyn_create(kmutex_t **mutex, const name_t *name) { kstat_t stat; kmutex_t *mutex_obj; if (mutex == NULL) { return RHINO_NULL_PTR; } NULL_PARA_CHK(mutex); mutex_obj = krhino_mm_alloc(sizeof(kmutex_t)); if (mutex_obj == NULL) { return RHINO_NO_MEM; } stat = mutex_create(mutex_obj, name, K_OBJ_DYN_ALLOC); if (stat != RHINO_SUCCESS) { krhino_mm_free(mutex_obj); return stat; } *mutex = mutex_obj; return stat; } kstat_t krhino_mutex_dyn_del(kmutex_t *mutex) { CPSR_ALLOC(); klist_t *blk_list_head; if (mutex == NULL) { return RHINO_NULL_PTR; } NULL_PARA_CHK(mutex); RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); if (mutex->blk_obj.obj_type != RHINO_MUTEX_OBJ_TYPE) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_TYPE_ERR; } if (mutex->mm_alloc_flag != K_OBJ_DYN_ALLOC) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_DEL_ERR; } blk_list_head = &mutex->blk_obj.blk_list; mutex->blk_obj.obj_type = RHINO_OBJ_TYPE_NONE; if (mutex->mutex_task != NULL) { mutex_release(mutex->mutex_task, mutex); } /* all task blocked on this mutex is waken up */ while (!is_klist_empty(blk_list_head)) { pend_task_rm(krhino_list_entry(blk_list_head->next, ktask_t, task_list)); } #if (RHINO_CONFIG_KOBJ_LIST > 0) klist_rm(&mutex->mutex_item); #endif TRACE_MUTEX_DEL(g_active_task[cpu_cur_get()], mutex); RHINO_CRITICAL_EXIT_SCHED(); krhino_mm_free(mutex); return RHINO_SUCCESS; } #endif uint8_t mutex_pri_limit(ktask_t *task, uint8_t pri) { #if (RHINO_CONFIG_MUTEX_INHERIT > 0) kmutex_t *mutex_tmp; uint8_t high_pri; ktask_t *first_blk_task; klist_t *blk_list_head; high_pri = pri; for (mutex_tmp = task->mutex_list; mutex_tmp != NULL; mutex_tmp = mutex_tmp->mutex_list) { blk_list_head = &mutex_tmp->blk_obj.blk_list; if (!is_klist_empty(blk_list_head)) { first_blk_task = krhino_list_entry(blk_list_head->next, ktask_t, task_list); pri = first_blk_task->prio; } /* can not set lower prio than the highest prio in all mutexes which hold lock */ if (pri < high_pri) { high_pri = pri; } } return high_pri; #else return pri; #endif } uint8_t mutex_pri_look(ktask_t *task, kmutex_t *mutex_rel) { #if (RHINO_CONFIG_MUTEX_INHERIT > 0) kmutex_t *mutex_tmp; kmutex_t **prev; uint8_t new_pri; uint8_t pri; ktask_t *first_blk_task; klist_t *blk_list_head; /* the base prio of task */ new_pri = task->b_prio; /* the highest prio in mutex which is locked */ pri = new_pri; prev = &task->mutex_list; while ((mutex_tmp = *prev) != NULL) { if (mutex_tmp == mutex_rel) { /* delete itself from list and make task->mutex_list point to next */ *prev = mutex_tmp->mutex_list; continue; } blk_list_head = &mutex_tmp->blk_obj.blk_list; if (!is_klist_empty(blk_list_head)) { first_blk_task = krhino_list_entry(blk_list_head->next, ktask_t, task_list); pri = first_blk_task->prio; } if (new_pri > pri) { new_pri = pri; } prev = &mutex_tmp->mutex_list; } return new_pri; #else return task->b_prio; #endif } void mutex_task_pri_reset(ktask_t *task) { #if (RHINO_CONFIG_MUTEX_INHERIT > 0) kmutex_t *mutex_tmp; ktask_t *mutex_task; if (task->blk_obj->obj_type == RHINO_MUTEX_OBJ_TYPE) { mutex_tmp = (kmutex_t *)(task->blk_obj); mutex_task = mutex_tmp->mutex_task; /* the new highest prio task blocked on this mutex may decrease prio than before so reset the mutex task prio */ if (mutex_task->prio == task->prio) { mutex_release(mutex_task, NULL); } } #endif } kstat_t krhino_mutex_lock(kmutex_t *mutex, tick_t ticks) { CPSR_ALLOC(); kstat_t ret; ktask_t *mutex_task; uint8_t cur_cpu_num; NULL_PARA_CHK(mutex); if (g_sys_stat == RHINO_STOPPED) { return RHINO_SUCCESS; } RHINO_CRITICAL_ENTER(); cur_cpu_num = cpu_cur_get(); TASK_CANCEL_CHK(mutex); INTRPT_NESTED_LEVEL_CHK(); if (mutex->blk_obj.obj_type != RHINO_MUTEX_OBJ_TYPE) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_TYPE_ERR; } /* if the same task get the same mutex again, it causes mutex owner nested */ if (g_active_task[cur_cpu_num] == mutex->mutex_task) { if (mutex->owner_nested == (mutex_nested_t)-1) { /* fatal error here, system must be stoped here */ k_err_proc(RHINO_MUTEX_NESTED_OVF); RHINO_CRITICAL_EXIT(); return RHINO_MUTEX_NESTED_OVF; } else { mutex->owner_nested++; } RHINO_CRITICAL_EXIT(); return RHINO_MUTEX_OWNER_NESTED; } mutex_task = mutex->mutex_task; if (mutex_task == NULL) { /* get lock */ mutex->mutex_task = g_active_task[cur_cpu_num]; #if (RHINO_CONFIG_MUTEX_INHERIT > 0) mutex->mutex_list = g_active_task[cur_cpu_num]->mutex_list; g_active_task[cur_cpu_num]->mutex_list = mutex; #endif mutex->owner_nested = 1u; TRACE_MUTEX_GET(g_active_task[cur_cpu_num], mutex, ticks); RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } /* can't get mutex, and return immediately if wait_option is RHINO_NO_WAIT */ if (ticks == RHINO_NO_WAIT) { RHINO_CRITICAL_EXIT(); return RHINO_NO_PEND_WAIT; } /* system is locked so task can not be blocked just return immediately */ if (g_sched_lock[cur_cpu_num] > 0u) { RHINO_CRITICAL_EXIT(); return RHINO_SCHED_DISABLE; } #if (RHINO_CONFIG_MUTEX_INHERIT > 0) /* if current task is a higher prio task and block on the mutex prio inverse condition happened, prio inherit method is used here */ if (g_active_task[cur_cpu_num]->prio < mutex_task->prio) { task_pri_change(mutex_task, g_active_task[cur_cpu_num]->prio); TRACE_TASK_PRI_INV(g_active_task[cur_cpu_num], mutex_task); } #endif /* any way block the current task */ pend_to_blk_obj(&mutex->blk_obj, g_active_task[cur_cpu_num], ticks); TRACE_MUTEX_GET_BLK(g_active_task[cur_cpu_num], mutex, ticks); RHINO_CRITICAL_EXIT_SCHED(); RHINO_CPU_INTRPT_DISABLE(); /* so the task is waked up, need know which reason cause wake up */ ret = pend_state_end_proc(g_active_task[cpu_cur_get()], &mutex->blk_obj); RHINO_CPU_INTRPT_ENABLE(); return ret; } kstat_t krhino_mutex_unlock(kmutex_t *mutex) { CPSR_ALLOC(); klist_t *blk_list_head; ktask_t *task; uint8_t cur_cpu_num; NULL_PARA_CHK(mutex); if (g_sys_stat == RHINO_STOPPED) { return RHINO_SUCCESS; } RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); if (mutex->blk_obj.obj_type != RHINO_MUTEX_OBJ_TYPE) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_TYPE_ERR; } cur_cpu_num = cpu_cur_get(); /* mutex must be released by itself */ if (g_active_task[cur_cpu_num] != mutex->mutex_task) { RHINO_CRITICAL_EXIT(); return RHINO_MUTEX_NOT_RELEASED_BY_OWNER; } mutex->owner_nested--; if (mutex->owner_nested > 0u) { RHINO_CRITICAL_EXIT(); return RHINO_MUTEX_OWNER_NESTED; } mutex_release(g_active_task[cur_cpu_num], mutex); blk_list_head = &mutex->blk_obj.blk_list; /* if no block task on this list just return */ if (is_klist_empty(blk_list_head)) { /* No wait task */ mutex->mutex_task = NULL; TRACE_MUTEX_RELEASE_SUCCESS(g_active_task[cur_cpu_num], mutex); RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } /* there must have task blocked on this mutex object */ task = krhino_list_entry(blk_list_head->next, ktask_t, task_list); /* wake up the occupy task, which is the highst prio task on the list */ pend_task_wakeup(task); TRACE_MUTEX_TASK_WAKE(g_active_task[cur_cpu_num], task, mutex); /* change mutex get task */ mutex->mutex_task = task; #if (RHINO_CONFIG_MUTEX_INHERIT > 0) mutex->mutex_list = task->mutex_list; task->mutex_list = mutex; #endif mutex->owner_nested = 1u; RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; }
YifuLiu/AliOS-Things
kernel/rhino/k_mutex.c
C
apache-2.0
11,145
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "k_api.h" kstat_t g_sys_stat; uint8_t g_idle_task_spawned[RHINO_CONFIG_CPU_NUM]; runqueue_t g_ready_queue; /* schedule lock counter */ uint8_t g_sched_lock[RHINO_CONFIG_CPU_NUM]; uint8_t g_intrpt_nested_level[RHINO_CONFIG_CPU_NUM]; /* highest pri task in ready queue */ ktask_t *g_preferred_ready_task[RHINO_CONFIG_CPU_NUM]; /* current active task */ ktask_t *g_active_task[RHINO_CONFIG_CPU_NUM]; /* global task ID */ uint32_t g_task_id; /* idle task attribute */ ktask_t g_idle_task[RHINO_CONFIG_CPU_NUM]; idle_count_t g_idle_count[RHINO_CONFIG_CPU_NUM]; cpu_stack_t g_idle_task_stack[RHINO_CONFIG_CPU_NUM][RHINO_CONFIG_IDLE_TASK_STACK_SIZE]; per_cpu_t g_per_cpu[RHINO_CONFIG_CPU_NUM]; /* tick attribute */ tick_t g_tick_count; klist_t g_tick_head; #if (RHINO_CONFIG_KOBJ_LIST > 0) kobj_list_t g_kobj_list; #endif #if (RHINO_CONFIG_TIMER > 0) klist_t g_timer_head; tick_t g_timer_count; ktask_t g_timer_task; cpu_stack_t g_timer_task_stack[RHINO_CONFIG_TIMER_TASK_STACK_SIZE]; kbuf_queue_t g_timer_queue; k_timer_queue_cb timer_queue_cb[RHINO_CONFIG_TIMER_MSG_NUM]; #endif #if (RHINO_CONFIG_SYS_STATS > 0) hr_timer_t g_sched_disable_time_start; hr_timer_t g_sched_disable_max_time; hr_timer_t g_cur_sched_disable_max_time; uint16_t g_intrpt_disable_times; hr_timer_t g_intrpt_disable_time_start; hr_timer_t g_intrpt_disable_max_time; hr_timer_t g_cur_intrpt_disable_max_time; ctx_switch_t g_sys_ctx_switch_times; #endif #if (RHINO_CONFIG_HW_COUNT > 0) hr_timer_t g_sys_measure_waste; #endif #if (RHINO_CONFIG_CPU_USAGE_STATS > 0) ktask_t g_cpu_usage_task; cpu_stack_t g_cpu_task_stack[RHINO_CONFIG_CPU_USAGE_TASK_STACK]; idle_count_t g_idle_count_max; uint32_t g_cpu_usage; #endif #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) ksem_t g_res_sem; klist_t g_res_list; ktask_t g_dyn_task; cpu_stack_t g_dyn_task_stack[RHINO_CONFIG_K_DYN_TASK_STACK]; #endif #if (RHINO_CONFIG_WORKQUEUE > 0) klist_t g_workqueue_list_head; kmutex_t g_workqueue_mutex; kworkqueue_t g_workqueue_default; cpu_stack_t g_workqueue_stack[RHINO_CONFIG_WORKQUEUE_STACK_SIZE]; #endif #if (RHINO_CONFIG_MM_TLF > 0) k_mm_head *g_kmm_head; #endif #if (RHINO_CONFIG_CPU_NUM > 1) kspinlock_t g_sys_lock; klist_t g_task_del_head; volatile uint64_t g_cpu_flag; #endif
YifuLiu/AliOS-Things
kernel/rhino/k_obj.c
C
apache-2.0
2,426
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "k_api.h" RHINO_INLINE void pend_list_add(klist_t *head, ktask_t *task) { klist_t *tmp; klist_t *list_start = head; klist_t *list_end = head; for (tmp = list_start->next; tmp != list_end; tmp = tmp->next) { if (krhino_list_entry(tmp, ktask_t, task_list)->prio > task->prio) { break; } } klist_insert(tmp, &task->task_list); } void pend_task_wakeup(ktask_t *task) { /* wake up task depend on the different state of task */ switch (task->task_state) { case K_PEND: /* remove task on the block list because task is waken up */ klist_rm(&task->task_list); /* add to the ready list again */ ready_list_add(&g_ready_queue, task); task->task_state = K_RDY; break; case K_PEND_SUSPENDED: /* remove task on the block list because task is waken up */ klist_rm(&task->task_list); task->task_state = K_SUSPENDED; break; default: k_err_proc(RHINO_SYS_FATAL_ERR); break; } /* remove task on the tick list because task is waken up */ tick_list_rm(task); task->blk_state = BLK_FINISH; task->blk_obj = NULL; } void pend_to_blk_obj(blk_obj_t *blk_obj, ktask_t *task, tick_t timeout) { /* task need to remember which object is blocked on */ task->blk_obj = blk_obj; if (timeout != RHINO_WAIT_FOREVER) { tick_list_insert(task, timeout); } task->task_state = K_PEND; /* remove from the ready list */ ready_list_rm(&g_ready_queue, task); if (blk_obj->blk_policy == BLK_POLICY_FIFO) { /* add to the end of blocked objet list */ klist_insert(&blk_obj->blk_list, &task->task_list); } else { /* add to the prio sorted block list */ pend_list_add(&blk_obj->blk_list, task); } } void pend_task_rm(ktask_t *task) { switch (task->task_state) { case K_PEND: /* remove task on the block list because task is waken up */ klist_rm(&task->task_list); /*add to the ready list again*/ ready_list_add(&g_ready_queue, task); task->task_state = K_RDY; break; case K_PEND_SUSPENDED: /* remove task on the block list because task is waken up */ klist_rm(&task->task_list); task->task_state = K_SUSPENDED; break; default: k_err_proc(RHINO_SYS_FATAL_ERR); break; } /* remove task on the tick list because task is waken up */ tick_list_rm(task); task->blk_state = BLK_DEL; /* task is nothing blocked on so reset it to NULL */ task->blk_obj = NULL; } void pend_list_reorder(ktask_t *task) { if (task->blk_obj->blk_policy == BLK_POLICY_PRI) { /* remove it first and add it again in prio sorted list */ klist_rm(&task->task_list); pend_list_add(&task->blk_obj->blk_list, task); } } kstat_t pend_state_end_proc(ktask_t *task, blk_obj_t *blk_obj) { kstat_t status; (void)blk_obj; switch (task->blk_state) { case BLK_FINISH: status = RHINO_SUCCESS; break; case BLK_ABORT: status = RHINO_BLK_ABORT; break; case BLK_TIMEOUT: status = RHINO_BLK_TIMEOUT; break; case BLK_DEL: status = RHINO_BLK_DEL; break; default: k_err_proc(RHINO_BLK_INV_STATE); status = RHINO_BLK_INV_STATE; break; } #if (RHINO_CONFIG_TASK_DEL > 0) if (blk_obj == NULL) { if (task->cancel == 1u) { status = RHINO_TASK_CANCELED; } return status; } if ((task->cancel == 1u) && (blk_obj->cancel == 1u)) { status = RHINO_TASK_CANCELED; } #endif return status; }
YifuLiu/AliOS-Things
kernel/rhino/k_pend.c
C
apache-2.0
3,982
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "k_api.h" #if (RHINO_CONFIG_QUEUE > 0) RHINO_INLINE void task_msg_recv(ktask_t *task, void *msg) { task->msg = msg; pend_task_wakeup(task); } static kstat_t queue_create(kqueue_t *queue, const name_t *name, void **start, size_t msg_num, uint8_t mm_alloc_flag) { #if (RHINO_CONFIG_KOBJ_LIST > 0) CPSR_ALLOC(); #endif NULL_PARA_CHK(queue); NULL_PARA_CHK(start); NULL_PARA_CHK(name); if (msg_num == 0u) { return RHINO_INV_PARAM; } memset(queue, 0, sizeof(kqueue_t)); /* init the queue blocked list */ klist_init(&queue->blk_obj.blk_list); queue->blk_obj.name = name; queue->blk_obj.blk_policy = BLK_POLICY_PRI; queue->msg_q.queue_start = start; ringbuf_init(&queue->ringbuf, (void *)start, msg_num * sizeof(void *), RINGBUF_TYPE_FIX, sizeof(void *)); queue->msg_q.size = msg_num; queue->msg_q.cur_num = 0u; queue->msg_q.peak_num = 0u; queue->mm_alloc_flag = mm_alloc_flag; #if (RHINO_CONFIG_TASK_DEL > 0) queue->blk_obj.cancel = 1u; #endif #if (RHINO_CONFIG_KOBJ_LIST > 0) RHINO_CRITICAL_ENTER(); klist_insert(&(g_kobj_list.queue_head), &queue->queue_item); RHINO_CRITICAL_EXIT(); #endif queue->blk_obj.obj_type = RHINO_QUEUE_OBJ_TYPE; return RHINO_SUCCESS; } kstat_t krhino_queue_create(kqueue_t *queue, const name_t *name, void **start, size_t msg_num) { return queue_create(queue, name, start, msg_num, K_OBJ_STATIC_ALLOC); } kstat_t krhino_queue_del(kqueue_t *queue) { CPSR_ALLOC(); klist_t *blk_list_head; NULL_PARA_CHK(queue); RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); if (queue->blk_obj.obj_type != RHINO_QUEUE_OBJ_TYPE) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_TYPE_ERR; } if (queue->mm_alloc_flag != K_OBJ_STATIC_ALLOC) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_DEL_ERR; } blk_list_head = &queue->blk_obj.blk_list; queue->blk_obj.obj_type = RHINO_OBJ_TYPE_NONE; /* all task blocked on this queue is waken up */ while (!is_klist_empty(blk_list_head)) { pend_task_rm(krhino_list_entry(blk_list_head->next, ktask_t, task_list)); } #if (RHINO_CONFIG_KOBJ_LIST > 0) klist_rm(&queue->queue_item); #endif ringbuf_reset(&queue->ringbuf); RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) kstat_t krhino_queue_dyn_create(kqueue_t **queue, const name_t *name, size_t msg_num) { kstat_t stat; kqueue_t *queue_obj; void **msg_start; NULL_PARA_CHK(queue); queue_obj = krhino_mm_alloc(sizeof(kqueue_t)); if (queue_obj == NULL) { return RHINO_NO_MEM; } msg_start = krhino_mm_alloc(msg_num * sizeof(void *)); if (msg_start == NULL) { krhino_mm_free(queue_obj); return RHINO_NO_MEM; } stat = queue_create(queue_obj, name, (void **)msg_start, msg_num, K_OBJ_DYN_ALLOC); if (stat != RHINO_SUCCESS) { krhino_mm_free(msg_start); krhino_mm_free(queue_obj); return stat; } *queue = queue_obj; return stat; } kstat_t krhino_queue_dyn_del(kqueue_t *queue) { CPSR_ALLOC(); klist_t *blk_list_head; NULL_PARA_CHK(queue); RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); if (queue->blk_obj.obj_type != RHINO_QUEUE_OBJ_TYPE) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_TYPE_ERR; } if (queue->mm_alloc_flag != K_OBJ_DYN_ALLOC) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_DEL_ERR; } blk_list_head = &queue->blk_obj.blk_list; queue->blk_obj.obj_type = RHINO_OBJ_TYPE_NONE; /* all task blocked on this queue is waken up */ while (!is_klist_empty(blk_list_head)) { pend_task_rm(krhino_list_entry(blk_list_head->next, ktask_t, task_list)); } #if (RHINO_CONFIG_KOBJ_LIST > 0) klist_rm(&queue->queue_item); #endif ringbuf_reset(&queue->ringbuf); RHINO_CRITICAL_EXIT_SCHED(); krhino_mm_free(queue->msg_q.queue_start); krhino_mm_free(queue); return RHINO_SUCCESS; } #endif static kstat_t msg_send(kqueue_t *p_q, void *p_void, uint8_t opt_wake_all) { CPSR_ALLOC(); klist_t *blk_list_head; NULL_PARA_CHK(p_q); RHINO_CRITICAL_ENTER(); if (p_q->blk_obj.obj_type != RHINO_QUEUE_OBJ_TYPE) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_TYPE_ERR; } if (p_q->msg_q.cur_num >= p_q->msg_q.size) { RHINO_CRITICAL_EXIT(); return RHINO_QUEUE_FULL; } blk_list_head = &p_q->blk_obj.blk_list; /* queue is not full here, if there is no blocked receive task */ if (is_klist_empty(blk_list_head)) { p_q->msg_q.cur_num++; /* update peak_num for debug */ if (p_q->msg_q.cur_num > p_q->msg_q.peak_num) { p_q->msg_q.peak_num = p_q->msg_q.cur_num; } ringbuf_queue_push(&p_q->ringbuf, &p_void, sizeof(void *)); RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } /* wake all the task blocked on this queue */ if (opt_wake_all) { while (!is_klist_empty(blk_list_head)) { task_msg_recv(krhino_list_entry(blk_list_head->next, ktask_t, task_list), p_void); } } else { task_msg_recv(krhino_list_entry(blk_list_head->next, ktask_t, task_list), p_void); } RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } kstat_t krhino_queue_back_send(kqueue_t *queue, void *msg) { return msg_send(queue, msg, WAKE_ONE_TASK); } kstat_t krhino_queue_all_send(kqueue_t *queue, void *msg) { return msg_send(queue, msg, WAKE_ALL_TASK); } kstat_t krhino_queue_recv(kqueue_t *queue, tick_t ticks, void **msg) { CPSR_ALLOC(); kstat_t ret; uint8_t cur_cpu_num; NULL_PARA_CHK(queue); NULL_PARA_CHK(msg); RHINO_CRITICAL_ENTER(); cur_cpu_num = cpu_cur_get(); TASK_CANCEL_CHK(queue); if ((g_intrpt_nested_level[cur_cpu_num] > 0u) && (ticks != RHINO_NO_WAIT)) { RHINO_CRITICAL_EXIT(); return RHINO_NOT_CALLED_BY_INTRPT; } if (queue->blk_obj.obj_type != RHINO_QUEUE_OBJ_TYPE) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_TYPE_ERR; } /* if queue has msgs, just receive it */ if (queue->msg_q.cur_num > 0u) { ringbuf_queue_pop(&queue->ringbuf, msg, NULL); queue->msg_q.cur_num--; RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } if (ticks == RHINO_NO_WAIT) { *msg = NULL; RHINO_CRITICAL_EXIT(); return RHINO_NO_PEND_WAIT; } /* if system is locked, block operation is not allowed */ if (g_sched_lock[cur_cpu_num] > 0u) { *msg = NULL; RHINO_CRITICAL_EXIT(); return RHINO_SCHED_DISABLE; } pend_to_blk_obj(&queue->blk_obj, g_active_task[cur_cpu_num], ticks); RHINO_CRITICAL_EXIT_SCHED(); RHINO_CPU_INTRPT_DISABLE(); cur_cpu_num = cpu_cur_get(); ret = pend_state_end_proc(g_active_task[cur_cpu_num], &queue->blk_obj); switch (ret) { case RHINO_SUCCESS: *msg = g_active_task[cur_cpu_num]->msg; break; default: *msg = NULL; break; } RHINO_CPU_INTRPT_ENABLE(); return ret; } kstat_t krhino_queue_is_full(kqueue_t *queue) { CPSR_ALLOC(); kstat_t ret; NULL_PARA_CHK(queue); RHINO_CRITICAL_ENTER(); if (queue->blk_obj.obj_type != RHINO_QUEUE_OBJ_TYPE) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_TYPE_ERR; } if (queue->msg_q.cur_num >= queue->msg_q.size) { ret = RHINO_QUEUE_FULL; } else { ret = RHINO_QUEUE_NOT_FULL; } RHINO_CRITICAL_EXIT(); return ret; } kstat_t krhino_queue_flush(kqueue_t *queue) { CPSR_ALLOC(); NULL_PARA_CHK(queue); RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); if (queue->blk_obj.obj_type != RHINO_QUEUE_OBJ_TYPE) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_TYPE_ERR; } queue->msg_q.cur_num = 0u; ringbuf_reset(&queue->ringbuf); RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } kstat_t krhino_queue_info_get(kqueue_t *queue, msg_info_t *info) { CPSR_ALLOC(); klist_t *blk_list_head; if (queue == NULL) { return RHINO_NULL_PTR; } if (info == NULL) { return RHINO_NULL_PTR; } NULL_PARA_CHK(queue); NULL_PARA_CHK(info); RHINO_CPU_INTRPT_DISABLE(); if (queue->blk_obj.obj_type != RHINO_QUEUE_OBJ_TYPE) { RHINO_CPU_INTRPT_ENABLE(); return RHINO_KOBJ_TYPE_ERR; } blk_list_head = &queue->blk_obj.blk_list; info->msg_q.peak_num = queue->msg_q.peak_num; info->msg_q.cur_num = queue->msg_q.cur_num; info->msg_q.queue_start = queue->msg_q.queue_start; info->msg_q.size = queue->msg_q.size; info->pend_entry = blk_list_head->next; RHINO_CPU_INTRPT_ENABLE(); return RHINO_SUCCESS; } #endif
YifuLiu/AliOS-Things
kernel/rhino/k_queue.c
C
apache-2.0
9,248
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "k_rbtree.h" static inline void rbtree_set_black(struct k_rbtree_node_t *rbt) { rbt->rbt_parent_color |= K_RBTREE_BLACK; } static inline void rbtree_rotate_set_parents(struct k_rbtree_node_t *old, struct k_rbtree_node_t *new, struct k_rbtree_root_t *root, int color) { struct k_rbtree_node_t *parent = K_RBTREE_PARENT(old); new->rbt_parent_color = old->rbt_parent_color; rbtree_set_parent_color(old, new, color); rbtree_change_child(old, new, parent, root); } static void rbtree_insert(struct k_rbtree_node_t *node, struct k_rbtree_root_t *root, void (*augment_rotate)(struct k_rbtree_node_t *old, struct k_rbtree_node_t *new)) { struct k_rbtree_node_t *parent = (struct k_rbtree_node_t *)node->rbt_parent_color, *gparent, *tmp; while (1) { if (!parent) { rbtree_set_parent_color(node, NULL, K_RBTREE_BLACK); break; } else if (K_RBTREE_IS_BLACK(parent)){ break; } gparent = (struct k_rbtree_node_t *)parent->rbt_parent_color; tmp = gparent->rbt_right; if (parent != tmp) { if (tmp && K_RBTREE_IS_RED(tmp)) { rbtree_set_parent_color(tmp, gparent, K_RBTREE_BLACK); rbtree_set_parent_color(parent, gparent, K_RBTREE_BLACK); node = gparent; parent = K_RBTREE_PARENT(node); rbtree_set_parent_color(node, parent, K_RBTREE_RED); continue; } tmp = parent->rbt_right; if (node == tmp) { parent->rbt_right = tmp = node->rbt_left; node->rbt_left = parent; if (tmp){ rbtree_set_parent_color(tmp, parent, K_RBTREE_BLACK); } rbtree_set_parent_color(parent, node, K_RBTREE_RED); augment_rotate(parent, node); parent = node; tmp = node->rbt_right; } gparent->rbt_left = tmp; parent->rbt_right = gparent; if (tmp){ rbtree_set_parent_color(tmp, gparent, K_RBTREE_BLACK); } rbtree_rotate_set_parents(gparent, parent, root, K_RBTREE_RED); augment_rotate(gparent, parent); break; } else { tmp = gparent->rbt_left; if (tmp && K_RBTREE_IS_RED(tmp)) { rbtree_set_parent_color(tmp, gparent, K_RBTREE_BLACK); rbtree_set_parent_color(parent, gparent, K_RBTREE_BLACK); node = gparent; parent = K_RBTREE_PARENT(node); rbtree_set_parent_color(node, parent, K_RBTREE_RED); continue; } tmp = parent->rbt_left; if (node == tmp) { parent->rbt_left = tmp = node->rbt_right; node->rbt_right = parent; if (tmp){ rbtree_set_parent_color(tmp, parent, K_RBTREE_BLACK); } rbtree_set_parent_color(parent, node, K_RBTREE_RED); augment_rotate(parent, node); parent = node; tmp = node->rbt_left; } gparent->rbt_right = tmp; parent->rbt_left = gparent; if (tmp){ rbtree_set_parent_color(tmp, gparent, K_RBTREE_BLACK); } rbtree_rotate_set_parents(gparent, parent, root, K_RBTREE_RED); augment_rotate(gparent, parent); break; } } } void rbtree_erase_color(struct k_rbtree_node_t *parent, struct k_rbtree_root_t *root, void (*augment_rotate)(struct k_rbtree_node_t *old, struct k_rbtree_node_t *new)) { struct k_rbtree_node_t *node = NULL, *sibling, *tmp1, *tmp2; while (1) { sibling = parent->rbt_right; if (node != sibling) { if (K_RBTREE_IS_RED(sibling)) { parent->rbt_right = tmp1 = sibling->rbt_left; sibling->rbt_left = parent; rbtree_set_parent_color(tmp1, parent, K_RBTREE_BLACK); rbtree_rotate_set_parents(parent, sibling, root, K_RBTREE_RED); augment_rotate(parent, sibling); sibling = tmp1; } tmp1 = sibling->rbt_right; if (!tmp1 || K_RBTREE_IS_BLACK(tmp1)) { tmp2 = sibling->rbt_left; if (!tmp2 || K_RBTREE_IS_BLACK(tmp2)) { rbtree_set_parent_color(sibling, parent, K_RBTREE_RED); if (K_RBTREE_IS_RED(parent)){ rbtree_set_black(parent); } else { node = parent; parent = K_RBTREE_PARENT(node); if (parent){ continue; } } break; } sibling->rbt_left = tmp1 = tmp2->rbt_right; tmp2->rbt_right = sibling; parent->rbt_right = tmp2; if (tmp1){ rbtree_set_parent_color(tmp1, sibling, K_RBTREE_BLACK); } augment_rotate(sibling, tmp2); tmp1 = sibling; sibling = tmp2; } parent->rbt_right = tmp2 = sibling->rbt_left; sibling->rbt_left = parent; rbtree_set_parent_color(tmp1, sibling, K_RBTREE_BLACK); if (tmp2){ rbtree_set_parent(tmp2, parent); } rbtree_rotate_set_parents(parent, sibling, root, K_RBTREE_BLACK); augment_rotate(parent, sibling); break; } else { sibling = parent->rbt_left; if (K_RBTREE_IS_RED(sibling)) { parent->rbt_left = tmp1 = sibling->rbt_right; sibling->rbt_right = parent; rbtree_set_parent_color(tmp1, parent, K_RBTREE_BLACK); rbtree_rotate_set_parents(parent, sibling, root, K_RBTREE_RED); augment_rotate(parent, sibling); sibling = tmp1; } tmp1 = sibling->rbt_left; if (!tmp1 || K_RBTREE_IS_BLACK(tmp1)) { tmp2 = sibling->rbt_right; if (!tmp2 || K_RBTREE_IS_BLACK(tmp2)) { rbtree_set_parent_color(sibling, parent, K_RBTREE_RED); if (K_RBTREE_IS_RED(parent)){ rbtree_set_black(parent); } else { node = parent; parent = K_RBTREE_PARENT(node); if (parent){ continue; } } break; } sibling->rbt_right = tmp1 = tmp2->rbt_left; tmp2->rbt_left = sibling; parent->rbt_left = tmp2; if (tmp1){ rbtree_set_parent_color(tmp1, sibling, K_RBTREE_BLACK); } augment_rotate(sibling, tmp2); tmp1 = sibling; sibling = tmp2; } parent->rbt_left = tmp2 = sibling->rbt_right; sibling->rbt_right = parent; rbtree_set_parent_color(tmp1, sibling, K_RBTREE_BLACK); if (tmp2){ rbtree_set_parent(tmp2, parent); } rbtree_rotate_set_parents(parent, sibling, root, K_RBTREE_BLACK); augment_rotate(parent, sibling); break; } } } static inline void rbtree_dummy_propagate(struct k_rbtree_node_t *node, struct k_rbtree_node_t *stop) {} static inline void rbtree_dummy_copy(struct k_rbtree_node_t *old, struct k_rbtree_node_t *new) {} static inline void rbtree_dummy_rotate(struct k_rbtree_node_t *old, struct k_rbtree_node_t *new) {} static const struct k_rbtree_augment_callbacks dummy_callbacks = { rbtree_dummy_propagate, rbtree_dummy_copy, rbtree_dummy_rotate }; void rbtree_insert_augmented(struct k_rbtree_node_t *node, struct k_rbtree_root_t *root, void (*augment_rotate)(struct k_rbtree_node_t *old, struct k_rbtree_node_t *new)) { rbtree_insert(node, root, augment_rotate); } void k_rbtree_insert_color(struct k_rbtree_node_t *node, struct k_rbtree_root_t *root) { rbtree_insert(node, root, rbtree_dummy_rotate); } void k_rbtree_erase(struct k_rbtree_node_t *node, struct k_rbtree_root_t *root) { struct k_rbtree_node_t *rebalance; rebalance = rbtree_erase_augmented(node, root, &dummy_callbacks); if (rebalance){ rbtree_erase_color(rebalance, root, rbtree_dummy_rotate); } } struct k_rbtree_node_t *k_rbtree_first(const struct k_rbtree_root_t *root) { struct k_rbtree_node_t *n; n = root->rbt_node; if (!n){ return NULL; } while (n->rbt_left){ n = n->rbt_left; } return n; } struct k_rbtree_node_t *k_rbtree_last(const struct k_rbtree_root_t *root) { struct k_rbtree_node_t *n; n = root->rbt_node; if (!n){ return NULL; } while (n->rbt_right){ n = n->rbt_right; } return n; } struct k_rbtree_node_t *k_rbtree_next(const struct k_rbtree_node_t *node) { struct k_rbtree_node_t *parent; if (K_RBTREE_EMPTY_NODE(node)){ return NULL; } if (node->rbt_right) { node = node->rbt_right; while (node->rbt_left){ node=node->rbt_left; } return (struct k_rbtree_node_t *)node; } while ((parent = K_RBTREE_PARENT(node)) && node == parent->rbt_right){ node = parent; } return parent; } struct k_rbtree_node_t *k_rbtree_prev(const struct k_rbtree_node_t *node) { struct k_rbtree_node_t *parent; if (K_RBTREE_EMPTY_NODE(node)){ return NULL; } if (node->rbt_left) { node = node->rbt_left; while (node->rbt_right){ node=node->rbt_right; } return (struct k_rbtree_node_t *)node; } while ((parent = K_RBTREE_PARENT(node)) && node == parent->rbt_left){ node = parent; } return parent; } void k_rbtree_replace_node(struct k_rbtree_node_t *victim, struct k_rbtree_node_t *new, struct k_rbtree_root_t *root) { struct k_rbtree_node_t *parent = K_RBTREE_PARENT(victim); rbtree_change_child(victim, new, parent, root); if (victim->rbt_left){ rbtree_set_parent(victim->rbt_left, new); } if (victim->rbt_right){ rbtree_set_parent(victim->rbt_right, new); } *new = *victim; } static struct k_rbtree_node_t *k_rbtree_left_deepest_node(const struct k_rbtree_node_t *node) { for (;;) { if (node->rbt_left){ node = node->rbt_left; } else if (node->rbt_right){ node = node->rbt_right; } else{ return (struct k_rbtree_node_t *)node; } } } struct k_rbtree_node_t *k_rbtree_next_postorder(const struct k_rbtree_node_t *node) { const struct k_rbtree_node_t *parent; if (!node){ return NULL; } parent = K_RBTREE_PARENT(node); if (parent && node == parent->rbt_left && parent->rbt_right) { return k_rbtree_left_deepest_node(parent->rbt_right); } else{ return (struct k_rbtree_node_t *)parent; } } struct k_rbtree_node_t *k_rbtree_first_postorder(const struct k_rbtree_root_t *root) { if (!root->rbt_node){ return NULL; } return k_rbtree_left_deepest_node(root->rbt_node); }
YifuLiu/AliOS-Things
kernel/rhino/k_rbtree.c
C
apache-2.0
12,073
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "k_api.h" #define RING_BUF_LEN sizeof(size_t) kstat_t ringbuf_init(k_ringbuf_t *p_ringbuf, void *buf, size_t len, size_t type, size_t block_size) { p_ringbuf->type = type; p_ringbuf->buf = buf; p_ringbuf->end = (uint8_t *)buf + len; p_ringbuf->blk_size = block_size; ringbuf_reset(p_ringbuf); return RHINO_SUCCESS; } kstat_t ringbuf_push(k_ringbuf_t *p_ringbuf, void *data, size_t len) { size_t len_bytes = 0; size_t split_len = 0; uint8_t c_len[RING_BUF_LEN] = {0}; if (p_ringbuf->type == RINGBUF_TYPE_FIX) { if (p_ringbuf->freesize < p_ringbuf->blk_size) { return RHINO_RINGBUF_FULL; } if (p_ringbuf->tail == p_ringbuf->end) { p_ringbuf->tail = p_ringbuf->buf; } memcpy(p_ringbuf->tail, data, p_ringbuf->blk_size); p_ringbuf->tail += p_ringbuf->blk_size; p_ringbuf->freesize -= p_ringbuf->blk_size; } else { if ((len == 0u) || (len >= (uint32_t) -1)) { return RHINO_INV_PARAM; } len_bytes = RING_BUF_LEN; /* for dynamic length ringbuf */ if (p_ringbuf->freesize < (len_bytes + len)) { return RHINO_RINGBUF_FULL; } memcpy(c_len, &len, RING_BUF_LEN); if (p_ringbuf->tail == p_ringbuf->end) { p_ringbuf->tail = p_ringbuf->buf; } /* copy length data to buffer */ split_len = p_ringbuf->end - p_ringbuf->tail; if (p_ringbuf->tail >= p_ringbuf->head && split_len < len_bytes && split_len > 0) { memcpy(p_ringbuf->tail, &c_len[0], split_len); len_bytes -= split_len; p_ringbuf->tail = p_ringbuf->buf; p_ringbuf->freesize -= split_len; } else { split_len = 0; } if (len_bytes > 0) { memcpy(p_ringbuf->tail, &c_len[split_len], len_bytes); p_ringbuf->freesize -= len_bytes; p_ringbuf->tail += len_bytes; } /* copy data to ringbuf, if break by buffer end, split data and copy to buffer head*/ split_len = 0; if (p_ringbuf->tail == p_ringbuf->end) { p_ringbuf->tail = p_ringbuf->buf; } split_len = p_ringbuf->end - p_ringbuf->tail; if (p_ringbuf->tail >= p_ringbuf->head && split_len < len && split_len > 0) { memcpy(p_ringbuf->tail, data, split_len); data = (uint8_t *)data + split_len; len -= split_len; p_ringbuf->tail = p_ringbuf->buf; p_ringbuf->freesize -= split_len; } memcpy(p_ringbuf->tail, data, len); p_ringbuf->tail += len; p_ringbuf->freesize -= len; } return RHINO_SUCCESS; } kstat_t ringbuf_pop(k_ringbuf_t *p_ringbuf, void *pdata, size_t *plen) { size_t split_len = 0; uint8_t *data = pdata; size_t len = 0; uint8_t c_len[RING_BUF_LEN] = {0}; size_t len_bytes = 0; if (p_ringbuf->type == RINGBUF_TYPE_FIX) { if (p_ringbuf->head == p_ringbuf->end) { p_ringbuf->head = p_ringbuf->buf; } memcpy(pdata, p_ringbuf->head, p_ringbuf->blk_size); p_ringbuf->head += p_ringbuf->blk_size; p_ringbuf->freesize += p_ringbuf->blk_size; if (plen != NULL) { *plen = p_ringbuf->blk_size; } return RHINO_SUCCESS; } else { len_bytes = RING_BUF_LEN; if (p_ringbuf->head == p_ringbuf->end) { p_ringbuf->head = p_ringbuf->buf; } split_len = p_ringbuf->end - p_ringbuf->head; if (split_len < len_bytes && split_len > 0) { memcpy(&c_len[0], p_ringbuf->head, split_len); p_ringbuf->head = p_ringbuf->buf; p_ringbuf->freesize += split_len; } else { split_len = 0; } if (len_bytes - split_len > 0) { memcpy(&c_len[split_len], p_ringbuf->head, (len_bytes - split_len)); p_ringbuf->head += (len_bytes - split_len); p_ringbuf->freesize += (len_bytes - split_len); } memcpy(&len, c_len, RING_BUF_LEN); *plen = len; if (p_ringbuf->head == p_ringbuf->end) { p_ringbuf->head = p_ringbuf->buf; } split_len = p_ringbuf->end - p_ringbuf->head; if (p_ringbuf->head > p_ringbuf->tail && split_len < len) { memcpy(pdata, p_ringbuf->head, split_len); data = (uint8_t *)pdata + split_len; len -= split_len; p_ringbuf->head = p_ringbuf->buf; p_ringbuf->freesize += split_len; } memcpy(data, p_ringbuf->head, len); p_ringbuf->head += len; p_ringbuf->freesize += len; return RHINO_SUCCESS; } } uint8_t ringbuf_is_full(k_ringbuf_t *p_ringbuf) { if (p_ringbuf->type == RINGBUF_TYPE_DYN && p_ringbuf->freesize < (RING_BUF_LEN + 1)) { return 1; } if ((p_ringbuf->type == RINGBUF_TYPE_FIX) && (p_ringbuf->freesize < p_ringbuf->blk_size)) { return 1; } return 0; } uint8_t ringbuf_is_empty(k_ringbuf_t *p_ringbuf) { if (p_ringbuf->freesize == (size_t)(p_ringbuf->end - p_ringbuf->buf)) { return 1; } return 0; } kstat_t ringbuf_reset(k_ringbuf_t *p_ringbuf) { p_ringbuf->head = p_ringbuf->buf; p_ringbuf->tail = p_ringbuf->buf; p_ringbuf->freesize = p_ringbuf->end - p_ringbuf->buf; return RHINO_SUCCESS; }
YifuLiu/AliOS-Things
kernel/rhino/k_ringbuf.c
C
apache-2.0
5,725
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "k_api.h" #if (RHINO_CONFIG_SYS_STATS > 0) static void sched_disable_measure_start(void) { /* start measure system lock time */ if (g_sched_lock[cpu_cur_get()] == 0u) { g_sched_disable_time_start = HR_COUNT_GET(); } } static void sched_disable_measure_stop(void) { hr_timer_t diff; /* stop measure system lock time, g_sched_lock is always zero here */ diff = HR_COUNT_GET() - g_sched_disable_time_start; if (g_sched_disable_max_time < diff) { g_sched_disable_max_time = diff; } if (g_cur_sched_disable_max_time < diff) { g_cur_sched_disable_max_time = diff; } } #endif kstat_t krhino_sched_disable(void) { CPSR_ALLOC(); RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); if (g_sched_lock[cpu_cur_get()] >= SCHED_MAX_LOCK_COUNT) { RHINO_CRITICAL_EXIT(); return RHINO_SCHED_LOCK_COUNT_OVF; } #if (RHINO_CONFIG_SYS_STATS > 0) sched_disable_measure_start(); #endif g_sched_lock[cpu_cur_get()]++; RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } kstat_t krhino_sched_enable(void) { CPSR_ALLOC(); RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); if (g_sched_lock[cpu_cur_get()] == 0u) { RHINO_CRITICAL_EXIT(); return RHINO_SCHED_ALREADY_ENABLED; } g_sched_lock[cpu_cur_get()]--; if (g_sched_lock[cpu_cur_get()] > 0u) { RHINO_CRITICAL_EXIT(); return RHINO_SCHED_DISABLE; } #if (RHINO_CONFIG_SYS_STATS > 0) sched_disable_measure_stop(); #endif RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } #if (RHINO_CONFIG_CPU_NUM > 1) void core_sched(void) { uint8_t cur_cpu_num; ktask_t *preferred_task; #if (RHINO_CONFIG_SCHED_CFS > 0) lr_timer_t cur_task_exec_time; #endif cur_cpu_num = cpu_cur_get(); if (g_per_cpu[cur_cpu_num].dis_sched > 0u) { g_per_cpu[cur_cpu_num].dis_sched = 0u; krhino_spin_unlock(&g_sys_lock); return; } if (g_intrpt_nested_level[cur_cpu_num] > 0u) { krhino_spin_unlock(&g_sys_lock); return; } if (g_sched_lock[cur_cpu_num] > 0u) { krhino_spin_unlock(&g_sys_lock); return; } preferred_task = preferred_cpu_ready_task_get(&g_ready_queue, cur_cpu_num); #if (RHINO_CONFIG_SCHED_CFS > 0) if (preferred_task == &g_idle_task[cur_cpu_num]) { if (g_active_task[cur_cpu_num]->sched_policy == KSCHED_CFS) { if (g_active_task[cur_cpu_num]->task_state == K_RDY) { cur_task_exec_time = g_active_task[cur_cpu_num]->task_time_this_run + (LR_COUNT_GET() - g_active_task[cur_cpu_num]->task_time_start); if (cur_task_exec_time < MIN_TASK_RUN_TIME) { krhino_spin_unlock(&g_sys_lock); return; } cfs_node_insert(&g_active_task[cur_cpu_num]->node, cur_task_exec_time); } } preferred_task = cfs_preferred_task_get(); if (preferred_task == 0) { preferred_task = &g_idle_task[cur_cpu_num]; } } else { if (g_active_task[cur_cpu_num]->sched_policy == KSCHED_CFS) { if (g_active_task[cur_cpu_num]->task_state == K_RDY) { cur_task_exec_time = g_active_task[cur_cpu_num]->task_time_this_run + (LR_COUNT_GET() - g_active_task[cur_cpu_num]->task_time_start); cfs_node_insert(&g_active_task[cur_cpu_num]->node, cur_task_exec_time); } } } if (preferred_task->sched_policy == KSCHED_CFS) { cfs_node_del(&preferred_task->node); } #endif /* if preferred task is currently task, then no need to do switch and just return */ if (preferred_task == g_active_task[cur_cpu_num]) { krhino_spin_unlock(&g_sys_lock); return; } TRACE_TASK_SWITCH(g_active_task[cur_cpu_num], preferred_task); #if (RHINO_CONFIG_USER_HOOK > 0) krhino_task_switch_hook(g_active_task[cur_cpu_num], preferred_task); #endif g_active_task[cur_cpu_num]->cur_exc = 0; preferred_task->cpu_num = cur_cpu_num; preferred_task->cur_exc = 1; g_preferred_ready_task[cur_cpu_num] = preferred_task; cpu_task_switch(); } #else void core_sched(void) { uint8_t cur_cpu_num; ktask_t *preferred_task; #if (RHINO_CONFIG_SCHED_CFS > 0) lr_timer_t cur_task_exec_time; #endif cur_cpu_num = cpu_cur_get(); if (g_intrpt_nested_level[cur_cpu_num] > 0u) { return; } if (g_sched_lock[cur_cpu_num] > 0u) { return; } preferred_task = preferred_cpu_ready_task_get(&g_ready_queue, cur_cpu_num); #if (RHINO_CONFIG_SCHED_CFS > 0) if (preferred_task == &g_idle_task[cur_cpu_num]) { if (g_active_task[cur_cpu_num]->sched_policy == KSCHED_CFS) { if (g_active_task[cur_cpu_num]->task_state == K_RDY) { cur_task_exec_time = g_active_task[cur_cpu_num]->task_time_this_run + (LR_COUNT_GET() - g_active_task[cur_cpu_num]->task_time_start); if (cur_task_exec_time < MIN_TASK_RUN_TIME) { return; } cfs_node_insert(&g_active_task[cur_cpu_num]->node, cur_task_exec_time); } } preferred_task = cfs_preferred_task_get(); if (preferred_task == 0) { preferred_task = &g_idle_task[cur_cpu_num]; } } else { if (g_active_task[cur_cpu_num]->sched_policy == KSCHED_CFS) { if (g_active_task[cur_cpu_num]->task_state == K_RDY) { cur_task_exec_time = g_active_task[cur_cpu_num]->task_time_this_run + (LR_COUNT_GET() - g_active_task[cur_cpu_num]->task_time_start); cfs_node_insert(&g_active_task[cur_cpu_num]->node, cur_task_exec_time); } } } if (preferred_task->sched_policy == KSCHED_CFS) { cfs_node_del(&preferred_task->node); } #endif /* if preferred task is currently task, then no need to do switch and just return */ if (preferred_task == g_active_task[cur_cpu_num]) { return; } g_preferred_ready_task[cur_cpu_num] = preferred_task; TRACE_TASK_SWITCH(g_active_task[cur_cpu_num], g_preferred_ready_task[cur_cpu_num]); #if (RHINO_CONFIG_USER_HOOK > 0) krhino_task_switch_hook(g_active_task[cur_cpu_num], g_preferred_ready_task[cur_cpu_num]); #endif cpu_task_switch(); } #endif void runqueue_init(runqueue_t *rq) { uint8_t prio; rq->highest_pri = RHINO_CONFIG_PRI_MAX; for (prio = 0; prio < RHINO_CONFIG_PRI_MAX; prio++) { rq->cur_list_item[prio] = NULL; } } RHINO_INLINE void ready_list_init(runqueue_t *rq, ktask_t *task) { rq->cur_list_item[task->prio] = &task->task_list; klist_init(rq->cur_list_item[task->prio]); krhino_bitmap_set(rq->task_bit_map, task->prio); if ((task->prio) < (rq->highest_pri)) { rq->highest_pri = task->prio; } } RHINO_INLINE uint8_t is_ready_list_empty(uint8_t prio) { return (g_ready_queue.cur_list_item[prio] == NULL); } RHINO_INLINE void _ready_list_add_tail(runqueue_t *rq, ktask_t *task) { if (is_ready_list_empty(task->prio)) { ready_list_init(rq, task); return; } klist_insert(rq->cur_list_item[task->prio], &task->task_list); } RHINO_INLINE void _ready_list_add_head(runqueue_t *rq, ktask_t *task) { if (is_ready_list_empty(task->prio)) { ready_list_init(rq, task); return; } klist_insert(rq->cur_list_item[task->prio], &task->task_list); rq->cur_list_item[task->prio] = &task->task_list; } #if (RHINO_CONFIG_CPU_NUM > 1) static void task_sched_to_cpu(runqueue_t *rq, ktask_t *task, uint8_t cur_cpu_num) { size_t i; uint8_t low_pri; size_t low_pri_cpu_num = 0; (void)rq; if (g_sys_stat == RHINO_RUNNING) { if (task->cpu_binded == 1) { if (task->cpu_num != cur_cpu_num) { if (task->prio <= g_active_task[task->cpu_num]->prio) { cpu_signal(task->cpu_num); } } } else { /* find the lowest pri */ low_pri = g_active_task[0]->prio; for (i = 0; i < RHINO_CONFIG_CPU_NUM - 1; i++) { if (low_pri < g_active_task[i + 1]->prio) { low_pri = g_active_task[i + 1]->prio; low_pri_cpu_num = i + 1; } } if (task->prio <= low_pri) { if (low_pri_cpu_num != cur_cpu_num) { if (task->prio < g_active_task[cur_cpu_num]->prio) { g_per_cpu[cur_cpu_num].dis_sched = 1u; } cpu_signal(low_pri_cpu_num); } } } } } void ready_list_add_head(runqueue_t *rq, ktask_t *task) { #if (RHINO_CONFIG_SCHED_CFS > 0) if (task->sched_policy == KSCHED_CFS) { cfs_node_insert(&task->node, cfs_node_min_get()); } else { _ready_list_add_head(rq, task); } task_sched_to_cpu(rq, task, cpu_cur_get()); #else _ready_list_add_head(rq, task); task_sched_to_cpu(rq, task, cpu_cur_get()); #endif } void ready_list_add_tail(runqueue_t *rq, ktask_t *task) { #if (RHINO_CONFIG_SCHED_CFS > 0) if (task->sched_policy == KSCHED_CFS) { cfs_node_insert(&task->node, cfs_node_min_get()); } else { _ready_list_add_tail(rq, task); } task_sched_to_cpu(rq, task, cpu_cur_get()); #else _ready_list_add_tail(rq, task); task_sched_to_cpu(rq, task, cpu_cur_get()); #endif } #else void ready_list_add_head(runqueue_t *rq, ktask_t *task) { #if (RHINO_CONFIG_SCHED_CFS > 0) if (task->sched_policy == KSCHED_CFS) { cfs_node_insert(&task->node, cfs_node_min_get()); } else { _ready_list_add_head(rq, task); } #else _ready_list_add_head(rq, task); #endif } void ready_list_add_tail(runqueue_t *rq, ktask_t *task) { #if (RHINO_CONFIG_SCHED_CFS > 0) if (task->sched_policy == KSCHED_CFS) { cfs_node_insert(&task->node, cfs_node_min_get()); } else { _ready_list_add_tail(rq, task); } #else _ready_list_add_tail(rq, task); #endif } #endif void ready_list_add(runqueue_t *rq, ktask_t *task) { ready_list_add_tail(rq, task); TRACE_TASK_START_READY(task); } void ready_list_rm(runqueue_t *rq, ktask_t *task) { int32_t i; uint8_t pri = task->prio; TRACE_TASK_STOP_READY(task); #if (RHINO_CONFIG_SCHED_CFS > 0) if (task->sched_policy == KSCHED_CFS) { if (g_active_task[cpu_cur_get()] != task) { cfs_node_del(&task->node); } return; } #endif /* if the ready list is not only one, we do not need to update the highest prio */ if ((rq->cur_list_item[pri]) != (rq->cur_list_item[pri]->next)) { if (rq->cur_list_item[pri] == &task->task_list) { rq->cur_list_item[pri] = rq->cur_list_item[pri]->next; } klist_rm(&task->task_list); return; } /* only one item,just set cur item ptr to NULL */ rq->cur_list_item[pri] = NULL; krhino_bitmap_clear(rq->task_bit_map, pri); /* if task prio not equal to the highest prio, then we do not need to update the highest prio */ /* this condition happens when a current high prio task to suspend a low priotity task */ if (pri != rq->highest_pri) { return; } /* find the highest ready task */ i = krhino_bitmap_first(rq->task_bit_map); /* update the next highest prio task */ if (i >= 0) { rq->highest_pri = i; } else { k_err_proc(RHINO_SYS_FATAL_ERR); } } void ready_list_head_to_tail(runqueue_t *rq, ktask_t *task) { rq->cur_list_item[task->prio] = rq->cur_list_item[task->prio]->next; } #if (RHINO_CONFIG_CPU_NUM > 1) ktask_t *preferred_cpu_ready_task_get(runqueue_t *rq, uint8_t cpu_num) { klist_t *iter; ktask_t *task; uint32_t task_bit_map[NUM_WORDS]; klist_t *node; uint8_t flag; uint8_t i; uint8_t highest_pri = rq->highest_pri; node = rq->cur_list_item[highest_pri]; iter = node; for (i = 0; i < NUM_WORDS; i++) { task_bit_map[i] = rq->task_bit_map[i]; } while (1) { task = krhino_list_entry(iter, ktask_t, task_list); if (g_active_task[cpu_num] == task) { return task; } flag = ((task->cur_exc == 0) && (task->cpu_binded == 0)) || ((task->cur_exc == 0) && (task->cpu_binded == 1) && (task->cpu_num == cpu_num)); if (flag > 0) { return task; } if (iter->next == rq->cur_list_item[highest_pri]) { krhino_bitmap_clear(task_bit_map, highest_pri); highest_pri = krhino_bitmap_first(task_bit_map); iter = rq->cur_list_item[highest_pri]; } else { iter = iter->next; } } } #else ktask_t *preferred_cpu_ready_task_get(runqueue_t *rq, uint8_t cpu_num) { klist_t *node = rq->cur_list_item[rq->highest_pri]; /* get the highest prio task object */ return krhino_list_entry(node, ktask_t, task_list); } #endif #if (RHINO_CONFIG_SCHED_RR > 0) void time_slice_update(void) { CPSR_ALLOC(); ktask_t *task; klist_t *head; uint8_t task_pri; RHINO_CRITICAL_ENTER(); task = g_active_task[cpu_cur_get()]; #if (RHINO_CONFIG_SCHED_CFS > 0) if (task->sched_policy == KSCHED_CFS) { RHINO_CRITICAL_EXIT(); return; } #endif task_pri = task->prio; head = g_ready_queue.cur_list_item[task_pri]; /* if ready list is empty then just return because nothing is to be caculated */ if (is_ready_list_empty(task_pri)) { RHINO_CRITICAL_EXIT(); return; } if (task->sched_policy == KSCHED_FIFO) { RHINO_CRITICAL_EXIT(); return; } /* there is only one task on this ready list, so do not need to caculate time slice */ /* idle task must satisfy this condition */ if (head->next == head) { RHINO_CRITICAL_EXIT(); return; } if (task->time_slice > 0u) { task->time_slice--; } /* if current active task has time_slice, just return */ if (task->time_slice > 0u) { RHINO_CRITICAL_EXIT(); return; } /* move current active task to the end of ready list for the same prio */ ready_list_head_to_tail(&g_ready_queue, task); /* restore the task time slice */ task->time_slice = task->time_total; RHINO_CRITICAL_EXIT(); } #endif
YifuLiu/AliOS-Things
kernel/rhino/k_sched.c
C
apache-2.0
14,763
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "k_api.h" #if (RHINO_CONFIG_SEM > 0) static kstat_t sem_create(ksem_t *sem, const name_t *name, sem_count_t count, uint8_t mm_alloc_flag) { #if (RHINO_CONFIG_KOBJ_LIST > 0) CPSR_ALLOC(); #endif NULL_PARA_CHK(sem); NULL_PARA_CHK(name); memset(sem, 0, sizeof(ksem_t)); /* init the list */ klist_init(&sem->blk_obj.blk_list); /* init resource */ sem->count = count; sem->peak_count = count; sem->blk_obj.name = name; sem->blk_obj.blk_policy = BLK_POLICY_PRI; sem->mm_alloc_flag = mm_alloc_flag; #if (RHINO_CONFIG_TASK_DEL > 0) sem->blk_obj.cancel = 1u; #endif #if (RHINO_CONFIG_KOBJ_LIST > 0) RHINO_CRITICAL_ENTER(); klist_insert(&(g_kobj_list.sem_head), &sem->sem_item); RHINO_CRITICAL_EXIT(); #endif sem->blk_obj.obj_type = RHINO_SEM_OBJ_TYPE; TRACE_SEM_CREATE(krhino_cur_task_get(), sem); return RHINO_SUCCESS; } kstat_t krhino_sem_create(ksem_t *sem, const name_t *name, sem_count_t count) { return sem_create(sem, name, count, K_OBJ_STATIC_ALLOC); } kstat_t krhino_sem_del(ksem_t *sem) { CPSR_ALLOC(); klist_t *blk_list_head; NULL_PARA_CHK(sem); RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); if (sem->blk_obj.obj_type != RHINO_SEM_OBJ_TYPE) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_TYPE_ERR; } if (sem->mm_alloc_flag != K_OBJ_STATIC_ALLOC) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_DEL_ERR; } blk_list_head = &sem->blk_obj.blk_list; sem->blk_obj.obj_type = RHINO_OBJ_TYPE_NONE; /* all task blocked on this queue is waken up */ while (!is_klist_empty(blk_list_head)) { pend_task_rm(krhino_list_entry(blk_list_head->next, ktask_t, task_list)); } #if (RHINO_CONFIG_KOBJ_LIST > 0) klist_rm(&sem->sem_item); #endif TRACE_SEM_DEL(g_active_task[cpu_cur_get()], sem); RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) kstat_t krhino_sem_dyn_create(ksem_t **sem, const name_t *name, sem_count_t count) { kstat_t stat; ksem_t *sem_obj; NULL_PARA_CHK(sem); sem_obj = krhino_mm_alloc(sizeof(ksem_t)); if (sem_obj == NULL) { return RHINO_NO_MEM; } stat = sem_create(sem_obj, name, count, K_OBJ_DYN_ALLOC); if (stat != RHINO_SUCCESS) { krhino_mm_free(sem_obj); return stat; } *sem = sem_obj; return stat; } kstat_t krhino_sem_dyn_del(ksem_t *sem) { CPSR_ALLOC(); klist_t *blk_list_head; NULL_PARA_CHK(sem); RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); if (sem->blk_obj.obj_type != RHINO_SEM_OBJ_TYPE) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_TYPE_ERR; } if (sem->mm_alloc_flag != K_OBJ_DYN_ALLOC) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_DEL_ERR; } blk_list_head = &sem->blk_obj.blk_list; sem->blk_obj.obj_type = RHINO_OBJ_TYPE_NONE; /* all task blocked on this queue is waken up */ while (!is_klist_empty(blk_list_head)) { pend_task_rm(krhino_list_entry(blk_list_head->next, ktask_t, task_list)); } #if (RHINO_CONFIG_KOBJ_LIST > 0) klist_rm(&sem->sem_item); #endif TRACE_SEM_DEL(g_active_task[cpu_cur_get()], sem); RHINO_CRITICAL_EXIT_SCHED(); krhino_mm_free(sem); return RHINO_SUCCESS; } #endif static kstat_t sem_give(ksem_t *sem, uint8_t opt_wake_all) { CPSR_ALLOC(); uint8_t cur_cpu_num; klist_t *blk_list_head; RHINO_CRITICAL_ENTER(); if (sem->blk_obj.obj_type != RHINO_SEM_OBJ_TYPE) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_TYPE_ERR; } cur_cpu_num = cpu_cur_get(); (void)cur_cpu_num; blk_list_head = &sem->blk_obj.blk_list; if (is_klist_empty(blk_list_head)) { if (sem->count == (sem_count_t)-1) { TRACE_SEM_OVERFLOW(g_active_task[cur_cpu_num], sem); RHINO_CRITICAL_EXIT(); return RHINO_SEM_OVF; } /* increase resource */ sem->count++; if (sem->count > sem->peak_count) { sem->peak_count = sem->count; } TRACE_SEM_CNT_INCREASE(g_active_task[cur_cpu_num], sem); RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } /* wake all the task blocked on this semaphore */ if (opt_wake_all) { while (!is_klist_empty(blk_list_head)) { TRACE_SEM_TASK_WAKE(g_active_task[cur_cpu_num], krhino_list_entry(blk_list_head->next, ktask_t, task_list), sem, opt_wake_all); pend_task_wakeup(krhino_list_entry(blk_list_head->next, ktask_t, task_list)); } } else { TRACE_SEM_TASK_WAKE(g_active_task[cur_cpu_num], krhino_list_entry(blk_list_head->next, ktask_t, task_list), sem, opt_wake_all); /* wake up the highest prio task block on the semaphore */ pend_task_wakeup(krhino_list_entry(blk_list_head->next, ktask_t, task_list)); } TRACE_SEM_GIVE(sem, opt_wake_all); RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } kstat_t krhino_sem_give(ksem_t *sem) { NULL_PARA_CHK(sem); return sem_give(sem, WAKE_ONE_SEM); } kstat_t krhino_sem_give_all(ksem_t *sem) { NULL_PARA_CHK(sem); return sem_give(sem, WAKE_ALL_SEM); } kstat_t krhino_sem_take(ksem_t *sem, tick_t ticks) { CPSR_ALLOC(); uint8_t cur_cpu_num; kstat_t stat; NULL_PARA_CHK(sem); RHINO_CRITICAL_ENTER(); cur_cpu_num = cpu_cur_get(); TASK_CANCEL_CHK(sem); INTRPT_NESTED_LEVEL_CHK(); if (sem->blk_obj.obj_type != RHINO_SEM_OBJ_TYPE) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_TYPE_ERR; } if (sem->count > 0u) { sem->count--; TRACE_SEM_GET_SUCCESS(g_active_task[cur_cpu_num], sem); RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } /* can't get semphore, and return immediately if wait_option is RHINO_NO_WAIT */ if (ticks == RHINO_NO_WAIT) { RHINO_CRITICAL_EXIT(); return RHINO_NO_PEND_WAIT; } if (g_sched_lock[cur_cpu_num] > 0u) { RHINO_CRITICAL_EXIT(); return RHINO_SCHED_DISABLE; } pend_to_blk_obj(&sem->blk_obj, g_active_task[cur_cpu_num], ticks); TRACE_SEM_GET_BLK(g_active_task[cur_cpu_num], sem, ticks); RHINO_CRITICAL_EXIT_SCHED(); RHINO_CPU_INTRPT_DISABLE(); stat = pend_state_end_proc(g_active_task[cpu_cur_get()], &sem->blk_obj); RHINO_CPU_INTRPT_ENABLE(); return stat; } kstat_t krhino_sem_count_set(ksem_t *sem, sem_count_t sem_count) { CPSR_ALLOC(); klist_t *blk_list_head; NULL_PARA_CHK(sem); blk_list_head = &sem->blk_obj.blk_list; RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); if (sem->blk_obj.obj_type != RHINO_SEM_OBJ_TYPE) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_TYPE_ERR; } /* set new count */ if (sem->count > 0u) { sem->count = sem_count; } else { if (is_klist_empty(blk_list_head)) { sem->count = sem_count; } else { RHINO_CRITICAL_EXIT(); return RHINO_SEM_TASK_WAITING; } } /* update sem peak count if need */ if (sem->count > sem->peak_count) { sem->peak_count = sem->count; } RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } kstat_t krhino_sem_count_get(ksem_t *sem, sem_count_t *count) { CPSR_ALLOC(); NULL_PARA_CHK(sem); NULL_PARA_CHK(count); RHINO_CRITICAL_ENTER(); *count = sem->count; RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } #endif /* RHINO_CONFIG_SEM */
YifuLiu/AliOS-Things
kernel/rhino/k_sem.c
C
apache-2.0
7,895
/* * Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #include "k_api.h" #include "k_spin_lock.h" #if (RHINO_CONFIG_CPU_NUM > 1) /* not use for linuxhost */ #define DBG_PRINTF(...) //printf(__VA_ARGS__) #define KRHINO_SPINLOCK_FREE_VAL 0xB33FFFFFu #define KRHINO_SPINLOCK_MAGIC_VAL 0xB33F0000u #define KRHINO_SPINLOCK_MAGIC_MASK 0xFFFF0000u #define KRHINO_SPINLOCK_MAGIC_SHIFT 16 #define KRHINO_SPINLOCK_CNT_MASK 0x0000FF00u #define KRHINO_SPINLOCK_CNT_SHIFT 8 #define KRHINO_SPINLOCK_VAL_MASK 0x000000FFu #define KRHINO_SPINLOCK_VAL_SHIFT 0 #ifdef RHINO_CONFIG_SPINLOCK_DEBUG void k_cpu_spin_lock(kspinlock_t *lock, const char *fnName, int32_t line) #else void k_cpu_spin_lock(kspinlock_t *lock) #endif { uint32_t res; uint32_t recCnt; uint32_t cnt = (1 << 16); if ((lock->owner & KRHINO_SPINLOCK_MAGIC_MASK) != KRHINO_SPINLOCK_MAGIC_VAL) { lock->owner = KRHINO_SPINLOCK_FREE_VAL; } do { /* Lock mux if it's currently unlocked */ res = (cpu_cur_get() << KRHINO_SPINLOCK_VAL_SHIFT) | KRHINO_SPINLOCK_MAGIC_VAL; cpu_atomic_compare_set(&lock->owner, KRHINO_SPINLOCK_FREE_VAL, &res); /* If it wasn't free and we're the owner of the lock, we are locking recursively. */ if ((res != KRHINO_SPINLOCK_FREE_VAL) && (((res & KRHINO_SPINLOCK_VAL_MASK) >> KRHINO_SPINLOCK_VAL_SHIFT) == cpu_cur_get())) { /* Mux was already locked by us. Just increase count by one. */ recCnt = (res & KRHINO_SPINLOCK_CNT_MASK) >> KRHINO_SPINLOCK_CNT_SHIFT; recCnt++; #ifdef RHINO_CONFIG_SPINLOCK_DEBUG /* DBG_PRINTF("Recursive lock: recCnt=%d last non-recursive lock %s line %d,curr %s line %d\n", recCnt, lock->last_lockfile, lock->last_lockline, fnName, line); */ #endif lock->owner = KRHINO_SPINLOCK_MAGIC_VAL | (recCnt << KRHINO_SPINLOCK_CNT_SHIFT) | (cpu_cur_get() << KRHINO_SPINLOCK_VAL_SHIFT); break; } cnt--; if (cnt == 0) { #ifdef RHINO_CONFIG_SPINLOCK_DEBUG /* DBG_PRINTF("Error! Timeout on mux! last non-recursive lock %s line %d, curr %s line %d\n", lock->last_lockfile, lock->last_lockline, fnName, line); */ #endif DBG_PRINTF("Error! Timeout on mux! lock value %X,cpu_cur_get():%d\r\n", lock->owner, cpu_cur_get()); } } while (res != KRHINO_SPINLOCK_FREE_VAL); #ifdef RHINO_CONFIG_SPINLOCK_DEBUG if (res == KRHINO_SPINLOCK_FREE_VAL) { lock->last_lockfile = fnName; lock->last_lockline = line; } #endif } #ifdef RHINO_CONFIG_SPINLOCK_DEBUG void k_cpu_spin_unlock(kspinlock_t *lock, const char *fnName, int32_t line) #else void k_cpu_spin_unlock(kspinlock_t *lock) #endif { uint32_t res = 0; uint32_t recCnt; #ifdef RHINO_CONFIG_SPINLOCK_DEBUG const char *lastLockedFn = lock->last_lockfile; int lastLockedLine = lock->last_lockline; lock->last_lockfile = fnName; lock->last_lockline = line; #endif if ((lock->owner & KRHINO_SPINLOCK_MAGIC_MASK) != KRHINO_SPINLOCK_MAGIC_VAL) { DBG_PRINTF("ERROR: k_cpu_spin_unlock: spinlock %p is uninitialized (0x%X)!\n", lock, lock->owner); } /* Unlock if it's currently locked with a recurse count of 0 */ res = KRHINO_SPINLOCK_FREE_VAL; cpu_atomic_compare_set(&lock->owner, (cpu_cur_get() << KRHINO_SPINLOCK_VAL_SHIFT) | KRHINO_SPINLOCK_MAGIC_VAL, &res); if ( ((res & KRHINO_SPINLOCK_VAL_MASK) >> KRHINO_SPINLOCK_VAL_SHIFT) == cpu_cur_get() ) { if ( ((res & KRHINO_SPINLOCK_CNT_MASK) >> KRHINO_SPINLOCK_CNT_SHIFT) != 0) { /* We locked this, but the reccount isn't zero. Decrease refcount and continue. */ recCnt = (res & KRHINO_SPINLOCK_CNT_MASK) >> KRHINO_SPINLOCK_CNT_SHIFT; recCnt--; lock->owner = KRHINO_SPINLOCK_MAGIC_VAL | (recCnt << KRHINO_SPINLOCK_CNT_SHIFT) | (cpu_cur_get() << KRHINO_SPINLOCK_VAL_SHIFT); } } else if ( res == KRHINO_SPINLOCK_FREE_VAL ) { DBG_PRINTF("ERROR: k_cpu_spin_unlock: lock %p was already unlocked!\n", lock); } else { DBG_PRINTF("ERROR: k_cpu_spin_unlock: lock %p wasn't locked by this core (%d) \ but by core %d (ret=%x, lock=%x).\n", lock, cpu_cur_get(), \ ((res & KRHINO_SPINLOCK_VAL_MASK) >> KRHINO_SPINLOCK_VAL_SHIFT),\ res, lock->owner); } return; } extern volatile uint64_t g_cpu_flag; void k_wait_allcores(void) { uint8_t loop = 1; while (loop) { switch (RHINO_CONFIG_CPU_NUM) { case 2: if (g_cpu_flag == 2u) { loop = 0; } break; case 3: if (g_cpu_flag == 6u) { loop = 0; } break; case 4: if (g_cpu_flag == 14u) { loop = 0; } break; default: DBG_PRINTF("too many cpus!!!\n"); break; } } } #endif /* RHINO_CONFIG_CPU_NUM > 1 */
YifuLiu/AliOS-Things
kernel/rhino/k_spin_lock.c
C
apache-2.0
5,547
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdio.h> #include "k_api.h" #if (RHINO_CONFIG_KOBJ_LIST > 0) void kobj_list_init(void) { klist_init(&(g_kobj_list.task_head)); klist_init(&(g_kobj_list.mutex_head)); #if (RHINO_CONFIG_SEM > 0) klist_init(&(g_kobj_list.sem_head)); #endif #if (RHINO_CONFIG_QUEUE > 0) klist_init(&(g_kobj_list.queue_head)); #endif #if (RHINO_CONFIG_BUF_QUEUE > 0) klist_init(&(g_kobj_list.buf_queue_head)); #endif #if (RHINO_CONFIG_EVENT_FLAG > 0) klist_init(&(g_kobj_list.event_head)); #endif } #endif #if (RHINO_CONFIG_TASK_STACK_OVF_CHECK > 0) #if (RHINO_CONFIG_CPU_STACK_DOWN > 0) void krhino_stack_ovf_check(void) { ktask_t *cur; cpu_stack_t *stack_start; uint8_t i; cur = g_active_task[cpu_cur_get()]; stack_start = cur->task_stack_base; for (i = 0; i < RHINO_CONFIG_STK_CHK_WORDS; i++) { if (*stack_start++ != RHINO_TASK_STACK_OVF_MAGIC) { k_err_proc(RHINO_TASK_STACK_OVF); } } if ((cpu_stack_t *)(cur->task_stack) < stack_start) { k_err_proc(RHINO_TASK_STACK_OVF); } #if (RHINO_CONFIG_USER_SPACE > 0) if (cur->pid == 0) { return; } stack_start = cur->task_ustack_base; for (i = 0; i < RHINO_CONFIG_STK_CHK_WORDS; i++) { if (*stack_start++ != RHINO_TASK_STACK_OVF_MAGIC) { k_err_proc(RHINO_TASK_STACK_OVF); } } if ((cpu_stack_t *)(cur->task_ustack) < stack_start) { k_err_proc(RHINO_TASK_STACK_OVF); } #endif } #else void krhino_stack_ovf_check(void) { ktask_t *cur; cpu_stack_t *stack_start; cpu_stack_t *stack_end; uint8_t i; cur = g_active_task[cpu_cur_get()]; stack_start = cur->task_stack_base; stack_end = stack_start + cur->stack_size - RHINO_CONFIG_STK_CHK_WORDS; for (i = 0; i < RHINO_CONFIG_STK_CHK_WORDS; i++) { if (*stack_end++ != RHINO_TASK_STACK_OVF_MAGIC) { k_err_proc(RHINO_TASK_STACK_OVF); } } if ((cpu_stack_t *)(cur->task_stack) > stack_end) { k_err_proc(RHINO_TASK_STACK_OVF); } #if (RHINO_CONFIG_USER_SPACE > 0) if (cur->pid == 0) { return; } stack_start = cur->task_ustack_base; stack_end = stack_start + cur->ustack_size - RHINO_CONFIG_STK_CHK_WORDS; for (i = 0; i < RHINO_CONFIG_STK_CHK_WORDS; i++) { if (*stack_end++ != RHINO_TASK_STACK_OVF_MAGIC) { k_err_proc(RHINO_TASK_STACK_OVF); } } if ((cpu_stack_t *)(cur->task_ustack) > stack_end) { k_err_proc(RHINO_TASK_STACK_OVF); } #endif } #endif #endif #if (RHINO_CONFIG_SYS_STATS > 0) void krhino_task_sched_stats_reset(void) { lr_timer_t cur_time; uint32_t i; g_cur_intrpt_disable_max_time = 0; g_cur_sched_disable_max_time = 0; /* system first task starting time should be measured otherwise not correct */ cur_time = LR_COUNT_GET(); for (i = 0; i < RHINO_CONFIG_CPU_NUM; i++) { g_preferred_ready_task[i]->task_time_start = cur_time; } } void krhino_task_sched_stats_get(void) { lr_timer_t cur_time; lr_timer_t exec_time; hr_timer_t intrpt_disable_time; if (g_cur_intrpt_disable_max_time > g_sys_measure_waste) { intrpt_disable_time = g_cur_intrpt_disable_max_time - g_sys_measure_waste; } else { intrpt_disable_time = 0; } if (g_active_task[cpu_cur_get()]->task_intrpt_disable_time_max < intrpt_disable_time) { g_active_task[cpu_cur_get()]->task_intrpt_disable_time_max = intrpt_disable_time; } g_cur_intrpt_disable_max_time = 0; if (g_active_task[cpu_cur_get()]->task_sched_disable_time_max < g_cur_sched_disable_max_time) { g_active_task[cpu_cur_get()]->task_sched_disable_time_max = g_cur_sched_disable_max_time; } g_cur_sched_disable_max_time = 0; /* Keep track of new task and total system context switch times */ g_preferred_ready_task[cpu_cur_get()]->task_ctx_switch_times++; g_sys_ctx_switch_times++; cur_time = LR_COUNT_GET(); exec_time = cur_time - g_active_task[cpu_cur_get()]->task_time_start; g_active_task[cpu_cur_get()]->task_time_total_run += (uint64_t)exec_time; if (g_active_task[cpu_cur_get()]->task_state == K_RDY) { g_active_task[cpu_cur_get()]->task_time_this_run += exec_time; } else { g_active_task[cpu_cur_get()]->task_time_this_run = 0u; } g_preferred_ready_task[cpu_cur_get()]->task_time_start = cur_time; } void intrpt_disable_measure_start(void) { g_intrpt_disable_times++; /* start measure interrupt disable time */ if (g_intrpt_disable_times == 1u) { g_intrpt_disable_time_start = HR_COUNT_GET(); } } void intrpt_disable_measure_stop(void) { hr_timer_t diff; g_intrpt_disable_times--; if (g_intrpt_disable_times == 0u) { diff = HR_COUNT_GET() - g_intrpt_disable_time_start; if (g_intrpt_disable_max_time < diff) { g_intrpt_disable_max_time = diff; } if (g_cur_intrpt_disable_max_time < diff) { g_cur_intrpt_disable_max_time = diff; } } } #endif #if (RHINO_CONFIG_HW_COUNT > 0) void krhino_overhead_measure(void) { hr_timer_t diff; hr_timer_t m1; hr_timer_t m2; m1 = HR_COUNT_GET(); m2 = HR_COUNT_GET(); diff = m2 - m1; /* measure time overhead */ g_sys_measure_waste = diff; } #endif /*it should be called in cpu_stats task*/ #if (RHINO_CONFIG_CPU_USAGE_STATS > 0) static void cpu_usage_task_entry(void *arg) { idle_count_t idle_count; (void)arg; while (1) { idle_count_set(0u); krhino_task_sleep(RHINO_CONFIG_TICKS_PER_SECOND / 2); idle_count = idle_count_get(); if (idle_count > g_idle_count_max) { g_idle_count_max = idle_count; } if (idle_count < g_idle_count_max) { /* use 64bit for cpu_task_idle_count to avoid overflow quickly */ g_cpu_usage = 10000 - (uint32_t)((idle_count * 10000) / g_idle_count_max); } else { g_cpu_usage = 10000; } } } void cpu_usage_stats_start(void) { /* create a statistic task to calculate cpu usage */ krhino_task_create(&g_cpu_usage_task, "cpu_stats", 0, RHINO_CONFIG_CPU_USAGE_TASK_PRI, 0, g_cpu_task_stack, RHINO_CONFIG_CPU_USAGE_TASK_STACK, cpu_usage_task_entry, 1); } uint32_t krhino_get_cpu_usage(void) { return g_cpu_usage; } #endif /* RHINO_CONFIG_CPU_USAGE_STATS */
YifuLiu/AliOS-Things
kernel/rhino/k_stats.c
C
apache-2.0
6,610
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "k_api.h" RHINO_INLINE void rhino_stack_check_init(void) { #if (RHINO_CONFIG_INTRPT_STACK_OVF_CHECK > 0) #if (RHINO_CONFIG_CPU_STACK_DOWN > 0) g_intrpt_stack_bottom = (cpu_stack_t *)RHINO_CONFIG_INTRPT_STACK_TOP; *g_intrpt_stack_bottom = RHINO_INTRPT_STACK_OVF_MAGIC; #else g_intrpt_stack_top = (cpu_stack_t *)RHINO_CONFIG_INTRPT_STACK_TOP; *g_intrpt_stack_top = RHINO_INTRPT_STACK_OVF_MAGIC; #endif #endif /* RHINO_CONFIG_INTRPT_STACK_OVF_CHECK */ #if (RHINO_CONFIG_STACK_OVF_CHECK_HW != 0) cpu_intrpt_stack_protect(); #endif } kstat_t krhino_init(void) { #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) kstat_t ret; #endif g_sys_stat = RHINO_STOPPED; g_task_id = 0; #if (RHINO_CONFIG_CPU_NUM > 1) krhino_spin_lock_init(&g_sys_lock); klist_init(&g_task_del_head); #endif runqueue_init(&g_ready_queue); tick_list_init(); #if (RHINO_CONFIG_KOBJ_LIST > 0) kobj_list_init(); #endif #if (RHINO_CONFIG_USER_HOOK > 0) krhino_init_hook(); #endif #if (RHINO_CONFIG_MM_TLF > 0) k_mm_init(); #endif #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) klist_init(&g_res_list); ret = krhino_sem_create(&g_res_sem, "res_sem", 0); if (ret != RHINO_SUCCESS) { return ret; } dyn_mem_proc_task_start(); #endif #if (RHINO_CONFIG_CPU_NUM > 1) for (uint8_t i = 0; i < RHINO_CONFIG_CPU_NUM; i++) { krhino_task_cpu_create(&g_idle_task[i], "idle_task", NULL, RHINO_IDLE_PRI, 0, &g_idle_task_stack[i][0], RHINO_CONFIG_IDLE_TASK_STACK_SIZE, idle_task, i, 1u); } #else krhino_task_create(&g_idle_task[0], "idle_task", NULL, RHINO_IDLE_PRI, 0, &g_idle_task_stack[0][0], RHINO_CONFIG_IDLE_TASK_STACK_SIZE, idle_task, 1u); #endif #if (RHINO_CONFIG_WORKQUEUE > 0) workqueue_init(); #endif #if (RHINO_CONFIG_TIMER > 0) ktimer_init(); #endif #if (RHINO_CONFIG_CPU_USAGE_STATS > 0) cpu_usage_stats_start(); #endif rhino_stack_check_init(); return RHINO_SUCCESS; } kstat_t krhino_start(void) { ktask_t *preferred_task; if (g_sys_stat == RHINO_STOPPED) { #if (RHINO_CONFIG_CPU_NUM > 1) for (uint8_t i = 0; i < RHINO_CONFIG_CPU_NUM; i++) { preferred_task = preferred_cpu_ready_task_get(&g_ready_queue, i); preferred_task->cpu_num = i; preferred_task->cur_exc = 1; g_preferred_ready_task[i] = preferred_task; g_active_task[i] = g_preferred_ready_task[i]; g_active_task[i]->cur_exc = 1; } #else preferred_task = preferred_cpu_ready_task_get(&g_ready_queue, 0); g_preferred_ready_task[0] = preferred_task; g_active_task[0] = preferred_task; #endif #if (RHINO_CONFIG_USER_HOOK > 0) krhino_start_hook(); #endif g_sys_stat = RHINO_RUNNING; cpu_first_task_start(); /* should not be here */ return RHINO_SYS_FATAL_ERR; } return RHINO_RUNNING; } #if (RHINO_CONFIG_INTRPT_STACK_OVF_CHECK > 0) #if (RHINO_CONFIG_CPU_STACK_DOWN > 0) void krhino_intrpt_stack_ovf_check(void) { if (*g_intrpt_stack_bottom != RHINO_INTRPT_STACK_OVF_MAGIC) { k_err_proc(RHINO_INTRPT_STACK_OVF); } } #else void krhino_intrpt_stack_ovf_check(void) { if (*g_intrpt_stack_top != RHINO_INTRPT_STACK_OVF_MAGIC) { k_err_proc(RHINO_INTRPT_STACK_OVF); } } #endif #endif /* RHINO_CONFIG_INTRPT_STACK_OVF_CHECK */ kstat_t krhino_intrpt_enter(void) { CPSR_ALLOC(); TRACE_INTRPT_ENTETR(); #if (RHINO_CONFIG_INTRPT_STACK_OVF_CHECK > 0) krhino_intrpt_stack_ovf_check(); #endif RHINO_CPU_INTRPT_DISABLE(); g_intrpt_nested_level[cpu_cur_get()]++; RHINO_CPU_INTRPT_ENABLE(); #if (RHINO_CONFIG_PWRMGMT > 0) cpu_pwr_up(); #endif return RHINO_SUCCESS; } void krhino_intrpt_exit(void) { CPSR_ALLOC(); uint8_t cur_cpu_num; ktask_t *preferred_task; #if (RHINO_CONFIG_SCHED_CFS > 0) lr_timer_t cur_task_exec_time; #endif TRACE_INTRPT_EXIT(); #if (RHINO_CONFIG_INTRPT_STACK_OVF_CHECK > 0) krhino_intrpt_stack_ovf_check(); #endif RHINO_CPU_INTRPT_DISABLE(); cur_cpu_num = cpu_cur_get(); g_intrpt_nested_level[cur_cpu_num]--; if (g_intrpt_nested_level[cur_cpu_num] > 0u) { RHINO_CPU_INTRPT_ENABLE(); return; } if (g_per_cpu[cur_cpu_num].dis_sched > 0u) { g_per_cpu[cur_cpu_num].dis_sched = 0u; RHINO_CPU_INTRPT_ENABLE(); return; } if (g_sched_lock[cur_cpu_num] > 0u) { RHINO_CPU_INTRPT_ENABLE(); return; } preferred_task = preferred_cpu_ready_task_get(&g_ready_queue, cur_cpu_num); #if (RHINO_CONFIG_SCHED_CFS > 0) if (preferred_task == &g_idle_task[cur_cpu_num]) { if (g_active_task[cur_cpu_num]->sched_policy == KSCHED_CFS) { if (g_active_task[cur_cpu_num]->task_state == K_RDY) { cur_task_exec_time = g_active_task[cur_cpu_num]->task_time_this_run + (LR_COUNT_GET() - g_active_task[cur_cpu_num]->task_time_start); if (cur_task_exec_time < MIN_TASK_RUN_TIME) { RHINO_CPU_INTRPT_ENABLE(); return; } cfs_node_insert(&g_active_task[cur_cpu_num]->node, cur_task_exec_time); } } preferred_task = cfs_preferred_task_get(); if (preferred_task == 0) { preferred_task = &g_idle_task[cur_cpu_num]; } } else { if (g_active_task[cur_cpu_num]->sched_policy == KSCHED_CFS) { if (g_active_task[cur_cpu_num]->task_state == K_RDY) { cur_task_exec_time = g_active_task[cur_cpu_num]->task_time_this_run + (LR_COUNT_GET() - g_active_task[cur_cpu_num]->task_time_start); cfs_node_insert(&g_active_task[cur_cpu_num]->node, cur_task_exec_time); } } } if (preferred_task->sched_policy == KSCHED_CFS) { cfs_node_del(&preferred_task->node); } #endif if (preferred_task == g_active_task[cur_cpu_num]) { RHINO_CPU_INTRPT_ENABLE(); return; } TRACE_INTRPT_TASK_SWITCH(g_active_task[cur_cpu_num], preferred_task); #if (RHINO_SCHED_NONE_PREEMPT > 0) if (g_active_task[cur_cpu_num] == &g_idle_task[cur_cpu_num]) { #endif #if (RHINO_CONFIG_CPU_NUM > 1) g_active_task[cur_cpu_num]->cur_exc = 0; preferred_task->cpu_num = cur_cpu_num; preferred_task->cur_exc = 1; #endif g_preferred_ready_task[cur_cpu_num] = preferred_task; cpu_intrpt_switch(); #if (RHINO_SCHED_NONE_PREEMPT > 0) } #endif RHINO_CPU_INTRPT_ENABLE(); } tick_t krhino_next_sleep_ticks_get(void) { CPSR_ALLOC(); klist_t *tick_head; ktask_t *tcb; klist_t *iter; tick_t ticks; tick_head = &g_tick_head; RHINO_CRITICAL_ENTER(); if (tick_head->next == &g_tick_head) { RHINO_CRITICAL_EXIT(); return RHINO_WAIT_FOREVER; } iter = tick_head->next; tcb = krhino_list_entry(iter, ktask_t, tick_list); ticks = tcb->tick_match - g_tick_count; RHINO_CRITICAL_EXIT(); return ticks; } size_t krhino_global_space_get(void) { size_t mem; mem = sizeof(g_sys_stat) + sizeof(g_idle_task_spawned) + sizeof(g_ready_queue) + sizeof(g_sched_lock) + sizeof(g_intrpt_nested_level) + sizeof(g_preferred_ready_task) + sizeof(g_active_task) + sizeof(g_idle_task) + sizeof(g_idle_task_stack) + sizeof(g_tick_head) + sizeof(g_tick_count) + sizeof(g_idle_count); #if (RHINO_CONFIG_TIMER > 0) mem += sizeof(g_timer_head) + sizeof(g_timer_count) + sizeof(g_timer_task) + sizeof(g_timer_task_stack) + sizeof(g_timer_queue) + sizeof(timer_queue_cb); #endif #if (RHINO_CONFIG_KOBJ_LIST > 0) mem += sizeof(g_kobj_list); #endif return mem; } uint32_t krhino_version_get(void) { return RHINO_VERSION; }
YifuLiu/AliOS-Things
kernel/rhino/k_sys.c
C
apache-2.0
8,131
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "k_api.h" #if (RHINO_CONFIG_SCHED_CFS > 0) static void task_policy_change(ktask_t *task, uint8_t new_pri) { if ((new_pri >= RT_MIN_PRI) && (new_pri <= RT_MAX_PRI)) { if (task->sched_policy == KSCHED_CFS) { task->sched_policy = KSCHED_FIFO; } } else { task->sched_policy = KSCHED_CFS; } } static kstat_t task_policy_check(uint8_t prio, uint8_t policy) { kstat_t err; err = RHINO_SUCCESS; switch (policy) { case KSCHED_FIFO: case KSCHED_RR: if (prio > RT_MAX_PRI) { if (prio != RHINO_IDLE_PRI) { err = RHINO_INV_PARAM; } } break; case KSCHED_CFS: if (prio <= RT_MAX_PRI) { err = RHINO_INV_PARAM; } break; default: k_err_proc(RHINO_INV_TASK_STATE); err = RHINO_INV_TASK_STATE; } return err; } #endif static kstat_t task_create(ktask_t *task, const name_t *name, void *arg, uint8_t prio, tick_t ticks, cpu_stack_t *stack_buf, size_t stack_size, task_entry_t entry, uint8_t autorun, uint8_t mm_alloc_flag, uint8_t cpu_num, uint8_t cpu_binded, uint8_t sched_policy) { CPSR_ALLOC(); cpu_stack_t *tmp; uint8_t i = 0; (void)cpu_binded; (void)i; NULL_PARA_CHK(task); NULL_PARA_CHK(name); NULL_PARA_CHK(entry); NULL_PARA_CHK(stack_buf); if (stack_size == 0u) { return RHINO_TASK_INV_STACK_SIZE; } if (prio >= RHINO_CONFIG_PRI_MAX) { return RHINO_BEYOND_MAX_PRI; } #if (RHINO_CONFIG_SCHED_CFS > 0) if (task_policy_check(prio, sched_policy) != RHINO_SUCCESS) { return task_policy_check(prio, sched_policy); } #endif RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); /* idle task is only allowed to create once */ if (prio == RHINO_IDLE_PRI) { if (g_idle_task_spawned[cpu_num] > 0u) { RHINO_CRITICAL_EXIT(); return RHINO_IDLE_TASK_EXIST; } g_idle_task_spawned[cpu_num] = 1u; } RHINO_CRITICAL_EXIT(); memset(task, 0, sizeof(ktask_t)); #if (RHINO_CONFIG_SCHED_RR > 0) if (ticks > 0u) { task->time_total = ticks; } else { task->time_total = RHINO_CONFIG_TIME_SLICE_DEFAULT; } task->time_slice = task->time_total; #endif task->sched_policy = sched_policy; if (autorun > 0u) { task->task_state = K_RDY; } else { task->task_state = K_SUSPENDED; task->suspend_count = 1u; } /* init all the stack element to 0 */ task->task_stack_base = stack_buf; tmp = stack_buf; memset(tmp, 0, stack_size * sizeof(cpu_stack_t)); klist_init(&task->tick_list); task->task_name = name; task->prio = prio; task->b_prio = prio; task->stack_size = stack_size; task->mm_alloc_flag = mm_alloc_flag; task->cpu_num = cpu_num; task->task_id = ++g_task_id; #if (RHINO_CONFIG_MM_DEBUG > 0) task->task_alloc_size = 0; #endif #if (RHINO_CONFIG_USER_SPACE > 0) task->mode = 0; task->pid = 0; task->task_ustack_base = 0; task->task_group = 0; #endif #if (RHINO_CONFIG_CPU_NUM > 1) task->cpu_binded = cpu_binded; #endif #if (RHINO_CONFIG_TASK_STACK_OVF_CHECK > 0) #if (RHINO_CONFIG_CPU_STACK_DOWN > 0) tmp = task->task_stack_base; for (i = 0; i < RHINO_CONFIG_STK_CHK_WORDS; i++) { *tmp++ = RHINO_TASK_STACK_OVF_MAGIC; } #else tmp = (cpu_stack_t *)(task->task_stack_base) + task->stack_size - RHINO_CONFIG_STK_CHK_WORDS; for (i = 0; i < RHINO_CONFIG_STK_CHK_WORDS; i++) { *tmp++ = RHINO_TASK_STACK_OVF_MAGIC; } #endif #endif task->task_stack = cpu_task_stack_init(stack_buf, stack_size, arg, entry); #if (RHINO_CONFIG_USER_HOOK > 0) krhino_task_create_hook(task); #endif TRACE_TASK_CREATE(task); RHINO_CRITICAL_ENTER(); #if (RHINO_CONFIG_KOBJ_LIST > 0) klist_insert(&(g_kobj_list.task_head), &task->task_stats_item); #endif if (autorun > 0u) { ready_list_add_tail(&g_ready_queue, task); /* if system is not start,not call core_sched */ if (g_sys_stat == RHINO_RUNNING) { RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } } RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } kstat_t krhino_task_create(ktask_t *task, const name_t *name, void *arg, uint8_t prio, tick_t ticks, cpu_stack_t *stack_buf, size_t stack_size, task_entry_t entry, uint8_t autorun) { return task_create(task, name, arg, prio, ticks, stack_buf, stack_size, entry, autorun, K_OBJ_STATIC_ALLOC, 0, 0, KSCHED_RR); } #if (RHINO_CONFIG_SCHED_CFS > 0) kstat_t krhino_cfs_task_create(ktask_t *task, const name_t *name, void *arg, uint8_t prio, cpu_stack_t *stack_buf, size_t stack_size, task_entry_t entry, uint8_t autorun) { return task_create(task, name, arg, prio, 0, stack_buf, stack_size, entry, autorun, K_OBJ_STATIC_ALLOC, 0, 0, KSCHED_CFS); } #endif #if (RHINO_CONFIG_CPU_NUM > 1) kstat_t krhino_task_cpu_create(ktask_t *task, const name_t *name, void *arg, uint8_t prio, tick_t ticks, cpu_stack_t *stack_buf, size_t stack_size, task_entry_t entry, uint8_t cpu_num, uint8_t autorun) { return task_create(task, name, arg, prio, ticks, stack_buf, stack_size, entry, autorun, K_OBJ_STATIC_ALLOC, cpu_num, 1, KSCHED_RR); } #if (RHINO_CONFIG_SCHED_CFS > 0) kstat_t krhino_cfs_task_cpu_create(ktask_t *task, const name_t *name, void *arg, uint8_t prio, cpu_stack_t *stack_buf, size_t stack_size, task_entry_t entry, uint8_t cpu_num, uint8_t autorun) { return task_create(task, name, arg, prio, 0, stack_buf, stack_size, entry, autorun, K_OBJ_STATIC_ALLOC, cpu_num, 1, KSCHED_CFS); } #endif kstat_t krhino_task_cpu_bind(ktask_t *task, uint8_t cpu_num) { CPSR_ALLOC(); ktask_t *task_cur; RHINO_CRITICAL_ENTER(); task_cur = g_active_task[cpu_cur_get()]; if (task != task_cur) { RHINO_CRITICAL_EXIT(); return RHINO_INV_PARAM; } task->cpu_num = cpu_num; task->cpu_binded = 1u; RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } kstat_t krhino_task_cpu_unbind(ktask_t *task) { CPSR_ALLOC(); ktask_t *task_cur; RHINO_CRITICAL_ENTER(); task_cur = g_active_task[cpu_cur_get()]; if (task != task_cur) { RHINO_CRITICAL_EXIT(); return RHINO_INV_PARAM; } task->cpu_binded = 0u; RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } #endif #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) static kstat_t task_dyn_create(ktask_t **task, const name_t *name, void *arg, uint8_t pri, tick_t ticks, size_t stack, task_entry_t entry, uint8_t cpu_num, uint8_t cpu_binded, uint8_t autorun, uint8_t sched_policy) { kstat_t ret; cpu_stack_t *task_stack; ktask_t *task_obj; NULL_PARA_CHK(task); if (stack == 0) { return RHINO_INV_PARAM; } task_stack = krhino_mm_alloc(stack * sizeof(cpu_stack_t)); if (task_stack == NULL) { return RHINO_NO_MEM; } task_obj = krhino_mm_alloc(sizeof(ktask_t)); if (task_obj == NULL) { krhino_mm_free(task_stack); return RHINO_NO_MEM; } *task = task_obj; ret = task_create(task_obj, name, arg, pri, ticks, task_stack, stack, entry, autorun, K_OBJ_DYN_ALLOC, cpu_num, cpu_binded, sched_policy); if ((ret != RHINO_SUCCESS) && (ret != RHINO_STOPPED)) { krhino_mm_free(task_stack); krhino_mm_free(task_obj); *task = NULL; return ret; } return ret; } kstat_t krhino_task_dyn_create(ktask_t **task, const name_t *name, void *arg, uint8_t pri, tick_t ticks, size_t stack, task_entry_t entry, uint8_t autorun) { return task_dyn_create(task, name, arg, pri, ticks, stack, entry, 0, 0, autorun, KSCHED_RR); } #if (RHINO_CONFIG_SCHED_CFS > 0) kstat_t krhino_cfs_task_dyn_create(ktask_t **task, const name_t *name, void *arg, uint8_t pri, size_t stack, task_entry_t entry, uint8_t autorun) { return task_dyn_create(task, name, arg, pri, 0, stack, entry, 0, 0, autorun, KSCHED_CFS); } #endif #if (RHINO_CONFIG_CPU_NUM > 1) kstat_t krhino_task_cpu_dyn_create(ktask_t **task, const name_t *name, void *arg, uint8_t pri, tick_t ticks, size_t stack, task_entry_t entry, uint8_t cpu_num, uint8_t autorun) { return task_dyn_create(task, name, arg, pri, ticks, stack, entry, cpu_num, 1, autorun, KSCHED_RR); } #if (RHINO_CONFIG_SCHED_CFS > 0) kstat_t krhino_cfs_task_cpu_dyn_create(ktask_t **task, const name_t *name, void *arg, uint8_t pri, size_t stack, task_entry_t entry, uint8_t cpu_num, uint8_t autorun) { return task_dyn_create(task, name, arg, pri, 0, stack, entry, cpu_num, 1, autorun, KSCHED_CFS); } #endif #endif #endif kstat_t krhino_task_sleep(tick_t ticks) { CPSR_ALLOC(); uint8_t cur_cpu_num; kstat_t ret; if (ticks == 0u) { return RHINO_INV_PARAM; } RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); cur_cpu_num = cpu_cur_get(); /* system is locked so task can not be blocked just return immediately */ if (g_sched_lock[cur_cpu_num] > 0u) { RHINO_CRITICAL_EXIT(); return RHINO_SCHED_DISABLE; } g_active_task[cur_cpu_num]->task_state = K_SLEEP; tick_list_insert(g_active_task[cur_cpu_num], ticks); ready_list_rm(&g_ready_queue, g_active_task[cur_cpu_num]); TRACE_TASK_SLEEP(g_active_task[cur_cpu_num], ticks); RHINO_CRITICAL_EXIT_SCHED(); RHINO_CPU_INTRPT_DISABLE(); /* is task timeout normally after sleep */ ret = pend_state_end_proc(g_active_task[cpu_cur_get()], NULL); RHINO_CPU_INTRPT_ENABLE(); return ret; } kstat_t krhino_task_yield(void) { CPSR_ALLOC(); /* make current task to the end of ready list */ RHINO_CRITICAL_ENTER(); ready_list_head_to_tail(&g_ready_queue, g_active_task[cpu_cur_get()]); RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } ktask_t *krhino_cur_task_get(void) { CPSR_ALLOC(); ktask_t *task; RHINO_CRITICAL_ENTER(); task = g_active_task[cpu_cur_get()]; RHINO_CRITICAL_EXIT(); return task; } kstat_t task_suspend(ktask_t *task) { CPSR_ALLOC(); uint8_t cur_cpu_num; RHINO_CRITICAL_ENTER(); cur_cpu_num = cpu_cur_get(); #if (RHINO_CONFIG_CPU_NUM > 1) if (task->cpu_num != cur_cpu_num) { if (task->cur_exc == 1) { RHINO_CRITICAL_EXIT(); return RHINO_TRY_AGAIN; } } #endif if (task == g_active_task[cur_cpu_num]) { if (g_sched_lock[cur_cpu_num] > 0u) { RHINO_CRITICAL_EXIT(); return RHINO_SCHED_DISABLE; } } switch (task->task_state) { case K_RDY: task->suspend_count = 1u; task->task_state = K_SUSPENDED; ready_list_rm(&g_ready_queue, task); break; case K_SLEEP: task->suspend_count = 1u; task->task_state = K_SLEEP_SUSPENDED; break; case K_PEND: task->suspend_count = 1u; task->task_state = K_PEND_SUSPENDED; break; case K_SUSPENDED: case K_SLEEP_SUSPENDED: case K_PEND_SUSPENDED: if (task->suspend_count == (suspend_nested_t) -1) { RHINO_CRITICAL_EXIT(); return RHINO_SUSPENDED_COUNT_OVF; } task->suspend_count++; break; case K_SEED: default: RHINO_CRITICAL_EXIT(); return RHINO_INV_TASK_STATE; } TRACE_TASK_SUSPEND(g_active_task[cur_cpu_num], task); RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } kstat_t krhino_task_suspend(ktask_t *task) { if (task == NULL) { return RHINO_NULL_PTR; } if (task->prio == RHINO_IDLE_PRI) { return RHINO_TASK_SUSPEND_NOT_ALLOWED; } return task_suspend(task); } kstat_t task_resume(ktask_t *task) { CPSR_ALLOC(); RHINO_CRITICAL_ENTER(); switch (task->task_state) { case K_RDY: case K_SLEEP: case K_PEND: RHINO_CRITICAL_EXIT(); return RHINO_TASK_NOT_SUSPENDED; case K_SUSPENDED: task->suspend_count--; if (task->suspend_count == 0u) { /* Make task ready */ task->task_state = K_RDY; ready_list_add(&g_ready_queue, task); } break; case K_SLEEP_SUSPENDED: task->suspend_count--; if (task->suspend_count == 0u) { task->task_state = K_SLEEP; } break; case K_PEND_SUSPENDED: task->suspend_count--; if (task->suspend_count == 0u) { task->task_state = K_PEND; } break; case K_SEED: default: RHINO_CRITICAL_EXIT(); return RHINO_INV_TASK_STATE; } TRACE_TASK_RESUME(g_active_task[cpu_cur_get()], task); RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } kstat_t krhino_task_resume(ktask_t *task) { NULL_PARA_CHK(task); return task_resume(task); } kstat_t krhino_task_stack_min_free(ktask_t *task, size_t *free) { cpu_stack_t *task_stack; size_t free_stk = 0; NULL_PARA_CHK(task); NULL_PARA_CHK(free); if (task->task_state == K_DELETED) { return RHINO_INV_TASK_STATE; } #if (RHINO_CONFIG_CPU_STACK_DOWN > 0) task_stack = task->task_stack_base + RHINO_CONFIG_STK_CHK_WORDS; while (*task_stack++ == 0u) { free_stk++; } #else task_stack = (cpu_stack_t *)(task->task_stack_base) + task->stack_size - RHINO_CONFIG_STK_CHK_WORDS - 1u; while (*task_stack-- == 0u) { free_stk++; } #endif *free = free_stk; return RHINO_SUCCESS; } kstat_t task_pri_change(ktask_t *task, uint8_t new_pri) { uint8_t old_pri; uint8_t task_exec; kmutex_t *mutex_tmp; ktask_t *mutex_task; do { if (task->prio != new_pri) { switch (task->task_state) { case K_RDY: task_exec = is_task_exec(task); if (task_exec > 0u) { if (task->sched_policy != KSCHED_CFS) { ready_list_rm(&g_ready_queue, task); } } else { ready_list_rm(&g_ready_queue, task); } #if (RHINO_CONFIG_SCHED_CFS > 0) task_policy_change(task, new_pri); #endif task->prio = new_pri; if (task_exec > 0u) { if (task->sched_policy != KSCHED_CFS) { ready_list_add_head(&g_ready_queue, task); } } else { ready_list_add_tail(&g_ready_queue, task); } task = NULL; break; case K_SLEEP: case K_SUSPENDED: case K_SLEEP_SUSPENDED: #if (RHINO_CONFIG_SCHED_CFS > 0) task_policy_change(task, new_pri); #endif /* set new task prio */ task->prio = new_pri; task = NULL; break; case K_PEND: case K_PEND_SUSPENDED: #if (RHINO_CONFIG_SCHED_CFS > 0) task_policy_change(task, new_pri); #endif old_pri = task->prio; task->prio = new_pri; pend_list_reorder(task); if (task->blk_obj->obj_type == RHINO_MUTEX_OBJ_TYPE) { mutex_tmp = (kmutex_t *)(task->blk_obj); mutex_task = mutex_tmp->mutex_task; if (mutex_task->prio > task->prio) { /* since the highest prio of the lock wait task became higher, raise the lock get task prio higher */ task = mutex_task; } else if (mutex_task->prio == old_pri) { /* find suitable tcb prio */ new_pri = mutex_pri_look(mutex_task, 0); if (new_pri != mutex_task->prio) { /* Change prio of lock get task */ task = mutex_task; } else { task = NULL; } } else { task = NULL; } } else { task = NULL; } break; default: k_err_proc(RHINO_INV_TASK_STATE); return RHINO_INV_TASK_STATE; } } else { task = NULL; } } while (task != NULL); return RHINO_SUCCESS; } kstat_t krhino_task_pri_change(ktask_t *task, uint8_t pri, uint8_t *old_pri) { CPSR_ALLOC(); uint8_t pri_limit; kstat_t error; NULL_PARA_CHK(task); NULL_PARA_CHK(old_pri); /* idle task is not allowed to change prio */ if (task->prio >= RHINO_IDLE_PRI) { return RHINO_PRI_CHG_NOT_ALLOWED; } /* not allowed change to idle prio */ if (pri >= RHINO_IDLE_PRI) { return RHINO_PRI_CHG_NOT_ALLOWED; } /* deleted task is not allowed to change prio */ if (task->task_state == K_DELETED) { return RHINO_INV_TASK_STATE; } RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); /* limit the prio change by mutex at task prio change */ pri_limit = mutex_pri_limit(task, pri); task->b_prio = pri; /* new pripority may change here */ pri = pri_limit; *old_pri = task->prio; error = task_pri_change(task, pri); if (error != RHINO_SUCCESS) { RHINO_CRITICAL_EXIT(); return error; } TRACE_TASK_PRI_CHANGE(g_active_task[cpu_cur_get()], task, pri); RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } kstat_t krhino_task_wait_abort(ktask_t *task) { CPSR_ALLOC(); NULL_PARA_CHK(task); RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); switch (task->task_state) { case K_RDY: break; case K_SUSPENDED: /* change to ready state */ task->task_state = K_RDY; ready_list_add(&g_ready_queue, task); break; case K_SLEEP: case K_SLEEP_SUSPENDED: /* change to ready state */ tick_list_rm(task); ready_list_add(&g_ready_queue, task); task->task_state = K_RDY; task->blk_state = BLK_ABORT; break; case K_PEND_SUSPENDED: case K_PEND: /* remove task on the tick list because task is woken up */ tick_list_rm(task); /* remove task on the block list because task is woken up */ klist_rm(&task->task_list); /* add to the ready list again */ ready_list_add(&g_ready_queue, task); task->task_state = K_RDY; task->blk_state = BLK_ABORT; mutex_task_pri_reset(task); task->blk_obj = NULL; break; default: RHINO_CRITICAL_EXIT(); return RHINO_INV_TASK_STATE; } #if (RHINO_CONFIG_USER_HOOK > 0) krhino_task_abort_hook(task); #endif TRACE_TASK_WAIT_ABORT(g_active_task[cpu_cur_get()], task); RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } #if (RHINO_CONFIG_TASK_DEL > 0) static void task_mutex_free(ktask_t *task) { kmutex_t *mutex; kmutex_t *next_mutex; ktask_t *next_task; klist_t *blk_list_head; next_mutex = task->mutex_list; while ((mutex = next_mutex) != NULL) { next_mutex = mutex->mutex_list; blk_list_head = &mutex->blk_obj.blk_list; if (!is_klist_empty(blk_list_head)) { next_task = krhino_list_entry(blk_list_head->next, ktask_t, task_list); /* wakeup wait task */ pend_task_wakeup(next_task); /* change mutex get task */ mutex->mutex_task = next_task; mutex->mutex_list = next_task->mutex_list; next_task->mutex_list = mutex; } else { /* no wait task */ mutex->mutex_task = NULL; } } } kstat_t krhino_task_del(ktask_t *task) { CPSR_ALLOC(); uint8_t cur_cpu_num; #if (RHINO_CONFIG_USER_HOOK > 0) res_free_t *res_free; #endif #if (RHINO_CONFIG_NEWLIBC_REENT > 0) krhino_sched_disable(); if (task == NULL) { cur_cpu_num = cpu_cur_get(); task = g_active_task[cur_cpu_num]; } if (task->newlibc_reent != NULL) { /* Reclaiming reent may takes few long time as it may flush io, * so don't disable interrupt. */ _reclaim_reent(task->newlibc_reent); krhino_mm_free(task->newlibc_reent); task->newlibc_reent = NULL; } krhino_sched_enable(); #endif RHINO_CRITICAL_ENTER(); cur_cpu_num = cpu_cur_get(); INTRPT_NESTED_LEVEL_CHK(); if (task == NULL) { task = g_active_task[cur_cpu_num]; } if (task->prio == RHINO_IDLE_PRI) { RHINO_CRITICAL_EXIT(); return RHINO_TASK_DEL_NOT_ALLOWED; } if (task->mm_alloc_flag != K_OBJ_STATIC_ALLOC) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_DEL_ERR; } #if (RHINO_CONFIG_CPU_NUM > 1) if (task->cpu_num != cur_cpu_num) { if (task->cur_exc == 1) { klist_insert(&g_task_del_head, &task->task_del_item); RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } } #endif if (task == g_active_task[cpu_cur_get()]) { if (g_sched_lock[cpu_cur_get()] > 0u) { RHINO_CRITICAL_EXIT(); return RHINO_SCHED_DISABLE; } } /* free all the mutex which task hold */ task_mutex_free(task); switch (task->task_state) { case K_RDY: ready_list_rm(&g_ready_queue, task); task->task_state = K_DELETED; break; case K_SUSPENDED: task->task_state = K_DELETED; break; case K_SLEEP: case K_SLEEP_SUSPENDED: tick_list_rm(task); task->task_state = K_DELETED; break; case K_PEND: case K_PEND_SUSPENDED: tick_list_rm(task); klist_rm(&task->task_list); task->task_state = K_DELETED; mutex_task_pri_reset(task); break; default: RHINO_CRITICAL_EXIT(); return RHINO_INV_TASK_STATE; } #if (RHINO_CONFIG_KOBJ_LIST > 0) klist_rm(&task->task_stats_item); #endif TRACE_TASK_DEL(g_active_task[cur_cpu_num], task); #if (RHINO_CONFIG_USER_HOOK > 0) #if (RHINO_CONFIG_CPU_STACK_DOWN > 0) res_free = (res_free_t *)(task->task_stack_base + RHINO_CONFIG_STK_CHK_WORDS); #else res_free = (res_free_t *)(task->task_stack_base + task->stack_size - (sizeof(res_free_t) / sizeof(cpu_stack_t)) - RHINO_CONFIG_STK_CHK_WORDS); #endif res_free->cnt = 0; krhino_task_del_hook(task, res_free); #endif RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) kstat_t krhino_task_dyn_del(ktask_t *task) { CPSR_ALLOC(); kstat_t ret; uint8_t cur_cpu_num; res_free_t *res_free; #if (RHINO_CONFIG_NEWLIBC_REENT > 0) krhino_sched_disable(); if (task == NULL) { cur_cpu_num = cpu_cur_get(); task = g_active_task[cur_cpu_num]; } if (task->newlibc_reent != NULL) { /* Reclaiming reent may takes few long time as it may flush io, * so don't disable interrupt. */ _reclaim_reent(task->newlibc_reent); krhino_mm_free(task->newlibc_reent); task->newlibc_reent = NULL; } krhino_sched_enable(); #endif RHINO_CRITICAL_ENTER(); cur_cpu_num = cpu_cur_get(); INTRPT_NESTED_LEVEL_CHK(); if (task == NULL) { task = g_active_task[cur_cpu_num]; } if (task->prio == RHINO_IDLE_PRI) { RHINO_CRITICAL_EXIT(); return RHINO_TASK_DEL_NOT_ALLOWED; } if (task->mm_alloc_flag != K_OBJ_DYN_ALLOC) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_DEL_ERR; } #if (RHINO_CONFIG_CPU_NUM > 1) if (task->cpu_num != cur_cpu_num) { if (task->cur_exc == 1) { klist_insert(&g_task_del_head, &task->task_del_item); RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } } #endif if (task == g_active_task[cpu_cur_get()]) { if (g_sched_lock[cpu_cur_get()] > 0u) { RHINO_CRITICAL_EXIT(); return RHINO_SCHED_DISABLE; } } if (task->task_state == K_DELETED) { RHINO_CRITICAL_EXIT(); return RHINO_INV_TASK_STATE; } #if (RHINO_CONFIG_CPU_STACK_DOWN > 0) res_free = (res_free_t *)(task->task_stack_base + RHINO_CONFIG_STK_CHK_WORDS); #else res_free = (res_free_t *)(task->task_stack_base + task->stack_size - (sizeof(res_free_t) / sizeof(cpu_stack_t)) - RHINO_CONFIG_STK_CHK_WORDS); #endif res_free->cnt = 0; g_sched_lock[cpu_cur_get()]++; klist_insert(&g_res_list, &res_free->res_list); res_free->res[0] = task->task_stack_base; res_free->res[1] = task; res_free->cnt += 2; ret = krhino_sem_give(&g_res_sem); g_sched_lock[cpu_cur_get()]--; if (ret != RHINO_SUCCESS) { RHINO_CRITICAL_EXIT(); k_err_proc(RHINO_SYS_SP_ERR); return ret; } /* free all the mutex which task hold */ task_mutex_free(task); switch (task->task_state) { case K_RDY: ready_list_rm(&g_ready_queue, task); task->task_state = K_DELETED; break; case K_SUSPENDED: task->task_state = K_DELETED; break; case K_SLEEP: case K_SLEEP_SUSPENDED: tick_list_rm(task); task->task_state = K_DELETED; break; case K_PEND: case K_PEND_SUSPENDED: tick_list_rm(task); klist_rm(&task->task_list); task->task_state = K_DELETED; mutex_task_pri_reset(task); break; case K_SEED: default: break; } #if (RHINO_CONFIG_KOBJ_LIST > 0) klist_rm(&task->task_stats_item); #endif TRACE_TASK_DEL(g_active_task[cpu_cur_get()], task); #if (RHINO_CONFIG_USER_HOOK > 0) krhino_task_del_hook(task, res_free); #endif RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } #endif kstat_t krhino_task_cancel(ktask_t *task) { CPSR_ALLOC(); kstat_t ret; NULL_PARA_CHK(task); RHINO_CRITICAL_ENTER(); task->cancel = 1u; ret = krhino_task_wait_abort(task); RHINO_CRITICAL_EXIT(); return ret; } RHINO_BOOL krhino_task_cancel_chk(void) { CPSR_ALLOC(); ktask_t *cur_task; RHINO_BOOL ret; cur_task = krhino_cur_task_get(); RHINO_CRITICAL_ENTER(); if (cur_task->cancel == 1u) { ret = RHINO_TRUE; } else { ret = RHINO_FALSE; } RHINO_CRITICAL_EXIT(); return ret; } #endif #if (RHINO_CONFIG_SCHED_RR > 0) kstat_t krhino_task_time_slice_set(ktask_t *task, size_t slice) { CPSR_ALLOC(); NULL_PARA_CHK(task); RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); if (slice > 0u) { /* assign the new time slice */ task->time_total = slice; } else { /* assign the default time slice */ task->time_total = RHINO_CONFIG_TIME_SLICE_DEFAULT; } task->time_slice = task->time_total; RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } kstat_t krhino_sched_param_set(ktask_t *task, uint8_t policy, uint8_t pri) { CPSR_ALLOC(); uint8_t old_pri; kstat_t ret; (void)ret; NULL_PARA_CHK(task); if ((policy != KSCHED_FIFO) && (policy != KSCHED_RR) && (policy != KSCHED_CFS)) { return RHINO_INV_SCHED_WAY; } #if (RHINO_CONFIG_SCHED_CFS > 0) ret = task_policy_check(pri, policy); if (ret != RHINO_SUCCESS) { return ret; } #endif krhino_sched_disable(); RHINO_CRITICAL_ENTER(); krhino_task_pri_change(task, pri, &old_pri); task->sched_policy = policy; RHINO_CRITICAL_EXIT(); krhino_sched_enable(); return RHINO_SUCCESS; } kstat_t krhino_sched_policy_set(ktask_t *task, uint8_t policy) { NULL_PARA_CHK(task); return krhino_sched_param_set(task, policy, task->prio); } kstat_t krhino_sched_policy_get(ktask_t *task, uint8_t *policy) { CPSR_ALLOC(); NULL_PARA_CHK(task); NULL_PARA_CHK(policy); RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); *policy = task->sched_policy; RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } #endif #if (RHINO_CONFIG_TASK_INFO > 0) kstat_t krhino_task_info_set(ktask_t *task, size_t idx, void *info) { CPSR_ALLOC(); NULL_PARA_CHK(task); if (idx >= RHINO_CONFIG_TASK_INFO_NUM) { return RHINO_INV_PARAM; } RHINO_CPU_INTRPT_DISABLE(); task->user_info[idx] = info; RHINO_CPU_INTRPT_ENABLE(); return RHINO_SUCCESS; } kstat_t krhino_task_info_get(ktask_t *task, size_t idx, void **info) { NULL_PARA_CHK(task); NULL_PARA_CHK(info); if (idx >= RHINO_CONFIG_TASK_INFO_NUM) { return RHINO_INV_PARAM; } *info = task->user_info[idx]; return RHINO_SUCCESS; } #endif void krhino_task_deathbed(void) { #if (RHINO_CONFIG_TASK_DEL > 0) ktask_t *task; task = krhino_cur_task_get(); if (task->mm_alloc_flag == K_OBJ_DYN_ALLOC) { /* del my self*/ #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) krhino_task_dyn_del(NULL); #endif } else { krhino_task_del(NULL); } #else while (1) { krhino_task_sleep(RHINO_CONFIG_TICKS_PER_SECOND * 10); } #endif } ktask_t *krhino_task_find(name_t *name) { CPSR_ALLOC(); klist_t *listnode; ktask_t *task; RHINO_CRITICAL_ENTER(); #if (RHINO_CONFIG_KOBJ_LIST > 0) for (listnode = g_kobj_list.task_head.next; listnode != &g_kobj_list.task_head; listnode = listnode->next) { task = krhino_list_entry(listnode, ktask_t, task_stats_item); if (0 == strcmp(name, task->task_name)) { RHINO_CRITICAL_EXIT(); return task; } } #endif RHINO_CRITICAL_EXIT(); return NULL; }
YifuLiu/AliOS-Things
kernel/rhino/k_task.c
C
apache-2.0
31,799
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "k_api.h" #if (RHINO_CONFIG_TASK_SEM > 0) kstat_t krhino_task_sem_create(ktask_t *task, ksem_t *sem, const name_t *name, size_t count) { kstat_t ret; if (task == NULL) { return RHINO_NULL_PTR; } NULL_PARA_CHK(task); ret = krhino_sem_create(sem, name, count); if (ret == RHINO_SUCCESS) { task->task_sem_obj = sem; } else { task->task_sem_obj = NULL; } return ret; } kstat_t krhino_task_sem_del(ktask_t *task) { NULL_PARA_CHK(task); return krhino_sem_del(task->task_sem_obj); } kstat_t krhino_task_sem_give(ktask_t *task) { NULL_PARA_CHK(task); return krhino_sem_give(task->task_sem_obj); } kstat_t krhino_task_sem_take(tick_t ticks) { return krhino_sem_take(krhino_cur_task_get()->task_sem_obj, ticks); } kstat_t krhino_task_sem_count_set(ktask_t *task, sem_count_t count) { NULL_PARA_CHK(task); return krhino_sem_count_set(task->task_sem_obj, count); } kstat_t krhino_task_sem_count_get(ktask_t *task, sem_count_t *count) { NULL_PARA_CHK(task); return krhino_sem_count_get(task->task_sem_obj, count); } #endif
YifuLiu/AliOS-Things
kernel/rhino/k_task_sem.c
C
apache-2.0
1,226
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "k_api.h" void tick_list_init(void) { klist_init(&g_tick_head); } RHINO_INLINE void tick_list_pri_insert(klist_t *head, ktask_t *task) { tick_t val; klist_t *q; klist_t *list_start; klist_t *list_end; ktask_t *task_iter_temp; list_start = head; list_end = head; val = task->tick_remain; for (q = list_start->next; q != list_end; q = q->next) { task_iter_temp = krhino_list_entry(q, ktask_t, tick_list); if ((task_iter_temp->tick_match - g_tick_count) > val) { break; } } klist_insert(q, &task->tick_list); } void tick_list_insert(ktask_t *task, tick_t time) { task->tick_match = g_tick_count + time; task->tick_remain = time; tick_list_pri_insert(&g_tick_head, task); } void tick_list_rm(ktask_t *task) { klist_rm_init(&task->tick_list); } void tick_list_update(tick_i_t ticks) { CPSR_ALLOC(); klist_t *tick_head_ptr; ktask_t *p_tcb; klist_t *iter; klist_t *iter_temp; tick_i_t delta; RHINO_CRITICAL_ENTER(); g_tick_count += ticks; tick_head_ptr = &g_tick_head; iter = tick_head_ptr->next; while (iter != tick_head_ptr) { /* search all the time list if possible */ iter_temp = iter->next; p_tcb = krhino_list_entry(iter, ktask_t, tick_list); delta = (tick_i_t)p_tcb->tick_match - (tick_i_t)g_tick_count; /* since time list is sorted by remain time, so just campare the absolute time */ if (delta > 0) { break; } switch (p_tcb->task_state) { case K_SLEEP: p_tcb->blk_state = BLK_FINISH; p_tcb->task_state = K_RDY; tick_list_rm(p_tcb); ready_list_add(&g_ready_queue, p_tcb); break; case K_PEND: tick_list_rm(p_tcb); /* remove task on the block list because task is timeout */ klist_rm(&p_tcb->task_list); ready_list_add(&g_ready_queue, p_tcb); p_tcb->blk_state = BLK_TIMEOUT; p_tcb->task_state = K_RDY; mutex_task_pri_reset(p_tcb); p_tcb->blk_obj = NULL; break; case K_PEND_SUSPENDED: tick_list_rm(p_tcb); /* remove task on the block list because task is timeout */ klist_rm(&p_tcb->task_list); p_tcb->blk_state = BLK_TIMEOUT; p_tcb->task_state = K_SUSPENDED; mutex_task_pri_reset(p_tcb); p_tcb->blk_obj = NULL; break; case K_SLEEP_SUSPENDED: p_tcb->task_state = K_SUSPENDED; p_tcb->blk_state = BLK_FINISH; tick_list_rm(p_tcb); break; default: k_err_proc(RHINO_SYS_FATAL_ERR); break; } iter = iter_temp; } RHINO_CRITICAL_EXIT(); }
YifuLiu/AliOS-Things
kernel/rhino/k_tick.c
C
apache-2.0
3,106
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "k_api.h" void krhino_tick_proc(void) { #if (RHINO_CONFIG_USER_HOOK > 0) krhino_tick_hook(); #endif tick_list_update(1); #if (RHINO_CONFIG_SCHED_RR > 0) time_slice_update(); #endif } tick_t krhino_sys_tick_get(void) { CPSR_ALLOC(); tick_t tick_tmp; RHINO_CPU_INTRPT_DISABLE(); tick_tmp = g_tick_count; RHINO_CPU_INTRPT_ENABLE(); return tick_tmp; } sys_time_t krhino_sys_time_get(void) { return (sys_time_t)(krhino_sys_tick_get() * 1000 / RHINO_CONFIG_TICKS_PER_SECOND); } tick_t krhino_ms_to_ticks(sys_time_t ms) { uint16_t padding; tick_t ticks; padding = 1000 / RHINO_CONFIG_TICKS_PER_SECOND; padding = (padding > 0) ? (padding - 1) : 0; ticks = ((ms + padding) * RHINO_CONFIG_TICKS_PER_SECOND) / 1000; return ticks; } sys_time_t krhino_ticks_to_ms(tick_t ticks) { uint32_t padding; sys_time_t time; padding = RHINO_CONFIG_TICKS_PER_SECOND / 1000; padding = (padding > 0) ? (padding - 1) : 0; time = ((ticks + padding) * 1000) / RHINO_CONFIG_TICKS_PER_SECOND; return time; }
YifuLiu/AliOS-Things
kernel/rhino/k_time.c
C
apache-2.0
1,164
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "k_api.h" #if (RHINO_CONFIG_TIMER > 0) static void timer_list_pri_insert(klist_t *head, ktimer_t *timer) { tick_t val; klist_t *q; klist_t *start; klist_t *end; ktimer_t *task_iter_temp; start = head; end = head; val = timer->remain; for (q = start->next; q != end; q = q->next) { task_iter_temp = krhino_list_entry(q, ktimer_t, timer_list); if ((task_iter_temp->match - g_timer_count) > val) { break; } } klist_insert(q, &timer->timer_list); } static void timer_list_rm(ktimer_t *timer) { klist_t *head; head = timer->to_head; if (head != NULL) { klist_rm(&timer->timer_list); timer->to_head = NULL; } } static kstat_t timer_create(ktimer_t *timer, const name_t *name, timer_cb_t cb, tick_t first, tick_t round, void *arg, uint8_t auto_run, uint8_t mm_alloc_flag) { kstat_t err = RHINO_SUCCESS; NULL_PARA_CHK(timer); NULL_PARA_CHK(name); NULL_PARA_CHK(cb); if (first == 0u) { return RHINO_INV_PARAM; } if (first > RHINO_MAX_TICKS) { return RHINO_INV_PARAM; } if (round > RHINO_MAX_TICKS) { return RHINO_INV_PARAM; } timer->name = name; timer->cb = cb; timer->init_count = first; timer->round_ticks = round; timer->remain = 0u; timer->match = 0u; timer->timer_state = TIMER_DEACTIVE; timer->to_head = NULL; timer->mm_alloc_flag = mm_alloc_flag; timer->timer_cb_arg = arg; klist_init(&timer->timer_list); timer->obj_type = RHINO_TIMER_OBJ_TYPE; if (auto_run > 0u) { err = krhino_timer_start(timer); } TRACE_TIMER_CREATE(krhino_cur_task_get(), timer); return err; } kstat_t krhino_timer_create(ktimer_t *timer, const name_t *name, timer_cb_t cb, tick_t first, tick_t round, void *arg, uint8_t auto_run) { return timer_create(timer, name, cb, first, round, arg, auto_run, K_OBJ_STATIC_ALLOC); } kstat_t krhino_timer_del(ktimer_t *timer) { k_timer_queue_cb cb; NULL_PARA_CHK(timer); cb.timer = timer; cb.cb_num = TIMER_CMD_DEL; return krhino_buf_queue_send(&g_timer_queue, &cb, sizeof(k_timer_queue_cb)); } #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) kstat_t krhino_timer_dyn_create(ktimer_t **timer, const name_t *name, timer_cb_t cb, tick_t first, tick_t round, void *arg, uint8_t auto_run) { kstat_t ret; ktimer_t *timer_obj; NULL_PARA_CHK(timer); timer_obj = krhino_mm_alloc(sizeof(ktimer_t)); if (timer_obj == NULL) { return RHINO_NO_MEM; } ret = timer_create(timer_obj, name, cb, first, round, arg, auto_run, K_OBJ_DYN_ALLOC); if (ret != RHINO_SUCCESS) { krhino_mm_free(timer_obj); return ret; } *timer = timer_obj; return ret; } kstat_t krhino_timer_dyn_del(ktimer_t *timer) { k_timer_queue_cb cb; NULL_PARA_CHK(timer); cb.timer = timer; cb.cb_num = TIMER_CMD_DYN_DEL; return krhino_buf_queue_send(&g_timer_queue, &cb, sizeof(k_timer_queue_cb)); } #endif kstat_t krhino_timer_start(ktimer_t *timer) { k_timer_queue_cb cb; NULL_PARA_CHK(timer); cb.timer = timer; cb.cb_num = TIMER_CMD_START; return krhino_buf_queue_send(&g_timer_queue, &cb, sizeof(k_timer_queue_cb)); } kstat_t krhino_timer_stop(ktimer_t *timer) { k_timer_queue_cb cb; NULL_PARA_CHK(timer); cb.timer = timer; cb.cb_num = TIMER_CMD_STOP; return krhino_buf_queue_send(&g_timer_queue, &cb, sizeof(k_timer_queue_cb)); } kstat_t krhino_timer_change(ktimer_t *timer, tick_t first, tick_t round) { k_timer_queue_cb cb; NULL_PARA_CHK(timer); if (first == 0u) { return RHINO_INV_PARAM; } if (first > RHINO_MAX_TICKS) { return RHINO_INV_PARAM; } if (round > RHINO_MAX_TICKS) { return RHINO_INV_PARAM; } cb.timer = timer; cb.first = first; cb.u.round = round; cb.cb_num = TIMER_CMD_CHG; return krhino_buf_queue_send(&g_timer_queue, &cb, sizeof(k_timer_queue_cb)); } kstat_t krhino_timer_arg_change(ktimer_t *timer, void *arg) { k_timer_queue_cb cb; NULL_PARA_CHK(timer); cb.timer = timer; cb.u.arg = arg; cb.cb_num = TIMER_ARG_CHG; return krhino_buf_queue_send(&g_timer_queue, &cb, sizeof(k_timer_queue_cb)); } kstat_t krhino_timer_arg_change_auto(ktimer_t *timer, void *arg) { k_timer_queue_cb cb; NULL_PARA_CHK(timer); cb.timer = timer; cb.u.arg = arg; cb.cb_num = TIMER_ARG_CHG_AUTO; return krhino_buf_queue_send(&g_timer_queue, &cb, sizeof(k_timer_queue_cb)); } static void timer_cb_proc(void) { klist_t *q; klist_t *start; klist_t *end; ktimer_t *timer; tick_i_t delta; start = end = &g_timer_head; for (q = start->next; q != end; q = q->next) { timer = krhino_list_entry(q, ktimer_t, timer_list); delta = (tick_i_t)timer->match - (tick_i_t)g_timer_count; if (delta <= 0) { timer->cb(timer, timer->timer_cb_arg); timer_list_rm(timer); if (timer->round_ticks > 0u) { timer->remain = timer->round_ticks; timer->match = g_timer_count + timer->remain; timer->to_head = &g_timer_head; timer_list_pri_insert(&g_timer_head, timer); } else { timer->timer_state = TIMER_DEACTIVE; } } else { break; } } } static void cmd_proc(k_timer_queue_cb *cb, uint8_t cmd) { ktimer_t *timer = cb->timer; if (timer->obj_type != RHINO_TIMER_OBJ_TYPE) { return; } switch (cmd) { case TIMER_CMD_START: if (timer->timer_state == TIMER_ACTIVE) { break; } timer->match = g_timer_count + timer->init_count; /* sort by remain time */ timer->remain = timer->init_count; /* used by timer delete */ timer->to_head = &g_timer_head; timer_list_pri_insert(&g_timer_head, timer); timer->timer_state = TIMER_ACTIVE; break; case TIMER_CMD_STOP: if (timer->timer_state == TIMER_DEACTIVE) { break; } timer_list_rm(timer); timer->timer_state = TIMER_DEACTIVE; break; case TIMER_CMD_CHG: if (cb->first == 0u) { break; } if (timer->timer_state != TIMER_DEACTIVE) { /* should stop timer before change attributes */ break; } timer->init_count = cb->first; timer->round_ticks = cb->u.round; break; case TIMER_ARG_CHG: if (timer->timer_state != TIMER_DEACTIVE) { break; } timer->timer_cb_arg = cb->u.arg; break; case TIMER_CMD_DEL: if (timer->timer_state != TIMER_DEACTIVE) { break; } if (timer->mm_alloc_flag != K_OBJ_STATIC_ALLOC) { break; } timer->obj_type = RHINO_OBJ_TYPE_NONE; TRACE_TIMER_DEL(krhino_cur_task_get(), timer); break; #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) case TIMER_CMD_DYN_DEL: if (timer->timer_state != TIMER_DEACTIVE) { break; } if (timer->mm_alloc_flag != K_OBJ_DYN_ALLOC) { break; } timer->obj_type = RHINO_OBJ_TYPE_NONE; TRACE_TIMER_DEL(krhino_cur_task_get(), timer); krhino_mm_free(timer); break; #endif default: k_err_proc(RHINO_SYS_FATAL_ERR); break; } } static void timer_cmd_proc(k_timer_queue_cb *cb) { if (cb->cb_num == TIMER_ARG_CHG_AUTO) { cmd_proc(cb, TIMER_CMD_STOP); cmd_proc(cb, TIMER_ARG_CHG); cmd_proc(cb, TIMER_CMD_START); } else { cmd_proc(cb, cb->cb_num); } } static void timer_task(void *pa) { ktimer_t *timer; k_timer_queue_cb cb_msg; kstat_t err; tick_t tick_start; tick_t tick_end; tick_i_t delta; size_t msg_size; (void)pa; while (RHINO_TRUE) { err = krhino_buf_queue_recv(&g_timer_queue, RHINO_WAIT_FOREVER, &cb_msg, &msg_size); tick_end = krhino_sys_tick_get(); if (err == RHINO_SUCCESS) { g_timer_count = tick_end; } else { k_err_proc(RHINO_SYS_FATAL_ERR); } timer_cmd_proc(&cb_msg); while (!is_klist_empty(&g_timer_head)) { timer = krhino_list_entry(g_timer_head.next, ktimer_t, timer_list); tick_start = krhino_sys_tick_get(); delta = (tick_i_t)timer->match - (tick_i_t)tick_start; if (delta > 0) { err = krhino_buf_queue_recv(&g_timer_queue, (tick_t)delta, &cb_msg, &msg_size); tick_end = krhino_sys_tick_get(); if (err == RHINO_BLK_TIMEOUT) { g_timer_count = tick_end; } else if (err == RHINO_SUCCESS) { g_timer_count = tick_end; timer_cb_proc(); timer_cmd_proc(&cb_msg); } else { k_err_proc(RHINO_SYS_FATAL_ERR); } } else { g_timer_count = tick_start; } timer_cb_proc(); } } } void ktimer_init(void) { klist_init(&g_timer_head); krhino_fix_buf_queue_create(&g_timer_queue, "timer_queue", timer_queue_cb, sizeof(k_timer_queue_cb), RHINO_CONFIG_TIMER_MSG_NUM); krhino_task_create(&g_timer_task, "timer_task", NULL, RHINO_CONFIG_TIMER_TASK_PRI, 0u, g_timer_task_stack, RHINO_CONFIG_TIMER_TASK_STACK_SIZE, timer_task, 1u); } #endif /* RHINO_CONFIG_TIMER */
YifuLiu/AliOS-Things
kernel/rhino/k_timer.c
C
apache-2.0
10,289
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "k_api.h" #if (RHINO_CONFIG_WORKQUEUE > 0) static kstat_t workqueue_is_exist(kworkqueue_t *workqueue) { CPSR_ALLOC(); kworkqueue_t *pos; RHINO_CRITICAL_ENTER(); for (pos = krhino_list_entry(g_workqueue_list_head.next, kworkqueue_t, workqueue_node); &pos->workqueue_node != &g_workqueue_list_head; pos = krhino_list_entry(pos->workqueue_node.next, kworkqueue_t, workqueue_node)) { if (pos == workqueue) { RHINO_CRITICAL_EXIT(); return RHINO_WORKQUEUE_EXIST; } } RHINO_CRITICAL_EXIT(); return RHINO_WORKQUEUE_NOT_EXIST; } static void worker_task(void *arg) { CPSR_ALLOC(); kstat_t ret; kwork_t *work = NULL; kworkqueue_t *queue = (kworkqueue_t *)arg; while (1) { ret = krhino_sem_take(&(queue->sem), RHINO_WAIT_FOREVER); if (ret != RHINO_SUCCESS) { k_err_proc(ret); } RHINO_CRITICAL_ENTER(); /* have work to do. */ work = krhino_list_entry(queue->work_list.next, kwork_t, work_node); klist_rm_init(&(work->work_node)); queue->work_current = work; work->work_exit = 0; RHINO_CRITICAL_EXIT(); /* do work */ work->handle(work->arg); RHINO_CRITICAL_ENTER(); /* clean current work */ queue->work_current = NULL; RHINO_CRITICAL_EXIT(); } } kstat_t krhino_workqueue_create(kworkqueue_t *workqueue, const name_t *name, uint8_t pri, cpu_stack_t *stack_buf, size_t stack_size) { CPSR_ALLOC(); kstat_t ret; NULL_PARA_CHK(workqueue); NULL_PARA_CHK(name); NULL_PARA_CHK(stack_buf); if (pri >= RHINO_CONFIG_PRI_MAX) { return RHINO_BEYOND_MAX_PRI; } if (stack_size == 0u) { return RHINO_TASK_INV_STACK_SIZE; } ret = workqueue_is_exist(workqueue); if (ret == RHINO_WORKQUEUE_EXIST) { return RHINO_WORKQUEUE_EXIST; } klist_init(&(workqueue->workqueue_node)); klist_init(&(workqueue->work_list)); workqueue->work_current = NULL; workqueue->name = name; ret = krhino_sem_create(&(workqueue->sem), "WORKQUEUE-SEM", 0); if (ret != RHINO_SUCCESS) { return ret; } RHINO_CRITICAL_ENTER(); klist_insert(&g_workqueue_list_head, &(workqueue->workqueue_node)); RHINO_CRITICAL_EXIT(); ret = krhino_task_create(&(workqueue->worker), name, (void *)workqueue, pri, 0, stack_buf, stack_size, worker_task, 1); if (ret != RHINO_SUCCESS) { RHINO_CRITICAL_ENTER(); klist_rm_init(&(workqueue->workqueue_node)); RHINO_CRITICAL_EXIT(); krhino_sem_del(&(workqueue->sem)); return ret; } TRACE_WORKQUEUE_CREATE(krhino_cur_task_get(), workqueue); return RHINO_SUCCESS; } kstat_t krhino_workqueue_del(kworkqueue_t *workqueue) { CPSR_ALLOC(); kstat_t ret; NULL_PARA_CHK(workqueue); ret = workqueue_is_exist(workqueue); if (ret == RHINO_WORKQUEUE_NOT_EXIST) { return RHINO_WORKQUEUE_NOT_EXIST; } RHINO_CRITICAL_ENTER(); if (!is_klist_empty(&(workqueue->work_list))) { RHINO_CRITICAL_EXIT(); return RHINO_WORKQUEUE_BUSY; } if (workqueue->work_current != NULL) { RHINO_CRITICAL_EXIT(); return RHINO_WORKQUEUE_BUSY; } RHINO_CRITICAL_EXIT(); ret = krhino_task_del(&(workqueue->worker)); if (ret != RHINO_SUCCESS) { return ret; } ret = krhino_sem_del(&(workqueue->sem)); if (ret != RHINO_SUCCESS) { return ret; } RHINO_CRITICAL_ENTER(); klist_rm_init(&(workqueue->workqueue_node)); TRACE_WORKQUEUE_DEL(g_active_task[cpu_cur_get()], workqueue); RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } static void work_timer_cb(void *timer, void *arg) { CPSR_ALLOC(); kstat_t ret; kwork_t *work = ((ktimer_t *)timer)->priv; kworkqueue_t *wq = (kworkqueue_t *)arg; RHINO_CRITICAL_ENTER(); if (wq->work_current == work) { RHINO_CRITICAL_EXIT(); return; } if (work->work_exit == 1) { RHINO_CRITICAL_EXIT(); return; } /* NOTE: the work MUST be initialized firstly */ klist_rm_init(&(work->work_node)); klist_insert(&(wq->work_list), &(work->work_node)); work->wq = wq; work->work_exit = 1; RHINO_CRITICAL_EXIT(); ret = krhino_sem_give(&(wq->sem)); if (ret != RHINO_SUCCESS) { return; } } kstat_t krhino_work_init(kwork_t *work, work_handle_t handle, void *arg, tick_t dly) { kstat_t ret; if (work == NULL) { return RHINO_NULL_PTR; } if (handle == NULL) { return RHINO_NULL_PTR; } NULL_PARA_CHK(work); NULL_PARA_CHK(handle); memset(work, 0, sizeof(kwork_t)); klist_init(&(work->work_node)); work->handle = handle; work->arg = arg; work->dly = dly; work->wq = NULL; if (dly > 0) { ret = krhino_timer_dyn_create((ktimer_t **)(&work->timer), "WORK-TIMER", work_timer_cb, work->dly, 0, (void *)work, 0); if (ret != RHINO_SUCCESS) { return ret; } } TRACE_WORK_INIT(krhino_cur_task_get(), work); return RHINO_SUCCESS; } kstat_t krhino_work_run(kworkqueue_t *workqueue, kwork_t *work) { CPSR_ALLOC(); kstat_t ret; NULL_PARA_CHK(workqueue); NULL_PARA_CHK(work); RHINO_CRITICAL_ENTER(); if (work->dly == 0) { if (workqueue->work_current == work) { RHINO_CRITICAL_EXIT(); return RHINO_WORKQUEUE_WORK_RUNNING; } if (work->work_exit == 1) { RHINO_CRITICAL_EXIT(); return RHINO_WORKQUEUE_WORK_EXIST; } /* NOTE: the work MUST be initialized firstly */ klist_rm_init(&(work->work_node)); klist_insert(&(workqueue->work_list), &(work->work_node)); work->wq = workqueue; work->work_exit = 1; RHINO_CRITICAL_EXIT(); ret = krhino_sem_give(&(workqueue->sem)); if (ret != RHINO_SUCCESS) { return ret; } } else { work->timer->priv = work; RHINO_CRITICAL_EXIT(); ret = krhino_timer_arg_change_auto(work->timer, (void *)workqueue); if (ret != RHINO_SUCCESS) { return ret; } } return RHINO_SUCCESS; } kstat_t krhino_work_sched(kwork_t *work) { return krhino_work_run(&g_workqueue_default, work); } kstat_t krhino_work_cancel(kwork_t *work) { CPSR_ALLOC(); kworkqueue_t *wq; NULL_PARA_CHK(work); wq = (kworkqueue_t *)work->wq; if (wq == NULL) { if (work->dly > 0) { krhino_timer_stop(work->timer); } return RHINO_SUCCESS; } RHINO_CRITICAL_ENTER(); if (wq->work_current == work) { RHINO_CRITICAL_EXIT(); return RHINO_WORKQUEUE_WORK_RUNNING; } if (work->work_exit == 1) { RHINO_CRITICAL_EXIT(); return RHINO_WORKQUEUE_WORK_EXIST; } klist_rm_init(&(work->work_node)); work->wq = NULL; RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } void workqueue_init(void) { klist_init(&g_workqueue_list_head); krhino_workqueue_create(&g_workqueue_default, "DEFAULT-WORKQUEUE", RHINO_CONFIG_WORKQUEUE_TASK_PRIO, g_workqueue_stack, RHINO_CONFIG_WORKQUEUE_STACK_SIZE); } #endif
YifuLiu/AliOS-Things
kernel/rhino/k_workqueue.c
C
apache-2.0
7,638
CPRE := @ ifeq ($(V),1) CPRE := VERB := --verbose endif .PHONY:startup startup: all all: @echo "Build Solution by $(BOARD) " $(CPRE) scons $(VERB) --board=$(BOARD) $(MULTITHREADS) $(MAKEFLAGS) @echo AOS SDK Done sdk: $(CPRE) aos sdk .PHONY:clean clean: $(CPRE) scons -c --board=$(BOARD) $(CPRE) rm -rf aos_sdk aos.elf aos.map aos.bin generated out
YifuLiu/AliOS-Things
solutions/amp_demo/Makefile
Makefile
apache-2.0
358
#! /bin/env python from aostools import Make # default elf is out/<solution>@<board>.elf, and default objcopy is out/<solution>@<board>.bin # defconfig = Make(elf='out/<solution>@<board>.elf', objcopy='out/<solution>@<board>.bin') defconfig = Make() Export('defconfig') defconfig.build_components()
YifuLiu/AliOS-Things
solutions/amp_demo/SConstruct
Python
apache-2.0
302
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/init.h" #include "board.h" #include <aos/errno.h> #include <aos/kernel.h> #include <k_api.h> #include <stdio.h> #include <stdlib.h> extern int amp_main(void); int application_start(int argc, char *argv[]) { int count = 0; aos_task_t amp_task; event_service_init(NULL); aos_task_new_ext(&amp_task, "amp_task", amp_main, NULL, 8192, AOS_DEFAULT_APP_PRI - 2); while (1) { aos_msleep(1000); }; }
YifuLiu/AliOS-Things
solutions/amp_demo/amp_entry.c
C
apache-2.0
507
/* user space */ #ifndef RHINO_CONFIG_USER_SPACE #define RHINO_CONFIG_USER_SPACE 0 #endif
YifuLiu/AliOS-Things
solutions/amp_demo/k_app_config.h
C
apache-2.0
106
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <aos/kernel.h> #include "aos/init.h" #include "board.h" #include <k_api.h> #ifndef AOS_BINS extern int application_start(int argc, char *argv[]); #endif /* If board have no component for example board_xx_init, it indicates that this app does not support this board. Set the correspondence in file platform\board\aaboard_demo\ucube.py. */ extern void board_tick_init(void); extern void board_stduart_init(void); extern void board_dma_init(void); extern void board_gpio_init(void); extern void board_kinit_init(kinit_t *init_args); /* For user config kinit.argc = 0; kinit.argv = NULL; kinit.cli_enable = 1; */ static kinit_t kinit = {0, NULL, 1}; /** * @brief Board Initialization Function * @param None * @retval None */ void board_init(void) { board_tick_init(); board_stduart_init(); board_dma_init(); board_gpio_init(); } void aos_maintask(void *arg) { board_init(); board_kinit_init(&kinit); aos_components_init(&kinit); #ifndef AOS_BINS application_start(kinit.argc, kinit.argv); /* jump to app entry */ #endif }
YifuLiu/AliOS-Things
solutions/amp_demo/maintask.c
C
apache-2.0
1,192
CPRE := @ ifeq ($(V),1) CPRE := VERB := --verbose endif .PHONY:startup startup: all all: @echo "Build Solution by $(BOARD) " $(CPRE) scons $(VERB) --board=$(BOARD) $(MULTITHREADS) $(MAKEFLAGS) @echo AOS SDK Done sdk: $(CPRE) aos sdk .PHONY:clean clean: $(CPRE) scons -c --board=$(BOARD) $(CPRE) find . -name "*.[od]" -delete $(CPRE) rm -rf aos_sdk aos.elf aos.map aos.bin generated out
YifuLiu/AliOS-Things
solutions/audio_demo/Makefile
Makefile
apache-2.0
397
Import('defconfig') defconfig.library_yaml()
YifuLiu/AliOS-Things
solutions/audio_demo/SConscript
Python
apache-2.0
45
#! /bin/env python from aostools import Make defconfig = Make(elf='aos.elf', objcopy='binary/audio_demo@haas100.bin') Export('defconfig') defconfig.build_components()
YifuLiu/AliOS-Things
solutions/audio_demo/SConstruct
Python
apache-2.0
171
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited * */ #include "k_api.h" #if AOS_COMP_CLI #include "aos/cli.h" #endif #include "ulog/ulog.h" #include "uvoice_init.h" #include "uvoice_test.h" void cmd_tts_handler(char *buf, int len, int argc, char **argv) { /* >> tts "我爱你中国" /data/tts.mp3 */ extern void test_tts_handle(int argc, char **argv); return test_tts_handle(argc, argv); } void cmd_play_handler(char *buf, int len, int argc, char **argv) { /* >> play fs:/data/6.mp3 */ char *param_array[2]; if (argc < 2 || strcmp(argv[0], "play")) return; if(!strcmp(argv[1], "pause")) { param_array[0] = "play"; param_array[1] = "pause"; uvoice_play_test(2, param_array); } else if(!strcmp(argv[1], "resume")) { param_array[0] = "play"; param_array[1] = "resume"; uvoice_play_test(2, param_array); } else if(!strcmp(argv[1], "stop")) { param_array[0] = "play"; param_array[1] = "stop"; uvoice_play_test(2, param_array); param_array[0] = "play"; param_array[1] = "clear"; uvoice_play_test(2, param_array); } else { param_array[0] = "play"; param_array[1] = "stopsync"; uvoice_play_test(2, param_array); param_array[0] = "play"; param_array[1] = "clear"; uvoice_play_test(2, param_array); param_array[0] = "play"; param_array[1] = argv[1]; uvoice_play_test(2, param_array); } } #if AOS_COMP_CLI struct cli_command audio_demo_commands[] = { {"play", "try 'play fs:/data/6.mp3' | 'play url' | play pause | play pause | play resume", cmd_play_handler}, {"tts", "try 'tts 我爱你中国 /data/tts.mp3", cmd_tts_handler}, }; #endif /* AOS_COMP_CLI */ int haas_audio_init(void) { uvoice_init(); #if AOS_COMP_CLI aos_cli_register_commands(audio_demo_commands, sizeof(audio_demo_commands) / sizeof(struct cli_command)); #endif /* AOS_COMP_CLI */ return 0; }
YifuLiu/AliOS-Things
solutions/audio_demo/audio_api.c
C
apache-2.0
1,997
/* * 这个例程演示了用SDK配置MQTT参数并建立连接, 之后创建2个线程 * * + 一个线程用于保活长连接 * + 一个线程用于接收消息, 并在有消息到达时进入默认的数据回调, 在连接状态变化时进入事件回调 * * 接着演示了在MQTT连接上进行属性上报, 事件上报, 以及处理收到的属性设置, 服务调用, 取消这些代码段落的注释即可观察运行效果 * * 需要用户关注或修改的部分, 已经用 TODO 在注释中标明 * */ #include <stdio.h> #include <string.h> #include <unistd.h> #include <aos/kernel.h> #include "aiot_state_api.h" #include "aiot_sysdep_api.h" #include "aiot_mqtt_api.h" #include "aiot_dm_api.h" #include "cJSON.h" /* 位于portfiles/aiot_port文件夹下的系统适配函数集合 */ extern aiot_sysdep_portfile_t g_aiot_sysdep_portfile; /* 位于external/ali_ca_cert.c中的服务器证书 */ extern const char *ali_ca_cert; static uint8_t g_mqtt_process_thread_running = 0; static uint8_t g_mqtt_recv_thread_running = 0; extern int audio_install_codec_driver(); extern void sound_example_loopback_entry(int argc, char **argv); extern void cmd_tts_handler(char *buf, int len, int argc, char **argv); extern void cmd_play_handler(char *buf, int len, int argc, char **argv); /* TODO: 如果要关闭日志, 就把这个函数实现为空, 如果要减少日志, 可根据code选择不打印 * * 例如: [1577589489.033][LK-0317] mqtt_basic_demo&a13FN5TplKq * * 上面这条日志的code就是0317(十六进制), code值的定义见core/aiot_state_api.h * */ /* 日志回调函数, SDK的日志会从这里输出 */ int32_t demo_state_logcb(int32_t code, char *message) { printf("%s", message); return 0; } /* MQTT事件回调函数, 当网络连接/重连/断开时被触发, 事件定义见core/aiot_mqtt_api.h */ void demo_mqtt_event_handler(void *handle, const aiot_mqtt_event_t *event, void *userdata) { switch (event->type) { /* SDK因为用户调用了aiot_mqtt_connect()接口, 与mqtt服务器建立连接已成功 */ case AIOT_MQTTEVT_CONNECT: { printf("AIOT_MQTTEVT_CONNECT\n"); } break; /* SDK因为网络状况被动断连后, 自动发起重连已成功 */ case AIOT_MQTTEVT_RECONNECT: { printf("AIOT_MQTTEVT_RECONNECT\n"); } break; /* SDK因为网络的状况而被动断开了连接, network是底层读写失败, heartbeat是没有按预期得到服务端心跳应答 */ case AIOT_MQTTEVT_DISCONNECT: { char *cause = (event->data.disconnect == AIOT_MQTTDISCONNEVT_NETWORK_DISCONNECT) ? ("network disconnect") : ("heartbeat disconnect"); printf("AIOT_MQTTEVT_DISCONNECT: %s\n", cause); } break; default: { } } } /* 执行aiot_mqtt_process的线程, 包含心跳发送和QoS1消息重发 */ void *demo_mqtt_process_thread(void *args) { int32_t res = STATE_SUCCESS; while (g_mqtt_process_thread_running) { res = aiot_mqtt_process(args); if (res == STATE_USER_INPUT_EXEC_DISABLED) { break; } aos_msleep(1000); } return NULL; } /* 执行aiot_mqtt_recv的线程, 包含网络自动重连和从服务器收取MQTT消息 */ void *demo_mqtt_recv_thread(void *args) { int32_t res = STATE_SUCCESS; while (g_mqtt_recv_thread_running) { res = aiot_mqtt_recv(args); if (res < STATE_SUCCESS) { if (res == STATE_USER_INPUT_EXEC_DISABLED) { break; } aos_msleep(1000); } } return NULL; } /* 用户数据接收处理回调函数 */ static void demo_dm_recv_handler(void *dm_handle, const aiot_dm_recv_t *recv, void *userdata) { printf("demo_dm_recv_handler, type = %d\r\n", recv->type); switch (recv->type) { /* 属性上报, 事件上报, 获取期望属性值或者删除期望属性值的应答 */ case AIOT_DMRECV_GENERIC_REPLY: { printf("msg_id = %d, code = %d, data = %.*s, message = %.*s\r\n", recv->data.generic_reply.msg_id, recv->data.generic_reply.code, recv->data.generic_reply.data_len, recv->data.generic_reply.data, recv->data.generic_reply.message_len, recv->data.generic_reply.message); } break; /* 属性设置 */ case AIOT_DMRECV_PROPERTY_SET: { printf("msg_id = %lu, params = %.*s\r\n", (unsigned long)recv->data.property_set.msg_id, recv->data.property_set.params_len, recv->data.property_set.params); /* ------ 云端钉一体智能语音播放器指令解析 ------ */ cJSON *root = NULL, *item_payload = NULL; static int pause_state = 0, power_state = 0, recorder_state = 0; char *param_array[10]; /* Parse Root */ root = cJSON_Parse(recv->data.property_set.params); if (root == NULL || !cJSON_IsObject(root)) { printf("JSON Parse Error\r\n"); return -1; } /* Payload: PowerSwitch */ item_payload = cJSON_GetObjectItem(root, "PowerSwitch"); if (item_payload != NULL && cJSON_IsNumber(item_payload)) { if(1 == item_payload->valueint) { printf("PowerSwitch = %d \r\n", item_payload->valueint); if(0 == power_state) { printf("start load sound driver... \r\n"); power_state = 1; audio_install_codec_driver(); } else { printf("sound driver already loaded. \r\n"); } } else { printf("uninstall sound driver, TBD \r\n"); } } /* Payload: startRecord */ item_payload = cJSON_GetObjectItem(root, "startRecord"); if (item_payload != NULL && cJSON_IsNumber(item_payload)) { if((1 == item_payload->valueint) && (0 == recorder_state)) { printf("start recorder. \r\n"); recorder_state = 1; param_array[0] = "sound_loopback"; param_array[1] = "start"; sound_example_loopback_entry(2, param_array); } else { printf("stop recorder. \r\n"); recorder_state = 0; param_array[0] = "sound_loopback"; param_array[1] = "stop"; sound_example_loopback_entry(2, param_array); } } /* Payload: TTSText */ item_payload = cJSON_GetObjectItem(root, "TTSText"); if (item_payload != NULL && cJSON_IsString(item_payload)) { printf("tts %s /data/tts.mp3\r\n", item_payload->valuestring); param_array[0] = "tts"; param_array[1] = item_payload->valuestring; param_array[2] = "/data/tts.mp3"; cmd_tts_handler(NULL, 0, 3, param_array); } /* Payload: PlayURL */ item_payload = cJSON_GetObjectItem(root, "PlayURL"); if (item_payload != NULL && cJSON_IsString(item_payload)) { printf("play %s\r\n", item_payload->valuestring); param_array[0] = "play"; param_array[1] = item_payload->valuestring; cmd_play_handler(NULL, 0, 2, param_array); } /* Payload: PlayType */ item_payload = cJSON_GetObjectItem(root, "PlayType"); if (item_payload != NULL && cJSON_IsNumber(item_payload)) { printf("PlayType = %d \r\n", item_payload->valueint); switch(item_payload->valueint) { case 0: // 停止 printf("play stop \r\n"); param_array[0] = "play"; param_array[1] = "stop"; cmd_play_handler(NULL, 0, 2, param_array); break; case 1: // 恢复 if(pause_state) { printf("play resume \r\n"); param_array[0] = "play"; param_array[1] = "resume"; cmd_play_handler(NULL, 0, 2, param_array); } pause_state = 0; break; case 2: //暂停 printf("play pause \r\n"); param_array[0] = "play"; param_array[1] = "pause"; pause_state = 1; cmd_play_handler(NULL, 0, 2, param_array); break; } } /* Payload: SetVolume */ item_payload = cJSON_GetObjectItem(root, "SetVolume"); if (item_payload != NULL && cJSON_IsNumber(item_payload)) { printf("set volume = %d \r\n", item_payload->valueint); aos_set_master_volume(item_payload->valueint); } } break; /* 异步服务调用 */ case AIOT_DMRECV_ASYNC_SERVICE_INVOKE: { printf("msg_id = %lu, service_id = %s, params = %.*s\r\n", (unsigned long)recv->data.async_service_invoke.msg_id, recv->data.async_service_invoke.service_id, recv->data.async_service_invoke.params_len, recv->data.async_service_invoke.params); /* TODO: 以下代码演示如何对来自云平台的异步服务调用进行应答, 用户可取消注释查看演示效果 * * 注意: 如果用户在回调函数外进行应答, 需要自行保存msg_id, 因为回调函数入参在退出回调函数后将被SDK销毁, 不可以再访问到 */ /* { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_ASYNC_SERVICE_REPLY; msg.data.async_service_reply.msg_id = recv->data.async_service_invoke.msg_id; msg.data.async_service_reply.code = 200; msg.data.async_service_reply.service_id = "ToggleLightSwitch"; msg.data.async_service_reply.data = "{\"dataA\": 20}"; int32_t res = aiot_dm_send(dm_handle, &msg); if (res < 0) { printf("aiot_dm_send failed\r\n"); } } */ } break; /* 同步服务调用 */ case AIOT_DMRECV_SYNC_SERVICE_INVOKE: { printf("msg_id = %lu, rrpc_id = %s, service_id = %s, params = %.*s\r\n", (unsigned long)recv->data.sync_service_invoke.msg_id, recv->data.sync_service_invoke.rrpc_id, recv->data.sync_service_invoke.service_id, recv->data.sync_service_invoke.params_len, recv->data.sync_service_invoke.params); /* TODO: 以下代码演示如何对来自云平台的同步服务调用进行应答, 用户可取消注释查看演示效果 * * 注意: 如果用户在回调函数外进行应答, 需要自行保存msg_id和rrpc_id字符串, 因为回调函数入参在退出回调函数后将被SDK销毁, 不可以再访问到 */ /* { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_SYNC_SERVICE_REPLY; msg.data.sync_service_reply.rrpc_id = recv->data.sync_service_invoke.rrpc_id; msg.data.sync_service_reply.msg_id = recv->data.sync_service_invoke.msg_id; msg.data.sync_service_reply.code = 200; msg.data.sync_service_reply.service_id = "SetLightSwitchTimer"; msg.data.sync_service_reply.data = "{}"; int32_t res = aiot_dm_send(dm_handle, &msg); if (res < 0) { printf("aiot_dm_send failed\r\n"); } } */ } break; /* 下行二进制数据 */ case AIOT_DMRECV_RAW_DATA: { printf("raw data len = %d\r\n", recv->data.raw_data.data_len); /* TODO: 以下代码演示如何发送二进制格式数据, 若使用需要有相应的数据透传脚本部署在云端 */ /* { aiot_dm_msg_t msg; uint8_t raw_data[] = {0x01, 0x02}; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_RAW_DATA; msg.data.raw_data.data = raw_data; msg.data.raw_data.data_len = sizeof(raw_data); aiot_dm_send(dm_handle, &msg); } */ } break; /* 二进制格式的同步服务调用, 比单纯的二进制数据消息多了个rrpc_id */ case AIOT_DMRECV_RAW_SYNC_SERVICE_INVOKE: { printf("raw sync service rrpc_id = %s, data_len = %d\r\n", recv->data.raw_service_invoke.rrpc_id, recv->data.raw_service_invoke.data_len); } break; default: break; } } /* 属性上报函数演示 */ int32_t demo_send_property_post(void *dm_handle, char *params) { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_PROPERTY_POST; msg.data.property_post.params = params; return aiot_dm_send(dm_handle, &msg); } /* 事件上报函数演示 */ int32_t demo_send_event_post(void *dm_handle, char *event_id, char *params) { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_EVENT_POST; msg.data.event_post.event_id = event_id; msg.data.event_post.params = params; return aiot_dm_send(dm_handle, &msg); } /* 演示了获取属性LightSwitch的期望值, 用户可将此函数加入到main函数中运行演示 */ int32_t demo_send_get_desred_requset(void *dm_handle) { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_GET_DESIRED; msg.data.get_desired.params = "[\"LightSwitch\"]"; return aiot_dm_send(dm_handle, &msg); } /* 演示了删除属性LightSwitch的期望值, 用户可将此函数加入到main函数中运行演示 */ int32_t demo_send_delete_desred_requset(void *dm_handle) { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_DELETE_DESIRED; msg.data.get_desired.params = "{\"LightSwitch\":{}}"; return aiot_dm_send(dm_handle, &msg); } int demo_main(int argc, char *argv[]) { int32_t res = STATE_SUCCESS; void *dm_handle = NULL; void *mqtt_handle = NULL; char *url = "iot-as-mqtt.cn-shanghai.aliyuncs.com"; /* 阿里云平台上海站点的域名后缀 */ char host[100] = {0}; /* 用这个数组拼接设备连接的云平台站点全地址, 规则是 ${productKey}.iot-as-mqtt.cn-shanghai.aliyuncs.com */ uint16_t port = 443; /* 无论设备是否使用TLS连接阿里云平台, 目的端口都是443 */ aiot_sysdep_network_cred_t cred; /* 安全凭据结构体, 如果要用TLS, 这个结构体中配置CA证书等参数 */ /* TODO: 替换为自己设备的三元组 */ char *product_key = ""; char *device_name = ""; char *device_secret = ""; /* 配置SDK的底层依赖 */ aiot_sysdep_set_portfile(&g_aiot_sysdep_portfile); /* 配置SDK的日志输出 */ aiot_state_set_logcb(demo_state_logcb); /* 创建SDK的安全凭据, 用于建立TLS连接 */ memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t)); cred.option = AIOT_SYSDEP_NETWORK_CRED_SVRCERT_CA; /* 使用RSA证书校验MQTT服务端 */ cred.max_tls_fragment = 16384; /* 最大的分片长度为16K, 其它可选值还有4K, 2K, 1K, 0.5K */ cred.sni_enabled = 1; /* TLS建连时, 支持Server Name Indicator */ cred.x509_server_cert = ali_ca_cert; /* 用来验证MQTT服务端的RSA根证书 */ cred.x509_server_cert_len = strlen(ali_ca_cert); /* 用来验证MQTT服务端的RSA根证书长度 */ /* 创建1个MQTT客户端实例并内部初始化默认参数 */ mqtt_handle = aiot_mqtt_init(); if (mqtt_handle == NULL) { printf("aiot_mqtt_init failed\n"); return -1; } snprintf(host, 100, "%s.%s", product_key, url); /* 配置MQTT服务器地址 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_HOST, (void *)host); /* 配置MQTT服务器端口 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PORT, (void *)&port); /* 配置设备productKey */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PRODUCT_KEY, (void *)product_key); /* 配置设备deviceName */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_NAME, (void *)device_name); /* 配置设备deviceSecret */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_SECRET, (void *)device_secret); /* 配置网络连接的安全凭据, 上面已经创建好了 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_NETWORK_CRED, (void *)&cred); /* 配置MQTT事件回调函数 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_EVENT_HANDLER, (void *)demo_mqtt_event_handler); /* 创建DATA-MODEL实例 */ dm_handle = aiot_dm_init(); if (dm_handle == NULL) { printf("aiot_dm_init failed"); return -1; } /* 配置MQTT实例句柄 */ aiot_dm_setopt(dm_handle, AIOT_DMOPT_MQTT_HANDLE, mqtt_handle); /* 配置消息接收处理回调函数 */ aiot_dm_setopt(dm_handle, AIOT_DMOPT_RECV_HANDLER, (void *)demo_dm_recv_handler); /* 与服务器建立MQTT连接 */ res = aiot_mqtt_connect(mqtt_handle); if (res < STATE_SUCCESS) { /* 尝试建立连接失败, 销毁MQTT实例, 回收资源 */ aiot_mqtt_deinit(&mqtt_handle); printf("aiot_mqtt_connect failed: -0x%04X\n", -res); return -1; } /* 创建一个单独的线程, 专用于执行aiot_mqtt_process, 它会自动发送心跳保活, 以及重发QoS1的未应答报文 */ g_mqtt_process_thread_running = 1; res = aos_task_new("demo_mqtt_process", demo_mqtt_process_thread, mqtt_handle, 4096); // res = pthread_create(&g_mqtt_process_thread, NULL, demo_mqtt_process_thread, mqtt_handle); if (res != 0) { printf("create demo_mqtt_process_thread failed: %d\n", res); return -1; } /* 创建一个单独的线程用于执行aiot_mqtt_recv, 它会循环收取服务器下发的MQTT消息, 并在断线时自动重连 */ g_mqtt_recv_thread_running = 1; res = aos_task_new("demo_mqtt_process", demo_mqtt_recv_thread, mqtt_handle, 4096); // res = pthread_create(&g_mqtt_recv_thread, NULL, demo_mqtt_recv_thread, mqtt_handle); if (res != 0) { printf("create demo_mqtt_recv_thread failed: %d\n", res); return -1; } /* 主循环进入休眠 */ while (1) { /* TODO: 以下代码演示了简单的属性上报和事件上报, 用户可取消注释观察演示效果 */ demo_send_property_post(dm_handle, "{\"LightSwitch\": 0}"); demo_send_event_post(dm_handle, "Error", "{\"ErrorCode\": 0}"); aos_msleep(10000); } /* 断开MQTT连接, 一般不会运行到这里 */ res = aiot_mqtt_disconnect(mqtt_handle); if (res < STATE_SUCCESS) { aiot_mqtt_deinit(&mqtt_handle); printf("aiot_mqtt_disconnect failed: -0x%04X\n", -res); return -1; } /* 销毁DATA-MODEL实例, 一般不会运行到这里 */ res = aiot_dm_deinit(&dm_handle); if (res < STATE_SUCCESS) { printf("aiot_dm_deinit failed: -0x%04X\n", -res); return -1; } /* 销毁MQTT实例, 一般不会运行到这里 */ res = aiot_mqtt_deinit(&mqtt_handle); if (res < STATE_SUCCESS) { printf("aiot_mqtt_deinit failed: -0x%04X\n", -res); return -1; } g_mqtt_process_thread_running = 0; g_mqtt_recv_thread_running = 0; return 0; }
YifuLiu/AliOS-Things
solutions/audio_demo/data_model_basic_demo.c
C
apache-2.0
20,566
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ /** * @file main.c * * This file includes the entry code of link sdk related demo * */ #include <string.h> #include <stdio.h> #include <aos/kernel.h> #include "ulog/ulog.h" #include "netmgr.h" #include <uservice/uservice.h> #include <uservice/eventid.h> extern int demo_main(int argc, char *argv[]); static int _ip_got_finished = 0; static void entry_func(void *data) { demo_main(0 , NULL); } static void wifi_event_cb(uint32_t event_id, const void *param, void *context) { if (event_id != EVENT_NETMGR_DHCP_SUCCESS) return; if (_ip_got_finished != 0) return; _ip_got_finished = 1; aos_task_new("link_dmeo", entry_func, NULL, 6 << 10); } int application_start(int argc, char *argv[]) { aos_set_log_level(AOS_LL_DEBUG); event_service_init(NULL); netmgr_service_init(NULL); /*enable network auto reconnect*/ netmgr_set_auto_reconnect(NULL, true); /*enable auto save wifi config*/ netmgr_wifi_set_auto_save_ap(true); event_subscribe(EVENT_NETMGR_DHCP_SUCCESS, wifi_event_cb, NULL); haas_audio_init(); while (1) { aos_msleep(1000); }; return 0; }
YifuLiu/AliOS-Things
solutions/audio_demo/main.c
C
apache-2.0
1,218
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <aos/kernel.h> #include "aos/init.h" #include "board.h" #include <k_api.h> #ifndef AOS_BINS extern int application_start(int argc, char *argv[]); #endif /* * If board have no component for example board_xx_init, it indicates that this * app does not support this board. * Set the correspondence in file platform\board\aaboard_demo\ucube.py. */ extern void board_tick_init(void); extern void board_stduart_init(void); extern void board_dma_init(void); extern void board_gpio_init(void); extern void board_kinit_init(kinit_t *init_args); /* * For user config * kinit.argc = 0; * kinit.argv = NULL; * kinit.cli_enable = 1; */ static kinit_t kinit = {0, NULL, 1}; /* * @brief Board Initialization Function * @param None * @retval None */ void board_init(void) { board_tick_init(); board_stduart_init(); board_dma_init(); board_gpio_init(); } void aos_maintask(void *arg) { board_init(); board_kinit_init(&kinit); aos_components_init(&kinit); #ifndef AOS_BINS application_start(kinit.argc, kinit.argv); /* jump to app entry */ #endif }
YifuLiu/AliOS-Things
solutions/audio_demo/maintask.c
C
apache-2.0
1,197
CPRE := @ ifeq ($(V),1) CPRE := VERB := --verbose endif MK_GENERATED_IMGS_PATH:=generated PRODUCT_BIN:=product .PHONY:startup startup: all all: @echo "Build Solution by $(BOARD) " $(CPRE) scons $(VERB) --board=$(BOARD) $(MULTITHREADS) $(MAKEFLAGS) @echo YoC SDK Done @echo [INFO] Create bin files # $(CPRE) $(PRODUCT_BIN) image $(MK_GENERATED_IMGS_PATH)/images.zip -i $(MK_GENERATED_IMGS_PATH)/data -l -p # $(CPRE) $(PRODUCT_BIN) image $(MK_GENERATED_IMGS_PATH)/images.zip -e $(MK_GENERATED_IMGS_PATH) -x .PHONY:flash flash: $(CPRE) $(PRODUCT_BIN) flash $(MK_GENERATED_IMGS_PATH)/images.zip -w prim .PHONY:flashall flashall: $(CPRE) $(PRODUCT_BIN) flash $(MK_GENERATED_IMGS_PATH)/images.zip -a sdk: $(CPRE) yoc sdk .PHONY:clean clean: $(CPRE) scons -c --board=$(BOARD) $(CPRE) find . -name "*.[od]" -delete $(CPRE) rm -rf aos_sdk aos.elf aos.map aos.bin binary generated out
YifuLiu/AliOS-Things
solutions/auto_demo/Makefile
Makefile
apache-2.0
892
Import('defconfig') defconfig.library_yaml()
YifuLiu/AliOS-Things
solutions/auto_demo/SConscript
Python
apache-2.0
45
#! /bin/env python from aostools import Make # defconfig = Make(elf='yoc.elf', objcopy='generated/data/prim', objdump='yoc.asm') defconfig = Make(elf='aos.elf', objcopy='binary/auto_demo@haas100.bin') Export('defconfig') defconfig.build_components()
YifuLiu/AliOS-Things
solutions/auto_demo/SConstruct
Python
apache-2.0
254
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <aos/kernel.h> #include "ulog/ulog.h" #include "auto_app.h" #include "k_api.h" #if AOS_COMP_CLI #include "aos/cli.h" #endif #include <sys/ioctl.h> #include <vfsdev/gpio_dev.h> #include <drivers/char/u_device.h> #include <drivers/u_ld.h> #include "aos/vfs.h" #include "aos/hal/gpio.h" #include "hal_iomux_haas1000.h" static int fd = 0; extern uint32_t hal_fast_sys_timer_get(); extern uint32_t hal_cmu_get_crystal_freq(); #define CONFIG_FAST_SYSTICK_HZ (hal_cmu_get_crystal_freq() / 4) #define FAST_TICKS_TO_US(tick) ((uint32_t)(tick) * 10 / (CONFIG_FAST_SYSTICK_HZ / 1000 / 100)) #define IN1_PORT 0 #define IN2_PORT 1 #define IN3_PORT 2 #define IN4_PORT 3 #define ENA_PORT 4 #define ENB_PORT 5 #define IN1_PIN HAL_IOMUX_PIN_P4_7 #define IN2_PIN HAL_IOMUX_PIN_P4_0 #define IN3_PIN HAL_IOMUX_PIN_P2_6 #define IN4_PIN HAL_IOMUX_PIN_P4_6 #define ENA_PIN HAL_IOMUX_PIN_P2_4 #define ENB_PIN HAL_IOMUX_PIN_P2_5 #define DEMO_TIME_DEFAULT_MS 300 #if (RHINO_CONFIG_HW_COUNT > 0) void _udelay(unsigned long x) { unsigned long now,t; t = FAST_TICKS_TO_US(hal_fast_sys_timer_get()); now = t; while ((now - t) < x) { now = FAST_TICKS_TO_US(hal_fast_sys_timer_get()); } } void _msdelay(unsigned long x) { _udelay(x * 1000); } #else #error "RHINO_CONFIG_HW_COUNT should be configured to get us level delay" #endif //auto gpio set static void GPIO_Set(unsigned char port,unsigned char leve) { struct gpio_io_config config; switch(port){ case IN1_PORT: config.id = IN1_PIN;//8*4 + 7; break; case IN2_PORT: config.id = IN2_PIN;//8*4 + 0; break; case IN3_PORT: config.id = IN3_PIN;//8*2 + 6; break; case IN4_PORT: config.id = IN4_PIN;//8*4 + 6; break; case ENA_PORT: config.id = ENA_PIN;//8*2 + 4; break; case ENB_PORT: config.id = ENB_PIN;//8*2 + 5; break; default: break; } config.config = GPIO_IO_OUTPUT | GPIO_IO_OUTPUT_ODPU; if(leve == 1){ config.data = 1; } else if(leve == 0){ config.data = 0; } ioctl(fd, IOC_GPIO_SET, (unsigned long)&config); } //停止 void stop_ctl(void) { GPIO_Set(IN1_PORT,0); GPIO_Set(IN2_PORT,0); GPIO_Set(IN3_PORT,0); GPIO_Set(IN4_PORT,0); } //前进 void front_ctl(void) { GPIO_Set(IN1_PORT,1); GPIO_Set(IN2_PORT,0); GPIO_Set(IN3_PORT,0); GPIO_Set(IN4_PORT,1); _msdelay(DEMO_TIME_DEFAULT_MS); stop_ctl(); } //后退 void back_ctl(void) { GPIO_Set(IN1_PORT,0); GPIO_Set(IN2_PORT,1); GPIO_Set(IN3_PORT,1); GPIO_Set(IN4_PORT,0); _msdelay(DEMO_TIME_DEFAULT_MS); stop_ctl(); } //左转 void left_ctl(void) { GPIO_Set(IN1_PORT,0); GPIO_Set(IN2_PORT,0); GPIO_Set(IN3_PORT,0); GPIO_Set(IN4_PORT,1); _msdelay(DEMO_TIME_DEFAULT_MS); stop_ctl(); } //右转 void right_ctl(void) { GPIO_Set(IN1_PORT,1); GPIO_Set(IN2_PORT,0); GPIO_Set(IN3_PORT,0); GPIO_Set(IN4_PORT,0); _msdelay(DEMO_TIME_DEFAULT_MS); stop_ctl(); } static void handle_haas_cmd(char *pwbuf, int blen, int argc, char **argv) { if(0 == strcmp(argv[1],"0")){ stop_ctl(); LOGI("APP", "stop\n"); } else if(0 == strcmp(argv[1],"1")){ front_ctl(); LOGI("APP", "front\n"); } else if(0 == strcmp(argv[1],"2")){ back_ctl(); LOGI("APP", "back\n"); } else if(0 == strcmp(argv[1],"3")){ left_ctl(); LOGI("APP", "left\n"); } else if(0 == strcmp(argv[1],"4")){ right_ctl(); LOGI("APP", "right\n"); } } #if AOS_COMP_CLI static struct cli_command haas_cmd = { .name = "haas", .help = "haas [read]", .function = handle_haas_cmd }; int auto_app_init(void) { gpio_dev_t temp_gpio; temp_gpio.port = IN1_PIN; temp_gpio.config = OUTPUT_OPEN_DRAIN_PULL_UP; hal_gpio_init(&temp_gpio); temp_gpio.port = IN2_PIN; temp_gpio.config = OUTPUT_OPEN_DRAIN_PULL_UP; hal_gpio_init(&temp_gpio); temp_gpio.port = IN3_PIN; temp_gpio.config = OUTPUT_OPEN_DRAIN_PULL_UP; hal_gpio_init(&temp_gpio); temp_gpio.port = IN4_PIN; temp_gpio.config = OUTPUT_OPEN_DRAIN_PULL_UP; hal_gpio_init(&temp_gpio); temp_gpio.port = ENA_PIN; temp_gpio.config = OUTPUT_OPEN_DRAIN_PULL_UP; hal_gpio_init(&temp_gpio); temp_gpio.port = ENB_PIN; temp_gpio.config = OUTPUT_OPEN_DRAIN_PULL_UP; hal_gpio_init(&temp_gpio); fd = open("/dev/gpio", 0); printf("open gpio %s, fd:%d\r\n", fd >= 0 ? "success" : "fail", fd); GPIO_Set(ENA_PORT,1); GPIO_Set(ENB_PORT,1); stop_ctl(); aos_cli_register_command(&haas_cmd); return 0; } #endif /* AOS_COMP_CLI */
YifuLiu/AliOS-Things
solutions/auto_demo/auto_app.c
C
apache-2.0
4,931
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef AUTO_APP_H #define AUTO_APP_H void right_ctl(void); void left_ctl(void); void back_ctl(void); void front_ctl(void); void stop_ctl(void); int auto_app_init(void); #endif
YifuLiu/AliOS-Things
solutions/auto_demo/auto_app.h
C
apache-2.0
245
/* * 这个例程演示了用SDK配置MQTT参数并建立连接, 之后创建2个线程 * * + 一个线程用于保活长连接 * + 一个线程用于接收消息, 并在有消息到达时进入默认的数据回调, 在连接状态变化时进入事件回调 * * 接着演示了在MQTT连接上进行属性上报, 事件上报, 以及处理收到的属性设置, 服务调用, 取消这些代码段落的注释即可观察运行效果 * * 需要用户关注或修改的部分, 已经用 TODO 在注释中标明 * */ #include <stdio.h> #include <string.h> #include <unistd.h> #include <aos/kernel.h> #include "aiot_state_api.h" #include "aiot_sysdep_api.h" #include "aiot_mqtt_api.h" #include "aiot_dm_api.h" #include "cJSON.h" #include "auto_app.h" /* 位于portfiles/aiot_port文件夹下的系统适配函数集合 */ extern aiot_sysdep_portfile_t g_aiot_sysdep_portfile; /* 位于external/ali_ca_cert.c中的服务器证书 */ extern const char *ali_ca_cert; static uint8_t g_mqtt_process_thread_running = 0; static uint8_t g_mqtt_recv_thread_running = 0; /* TODO: 如果要关闭日志, 就把这个函数实现为空, 如果要减少日志, 可根据code选择不打印 * * 例如: [1577589489.033][LK-0317] mqtt_basic_demo&a13FN5TplKq * * 上面这条日志的code就是0317(十六进制), code值的定义见core/aiot_state_api.h * */ /* 日志回调函数, SDK的日志会从这里输出 */ int32_t demo_state_logcb(int32_t code, char *message) { printf("%s", message); return 0; } /* MQTT事件回调函数, 当网络连接/重连/断开时被触发, 事件定义见core/aiot_mqtt_api.h */ void demo_mqtt_event_handler(void *handle, const aiot_mqtt_event_t *event, void *userdata) { switch (event->type) { /* SDK因为用户调用了aiot_mqtt_connect()接口, 与mqtt服务器建立连接已成功 */ case AIOT_MQTTEVT_CONNECT: { printf("AIOT_MQTTEVT_CONNECT\n"); } break; /* SDK因为网络状况被动断连后, 自动发起重连已成功 */ case AIOT_MQTTEVT_RECONNECT: { printf("AIOT_MQTTEVT_RECONNECT\n"); } break; /* SDK因为网络的状况而被动断开了连接, network是底层读写失败, heartbeat是没有按预期得到服务端心跳应答 */ case AIOT_MQTTEVT_DISCONNECT: { char *cause = (event->data.disconnect == AIOT_MQTTDISCONNEVT_NETWORK_DISCONNECT) ? ("network disconnect") : ("heartbeat disconnect"); printf("AIOT_MQTTEVT_DISCONNECT: %s\n", cause); } break; default: { } } } /* 执行aiot_mqtt_process的线程, 包含心跳发送和QoS1消息重发 */ void *demo_mqtt_process_thread(void *args) { int32_t res = STATE_SUCCESS; while (g_mqtt_process_thread_running) { res = aiot_mqtt_process(args); if (res == STATE_USER_INPUT_EXEC_DISABLED) { break; } aos_msleep(1000); } return NULL; } /* 执行aiot_mqtt_recv的线程, 包含网络自动重连和从服务器收取MQTT消息 */ void *demo_mqtt_recv_thread(void *args) { int32_t res = STATE_SUCCESS; while (g_mqtt_recv_thread_running) { res = aiot_mqtt_recv(args); if (res < STATE_SUCCESS) { if (res == STATE_USER_INPUT_EXEC_DISABLED) { break; } aos_msleep(1000); } } return NULL; } /* 用户数据接收处理回调函数 */ static void demo_dm_recv_handler(void *dm_handle, const aiot_dm_recv_t *recv, void *userdata) { uint8_t i; printf("demo_dm_recv_handler, type = %d\r\n", recv->type); switch (recv->type) { /* 属性上报, 事件上报, 获取期望属性值或者删除期望属性值的应答 */ case AIOT_DMRECV_GENERIC_REPLY: { printf("msg_id = %d, code = %d, data = %.*s, message = %.*s\r\n", recv->data.generic_reply.msg_id, recv->data.generic_reply.code, recv->data.generic_reply.data_len, recv->data.generic_reply.data, recv->data.generic_reply.message_len, recv->data.generic_reply.message); } break; /* 属性设置 */ case AIOT_DMRECV_PROPERTY_SET: { printf("msg_id = %ld, params = %.*s\r\n", (unsigned long)recv->data.property_set.msg_id, recv->data.property_set.params_len, recv->data.property_set.params); char *auto_temp[5]={"back","left","right","stop","front"}; cJSON *root = cJSON_Parse(recv->data.property_set.params); for(i = 0 ;i<5 ;i++){ cJSON *value = cJSON_GetObjectItem(root,auto_temp[i]); if (value != NULL && cJSON_IsNumber(value)) { printf("%s is find!\r\n",auto_temp[i]); break; } } switch(i){ case 0: back_ctl(); printf("---back\r\n"); break; case 1: left_ctl(); printf("---left\r\n"); break; case 2: right_ctl(); printf("---right\r\n"); break; case 3: stop_ctl(); printf("---stop\r\n"); break; case 4: front_ctl(); printf("---front\r\n"); break; default: break; } } break; /* 异步服务调用 */ case AIOT_DMRECV_ASYNC_SERVICE_INVOKE: { printf("msg_id = %ld, service_id = %s, params = %.*s\r\n", (unsigned long)recv->data.async_service_invoke.msg_id, recv->data.async_service_invoke.service_id, recv->data.async_service_invoke.params_len, recv->data.async_service_invoke.params); /* TODO: 以下代码演示如何对来自云平台的异步服务调用进行应答, 用户可取消注释查看演示效果 * * 注意: 如果用户在回调函数外进行应答, 需要自行保存msg_id, 因为回调函数入参在退出回调函数后将被SDK销毁, 不可以再访问到 */ /* { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_ASYNC_SERVICE_REPLY; msg.data.async_service_reply.msg_id = recv->data.async_service_invoke.msg_id; msg.data.async_service_reply.code = 200; msg.data.async_service_reply.service_id = "ToggleLightSwitch"; msg.data.async_service_reply.data = "{\"dataA\": 20}"; int32_t res = aiot_dm_send(dm_handle, &msg); if (res < 0) { printf("aiot_dm_send failed\r\n"); } } */ } break; /* 同步服务调用 */ case AIOT_DMRECV_SYNC_SERVICE_INVOKE: { printf("msg_id = %ld, rrpc_id = %s, service_id = %s, params = %.*s\r\n", (unsigned long)recv->data.sync_service_invoke.msg_id, recv->data.sync_service_invoke.rrpc_id, recv->data.sync_service_invoke.service_id, recv->data.sync_service_invoke.params_len, recv->data.sync_service_invoke.params); /* TODO: 以下代码演示如何对来自云平台的同步服务调用进行应答, 用户可取消注释查看演示效果 * * 注意: 如果用户在回调函数外进行应答, 需要自行保存msg_id和rrpc_id字符串, 因为回调函数入参在退出回调函数后将被SDK销毁, 不可以再访问到 */ /* { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_SYNC_SERVICE_REPLY; msg.data.sync_service_reply.rrpc_id = recv->data.sync_service_invoke.rrpc_id; msg.data.sync_service_reply.msg_id = recv->data.sync_service_invoke.msg_id; msg.data.sync_service_reply.code = 200; msg.data.sync_service_reply.service_id = "SetLightSwitchTimer"; msg.data.sync_service_reply.data = "{}"; int32_t res = aiot_dm_send(dm_handle, &msg); if (res < 0) { printf("aiot_dm_send failed\r\n"); } } */ } break; /* 下行二进制数据 */ case AIOT_DMRECV_RAW_DATA: { printf("raw data len = %d\r\n", recv->data.raw_data.data_len); /* TODO: 以下代码演示如何发送二进制格式数据, 若使用需要有相应的数据透传脚本部署在云端 */ /* { aiot_dm_msg_t msg; uint8_t raw_data[] = {0x01, 0x02}; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_RAW_DATA; msg.data.raw_data.data = raw_data; msg.data.raw_data.data_len = sizeof(raw_data); aiot_dm_send(dm_handle, &msg); } */ } break; /* 二进制格式的同步服务调用, 比单纯的二进制数据消息多了个rrpc_id */ case AIOT_DMRECV_RAW_SYNC_SERVICE_INVOKE: { printf("raw sync service rrpc_id = %s, data_len = %d\r\n", recv->data.raw_service_invoke.rrpc_id, recv->data.raw_service_invoke.data_len); } break; default: break; } } /* 属性上报函数演示 */ int32_t demo_send_property_post(void *dm_handle, char *params) { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_PROPERTY_POST; msg.data.property_post.params = params; return aiot_dm_send(dm_handle, &msg); } /* 事件上报函数演示 */ int32_t demo_send_event_post(void *dm_handle, char *event_id, char *params) { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_EVENT_POST; msg.data.event_post.event_id = event_id; msg.data.event_post.params = params; return aiot_dm_send(dm_handle, &msg); } /* 演示了获取属性LightSwitch的期望值, 用户可将此函数加入到main函数中运行演示 */ int32_t demo_send_get_desred_requset(void *dm_handle) { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_GET_DESIRED; msg.data.get_desired.params = "[\"LightSwitch\"]"; return aiot_dm_send(dm_handle, &msg); } /* 演示了删除属性LightSwitch的期望值, 用户可将此函数加入到main函数中运行演示 */ int32_t demo_send_delete_desred_requset(void *dm_handle) { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_DELETE_DESIRED; msg.data.get_desired.params = "{\"LightSwitch\":{}}"; return aiot_dm_send(dm_handle, &msg); } int demo_main(int argc, char *argv[]) { int32_t res = STATE_SUCCESS; void *dm_handle = NULL; void *mqtt_handle = NULL; char *url = "iot-as-mqtt.cn-shanghai.aliyuncs.com"; /* 阿里云平台上海站点的域名后缀 */ char host[100] = {0}; /* 用这个数组拼接设备连接的云平台站点全地址, 规则是 ${productKey}.iot-as-mqtt.cn-shanghai.aliyuncs.com */ uint16_t port = 443; /* 无论设备是否使用TLS连接阿里云平台, 目的端口都是443 */ aiot_sysdep_network_cred_t cred; /* 安全凭据结构体, 如果要用TLS, 这个结构体中配置CA证书等参数 */ /* TODO: 替换为自己设备的三元组 */ char *product_key = "产品key"; char *device_name = "设备名"; char *device_secret = "设备密钥"; /* 配置SDK的底层依赖 */ aiot_sysdep_set_portfile(&g_aiot_sysdep_portfile); /* 配置SDK的日志输出 */ aiot_state_set_logcb(demo_state_logcb); /* 创建SDK的安全凭据, 用于建立TLS连接 */ memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t)); cred.option = AIOT_SYSDEP_NETWORK_CRED_SVRCERT_CA; /* 使用RSA证书校验MQTT服务端 */ cred.max_tls_fragment = 16384; /* 最大的分片长度为16K, 其它可选值还有4K, 2K, 1K, 0.5K */ cred.sni_enabled = 1; /* TLS建连时, 支持Server Name Indicator */ cred.x509_server_cert = ali_ca_cert; /* 用来验证MQTT服务端的RSA根证书 */ cred.x509_server_cert_len = strlen(ali_ca_cert); /* 用来验证MQTT服务端的RSA根证书长度 */ /* 创建1个MQTT客户端实例并内部初始化默认参数 */ mqtt_handle = aiot_mqtt_init(); if (mqtt_handle == NULL) { printf("aiot_mqtt_init failed\n"); return -1; } snprintf(host, 100, "%s.%s", product_key, url); /* 配置MQTT服务器地址 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_HOST, (void *)host); /* 配置MQTT服务器端口 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PORT, (void *)&port); /* 配置设备productKey */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PRODUCT_KEY, (void *)product_key); /* 配置设备deviceName */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_NAME, (void *)device_name); /* 配置设备deviceSecret */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_SECRET, (void *)device_secret); /* 配置网络连接的安全凭据, 上面已经创建好了 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_NETWORK_CRED, (void *)&cred); /* 配置MQTT事件回调函数 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_EVENT_HANDLER, (void *)demo_mqtt_event_handler); /* 创建DATA-MODEL实例 */ dm_handle = aiot_dm_init(); if (dm_handle == NULL) { printf("aiot_dm_init failed"); return -1; } /* 配置MQTT实例句柄 */ aiot_dm_setopt(dm_handle, AIOT_DMOPT_MQTT_HANDLE, mqtt_handle); /* 配置消息接收处理回调函数 */ aiot_dm_setopt(dm_handle, AIOT_DMOPT_RECV_HANDLER, (void *)demo_dm_recv_handler); /* 与服务器建立MQTT连接 */ res = aiot_mqtt_connect(mqtt_handle); if (res < STATE_SUCCESS) { /* 尝试建立连接失败, 销毁MQTT实例, 回收资源 */ aiot_mqtt_deinit(&mqtt_handle); printf("aiot_mqtt_connect failed: -0x%04X\n", -res); return -1; } /* 创建一个单独的线程, 专用于执行aiot_mqtt_process, 它会自动发送心跳保活, 以及重发QoS1的未应答报文 */ g_mqtt_process_thread_running = 1; res = aos_task_new("demo_mqtt_process", demo_mqtt_process_thread, mqtt_handle, 4096); //res = pthread_create(&g_mqtt_process_thread, NULL, demo_mqtt_process_thread, mqtt_handle); if (res != 0) { printf("create demo_mqtt_process_thread failed: %d\n", res); return -1; } /* 创建一个单独的线程用于执行aiot_mqtt_recv, 它会循环收取服务器下发的MQTT消息, 并在断线时自动重连 */ g_mqtt_recv_thread_running = 1; res = aos_task_new("demo_mqtt_process", demo_mqtt_recv_thread, mqtt_handle, 4096); //res = pthread_create(&g_mqtt_recv_thread, NULL, demo_mqtt_recv_thread, mqtt_handle); if (res != 0) { printf("create demo_mqtt_recv_thread failed: %d\n", res); return -1; } /* 主循环进入休眠 */ while (1) { /* TODO: 以下代码演示了简单的属性上报和事件上报, 用户可取消注释观察演示效果 */ //demo_send_property_post(dm_handle, "{\"LightSwitch\": 0}"); //demo_send_event_post(dm_handle, "Error", "{\"ErrorCode\": 0}"); aos_msleep(10000); } /* 断开MQTT连接, 一般不会运行到这里 */ res = aiot_mqtt_disconnect(mqtt_handle); if (res < STATE_SUCCESS) { aiot_mqtt_deinit(&mqtt_handle); printf("aiot_mqtt_disconnect failed: -0x%04X\n", -res); return -1; } /* 销毁DATA-MODEL实例, 一般不会运行到这里 */ res = aiot_dm_deinit(&dm_handle); if (res < STATE_SUCCESS) { printf("aiot_dm_deinit failed: -0x%04X\n", -res); return -1; } /* 销毁MQTT实例, 一般不会运行到这里 */ res = aiot_mqtt_deinit(&mqtt_handle); if (res < STATE_SUCCESS) { printf("aiot_mqtt_deinit failed: -0x%04X\n", -res); return -1; } g_mqtt_process_thread_running = 0; g_mqtt_recv_thread_running = 0; return 0; }
YifuLiu/AliOS-Things
solutions/auto_demo/data_model_basic_demo.c
C
apache-2.0
16,885
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ /** * @file main.c * * This file includes the entry code of link sdk related demo * */ #include <string.h> #include <stdio.h> #include <aos/kernel.h> #include "ulog/ulog.h" #include "netmgr.h" #include <uservice/uservice.h> #include <uservice/eventid.h> #include "auto_app.h" extern int demo_main(int argc, char *argv[]); static int _ip_got_finished = 0; static void entry_func(void *data) { demo_main(0 , NULL); } static void wifi_event_cb(uint32_t event_id, const void *param, void *context) { if (event_id != EVENT_NETMGR_DHCP_SUCCESS) { return; } if(_ip_got_finished != 0) { return; } _ip_got_finished = 1; aos_task_new("link_dmeo", entry_func, NULL, 6*1024); } int application_start(int argc, char *argv[]) { aos_set_log_level(AOS_LL_DEBUG); event_service_init(NULL); netmgr_service_init(NULL); /*enable network auto reconnect*/ netmgr_set_auto_reconnect(NULL, true); /*enable auto save wifi config*/ netmgr_wifi_set_auto_save_ap(true); event_subscribe(EVENT_NETMGR_DHCP_SUCCESS, wifi_event_cb, NULL); auto_app_init(); while(1) { aos_msleep(1000); }; return 0; }
YifuLiu/AliOS-Things
solutions/auto_demo/main.c
C
apache-2.0
1,248
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <aos/kernel.h> #include "aos/init.h" #include "board.h" #include <k_api.h> #ifndef AOS_BINS extern int application_start(int argc, char *argv[]); #endif /* If board have no component for example board_xx_init, it indicates that this app does not support this board. Set the correspondence in file platform\board\aaboard_demo\ucube.py. */ extern void board_tick_init(void); extern void board_stduart_init(void); extern void board_dma_init(void); extern void board_gpio_init(void); extern void board_kinit_init(kinit_t* init_args); /* For user config kinit.argc = 0; kinit.argv = NULL; kinit.cli_enable = 1; */ static kinit_t kinit = {0, NULL, 1}; /** * @brief Board Initialization Function * @param None * @retval None */ void board_init(void) { board_tick_init(); board_stduart_init(); board_dma_init(); board_gpio_init(); } void aos_maintask(void* arg) { board_init(); board_kinit_init(&kinit); aos_components_init(&kinit); #ifndef AOS_BINS application_start(kinit.argc, kinit.argv); /* jump to app entry */ #endif }
YifuLiu/AliOS-Things
solutions/auto_demo/maintask.c
C
apache-2.0
1,192
#!/usr/bin/env python # -*- encoding: utf-8 -*- # version 1.0.1 import os import sys import re import codecs import time import json import argparse import inspect from ymodemfile import YModemfile try: import serial from serial.tools import miniterm from serial.tools.list_ports import comports except: print("\n\nNot found pyserial, please install: \nsudo pip install pyserial") sys.exit(0) def read_json(json_file): data = None if os.path.isfile(json_file): with open(json_file, 'r') as f: data = json.load(f) return data def write_json(json_file, data): with open(json_file, 'w') as f: f.write(json.dumps(data, indent=4, separators=(',', ': '))) def ymodemTrans(serialport, filename): def sender_getc(size): return serialport.read(size) or None def sender_putc(data, timeout=15): return serialport.write(data) sender = YModemfile(sender_getc, sender_putc) sent = sender.send_file(filename) def send_check_recv_data(serialport, pattern, timeout): """ receive serial data, and check it with pattern """ matcher = re.compile(pattern) tic = time.time() buff = serialport.read(128) while (time.time() - tic) < timeout: buff += serialport.read(128) if matcher.search(buff): return True return False def download_file(portnum, baudrate, filepath): # open serial port first serialport = serial.Serial() serialport.port = portnum serialport.baudrate = baudrate serialport.parity = "N" serialport.bytesize = 8 serialport.stopbits = 1 serialport.timeout = 0.05 try: serialport.open() except Exception as e: raise Exception("Failed to open serial port: %s!" % portnum) # send handshark world for check amp boot mode mylist = [0xA5] checkstatuslist = [0x5A] bmatched = False shakehand = False count = 0 reboot_count = 0 # step 1: check system status for i in range(300): serialport.write(serial.to_bytes(checkstatuslist)) time.sleep(0.1) buff = serialport.read(2) print(buff) # case 1: input == output is cli or repl mode if((buff) == b'Z'): # print('Read data OK'); reboot_count += 1 else: # not cli or repl mode is running mode print("Please reboot the board manually.") break if(reboot_count >= 4): # need reboot system print("Please reboot the board manually.") break # step 2: wait reboot and hand shakend cmd time.sleep(1) bmatched = send_check_recv_data(serialport, b'amp shakehand begin...', 10) # print(buff) if bmatched: print('amp shakehand begin...') for i in range(300): serialport.write(serial.to_bytes(mylist)) time.sleep(0.1) buff = serialport.read(2) print(buff) if((buff) == b'Z'): # print('Read data OK'); count += 1 if(count >= 4): shakehand = True if shakehand: break if i > 5: print("Please reboot the board manually.") break else: print("Please reboot the board manually, and try it again.") serialport.close() return # start send amp boot cmd time.sleep(0.1) print("start to send amp_boot cmd") cmd = 'amp_boot' serialport.write(cmd.encode()) # serialport.write(b'amp_boot') # send file transfer cmd time.sleep(0.1) # print("start to send file cmd") # cmd = 'cmd_file_transfer\n' # serialport.write(cmd.encode()) bmatched = send_check_recv_data(serialport, b'amp shakehand success', 2) # serialport.write(b'cmd_flash_js\n') # send file if bmatched: print("start to send file cmd") cmd = 'cmd_file_transfer\n' serialport.write(cmd.encode()) print('amp shakehand success') time.sleep(0.1) ymodemTrans(serialport, filepath) print("Ymodem transfer file finish") # send file transfer cmd time.sleep(0.1) print("send cmd exit") cmd = 'cmd_exit\n' serialport.write(cmd.encode()) else: print('amp shakehand failed, please reboot the boaard manually') # close serialport serialport.close() def get_downloadconfig(): """ get configuration from .config_burn file, if it is not existed, generate default configuration of chip_haas1000 """ configs = {} configs['chip_haas1000'] = {} configs['chip_haas1000']['serialport'] = '' configs['chip_haas1000']['baudrate'] = '' configs['chip_haas1000']['filepath'] = '' return configs['chip_haas1000'] def main2(): cmd_parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description='''Run and transfer file to system.''',) cmd_parser.add_argument('-d', '--device', default='', help='the serial device or the IP address of the pyboard') cmd_parser.add_argument( '-b', '--baudrate', default=115200, help='the baud rate of the serial device') cmd_parser.add_argument('files', nargs='*', help='input transfer files') args = cmd_parser.parse_args() print(args) # download file # step 1: set config downloadconfig = get_downloadconfig() # step 2: get serial port if not downloadconfig["serialport"]: downloadconfig["serialport"] = args.device if not downloadconfig["serialport"]: downloadconfig["serialport"] = miniterm.ask_for_port() if not downloadconfig["serialport"]: print("no specified serial port") return else: needsave = True # step 3: get baudrate if not downloadconfig["baudrate"]: downloadconfig["baudrate"] = args.baudrate if not downloadconfig["baudrate"]: downloadconfig["baudrate"] = "115200" # step 4: get transfer file if not downloadconfig["filepath"]: downloadconfig["filepath"] = args.files if not downloadconfig["filepath"]: print('no file wait to transfer') return if os.path.isabs("".join(downloadconfig["filepath"])): filepath = "".join(downloadconfig["filepath"]) print('the filepath is abs path') else: basepath = os.path.abspath('.') filepath = basepath + '/' + "".join(downloadconfig["filepath"]) print('the filepath is not abs path') print("serial port is %s" % downloadconfig["serialport"]) print("transfer baudrate is %s" % downloadconfig["baudrate"]) # print(base_path(downloadconfig["filepath"])) print("filepath is %s" % filepath) # print("the settings were restored in the file %s" % os.path.join(os.getcwd(), '.config_burn')) # step 3: download file download_file(downloadconfig["serialport"], downloadconfig['baudrate'], filepath) if __name__ == "__main__": main2()
YifuLiu/AliOS-Things
solutions/block_demo/.utility/python/transymodem.py
Python
apache-2.0
7,164
#! /usr/bin/env python # -*- coding: utf-8 -*- #version 1.0.0 """ MIT License Copyright (c) 2018 Alex Woo Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import os, sys, math, time, string, struct # ymodem data header byte SOH = b'\x01' STX = b'\x02' EOT = b'\x04' ACK = b'\x06' NAK = b'\x15' CAN = b'\x18' CRC = b'C' class SendTask(object): def __init__(self): self._task_name = "" self._task_size = 0 self._task_packets = 0 self._last_valid_packets_size = 0 self._sent_packets = 0 self._missing_sent_packets = 0 self._valid_sent_packets = 0 self._valid_sent_bytes = 0 def inc_sent_packets(self): self._sent_packets += 1 def inc_missing_sent_packets(self): self._missing_sent_packets += 1 def inc_valid_sent_packets(self): self._valid_sent_packets += 1 def add_valid_sent_bytes(self, this_valid_sent_bytes): self._valid_sent_bytes += this_valid_sent_bytes def get_valid_sent_packets(self): return self._valid_sent_packets def get_valid_sent_bytes(self): return self._valid_sent_bytes def set_task_name(self, data_name): self._task_name = data_name def set_task_size(self, data_size): self._task_size = data_size self._task_packets = math.ceil(data_size / 1024) self._last_valid_packets_size = data_size % 1024 class ReceiveTask(object): def __init__(self): self._task_name = "" self._task_size = 0 self._task_packets = 0 self._last_valid_packets_size = 0 self._received_packets = 0 self._missing_received_packets = 0 self._valid_received_packets = 0 self._valid_received_bytes = 0 def inc_received_packets(self): self._received_packets += 1 def inc_missing_received_packets(self): self._missing_received_packets += 1 def inc_valid_received_packets(self): self._valid_received_packets += 1 def add_valid_received_bytes(self, this_valid_received_bytes): self._valid_received_bytes += this_valid_received_bytes def get_task_packets(self): return self._task_packets def get_last_valid_packet_size(self): return self._last_valid_packets_size def get_valid_received_packets(self): return self._valid_received_packets def get_valid_received_bytes(self): return self._valid_received_bytes def set_task_name(self, data_name): self._task_name = data_name def set_task_size(self, data_size): self._task_size = data_size self._task_packets = math.ceil(data_size / 1024) self._last_valid_packets_size = data_size % 1024 def get_task_name(self): return self._task_name def get_task_size(self): return self._task_size class YModemfile(object): def __init__(self, getc, putc, header_pad=b'\x00', data_pad=b'\x1a'): self.getc = getc self.putc = putc self.st = SendTask() self.rt = ReceiveTask() self.header_pad = header_pad self.data_pad = data_pad def abort(self, count=2): for _ in range(count): self.putc(CAN) def send_file(self, file_path, retry=20, callback=None): try: file_stream = open(file_path, 'rb') file_name = os.path.basename(file_path) file_size = os.path.getsize(file_path) file_sent = self.send(file_stream, file_name, file_size, retry, callback) except IOError as e: print(str(e)) finally: file_stream.close() print("File: " + file_name) print("Size: " + str(file_sent) + "Bytes") return file_sent def wait_for_next(self, ch): cancel_count = 0 while True: c = self.getc(1) if c: if c == ch: print("<<< " + hex(ord(ch))) break elif c == CAN: if cancel_count == 2: return -1 else: cancel_count += 1 else: # print("Expected " + hex(ord(ch)) + ", but got " + hex(ord(c))) print("Expected " + hex(ord(ch)) + ", but got " + str(c)) return 0 def send(self, data_stream, data_name, data_size, retry=20, callback=None): packet_size = 1024 # [<<< CRC] self.wait_for_next(CRC) # [first packet >>>] header = self._make_edge_packet_header() if len(data_name) > 100: data_name = data_name[:100] self.st.set_task_name(data_name) data_name += bytes.decode(self.header_pad) data_size = str(data_size) if len(data_size) > 20: raise Exception("Data volume is too large!") self.st.set_task_size(int(data_size)) data_size += bytes.decode(self.header_pad) data = data_name + data_size data = data.ljust(128, bytes.decode(self.header_pad)) checksum = self._make_send_checksum(data) data_for_send = header + data.encode() + checksum self.putc(data_for_send) self.st.inc_sent_packets() # data_in_hexstring = "".join("%02x" % b for b in data_for_send) print("Packet 0 >>>") # print(str(data_for_send)) # [<<< ACK] # [<<< CRC] self.wait_for_next(ACK) self.wait_for_next(CRC) # [data packet >>>] # [<<< ACK] error_count = 0 sequence = 1 while True: data = data_stream.read(packet_size) if not data: print('EOF') break extracted_data_bytes = len(data) if extracted_data_bytes <= 128: packet_size = 128 header = self._make_data_packet_header(packet_size, sequence) data = data.ljust(packet_size, self.data_pad) checksum = self._make_send_checksum(data) data_for_send = header + data + checksum # data_in_hexstring = "".join("%02x" % b for b in data_for_send) while True: self.putc(data_for_send) self.st.inc_sent_packets() print("Packet " + str(sequence) + " >>>") # print(str(data_for_send)) time.sleep(0.1) c = self.getc(1) # print(str(c)) if c == ACK: print("<<< ACK") self.st.inc_valid_sent_packets() self.st.add_valid_sent_bytes(extracted_data_bytes) error_count = 0 break elif c == NAK: error_count += 1 self.st.inc_missing_sent_packets() print("RETRY NAK" + str(error_count)) if error_count > retry: self.abort() print('send error: NAK received, aborting') return -2 else: # c = self.getc(120) print(str(c)) error_count += 1 self.st.inc_missing_sent_packets() print("RETRY " + str(error_count)) if error_count > retry: self.abort() print('send error. aborting') return -2 sequence = (sequence + 1) % 0x100 # [EOT >>>] # [<<< NAK] # [EOT >>>] # [<<< ACK] self.putc(EOT) print(">>> EOT") self.wait_for_next(NAK) self.putc(EOT) print(">>> EOT") self.wait_for_next(ACK) # [<<< CRC] self.wait_for_next(CRC) # [Final packet >>>] header = self._make_edge_packet_header() if sys.version_info.major == 2: data = bytes.decode("").ljust(128, bytes.decode(self.header_pad)) else: data = "".ljust(128, bytes.decode(self.header_pad)) checksum = self._make_send_checksum(data) data_for_send = header + data.encode() + checksum self.putc(data_for_send) self.st.inc_sent_packets() print("Packet End >>>") self.wait_for_next(ACK) return self.st.get_valid_sent_bytes() def wait_for_header(self): cancel_count = 0 while True: c = self.getc(1) if c: if c == SOH or c == STX: return c elif c == CAN: if cancel_count == 2: return -1 else: cancel_count += 1 else: print("Expected 0x01(SOH)/0x02(STX)/0x18(CAN), but got " + hex(ord(c))) def wait_for_eot(self): eot_count = 0 while True: c = self.getc(1) if c: if c == EOT: eot_count += 1 if eot_count == 1: print("EOT >>>") self.putc(NAK) print("<<< NAK") elif eot_count == 2: print("EOT >>>") self.putc(ACK) print("<<< ACK") self.putc(CRC) print("<<< CRC") break else: print("Expected 0x04(EOT), but got " + hex(ord(c))) def recv_file(self, root_path, callback=None): while True: self.putc(CRC) print("<<< CRC") c = self.getc(1) if c: if c == SOH: packet_size = 128 break elif c == STX: packet_size = 1024 break else: print("Expected 0x01(SOH)/0x02(STX)/0x18(CAN), but got " + hex(ord(c))) IS_FIRST_PACKET = True FIRST_PACKET_RECEIVED = False WAIT_FOR_EOT = False WAIT_FOR_END_PACKET = False sequence = 0 while True: if WAIT_FOR_EOT: self.wait_for_eot() WAIT_FOR_EOT = False WAIT_FOR_END_PACKET = True sequence = 0 else: if IS_FIRST_PACKET: IS_FIRST_PACKET = False else: c = self.wait_for_header() if c == SOH: packet_size = 128 elif c == STX: packet_size = 1024 else: return c seq = self.getc(1) if seq is None: seq_oc = None else: seq = ord(seq) c = self.getc(1) if c is not None: seq_oc = 0xFF - ord(c) data = self.getc(packet_size + 2) if not (seq == seq_oc == sequence): continue else: valid, _ = self._verify_recv_checksum(data) if valid: # first packet # [<<< ACK] # [<<< CRC] if seq == 0 and not FIRST_PACKET_RECEIVED and not WAIT_FOR_END_PACKET: print("Packet 0 >>>") self.putc(ACK) print("<<< ACK") self.putc(CRC) print("<<< CRC") file_name_bytes, data_size_bytes = (data[:-2]).rstrip(self.header_pad).split(self.header_pad) file_name = bytes.decode(file_name_bytes) data_size = bytes.decode(data_size_bytes) print("TASK: " + file_name + " " + data_size + "Bytes") self.rt.set_task_name(file_name) self.rt.set_task_size(int(data_size)) file_stream = open(os.path.join(root_path, file_name), 'wb+') FIRST_PACKET_RECEIVED = True sequence = (sequence + 1) % 0x100 # data packet # [data packet >>>] # [<<< ACK] elif not WAIT_FOR_END_PACKET: self.rt.inc_valid_received_packets() print("Packet " + str(sequence) + " >>>") valid_data = data[:-2] # last data packet if self.rt.get_valid_received_packets() == self.rt.get_task_packets(): valid_data = valid_data[:self.rt.get_last_valid_packet_size()] WAIT_FOR_EOT = True self.rt.add_valid_received_bytes(len(valid_data)) file_stream.write(valid_data) self.putc(ACK) print("<<< ACK") sequence = (sequence + 1) % 0x100 # final packet # [<<< ACK] else: print("Packet End >>>") self.putc(ACK) print("<<< ACK") break file_stream.close() print("File: " + self.rt.get_task_name()) print("Size: " + str(self.rt.get_task_size()) + "Bytes") return self.rt.get_valid_received_bytes() # Header byte def _make_edge_packet_header(self): _bytes = [ord(SOH), 0, 0xff] return bytearray(_bytes) def _make_data_packet_header(self, packet_size, sequence): assert packet_size in (128, 1024), packet_size _bytes = [] if packet_size == 128: _bytes.append(ord(SOH)) elif packet_size == 1024: _bytes.append(ord(STX)) _bytes.extend([sequence, 0xff - sequence]) return bytearray(_bytes) # Make check code def _make_send_checksum(self, data): _bytes = [] crc = self.calc_crc(data) _bytes.extend([crc >> 8, crc & 0xff]) return bytearray(_bytes) def _verify_recv_checksum(self, data): _checksum = bytearray(data[-2:]) their_sum = (_checksum[0] << 8) + _checksum[1] data = data[:-2] our_sum = self.calc_crc(data) valid = bool(their_sum == our_sum) return valid, data # For CRC algorithm crctable = [ 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0, ] # CRC algorithm: CCITT-0 def calc_crc(self, data, crc=0): if sys.version_info.major == 2: ba = struct.unpack("@%dB" % len(data), data) else: if isinstance(data, str): ba = bytearray(data, 'utf-8') else: ba = bytearray(data) for char in ba: crctbl_idx = ((crc >> 8) ^ char) & 0xff crc = ((crc << 8) ^ self.crctable[crctbl_idx]) & 0xffff return crc & 0xffff
YifuLiu/AliOS-Things
solutions/block_demo/.utility/python/ymodemfile.py
Python
apache-2.0
18,669
CPRE := @ ifeq ($(V),1) CPRE := VERB := --verbose endif .PHONY:startup startup: all all: @echo "Build Solution by $(BOARD) " $(CPRE) scons $(VERB) --board=$(BOARD) $(MULTITHREADS) $(MAKEFLAGS) @echo AOS SDK Done sdk: $(CPRE) aos sdk .PHONY:clean clean: $(CPRE) scons -c --board=$(BOARD) $(CPRE) find . -name "*.[od]" -delete $(CPRE) rm -rf aos_sdk aos.elf aos.map aos.bin generated out
YifuLiu/AliOS-Things
solutions/eduk1_demo/Makefile
Makefile
apache-2.0
397
#! /bin/env python from aostools import Make # defconfig = Make(elf='yoc.elf', objcopy='generated/data/prim', objdump='yoc.asm') defconfig = Make(elf='aos.elf', objcopy='aos.bin') Export('defconfig') defconfig.build_components()
YifuLiu/AliOS-Things
solutions/eduk1_demo/SConstruct
Python
apache-2.0
233
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/init.h" #include "board.h" #include "k1_apps/menu.h" #include <aos/errno.h> #include <aos/kernel.h> #include <k_api.h> #include <stdio.h> #include <stdlib.h> #include <uservice/eventid.h> // #include "drivers/lcd/st7789v/st7789v_vfs.h" // #include "drivers/lcd/st7789v/st7789v.h" #include "netmgr.h" extern int board_test(void); extern void vendor_cli_register_init(void); int g_haasboard_is_k1c = 0; int bt_connected = 0; int wifi_connected = 0; int ip_got_finished = 0; char eduk1_ip_addr[IPADDR_STR_LEN] = {0}; int demo_main(int argc, char *argv[]) { int ret = 0; while (1) { if (wifi_connected && !ip_got_finished) { ret = netmgr_wifi_get_ip_addr(&eduk1_ip_addr); if (ret ==0) ip_got_finished = 1; } aos_msleep(1000); } } static void entry_func(void *data) { demo_main(0 , NULL); } static void wifi_event_cb(uint32_t event_id, const void *param, void *context) { switch (event_id) { case EVENT_NETMGR_DHCP_SUCCESS: wifi_connected = 1; aos_task_new("link_dmeo", entry_func, NULL, 6*1024); break; case EVENT_NETMGR_WIFI_DISCONNECTED: wifi_connected = 0; break; default: break; } return; } extern int haasedu_is_k1c(); int application_start(int argc, char **argv) { int ret; aos_set_log_level(AOS_LL_INFO); event_service_init(NULL); netmgr_service_init(NULL); /*enable network auto reconnect*/ netmgr_set_auto_reconnect(NULL, true); /*enable auto save wifi config*/ netmgr_wifi_set_auto_save_ap(true); event_subscribe(EVENT_NETMGR_DHCP_SUCCESS, wifi_event_cb, NULL); g_haasboard_is_k1c = haasedu_is_k1c(); sh1106_init(); menu_init(); ret = BleCfg_run(); if (ret) { return ret; } aos_msleep(100); (void)BleCfg_recovery_wifi(); (void)BleCfg_recovery_devinfo(); return 0; }
YifuLiu/AliOS-Things
solutions/eduk1_demo/app_start.c
C
apache-2.0
2,053
#define BUILD_VERSION "1.1.0"
YifuLiu/AliOS-Things
solutions/eduk1_demo/build_version.h
C
apache-2.0
30
#include "aircraftBattle.h" #include <stdio.h> #include <stdlib.h> MENU_COVER_TYP aircraftBattle_cover = {MENU_COVER_FUNC, NULL, NULL, aircraftBattle_cover_draw}; MENU_TASK_TYP aircraftBattle_tasks = {aircraftBattle_init, aircraftBattle_uninit}; MENU_TYP aircraftBattle = {"aircraftBattle", &aircraftBattle_cover, &aircraftBattle_tasks, aircraftBattle_key_handel, NULL}; static aos_task_t aircraftBattle_task_handle; #define MAX_L_CRAFT 1 #define MAX_M_CRAFT 5 #define MAX_S_CRAFT 10 #define MAX_BULLET 30 #define MY_CHANCE 3 #define AUTO_RELOAD -1024 uint8_t g_chance = MY_CHANCE; dfo_t *my_craft; dfo_t **bullet_group; dfo_t **enemy_crafts; static map_t achilles_normal0_map = {&icon_Mycraft0_19_19, -9, -9}; static map_t achilles_normal1_map = {&icon_Mycraft1_19_19, -9, -9}; static map_t achilles_normal2_map = {&icon_Mycraft2_19_19, -9, -9}; static map_t *achilles_normal_maplist[3] = { &achilles_normal0_map, &achilles_normal1_map, &achilles_normal2_map}; static map_t achilles_destory0_map = {&icon_Mycraft_destory0_19_19, -9, -9}; static map_t achilles_destory1_map = {&icon_Mycraft_destory1_19_19, -9, -9}; static map_t achilles_destory2_map = {&icon_Mycraft_destory2_16_16, -7, -7}; static map_t *achilles_destory_maplist[3] = { &achilles_destory0_map, &achilles_destory1_map, &achilles_destory2_map}; static arms_t achilles_arms0 = {-6, -3}; static arms_t achilles_arms1 = {6, -3}; static arms_t *achilles_arms_list[2] = {&achilles_arms0, &achilles_arms1}; static map_t titan_normal0_map = {&icon_Lcraft_32_32, -15, -15}; static map_t *titan_normal_maplist[1] = {&titan_normal0_map}; static map_t titan_destory0_map = {&icon_Lcraft_destory0_32_32, -15, -15}; static map_t titan_destory1_map = {&icon_Lcraft_destory1_32_32, -15, -15}; static map_t titan_destory2_map = {&icon_Lcraft_destory2_32_32, -15, -15}; static map_t *titan_destory_maplist[3] = { &titan_destory0_map, &titan_destory1_map, &titan_destory2_map}; static map_t ares_normal0_map = {&icon_Mcraft_12_12, -5, -5}; static map_t *ares_normal_maplist[1] = {&ares_normal0_map}; static map_t ares_destory0_map = {&icon_Mcraft_destory0_12_12, -5, -5}; static map_t ares_destory1_map = {&icon_Mcraft_destory1_12_12, -5, -5}; static map_t ares_destory2_map = {&icon_Mcraft_destory2_12_12, -5, -5}; static map_t *ares_destory_maplist[3] = {&ares_destory0_map, &ares_destory1_map, &ares_destory2_map}; static map_t venture_normal0_map = {&icon_Scraft_7_8, -3, -3}; static map_t *venture_normal_maplist[1] = {&venture_normal0_map}; static map_t venture_destory0_map = {&icon_Scraft_destory0_9_8, -4, -4}; static map_t venture_destory1_map = {&icon_Scraft_destory1_9_8, -4, -4}; static map_t venture_destory2_map = {&icon_Scraft_destory2_7_6, -3, -3}; static map_t *venture_destory_maplist[3] = { &venture_destory0_map, &venture_destory1_map, &venture_destory2_map}; static map_t bullet_map = {&icon_bullet_2_1, 0, -1}; static map_t *bullet_maplist[1] = {&bullet_map}; void aircraftBattle_cover_draw(int *draw_index) { OLED_Clear(); OLED_Icon_Draw(0, 0, &img_craft_bg_132_64, 1); for (int i = 0; i < random() % 20; i++) { OLED_DrawPoint(random() % 132, random() % 64, 1); } for (int i = 0; i < random() % 10; i++) { OLED_Icon_Draw(random() % 132, random() % 64, &icon_mini_start_3_3, 0); } OLED_Icon_Draw(2, 24, &icon_skip_left, 0); OLED_Icon_Draw(122, 24, &icon_skip_right, 0); OLED_Refresh_GRAM(); aos_msleep(800); return 0; } dfo_t *create_achilles() { dfo_t *achilles = (dfo_t *)malloc(sizeof(dfo_t)); achilles->act_seq_list_len = 2; act_seq_t *achilles_normal_act = (act_seq_t *)malloc(sizeof(act_seq_t)); achilles_normal_act->act_seq_maps = achilles_normal_maplist; achilles_normal_act->act_seq_len = 3; achilles_normal_act->act_seq_interval = 10; achilles_normal_act->act_is_destory = 0; act_seq_t *achilles_destory_act = (act_seq_t *)malloc(sizeof(act_seq_t)); achilles_destory_act->act_seq_maps = achilles_destory_maplist; achilles_destory_act->act_seq_len = 3; achilles_destory_act->act_seq_interval = 4; achilles_destory_act->act_is_destory = 1; act_seq_t **achilles_act_seq_list = (act_seq_t **)malloc(sizeof(act_seq_t *) * achilles->act_seq_list_len); achilles_act_seq_list[0] = achilles_normal_act; achilles_act_seq_list[1] = achilles_destory_act; achilles->model = Achilles; achilles->speed = 4; achilles->range = -1; achilles->act_seq_list = achilles_act_seq_list; achilles->act_seq_type = 0; achilles->damage = 8; achilles->full_life = 10; achilles->cur_life = 10; achilles->arms_list_len = 2; achilles->arms_list = achilles_arms_list; reload_dfo(achilles, 31, 116); return achilles; } dfo_t *create_titan() { dfo_t *titan = (dfo_t *)malloc(sizeof(dfo_t)); titan->act_seq_list_len = 2; act_seq_t *titan_normal_act = (act_seq_t *)malloc(sizeof(act_seq_t)); titan_normal_act->act_seq_maps = titan_normal_maplist; titan_normal_act->act_seq_len = 1; titan_normal_act->act_seq_interval = 0; titan_normal_act->act_is_destory = 0; act_seq_t *titan_destory_act = (act_seq_t *)malloc(sizeof(act_seq_t)); titan_destory_act->act_seq_maps = titan_destory_maplist; titan_destory_act->act_seq_len = 3; titan_destory_act->act_seq_interval = 4; titan_destory_act->act_is_destory = 1; act_seq_t **titan_act_seq_list = (act_seq_t **)malloc(sizeof(act_seq_t *) * titan->act_seq_list_len); titan_act_seq_list[0] = titan_normal_act; titan_act_seq_list[1] = titan_destory_act; titan->model = TiTan; titan->speed = 1; titan->range = -1; titan->act_seq_list = titan_act_seq_list; titan->act_seq_type = 0; titan->damage = 100; titan->full_life = 60; titan->cur_life = 60; titan->arms_list_len = 0; titan->arms_list = NULL; reload_dfo(titan, AUTO_RELOAD, AUTO_RELOAD); return titan; } dfo_t *create_ares() { dfo_t *ares = (dfo_t *)malloc(sizeof(dfo_t)); ares->act_seq_list_len = 2; act_seq_t *ares_normal_act = (act_seq_t *)malloc(sizeof(act_seq_t)); ares_normal_act->act_seq_maps = ares_normal_maplist; ares_normal_act->act_seq_len = 1; ares_normal_act->act_seq_interval = 0; ares_normal_act->act_is_destory = 0; act_seq_t *ares_destory_act = (act_seq_t *)malloc(sizeof(act_seq_t)); ares_destory_act->act_seq_maps = ares_destory_maplist; ares_destory_act->act_seq_len = 3; ares_destory_act->act_seq_interval = 3; ares_destory_act->act_is_destory = 1; act_seq_t **ares_act_seq_list = (act_seq_t **)malloc(sizeof(act_seq_t *) * ares->act_seq_list_len); ares_act_seq_list[0] = ares_normal_act; ares_act_seq_list[1] = ares_destory_act; ares->model = Ares; ares->speed = 2; ares->range = -1; ares->act_seq_list = ares_act_seq_list; ares->act_seq_type = 0; ares->damage = 8; ares->full_life = 10; ares->cur_life = 10; ares->arms_list_len = 0; ares->arms_list = NULL; reload_dfo(ares, AUTO_RELOAD, AUTO_RELOAD); return ares; } dfo_t *create_venture() { dfo_t *venture = (dfo_t *)malloc(sizeof(dfo_t)); venture->act_seq_list_len = 2; act_seq_t *venture_normal_act = (act_seq_t *)malloc(sizeof(act_seq_t)); venture_normal_act->act_seq_maps = venture_normal_maplist; venture_normal_act->act_seq_len = 1; venture_normal_act->act_seq_interval = 0; venture_normal_act->act_is_destory = 0; act_seq_t *venture_destory_act = (act_seq_t *)malloc(sizeof(act_seq_t)); venture_destory_act->act_seq_maps = venture_destory_maplist; venture_destory_act->act_seq_len = 3; venture_destory_act->act_seq_interval = 2; venture_destory_act->act_is_destory = 1; act_seq_t **venture_act_seq_list = (act_seq_t **)malloc(sizeof(act_seq_t *) * venture->act_seq_list_len); venture_act_seq_list[0] = venture_normal_act; venture_act_seq_list[1] = venture_destory_act; venture->model = Venture; venture->speed = 3; venture->range = -1; venture->act_seq_list = venture_act_seq_list; venture->act_seq_type = 0; venture->damage = 5; venture->full_life = 2; venture->cur_life = 2; venture->arms_list_len = 0; venture->arms_list = NULL; reload_dfo(venture, AUTO_RELOAD, AUTO_RELOAD); return venture; } dfo_t *create_bullet() { dfo_t *bullet = (dfo_t *)malloc(sizeof(dfo_t)); bullet->act_seq_list_len = 1; act_seq_t *bullet_normal_act = (act_seq_t *)malloc(sizeof(act_seq_t)); bullet_normal_act->act_seq_maps = bullet_maplist; bullet_normal_act->act_seq_len = 1; bullet_normal_act->act_seq_interval = 0; bullet_normal_act->act_is_destory = 0; act_seq_t **bullet_act_seq_list = (act_seq_t **)malloc(sizeof(act_seq_t *) * bullet->act_seq_list_len); bullet_act_seq_list[0] = bullet_normal_act; bullet->model = Bullet; bullet->speed = 10; bullet->range = 120; bullet->act_seq_list = bullet_act_seq_list; bullet->act_seq_type = 0; bullet->damage = 1; bullet->full_life = 1; bullet->cur_life = 0; bullet->arms_list_len = 0; bullet->arms_list = NULL; bullet->start_x = -100; bullet->start_y = -100; bullet->cur_x = -100; bullet->cur_y = -100; return bullet; } void free_dfo(dfo_t *dfo) { for (int i = 0; i < dfo->act_seq_list_len; i++) { free(dfo->act_seq_list[i]); } free(dfo->act_seq_list); free(dfo); } void global_create(void) { my_craft = create_achilles(); bullet_group = (dfo_t **)malloc(sizeof(dfo_t *) * MAX_BULLET); for (int i = 0; i < MAX_BULLET; i++) { bullet_group[i] = create_bullet(); } enemy_crafts = (dfo_t **)malloc(sizeof(dfo_t *) * (MAX_L_CRAFT + MAX_M_CRAFT + MAX_S_CRAFT)); for (int i = 0; i < MAX_L_CRAFT + MAX_M_CRAFT + MAX_S_CRAFT; i++) { if (i < MAX_L_CRAFT) enemy_crafts[i] = create_titan(); else if (i < MAX_L_CRAFT + MAX_M_CRAFT && i >= MAX_L_CRAFT) enemy_crafts[i] = create_ares(); else if (i < MAX_L_CRAFT + MAX_M_CRAFT + MAX_S_CRAFT && i >= MAX_L_CRAFT + MAX_M_CRAFT) enemy_crafts[i] = create_venture(); } } void aircraftBattle_key_handel(key_code_t key_code) { switch (key_code) { case 0b1000: move_MyCraft(my_craft, LEFT); break; case 0b0001: move_MyCraft(my_craft, UP); break; case 0b0100: move_MyCraft(my_craft, DOWN); break; case 0b0010: move_MyCraft(my_craft, RIGHT); break; default: break; } } map_t *get_cur_map(dfo_t *craft) { act_seq_t *cur_act_seq = craft->act_seq_list[craft->act_seq_type]; map_t *cur_map = cur_act_seq->act_seq_maps[cur_act_seq->act_seq_index]; return cur_map; } void reload_dfo(dfo_t *craft, int pos_x, int pos_y) { for (int i = 0; i < craft->act_seq_list_len; i++) { craft->act_seq_list[i]->act_seq_index = 0; craft->act_seq_list[i]->act_seq_interval_cnt = 0; } craft->start_x = pos_x; craft->start_y = pos_y; if (pos_x == AUTO_RELOAD) { uint16_t height = get_cur_map(craft)->icon->width; craft->start_x = random() % (64 - height) + height / 2; } if (pos_y == AUTO_RELOAD) { uint16_t width = get_cur_map(craft)->icon->height; craft->start_y = -(random() % 1000) - width / 2; } if (craft->model != Bullet) LOGI(EDU_TAG, "reset craft %d at %d,%d\n", craft->model, craft->start_x, craft->start_y); craft->cur_x = craft->start_x; craft->cur_y = craft->start_y; craft->cur_life = craft->full_life; craft->act_seq_type = 0; } void destory(dfo_t *craft) { craft->act_seq_type = 1; craft->cur_life = 0; } void move_enemy(dfo_t *craft) { if (craft->cur_life <= 0) return; map_t *cur_map = get_cur_map(craft); craft->cur_y += craft->speed; int top = craft->cur_y + cur_map->offset_y; if (top > 132) reload_dfo(craft, AUTO_RELOAD, AUTO_RELOAD); } void move_MyCraft(dfo_t *my_craft, my_craft_dir_e_t dir) { if (my_craft->cur_life <= 0) return; map_t *cur_map = get_cur_map(my_craft); int top = my_craft->cur_y + cur_map->offset_y; int bottom = my_craft->cur_y + cur_map->offset_y + cur_map->icon->width; int left = my_craft->cur_x + cur_map->offset_x; int right = my_craft->cur_x + cur_map->offset_x + cur_map->icon->height; switch (dir) { case UP: if (!(top - my_craft->speed < 0)) my_craft->cur_y -= my_craft->speed; break; case DOWN: if (!(bottom + my_craft->speed > 132)) my_craft->cur_y += my_craft->speed; break; case LEFT: if (!(left - my_craft->speed < 0)) my_craft->cur_x -= my_craft->speed; break; case RIGHT: if (!(right + my_craft->speed > 64)) my_craft->cur_x += my_craft->speed; break; default: break; } } void move_bullet(dfo_t *bullet) { if (bullet->cur_life <= 0) return; map_t *cur_map = get_cur_map(bullet); bullet->cur_y -= bullet->speed; int bottom = bullet->cur_y + cur_map->offset_y + cur_map->icon->width; if (bottom < 0 || (bullet->start_y - bullet->cur_y) > bullet->range) { bullet->cur_life = 0; bullet->cur_x = -100; } } dfo_t *get_deactived_bullet() { for (int i = 0; i < MAX_BULLET; i++) { if (bullet_group[i]->cur_life <= 0) return bullet_group[i]; } return NULL; } void shut_craft(dfo_t *craft) { if (craft->cur_life <= 0) return; if (craft->arms_list == NULL || craft->arms_list_len == 0) return; for (int i = 0; i < craft->arms_list_len; i++) { dfo_t *bullet = get_deactived_bullet(); if (bullet == NULL) return; reload_dfo(bullet, craft->cur_x + craft->arms_list[i]->offset_x, craft->cur_y + craft->arms_list[i]->offset_y); } } void draw_dfo(dfo_t *dfo) { map_t *cur_map = get_cur_map(dfo); int top = dfo->cur_y + cur_map->offset_y; int bottom = dfo->cur_y + cur_map->offset_y + cur_map->icon->width; int left = dfo->cur_x + cur_map->offset_x; int right = dfo->cur_x + cur_map->offset_x + cur_map->icon->height; if (top > 132 || bottom < 0 || left > 64 || right < 0) return; OLED_Icon_Draw(dfo->cur_y + cur_map->offset_y, 64 - (dfo->cur_x + cur_map->offset_x + cur_map->icon->height), cur_map->icon, 2); } void craft_update_act(dfo_t *craft) { act_seq_t *cur_act_seq = craft->act_seq_list[craft->act_seq_type]; if (cur_act_seq->act_seq_interval == 0) return; ++(cur_act_seq->act_seq_interval_cnt); if (cur_act_seq->act_seq_interval_cnt >= cur_act_seq->act_seq_interval) { cur_act_seq->act_seq_interval_cnt = 0; ++(cur_act_seq->act_seq_index); if (cur_act_seq->act_seq_index >= cur_act_seq->act_seq_len) { cur_act_seq->act_seq_index = 0; if (cur_act_seq->act_is_destory == 1) { switch (craft->model) { case Achilles: reload_dfo(craft, 31, 116); break; case Venture: case Ares: case TiTan: reload_dfo(craft, AUTO_RELOAD, AUTO_RELOAD); break; case Bullet: break; default: break; } } } } } void global_update(void) { for (int i = 0; i < MAX_L_CRAFT + MAX_M_CRAFT + MAX_S_CRAFT; i++) { craft_update_act(enemy_crafts[i]); move_enemy(enemy_crafts[i]); } for (int i = 0; i < MAX_BULLET; i++) { move_bullet(bullet_group[i]); } craft_update_act(my_craft); shut_craft(my_craft); global_hit_check(); } void global_draw(void) { for (int i = 0; i < MAX_L_CRAFT + MAX_M_CRAFT + MAX_S_CRAFT; i++) { draw_dfo(enemy_crafts[i]); } for (int i = 0; i < MAX_BULLET; i++) { draw_dfo(bullet_group[i]); } draw_dfo(my_craft); } int hit_check(dfo_t *bullet, dfo_t *craft) { if (craft->cur_y <= 0 || craft->cur_x <= 0) return 0; if (craft->cur_life <= 0) return 0; if (bullet->cur_life <= 0) return 0; act_seq_t *cur_act_seq = bullet->act_seq_list[bullet->act_seq_type]; map_t *cur_map = cur_act_seq->act_seq_maps[cur_act_seq->act_seq_index]; for (int bullet_bit_x = 0; bullet_bit_x < (cur_map->icon->height); bullet_bit_x++) { for (int bullet_bit_y = 0; bullet_bit_y < (cur_map->icon->width); bullet_bit_y++) { uint8_t bit = (cur_map->icon->p_icon_mask == NULL) ? cur_map->icon ->p_icon_data[bullet_bit_x / 8 + bullet_bit_y] & (0x01 << bullet_bit_x % 8) : cur_map->icon ->p_icon_mask[bullet_bit_x / 8 + bullet_bit_y] & (0x01 << bullet_bit_x % 8); if (bit == 0) continue; int bit_cur_x = bullet->cur_x + cur_map->offset_x + cur_map->icon->height - bullet_bit_x; int bit_cur_y = bullet->cur_y + cur_map->offset_y + bullet_bit_y; act_seq_t *cur_craft_act_seq = craft->act_seq_list[craft->act_seq_type]; map_t *cur_craft_map = cur_craft_act_seq ->act_seq_maps[cur_craft_act_seq->act_seq_index]; for (int craft_bit_x = 0; craft_bit_x < (cur_craft_map->icon->height); craft_bit_x++) { for (int craft_bit_y = 0; craft_bit_y < (cur_craft_map->icon->width); craft_bit_y++) { uint8_t craft_bit = (cur_craft_map->icon->p_icon_mask == NULL) ? cur_craft_map->icon->p_icon_data[craft_bit_x / 8 + craft_bit_y] & (0x01 << craft_bit_x % 8) : cur_craft_map->icon->p_icon_mask[craft_bit_x / 8 + craft_bit_y] & (0x01 << craft_bit_x % 8); if (craft_bit == 0) continue; // 找到有效点对应的绝对坐标 int craft_bit_cur_x = craft->cur_x + cur_craft_map->offset_x + cur_craft_map->icon->height - craft_bit_x; int craft_bit_cur_y = craft->cur_y + cur_craft_map->offset_y + craft_bit_y; // 开始遍历所有可撞击对象 if (craft_bit_cur_x == bit_cur_x && craft_bit_cur_y == bit_cur_y) { return 1; } } } } } return 0; } void global_hit_check(void) { // 子弹撞击检测 for (int j = 0; j < MAX_BULLET; j++) { dfo_t *bullet = bullet_group[j]; if (bullet->cur_life <= 0) continue; for (int i = 0; i < MAX_L_CRAFT + MAX_M_CRAFT + MAX_S_CRAFT; i++) { dfo_t *craft = enemy_crafts[i]; if (craft->cur_life <= 0) continue; if (hit_check(bullet, craft)) { craft->cur_life -= bullet->damage; bullet->cur_life = 0; bullet->cur_x = -100; if (craft->cur_life <= 0) { destory(craft); } continue; } } } // 我方飞机撞击检测 for (int i = 0; i < MAX_L_CRAFT + MAX_M_CRAFT + MAX_S_CRAFT; i++) { dfo_t *craft = enemy_crafts[i]; if (craft->cur_life <= 0) continue; if (hit_check(my_craft, craft)) { craft->cur_life -= my_craft->damage; my_craft->cur_life -= craft->damage; if (craft->cur_life <= 0) { destory(craft); } if (my_craft->cur_life <= 0) { destory(my_craft); g_chance--; } continue; } } } int aircraftBattle_init(void) { OLED_Clear(); OLED_Refresh_GRAM(); global_create(); g_chance = MY_CHANCE; aos_task_new_ext(&aircraftBattle_task_handle, "aircraftBattle_task", aircraftBattle_task, NULL, 1024, AOS_DEFAULT_APP_PRI); LOGI(EDU_TAG, "aos_task_new aircraftBattle_task\n"); return 0; } int aircraftBattle_uninit(void) { free_dfo(my_craft); for (int i = 0; i < MAX_L_CRAFT + MAX_M_CRAFT + MAX_S_CRAFT; i++) free_dfo(enemy_crafts[i]); for (int i = 0; i < MAX_BULLET; i++) free_dfo(bullet_group[i]); aos_task_delete(&aircraftBattle_task_handle); LOGI(EDU_TAG, "aos_task_delete aircraftBattle_task\n"); return 0; } void aircraftBattle_task() { while (1) { if (g_chance > 0) { OLED_Clear(); global_update(); global_draw(); OLED_Refresh_GRAM(); aos_msleep(40); } else { OLED_Clear(); OLED_Show_String(30, 12, "GAME OVER", 16, 1); OLED_Show_String(10, 40, "press K1&K2 to quit", 12, 1); OLED_Refresh_GRAM(); aos_msleep(1000); } } }
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/aircraftBattle/aircraftBattle.c
C
apache-2.0
22,523
#ifndef __AIRCRAFTBATTLE_H__ #define __AIRCRAFTBATTLE_H__ #include "../menu.h" extern MENU_TYP aircraftBattle; int aircraftBattle_init(void); int aircraftBattle_uninit(void); void aircraftBattle_task(void); void aircraftBattle_key_handel(key_code_t key_code); void aircraftBattle_cover_draw(int *draw_index); /* -> x ____________________ | | icon| | | of_y | \/ | | | y |--of_x--x* | |__________________| */ typedef struct { icon_t *icon; int offset_x; int offset_y; } map_t; // 贴图 typedef struct { map_t **act_seq_maps; // 贴图指针数组 // 该动作序列的所有贴图(例如爆炸动作包含3帧) uint8_t act_seq_len; // 贴图指针数组长度 uint8_t act_seq_index; // 用于索引帧 uint8_t act_seq_interval; // 帧间延迟 uint8_t act_seq_interval_cnt; // 用于延迟计数 uint8_t act_is_destory; // 用于标记该动作序列是否是爆炸动作 } act_seq_t; typedef struct { int offset_x; int offset_y; } arms_t; typedef enum { UP, LEFT, RIGHT, DOWN } my_craft_dir_e_t; typedef enum { Achilles, // 阿克琉斯级 Venture, // 冲锋者级 Ares, // 阿瑞斯级 战神级 TiTan, // 泰坦级 Bullet, } dfo_model_e_t; typedef struct { dfo_model_e_t model; // 运动相关 int start_x; // 相对固定 int start_y; int cur_x; // 运动 int cur_y; uint8_t speed; // 绝对固定 unsigned int range; // 绝对固定 // 显示相关 act_seq_t **act_seq_list; // 动作序列数组 uint8_t act_seq_list_len; // 动作序列数组长度 uint8_t act_seq_type; // 判定相关 uint8_t damage; // 撞击伤害 uint8_t full_life; // 满血生命值 int8_t cur_life; // 当前生命值 // 攻击相关 arms_t **arms_list; // 武器装备数组 uint8_t arms_list_len; // 武器数组长度 } dfo_t; // Dentified Flying Object // Lcraft // nomal static uint8_t icon_data_Lcraft_32_32[] = { 0x00, 0x00, 0x00, 0x30, 0x30, 0x30, 0xB8, 0xB8, 0xBC, 0xBC, 0xBE, 0xFF, 0xFF, 0xFF, 0xFF, 0xBE, 0xB6, 0xB6, 0x34, 0x74, 0x70, 0x70, 0xD0, 0x90, 0xB0, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x08, 0x1C, 0x16, 0x12, 0x5B, 0x5F, 0xCF, 0xCF, 0xC7, 0xC7, 0xE7, 0x77, 0x3F, 0xBF, 0xFF, 0xFF, 0xEF, 0x6F, 0x2F, 0x2F, 0x6F, 0x6F, 0x5F, 0xDF, 0xDF, 0xDE, 0xDE, 0x9A, 0xB2, 0x36, 0x1C, 0x18, 0x10, 0x38, 0x68, 0x48, 0xDA, 0xFA, 0xF3, 0xF3, 0xE3, 0xE3, 0xE7, 0xEE, 0xFC, 0xFD, 0xFF, 0xFF, 0xF7, 0xF6, 0xF4, 0xF4, 0xF6, 0xF6, 0xFA, 0xFB, 0xFB, 0x7B, 0x7B, 0x59, 0x4D, 0x6C, 0x38, 0x18, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x0C, 0x1D, 0x1D, 0x3D, 0x3D, 0x7D, 0xFF, 0xFF, 0xFF, 0xFF, 0x7D, 0x6D, 0x6D, 0x2C, 0x2E, 0x0E, 0x0E, 0x0B, 0x09, 0x0D, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00}; static uint8_t icon_mask_Lcraft_32_32[] = { 0x00, 0x00, 0x00, 0x30, 0x30, 0x30, 0xB8, 0xB8, 0xBC, 0xBC, 0xBE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xF6, 0xF6, 0xF4, 0xF4, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x08, 0x1C, 0x1E, 0x1E, 0x5F, 0x5F, 0xCF, 0xCF, 0xC7, 0xC7, 0xE7, 0xF7, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xDF, 0xDF, 0xDF, 0xDE, 0xDE, 0x9E, 0xBE, 0x3E, 0x1C, 0x18, 0x10, 0x38, 0x78, 0x78, 0xFA, 0xFA, 0xF3, 0xF3, 0xE3, 0xE3, 0xE7, 0xEF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFB, 0xFB, 0xFB, 0x7B, 0x7B, 0x79, 0x7D, 0x7C, 0x38, 0x18, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x0C, 0x1D, 0x1D, 0x3D, 0x3D, 0x7D, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x6F, 0x6F, 0x2F, 0x2F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00}; static icon_t icon_Lcraft_32_32 = {icon_data_Lcraft_32_32, 32, 32, icon_mask_Lcraft_32_32}; // destory static uint8_t icon_data_Lcraft_destory2_32_32[] = { 0x00, 0x30, 0x46, 0xB8, 0x70, 0x10, 0x20, 0x8D, 0xAC, 0x98, 0x3C, 0x1B, 0x53, 0x16, 0x04, 0x0E, 0x22, 0x02, 0x54, 0x64, 0x40, 0x40, 0xC0, 0xA6, 0xA0, 0xE3, 0xC0, 0xF8, 0x14, 0xCE, 0x15, 0x18, 0x00, 0x00, 0x16, 0x81, 0x0A, 0x49, 0x0D, 0x4B, 0x43, 0xC1, 0xE4, 0x10, 0x29, 0x0C, 0x09, 0x5A, 0x07, 0x62, 0x82, 0x0C, 0x27, 0x08, 0x09, 0xCB, 0x3F, 0xC0, 0x85, 0x0A, 0xA0, 0x31, 0x10, 0x00, 0x00, 0x14, 0x07, 0x40, 0x03, 0xC8, 0x72, 0xE0, 0x41, 0x61, 0x02, 0x8A, 0x40, 0x00, 0x7C, 0x2B, 0x26, 0x0C, 0xB0, 0x1B, 0x62, 0x49, 0x1A, 0x51, 0x03, 0x0B, 0x19, 0x01, 0x81, 0x0C, 0x00, 0x18, 0x40, 0x50, 0x38, 0x00, 0x0C, 0x68, 0x18, 0x01, 0x18, 0x14, 0x68, 0x06, 0x0A, 0x54, 0x0A, 0x50, 0x4D, 0x01, 0x28, 0x20, 0xDC, 0x08, 0x33, 0x49, 0x40, 0x87, 0x04, 0x09, 0x01, 0x04, 0x08, 0x08}; static icon_t icon_Lcraft_destory2_32_32 = {icon_data_Lcraft_destory2_32_32, 32, 32, NULL}; static uint8_t icon_data_Lcraft_destory1_32_32[] = { 0x20, 0x27, 0x24, 0xE6, 0x7C, 0x58, 0x00, 0xC0, 0xE0, 0xE9, 0xC1, 0xE3, 0x26, 0x0E, 0x54, 0xD4, 0x58, 0xB0, 0x10, 0x5C, 0xF0, 0xC4, 0xF4, 0xE8, 0x88, 0x14, 0xFA, 0xFA, 0xC8, 0x84, 0x04, 0x80, 0x78, 0xF4, 0x44, 0xA3, 0x5D, 0x6E, 0x78, 0x39, 0x1F, 0x5F, 0xEB, 0x60, 0xC8, 0x40, 0xCC, 0xC7, 0x67, 0xC7, 0x9C, 0x88, 0xF0, 0x7C, 0xF1, 0x57, 0x63, 0x31, 0x7F, 0x7F, 0x8F, 0xED, 0xFC, 0x78, 0x10, 0x91, 0x4C, 0x58, 0xBF, 0x19, 0x40, 0xC3, 0x16, 0xBF, 0xDF, 0xCE, 0x6A, 0x17, 0xD9, 0xA8, 0xCC, 0xBA, 0xB6, 0xC0, 0xFB, 0x39, 0x9F, 0xD3, 0xC4, 0x7C, 0x89, 0xEE, 0x02, 0x8D, 0x83, 0x00, 0x02, 0x11, 0x18, 0x18, 0xC8, 0x27, 0x23, 0x3B, 0x10, 0x39, 0x0B, 0x87, 0xAE, 0x21, 0x07, 0x1F, 0x16, 0x02, 0x33, 0xFB, 0x89, 0x27, 0x39, 0x35, 0x2F, 0xEE, 0x4B, 0xD8, 0xA8, 0x70, 0x22, 0x42}; static icon_t icon_Lcraft_destory1_32_32 = {icon_data_Lcraft_destory1_32_32, 32, 32, NULL}; static uint8_t icon_data_Lcraft_destory0_32_32[] = { 0x00, 0x00, 0x06, 0x38, 0x70, 0x30, 0x38, 0xBD, 0xFC, 0xB8, 0x3E, 0x3F, 0x73, 0xF7, 0xB7, 0x0E, 0x26, 0x12, 0x14, 0x74, 0x70, 0x70, 0xD0, 0xF6, 0xA0, 0xE3, 0xC0, 0x98, 0x04, 0x06, 0x41, 0x40, 0x08, 0x1C, 0x16, 0x10, 0x5A, 0x5F, 0xCF, 0xCD, 0xC3, 0xC1, 0xE5, 0x34, 0x2F, 0x9E, 0xFF, 0xFA, 0x8F, 0x2B, 0x23, 0xCB, 0x67, 0x6C, 0x59, 0xDF, 0x5F, 0xFE, 0xDE, 0x9A, 0xB2, 0x37, 0x1C, 0x18, 0x10, 0x38, 0x68, 0x48, 0x92, 0xFA, 0xF3, 0xF0, 0xE3, 0xE1, 0xE3, 0xEA, 0xC0, 0x38, 0x7F, 0x2B, 0x67, 0x7E, 0xF4, 0xE4, 0xE0, 0xC0, 0x2A, 0x33, 0xFB, 0x7B, 0x7B, 0x59, 0x4D, 0x6C, 0x38, 0x18, 0x40, 0x50, 0x78, 0x0C, 0x0C, 0x08, 0x1D, 0x11, 0x39, 0x3C, 0x7C, 0xDF, 0xDB, 0xDF, 0xEE, 0x5C, 0x4D, 0x0D, 0x2C, 0x3E, 0xDE, 0x0F, 0x3B, 0x49, 0x4F, 0x8F, 0x00, 0x31, 0x60, 0x00, 0x00, 0x00}; static icon_t icon_Lcraft_destory0_32_32 = {icon_data_Lcraft_destory0_32_32, 32, 32, NULL}; // Layer Ready static uint8_t icon_data_Lcraft_LayerReady0_3_3[] = {0x02, 0x05, 0x02}; static icon_t icon_Lcraft_LayerReady0_3_3 = {icon_data_Lcraft_LayerReady0_3_3, 3, 3, NULL}; static uint8_t icon_data_Lcraft_LayerReady1_3_3[] = {0x05, 0x02, 0x05}; static icon_t icon_Lcraft_LayerReady1_3_3 = {icon_data_Lcraft_LayerReady1_3_3, 3, 3, NULL}; // Mcraft // nomal static uint8_t icon_data_Mcraft_12_12[] = { 0x01, 0x03, 0x6F, 0xFE, 0x9C, 0xFC, 0xF8, 0x98, 0x98, 0x98, 0x90, 0x90, 0x08, 0x0C, 0x0F, 0x07, 0x03, 0x03, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00}; static uint8_t icon_mask_Mcraft_12_12[] = { 0x01, 0x03, 0x6F, 0xFE, 0xFC, 0xFC, 0xF8, 0x98, 0x98, 0x98, 0x90, 0x90, 0x08, 0x0C, 0x0F, 0x07, 0x03, 0x03, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00}; static icon_t icon_Mcraft_12_12 = {icon_data_Mcraft_12_12, 12, 12, icon_mask_Mcraft_12_12}; // destory static uint8_t icon_data_Mcraft_destory0_12_12[] = { 0x01, 0x0E, 0xBC, 0xDD, 0x1A, 0x4C, 0x68, 0x7B, 0xDC, 0x34, 0x68, 0x83, 0x02, 0x01, 0x08, 0x07, 0x06, 0x01, 0x01, 0x0F, 0x03, 0x04, 0x09, 0x02}; static icon_t icon_Mcraft_destory0_12_12 = {icon_data_Mcraft_destory0_12_12, 12, 12}; static uint8_t icon_data_Mcraft_destory1_12_12[] = { 0x01, 0x06, 0x9C, 0xD1, 0x22, 0x4C, 0x78, 0x6B, 0x94, 0x3C, 0x68, 0x83, 0x04, 0x03, 0x00, 0x01, 0x06, 0x05, 0x01, 0x04, 0x02, 0x03, 0x09, 0x02}; static icon_t icon_Mcraft_destory1_12_12 = {icon_data_Mcraft_destory1_12_12, 12, 12}; static uint8_t icon_data_Mcraft_destory2_12_12[] = { 0x01, 0x02, 0x9C, 0x51, 0x22, 0x4C, 0x60, 0x09, 0x90, 0x04, 0x68, 0x83, 0x00, 0x02, 0x00, 0x01, 0x04, 0x04, 0x00, 0x04, 0x00, 0x01, 0x09, 0x02}; static icon_t icon_Mcraft_destory2_12_12 = {icon_data_Mcraft_destory2_12_12, 12, 12}; // Mycraft // nomal static uint8_t icon_mask_Mycraft_19_19[] = { 0x00, 0x00, 0x80, 0x80, 0x80, 0x80, 0xC0, 0xC0, 0xC8, 0xE8, 0xF8, 0xFE, 0xFF, 0xFF, 0x3E, 0x0C, 0x0C, 0x0C, 0x0C, 0x07, 0x07, 0x0F, 0x0F, 0x0F, 0x0F, 0x1F, 0x1F, 0x9F, 0xBF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE2, 0x80, 0x80, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03, 0x07, 0x03, 0x01, 0x01, 0x01, 0x01}; static uint8_t icon_data_Mycraft0_19_19[] = { 0x00, 0x00, 0x80, 0x80, 0x80, 0x80, 0xC0, 0xC0, 0xC8, 0x68, 0xB8, 0x4E, 0x13, 0xFF, 0x3E, 0x0C, 0x0C, 0x00, 0x00, 0x07, 0x05, 0x0D, 0x0A, 0x08, 0x0F, 0x1A, 0x1A, 0x9A, 0xB2, 0xE8, 0x97, 0x42, 0xFF, 0xE2, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x02, 0x07, 0x03, 0x01, 0x01, 0x00, 0x00}; static icon_t icon_Mycraft0_19_19 = {icon_data_Mycraft0_19_19, 19, 19, icon_mask_Mycraft_19_19}; static uint8_t icon_data_Mycraft1_19_19[] = { 0x00, 0x00, 0x80, 0x80, 0x80, 0x80, 0xC0, 0xC0, 0xC8, 0x68, 0xB8, 0x4E, 0x13, 0xFF, 0x3E, 0x0C, 0x00, 0x0C, 0x00, 0x07, 0x05, 0x0D, 0x0A, 0x08, 0x0F, 0x1A, 0x1A, 0x9A, 0xB2, 0xE8, 0x97, 0x42, 0xFF, 0xE2, 0x80, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x02, 0x07, 0x03, 0x01, 0x00, 0x01, 0x00}; static icon_t icon_Mycraft1_19_19 = {icon_data_Mycraft1_19_19, 19, 19, icon_mask_Mycraft_19_19}; static uint8_t icon_data_Mycraft2_19_19[] = { 0x00, 0x00, 0x80, 0x80, 0x80, 0x80, 0xC0, 0xC0, 0xC8, 0x68, 0xB8, 0x4E, 0x13, 0xFF, 0x3E, 0x0C, 0x00, 0x00, 0x0C, 0x07, 0x05, 0x0D, 0x0A, 0x08, 0x0F, 0x1A, 0x1A, 0x9A, 0xB2, 0xE8, 0x97, 0x42, 0xFF, 0xE2, 0x80, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x02, 0x07, 0x03, 0x01, 0x00, 0x00, 0x01}; static icon_t icon_Mycraft2_19_19 = {icon_data_Mycraft2_19_19, 19, 19, icon_mask_Mycraft_19_19}; // destory static uint8_t icon_data_Mycraft_destory0_19_19[] = { 0x00, 0x14, 0xC2, 0x90, 0xC9, 0x80, 0xD8, 0x85, 0xC8, 0x78, 0xB9, 0x4E, 0x13, 0xCF, 0x3E, 0x4C, 0x80, 0x08, 0x00, 0x09, 0xC0, 0x0D, 0x0A, 0x28, 0x4F, 0x5A, 0x22, 0x8A, 0xB2, 0xC9, 0x97, 0x42, 0xF8, 0xE2, 0x80, 0x12, 0x04, 0x60, 0x00, 0x00, 0x00, 0x01, 0x01, 0x04, 0x02, 0x01, 0x00, 0x01, 0x00, 0x03, 0x02, 0x07, 0x03, 0x01, 0x02, 0x00, 0x00}; static icon_t icon_Mycraft_destory0_19_19 = {icon_data_Mycraft_destory0_19_19, 19, 19, NULL}; static uint8_t icon_data_Mycraft_destory1_19_19[] = { 0x00, 0x14, 0xF2, 0xD2, 0xC9, 0x8A, 0xD8, 0x85, 0x08, 0x38, 0x99, 0x46, 0x13, 0xC7, 0x36, 0xDC, 0x80, 0x8C, 0x00, 0x09, 0xC0, 0x0D, 0x02, 0x28, 0xDF, 0x5A, 0x22, 0x8B, 0xB2, 0xC9, 0x97, 0xC2, 0x38, 0x72, 0x90, 0x52, 0x2C, 0x60, 0x00, 0x00, 0x00, 0x01, 0x01, 0x04, 0x02, 0x03, 0x02, 0x03, 0x00, 0x03, 0x02, 0x05, 0x03, 0x01, 0x02, 0x00, 0x00}; static icon_t icon_Mycraft_destory1_19_19 = {icon_data_Mycraft_destory1_19_19, 19, 19, NULL}; static uint8_t icon_data_Mycraft_destory2_16_16[] = { 0x68, 0x80, 0x22, 0x20, 0x94, 0x21, 0x00, 0x88, 0x26, 0x01, 0x04, 0x30, 0x8C, 0x30, 0xA0, 0x00, 0x02, 0x40, 0x4A, 0x36, 0x14, 0x08, 0xA0, 0x00, 0x10, 0x04, 0x10, 0x0C, 0x10, 0x00, 0x00, 0x04}; static icon_t icon_Mycraft_destory2_16_16 = {icon_data_Mycraft_destory2_16_16, 16, 16, NULL}; // Scraft static uint8_t icon_data_Scraft_7_8[] = {0x24, 0x18, 0x3C, 0xC3, 0x66, 0x3C, 0x18}; static uint8_t icon_mask_Scraft_7_8[] = {0x3C, 0x18, 0x3C, 0xFF, 0x7E, 0x3C, 0x18}; static icon_t icon_Scraft_7_8 = {icon_data_Scraft_7_8, 7, 8, icon_data_Scraft_7_8}; static uint8_t icon_data_Scraft_destory0_9_8[] = {0x09, 0xEE, 0x14, 0x2F, 0x3D, 0x6F, 0x36, 0x50, 0x88}; static icon_t icon_Scraft_destory0_9_8 = {icon_data_Scraft_destory0_9_8, 9, 8, NULL}; static uint8_t icon_data_Scraft_destory1_9_8[] = {0x89, 0x66, 0x58, 0xAB, 0x2D, 0x52, 0x32, 0x50, 0x89}; static icon_t icon_Scraft_destory1_9_8 = {icon_data_Scraft_destory1_9_8, 9, 8, NULL}; static uint8_t icon_data_Scraft_destory2_7_6[] = {0x0C, 0x06, 0x31, 0x24, 0x0E, 0x11, 0x04}; static icon_t icon_Scraft_destory2_7_6 = {icon_data_Scraft_destory2_7_6, 7, 6, NULL}; // bullet static uint8_t icon_data_bullet_2_1[] = {0x01, 0x01}; static icon_t icon_bullet_2_1 = {icon_data_bullet_2_1, 2, 1, NULL}; // Game UI static uint8_t icon_data_craft_life_5_5[] = {0x0C, 0x1E, 0x0F, 0x1E, 0x0C}; static icon_t icon_craft_life_5_5 = {icon_data_craft_life_5_5, 5, 5, NULL}; static uint8_t icon_data_mini_start_3_3[] = {0x02, 0x05, 0x02}; static icon_t icon_mini_start_3_3 = {icon_data_mini_start_3_3, 3, 3, NULL}; static uint8_t img_data_craft_bg_132_64[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x08, 0xF8, 0x08, 0x00, 0xF8, 0x20, 0x20, 0xF8, 0x00, 0xF8, 0xA8, 0xA8, 0x88, 0x00, 0x00, 0x00, 0xB8, 0xA8, 0xA8, 0xE8, 0x00, 0xF8, 0x28, 0x28, 0x38, 0x00, 0xF0, 0x28, 0x28, 0xF0, 0x00, 0xF8, 0x88, 0x88, 0xD8, 0x00, 0xF8, 0xA8, 0xA8, 0x88, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x40, 0xA0, 0xB0, 0x4C, 0xB0, 0xA0, 0x40, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0xA0, 0x40, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0x40, 0x40, 0xC0, 0xA0, 0x20, 0x22, 0x20, 0x60, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x14, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x60, 0x10, 0x60, 0x1E, 0x00, 0x7C, 0x0A, 0x0A, 0x7C, 0x00, 0x7E, 0x12, 0x12, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6C, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x06, 0x01, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x50, 0x78, 0x28, 0xFC, 0xF6, 0xD3, 0x93, 0x09, 0x09, 0x0B, 0x0E, 0x08, 0x05, 0x05, 0x05, 0x04, 0x03, 0x03, 0x02, 0x02, 0x02, 0x03, 0x07, 0x07, 0x8F, 0xBF, 0x7F, 0xF3, 0xF3, 0xFB, 0xFB, 0xFB, 0x79, 0x7D, 0x3E, 0x1E, 0x0E, 0x0E, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x40, 0x60, 0xA0, 0x90, 0x50, 0x20, 0xA0, 0xA0, 0x40, 0x40, 0x80, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x14, 0x08, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0x00, 0x00, 0x80, 0x80, 0x40, 0xC0, 0xA0, 0x60, 0x50, 0xB0, 0xA8, 0x58, 0x54, 0x2C, 0x2C, 0x18, 0x10, 0x08, 0x08, 0x04, 0x02, 0x02, 0x01, 0x89, 0x04, 0x44, 0xA2, 0x41, 0xB3, 0x9F, 0x7F, 0xFF, 0xFF, 0x7E, 0x3C, 0x10, 0x80, 0x40, 0x40, 0xA0, 0xA0, 0x50, 0xD0, 0xA8, 0x98, 0xDC, 0x4A, 0x2A, 0x15, 0x1D, 0x0A, 0x0A, 0x05, 0x03, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x04, 0x1E, 0xE1, 0x01, 0x00, 0x00, 0x03, 0x04, 0x18, 0x20, 0xC0, 0x01, 0x01, 0x02, 0x02, 0x02, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x10, 0x10, 0x10, 0x10, 0x10, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0xA0, 0xAF, 0x74, 0x46, 0x26, 0x13, 0x11, 0x09, 0x09, 0x05, 0x06, 0x02, 0x02, 0x01, 0x00, 0x80, 0x80, 0xC0, 0xA0, 0x60, 0x30, 0x28, 0x18, 0x0C, 0x0C, 0xC6, 0xB5, 0x9B, 0x4E, 0x4B, 0xA6, 0xA5, 0x53, 0x32, 0xA9, 0x55, 0x54, 0x2A, 0x2A, 0x15, 0x15, 0x0A, 0x0D, 0x05, 0x02, 0x02, 0x01, 0x01, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x1C, 0x36, 0x1C, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x03, 0x1C, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x81, 0x86, 0x88, 0x70, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x40, 0x40, 0x20, 0x20, 0x10, 0x10, 0x08, 0x08, 0x04, 0x02, 0x02, 0x01, 0x01, 0x00, 0x00, 0x80, 0x80, 0xC0, 0x60, 0x60, 0x30, 0x30, 0x18, 0x0C, 0x0C, 0x06, 0x05, 0x03, 0x01, 0x01, 0x00, 0x00, 0x00, 0xC0, 0x60, 0x58, 0x2C, 0x27, 0x15, 0x1A, 0x0A, 0x05, 0x05, 0x02, 0x02, 0x01, 0x01, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x0C, 0x17, 0x14, 0x12, 0x0A, 0x09, 0x05, 0xC4, 0xC6, 0xD8, 0xE0, 0x10, 0x10, 0x08, 0x08, 0x04, 0x04, 0x02, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x80, 0x00, 0xE0, 0x18, 0x0C, 0x0C, 0x06, 0x06, 0x03, 0xE1, 0x1D, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x60, 0x18, 0x04, 0x03, 0x00, 0x00, 0x00, 0xF0, 0x50, 0x50, 0x20, 0x00, 0xF0, 0x50, 0xD0, 0x20, 0x00, 0xF0, 0x50, 0x50, 0x10, 0x00, 0x70, 0x50, 0x50, 0xD0, 0x00, 0x70, 0x50, 0x50, 0xD0, 0x02, 0x00, 0x00, 0x00, 0xF0, 0xC0, 0x30, 0x00, 0x70, 0x40, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0xF2, 0x10, 0x00, 0xF4, 0x10, 0x10, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x90, 0x80, 0xC0, 0x80, 0xE0, 0xA0, 0xD0, 0x10, 0x40, 0x84, 0xEA, 0x84, 0x00, 0x00, 0x7E, 0xF7, 0x8F, 0xF7, 0xFB, 0x9F, 0xDF, 0xBF, 0xFE, 0xF0, 0xF0, 0xE8, 0xD0, 0xE8, 0x50, 0x68, 0x34, 0x28, 0xF4, 0x3A, 0xAC, 0xAA, 0x55, 0x56, 0xAB, 0xFA, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x78, 0x47, 0x40, 0xA0, 0xA0, 0xA0, 0x90, 0x90, 0x50, 0x50, 0xF0, 0x60, 0x10, 0x0C, 0x03, 0x80, 0x80, 0x40, 0x40, 0x20, 0x20, 0x10, 0x10, 0x09, 0x08, 0x38, 0x78, 0xF8, 0xF9, 0x78, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x01, 0x00, 0xF1, 0x91, 0x91, 0x91, 0x90, 0x01, 0x01, 0x11, 0x11, 0xF0, 0x10, 0x10, 0x00, 0x01, 0xC0, 0xA1, 0x90, 0xA0, 0xC0, 0x01, 0x00, 0xF0, 0x90, 0x90, 0x90, 0x60, 0x01, 0x00, 0x10, 0x11, 0xF1, 0x11, 0x11, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x54, 0xAA, 0x5E, 0xAB, 0x55, 0xAA, 0x5D, 0xAA, 0x71, 0xAA, 0x1D, 0xAA, 0x5E, 0xCB, 0x49, 0x23, 0xEE, 0x13, 0x31, 0xB9, 0x40, 0x39, 0x0B, 0x07, 0x07, 0x03, 0x03, 0x03, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x38, 0x04, 0x03, 0x01, 0x00, 0x00, 0xC0, 0x3C, 0x07, 0x04, 0x04, 0x04, 0x84, 0x74, 0x0E, 0x01, 0x01, 0x01, 0x01, 0x00, 0x80, 0xC0, 0x60, 0x10, 0x0C, 0x02, 0x01, 0x82, 0x82, 0x41, 0x41, 0x20, 0x30, 0x90, 0x88, 0x48, 0x48, 0x24, 0x24, 0x92, 0x52, 0x51, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, 0x04, 0x07, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x07, 0x00, 0x00, 0x01, 0x06, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; static icon_t img_craft_bg_132_64 = {img_data_craft_bg_132_64, 132, 64, NULL}; #endif
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/aircraftBattle/aircraftBattle.h
C
apache-2.0
21,056
#include "barometer.h" #include "drv_baro_qst_qmp6988.h" #include "drv_baro_goertek_spl06.h" #include <stdio.h> #include <stdlib.h> static char pressure_str[16] = " "; static char altitude_str[16] = " "; static char Ctemp_str[7] = " "; static char Ftemp_str[7] = " "; static spl06_data_t spl06_data = {0}; static qmp6988_data p_qmp6988_data = {0}; static int running = 1; MENU_COVER_TYP barometer_cover = {MENU_COVER_NONE}; MENU_TASK_TYP barometer_tasks = {barometer_init, barometer_uninit}; MENU_TYP barometer = {"barometer", &barometer_cover, &barometer_tasks, NULL, NULL}; static aos_task_t barometer_task_handle; int barometer_init(void) { if (g_haasboard_is_k1c) { p_qmp6988_data.slave = QMP6988_SLAVE_ADDRESS_H; qmp6988_init(&p_qmp6988_data); aos_msleep(10); qmp6988_calc_pressure(&p_qmp6988_data); LOGI(EDU_TAG, "qmp6988_init done\n"); } else { spl06_init(); spl06_getdata(&spl06_data); LOGI(EDU_TAG, "spl06_init done\n"); } aos_task_new_ext(&barometer_task_handle, "barometer_task", barometer_task, NULL, 1024 * 4, AOS_DEFAULT_APP_PRI); LOGI(EDU_TAG, "aos_task_new barometer_task\n"); return 0; } void barometer_task() { while (running) { OLED_Clear(); if (g_haasboard_is_k1c) { sprintf(pressure_str, " %-10.3lfkPa", p_qmp6988_data.pressure / 1000); LOGD(EDU_TAG, "%s\n", pressure_str); sprintf(altitude_str, " %-12.2lfm", p_qmp6988_data.altitude); LOGD(EDU_TAG, "%s\n", altitude_str); sprintf(Ctemp_str, "%-5.2lf", p_qmp6988_data.temperature); LOGD(EDU_TAG, "%s\n", Ctemp_str); sprintf(Ftemp_str, "%-5.2lf", ((p_qmp6988_data.temperature * 9 / 5) + 32)); LOGD(EDU_TAG, "%s\n", Ftemp_str); } else { sprintf(pressure_str, " %-10.3lfkPa", spl06_data.pressure / 10); LOGD(EDU_TAG, "%s\n", pressure_str); sprintf(altitude_str, " %-12.2lfm", spl06_data.altitude); LOGD(EDU_TAG, "%s\n", altitude_str); sprintf(Ctemp_str, "%-5.2lf", spl06_data.Ctemp); LOGD(EDU_TAG, "%s\n", Ctemp_str); sprintf(Ftemp_str, "%-5.2lf", spl06_data.Ftemp); LOGD(EDU_TAG, "%s\n", Ftemp_str); } #if 1 OLED_Icon_Draw(14, 4, &icon_atmp_16_16, 0); OLED_Show_String(32, 6, pressure_str, 12, 1); OLED_Icon_Draw(14, 23, &icon_asl_16_16, 0); OLED_Show_String(32, 25, altitude_str, 12, 1); OLED_Icon_Draw(14, 44, &icon_tempC_16_16, 0); OLED_Show_String(30, 46, Ctemp_str, 12, 1); OLED_Icon_Draw(66, 44, &icon_tempF_16_16, 0); OLED_Show_String(82, 46, Ftemp_str, 12, 1); OLED_Icon_Draw(2, 24, &icon_skip_left, 0); OLED_Icon_Draw(122, 24, &icon_skip_right, 0); #endif if (g_haasboard_is_k1c) { qmp6988_calc_pressure(&p_qmp6988_data); } else { spl06_getdata(&spl06_data); } OLED_Refresh_GRAM(); aos_msleep(500); } running = 1; } int barometer_uninit(void) { running = 0; while (!running) { aos_msleep(50); } aos_task_delete(&barometer_task_handle); LOGI(EDU_TAG, "aos_task_delete barometer_task\n"); if (g_haasboard_is_k1c) { qmp6988_deinit(); } else { spl06_deinit(); } return 0; }
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/barometer/barometer.c
C
apache-2.0
3,464
#ifndef __BAROMETER_H__ #define __BAROMETER_H__ #include "../menu.h" extern MENU_TYP barometer; int barometer_init(void); int barometer_uninit(void); void barometer_task(void); static uint8_t icon_data_tempF_16_16[] = { 0x00, 0x00, 0x00, 0x38, 0x28, 0x38, 0x00, 0xF8, 0xF8, 0x88, 0x88, 0x88, 0x88, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; static icon_t icon_tempF_16_16 = {icon_data_tempF_16_16, 16, 16}; static uint8_t icon_data_tempC_16_16[] = { 0x00, 0x00, 0x00, 0x38, 0x28, 0x38, 0x00, 0xE0, 0xF0, 0x18, 0x18, 0x18, 0x30, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x0F, 0x18, 0x18, 0x18, 0x0C, 0x04, 0x00, 0x00}; static icon_t icon_tempC_16_16 = {icon_data_tempC_16_16, 16, 16}; static uint8_t icon_data_atmp_16_16[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x00, 0x00, 0xFC, 0x00, 0x00, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x21, 0x22, 0x27, 0x20, 0x24, 0x2F, 0x24, 0x20, 0x27, 0x22, 0x21, 0x00, 0x00}; static icon_t icon_atmp_16_16 = {icon_data_atmp_16_16, 16, 16}; static uint8_t icon_data_asl_16_16[] = { 0x00, 0x08, 0xDC, 0x08, 0x00, 0x00, 0xC0, 0x70, 0x38, 0xE0, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x20, 0x2E, 0x27, 0x21, 0x20, 0x20, 0x2F, 0x26, 0x23, 0x2E, 0x20, 0x00, 0x00}; static icon_t icon_asl_16_16 = {icon_data_asl_16_16, 16, 16}; #endif
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/barometer/barometer.h
C
apache-2.0
1,441
#include "compass.h" #include "drv_mag_qst_qmc5883l.h" #include "drv_mag_qst_qmc6310.h" #include <stdio.h> #include <stdlib.h> #define COMPASS_CENTER_X 38 #define COMPASS_CENTER_Y 32 // 严格限制长度 static char code_str[3] = " "; // ES static char number_str[4] = " "; // 329 static int heading = 0; static uint8_t arror_len = 16; static int running = 1; MENU_COVER_TYP compass_cover = {MENU_COVER_NONE}; MENU_TASK_TYP compass_tasks = {compass_init, compass_uninit}; MENU_TYP compass = {"compass", &compass_cover, &compass_tasks, NULL, NULL}; static aos_task_t compass_task_handle; int compass_init(void) { if (g_haasboard_is_k1c) { qmc6310_init(); LOGI(EDU_TAG, "qmc6310_init done\n"); } else { qmc5883l_init(); LOGI(EDU_TAG, "qmc5883l_init done\n"); } OLED_Clear(); OLED_Refresh_GRAM(); aos_task_new_ext(&compass_task_handle, "compass_task", compass_task, NULL, 1024 * 4, AOS_DEFAULT_APP_PRI); LOGI(EDU_TAG, "aos_task_new compass_task\n"); return 0; } void compass_task() { while (running) { if (g_haasboard_is_k1c) { heading = qmc6310_readHeading(); LOGD(EDU_TAG, "heading %d\n", heading); } else { heading = qmc5883l_readHeading(); LOGD(EDU_TAG, "heading %d\n", heading); } OLED_Clear(); OLED_Icon_Draw(COMPASS_CENTER_X - 27, COMPASS_CENTER_Y - 27, &icon_compass_55_55, 0); OLED_Icon_Draw(72, 4, &icon_compass_arror_24_24, 0); format_compass_str(number_str, code_str, (-heading), &arror_len); OLED_DrawLine_ByAngle(COMPASS_CENTER_X, COMPASS_CENTER_Y, (-heading - 90), arror_len, 1); OLED_Show_String(96, 4, code_str, 24, 1); OLED_Show_String(78, 36, number_str, 24, 1); OLED_Icon_Draw(2, 24, &icon_skip_left, 0); OLED_Icon_Draw(122, 24, &icon_skip_right, 0); OLED_Refresh_GRAM(); aos_msleep(30); } running = 1; } int compass_uninit(void) { running = 0; while (!running) { aos_msleep(50); } if (g_haasboard_is_k1c) { qmc6310_deinit(); } else { qmc5883l_deinit(); } aos_task_delete(&compass_task_handle); LOGI(EDU_TAG, "aos_task_delete compass_task\n"); return 0; } void format_compass_str(char *number_str, char *code_str, int heading, uint8_t *arror_len) { heading = (heading % 360 < 0) ? (heading % 360 + 360) : (heading % 360); sprintf(number_str, "%3d", heading); if ((heading > 0 && heading <= 23) || (heading > 337 && heading <= 360)) { sprintf(code_str, " N", heading); *arror_len = 16; } else if (heading > 292 && heading <= 337) { sprintf(code_str, "WN", heading); *arror_len = 20; } else if (heading > 246 && heading <= 292) { sprintf(code_str, " W", heading); *arror_len = 16; } else if (heading > 202 && heading <= 246) { sprintf(code_str, "WS", heading); *arror_len = 20; } else if (heading > 158 && heading <= 202) { sprintf(code_str, " S", heading); *arror_len = 16; } else if (heading > 112 && heading <= 158) { sprintf(code_str, "ES", heading); *arror_len = 20; } else if (heading > 67 && heading <= 112) { sprintf(code_str, " E", heading); *arror_len = 16; } else if (heading > 23 && heading <= 67) { sprintf(code_str, "EN", heading); *arror_len = 20; } }
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/compass/compass.c
C
apache-2.0
3,613
#ifndef __COMPASS_H__ #define __COMPASS_H__ #include "../menu.h" extern MENU_TYP compass; int compass_init(void); int compass_uninit(void); void compass_task(void); static uint8_t icon_data_compass_55_55[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0x60, 0x30, 0x30, 0x18, 0x18, 0x0C, 0x0C, 0x06, 0x06, 0x02, 0x03, 0x03, 0x03, 0x01, 0x01, 0xE3, 0x47, 0x8F, 0x07, 0xE3, 0x01, 0x01, 0x03, 0x03, 0x03, 0x02, 0x06, 0x06, 0x0C, 0x0C, 0x18, 0x18, 0x30, 0x30, 0x60, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xE0, 0x78, 0x1C, 0x06, 0x03, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03, 0x03, 0x06, 0x1C, 0x78, 0xE0, 0x80, 0x00, 0x00, 0xF0, 0x7E, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x07, 0x7E, 0xF0, 0xFF, 0x3E, 0x1C, 0x08, 0x00, 0x22, 0x22, 0x2A, 0x2A, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x02, 0x1E, 0x02, 0x3E, 0x00, 0x08, 0x1C, 0x3E, 0xFF, 0x07, 0x3F, 0xF0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xF0, 0x3F, 0x07, 0x00, 0x00, 0x00, 0x03, 0x0F, 0x1C, 0x30, 0x60, 0xE0, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xA0, 0xA0, 0xA0, 0xA0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xE0, 0x60, 0x30, 0x1C, 0x0F, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x06, 0x06, 0x0C, 0x0C, 0x18, 0x18, 0x30, 0x30, 0x20, 0x60, 0x60, 0x60, 0x40, 0x40, 0x62, 0x72, 0x7A, 0x72, 0x63, 0x40, 0x40, 0x60, 0x60, 0x60, 0x20, 0x30, 0x30, 0x18, 0x18, 0x0C, 0x0C, 0x06, 0x06, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; static icon_t icon_compass_55_55 = {icon_data_compass_55_55, 55, 55}; static uint8_t icon_data_compass_arror_24_24[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xF0, 0xFC, 0x1C, 0xF0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x07, 0x3F, 0xF8, 0xE0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x70, 0x3C, 0x3F, 0x1F, 0x1F, 0x1F, 0x0F, 0x0F, 0x07, 0x06, 0x0E, 0x0C, 0x18, 0x18, 0x13, 0x37, 0x3C, 0x70, 0x60, 0x00, 0x00}; static icon_t icon_compass_arror_24_24 = {icon_data_compass_arror_24_24, 24, 24}; #endif
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/compass/compass.h
C
apache-2.0
3,370
#include "greedySnake.h" #include <stdio.h> #include <stdlib.h> MENU_COVER_TYP greedySnake_cover = {MENU_COVER_FUNC, NULL, NULL, greedySnake_cover_draw}; MENU_TASK_TYP greedySnake_tasks = {greedySnake_init, greedySnake_uninit}; MENU_TYP greedySnake = {"greedySnake", &greedySnake_cover, &greedySnake_tasks, greedySnake_key_handel}; static aos_task_t greedySnake_task_handle; #define MIN_LENGTH 4 #define SNAKE_UP 0b0010 #define SNAKE_LEFT 0b0001 #define SNAKE_RIGHT 0b0100 #define SNAKE_DOWN 0b1000 typedef struct { uint8_t length; int16_t *XPos; int16_t *YPos; uint8_t cur_dir; uint8_t alive; } Snake; // left top -> (0,0) typedef struct { int16_t x; int16_t y; uint8_t eaten; } Food; typedef struct { int16_t border_top; int16_t border_right; int16_t border_botton; int16_t border_left; int16_t block_size; } Map; typedef struct { int16_t score; int16_t pos_x_max; int16_t pos_y_max; } snake_game_t; Food food = {-1, -1, 1}; Snake snake = {MIN_LENGTH, NULL, NULL, SNAKE_RIGHT, 1}; Map map = {2, 128, 62, 12, 4}; snake_game_t snake_game = {0, 0, 0}; void greedySnake_cover_draw(int *draw_index) { // edit these only ! int snake_size = 3; int snake_head_init_pos_x = 10; int snake_head_init_pos_y = 20; int border_top = 8; int border_right = 117; int border_left = 15; int border_bottom = 56; // border 的长宽最好都整除 snake_size // edit these only ! int ver_step = (border_right - border_left - snake_size) / snake_size; int hor_step = (border_bottom - border_top - snake_size) / snake_size; int whole_step = (ver_step + hor_step) * 2; int floating_y[20] = {-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4}; OLED_Clear(); for (int len = 0; len < 6; len++) { int snake_body_init_pos_x = snake_head_init_pos_x; int snake_body_init_pos_y = snake_head_init_pos_y + snake_size * len; int snake_body_draw_index = ((*draw_index) % (whole_step + 1)) - len; if (snake_body_draw_index < 0) snake_body_draw_index += (whole_step + 1); if (snake_body_draw_index < ((snake_head_init_pos_y - border_top) / snake_size + 1) && snake_body_draw_index >= 0) { snake_body_init_pos_x = border_left; snake_body_init_pos_y = snake_head_init_pos_y - snake_body_draw_index * snake_size; } if (snake_body_draw_index < (((snake_head_init_pos_y - border_top) + (border_right - border_left - snake_size)) / snake_size + 1) && snake_body_draw_index >= ((snake_head_init_pos_y - border_top) / snake_size + 1)) { snake_body_init_pos_x = border_left + (snake_body_draw_index - ((snake_head_init_pos_y - border_top) / snake_size + 1)) * snake_size; snake_body_init_pos_y = border_top; } if (snake_body_draw_index < (((snake_head_init_pos_y - border_top) + (border_right - border_left - snake_size) + (border_bottom - border_top - snake_size)) / snake_size + 1) && snake_body_draw_index >= (((snake_head_init_pos_y - border_top) + (border_right - border_left - snake_size)) / snake_size + 1)) { snake_body_init_pos_x = (border_right - snake_size); snake_body_init_pos_y = border_top + (snake_body_draw_index - (((snake_head_init_pos_y - border_top) + (border_right - border_left - snake_size)) / snake_size + 1)) * snake_size; } if (snake_body_draw_index < (((snake_head_init_pos_y - border_top) + (border_right - border_left - snake_size) * 2 + (border_bottom - border_top - snake_size)) / snake_size + 1) && snake_body_draw_index >= (((snake_head_init_pos_y - border_top) + (border_right - border_left - snake_size) + (border_bottom - border_top - snake_size)) / snake_size + 1)) { snake_body_init_pos_x = (border_right - snake_size) - (snake_body_draw_index - (((snake_head_init_pos_y - border_top) + (border_right - border_left - snake_size) + (border_bottom - border_top - snake_size)) / snake_size + 1)) * snake_size; snake_body_init_pos_y = (border_bottom - snake_size); } if (snake_body_draw_index < (whole_step + 1) && snake_body_draw_index >= (((snake_head_init_pos_y - border_top) + (border_right - border_left - snake_size) * 2 + (border_bottom - border_top - snake_size)) / snake_size + 1)) { snake_body_init_pos_x = border_left; snake_body_init_pos_y = (border_bottom - snake_size) - (snake_body_draw_index - (((snake_head_init_pos_y - border_top) + (border_right - border_left - snake_size) * 2 + (border_bottom - border_top - snake_size)) / snake_size + 1)) * snake_size; } // printf("%d snake_body_pos %d %d\n", len, snake_body_init_pos_x, // snake_body_init_pos_y); OLED_FillRect(snake_body_init_pos_x, snake_body_init_pos_y, snake_size, snake_size, 1); OLED_Icon_Draw(36, 27 + floating_y[(*draw_index) % 20], &img_SNAKE_61_10, 0); OLED_Icon_Draw(2, 24, &icon_skip_left, 0); OLED_Icon_Draw(122, 24, &icon_skip_right, 0); } OLED_Refresh_GRAM(); ++(*draw_index); if ((*draw_index) == (whole_step + 1) * 20) (*draw_index) = 0; aos_msleep(60); } int greedySnake_init(void) { snake_game.pos_x_max = (map.border_right - map.border_left) / map.block_size; snake_game.pos_y_max = (map.border_botton - map.border_top) / map.block_size; snake.XPos = (int16_t *)malloc(snake_game.pos_x_max * snake_game.pos_y_max * sizeof(int16_t)); snake.YPos = (int16_t *)malloc(snake_game.pos_x_max * snake_game.pos_y_max * sizeof(int16_t)); snake.length = MIN_LENGTH; snake.cur_dir = SNAKE_RIGHT; snake.alive = 1; snake_game.score = 0; food.eaten = 1; for (uint8_t i = 0; i < snake.length; i++) { snake.XPos[i] = snake_game.pos_x_max / 2 + i; snake.YPos[i] = snake_game.pos_y_max / 2; } OLED_Clear(); draw_snake(); gen_food(); draw_food(); OLED_Refresh_GRAM(); aos_task_new_ext(&greedySnake_task_handle, "greedySnake_task", greedySnake_task, NULL, 1024, AOS_DEFAULT_APP_PRI); printf("aos_task_new greedySnake_task\n"); return 0; } void draw_snake() { uint16_t i = 0; OLED_Icon_Draw(map.border_left + snake.XPos[i] * map.block_size, map.border_top + snake.YPos[i] * map.block_size, &icon_snake0_4_4, 0); for (; i < snake.length - 2; i++) { OLED_Icon_Draw(map.border_left + snake.XPos[i] * map.block_size, map.border_top + snake.YPos[i] * map.block_size, ((i % 2) ? &icon_snake1_4_4 : &icon_snake0_4_4), 0); } OLED_Icon_Draw(map.border_left + snake.XPos[i] * map.block_size, map.border_top + snake.YPos[i] * map.block_size, &icon_snake1_4_4, 0); } void gen_food() { int i = 0; if (food.eaten == 1) { while (1) { food.x = rand() % (snake_game.pos_x_max - 6) + 3; food.y = rand() % (snake_game.pos_y_max - 6) + 3; for (i = 0; i < snake.length; i++) { if ((food.x == snake.XPos[i]) && (food.y == snake.YPos[i])) break; } if (i == snake.length) { food.eaten = 0; break; } } } } void draw_food() { if (food.eaten == 0) { OLED_Icon_Draw(map.border_left + food.x * map.block_size, map.border_top + food.y * map.block_size, &icon_food_4_4, 0); } } void greedySnake_task(void) { while (1) { if (snake.alive) { OLED_Clear(); OLED_Icon_Draw(3, 41, &icon_scores_5_21, 0); OLED_DrawRect(11, 1, 118, 62, 1); draw_score(snake_game.score); Snake_Run(snake.cur_dir); OLED_Refresh_GRAM(); aos_msleep(200); } else { OLED_Clear(); OLED_Show_String(30, 12, "GAME OVER", 16, 1); OLED_Show_String(10, 40, "press K1&K2 to quit", 12, 1); OLED_Refresh_GRAM(); aos_msleep(500); } } } int greedySnake_uninit(void) { free(snake.YPos); free(snake.XPos); aos_task_delete(&greedySnake_task_handle); printf("aos_task_delete greedySnake_task\n"); return 0; } void greedySnake_key_handel(key_code_t key_code) { Snake_Run(key_code); } void check_snake_alive() { if (snake.XPos[snake.length - 1] < 0 || snake.XPos[snake.length - 1] >= snake_game.pos_x_max || snake.YPos[snake.length - 1] < 0 || snake.YPos[snake.length - 1] >= snake_game.pos_y_max) { snake.alive = 0; } for (int i = 0; i < snake.length - 1; i++) { if (snake.XPos[snake.length - 1] == snake.XPos[i] && snake.YPos[snake.length - 1] == snake.YPos[i]) { snake.alive = 0; break; } } } void Snake_Run(uint8_t dir) { uint16_t i; switch (dir) { case SNAKE_RIGHT: if (snake.cur_dir != SNAKE_LEFT) { for (i = 0; i < snake.length - 1; i++) { snake.XPos[i] = snake.XPos[i + 1]; snake.YPos[i] = snake.YPos[i + 1]; } snake.XPos[snake.length - 1] = snake.XPos[snake.length - 2] + 1; snake.YPos[snake.length - 1] = snake.YPos[snake.length - 2] - 0; snake.cur_dir = dir; } break; case SNAKE_LEFT: if (snake.cur_dir != SNAKE_RIGHT) { for (i = 0; i < snake.length - 1; i++) { snake.XPos[i] = snake.XPos[i + 1]; snake.YPos[i] = snake.YPos[i + 1]; } snake.XPos[snake.length - 1] = snake.XPos[snake.length - 2] - 1; snake.YPos[snake.length - 1] = snake.YPos[snake.length - 2] + 0; snake.cur_dir = dir; } break; case SNAKE_DOWN: if (snake.cur_dir != SNAKE_UP) { for (i = 0; i < snake.length - 1; i++) { snake.XPos[i] = snake.XPos[i + 1]; snake.YPos[i] = snake.YPos[i + 1]; } snake.XPos[snake.length - 1] = snake.XPos[snake.length - 2] + 0; snake.YPos[snake.length - 1] = snake.YPos[snake.length - 2] + 1; snake.cur_dir = dir; } break; case SNAKE_UP: if (snake.cur_dir != SNAKE_DOWN) { for (i = 0; i < snake.length - 1; i++) { snake.XPos[i] = snake.XPos[i + 1]; snake.YPos[i] = snake.YPos[i + 1]; } snake.XPos[snake.length - 1] = snake.XPos[snake.length - 2] + 0; snake.YPos[snake.length - 1] = snake.YPos[snake.length - 2] - 1; snake.cur_dir = dir; } break; default: break; } check_snake_alive(); check_food_eaten(); draw_snake(); draw_food(); } void check_food_eaten() { if (snake.XPos[snake.length - 1] == food.x && snake.YPos[snake.length - 1] == food.y) { snake.length++; snake.XPos[snake.length - 1] = food.x; snake.YPos[snake.length - 1] = food.y; snake_game.score++; food.eaten = 1; gen_food(); } } icon_t *get_icon_num_5_3(uint8_t num) { switch (num) { case 0: return &icon_0_5_3; break; case 1: return &icon_1_5_3; break; case 2: return &icon_2_5_3; break; case 3: return &icon_3_5_3; break; case 4: return &icon_4_5_3; break; case 5: return &icon_5_5_3; break; case 6: return &icon_6_5_3; break; case 7: return &icon_7_5_3; break; case 8: return &icon_8_5_3; break; case 9: return &icon_9_5_3; break; default: break; } } void draw_score(uint16_t score) { OLED_Icon_Draw(3, 35, get_icon_num_5_3((uint8_t)(score / 100)), 0); OLED_Icon_Draw(3, 31, get_icon_num_5_3((uint8_t)((score % 100) / 10)), 0); OLED_Icon_Draw(3, 27, get_icon_num_5_3((uint8_t)(score % 10)), 0); }
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/greedySnake/greedySnake.c
C
apache-2.0
13,996
#ifndef __GREEFYSNAKE_H__ #define __GREEFYSNAKE_H__ #include "../menu.h" extern MENU_TYP greedySnake; void StartGame(void); int greedySnake_init(void); int greedySnake_uninit(void); void greedySnake_task(void); void greedySnake_key_handel(key_code_t key_code); void greedySnake_cover_draw(int *draw_index); static uint8_t img_data_SNAKE_61_10[] = { 0x3F, 0x3F, 0x33, 0x33, 0x33, 0x33, 0x33, 0xF3, 0xF3, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x03, 0x0C, 0x30, 0xC0, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFE, 0x37, 0x33, 0x33, 0x33, 0x37, 0xFE, 0xFC, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x78, 0x78, 0xCC, 0xCE, 0x87, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03, 0x00, 0x00, 0x00, 0x01, 0x03, 0x03, 0x02, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03}; static icon_t img_SNAKE_61_10 = {img_data_SNAKE_61_10, 61, 10, NULL}; static uint8_t icon_data_scores_5_21[] = {0x9C, 0x50, 0x9D, 0x50, 0x5D, 0xDD, 0x55, 0x15, 0x55, 0xDD, 0x1D, 0x11, 0x1D, 0x05, 0x1D}; static icon_t icon_scores_5_21 = {icon_data_scores_5_21, 5, 21, NULL}; static uint8_t icon_data_0_5_3[] = {0x07, 0x05, 0x05, 0x05, 0x07}; static icon_t icon_0_5_3 = {icon_data_0_5_3, 5, 3, NULL}; static uint8_t icon_data_1_5_3[] = {0x01, 0x01, 0x01, 0x01, 0x01}; static icon_t icon_1_5_3 = {icon_data_1_5_3, 5, 3, NULL}; static uint8_t icon_data_2_5_3[] = {0x07, 0x01, 0x07, 0x04, 0x07}; static icon_t icon_2_5_3 = {icon_data_2_5_3, 5, 3, NULL}; static uint8_t icon_data_3_5_3[] = {0x07, 0x01, 0x07, 0x01, 0x07}; static icon_t icon_3_5_3 = {icon_data_3_5_3, 5, 3, NULL}; static uint8_t icon_data_4_5_3[] = {0x05, 0x05, 0x07, 0x01, 0x01}; static icon_t icon_4_5_3 = {icon_data_4_5_3, 5, 3, NULL}; static uint8_t icon_data_5_5_3[] = {0x07, 0x04, 0x07, 0x01, 0x07}; static icon_t icon_5_5_3 = {icon_data_5_5_3, 5, 3, NULL}; static uint8_t icon_data_6_5_3[] = {0x07, 0x04, 0x07, 0x05, 0x07}; static icon_t icon_6_5_3 = {icon_data_6_5_3, 5, 3, NULL}; static uint8_t icon_data_7_5_3[] = {0x07, 0x01, 0x01, 0x01, 0x01}; static icon_t icon_7_5_3 = {icon_data_7_5_3, 5, 3, NULL}; static uint8_t icon_data_8_5_3[] = {0x07, 0x05, 0x07, 0x05, 0x07}; static icon_t icon_8_5_3 = {icon_data_8_5_3, 5, 3, NULL}; static uint8_t icon_data_9_5_3[] = {0x07, 0x05, 0x07, 0x01, 0x07}; static icon_t icon_9_5_3 = {icon_data_9_5_3, 5, 3, NULL}; static uint8_t icon_data_snake0_4_4[] = {0x09, 0x09, 0x03, 0x03}; static icon_t icon_snake0_4_4 = {icon_data_snake0_4_4, 4, 4, NULL}; static uint8_t icon_data_snake1_4_4[] = {0x0f, 0x0f, 0x0f, 0x0f}; static icon_t icon_snake1_4_4 = {icon_data_snake1_4_4, 4, 4, NULL}; static uint8_t icon_data_food_4_4[] = {0x06, 0x09, 0x09, 0x06}; static icon_t icon_food_4_4 = {icon_data_food_4_4, 4, 4, NULL}; #endif
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/greedySnake/greedySnake.h
C
apache-2.0
3,335
#include "gyroscope.h" #include "drv_acc_gyro_inv_mpu6050.h" #include "drv_acc_gyro_qst_qmi8610.h" #include <stdio.h> #include <stdlib.h> MENU_COVER_TYP gyroscope_cover = {MENU_COVER_NONE}; MENU_TASK_TYP gyroscope_tasks = {gyroscope_init, gyroscope_uninit}; MENU_TYP gyroscope = {"gyroscope", &gyroscope_cover, &gyroscope_tasks, NULL, NULL}; static aos_task_t gyroscope_task_handle; static short r_ax = 0, r_ay = 0, r_az = 0; static int running = 1; typedef struct { int x; int y; int z; } node_t; typedef struct { node_t *start_node; node_t *end_node; } line_t; node_t node_list[] = {{0, 0, 0}, {20, 20, 20}, {-20, 20, 20}, {20, -20, 20}, {20, 20, -20}, {-20, -20, 20}, {-20, 20, -20}, {20, -20, -20}, {-20, -20, -20} }; line_t line_list[] = { {&node_list[1], &node_list[2]}, {&node_list[1], &node_list[3]}, {&node_list[3], &node_list[2]}, {&node_list[3], &node_list[4]}, {&node_list[1], &node_list[2]}, {&node_list[1], &node_list[2]}, {&node_list[1], &node_list[2]}, {&node_list[1], &node_list[2]}, {&node_list[1], &node_list[2]}, {&node_list[1], &node_list[2]}, {&node_list[1], &node_list[2]}, {&node_list[1], &node_list[2]}, }; int gyroscope_init(void) { if (g_haasboard_is_k1c) { FisImu_init(); LOGI(EDU_TAG, "FisImu_init done\n"); } else { MPU_Init(); LOGI(EDU_TAG, "MPU_Init done\n"); } LOGI(EDU_TAG, "MPU_Init done\n"); aos_task_new_ext(&gyroscope_task_handle, "gyroscope_task", gyroscope_task, NULL, 1024 * 4, AOS_DEFAULT_APP_PRI); LOGI(EDU_TAG, "aos_task_new gyroscope_task\n"); return 0; } void gyroscope_task(void) { float acc[3]; short ax, ay; while (running) { OLED_Clear(); if (g_haasboard_is_k1c) { FisImu_read_acc_xyz(acc); ax = (short)(acc[1] * 6.6); ay = (short)(acc[0] * 3.2); } else { MPU_Get_Accelerometer(&r_ax, &r_ay, &r_az); } OLED_Icon_Draw(2, 24, &icon_skip_left, 0); OLED_Icon_Draw(122, 24, &icon_skip_right, 0); OLED_DrawCircle(66, 32, 10, 1, 1); if (g_haasboard_is_k1c) { OLED_FillCircle(66 + ax, 32 + ay, 8, 1); } else { OLED_FillCircle(66 - r_ax / 250, 32 + r_ay / 500, 8, 1); } OLED_Refresh_GRAM(); aos_msleep(20); } running = 1; } int gyroscope_uninit(void) { running = 0; while (!running) { aos_msleep(50); } if (g_haasboard_is_k1c) { FisImu_deinit(); LOGI(EDU_TAG, "FisImu_deinit done\n"); } else { MPU_Deinit(); LOGI(EDU_TAG, "MPU_Deinit done\n"); } aos_task_delete(&gyroscope_task_handle); LOGI(EDU_TAG, "aos_task_delete gyroscope_task\n"); return 0; }
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/gyroscope/gyroscope.c
C
apache-2.0
2,854
#ifndef __GYROSCOPE_H__ #define __GYROSCOPE_H__ #include "../menu.h" extern MENU_TYP gyroscope; int gyroscope_init(void); int gyroscope_uninit(void); void gyroscope_task(void); #endif
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/gyroscope/gyroscope.h
C
apache-2.0
190
#include "homepage.h" #include "../menu.h" #include "aos/kernel.h" #include <stdio.h> #include <stdlib.h> #include <time.h> #include "posix/timer.h" #include "../../build_version.h" #include "netmgr.h" #include "aos/vfs.h" #include <drivers/u_ld.h> #include <vfsdev/adc_dev.h> #include <drivers/char/u_device.h> static int battery_level = 0; extern int bt_connected; extern int ip_got_finished; extern char eduk1_ip_addr[IPADDR_STR_LEN]; MENU_COVER_TYP homepage_cover = {MENU_COVER_NONE}; MENU_TASK_TYP homepage_tasks = {homepage_init, homepage_uninit}; MENU_TYP homepage = {"homepage", &homepage_cover, &homepage_tasks, NULL, NULL}; static aos_task_t homepage_task_handle; int homepage_init(void) { OLED_Clear(); OLED_Refresh_GRAM(); aos_task_new_ext(&homepage_task_handle, "homepage_task", homepage_task, NULL, 1024, AOS_DEFAULT_APP_PRI); LOGI(EDU_TAG, "aos_task_new homepage_task\n"); return 0; } static int get_battery(int *level, uint32_t *volage) { int32_t ret = 0; uint32_t test_sum = 0; uint32_t test_avrg = 0; uint32_t test_min = 3300; uint32_t test_max = 0; int32_t fd = 0; int32_t index = 1; int sampling_cycle = 100; char name[16] = {0}; io_adc_arg_t adc_arg; snprintf(name, sizeof(name), "/dev/adc%d", index); fd = open(name, 0); if (fd >= 0) { ret = ioctl(fd, IOC_ADC_START, sampling_cycle); usleep(1000); adc_arg.value = 0; adc_arg.timeout = 500000; // in unit of us for (int32_t i = 0; i < 10; i++) { ret = ioctl(fd, IOC_ADC_GET_VALUE, (unsigned long)&adc_arg); test_sum += adc_arg.value; /* the min sampling voltage */ if (test_min >= adc_arg.value) { test_min = adc_arg.value; } /* the max sampling voltage */ if (test_max <= adc_arg.value) { test_max = adc_arg.value; } } usleep(1000); ret = ioctl(fd, IOC_ADC_STOP, 0); close(fd); test_avrg = (test_sum - test_min - test_max) >> 3; LOGD(EDU_TAG, "the samping volage is:%dmv\n", test_avrg); test_avrg *= 3.208; *volage = test_avrg; if (test_avrg > 4100) { *level = 4; } else if ((test_avrg > 3980) && (test_avrg < 4100)) { *level = 3; } else if ((test_avrg > 3850) && (test_avrg < 3980)) { *level = 2; } else if ((test_avrg > 3700) && (test_avrg < 3850)) { *level = 1; } else if (test_avrg < 3700) { *level = 0; } } return 0; } void homepage_task(void) { unsigned char c = 0; struct tm *info; struct timespec tv; uint8_t image_version[22]; uint8_t tmp[22]; netmgr_ifconfig_info_t ifconfig; netmgr_hdl_t hdl; uint32_t volage; int ret = 0; while (1) { OLED_Clear(); /* 获取 GMT 时间 */ clock_gettime(CLOCK_REALTIME, &tv); info = gmtime(&tv); snprintf(tmp, 20, "%2d:%02d", (info->tm_hour + 8) % 24, info->tm_min); OLED_Show_String(2, 12 * 0, tmp, 12, 1); if (ip_got_finished) { OLED_Icon_Draw(86, 0, &icon_wifi_on_12_12, 0); snprintf(image_version, 20, "IP: %s", eduk1_ip_addr); OLED_Show_String(20, (12 + 4) * 3, image_version, 12, 1); }else { //snprintf(image_version, 20, "IP: ?.?.?.?", ifconfig.ip_addr); //OLED_Show_String(20, (12 + 4) * 3, image_version, 12, 1); } if (bt_connected) { OLED_Icon_Draw(97, 0, &icon_bt_on_12_12, 0); } OLED_Show_String(40, (12 + 4) * 1, "HaaS EDU", 12, 1); snprintf(image_version, 21, "VER: %s", BUILD_VERSION); OLED_Show_String(33, (12 + 4) * 2, image_version, 12, 1); OLED_Icon_Draw(2, 24, &icon_skip_left, 0); OLED_Icon_Draw(122, 24, &icon_skip_right, 0); if (0 == get_battery(&battery_level, &volage)) { LOGD(EDU_TAG, "get_battery success:%d mv,level :%d \n", volage, battery_level); OLED_Icon_Draw(110, 0, &icon_battery_20_12[battery_level], 0); } else { LOGE(EDU_TAG, "get_battery fail\n"); } OLED_Refresh_GRAM(); aos_msleep(1000); } } int homepage_uninit(void) { aos_task_delete(&homepage_task_handle); LOGI(EDU_TAG, "aos_task_delete homepage_task\n"); return 0; }
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/homepage/homepage.c
C
apache-2.0
4,517
#ifndef __HOMEPAGE_H__ #define __HOMEPAGE_H__ #include "../menu.h" extern MENU_TYP homepage; static uint8_t icon_data_battery0_20_12[] = { 0x00, 0xFC, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0xFC, 0xF8, 0x00, 0x00, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x03, 0x01, 0x00}; static uint8_t icon_data_battery25_20_12[] = { 0x00, 0xFC, 0xFE, 0xFE, 0xFE, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0xFC, 0xF8, 0x00, 0x00, 0x03, 0x07, 0x07, 0x07, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x03, 0x01, 0x00}; static uint8_t icon_data_battery50_20_12[] = { 0x00, 0xFC, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0xFC, 0xF8, 0x00, 0x00, 0x03, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x03, 0x01, 0x00}; static uint8_t icon_data_battery75_20_12[] = { 0x00, 0xFC, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0x02, 0x02, 0x02, 0x02, 0xFC, 0xF8, 0x00, 0x00, 0x03, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x04, 0x04, 0x04, 0x04, 0x03, 0x01, 0x00}; static uint8_t icon_data_battery100_20_12[] = { 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xF8, 0x00, 0x00, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x01, 0x00}; static icon_t icon_battery_20_12[5] = { {icon_data_battery0_20_12, 20, 12, NULL}, {icon_data_battery25_20_12, 20, 12, NULL}, {icon_data_battery50_20_12, 20, 12, NULL}, {icon_data_battery75_20_12, 20, 12, NULL}, {icon_data_battery100_20_12, 20, 12, NULL}, }; static uint8_t icon_data_bt_on_12_12[] = { 0x00, 0x00, 0x00, 0x10, 0xA0, 0x40, 0xFE, 0x44, 0xA8, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0F, 0x04, 0x02, 0x01, 0x00, 0x00}; static icon_t icon_bt_on_12_12 = {icon_data_bt_on_12_12, 12, 12, NULL}; static uint8_t icon_data_wifi_on_12_12[] = { 0x10, 0x18, 0x4C, 0x64, 0x36, 0x92, 0x92, 0x36, 0x64, 0x4C, 0x18, 0x10, 0x00, 0x00, 0x00, 0x00, 0x01, 0x04, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00}; static icon_t icon_wifi_on_12_12 = {icon_data_wifi_on_12_12, 12, 12, NULL}; int homepage_init(void); int homepage_uninit(void); void homepage_task(void); #endif
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/homepage/homepage.h
C
apache-2.0
2,526
#include "humiture.h" #include "drv_temp_humi_si_si7006.h" #include "drv_temp_humi_sensylink_cht8305.h" #include "../menu.h" MENU_COVER_TYP humiture_cover = {MENU_COVER_NONE}; MENU_TASK_TYP humiture_tasks = {humiture_init, humiture_uninit}; MENU_TYP humiture = {"humiture", &humiture_cover, &humiture_tasks, NULL, NULL}; static int running = 1; static aos_task_t humiture_task_handle; int humiture_init(void) { if (g_haasboard_is_k1c) { cht8305_init(); LOGI(EDU_TAG, "cht8305_init done\n"); } else { si7006_init(); LOGI(EDU_TAG, "si7006_init done\n"); } OLED_Clear(); OLED_Refresh_GRAM(); running = 1; aos_task_new_ext(&humiture_task_handle, "humiture_task", humiture_task, NULL, 1024 * 4, AOS_DEFAULT_APP_PRI); LOGI(EDU_TAG, "aos_task_delete humiture_task\n"); return 0; } void humiture_task(void) { float temp, hump; uint8_t temp_str[10]; uint8_t hump_str[10]; unsigned char c = 0; while (running) { if (g_haasboard_is_k1c) { cht8305_getTempHumidity(&hump, &temp); } else { si7006_getTempHumidity(&hump, &temp); } sprintf(temp_str, "T:%5.1fC", temp); sprintf(hump_str, "H:%5.1f%%", hump); // LOGD(EDU_TAG, "%s %s", temp_str, hump_str); OLED_Icon_Draw(14, 4, &icon_thermometer_24_24, 0); OLED_Icon_Draw(14, 36, &icon_hygrometer_24_24, 0); OLED_Icon_Draw(2, 24, &icon_skip_left, 0); OLED_Icon_Draw(122, 24, &icon_skip_right, 0); OLED_Show_String(42, 8, temp_str, 16, 1); OLED_Show_String(42, 40, hump_str, 16, 1); OLED_Refresh_GRAM(); aos_msleep(500); } running = 1; } int humiture_uninit(void) { running = 0; while (!running) { aos_msleep(50); } if (g_haasboard_is_k1c) { cht8305_deinit(); LOGI(EDU_TAG, "cht8305_deinit done\n"); } else { si7006_deinit(); LOGI(EDU_TAG, "si7006_deinit done\n"); } aos_task_delete(&humiture_task_handle); LOGI(EDU_TAG, "aos_task_delete humiture_task\n"); return 0; }
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/humiture/humiture.c
C
apache-2.0
2,143
#ifndef __HUMITURE_H__ #define __HUMITURE_H__ #include "../menu.h" extern MENU_TYP humiture; int humiture_init(void); int humiture_uninit(void); void humiture_task(void); static uint8_t icon_data_hygrometer_24_24[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x01, 0xFE, 0x00, 0x24, 0x24, 0x24, 0x24, 0x04, 0x80, 0xC0, 0xE0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x49, 0x09, 0x01, 0x00, 0x3E, 0x7F, 0x7F, 0x7F, 0x59, 0x63, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x7E, 0xFF, 0xFF, 0xFE, 0xFD, 0xFB, 0x66, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; static icon_t icon_hygrometer_24_24 = {icon_data_hygrometer_24_24, 24, 24, NULL}; static uint8_t icon_data_thermometer_24_24[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x01, 0xFE, 0x00, 0x24, 0x24, 0x24, 0x24, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x49, 0x09, 0x01, 0x00, 0x04, 0x0A, 0xE4, 0x10, 0x10, 0x10, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x7E, 0xFF, 0xFF, 0xFE, 0xFD, 0xFB, 0x66, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x03, 0x04, 0x04, 0x04, 0x02, 0x00, 0x00}; static icon_t icon_thermometer_24_24 = {icon_data_thermometer_24_24, 24, 24, NULL}; #endif
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/humiture/humiture.h
C
apache-2.0
1,441
/* * Copyright (C) 2020-2023 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdint.h> #include <stdbool.h> #include <ulog/ulog.h> #include <vfsdev/pwm_dev.h> void beeper_start(uint16_t port, uint16_t frequency, uint16_t duration) { int ret = -1; int fd = 0; char name[16] = {0}; float duty_cycle = 0.8; snprintf(name, sizeof(name), "/dev/pwm%d", port); fd = open(name, 0); if (fd >= 0) { if (frequency > 0) { ret = ioctl(fd, IOC_PWM_FREQ, (unsigned long)frequency); ret = ioctl(fd, IOC_PWM_DUTY_CYCLE, (unsigned long)&duty_cycle); ret = ioctl(fd, IOC_PWM_ON, (unsigned long)0); } if (duration != 0) { aos_msleep(duration); } if (frequency > 0 && duration > 0) { ret = ioctl(fd, IOC_PWM_OFF, (unsigned long)0); close(fd); } } } void beeper_stop(uint16_t port) { int ret = -1; int fd = 0; char name[16] = {0}; float duty_cycle = 0.8; int freq = 1; unsigned int period_s; snprintf(name, sizeof(name), "/dev/pwm%d", port); fd = open(name, 0); if (fd >= 0) { ret = ioctl(fd, IOC_PWM_FREQ, (unsigned long)freq); ret = ioctl(fd, IOC_PWM_DUTY_CYCLE, (unsigned long)&duty_cycle); ret = ioctl(fd, IOC_PWM_ON, (unsigned long)0); ret = ioctl(fd, IOC_PWM_OFF, (unsigned long)0); close(fd); } }
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/kws/beeper/beeper.c
C
apache-2.0
1,434
#ifndef _BEEPER_H_ #define _BEEPER_H_ #include <stdint.h> void beeper_start(uint16_t port, uint16_t frequency, uint16_t duration); void beeper_stop(uint16_t port); #endif
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/kws/beeper/beeper.h
C
apache-2.0
176
#!/usr/bin/env python3 import os import sys import getpass import shutil #!/usr/bin/env python3 import os import sys import getpass import shutil comp_path = sys.path[0] print("comp_path:") print(comp_path) # original folder src_mp3_path = comp_path + "/resources/mp3" # new folder data_path = comp_path + "/../../../../hardware/chip/haas1000/prebuild/data/data" mp3_dst_path = data_path + "/mp3" # delete prebuild/data resources if os.path.exists(mp3_dst_path): print ('Delete /data/mp3 firstly') shutil.rmtree(mp3_dst_path) # copy resources shutil.copytree(src_mp3_path, mp3_dst_path) # result print("run external script success")
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/kws/cp_resources.py
Python
apache-2.0
650
#include "kws.h" #include "../menu.h" #include "aiagent_service.h" #include "aiagent_common.h" #include "beeper/beeper.h" #define TAG "kws" #include "uvoice_init.h" #include "uvoice_types.h" #include "uvoice_event.h" #include "uvoice_player.h" #include "uvoice_recorder.h" #include "uvoice_os.h" MENU_COVER_TYP kws_cover = {MENU_COVER_NONE}; MENU_TASK_TYP kws_tasks = {kws_init, kws_uninit}; MENU_TYP kws = {"kws", &kws_cover, &kws_tasks, NULL, NULL}; static os_task_t play_task; static uvoice_player_t *uvocplayer; static char text_source[256]; static int source_sample_rate; static int source_channels; static bool running = false; extern int audio_install_codec_driver(); static int get_format_from_name(char *name, media_format_t *format) { if (!name || !format) { LOGE(TAG, "arg null !\n"); return -1; } if (strstr(name, ".mp3") || strstr(name, ".MP3")) *format = MEDIA_FMT_MP3; else if (strstr(name, ".wav") || strstr(name, ".WAV")) *format = MEDIA_FMT_WAV; else if (strstr(name, ".aac") || strstr(name, ".AAC")) *format = MEDIA_FMT_AAC; else if (strstr(name, ".m4a") || strstr(name, ".M4A")) *format = MEDIA_FMT_M4A; else if (strstr(name, ".pcm") || strstr(name, ".PCM")) *format = MEDIA_FMT_PCM; else if (strstr(name, ".spx") || strstr(name, ".SPX")) *format = MEDIA_FMT_SPX; else if (strstr(name, ".ogg") || strstr(name, ".OGG")) *format = MEDIA_FMT_OGG; else if (strstr(name, ".amrwb") || strstr(name, ".AMRWB")) *format = MEDIA_FMT_AMRWB; else if (strstr(name, ".amr") || strstr(name, ".AMR")) *format = MEDIA_FMT_AMR; else if (strstr(name, ".opus") || strstr(name, ".OPUS")) *format = MEDIA_FMT_OPS; else if (strstr(name, ".flac") || strstr(name, ".FLAC")) *format = MEDIA_FMT_FLAC; return 0; } static void *play_music(void *arg) { media_format_t format = MEDIA_FMT_UNKNOWN; get_format_from_name(text_source, &format); if (uvocplayer->set_source(text_source)) { LOGE(TAG, "set source failed !\n"); return NULL; } if (format == MEDIA_FMT_OPS || format == MEDIA_FMT_SPX) uvocplayer->set_pcminfo(source_sample_rate, source_channels, 16, 1280); if (uvocplayer->start()) { LOGE(TAG, "start failed !\n"); uvocplayer->clr_source(); } return NULL; } static int32_t play_local_mp3(void) { int32_t random; random = rand() % 240; LOG("random: %d\n", random); memset(text_source, 0, sizeof(text_source)); if (random < 100) { strcpy(text_source, "fs:/data/mp3/haas_intro.mp3"); } else if (random > 100 && random < 150) { strcpy(text_source, "fs:/data/mp3/haasxiaozhushou.mp3"); } else if (random > 150 && random < 200) { strcpy(text_source, "fs:/data/mp3/zhurenwozai.mp3"); } else { strcpy(text_source, "fs:/data/mp3/eiwozai.mp3"); } aos_task_new_ext(&play_task, "play music task", play_music, NULL, 8192, 0); return 0; } int32_t kws_callback(ai_result_t *result) { int32_t kws_ret = (int32_t)*result; int32_t ret = -1; player_state_t player_state = -1; if (kws_ret) { beeper_start(0, 1, 25); OLED_Clear(); OLED_Show_String(14, 24, "Hi, I am here!", 16, 1); OLED_Refresh_GRAM(); beeper_stop(0); /*play local asr*/ play_local_mp3(); ret = uvocplayer->wait_complete(); if (ret < 0) aos_msleep(1000); OLED_Clear(); OLED_Show_String(28, 16, "HaaS HaaS!", 16, 1); OLED_Show_String(28, 34, "Wakeup me!", 16, 1); OLED_Icon_Draw(2, 24, &icon_skip_left, 0); OLED_Icon_Draw(122, 24, &icon_skip_right, 0); OLED_Refresh_GRAM(); } return 0; } int32_t kws_init(void) { int32_t ret = 0; ai_config_t config; OLED_Clear(); OLED_Show_String(28, 16, "HaaS HaaS!", 16, 1); OLED_Show_String(28, 34, "Wakeup me!", 16, 1); OLED_Icon_Draw(2, 24, &icon_skip_left, 0); OLED_Icon_Draw(122, 24, &icon_skip_right, 0); OLED_Refresh_GRAM(); if (!running) { /*Init sound driver*/ audio_install_codec_driver(); /*Init uvoice to play mp3*/ uvoice_init(); /*create uvoice player*/ uvocplayer = uvoice_player_create(); if (!uvocplayer) { LOGE(TAG, "create media player failed !\n"); return -1; } /*set eq*/ uvocplayer->eq_enable(0); /*set play volume*/ uvocplayer->set_volume(10); running = true; } ret = aiagent_service_init("kws", AI_MODEL_KWS); if (ret < 0) { LOGE(TAG, "aiagent_service_init failed"); return -1; } /*config mic channel*/ config.channel = 0; aiagent_service_config(&config); return aiagent_service_model_infer(NULL, NULL, kws_callback); } int32_t kws_uninit(void) { // running = false; uvocplayer->stop(); uvocplayer->clr_source(); aiagent_service_uninit(); return 0; }
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/kws/kws.c
C
apache-2.0
4,975
#ifndef __KWS_H__ #define __KWS_H__ #include "../menu.h" extern MENU_TYP kws; int32_t kws_init(void); int32_t kws_uninit(void); #endif
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/kws/kws.h
C
apache-2.0
139
#include "lightmeter.h" #include "drv_als_ps_ir_liteon_ap3216c.h" #include "aos/kernel.h" #include <stdio.h> #include <stdlib.h> MENU_COVER_TYP lightmeter_cover = {MENU_COVER_NONE}; MENU_TASK_TYP lightmeter_tasks = {lightmeter_init, lightmeter_uninit}; MENU_LIST_TYP lightmeter_child_list = {NULL, 0}; MENU_TYP lightmeter = {"lightmeter", &lightmeter_cover, &lightmeter_tasks, NULL, &lightmeter_child_list}; static aos_task_t lightmeter_task_handle; static int running = 1; int lightmeter_init(void) { LOGI(EDU_TAG, "lightmeter_init begin\n"); ap3216c_init(); LOGI(EDU_TAG, "lightmeter_init done\n"); OLED_Clear(); OLED_Refresh_GRAM(); aos_task_new_ext(&lightmeter_task_handle, "lightmeter_task", lightmeter_task, NULL, 2048, AOS_DEFAULT_APP_PRI); LOGI(EDU_TAG, "aos_task_new lightmeter_task\n"); return 0; } void lightmeter_task(void) { uint16_t tmp[3]; uint8_t als[20]; uint8_t ps[20]; uint8_t ir[20]; while (running) { tmp[0] = ap3216c_read_ambient_light(); tmp[1] = ap3216c_read_ir_data(); tmp[2] = ap3216c_read_ps_data(); sprintf(als, "ALS: %d", tmp[0]); sprintf(ir, "IR : %d", tmp[1]); OLED_Clear(); OLED_Icon_Draw(20, 14, &icon_lighter_32_32, 0); OLED_Show_String(64, 6, als, 12, 1); OLED_Show_String(64, 20, ir, 12, 1); if ((tmp[2] >> 15) & 1) OLED_Show_String(64, 36, "near !", 16, 1); else OLED_Show_String(64, 40, "far !", 16, 1); OLED_Icon_Draw(2, 24, &icon_skip_left, 0); OLED_Icon_Draw(122, 24, &icon_skip_right, 0); OLED_Refresh_GRAM(); /* wait for 112.5ms at least according to ap3216c's datasheet */ aos_msleep(150); } running = 1; } int lightmeter_uninit(void) { running = 0; while (!running) { aos_msleep(50); } ap3216c_deinit(); aos_task_delete(&lightmeter_task_handle); LOGI(EDU_TAG, "aos_task_delete lightmeter_task\n"); return 0; }
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/lightmeter/lightmeter.c
C
apache-2.0
2,054
#ifndef __LIGHTMETER_H__ #define __LIGHTMETER_H__ #include "../menu.h" static uint8_t icon_data_lighter_24_24[] = { 0x00, 0xC0, 0xF0, 0x18, 0x0C, 0x24, 0x46, 0x86, 0x02, 0x00, 0x00, 0x00, 0x10, 0x50, 0x50, 0x92, 0x26, 0x46, 0x84, 0x0C, 0x18, 0xF0, 0xC0, 0x00, 0x00, 0x81, 0x00, 0x08, 0x08, 0x08, 0x08, 0x00, 0x3C, 0x66, 0xC3, 0x81, 0x81, 0xC3, 0x66, 0x3C, 0x01, 0x06, 0x00, 0x0F, 0x00, 0x00, 0x81, 0x00, 0x00, 0x03, 0x0F, 0x18, 0x30, 0x24, 0x62, 0x61, 0x40, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x00, 0x40, 0x61, 0x62, 0x24, 0x30, 0x18, 0x0F, 0x03, 0x00}; static icon_t icon_lighter_24_24 = {icon_data_lighter_24_24, 24, 24, NULL}; static uint8_t icon_data_lighter_32_32[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x30, 0x38, 0x18, 0x1C, 0x0C, 0x0C, 0x04, 0x84, 0x8C, 0x8C, 0x9C, 0x18, 0x38, 0x30, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x7C, 0x1E, 0x03, 0x00, 0x80, 0x80, 0x82, 0x04, 0x08, 0xC0, 0x20, 0x10, 0x12, 0x12, 0x16, 0x2C, 0xC9, 0x11, 0x73, 0xC6, 0x1C, 0x70, 0xC0, 0x03, 0x1E, 0x7C, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x3E, 0x78, 0xE0, 0x00, 0x00, 0x00, 0x40, 0x20, 0x10, 0x03, 0x04, 0x08, 0xE8, 0x08, 0x08, 0x04, 0x03, 0x10, 0x20, 0x41, 0x07, 0x00, 0x01, 0xC0, 0x78, 0x3E, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x0C, 0x18, 0x18, 0x38, 0x30, 0x30, 0x20, 0x20, 0x30, 0x30, 0x38, 0x18, 0x18, 0x0C, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; static icon_t icon_lighter_32_32 = {icon_data_lighter_32_32, 32, 32, NULL}; extern MENU_TYP lightmeter; int lightmeter_init(void); int lightmeter_uninit(void); void lightmeter_task(void); #endif
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/lightmeter/lightmeter.h
C
apache-2.0
2,264
#include <stdio.h> #include <stdlib.h> #include "aos/kernel.h" #include "menu.h" // 添加离自己最近的子级目录 #include "aircraftBattle/aircraftBattle.h" #include "barometer/barometer.h" #include "compass/compass.h" #include "greedySnake/greedySnake.h" #include "gyroscope/gyroscope.h" #include "homepage/homepage.h" #include "humiture/humiture.h" #include "lightmeter/lightmeter.h" #include "musicbox/musicbox.h" #include "shakeshake/shakeshake.h" #include "kws/kws.h" #define KEY_CODE_BACK (EDK_KEY_1 | EDK_KEY_2) #define KEY_CODE_LEFT EDK_KEY_1 #define KEY_CODE_RIGHT EDK_KEY_3 #define KEY_CODE_DOWN EDK_KEY_4 MENU_TYP *Menus[] = { &homepage, &humiture, &gyroscope, &shakeshake, &compass, &barometer, &lightmeter, &musicbox, &greedySnake, &aircraftBattle, &kws, }; MENU_LIST_TYP MenuList = {Menus, sizeof(Menus)/sizeof(Menus[0])}; MENU_TYP *pCurMenu = NULL; key_code_cb app_key_code_cb = NULL; void menu_list_fix(MENU_LIST_TYP *menuChildList, MENU_TYP *menuParent) { uint8_t curLevelMenuSize = menuChildList->MenuListSize; printf("curLevelMenuSize %d\n", curLevelMenuSize); for (uint8_t i = 0; i < curLevelMenuSize; i++) { if (menuParent != NULL) { menuParent->pChild = menuChildList->pMenuList[0]; menuChildList->pMenuList[i]->pParent = menuParent; } else { menuChildList->pMenuList[i]->pParent = NULL; } menuChildList->pMenuList[i]->pRight = ((i == curLevelMenuSize - 1) ? menuChildList->pMenuList[0] : menuChildList->pMenuList[i + 1]); menuChildList->pMenuList[i]->pLeft = ((i == 0) ? menuChildList->pMenuList[curLevelMenuSize - 1] : menuChildList->pMenuList[i - 1]); MENU_LIST_TYP *pchildlist = menuChildList->pMenuList[i]->pChildrenList; if (pchildlist != NULL) printf("pchildlist->MenuListSize\n", pchildlist->MenuListSize); if (pchildlist != NULL && pchildlist->MenuListSize > 0) { printf("pchildlist->MenuListSize\n", pchildlist->MenuListSize); menu_list_fix(menuChildList->pMenuList[i]->pChildrenList, menuChildList->pMenuList[i]); } } } void menu_init() { menu_list_fix(&MenuList, NULL); pCurMenu = MenuList.pMenuList[0]; key_init(public_key_event_handle); app_key_code_cb = menu_key_event_handle; aos_task_new("menu_show_cover_task", menu_show_cover_task, NULL, 5000); if (pCurMenu->MenuCover->MenuCoverMode == MENU_COVER_NONE) { menu_task_start(pCurMenu); } } static void menu_show_cover_task(void) { static int loading_draw_index = 0; static int error_draw_index = 0; while (1) { if (pCurMenu != NULL) { // printf("%s state %d\n", pCurMenu->MenuName, // pCurMenu->pMenuTask->menu_task_state); } if (pCurMenu != NULL && pCurMenu->pMenuTask->menu_task_state == MENU_TASK_IDLE) { switch (pCurMenu->MenuCover->MenuCoverMode) { case MENU_COVER_NONE: printf("[E] You are not suppose to get here %s:%d\n", __func__, __LINE__); aos_msleep(1000); break; case MENU_COVER_TEXT: OLED_Clear(); if (pCurMenu->MenuCover->text != NULL) { OLED_Show_String(22, 4, pCurMenu->MenuCover->text, 12, 1); } OLED_Icon_Draw(2, 24, &icon_skip_left, 0); OLED_Icon_Draw(122, 24, &icon_skip_right, 0); OLED_Refresh_GRAM(); aos_msleep(200); break; case MENU_COVER_IMG: OLED_Clear(); if (pCurMenu->MenuCover->img != NULL) { OLED_Icon_Draw(0, 0, pCurMenu->MenuCover->img, 1); } OLED_Icon_Draw(2, 24, &icon_skip_left, 0); OLED_Icon_Draw(122, 24, &icon_skip_right, 0); OLED_Refresh_GRAM(); aos_msleep(200); break; case MENU_COVER_FUNC: if (pCurMenu->MenuCover->draw_func != NULL) pCurMenu->MenuCover->draw_func( &(pCurMenu->MenuCover->draw_index)); break; default: aos_msleep(1000); break; } } else if (pCurMenu != NULL && (pCurMenu->pMenuTask->menu_task_state == MENU_TASK_UNINITING || pCurMenu->pMenuTask->menu_task_state == MENU_TASK_INITING)) { menu_loading_draw(&loading_draw_index); } else if (pCurMenu == NULL) { menu_error_draw(&error_draw_index); } else { aos_msleep(500); } } } void menu_loading_draw(int *draw_index) { (*draw_index)++; if ((*draw_index) >= 8) (*draw_index) = 0; OLED_Clear(); switch ((*draw_index)) { case 0: OLED_Icon_Draw(50, 4, &icon_loadlines0_32_32, 0); OLED_Show_String(36, 42, "loading", 12, 1); break; case 1: OLED_Icon_Draw(50, 4, &icon_loadlines1_32_32, 0); OLED_Show_String(36, 42, "loading.", 12, 1); break; case 2: OLED_Icon_Draw(50, 4, &icon_loadlines2_32_32, 0); OLED_Show_String(36, 42, "loading..", 12, 1); break; case 3: OLED_Icon_Draw(50, 4, &icon_loadlines3_32_32, 0); OLED_Show_String(36, 42, "loading...", 12, 1); break; case 4: OLED_Icon_Draw(50, 4, &icon_loadlines4_32_32, 0); OLED_Show_String(36, 42, "loading", 12, 1); break; case 5: OLED_Icon_Draw(50, 4, &icon_loadlines5_32_32, 0); OLED_Show_String(36, 42, "loading.", 12, 1); break; case 6: OLED_Icon_Draw(50, 4, &icon_loadlines6_32_32, 0); OLED_Show_String(36, 42, "loading..", 12, 1); break; case 7: OLED_Icon_Draw(50, 4, &icon_loadlines7_32_32, 0); OLED_Show_String(36, 42, "loading...", 12, 1); break; default: break; } OLED_Refresh_GRAM(); aos_msleep(100); } void menu_error_draw(int *draw_index) { OLED_Clear(); OLED_Icon_Draw(54, 10, &icon_error_ufo, 1); OLED_Show_String(15, 42, "Please reset me !", 12, 1); OLED_Refresh_GRAM(); aos_msleep(500); } static void public_key_event_handle(key_code_t key_code) { if (key_code == KEY_CODE_BACK) { app_key_code_cb = menu_key_event_handle; if (pCurMenu != NULL) { if (pCurMenu->MenuCover->MenuCoverMode != MENU_COVER_NONE) { if (pCurMenu->pMenuTask->menu_task_state != MENU_TASK_RUNNING) { if (pCurMenu->pParent != NULL) pCurMenu = pCurMenu->pParent; } else { menu_task_exit(pCurMenu); } } else { if (pCurMenu->pParent != NULL) { menu_task_exit(pCurMenu); pCurMenu = pCurMenu->pParent; if (pCurMenu->MenuCover->MenuCoverMode == MENU_COVER_NONE) { menu_task_start(pCurMenu); } } } } } else { if (app_key_code_cb != NULL) { app_key_code_cb(key_code); } else { printf("app_key_code_cb is null\n"); } } } static int menu_task_start(MENU_TYP *pMenu) { if (pMenu == NULL) { printf("pMenu null in %s:%d\n", __func__, __LINE__); return -1; } // 先卸载按键 app_key_code_cb = NULL; if (pMenu->pMenuTask != NULL) { if (pMenu->pMenuTask->menu_task_state == MENU_TASK_IDLE) { if (pMenu->pMenuTask->pMenuTaskInit != NULL) { pMenu->pMenuTask->menu_task_state = MENU_TASK_INITING; if (pMenu->pMenuTask->pMenuTaskInit() == 0) { pMenu->pMenuTask->menu_task_state = MENU_TASK_RUNNING; app_key_code_cb = (pMenu->pTaskKeyDeal == NULL) ? menu_key_event_handle : pMenu->pTaskKeyDeal; return 0; } else { printf("[E] %s task init func null\n", pMenu->MenuName); app_key_code_cb = menu_key_event_handle; return 1; } } else { pMenu->pMenuTask->menu_task_state = MENU_TASK_IDLE; app_key_code_cb = menu_key_event_handle; return 1; } } else { printf("[E] %s task state err %d\n", pMenu->MenuName, pMenu->pMenuTask->menu_task_state); pMenu->pMenuTask->menu_task_state = MENU_TASK_IDLE; app_key_code_cb = menu_key_event_handle; return 1; } } else { printf("[E] %s pMenuTask null in %s:%d\n", pMenu->MenuName, __func__, __LINE__); app_key_code_cb = menu_key_event_handle; return 1; } } static int menu_task_exit(MENU_TYP *pMenu) { if (pMenu == NULL) { printf("pMenu null in %s:%d\n", __func__, __LINE__); return -1; } app_key_code_cb = NULL; if (pMenu->pMenuTask != NULL) { if (pMenu->pMenuTask->menu_task_state == MENU_TASK_RUNNING) { if (pMenu->pMenuTask->pMenuTaskEnd != NULL) { pMenu->pMenuTask->menu_task_state = MENU_TASK_UNINITING; if (pMenu->pMenuTask->pMenuTaskEnd() == 0) { pMenu->pMenuTask->menu_task_state = MENU_TASK_IDLE; app_key_code_cb = menu_key_event_handle; return 0; } else { printf("[E] %s task exit fail\n", pMenu->MenuName); return 1; } } else { pMenu->pMenuTask->menu_task_state = MENU_TASK_IDLE; app_key_code_cb = menu_key_event_handle; return 0; } } else { pMenu->pMenuTask->menu_task_state = MENU_TASK_IDLE; app_key_code_cb = menu_key_event_handle; return 0; } } else { app_key_code_cb = menu_key_event_handle; return 0; } } static void menu_key_event_handle(key_code_t key_code) { if (pCurMenu == NULL) { printf("pCurMenu null in %s:%d\n", __func__, __LINE__); return; } switch (key_code) { case 4: if (pCurMenu->MenuCover->MenuCoverMode == MENU_COVER_NONE) { menu_task_exit(pCurMenu); pCurMenu = pCurMenu->pRight; } else { if (pCurMenu->pMenuTask->menu_task_state == MENU_TASK_IDLE) pCurMenu = pCurMenu->pRight; } break; case KEY_CODE_LEFT: if (pCurMenu->MenuCover->MenuCoverMode == MENU_COVER_NONE) { menu_task_exit(pCurMenu); pCurMenu = pCurMenu->pLeft; } else { if (pCurMenu->pMenuTask->menu_task_state == MENU_TASK_IDLE) pCurMenu = pCurMenu->pLeft; } break; case KEY_CODE_DOWN: if (pCurMenu->pChild != NULL) { pCurMenu = pCurMenu->pChild; } else { if (pCurMenu->MenuCover->MenuCoverMode != MENU_COVER_NONE) { menu_task_start(pCurMenu); } } break; default: break; } switch (key_code) { case KEY_CODE_RIGHT: case KEY_CODE_LEFT: if (pCurMenu == NULL) { printf("pCurMenu null in %s:%d\n", __func__, __LINE__); return; } if (pCurMenu->MenuCover->MenuCoverMode == MENU_COVER_NONE) { menu_task_start(pCurMenu); } break; } }
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/menu.c
C
apache-2.0
12,580
#ifndef __MENU_H__ #define __MENU_H__ #include "key.h" #include "sh1106.h" #include <stdio.h> #include "aos/kernel.h" extern uint8_t g_haasedu_boardname; extern int g_haasboard_is_k1c; typedef int MENU_ID_TYP; #ifdef EDU_TAG #undef EDU_TAG #endif #define EDU_TAG "eduk1_demo" typedef enum { MENU_TASK_IDLE, MENU_TASK_RUNNING, MENU_TASK_INITING, MENU_TASK_UNINITING } MENU_TASK_STATE_ENU; typedef struct { int (*pMenuTaskInit)(void); int (*pMenuTaskEnd)(void); // user don't need to care MENU_TASK_STATE_ENU menu_task_state; } MENU_TASK_TYP; typedef enum { MENU_COVER_NONE, MENU_COVER_TEXT, MENU_COVER_IMG, MENU_COVER_FUNC, } MENU_COVER_MODE_ENU; typedef struct { MENU_COVER_MODE_ENU MenuCoverMode; char *text; icon_t *img; void (*draw_func)(int *); int draw_index; } MENU_COVER_TYP; typedef struct { struct MenuTyp **pMenuList; uint8_t MenuListSize; } MENU_LIST_TYP; typedef struct MenuTyp { char *MenuName; // 菜单名称字符串 MENU_COVER_TYP *MenuCover; // 封面 MENU_TASK_TYP *pMenuTask; // 指向菜单任务的指针 void (*pTaskKeyDeal)(key_code_t key_code); // 指向菜单任务按键处理函数的指针 struct MENU_LIST_TYP *pChildrenList; // 指向子菜单列表的指针 // user don't need to care MENU_ID_TYP MenuID; struct MenuTyp *pParent; // 指向上层菜单的指针 struct MenuTyp *pChild; // 指向子菜单的指针 struct MenuTyp *pRight; // 指向右菜单的指针 struct MenuTyp *pLeft; // 指向左菜单的指针 } MENU_TYP; void menu_init(void); static void public_key_event_handle(key_code_t key_code); static void menu_key_event_handle(key_code_t key_code); static void menu_show_cover_task(void); static int menu_task_start(MENU_TYP *pMenu); static int menu_task_exit(MENU_TYP *pMenu); static uint8_t icon_data_skip_left[16] = {0x00, 0x00, 0x80, 0x60, 0x18, 0x04, 0x02, 0x00, 0x00, 0x00, 0x01, 0x06, 0x18, 0x20, 0x40, 0x00}; static icon_t icon_skip_left = {icon_data_skip_left, 8, 16}; static uint8_t icon_data_skip_right[16] = {0x00, 0x02, 0x04, 0x18, 0x60, 0x80, 0x00, 0x00, 0x00, 0x40, 0x20, 0x18, 0x06, 0x01, 0x00, 0x00}; static icon_t icon_skip_right = {icon_data_skip_right, 8, 16}; static uint8_t icon_data_error_ufo[75] = { 0x18, 0x24, 0x00, 0x18, 0x24, 0x00, 0x18, 0x38, 0x2A, 0xFB, 0x3B, 0x2B, 0xBB, 0x3B, 0x2B, 0xFB, 0x3A, 0x38, 0x18, 0x00, 0x24, 0x18, 0x00, 0x24, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0xA8, 0x00, 0xAA, 0x00, 0xA8, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xA8, 0xA8, 0x02, 0xF8, 0x2A, 0xD0, 0x02, 0xF8, 0x2A, 0xD0, 0x02, 0x70, 0x8A, 0x70, 0x02, 0xF8, 0x28, 0xD0, 0x00, 0x00, 0x00}; static icon_t icon_error_ufo = {icon_data_error_ufo, 25, 24}; static uint8_t icon_data_loadlines0_32_32[] = { 0x00, 0x00, 0x00, 0x00, 0x30, 0x70, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0x70, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x81, 0x83, 0x87, 0x8E, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x8E, 0x87, 0x83, 0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x81, 0xC1, 0xE1, 0x71, 0x20, 0x00, 0x00, 0x00, 0xE0, 0xE0, 0x00, 0x00, 0x00, 0x20, 0x71, 0xE1, 0xC1, 0x81, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0E, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x07, 0x0E, 0x0C, 0x00, 0x00, 0x00, 0x00}; static icon_t icon_loadlines0_32_32 = {icon_data_loadlines0_32_32, 32, 32}; static uint8_t icon_data_loadlines1_32_32[] = { 0x00, 0x00, 0x00, 0x00, 0x30, 0x70, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x81, 0x83, 0x87, 0x8E, 0x04, 0x00, 0x00, 0x00, 0x07, 0x07, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x81, 0xC1, 0xE1, 0x71, 0x20, 0x00, 0x00, 0x00, 0xE0, 0xE0, 0x00, 0x00, 0x00, 0x20, 0x71, 0xE1, 0xC1, 0x81, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0E, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x07, 0x0E, 0x0C, 0x00, 0x00, 0x00, 0x00}; static icon_t icon_loadlines1_32_32 = {icon_data_loadlines1_32_32, 32, 32}; static uint8_t icon_data_loadlines2_32_32[] = { 0x00, 0x00, 0x00, 0x00, 0x30, 0x70, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0x70, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x81, 0x83, 0x87, 0x8E, 0x04, 0x00, 0x00, 0x00, 0x07, 0x07, 0x00, 0x00, 0x00, 0x04, 0x0E, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x81, 0xC1, 0xE1, 0x71, 0x20, 0x00, 0x00, 0x00, 0xE0, 0xE0, 0x00, 0x00, 0x00, 0x20, 0x70, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0E, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x07, 0x0E, 0x0C, 0x00, 0x00, 0x00, 0x00}; static icon_t icon_loadlines2_32_32 = {icon_data_loadlines2_32_32, 32, 32}; static uint8_t icon_data_loadlines3_32_32[] = { 0x00, 0x00, 0x00, 0x00, 0x30, 0x70, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0x70, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x81, 0x83, 0x87, 0x8E, 0x04, 0x00, 0x00, 0x00, 0x07, 0x07, 0x00, 0x00, 0x00, 0x04, 0x8E, 0x87, 0x83, 0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x81, 0xC1, 0xE1, 0x71, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x71, 0xE1, 0xC1, 0x81, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0E, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x07, 0x0E, 0x0C, 0x00, 0x00, 0x00, 0x00}; static icon_t icon_loadlines3_32_32 = {icon_data_loadlines3_32_32, 32, 32}; static uint8_t icon_data_loadlines4_32_32[] = { 0x00, 0x00, 0x00, 0x00, 0x30, 0x70, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0x70, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x81, 0x83, 0x87, 0x8E, 0x04, 0x00, 0x00, 0x00, 0x07, 0x07, 0x00, 0x00, 0x00, 0x04, 0x8E, 0x87, 0x83, 0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x81, 0xC1, 0xE1, 0x71, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x71, 0xE1, 0xC1, 0x81, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0E, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x07, 0x0E, 0x0C, 0x00, 0x00, 0x00, 0x00}; static icon_t icon_loadlines4_32_32 = {icon_data_loadlines4_32_32, 32, 32}; static uint8_t icon_data_loadlines5_32_32[] = { 0x00, 0x00, 0x00, 0x00, 0x30, 0x70, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0x70, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x81, 0x83, 0x87, 0x8E, 0x04, 0x00, 0x00, 0x00, 0x07, 0x07, 0x00, 0x00, 0x00, 0x04, 0x8E, 0x87, 0x83, 0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xE0, 0x00, 0x00, 0x00, 0x20, 0x71, 0xE1, 0xC1, 0x81, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x07, 0x0E, 0x0C, 0x00, 0x00, 0x00, 0x00}; static icon_t icon_loadlines5_32_32 = {icon_data_loadlines5_32_32, 32, 32}; static uint8_t icon_data_loadlines6_32_32[] = { 0x00, 0x00, 0x00, 0x00, 0x30, 0x70, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0x70, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x07, 0x0E, 0x04, 0x00, 0x00, 0x00, 0x07, 0x07, 0x00, 0x00, 0x00, 0x04, 0x8E, 0x87, 0x83, 0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0x70, 0x20, 0x00, 0x00, 0x00, 0xE0, 0xE0, 0x00, 0x00, 0x00, 0x20, 0x71, 0xE1, 0xC1, 0x81, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0E, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x07, 0x0E, 0x0C, 0x00, 0x00, 0x00, 0x00}; static icon_t icon_loadlines6_32_32 = {icon_data_loadlines6_32_32, 32, 32}; static uint8_t icon_data_loadlines7_32_32[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0x70, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x07, 0x07, 0x00, 0x00, 0x00, 0x04, 0x8E, 0x87, 0x83, 0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x81, 0xC1, 0xE1, 0x71, 0x20, 0x00, 0x00, 0x00, 0xE0, 0xE0, 0x00, 0x00, 0x00, 0x20, 0x71, 0xE1, 0xC1, 0x81, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0E, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x07, 0x0E, 0x0C, 0x00, 0x00, 0x00, 0x00}; static icon_t icon_loadlines7_32_32 = {icon_data_loadlines7_32_32, 32, 32}; #endif
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/menu.h
C
apache-2.0
10,611
#include "musicbox.h" #include <stdio.h> #include <stdlib.h> #include <vfsdev/pwm_dev.h> MENU_COVER_TYP musicbox_cover = {MENU_COVER_FUNC, NULL, NULL, musicbox_cover_draw, 0}; MENU_TASK_TYP musicbox_tasks = {musicbox_init, musicbox_uninit}; MENU_TYP musicbox = {"musicbox", &musicbox_cover, &musicbox_tasks, musicbox_key_handel, NULL}; static aos_task_t musicbox_task_handle; #define NOTE_SPACE_RATIO 1.3 music_t *music_list[] = { &Imperial_March, &liang_zhi_lao_hu, }; player_t musicbox_player = {music_list, 2, 0, 0, 0, 0}; void musicbox_cover_draw(int *draw_index) { int floating_y[] = {-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4}; OLED_Clear(); OLED_Icon_Draw(48, 16 + floating_y[*draw_index], &icon_note_32_32, 0); OLED_Icon_Draw(2, 24, &icon_skip_left, 0); OLED_Icon_Draw(122, 24, &icon_skip_right, 0); (*draw_index)++; if ((*draw_index) >= 20) { (*draw_index) = 0; } OLED_Refresh_GRAM(); aos_msleep(100); return 0; } int musicbox_init(void) { OLED_Clear(); OLED_Refresh_GRAM(); musicbox_player.isPlaying = 0; musicbox_player.cur_music_note = 0; set_music_time(); aos_task_new_ext(&musicbox_task_handle, "musicbox_task", musicbox_task, NULL, 1024 * 4, AOS_DEFAULT_APP_PRI); LOGI(EDU_TAG, "aos_task_new musicbox_task\n"); return 0; } int musicbox_uninit(void) { noTone(0); aos_task_delete(&musicbox_task_handle); LOGI(EDU_TAG, "aos_task_delete musicbox_task\n"); return 0; } void set_music_time() { for (int i = 0; i < musicbox_player.music_list_len; i++) { for (int n = 0; n < musicbox_player.music_list[i]->noteLength; n++) { int noteDuration = 1000 / musicbox_player.music_list[i]->noteDurations[n]; noteDuration = (noteDuration < 0) ? (-noteDuration * 1.5) : noteDuration; musicbox_player.music_list[i]->musicTime += (noteDuration + (int)(noteDuration * NOTE_SPACE_RATIO)); } } } void next_song() { musicbox_player.cur_music_index = ((musicbox_player.cur_music_index == musicbox_player.music_list_len - 1) ? (0) : (musicbox_player.cur_music_index + 1)); LOGI(EDU_TAG, "cur_music_index %d\n", musicbox_player.cur_music_index); musicbox_player.cur_music_note = 0; musicbox_player.cur_music_time = 0; musicbox_player.isPlaying = 1; } void previous_song() { musicbox_player.cur_music_index = ((musicbox_player.cur_music_index == 0) ? (musicbox_player.music_list_len - 1) : (musicbox_player.cur_music_index - 1)); LOGI(EDU_TAG, "cur_music_index %d\n", musicbox_player.cur_music_index); musicbox_player.cur_music_note = 0; musicbox_player.cur_music_time = 0; musicbox_player.isPlaying = 1; } void pause_resume() { musicbox_player.isPlaying = !musicbox_player.isPlaying; } void musicbox_key_handel(key_code_t key_code) { switch (key_code) { case 0b0001: // pre previous_song(); aos_msleep(1000); break; case 0b0100: // next next_song(); aos_msleep(1000); break; case 0b1000: // pause/resume pause_resume(); break; default: break; } } void tone(uint16_t port, uint16_t frequency, uint16_t duration) { int ret = -1; int fd = 0; char name[16] = {0}; float duty_cycle = 0.8; snprintf(name, sizeof(name), "/dev/pwm%d", port); fd = open(name, 0); if (fd >= 0) { if (frequency > 0) { ret = ioctl(fd, IOC_PWM_FREQ, (unsigned long)frequency); ret = ioctl(fd, IOC_PWM_DUTY_CYCLE, (unsigned long)&duty_cycle); ret = ioctl(fd, IOC_PWM_ON, (unsigned long)0); } if (duration != 0) { aos_msleep(duration); } if (frequency > 0 && duration > 0) { ret = ioctl(fd, IOC_PWM_OFF, (unsigned long)0); close(fd); } } } void noTone(uint16_t port) { int ret = -1; int fd = 0; char name[16] = {0}; float duty_cycle = 0.8; int freq = 1; unsigned int period_s; snprintf(name, sizeof(name), "/dev/pwm%d", port); fd = open(name, 0); if (fd >= 0) { ret = ioctl(fd, IOC_PWM_FREQ, (unsigned long)freq); ret = ioctl(fd, IOC_PWM_DUTY_CYCLE, (unsigned long)&duty_cycle); ret = ioctl(fd, IOC_PWM_ON, (unsigned long)0); ret = ioctl(fd, IOC_PWM_OFF, (unsigned long)0); close(fd); } } void musicbox_task() { while (1) { OLED_Clear(); music_t *cur_music = musicbox_player.music_list[musicbox_player.cur_music_index]; char show_song_name[14] = {0}; sprintf(show_song_name, "%-13.13s", cur_music->name); OLED_Show_String(14, 4, show_song_name, 16, 1); if (musicbox_player.isPlaying) { if (musicbox_player.cur_music_note < cur_music->noteLength) { int noteDuration = 1000 / cur_music->noteDurations[musicbox_player.cur_music_note]; noteDuration = (noteDuration < 0) ? (-noteDuration * 1.5) : noteDuration; LOGI(EDU_TAG, "note[%d] = %d\t delay %d ms\n", musicbox_player.cur_music_note, cur_music->noteDurations[musicbox_player.cur_music_note], noteDuration); int note = cur_music->notes[musicbox_player.cur_music_note]; tone(0, note, noteDuration); aos_msleep((int)(noteDuration * NOTE_SPACE_RATIO)); musicbox_player.cur_music_time += (noteDuration + (int)(noteDuration * NOTE_SPACE_RATIO)); musicbox_player.cur_music_note++; } else { noTone(0); aos_msleep(1000); next_song(); } OLED_Icon_Draw(54, 36, &icon_pause_24_24, 1); } else { OLED_Icon_Draw(54, 36, &icon_resume_24_24, 1); aos_msleep(500); } OLED_DrawLine(14, 26, 14, 29, 1); OLED_DrawLine(117, 26, 117, 29, 1); OLED_DrawLine(16, 27, (int)(16 + 99.0 * (musicbox_player.cur_music_time * 1.0 / cur_music->musicTime)), 27, 1); OLED_DrawLine(16, 28, 16 + 99.0 * (musicbox_player.cur_music_time * 1.0 / cur_music->musicTime), 28, 1); OLED_Icon_Draw(94, 36, &icon_next_song_24_24, 1); OLED_Icon_Draw(14, 36, &icon_previous_song_24_24, 1); OLED_Refresh_GRAM(); } }
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/musicbox/musicbox.c
C
apache-2.0
6,989
#ifndef __MUSICBOX_H__ #define __MUSICBOX_H__ #include "../menu.h" #include "pitches.h" extern MENU_TYP musicbox; typedef struct { char *name; int *notes; int *noteDurations; unsigned int noteLength; unsigned int musicTime; } music_t; typedef struct { music_t **music_list; unsigned int music_list_len; int cur_music_index; unsigned int cur_music_note; unsigned int cur_music_time; unsigned int isPlaying; } player_t; int musicbox_init(void); int musicbox_uninit(void); void musicbox_task(void); void musicbox_key_handel(key_code_t key_code); void musicbox_cover_draw(int *draw_index); static uint8_t icon_data_next_song_24_24[] = { 0x00, 0x00, 0x00, 0xFE, 0xFC, 0xF8, 0xF0, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7E, 0x3C, 0x18, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x3F, 0x1F, 0x0F, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x7F, 0x7F, 0x00, 0x00, 0x00}; static icon_t icon_next_song_24_24 = {icon_data_next_song_24_24, 24, 24}; static uint8_t icon_data_previous_song_24_24[] = { 0x00, 0x00, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x7E, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x7F, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0x00, 0x00, 0x00}; static icon_t icon_previous_song_24_24 = {icon_data_previous_song_24_24, 24, 24}; static uint8_t icon_data_resemu_24_24[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFC, 0xF8, 0xF0, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7E, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x3F, 0x1F, 0x0F, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; static icon_t icon_resume_24_24 = {icon_data_resemu_24_24, 24, 24}; static uint8_t icon_data_pause_24_24[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x7F, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x7F, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; static icon_t icon_pause_24_24 = {icon_data_pause_24_24, 24, 24}; static uint8_t icon_data_note_32_32[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xF8, 0xF8, 0xF8, 0x7C, 0x7C, 0x7C, 0x3C, 0x3E, 0x3E, 0x3E, 0x9E, 0x9E, 0x9F, 0x9F, 0xCF, 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x1C, 0x1C, 0x0E, 0x0E, 0x0F, 0x07, 0x07, 0x07, 0x07, 0x07, 0x03, 0x03, 0x01, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x80, 0x80, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0x80, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xF8, 0xFC, 0xFE, 0x9E, 0x0F, 0x0F, 0x0F, 0x0F, 0x9E, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0x7F, 0x7F, 0xFF, 0xF3, 0xE1, 0xE1, 0xE1, 0xE1, 0xF3, 0xFF, 0x7F, 0x3F, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x07, 0x0F, 0x0F, 0x1F, 0x1F, 0x1F, 0x1F, 0x0F, 0x0F, 0x07, 0x01, 0x00}; static icon_t icon_note_32_32 = {icon_data_note_32_32, 32, 32}; static int liang_zhi_lao_hu_Notes[] = { NOTE_C4, NOTE_D4, NOTE_E4, NOTE_C4, NOTE_C4, NOTE_D4, NOTE_E4, NOTE_C4, NOTE_E4, NOTE_F4, NOTE_G4, NOTE_E4, NOTE_F4, NOTE_G4, NOTE_G4, NOTE_A4, NOTE_G4, NOTE_F4, NOTE_E4, NOTE_C4, NOTE_G4, NOTE_A4, NOTE_G4, NOTE_F4, NOTE_E4, NOTE_C4, NOTE_D4, NOTE_G3, NOTE_C4, 0, NOTE_D4, NOTE_G3, NOTE_C4, 0}; static int liang_zhi_lao_hu_NoteDurations[] = { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 8, 8, 4, 8, 8, 8, 8, 4, 4, 8, 8, 8, 8, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4}; static music_t liang_zhi_lao_hu = {"liang_zhi_lao_hu", liang_zhi_lao_hu_Notes, liang_zhi_lao_hu_NoteDurations, 34}; static int Imperial_March_Notes[] = { // Dart Vader theme (Imperial March) - Star wars // Score available at https://musescore.com/user/202909/scores/1141521 // The tenor saxophone part was used // notes from // https://github.com/robsoncouto/arduino-songs/blob/master/imperialmarch/imperialmarch.ino NOTE_A4, NOTE_A4, NOTE_A4, NOTE_A4, NOTE_A4, NOTE_A4, NOTE_F4, REST, NOTE_A4, NOTE_A4, NOTE_A4, NOTE_A4, NOTE_A4, NOTE_A4, NOTE_F4, REST, NOTE_A4, NOTE_A4, NOTE_A4, NOTE_F4, NOTE_C5, NOTE_A4, NOTE_F4, NOTE_C5, NOTE_A4, NOTE_E5, NOTE_E5, NOTE_E5, NOTE_F5, NOTE_C5, NOTE_A4, NOTE_F4, NOTE_C5, NOTE_A4, NOTE_A5, NOTE_A4, NOTE_A4, NOTE_A5, NOTE_GS5, NOTE_G5, NOTE_DS5, NOTE_D5, NOTE_DS5, REST, NOTE_A4, NOTE_DS5, NOTE_D5, NOTE_CS5, NOTE_C5, NOTE_B4, NOTE_C5, REST, NOTE_F4, NOTE_GS4, NOTE_F4, NOTE_A4, NOTE_C5, NOTE_A4, NOTE_C5, NOTE_E5, NOTE_A5, NOTE_A4, NOTE_A4, NOTE_A5, NOTE_GS5, NOTE_G5, NOTE_DS5, NOTE_D5, NOTE_DS5, REST, NOTE_A4, NOTE_DS5, NOTE_D5, NOTE_CS5, NOTE_C5, NOTE_B4, NOTE_C5, REST, NOTE_F4, NOTE_GS4, NOTE_F4, NOTE_A4, NOTE_A4, NOTE_F4, NOTE_C5, NOTE_A4}; static int Imperial_March_NoteDurations[] = { -4, -4, 16, 16, 16, 16, 8, 8, -4, -4, 16, 16, 16, 16, 8, 8, 4, 4, 4, -8, 16, 4, -8, 16, 2, 4, 4, 4, -8, 16, 4, -8, 16, 2, 4, -8, 16, 4, -8, 16, 16, 16, 8, 8, 8, 4, -8, 16, 16, 16, 16, 8, 8, 4, -8, 16, 4, -8, 16, 2, 4, -8, 16, 4, -8, 16, 16, 16, 8, 8, 8, 4, -8, 16, 16, 16, 16, 8, 8, 4, -8, 16, 4, -8, 16, 2}; static music_t Imperial_March = {"Imperial_March", Imperial_March_Notes, Imperial_March_NoteDurations, 86}; #endif
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/musicbox/musicbox.h
C
apache-2.0
6,340
#define NOTE_B0 31 #define NOTE_C1 33 #define NOTE_CS1 35 #define NOTE_D1 37 #define NOTE_DS1 39 #define NOTE_E1 41 #define NOTE_F1 44 #define NOTE_FS1 46 #define NOTE_G1 49 #define NOTE_GS1 52 #define NOTE_A1 55 #define NOTE_AS1 58 #define NOTE_B1 62 #define NOTE_C2 65 #define NOTE_CS2 69 #define NOTE_D2 73 #define NOTE_DS2 78 #define NOTE_E2 82 #define NOTE_F2 87 #define NOTE_FS2 93 #define NOTE_G2 98 #define NOTE_GS2 104 #define NOTE_A2 110 #define NOTE_AS2 117 #define NOTE_B2 123 #define NOTE_C3 131 #define NOTE_CS3 139 #define NOTE_D3 147 #define NOTE_DS3 156 #define NOTE_E3 165 #define NOTE_F3 175 #define NOTE_FS3 185 #define NOTE_G3 196 #define NOTE_GS3 208 #define NOTE_A3 220 #define NOTE_AS3 233 #define NOTE_B3 247 #define NOTE_C4 262 #define NOTE_CS4 277 #define NOTE_D4 294 #define NOTE_DS4 311 #define NOTE_E4 330 #define NOTE_F4 349 #define NOTE_FS4 370 #define NOTE_G4 392 #define NOTE_GS4 415 #define NOTE_A4 440 #define NOTE_AS4 466 #define NOTE_B4 494 #define NOTE_C5 523 #define NOTE_CS5 554 #define NOTE_D5 587 #define NOTE_DS5 622 #define NOTE_E5 659 #define NOTE_F5 698 #define NOTE_FS5 740 #define NOTE_G5 784 #define NOTE_GS5 831 #define NOTE_A5 880 #define NOTE_AS5 932 #define NOTE_B5 988 #define NOTE_C6 1047 #define NOTE_CS6 1109 #define NOTE_D6 1175 #define NOTE_DS6 1245 #define NOTE_E6 1319 #define NOTE_F6 1397 #define NOTE_FS6 1480 #define NOTE_G6 1568 #define NOTE_GS6 1661 #define NOTE_A6 1760 #define NOTE_AS6 1865 #define NOTE_B6 1976 #define NOTE_C7 2093 #define NOTE_CS7 2217 #define NOTE_D7 2349 #define NOTE_DS7 2489 #define NOTE_E7 2637 #define NOTE_F7 2794 #define NOTE_FS7 2960 #define NOTE_G7 3136 #define NOTE_GS7 3322 #define NOTE_A7 3520 #define NOTE_AS7 3729 #define NOTE_B7 3951 #define NOTE_C8 4186 #define NOTE_CS8 4435 #define NOTE_D8 4699 #define NOTE_DS8 4978 #define REST 0
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/musicbox/pitches.h
C
apache-2.0
1,895
#include "shakeshake.h" #include "drv_acc_gyro_inv_mpu6050.h" #include "drv_acc_gyro_qst_qmi8610.h" #include <stdio.h> #include <stdlib.h> #define SHAKE_Z_THRESHOLD 5000 #define SHAKE_Y_THRESHOLD 4000 MENU_COVER_TYP shakeshake_cover = {MENU_COVER_NONE}; MENU_TASK_TYP shakeshake_tasks = {shakeshake_init, shakeshake_uninit}; MENU_TYP shakeshake = {"shakeshake", &shakeshake_cover, &shakeshake_tasks, NULL, NULL}; static aos_task_t shakeshake_task_handle; char showstr[10] = "0"; short ax = 0, ay, az; short ay_pre = 0, az_pre = 0; short y_change = 0, z_change = 0; short rand_value = 0; static int running = 1; int shakeshake_init(void) { if (g_haasboard_is_k1c) { FisImu_init(); LOGI(EDU_TAG, "FisImu_init done\n"); } else { MPU_Init(); LOGI(EDU_TAG, "MPU_Init done\n"); } OLED_Clear(); OLED_Icon_Draw(50, 0, &icon_shakeshake_32_32_v2, 1); OLED_Show_String(32, 40, "Shake me !", 16, 1); OLED_Icon_Draw(2, 24, &icon_skip_left, 0); OLED_Icon_Draw(122, 24, &icon_skip_right, 0); OLED_Refresh_GRAM(); aos_task_new_ext(&shakeshake_task_handle, "shakeshake_task", shakeshake_task, NULL, 1024 * 4, AOS_DEFAULT_APP_PRI); LOGI(EDU_TAG, "aos_task_new shakeshake_task\n"); return 0; } void shakeshake_task() { float acc[3]; while (running) { if (g_haasboard_is_k1c) { FisImu_read_acc_xyz(acc); ay = (short)(acc[0] * 1000); az = (short)(acc[2] * 1000); } else { MPU_Get_Accelerometer(&ax, &ay, &az); } y_change = (ay >= ay_pre) ? (ay - ay_pre) : (ay_pre - ay); z_change = (az >= az_pre) ? (az - az_pre) : (az_pre - az); if ((y_change > SHAKE_Y_THRESHOLD) && (z_change > SHAKE_Z_THRESHOLD)) { rand_value = rand() % 100; itoa(rand_value, showstr, 10); OLED_Clear(); OLED_Icon_Draw(50, 0, &icon_shakeshake_32_32_v2, 1); OLED_Show_String(54, 36, showstr, 24, 1); OLED_Icon_Draw(2, 24, &icon_skip_left, 0); OLED_Icon_Draw(122, 24, &icon_skip_right, 0); OLED_Refresh_GRAM(); } az_pre = az; ay_pre = ay; aos_msleep(50); } running = 1; } int shakeshake_uninit(void) { running = 0; while (!running) { aos_msleep(50); } if (g_haasboard_is_k1c) { FisImu_deinit(); } else { MPU_Deinit(); } aos_task_delete(&shakeshake_task_handle); LOGI(EDU_TAG, "aos_task_delete shakeshake_task\n"); return 0; }
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/shakeshake/shakeshake.c
C
apache-2.0
2,632
#ifndef __SHAKESHAKE_H__ #define __SHAKESHAKE_H__ #include "../menu.h" extern MENU_TYP shakeshake; int shakeshake_init(void); int shakeshake_uninit(void); void shakeshake_task(void); static uint8_t icon_data_shakeshake_32_32[128] = { 0x00, 0x00, 0x00, 0x40, 0x80, 0x00, 0x00, 0x00, 0xF0, 0xF0, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0xF0, 0xF0, 0x00, 0x00, 0x00, 0x80, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x44, 0xAA, 0x11, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x11, 0xAA, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x44, 0xAA, 0x11, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x30, 0x30, 0xCC, 0xCC, 0x30, 0x30, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x11, 0xAA, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x07, 0x07, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x07, 0x07, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00}; static icon_t icon_shakeshake_32_32 = {icon_data_shakeshake_32_32, 32, 32}; static uint8_t icon_data_shakeshake_32_32_v2[128] = { 0x00, 0x00, 0x00, 0x40, 0x80, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x10, 0xD0, 0xD0, 0xD0, 0xD0, 0xD0, 0xD0, 0xD0, 0xD0, 0xD0, 0xD0, 0x10, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x80, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x44, 0xAA, 0x11, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF, 0xF3, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x11, 0xAA, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x44, 0xAA, 0x11, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x30, 0x30, 0xCC, 0xCC, 0x30, 0x30, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x11, 0xAA, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00}; static icon_t icon_shakeshake_32_32_v2 = {icon_data_shakeshake_32_32_v2, 32, 32}; static uint8_t icon_data_shakeshake_32_32_v2_wave[128] = { 0x00, 0x00, 0x00, 0x80, 0x40, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x10, 0x90, 0xD0, 0xD0, 0xD0, 0xD0, 0xD0, 0xD0, 0xD0, 0xD0, 0x90, 0x10, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x40, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0xAA, 0x44, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x7F, 0xFF, 0xFF, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF, 0xF3, 0x7F, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x44, 0xAA, 0x11, 0x00, 0x00, 0x00, 0x00, 0x11, 0xAA, 0x44, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x30, 0x30, 0xCC, 0xCC, 0x30, 0x30, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x44, 0xAA, 0x11, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x01, 0x00, 0x00}; static icon_t icon_shakeshake_32_32_v2_wave = { icon_data_shakeshake_32_32_v2_wave, 32, 32}; /* (32 X 32 )*/ #endif
YifuLiu/AliOS-Things
solutions/eduk1_demo/k1_apps/shakeshake/shakeshake.h
C
apache-2.0
3,115
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/init.h" #include "board.h" #include <aos/kernel.h> #include <k_api.h> #include <stdio.h> #include <stdlib.h> #include "build_version.h" #ifndef AOS_BINS extern int application_start(int argc, char *argv[]); #endif /* If board have no component for example board_xx_init, it indicates that this app does not support this board. Set the correspondence in file platform\board\aaboard_demo\ucube.py. */ extern void board_tick_init(void); extern void board_stduart_init(void); extern void board_detect(); extern void board_dma_init(void); extern void board_gpio_init(void); extern void board_kinit_init(kinit_t *init_args); /* For user config kinit.argc = 0; kinit.argv = NULL; kinit.cli_enable = 1; */ static kinit_t kinit = {0, NULL, 1}; /** * @brief Board Initialization Function * @param None * @retval None */ void board_init(void) { board_tick_init(); board_stduart_init(); board_dma_init(); board_gpio_init(); } void aos_maintask(void *arg) { board_init(); board_kinit_init(&kinit); aos_components_init(&kinit); board_detect(); #if (ENABLE_FACTORY_TEST == 1) uint8_t image_version[22]; sprintf(image_version, "VER: %s", BUILD_VERSION); printf("\r\n Enter HaaSEDUk1 factorytest model, Version : %s \r\n", image_version); int value = 0; int re_value = 0; int len = 32; if (0 != aos_kv_get("factory_test", &value, &len)) { if (0 == aos_kv_get("reboot_times", &re_value, &len)) { if (re_value++ < 3) { aos_kv_set("reboot_times", &re_value, len, 1); printf("reboot_times is avild, add it %d!\r\n", re_value); } else { goto normal_mode; } } else { re_value++; printf("reboot_times is not avild, create it %d!\r\n", re_value); aos_kv_set("reboot_times", &re_value, len, 1); } } factorytest_mode: printf("board_test entry here!\r\n"); board_test(); normal_mode: #endif #ifndef AOS_BINS application_start(kinit.argc, kinit.argv); /* jump to app entry */ #endif }
YifuLiu/AliOS-Things
solutions/eduk1_demo/maintask.c
C
apache-2.0
2,185
CPRE := @ ifeq ($(V),1) CPRE := VERB := --verbose endif MK_GENERATED_IMGS_PATH:=generated PRODUCT_BIN:=product .PHONY:startup startup: all all: @echo "Build Solution by $(BOARD) " $(CPRE) scons $(VERB) --board=$(BOARD) $(MULTITHREADS) $(MAKEFLAGS) @echo YoC SDK Done @echo [INFO] Create bin files # $(CPRE) $(PRODUCT_BIN) image $(MK_GENERATED_IMGS_PATH)/images.zip -i $(MK_GENERATED_IMGS_PATH)/data -l -p # $(CPRE) $(PRODUCT_BIN) image $(MK_GENERATED_IMGS_PATH)/images.zip -e $(MK_GENERATED_IMGS_PATH) -x .PHONY:flash flash: $(CPRE) $(PRODUCT_BIN) flash $(MK_GENERATED_IMGS_PATH)/images.zip -w prim .PHONY:flashall flashall: $(CPRE) $(PRODUCT_BIN) flash $(MK_GENERATED_IMGS_PATH)/images.zip -a sdk: $(CPRE) yoc sdk .PHONY:clean clean: $(CPRE) scons -c --board=$(BOARD) $(CPRE) find . -name "*.[od]" -delete $(CPRE) rm -rf aos_sdk aos.elf aos.map binary generated out
YifuLiu/AliOS-Things
solutions/flower_demo/Makefile
Makefile
apache-2.0
885
Import('defconfig') defconfig.library_yaml()
YifuLiu/AliOS-Things
solutions/flower_demo/SConscript
Python
apache-2.0
45
#! /bin/env python from aostools import Make # defconfig = Make(elf='yoc.elf', objcopy='generated/data/prim', objdump='yoc.asm') defconfig = Make(elf='aos.elf', objcopy='binary/flower_demo@haas100.bin') Export('defconfig') defconfig.build_components()
YifuLiu/AliOS-Things
solutions/flower_demo/SConstruct
Python
apache-2.0
256
/* * 这个例程演示了用SDK配置MQTT参数并建立连接, 之后创建2个线程 * * + 一个线程用于保活长连接 * + 一个线程用于接收消息, 并在有消息到达时进入默认的数据回调, 在连接状态变化时进入事件回调 * * 接着演示了在MQTT连接上进行属性上报, 事件上报, 以及处理收到的属性设置, 服务调用, 取消这些代码段落的注释即可观察运行效果 * * 需要用户关注或修改的部分, 已经用 TODO 在注释中标明 * */ #include <stdio.h> #include <string.h> #include <unistd.h> #include <aos/kernel.h> #include "aiot_state_api.h" #include "aiot_sysdep_api.h" #include "aiot_mqtt_api.h" #include "aiot_dm_api.h" #include "flower_app.h" /* 位于portfiles/aiot_port文件夹下的系统适配函数集合 */ extern aiot_sysdep_portfile_t g_aiot_sysdep_portfile; /* 位于external/ali_ca_cert.c中的服务器证书 */ extern const char *ali_ca_cert; static uint8_t g_mqtt_process_thread_running = 0; static uint8_t g_mqtt_recv_thread_running = 0; uint8_t mqtt_status = 0; void *g_dm_handle = NULL; /* TODO: 如果要关闭日志, 就把这个函数实现为空, 如果要减少日志, 可根据code选择不打印 * * 例如: [1577589489.033][LK-0317] mqtt_basic_demo&a13FN5TplKq * * 上面这条日志的code就是0317(十六进制), code值的定义见core/aiot_state_api.h * */ /* 日志回调函数, SDK的日志会从这里输出 */ int32_t demo_state_logcb(int32_t code, char *message) { printf("%s", message); return 0; } /* MQTT事件回调函数, 当网络连接/重连/断开时被触发, 事件定义见core/aiot_mqtt_api.h */ void demo_mqtt_event_handler(void *handle, const aiot_mqtt_event_t *event, void *userdata) { switch (event->type) { /* SDK因为用户调用了aiot_mqtt_connect()接口, 与mqtt服务器建立连接已成功 */ case AIOT_MQTTEVT_CONNECT: { printf("AIOT_MQTTEVT_CONNECT\n"); mqtt_status = 1; } break; /* SDK因为网络状况被动断连后, 自动发起重连已成功 */ case AIOT_MQTTEVT_RECONNECT: { printf("AIOT_MQTTEVT_RECONNECT\n"); mqtt_status = 1; } break; /* SDK因为网络的状况而被动断开了连接, network是底层读写失败, heartbeat是没有按预期得到服务端心跳应答 */ case AIOT_MQTTEVT_DISCONNECT: { char *cause = (event->data.disconnect == AIOT_MQTTDISCONNEVT_NETWORK_DISCONNECT) ? ("network disconnect") : ("heartbeat disconnect"); printf("AIOT_MQTTEVT_DISCONNECT: %s\n", cause); mqtt_status = 0; } break; default: { } } } /* 执行aiot_mqtt_process的线程, 包含心跳发送和QoS1消息重发 */ void *demo_mqtt_process_thread(void *args) { int32_t res = STATE_SUCCESS; while (g_mqtt_process_thread_running) { res = aiot_mqtt_process(args); if (res == STATE_USER_INPUT_EXEC_DISABLED) { break; } aos_msleep(1000); } return NULL; } /* 执行aiot_mqtt_recv的线程, 包含网络自动重连和从服务器收取MQTT消息 */ void *demo_mqtt_recv_thread(void *args) { int32_t res = STATE_SUCCESS; while (g_mqtt_recv_thread_running) { res = aiot_mqtt_recv(args); if (res < STATE_SUCCESS) { if (res == STATE_USER_INPUT_EXEC_DISABLED) { break; } aos_msleep(1000); } } return NULL; } /* 用户数据接收处理回调函数 */ static void demo_dm_recv_handler(void *dm_handle, const aiot_dm_recv_t *recv, void *userdata) { printf("demo_dm_recv_handler, type = %d\r\n", recv->type); switch (recv->type) { /* 属性上报, 事件上报, 获取期望属性值或者删除期望属性值的应答 */ case AIOT_DMRECV_GENERIC_REPLY: { printf("msg_id = %d, code = %d, data = %.*s, message = %.*s\r\n", recv->data.generic_reply.msg_id, recv->data.generic_reply.code, recv->data.generic_reply.data_len, recv->data.generic_reply.data, recv->data.generic_reply.message_len, recv->data.generic_reply.message); } break; /* 属性设置 */ case AIOT_DMRECV_PROPERTY_SET: { printf("msg_id = %ld, params = %.*s\r\n", (unsigned long)recv->data.property_set.msg_id, recv->data.property_set.params_len, recv->data.property_set.params); /* TODO: 以下代码演示如何对来自云平台的属性设置指令进行应答, 用户可取消注释查看演示效果 */ /* { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_PROPERTY_SET_REPLY; msg.data.property_set_reply.msg_id = recv->data.property_set.msg_id; msg.data.property_set_reply.code = 200; msg.data.property_set_reply.data = "{}"; int32_t res = aiot_dm_send(dm_handle, &msg); if (res < 0) { printf("aiot_dm_send failed\r\n"); } } */ } break; /* 异步服务调用 */ case AIOT_DMRECV_ASYNC_SERVICE_INVOKE: { printf("msg_id = %ld, service_id = %s, params = %.*s\r\n", (unsigned long)recv->data.async_service_invoke.msg_id, recv->data.async_service_invoke.service_id, recv->data.async_service_invoke.params_len, recv->data.async_service_invoke.params); /* TODO: 以下代码演示如何对来自云平台的异步服务调用进行应答, 用户可取消注释查看演示效果 * * 注意: 如果用户在回调函数外进行应答, 需要自行保存msg_id, 因为回调函数入参在退出回调函数后将被SDK销毁, 不可以再访问到 */ /* { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_ASYNC_SERVICE_REPLY; msg.data.async_service_reply.msg_id = recv->data.async_service_invoke.msg_id; msg.data.async_service_reply.code = 200; msg.data.async_service_reply.service_id = "ToggleLightSwitch"; msg.data.async_service_reply.data = "{\"dataA\": 20}"; int32_t res = aiot_dm_send(dm_handle, &msg); if (res < 0) { printf("aiot_dm_send failed\r\n"); } } */ } break; /* 同步服务调用 */ case AIOT_DMRECV_SYNC_SERVICE_INVOKE: { printf("msg_id = %ld, rrpc_id = %s, service_id = %s, params = %.*s\r\n", (unsigned long)recv->data.sync_service_invoke.msg_id, recv->data.sync_service_invoke.rrpc_id, recv->data.sync_service_invoke.service_id, recv->data.sync_service_invoke.params_len, recv->data.sync_service_invoke.params); /* TODO: 以下代码演示如何对来自云平台的同步服务调用进行应答, 用户可取消注释查看演示效果 * * 注意: 如果用户在回调函数外进行应答, 需要自行保存msg_id和rrpc_id字符串, 因为回调函数入参在退出回调函数后将被SDK销毁, 不可以再访问到 */ /* { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_SYNC_SERVICE_REPLY; msg.data.sync_service_reply.rrpc_id = recv->data.sync_service_invoke.rrpc_id; msg.data.sync_service_reply.msg_id = recv->data.sync_service_invoke.msg_id; msg.data.sync_service_reply.code = 200; msg.data.sync_service_reply.service_id = "SetLightSwitchTimer"; msg.data.sync_service_reply.data = "{}"; int32_t res = aiot_dm_send(dm_handle, &msg); if (res < 0) { printf("aiot_dm_send failed\r\n"); } } */ } break; /* 下行二进制数据 */ case AIOT_DMRECV_RAW_DATA: { printf("raw data len = %d\r\n", recv->data.raw_data.data_len); /* TODO: 以下代码演示如何发送二进制格式数据, 若使用需要有相应的数据透传脚本部署在云端 */ /* { aiot_dm_msg_t msg; uint8_t raw_data[] = {0x01, 0x02}; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_RAW_DATA; msg.data.raw_data.data = raw_data; msg.data.raw_data.data_len = sizeof(raw_data); aiot_dm_send(dm_handle, &msg); } */ } break; /* 二进制格式的同步服务调用, 比单纯的二进制数据消息多了个rrpc_id */ case AIOT_DMRECV_RAW_SYNC_SERVICE_INVOKE: { printf("raw sync service rrpc_id = %s, data_len = %d\r\n", recv->data.raw_service_invoke.rrpc_id, recv->data.raw_service_invoke.data_len); } break; default: break; } } /* 属性上报函数演示 */ int32_t demo_send_property_post(void *dm_handle, char *params) { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_PROPERTY_POST; msg.data.property_post.params = params; return aiot_dm_send(dm_handle, &msg); } /* 事件上报函数演示 */ int32_t demo_send_event_post(void *dm_handle, char *event_id, char *params) { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_EVENT_POST; msg.data.event_post.event_id = event_id; msg.data.event_post.params = params; return aiot_dm_send(dm_handle, &msg); } /* 演示了获取属性LightSwitch的期望值, 用户可将此函数加入到main函数中运行演示 */ int32_t demo_send_get_desred_requset(void *dm_handle) { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_GET_DESIRED; msg.data.get_desired.params = "[\"LightSwitch\"]"; return aiot_dm_send(dm_handle, &msg); } /* 演示了删除属性LightSwitch的期望值, 用户可将此函数加入到main函数中运行演示 */ int32_t demo_send_delete_desred_requset(void *dm_handle) { aiot_dm_msg_t msg; memset(&msg, 0, sizeof(aiot_dm_msg_t)); msg.type = AIOT_DMMSG_DELETE_DESIRED; msg.data.get_desired.params = "{\"LightSwitch\":{}}"; return aiot_dm_send(dm_handle, &msg); } int demo_main(int argc, char *argv[]) { int32_t res = STATE_SUCCESS; void *dm_handle = NULL; void *mqtt_handle = NULL; char *url = "iot-as-mqtt.cn-shanghai.aliyuncs.com"; /* 阿里云平台上海站点的域名后缀 */ char host[100] = {0}; /* 用这个数组拼接设备连接的云平台站点全地址, 规则是 ${productKey}.iot-as-mqtt.cn-shanghai.aliyuncs.com */ uint16_t port = 443; /* 无论设备是否使用TLS连接阿里云平台, 目的端口都是443 */ aiot_sysdep_network_cred_t cred; /* 安全凭据结构体, 如果要用TLS, 这个结构体中配置CA证书等参数 */ /* TODO: 替换为自己设备的三元组 */ char *product_key = "产品key"; char *device_name = "设备名"; char *device_secret = "设备密钥"; /* 配置SDK的底层依赖 */ aiot_sysdep_set_portfile(&g_aiot_sysdep_portfile); /* 配置SDK的日志输出 */ aiot_state_set_logcb(demo_state_logcb); /* 创建SDK的安全凭据, 用于建立TLS连接 */ memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t)); cred.option = AIOT_SYSDEP_NETWORK_CRED_SVRCERT_CA; /* 使用RSA证书校验MQTT服务端 */ cred.max_tls_fragment = 16384; /* 最大的分片长度为16K, 其它可选值还有4K, 2K, 1K, 0.5K */ cred.sni_enabled = 1; /* TLS建连时, 支持Server Name Indicator */ cred.x509_server_cert = ali_ca_cert; /* 用来验证MQTT服务端的RSA根证书 */ cred.x509_server_cert_len = strlen(ali_ca_cert); /* 用来验证MQTT服务端的RSA根证书长度 */ /* 创建1个MQTT客户端实例并内部初始化默认参数 */ mqtt_handle = aiot_mqtt_init(); if (mqtt_handle == NULL) { printf("aiot_mqtt_init failed\n"); return -1; } snprintf(host, 100, "%s.%s", product_key, url); /* 配置MQTT服务器地址 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_HOST, (void *)host); /* 配置MQTT服务器端口 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PORT, (void *)&port); /* 配置设备productKey */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PRODUCT_KEY, (void *)product_key); /* 配置设备deviceName */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_NAME, (void *)device_name); /* 配置设备deviceSecret */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_SECRET, (void *)device_secret); /* 配置网络连接的安全凭据, 上面已经创建好了 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_NETWORK_CRED, (void *)&cred); /* 配置MQTT事件回调函数 */ aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_EVENT_HANDLER, (void *)demo_mqtt_event_handler); /* 创建DATA-MODEL实例 */ dm_handle = aiot_dm_init(); g_dm_handle = dm_handle; if (dm_handle == NULL) { printf("aiot_dm_init failed"); return -1; } /* 配置MQTT实例句柄 */ aiot_dm_setopt(dm_handle, AIOT_DMOPT_MQTT_HANDLE, mqtt_handle); /* 配置消息接收处理回调函数 */ aiot_dm_setopt(dm_handle, AIOT_DMOPT_RECV_HANDLER, (void *)demo_dm_recv_handler); /* 与服务器建立MQTT连接 */ res = aiot_mqtt_connect(mqtt_handle); if (res < STATE_SUCCESS) { /* 尝试建立连接失败, 销毁MQTT实例, 回收资源 */ aiot_mqtt_deinit(&mqtt_handle); printf("aiot_mqtt_connect failed: -0x%04X\n", -res); return -1; } /* 创建一个单独的线程, 专用于执行aiot_mqtt_process, 它会自动发送心跳保活, 以及重发QoS1的未应答报文 */ g_mqtt_process_thread_running = 1; res = aos_task_new("demo_mqtt_process", demo_mqtt_process_thread, mqtt_handle, 4096); //res = pthread_create(&g_mqtt_process_thread, NULL, demo_mqtt_process_thread, mqtt_handle); if (res != 0) { printf("create demo_mqtt_process_thread failed: %d\n", res); return -1; } /* 创建一个单独的线程用于执行aiot_mqtt_recv, 它会循环收取服务器下发的MQTT消息, 并在断线时自动重连 */ g_mqtt_recv_thread_running = 1; res = aos_task_new("demo_mqtt_process", demo_mqtt_recv_thread, mqtt_handle, 4096); //res = pthread_create(&g_mqtt_recv_thread, NULL, demo_mqtt_recv_thread, mqtt_handle); if (res != 0) { printf("create demo_mqtt_recv_thread failed: %d\n", res); return -1; } /* 主循环进入休眠 */ while (1) { report_2_cloud(dm_handle); aos_msleep(3000); } /* 断开MQTT连接, 一般不会运行到这里 */ res = aiot_mqtt_disconnect(mqtt_handle); if (res < STATE_SUCCESS) { aiot_mqtt_deinit(&mqtt_handle); printf("aiot_mqtt_disconnect failed: -0x%04X\n", -res); return -1; } /* 销毁DATA-MODEL实例, 一般不会运行到这里 */ res = aiot_dm_deinit(&dm_handle); if (res < STATE_SUCCESS) { printf("aiot_dm_deinit failed: -0x%04X\n", -res); return -1; } /* 销毁MQTT实例, 一般不会运行到这里 */ res = aiot_mqtt_deinit(&mqtt_handle); if (res < STATE_SUCCESS) { printf("aiot_mqtt_deinit failed: -0x%04X\n", -res); return -1; } g_mqtt_process_thread_running = 0; g_mqtt_recv_thread_running = 0; return 0; }
YifuLiu/AliOS-Things
solutions/flower_demo/data_model_basic_demo.c
C
apache-2.0
16,368
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <aos/kernel.h> #include "ulog/ulog.h" #include "flower_app.h" #include "k_api.h" #if AOS_COMP_CLI #include "aos/cli.h" #endif #include <sys/ioctl.h> #include <vfsdev/gpio_dev.h> #include <drivers/char/u_device.h> #include <drivers/u_ld.h> #include "aos/vfs.h" #include "aos/hal/gpio.h" #include "hal_iomux_haas1000.h" extern uint32_t hal_fast_sys_timer_get(); extern uint32_t hal_cmu_get_crystal_freq(); #define CONFIG_FAST_SYSTICK_HZ (hal_cmu_get_crystal_freq() / 4) #define FAST_TICKS_TO_US(tick) ((uint32_t)(tick) * 10 / (CONFIG_FAST_SYSTICK_HZ / 1000 / 100)) #define DHT11_PIN HAL_IOMUX_PIN_P0_1 static int fd = 0; static uint8_t last_temp = 0,last_hum = 0; extern uint8_t mqtt_status; #if (RHINO_CONFIG_HW_COUNT > 0) void _udelay(unsigned long x) { unsigned long now,t; t = FAST_TICKS_TO_US(hal_fast_sys_timer_get()); now = t; while ((now - t) < x) { now = FAST_TICKS_TO_US(hal_fast_sys_timer_get()); } } void _msdelay(unsigned long x) { _udelay(x * 1000); } #else #error "RHINO_CONFIG_HW_COUNT should be configured to get us level delay" #endif // temp && humidity gpio set static void DHT11_GPIO_Set(unsigned char leve) { struct gpio_io_config config; config.id = DHT11_PIN; config.config = GPIO_IO_OUTPUT | GPIO_IO_OUTPUT_ODPU; if(leve == 1){ config.data = 1; } else if(leve == 0){ config.data = 0; } ioctl(fd, IOC_GPIO_SET, (unsigned long)&config); } static uint32_t DHT11_GPIO_Get(void) { struct gpio_io_config config; int ret = 0xff; config.id = DHT11_PIN; config.config = GPIO_IO_INPUT | GPIO_IO_INPUT_PU; config.data = 0; ret = ioctl(fd, IOC_GPIO_GET, (unsigned long)&config); return ret; } //复位DHT11 void DHT11_Reset(void) { DHT11_GPIO_Set(0); _msdelay(20); DHT11_GPIO_Set(1); _udelay(30); } uint8_t DHT11_IsOnline(void) { uint8_t retry = 0; //DHT11会拉低40~80us while (DHT11_GPIO_Get() && retry < 100){ retry ++; _udelay(1); } if(retry >= 100){ LOGE("APP", "DHT Pin High!\n"); return 1; } else{ retry = 0; } //DHT11拉低后会再次拉高40~80us while (!DHT11_GPIO_Get() && retry < 100){ retry ++; _udelay(1); } if(retry >= 100){ LOGE("APP", "DHT Pin Low!\n"); return 1; } return 0; } uint8_t DHT11_ReadBit(void) { uint8_t retry = 0; while(DHT11_GPIO_Get() && retry < 100){ retry ++; _udelay(1); } retry = 0; while(!DHT11_GPIO_Get() && retry < 100){ retry ++; _udelay(1); } _udelay(40);//等待40us if(DHT11_GPIO_Get()){ return 1; } else { return 0; } } uint8_t DHT11_ReadByte(void) { uint8_t i,dat; dat = 0; for (i = 0; i < 8; i ++) { dat <<= 1; dat |= DHT11_ReadBit(); } return dat; } uint8_t DHT11_Read_Data(uint8_t *temp,uint8_t *humi) { uint8_t buf[5]; uint8_t i; DHT11_Reset(); if(DHT11_IsOnline() == 0){ //读取40位数据 for(i = 0; i < 5; i ++){ buf[i] = DHT11_ReadByte(); } if((buf[0] + buf[1] + buf[2] + buf[3]) == buf[4]){ *humi = buf[0]; *temp = buf[2]; } } else { LOGE("APP", "DHT is not online!\n"); return 1; } return 0; } void report_2_cloud(void *dm_handle) { uint8_t temp =0,humidity=0,d_flag = 0; char property_payload[30] = {0}; if(mqtt_status == 0){ printf("mqtt status :%d %p\r\n",mqtt_status,dm_handle); return; } d_flag = DHT11_Read_Data(&temp,&humidity); printf("temp ->%d humidity->%d --%d\n",temp,humidity,d_flag); if((last_temp != temp)&&(!d_flag)){ snprintf(property_payload, sizeof(property_payload), "{\"Temperature\": %d}", temp); printf("report:%s\r\n",property_payload); demo_send_property_post(dm_handle, property_payload); last_temp = temp; } if((last_hum != humidity)&&(!d_flag)){ snprintf(property_payload, sizeof(property_payload), "{\"Humidity\": %d}", humidity); printf("report:%s\r\n",property_payload); demo_send_property_post(dm_handle, property_payload); last_hum = humidity; } } static void handle_temp_cmd(char *pwbuf, int blen, int argc, char **argv) { uint8_t temp =0,humidity=0; if(0 == strcmp(argv[1],"0")){ DHT11_GPIO_Set(0); } else if(0 == strcmp(argv[1],"1")){ DHT11_GPIO_Set(1); } else if(0 == strcmp(argv[1],"2")){ DHT11_Reset(); } else if(0 == strcmp(argv[1],"3")){ DHT11_Read_Data(&temp,&humidity); LOGI("APP", "temp ->%d humidity->%d\n",temp,humidity); } } #if AOS_COMP_CLI static struct cli_command temp_cmd = { .name = "temp", .help = "temp [read]", .function = handle_temp_cmd }; #endif /* AOS_COMP_CLI */ int flower_gpio_init(void) { gpio_dev_t temp_gpio; temp_gpio.port = DHT11_PIN; temp_gpio.config = OUTPUT_OPEN_DRAIN_PULL_UP; hal_gpio_init(&temp_gpio); fd = open("/dev/gpio", 0); printf("open gpio %s, fd:%d\r\n", fd >= 0 ? "success" : "fail", fd); DHT11_GPIO_Set(1); DHT11_Reset(); #if AOS_COMP_CLI aos_cli_register_command(&temp_cmd); #endif /* AOS_COMP_CLI */ return 0; }
YifuLiu/AliOS-Things
solutions/flower_demo/flower_app.c
C
apache-2.0
5,473
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef FLOWER_APP_H #define FLOWER_APP_H int flower_gpio_init(void); void report_2_cloud(void *dm_handle); #endif
YifuLiu/AliOS-Things
solutions/flower_demo/flower_app.h
C
apache-2.0
183
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ /** * @file main.c * * This file includes the entry code of link sdk related demo * */ #include <string.h> #include <stdio.h> #include <aos/kernel.h> #include "ulog/ulog.h" #include "netmgr.h" #include <uservice/uservice.h> #include <uservice/eventid.h> #include "flower_app.h" extern int demo_main(int argc, char *argv[]); extern void *g_dm_handle; static int _ip_got_finished = 0; static void entry_func(void *data) { demo_main(0 , NULL); } static void wifi_event_cb(uint32_t event_id, const void *param, void *context) { if (event_id != EVENT_NETMGR_DHCP_SUCCESS) { return; } if(_ip_got_finished != 0) { return; } _ip_got_finished = 1; aos_task_new("link_dmeo", entry_func, NULL, 6*1024); } int application_start(int argc, char *argv[]) { aos_set_log_level(AOS_LL_DEBUG); event_service_init(NULL); netmgr_service_init(NULL); /*enable network auto reconnect*/ netmgr_set_auto_reconnect(NULL, true); /*enable auto save wifi config*/ netmgr_wifi_set_auto_save_ap(true); event_subscribe(EVENT_NETMGR_DHCP_SUCCESS, wifi_event_cb, NULL); flower_gpio_init(); while(1) { aos_msleep(5000); }; return 0; }
YifuLiu/AliOS-Things
solutions/flower_demo/main.c
C
apache-2.0
1,281
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <aos/kernel.h> #include "aos/init.h" #include "board.h" #include <k_api.h> #ifndef AOS_BINS extern int application_start(int argc, char *argv[]); #endif /* If board have no component for example board_xx_init, it indicates that this app does not support this board. Set the correspondence in file platform\board\aaboard_demo\ucube.py. */ extern void board_tick_init(void); extern void board_stduart_init(void); extern void board_dma_init(void); extern void board_gpio_init(void); extern void board_kinit_init(kinit_t* init_args); /* For user config kinit.argc = 0; kinit.argv = NULL; kinit.cli_enable = 1; */ static kinit_t kinit = {0, NULL, 1}; /** * @brief Board Initialization Function * @param None * @retval None */ void board_init(void) { board_tick_init(); board_stduart_init(); board_dma_init(); board_gpio_init(); } void aos_maintask(void* arg) { board_init(); board_kinit_init(&kinit); aos_components_init(&kinit); #ifndef AOS_BINS application_start(kinit.argc, kinit.argv); /* jump to app entry */ #endif }
YifuLiu/AliOS-Things
solutions/flower_demo/maintask.c
C
apache-2.0
1,192
CPRE := @ ifeq ($(V),1) CPRE := VERB := --verbose endif .PHONY:startup startup: all all: @echo "Build Solution by $(BOARD) " $(CPRE) scons $(VERB) --board=$(BOARD) $(MAKEFLAGS) -j4 @echo AOS SDK Done sdk: $(CPRE) aos sdk .PHONY:clean clean: $(CPRE) scons -c --board=$(BOARD) ifeq ($(OS), Windows_NT) $(CPRE) if exist aos_sdk rmdir /s /q aos_sdk $(CPRE) if exist binary rmdir /s /q binary $(CPRE) if exist out rmdir /s /q out $(CPRE) if exist aos.elf del /f /q aos.elf $(CPRE) if exist aos.map del /f /q aos.map else $(CPRE) rm -rf aos_sdk binary out aos.elf aos.map endif
YifuLiu/AliOS-Things
solutions/genie_mesh_demo/Makefile
Makefile
apache-2.0
587
#! /bin/env python from aostools import Make # default elf is out/<solution>@<board>.elf, and default objcopy is out/<solution>@<board>.bin # defconfig = Make(elf='out/<solution>@<board>.elf', objcopy='out/<solution>@<board>.bin') defconfig = Make() Export('defconfig') defconfig.build_components()
YifuLiu/AliOS-Things
solutions/genie_mesh_demo/SConstruct
Python
apache-2.0
303
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <aos/kernel.h> #include "aos/init.h" #include "board.h" #include <k_api.h> #ifndef AOS_BINS extern int application_start(int argc, char *argv[]); #endif /* If board have no component for example board_xx_init, it indicates that this app does not support this board. Set the correspondence in file platform\board\aaboard_demo\ucube.py. */ extern void board_tick_init(void); extern void board_stduart_init(void); extern void board_dma_init(void); extern void board_gpio_init(void); extern void board_kinit_init(kinit_t *init_args); /* For user config kinit.argc = 0; kinit.argv = NULL; kinit.cli_enable = 1; */ static kinit_t kinit = { 0, NULL, 1 }; /** * @brief Board Initialization Function * @param None * @retval None */ void board_init(void) { board_tick_init(); board_stduart_init(); board_dma_init(); board_gpio_init(); } void aos_maintask(void *arg) { board_init(); board_kinit_init(&kinit); aos_components_init(&kinit); #ifndef AOS_BINS application_start(kinit.argc, kinit.argv); /* jump to app entry */ #endif }
YifuLiu/AliOS-Things
solutions/genie_mesh_demo/app/src/maintask.c
C
apache-2.0
1,192
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #include "common/log.h" #include <stdio.h> #include <string.h> #include <ctype.h> // #include <aos/aos.h> #include <aos/kernel.h> // #include <misc/printk.h> // #include <misc/byteorder.h> // #include <aos/hal/gpio.h> // #include <aos/hal/pwm.h> // #include <bluetooth.h> // #include <soc.h> #include <api/mesh.h> #include "genie_service.h" #include "light.h" #include "light_driver.h" static light_param_t light_param; static sig_model_element_state_t light_elem_stat[ELEMENT_NUM]; static sig_model_powerup_t light_powerup[ELEMENT_NUM]; #ifdef CONFIG_BT_MESH_CFG_CLI static struct bt_mesh_cfg_cli cfg_cli = {}; #endif static struct bt_mesh_model primary_element[] = { MESH_MODEL_CFG_SRV_NULL(), MESH_MODEL_HEALTH_SRV_NULL(), #ifdef CONFIG_BT_MESH_CFG_CLI BT_MESH_MODEL_CFG_CLI(&cfg_cli), #endif MESH_MODEL_GEN_ONOFF_SRV(&light_elem_stat[0]), MESH_MODEL_LIGHTNESS_SRV(&light_elem_stat[0]), MESH_MODEL_CTL_SRV(&light_elem_stat[0]), MESH_MODEL_SCENE_SRV(&light_elem_stat[0]), }; static struct bt_mesh_model primary_vendor_element[] = { MESH_MODEL_VENDOR_SRV(&light_elem_stat[0]), }; struct bt_mesh_elem light_elements[] = { BT_MESH_ELEM(0, primary_element, primary_vendor_element, GENIE_ADDR_LIGHT), }; #ifdef CONFIG_GENIE_OTA bool genie_sal_ota_is_allow_reboot(void) { // the device will reboot when it is off if (light_elem_stat[0].state.onoff[TYPE_PRESENT] == 0) { // save light para, always off light_powerup[0].last_onoff = 0; genie_storage_write_userdata(GFI_MESH_POWERUP, (uint8_t *)light_powerup, sizeof(light_powerup)); LIGHT_DBG("Allow to reboot!"); return true; } LIGHT_DBG("light is no so no reboot!"); return false; } #endif static void _mesh_delay_timer_cb(void *p_timer, void *p_arg) { sig_model_element_state_t *p_elem = (sig_model_element_state_t *)p_arg; #ifdef CONFIG_MESH_MODEL_TRANS sig_model_transition_timer_stop(p_elem); #endif sig_model_event(SIG_MODEL_EVT_DELAY_END, p_arg); } #ifdef CONFIG_MESH_MODEL_TRANS static void _mesh_trans_timer_cycle(void *p_timer, void *p_arg) { sig_model_element_state_t *p_elem = (sig_model_element_state_t *)p_arg; sig_model_state_t *p_state = &p_elem->state; sig_model_transition_timer_stop(p_elem); // do cycle sig_model_event(SIG_MODEL_EVT_TRANS_CYCLE, p_arg); // BT_DBG(">>>>>%d %d", (u32_t)cur_time, (u32_t)p_elem->state.trans_end_time); if (p_state->trans == 0) { sig_model_event(SIG_MODEL_EVT_TRANS_END, p_arg); } else { k_timer_start(&p_state->trans_timer, SIG_MODEL_TRANSITION_INTERVAL); } } #endif void light_elem_state_init(void) { uint8_t index = 0; genie_storage_status_e ret; memset(light_elem_stat, 0, sizeof(light_elem_stat)); // load light param ret = genie_storage_read_userdata(GFI_MESH_POWERUP, (uint8_t *)light_powerup, sizeof(light_powerup)); for (index = 0; index < ELEMENT_NUM; index++) { light_elem_stat[index].element_id = index; if (ret == GENIE_STORAGE_SUCCESS) { // Use saved data memcpy(&light_elem_stat[index].powerup, &light_powerup[index], sizeof(sig_model_powerup_t)); } else { // Use default value #ifdef CONFIG_MESH_MODEL_GEN_ONOFF_SRV light_elem_stat[index].powerup.last_onoff = GEN_ONOFF_DEFAULT; #endif #ifdef CONFIG_MESH_MODEL_LIGHTNESS_SRV light_elem_stat[index].powerup.last_lightness = LIGHTNESS_DEFAULT; #endif #ifdef CONFIG_MESH_MODEL_CTL_SRV light_elem_stat[index].powerup.last_color_temperature = COLOR_TEMPERATURE_DEFAULT; #endif #ifdef CONFIG_MESH_MODEL_SCENE_SRV light_elem_stat[index].powerup.last_scene = SCENE_DEFAULT; #endif } #ifdef CONFIG_MESH_MODEL_GEN_ONOFF_SRV light_elem_stat[index].state.onoff[TYPE_PRESENT] = 0; light_elem_stat[index].state.onoff[TYPE_TARGET] = light_elem_stat[index].powerup.last_onoff; #endif #ifdef CONFIG_MESH_MODEL_LIGHTNESS_SRV light_elem_stat[index].state.lightness[TYPE_PRESENT] = 0; light_elem_stat[index].state.lightness[TYPE_TARGET] = light_elem_stat[index].powerup.last_lightness; #endif #ifdef CONFIG_MESH_MODEL_CTL_SRV light_elem_stat[index].state.color_temperature[TYPE_PRESENT] = COLOR_TEMPERATURE_MIN; light_elem_stat[index].state.color_temperature[TYPE_TARGET] = light_elem_stat[index].powerup.last_color_temperature; #endif #ifdef CONFIG_MESH_MODEL_SCENE_SRV light_elem_stat[index].state.scene[TYPE_PRESENT] = GENIE_SCENE_NORMAL; light_elem_stat[index].state.scene[TYPE_TARGET] = light_elem_stat[index].powerup.last_scene; #endif #ifdef CONFIG_MESH_MODEL_TRANS k_timer_init(&light_elem_stat[index].state.delay_timer, _mesh_delay_timer_cb, &light_elem_stat[index]); k_timer_init(&light_elem_stat[index].state.trans_timer, _mesh_trans_timer_cycle, &light_elem_stat[index]); light_elem_stat[index].state.trans = TRANSITION_DEFAULT_VALUE; light_elem_stat[index].state.delay = DELAY_DEFAULT_VAULE; if (light_elem_stat[index].state.trans) { light_elem_stat[index].state.trans_start_time = k_uptime_get() + light_elem_stat[index].state.delay * DELAY_TIME_UNIT; light_elem_stat[index].state.trans_end_time = light_elem_stat[index].state.trans_start_time + sig_model_transition_get_transition_time(light_elem_stat[index].state.trans); } #ifdef CONFIG_MESH_MODEL_GEN_ONOFF_SRV if (light_elem_stat[index].state.onoff[TYPE_TARGET] == 1) { // light on sig_model_event(SIG_MODEL_EVT_DELAY_START, &light_elem_stat[index]); } #endif #else // No CONFIG_MESH_MODEL_TRANS #ifdef CONFIG_MESH_MODEL_GEN_ONOFF_SRV light_elem_stat[index].state.onoff[TYPE_PRESENT] = light_elem_stat[index].state.onoff[TYPE_TARGET]; if (light_elem_stat[index].state.onoff[TYPE_TARGET] == 1) { // light on // light_driver_update(1, light_elem_stat[index].state.lightness[TYPE_TARGET], light_elem_stat[index].state.color_temperature[TYPE_TARGET]); } #endif #ifdef CONFIG_MESH_MODEL_LIGHTNESS_SRV light_elem_stat[index].state.lightness[TYPE_PRESENT] = light_elem_stat[index].state.lightness[TYPE_TARGET]; #endif #ifdef CONFIG_MESH_MODEL_CTL_SRV light_elem_stat[index].state.color_temperature[TYPE_PRESENT] = light_elem_stat[index].state.color_temperature[TYPE_TARGET]; #endif #ifdef CONFIG_MESH_MODEL_SCENE_SRV light_elem_stat[index].state.scene[TYPE_PRESENT] = light_elem_stat[index].state.scene[TYPE_TARGET]; #endif #endif } } #ifdef MESH_MODEL_VENDOR_TIMER static void light_ctl_handle_order_msg(vendor_attr_data_t *attr_data) { GENIE_LOG_INFO("type:%04x data:%04x\r\n", attr_data->type, attr_data->para); if (attr_data->type == ATTR_TYPE_GENERIC_ONOFF) { #ifdef CONFIG_MESH_MODEL_GEN_ONOFF_SRV light_elem_stat[0].state.onoff[TYPE_TARGET] = attr_data->para; if (light_elem_stat[0].state.onoff[TYPE_PRESENT] != light_elem_stat[0].state.onoff[TYPE_TARGET]) { sig_model_event(SIG_MODEL_EVT_DELAY_START, &light_elem_stat[0]); } #endif } } #endif static void light_param_reset(void) { genie_storage_delete_userdata(GFI_MESH_POWERUP); } static void light_save_state(sig_model_element_state_t *p_elem) { uint8_t *p_read = NULL; if (p_elem->state.lightness[TYPE_PRESENT] != 0) { p_elem->powerup.last_lightness = p_elem->state.lightness[TYPE_PRESENT]; light_powerup[p_elem->element_id].last_lightness = p_elem->state.lightness[TYPE_PRESENT]; } p_elem->powerup.last_color_temperature = p_elem->state.color_temperature[TYPE_PRESENT]; light_powerup[p_elem->element_id].last_color_temperature = p_elem->state.color_temperature[TYPE_PRESENT]; // always on p_elem->powerup.last_onoff = p_elem->state.onoff[TYPE_PRESENT]; light_powerup[p_elem->element_id].last_onoff = p_elem->state.onoff[TYPE_PRESENT]; p_read = aos_malloc(sizeof(light_powerup)); if (!p_read) { GENIE_LOG_WARN("no mem"); return; } genie_storage_read_userdata(GFI_MESH_POWERUP, p_read, sizeof(light_powerup)); if (memcmp(light_powerup, p_read, sizeof(light_powerup))) { LIGHT_DBG("save %d %d %d", light_powerup[0].last_onoff, light_powerup[0].last_lightness, light_powerup[0].last_color_temperature); genie_storage_write_userdata(GFI_MESH_POWERUP, (uint8_t *)light_powerup, sizeof(light_powerup)); } aos_free(p_read); #ifdef CONFIG_GENIE_OTA if (light_powerup[0].last_onoff == 0 && genie_ota_is_ready() == 1) { // Means have ota, wait for reboot while light off GENIE_LOG_INFO("reboot by ota"); aos_reboot(); } #endif } static void light_update(sig_model_element_state_t *p_elem) { static uint8_t last_onoff = 0; static uint16_t last_lightness = 0; static uint16_t last_temperature = 0; uint8_t onoff = p_elem->state.onoff[TYPE_PRESENT]; uint16_t lightness = p_elem->state.lightness[TYPE_PRESENT]; uint16_t temperature = p_elem->state.color_temperature[TYPE_PRESENT]; if (last_onoff != onoff || last_lightness != lightness || last_temperature != temperature) { last_onoff = onoff; last_lightness = lightness; last_temperature = temperature; // LIGHT_DBG("%d,%d,%d", onoff, lightness, temperature); // light_driver_update(onoff, lightness, temperature); } } void _cal_flash_next_step(uint32_t delta_time) { uint16_t lightness_end; if (delta_time < 1000) { lightness_end = light_param.target_lightness; light_param.present_color_temperature = light_param.target_color_temperature; } else { lightness_end = light_param.lightness_start; delta_time %= 1000; } if (delta_time > LED_BLINK_ON_TIME) { delta_time -= LED_BLINK_ON_TIME; light_param.present_lightness = light_param.lightness_start * delta_time / LED_BLINK_OFF_TIME; } else { light_param.present_lightness = lightness_end * (LED_BLINK_ON_TIME - delta_time) / LED_BLINK_ON_TIME; } // LIGHT_DBG("delta %d, lightness %04x", delta_time, light_param.present_lightness); } static void _led_blink_timer_cb(void *p_timer, void *p_arg) { uint32_t cur_time = k_uptime_get(); if (cur_time >= light_param.color_temperature_end) { // light_driver_update(1, light_param.target_lightness, light_param.target_color_temperature); } else { _cal_flash_next_step(light_param.color_temperature_end - cur_time); // light_driver_update(1, light_param.present_lightness, light_param.present_color_temperature); k_timer_start(&light_param.led_blink_timer, SIG_MODEL_TRANSITION_INTERVAL); } } static void light_led_blink(uint8_t times, uint8_t reset) { if (light_elem_stat[0].state.onoff[TYPE_PRESENT] == 1) { if (light_elem_stat[0].state.lightness[TYPE_PRESENT]) { light_param.lightness_start = light_param.present_lightness = light_elem_stat[0].state.lightness[TYPE_PRESENT]; } else { light_param.lightness_start = light_param.present_lightness = LIGHTNESS_DEFAULT; } if (light_elem_stat[0].state.color_temperature[TYPE_PRESENT]) { light_param.present_color_temperature = light_elem_stat[0].state.color_temperature[TYPE_PRESENT]; } else { light_param.present_color_temperature = COLOR_TEMPERATURE_DEFAULT; } if (reset) { light_param.target_lightness = LIGHTNESS_DEFAULT; light_param.target_color_temperature = COLOR_TEMPERATURE_DEFAULT; } else { light_param.target_lightness = light_param.present_lightness; light_param.target_color_temperature = light_param.present_color_temperature; } light_param.color_temperature_end = k_uptime_get() + times * LED_BLINK_PERIOD; } else { if (light_elem_stat[0].powerup.last_lightness && !reset) { light_param.lightness_start = light_param.target_lightness = light_elem_stat[0].powerup.last_lightness; } else { light_param.lightness_start = light_param.target_lightness = LIGHTNESS_DEFAULT; } light_param.present_lightness = 0; if (light_elem_stat[0].powerup.last_color_temperature) { light_param.present_color_temperature = light_elem_stat[0].powerup.last_color_temperature; } else { light_param.present_color_temperature = COLOR_TEMPERATURE_DEFAULT; } if (reset) { light_param.target_color_temperature = COLOR_TEMPERATURE_DEFAULT; } else { light_param.target_color_temperature = light_param.present_color_temperature; } light_param.color_temperature_end = k_uptime_get() + times * LED_BLINK_PERIOD - LED_BLINK_OFF_TIME; } // LIGHT_DBG("%d (%d-%d) tar %04x", times, k_uptime_get(), light_param.color_temperature_end, light_param.target_lightness); k_timer_start(&light_param.led_blink_timer, SIG_MODEL_TRANSITION_INTERVAL); } static void light_report_poweron_state(sig_model_element_state_t *p_elem) { uint16_t index = 0; uint8_t payload[20]; genie_transport_payload_param_t transport_payload_param; #ifdef CONFIG_MESH_MODEL_GEN_ONOFF_SRV payload[index++] = ATTR_TYPE_GENERIC_ONOFF & 0xff; payload[index++] = (ATTR_TYPE_GENERIC_ONOFF >> 8) & 0xff; payload[index++] = p_elem->state.onoff[TYPE_TARGET]; #endif #ifdef CONFIG_MESH_MODEL_LIGHTNESS_SRV payload[index++] = ATTR_TYPE_LIGHTNESS & 0xff; payload[index++] = (ATTR_TYPE_LIGHTNESS >> 8) & 0xff; payload[index++] = p_elem->state.lightness[TYPE_TARGET] & 0xff; payload[index++] = (p_elem->state.lightness[TYPE_TARGET] >> 8) & 0xff; #endif #ifdef CONFIG_MESH_MODEL_CTL_SRV payload[index++] = ATTR_TYPE_COLOR_TEMPERATURE & 0xff; payload[index++] = (ATTR_TYPE_COLOR_TEMPERATURE >> 8) & 0xff; payload[index++] = p_elem->state.color_temperature[TYPE_TARGET] & 0xff; payload[index++] = (p_elem->state.color_temperature[TYPE_TARGET] >> 8) & 0xff; #endif #ifdef CONFIG_MESH_MODEL_SCENE_SRV payload[index++] = ATTR_TYPE_SENCE & 0xff; payload[index++] = (ATTR_TYPE_SENCE >> 8) & 0xff; payload[index++] = p_elem->state.scene[TYPE_TARGET] & 0xff; payload[index++] = (p_elem->state.scene[TYPE_TARGET] >> 8) & 0xff; #endif memset(&transport_payload_param, 0, sizeof(genie_transport_payload_param_t)); transport_payload_param.opid = VENDOR_OP_ATTR_INDICATE; transport_payload_param.p_payload = payload; transport_payload_param.payload_len = index; transport_payload_param.retry_cnt = GENIE_TRANSPORT_DEFAULT_RETRY_COUNT; genie_transport_send_payload(&transport_payload_param); } static void light_ctl_event_handler(genie_event_e event, void *p_arg) { switch (event) { case GENIE_EVT_SW_RESET: { light_param_reset(); // light_led_blink(3, 1); } break; case GENIE_EVT_MESH_READY: { // User can report data to cloud at here GENIE_LOG_INFO("User report data\n"); light_report_poweron_state(&light_elem_stat[0]); } break; case GENIE_EVT_SDK_MESH_PROV_SUCCESS: { GENIE_LOG_INFO("Mesh Prov success\n"); light_blink(); // light_led_blink(3, 0); } break; #ifdef CONFIG_MESH_MODEL_TRANS case GENIE_EVT_USER_TRANS_CYCLE: #endif case GENIE_EVT_USER_ACTION_DONE: { sig_model_element_state_t *p_elem = (sig_model_element_state_t *)p_arg; light_update(p_elem); if (event == GENIE_EVT_USER_ACTION_DONE) { light_save_state(p_elem); } } break; case GENIE_EVT_SIG_MODEL_MSG: { sig_model_msg *p_msg = (sig_model_msg *)p_arg; if (p_msg) { GENIE_LOG_INFO("SIG mesg ElemID(%d) in %s\n", p_msg->element_id, __func__); if (p_msg->opcode == 0x8202) { if (p_msg->data[0] == 0x00) { light_set(0); GENIE_LOG_INFO("rec SIG mesg: turn off cmd in ElemID(%d)\n", p_msg->element_id); } else if (p_msg->data[0] == 0x01) { light_set(1); GENIE_LOG_INFO("rec SIG mesg: turn on cmd in ElemID(%d)\n", p_msg->element_id); } } } } break; case GENIE_EVT_VENDOR_MODEL_MSG: { genie_transport_model_param_t *p_msg = (genie_transport_model_param_t *)p_arg; if (p_msg && p_msg->p_model && p_msg->p_model->user_data) { sig_model_element_state_t *p_elem_state = (sig_model_element_state_t *)p_msg->p_model->user_data; GENIE_LOG_INFO("ElemID(%d) TID(%02X)\n", p_elem_state->element_id, p_msg->tid); (void)p_elem_state; } } break; #ifdef CONIFG_GENIE_MESH_USER_CMD case GENIE_EVT_DOWN_MSG: { genie_down_msg_t *p_msg = (genie_down_msg_t *)p_arg; // User handle this msg,such as send to MCU // if (p_msg) { // } } break; #endif #ifdef MESH_MODEL_VENDOR_TIMER case GENIE_EVT_TIMEOUT: { vendor_attr_data_t *pdata = (vendor_attr_data_t *)p_arg; // User handle vendor timeout event at here if (pdata) { light_ctl_handle_order_msg(pdata); } } break; #endif default: break; } } #ifdef CONFIG_PM_SLEEP static void light_ctl_lpm_cb(genie_lpm_wakeup_reason_e reason, genie_lpm_status_e status, void *args) { if (status == STATUS_WAKEUP) { GENIE_LOG_INFO("wakeup by %s", (reason == WAKEUP_BY_IO) ? "io" : "timer"); } else { GENIE_LOG_INFO("sleep"); } } #endif static void light_init(void) { light_driver_init(); light_set(0); light_elem_state_init(); k_timer_init(&light_param.led_blink_timer, _led_blink_timer_cb, NULL); } int application_start(int argc, char **argv) { genie_service_ctx_t context; aos_set_log_level(LOG_INFO); GENIE_LOG_INFO("BTIME:%s\n", __DATE__ "," __TIME__); printf("enter %s:%d\n", __func__, __LINE__); light_init(); memset(&context, 0, sizeof(genie_service_ctx_t)); context.prov_timeout = MESH_PBADV_TIME; context.event_cb = light_ctl_event_handler; context.p_mesh_elem = light_elements; context.mesh_elem_counts = sizeof(light_elements) / sizeof(struct bt_mesh_elem); #ifdef CONFIG_PM_SLEEP context.lpm_conf.is_auto_enable = 1; context.lpm_conf.lpm_wakeup_io = 14; context.lpm_conf.genie_lpm_cb = light_ctl_lpm_cb; // User can config sleep time and wakeup time when not config GLP context.lpm_conf.sleep_ms = 1000; context.lpm_conf.wakeup_ms = 30; #endif genie_service_init(&context); #ifdef CONFIG_BT_MESH_SHELL extern void cli_reg_cmd_blemesh(void); cli_reg_cmd_blemesh(); #endif // aos_loop_run(); return 0; }
YifuLiu/AliOS-Things
solutions/genie_mesh_demo/light_ctl/light.c
C
apache-2.0
19,040
#ifndef __LIGHT_H__ #define __LIGHT_H__ #ifndef CONFIG_INFO_DISABLE #define LIGHT_DBG(fmt, ...) printf("[%s]" fmt "\n", __func__, ##__VA_ARGS__) #else #define LIGHT_DBG(fmt, ...) #endif #define LED_BLINK_PERIOD 1000 #define LED_BLINK_ON_TIME 600 #define LED_BLINK_OFF_TIME 400 /* unprovision device beacon adv time : 10 minutes*/ #define MESH_PBADV_TIME (600 * 1000) #define MESH_ELEM_COUNT 1 #define ELEMENT_NUM MESH_ELEM_COUNT typedef struct { struct k_timer led_blink_timer; uint16_t present_color_temperature; uint16_t target_color_temperature; uint16_t lightness_start; uint16_t present_lightness; uint16_t target_lightness; uint32_t color_temperature_end; } light_param_t; #endif
YifuLiu/AliOS-Things
solutions/genie_mesh_demo/light_ctl/light.h
C
apache-2.0
720
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/init.h" #include "board.h" #include <aos/errno.h> #include <aos/kernel.h> #include <aos/gpioc.h> #include <k_api.h> #include <stdio.h> #include <stdlib.h> #include "light_driver.h" // PA_28 #define RED_LED (28) // PB_4 #define GREEN_LED (4) // PB_7 #define BLUE_LED (7) void light_driver_init(void) { aos_gpioc_ref_t gpioc; uint32_t mode; aos_status_t r; r = aos_gpioc_get(&gpioc, 0); if (r) { printf("aos_gpioc_get failed %d\r\n", (int)r); return; } mode = AOS_GPIO_DIR_OUTPUT; mode |= AOS_GPIO_OUTPUT_CFG_PP; mode |= AOS_GPIO_OUTPUT_INIT_LOW; r = aos_gpioc_set_mode(&gpioc, RED_LED, mode); if (r) { printf("aos_gpioc_set_mode failed %d\r\n", (int)r); aos_gpioc_put(&gpioc); return; } r = aos_gpioc_get(&gpioc, 1); if (r) { printf("aos_gpioc_get failed %d\r\n", (int)r); return; } mode = AOS_GPIO_DIR_OUTPUT; mode |= AOS_GPIO_OUTPUT_CFG_PP; mode |= AOS_GPIO_OUTPUT_INIT_LOW; r = aos_gpioc_set_mode(&gpioc, GREEN_LED, mode); if (r) { printf("aos_gpioc_set_mode failed %d\r\n", (int)r); aos_gpioc_put(&gpioc); return; } r = aos_gpioc_set_mode(&gpioc, BLUE_LED, mode); if (r) { printf("aos_gpioc_set_mode failed %d\r\n", (int)r); aos_gpioc_put(&gpioc); return; } } void light_set(uint8_t onoff) { aos_gpioc_ref_t gpioc; aos_status_t r; r = aos_gpioc_get(&gpioc, 0); if (r) { printf("aos_gpioc_get failed %d\r\n", (int)r); return; } r = aos_gpioc_set_value(&gpioc, RED_LED, !onoff); r = aos_gpioc_get(&gpioc, 1); if (r) { printf("aos_gpioc_get failed %d\r\n", (int)r); return; } r = aos_gpioc_set_value(&gpioc, GREEN_LED, !onoff); r = aos_gpioc_set_value(&gpioc, BLUE_LED, !onoff); printf("aos_gpioc_set_value %d returned %d\r\n", onoff, (int)r); } void light_blink(void) { int out_val = 0; for (int i = 6; i > 0; i--) { light_set(out_val); out_val = !out_val; aos_msleep(500); } }
YifuLiu/AliOS-Things
solutions/genie_mesh_demo/light_ctl/light_driver.c
C
apache-2.0
2,187
#ifndef __LIGHT_DRIVER_H__ #define __LIGHT_DRIVER_H__ // #define WARM_PIN 24 //warm led // #define COLD_PIN 20 //cold led // #define COLD_PORT_NUM 0 // #define WARM_PORT_NUM 1 // #define PWM_CHANNEL_COUNT 2 // #define LIGHT_PERIOD 500 // void light_driver_init(void); // void light_driver_update(uint8_t onoff, uint16_t lightness, uint16_t temperature); void light_driver_init(void); void light_set(uint8_t onoff); void light_blink(void); #endif
YifuLiu/AliOS-Things
solutions/genie_mesh_demo/light_ctl/light_driver.h
C
apache-2.0
453
CPRE := @ ifeq ($(V),1) CPRE := VERB := --verbose endif .PHONY:startup startup: all all: @echo "Build Solution by $(BOARD) " $(CPRE) scons $(VERB) --board=$(BOARD) $(MULTITHREADS) $(MAKEFLAGS) @echo AOS SDK Done sdk: $(CPRE) aos sdk .PHONY:clean clean: $(CPRE) scons -c --board=$(BOARD) ifeq ($(OS), Windows_NT) $(CPRE) if exist aos_sdk rmdir /s /q aos_sdk $(CPRE) if exist binary rmdir /s /q binary $(CPRE) if exist out rmdir /s /q out $(CPRE) if exist aos.elf del /f /q aos.elf $(CPRE) if exist aos.map del /f /q aos.map else $(CPRE) rm -rf aos_sdk binary out aos.elf aos.map endif
YifuLiu/AliOS-Things
solutions/haas_dev_demo/Makefile
Makefile
apache-2.0
599
#! /bin/env python from aostools import Make # default elf is out/<solution>@<board>.elf, and default objcopy is out/<solution>@<board>.bin # defconfig = Make(elf='out/<solution>@<board>.elf', objcopy='out/<solution>@<board>.bin') defconfig = Make() Export('defconfig') defconfig.build_components()
YifuLiu/AliOS-Things
solutions/haas_dev_demo/SConstruct
Python
apache-2.0
303
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/init.h" #include "board.h" #include <aos/errno.h> #include <aos/kernel.h> #include <k_api.h> #include <stdio.h> #include <stdlib.h> #include <uservice/uservice.h> #include <uservice/eventid.h> #include "aos/cli.h" #include "haas_main.h" #define AMP_TYPE_MAX_LEN 32 #define AMP_TYPE_JS "JS" #define AMP_TYPE_PYTHON "Python" extern int amp_main(void); static void amp_set_command(int argc, char **argv) { if (argc < 2) { printf("Usge: amp_set [JS/Python]\r\n"); return; } if (strcmp(argv[1], AMP_TYPE_JS) == 0) { aos_kv_set("amp_type", AMP_TYPE_JS, strlen(AMP_TYPE_JS)); } else if (strcmp(argv[1], AMP_TYPE_PYTHON) == 0) { aos_kv_set("amp_type", AMP_TYPE_PYTHON, strlen(AMP_TYPE_PYTHON)); } } /* reg args: fun, cmd, description*/ ALIOS_CLI_CMD_REGISTER(amp_set_command, amp_set, set amp startup type) int application_start(int argc, char *argv[]) { int len = 0; int ret = 0; aos_task_t amp_task; char amp_type[AMP_TYPE_MAX_LEN] = {0}; printf("haas dev demp entry here!\r\n"); len = 32; ret = aos_kv_get("amp_type", amp_type, &len); if ((ret == 0) && (strcmp(amp_type, AMP_TYPE_JS) == 0)) { /* Start JS engine. */ aos_task_new_ext(&amp_task, "amp_task", amp_main, NULL, 8192, AOS_DEFAULT_APP_PRI - 2); } else { /* Start Python engine. */ haas_main(argc, argv); } while (1) { aos_msleep(10000); }; }
YifuLiu/AliOS-Things
solutions/haas_dev_demo/haas_dev_demo.c
C
apache-2.0
1,525
/* user space */ #ifndef RHINO_CONFIG_USER_SPACE #define RHINO_CONFIG_USER_SPACE 0 #endif
YifuLiu/AliOS-Things
solutions/haas_dev_demo/k_app_config.h
C
apache-2.0
106
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <aos/kernel.h> #include "aos/init.h" #include "board.h" #include <k_api.h> #ifndef AOS_BINS extern int application_start(int argc, char *argv[]); #endif /* If board have no component for example board_xx_init, it indicates that this app does not support this board. Set the correspondence in file platform\board\aaboard_demo\ucube.py. */ extern void board_tick_init(void); extern void board_stduart_init(void); extern void board_dma_init(void); extern void board_gpio_init(void); extern void board_kinit_init(kinit_t* init_args); /* For user config kinit.argc = 0; kinit.argv = NULL; kinit.cli_enable = 1; */ static kinit_t kinit = {0, NULL, 1}; /** * @brief Board Initialization Function * @param None * @retval None */ void board_init(void) { board_tick_init(); board_stduart_init(); board_dma_init(); board_gpio_init(); } void aos_maintask(void* arg) { board_init(); board_kinit_init(&kinit); aos_components_init(&kinit); #ifndef AOS_BINS application_start(kinit.argc, kinit.argv); /* jump to app entry */ #endif }
YifuLiu/AliOS-Things
solutions/haas_dev_demo/maintask.c
C
apache-2.0
1,192
CPRE := @ ifeq ($(V),1) CPRE := VERB := --verbose endif .PHONY:startup startup: all all: @echo "Build Solution by $(BOARD) " $(CPRE) scons $(VERB) --board=$(BOARD) $(MULTITHREADS) $(MAKEFLAGS) @echo AOS SDK Done sdk: $(CPRE) aos sdk .PHONY:clean clean: $(CPRE) scons -c --board=$(BOARD) ifeq ($(OS), Windows_NT) $(CPRE) if exist aos_sdk rmdir /s /q aos_sdk $(CPRE) if exist binary rmdir /s /q binary $(CPRE) if exist out rmdir /s /q out $(CPRE) if exist aos.elf del /f /q aos.elf $(CPRE) if exist aos.map del /f /q aos.map else $(CPRE) rm -rf aos_sdk binary out aos.elf aos.map endif
YifuLiu/AliOS-Things
solutions/helloworld_demo/Makefile
Makefile
apache-2.0
599