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) 2021 Alibaba Group Holding Limited
*/
/* Support newlib internal locks */
#ifndef _SYS_LOCK_H
#define _SYS_LOCK_H
#include <pthread.h>
#ifdef __cplusplus
extern "C" {
#endif
#define _LOCK_T pthread_mutex_t
#define _LOCK_RECURSIVE_T pthread_mutex_t
#define __LOCK_INIT(class, lock) \
class _LOCK_T lock = PTHREAD_MUTEX_INITIALIZER;
#define __LOCK_INIT_RECURSIVE(class, lock) __LOCK_INIT(class, lock)
#define __lock_init(_lock) pthread_mutex_init(&_lock, NULL)
#define __lock_acquire(_lock) pthread_mutex_lock(&_lock)
#define __lock_try_acquire(lock) pthread_mutex_trylock(&_lock)
#define __lock_release(_lock) pthread_mutex_unlock(&_lock)
#define __lock_close(_lock) pthread_mutex_destroy(&_lock)
#define __lock_init_recursive(_lock) pthread_mutex_init(&_lock, NULL)
#define __lock_acquire_recursive(_lock) pthread_mutex_lock(&_lock)
#define __lock_try_acquire_recursive(lock) pthread_mutex_trylock(&_lock)
#define __lock_release_recursive(_lock) pthread_mutex_unlock(&_lock)
#define __lock_close_recursive(_lock) pthread_mutex_destroy(&_lock)
#ifdef __cplusplus
}
#endif
#endif /*_SYS_LOCK_H*/
| YifuLiu/AliOS-Things | components/posix/include/sys/lock.h | C++ | apache-2.0 | 1,129 |
/*
* Copyright (C) 2021 Alibaba Group Holding Limited
*/
#ifndef _SYS_MMAN_H
#define _SYS_MMAN_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stddef.h>
#include <sys/types.h>
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
int munmap(void *addr, size_t length);
#ifdef __cplusplus
}
#endif
#endif /* _SYS_MMAN_H */
| YifuLiu/AliOS-Things | components/posix/include/sys/mman.h | C | apache-2.0 | 361 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#ifndef _PRCTL_H
#define _PRCTL_H
#ifdef __cplusplus
extern "C" {
#endif
/*
* PR_SET_NAME: Set the name of the calling thread, using the value in the
* location pointed to by (char *) arg2.
*/
#define PR_SET_NAME 0x00000000
int prctl(int option, ...);
#ifdef __cplusplus
}
#endif
#endif /* _PRCTL_H */
| YifuLiu/AliOS-Things | components/posix/include/sys/prctl.h | C | apache-2.0 | 388 |
/*
* Copyright (C) 2021 Alibaba Group Holding Limited
*/
#ifndef _SYS_SELECT_H
#define _SYS_SELECT_H
#ifdef __cplusplus
extern "C" {
#endif
#include <sys/_timeval.h>
#ifndef FD_SETSIZE
#define FD_SETSIZE 1024
#endif
typedef unsigned long fd_mask;
typedef struct {
unsigned long fds_bits[FD_SETSIZE / 8 / sizeof(long)];
} fd_set;
#define FD_ZERO(s) do { int __i; unsigned long *__b = (s)->fds_bits; for (__i = sizeof(fd_set) / sizeof(long); __i; __i--) *__b++ = 0; } while (0)
#define FD_SET(d, s) ((s)->fds_bits[(d) / (8 * sizeof(long))] |= (1UL << ((d) % (8 * sizeof(long)))))
#define FD_CLR(d, s) ((s)->fds_bits[(d) / (8 * sizeof(long))] &= ~(1UL << ((d) % (8 * sizeof(long)))))
#define FD_ISSET(d, s) (!!((s)->fds_bits[(d) / (8 * sizeof(long))] & (1UL << ((d) % (8 * sizeof(long))))))
int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds,
struct timeval *timeout);
#ifdef __cplusplus
}
#endif
#endif /*_SYS_SELECT_H*/
| YifuLiu/AliOS-Things | components/posix/include/sys/select.h | C | apache-2.0 | 985 |
/*
* Copyright (C) 2021 Alibaba Group Holding Limited
*/
#ifndef _SYS_STATFS_H
#define _SYS_STATFS_H
#ifdef __cplusplus
extern "C" {
#endif
struct statfs {
long f_type; /* fs type */
long f_bsize; /* optimized transport block size */
long f_blocks; /* total blocks */
long f_bfree; /* available blocks */
long f_bavail; /* number of blocks that non-super users can acquire */
long f_files; /* total number of file nodes */
long f_ffree; /* available file nodes */
long f_fsid; /* fs id */
long f_namelen; /* max file name length */
};
int statfs(const char *path, struct statfs *buf);
#ifdef __cplusplus
}
#endif
#endif /*_SYS_STATFS_H*/
| YifuLiu/AliOS-Things | components/posix/include/sys/statfs.h | C | apache-2.0 | 698 |
#include <sys/statfs.h>
| YifuLiu/AliOS-Things | components/posix/include/sys/vfs.h | C | apache-2.0 | 24 |
/*
* Copyright (C) 2018-2021 Alibaba Group Holding Limited
*/
#include <dirent.h>
#include <aos/errno.h>
#include <aos/kernel.h>
#include "internal/common.h"
DIR *opendir(const char *dirname)
{
if (dirname == NULL) {
errno = EINVAL;
return NULL;
}
return (DIR *)aos_opendir(dirname);
}
int closedir(DIR *dirp)
{
int ret;
CHECK_POSIX_PARAM(dirp);
ret = aos_closedir((aos_dir_t *)dirp);
CHECK_AOS_RET(ret);
return ret;
}
struct dirent *readdir(DIR *dirp)
{
if (dirp == NULL) {
errno = EINVAL;
return NULL;
}
return (struct dirent *)aos_readdir(dirp);
}
long telldir(DIR *dirp)
{
long ret;
CHECK_POSIX_PARAM(dirp);
ret = aos_telldir((aos_dir_t *)dirp);
CHECK_AOS_RET(ret);
return ret;
}
void seekdir(DIR *dirp, long loc)
{
if (dirp == NULL) {
return;
}
return aos_seekdir((aos_dir_t *)dirp, loc);
}
int scandir(const char *dirname, struct dirent ***namelist,
int (*filter)(const struct dirent *),
int (*compar)(const struct dirent **, const struct dirent **))
{
int num_entry = 0;
int array_size = 16;
DIR *dirp;
struct dirent *d, *p;
struct dirent **names, **names_new;
if ((dirname == NULL) || (namelist == NULL)) {
errno = EINVAL;
return -1;
}
dirp = opendir(dirname);
if (dirp == NULL)
return -1;
names = (struct dirent **)malloc(sizeof(struct dirent *) * array_size);
if (names == NULL) {
errno = ENOMEM;
goto error;
}
while ((d = readdir(dirp)) != NULL) {
if ((filter != NULL) && ((*filter)(d) == 0))
continue;
p = (struct dirent *) malloc(DIRSIZ(d));
if (p == NULL) {
errno = ENOMEM;
goto error;
}
p->d_ino = d->d_ino;
p->d_type = d->d_type;
strncpy(p->d_name, d->d_name, strlen(d->d_name));
if (num_entry >= array_size) {
names_new = realloc(names, sizeof(struct dirent *) * array_size * 2);
if (names_new == NULL) {
free(p);
errno = ENOMEM;
goto error;
}
names = names_new;
array_size *= 2;
}
names[num_entry++] = p;
}
closedir(dirp);
if ((num_entry > 0) && (compar != NULL))
qsort(names, num_entry, sizeof(struct dirent *), (void *)compar);
*namelist = names;
return num_entry;
error:
while (num_entry > 0)
free(names[num_entry--]);
free(names);
closedir(dirp);
return -1;
}
int mkdir(const char *path, mode_t mode)
{
int ret;
CHECK_POSIX_PARAM(path);
ret = aos_mkdir(path);
CHECK_AOS_RET(ret);
return ret;
}
int rmdir(const char *path)
{
int ret;
CHECK_POSIX_PARAM(path);
ret = aos_rmdir(path);
CHECK_AOS_RET(ret);
return ret;
}
void rewinddir(DIR *dirp)
{
if (dirp == NULL) {
return;
}
aos_rewinddir((aos_dir_t *)dirp);
}
int chdir(const char *path)
{
int ret;
CHECK_POSIX_PARAM(path);
ret = aos_chdir(path);
CHECK_AOS_RET(ret);
return ret;
}
| YifuLiu/AliOS-Things | components/posix/src/dirent.c | C | apache-2.0 | 3,183 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <unistd.h>
#include <pthread.h>
#include <enviro.h>
#include <aos/kernel.h>
/* Define POSIX_ENV as 1 to enable env apis here when there is no env apis in libc.
* Note: Newlib libc already implements env apis, tzset depends on them.
*/
#if (POSIX_ENV > 0)
pthread_mutex_t g_enviro_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_environ_t *g_penviron = NULL;
struct _envval {
const char *valname;
struct _envval *next;
};
static struct _envval *g_penvval_deprecated = NULL;
static int envval_deprecat(const char *valname);
static pthread_environ_t *env_new(const char *envname, const char *envval)
{
pthread_environ_t *penv = NULL;
int envname_len, envval_len;
/* malloc pthread_environ_t */
penv = malloc(sizeof(pthread_environ_t));
if (penv == NULL) {
return NULL;
}
/* malloc envname and copy the envname */
envname_len = strlen(envname);
penv->envname = malloc(envname_len + 1);
if (penv->envname == NULL) {
free(penv);
return NULL;
}
strncpy(penv->envname, envname, envname_len);
penv->envname[envname_len] = '\0';
/* malloc envval and copy the envval */
envval_len = strlen(envval);
penv->envval = malloc(envval_len + 1);
if (penv->envval == NULL) {
free(penv->envname);
free(penv);
return NULL;
}
strncpy(penv->envval, envval, envval_len);
penv->envval[envval_len] = '\0';
penv->next = NULL;
return penv;
}
static void env_free(pthread_environ_t *penv)
{
if (penv == NULL) {
return;
}
if (penv->envname != NULL) {
free(penv->envname);
}
if (penv->envval != NULL) {
envval_deprecat(penv->envval);
}
free(penv);
}
static int envval_deprecat(const char *valname)
{
struct _envval *ev;
ev = malloc(sizeof(struct _envval));
if (ev == NULL) {
return -1;
}
ev->valname = valname;
ev->next = NULL;
if (g_penvval_deprecated == NULL) {
g_penvval_deprecated = ev;
return 0;
}
ev->next = g_penvval_deprecated;
g_penvval_deprecated = ev;
return 0;
}
int setenv(const char *envname, const char *envval, int overwrite)
{
pthread_environ_t *penv = NULL;
pthread_environ_t *penv_pre = NULL;
int envval_len;
int ret = -1;
if ((envname == NULL) || (envval == NULL)) {
return -1;
}
ret = pthread_mutex_lock(&g_enviro_mutex);
if (ret != 0) {
return -1;
}
/* if no environ in tcb, create the first one */
if (g_penviron == NULL) {
penv = env_new(envname, envval);
if (penv == NULL) {
pthread_mutex_unlock(&g_enviro_mutex);
return -1;
}
g_penviron = penv;
pthread_mutex_unlock(&g_enviro_mutex);
return 0;
}
/* search the environ list to find the match item */
penv = g_penviron;
while (penv != NULL) {
if (strcmp(penv->envname, envname) == 0) {
/* if the environment variable named by envname already exists and the value of overwrite is non-zero,
the function shall return success and the environment shall be updated */
if (overwrite != 0) {
/* add the deprecated val in deprecated list */
if (!envval_deprecat(penv->envval)) {
envval_len = strlen(envval);
penv->envval = malloc(envval_len + 1);
strncpy(penv->envval, envval, envval_len);
penv->envval[envval_len] = '\0';
pthread_mutex_unlock(&g_enviro_mutex);
return 0;
} else {
pthread_mutex_unlock(&g_enviro_mutex);
return -1;
}
} else {
/* If the environment variable named by envname already exists and the value of overwrite is zero, the
function shall return success and the environment shall remain unchanged */
pthread_mutex_unlock(&g_enviro_mutex);
return 0;
}
}
penv_pre = penv;
penv = penv->next;
}
/* if no match item create one and add to the end of list */
penv = env_new(envname, envval);
if (penv == NULL) {
pthread_mutex_unlock(&g_enviro_mutex);
return -1;
}
penv_pre->next = penv;
pthread_mutex_unlock(&g_enviro_mutex);
return 0;
}
char *getenv(const char *name)
{
int ret;
char *val = NULL;
pthread_environ_t *penv = NULL;
if (name == NULL) {
return NULL;
}
penv = g_penviron;
if (penv == NULL) {
return NULL;
}
ret = pthread_mutex_lock(&g_enviro_mutex);
if (ret != 0) {
return NULL;
}
/* search the environ list to find the match item */
while (penv != NULL) {
if (strcmp(penv->envname, name) == 0) {
val = penv->envval;
pthread_mutex_unlock(&g_enviro_mutex);
return val;
}
penv = penv->next;
}
pthread_mutex_unlock(&g_enviro_mutex);
return NULL;
}
int unsetenv(const char *name)
{
pthread_environ_t *penv = NULL;
pthread_environ_t *penv_pre = NULL;
int ret = -1;
if (name == NULL) {
return -1;
}
penv = g_penviron;
if (penv == NULL) {
return -1;
}
ret = pthread_mutex_lock(&g_enviro_mutex);
if (ret != 0) {
return -1;
}
/* search the environ list to find the match item and free it */
while (penv != NULL) {
if (strcmp(penv->envname, name) == 0) {
if (penv_pre == NULL) {
g_penviron = penv->next;
} else {
penv_pre->next = penv->next;
}
pthread_mutex_unlock(&g_enviro_mutex);
/* free the pthread_environ_t data */
env_free(penv);
return 0;
}
penv_pre = penv;
penv = penv->next;
}
pthread_mutex_unlock(&g_enviro_mutex);
return -1;
}
int putenv(char *string)
{
int pos = 0;
char *envname = NULL;
char *envval = NULL;
int ret = -1;
for (pos = 0; pos < strlen(string); pos++) {
if (string[pos] == '=') {
envval = &string[pos + 1];
/* malloc a memory to save envname */
envname = malloc(pos + 1);
if (envname == NULL) {
return -1;
}
/* copy envname */
strncpy(envname, string, pos);
envname[pos] = '\0';
ret = setenv(envname, envval, 1);
/* free envname */
free(envname);
return ret;
}
}
return -1;
}
int clearenv(void)
{
pthread_environ_t *env;
pthread_environ_t *next;
struct _envval *envval, *envval_next;
env = g_penviron;
while (env != NULL) {
next= env->next;
if (env->envname != NULL) {
free(env->envname);
}
if (env->envval != NULL) {
free(env->envval);
}
free(env);
env = next;
}
g_penviron = NULL;
envval = g_penvval_deprecated;
while (envval != NULL) {
envval_next = envval->next;
free((void*)envval->valname);
free(envval);
envval = envval_next;
}
g_penvval_deprecated = NULL;
return 0;
}
#endif /*(POSIX_ENV > 0) */
int uname(struct utsname *name)
{
const char *os = "AliOS Things";
if (name == NULL) {
return -1;
}
memset(name, 0, sizeof(struct utsname));
aos_version_str_get(name->version, _UTSNAME_VERSION_LENGTH - 1);
strncpy(name->sysname, os, _UTSNAME_SYSNAME_LENGTH - 1);
return 0;
}
long sysconf(int name)
{
long val = 0;
switch (name) {
case _SC_JOB_CONTROL :
val = _POSIX_JOB_CONTROL;
break;
case _SC_SAVED_IDS :
val = _POSIX_SAVED_IDS;
break;
case _SC_VERSION :
val = _POSIX_VERSION;
break;
case _SC_ASYNCHRONOUS_IO :
val = _POSIX_ASYNCHRONOUS_IO;
break;
case _SC_FSYNC :
val = _POSIX_FSYNC;
break;
case _SC_MAPPED_FILES :
val = _POSIX_MAPPED_FILES;
break;
case _SC_MEMLOCK :
val = _POSIX_MEMLOCK;
break;
case _SC_MEMLOCK_RANGE :
val = _POSIX_MEMLOCK_RANGE;
break;
case _SC_MEMORY_PROTECTION :
val = _POSIX_MEMORY_PROTECTION;
break;
case _SC_MESSAGE_PASSING :
val = _POSIX_MESSAGE_PASSING;
break;
case _SC_PRIORITIZED_IO :
val = _POSIX_PRIORITIZED_IO;
break;
case _SC_REALTIME_SIGNALS :
#if (_POSIX_REALTIME_SIGNALS > 0)
val = 1;
#else
val = 0;
#endif
break;
case _SC_SEMAPHORES :
val = _POSIX_SEMAPHORES;
break;
case _SC_SYNCHRONIZED_IO :
val = _POSIX_SYNCHRONIZED_IO;
break;
case _SC_TIMERS :
val = _POSIX_TIMERS;
break;
case _SC_BARRIERS :
val = _POSIX_BARRIERS;
break;
case _SC_READER_WRITER_LOCKS :
val = _POSIX_READER_WRITER_LOCKS;
break;
case _SC_SPIN_LOCKS :
val = _POSIX_SPIN_LOCKS;
break;
case _SC_THREADS :
val = _POSIX_THREADS;
break;
case _SC_THREAD_ATTR_STACKADDR :
val = _POSIX_THREAD_ATTR_STACKADDR;
break;
case _SC_THREAD_ATTR_STACKSIZE :
val = _POSIX_THREAD_ATTR_STACKSIZE;
break;
case _SC_THREAD_PRIORITY_SCHEDULING :
val = _POSIX_THREAD_PRIORITY_SCHEDULING;
break;
case _SC_THREAD_PRIO_INHERIT :
val = _POSIX_THREAD_PRIO_INHERIT;
break;
case _SC_THREAD_PRIO_PROTECT :
val = _POSIX_THREAD_PRIO_PROTECT;
break;
case _SC_THREAD_PROCESS_SHARED :
val = _POSIX_THREAD_PROCESS_SHARED;
break;
case _SC_THREAD_SAFE_FUNCTIONS :
val = _POSIX_THREAD_SAFE_FUNCTIONS;
break;
case _SC_SPAWN :
val = _POSIX_SPAWN;
break;
case _SC_TIMEOUTS :
val = _POSIX_TIMEOUTS;
break;
case _SC_CPUTIME :
val = _POSIX_CPUTIME;
break;
case _SC_THREAD_CPUTIME :
val = _POSIX_THREAD_CPUTIME;
break;
case _SC_ADVISORY_INFO :
val = _POSIX_ADVISORY_INFO;
break;
default:
val = -1;
break;
}
return val;
}
size_t confstr(int name, char *buf, size_t len)
{
int len_real = 0;
if (name == _CS_GNU_LIBC_VERSION) {
len_real = strlen(_POSIX_GNU_LIBC_VERSION);
if (len < len_real) {
return 0;
}
strncpy(buf, _POSIX_GNU_LIBC_VERSION, len);
return len_real;
} else if (name == _CS_GNU_LIBPTHREAD_VERSION) {
len_real = strlen(_POSIX_GNU_LIBPTHREAD_VERSION);
if (len < len_real) {
return 0;
}
strncpy(buf, _POSIX_GNU_LIBPTHREAD_VERSION, len);
return len_real;
} else {
return 0;
}
}
| YifuLiu/AliOS-Things | components/posix/src/enviro.c | C | apache-2.0 | 11,148 |
/*
* Copyright (C) 2015-2022 Alibaba Group Holding Limited
*/
#include <stddef.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/statfs.h>
#include <utime.h>
#include <aos/vfs.h>
#include "internal/common.h"
int statfs(const char *path, struct statfs *buf)
{
int ret;
struct aos_statfs statfs_temp;
CHECK_POSIX_PARAM(path);
CHECK_POSIX_PARAM(buf);
ret = aos_statfs(path, &statfs_temp);
CHECK_AOS_RET(ret);
if (ret == 0) {
buf->f_type = statfs_temp.f_type;
buf->f_bsize = statfs_temp.f_bsize;
buf->f_blocks = statfs_temp.f_blocks;
buf->f_bfree = statfs_temp.f_bfree;
buf->f_bavail = statfs_temp.f_bavail;
buf->f_files = statfs_temp.f_files;
buf->f_ffree = statfs_temp.f_ffree;
buf->f_fsid = statfs_temp.f_fsid;
buf->f_namelen = statfs_temp.f_namelen;
}
return ret;
}
int remove(const char *path)
{
int ret;
CHECK_POSIX_PARAM(path);
ret = aos_remove(path);
CHECK_AOS_RET(ret);
return ret;
}
int fsync(int fd)
{
int ret;
if (fd < 0) {
errno = EBADF;
return -1;
}
ret = aos_sync(fd);
CHECK_AOS_RET(ret);
return ret;
}
int fdatasync(int fd)
{
int ret;
if (fd < 0) {
errno = EBADF;
return -1;
}
ret = aos_sync(fd);
CHECK_AOS_RET(ret);
return ret;
}
void sync(void)
{
aos_allsync();
}
int access(const char *path, int mode)
{
int ret;
CHECK_POSIX_PARAM(path);
ret = aos_access(path, mode);
CHECK_AOS_RET(ret);
return ret;
}
char *getcwd(char *buf, size_t size)
{
if (buf == NULL) {
return NULL;
}
return aos_getcwd(buf, size);
}
int creat(const char *path, mode_t mode)
{
int ret;
CHECK_POSIX_PARAM(path);
ret = open(path, O_WRONLY | O_CREAT | O_TRUNC, mode);
CHECK_AOS_RET(ret);
return ret;
}
long pathconf(const char *path, int name)
{
long ret;
CHECK_POSIX_PARAM(path);
ret = aos_pathconf(path, name);
CHECK_AOS_RET(ret);
return ret;
}
long fpathconf(int fd, int name)
{
long ret;
if (fd < 0) {
errno = EBADF;
return -1;
}
ret = aos_fpathconf(fd, name);
CHECK_AOS_RET(ret);
return ret;
}
int utime(const char *path, const struct utimbuf *buf)
{
int ret;
struct aos_utimbuf utimbuf_temp;
CHECK_POSIX_PARAM(path);
if (buf == NULL) {
utimbuf_temp.actime = time(NULL);
utimbuf_temp.modtime = utimbuf_temp.actime;
} else {
utimbuf_temp.actime = buf->actime;
utimbuf_temp.modtime = buf->modtime;
}
ret = aos_utime(path, &utimbuf_temp);
CHECK_AOS_RET(ret);
return ret;
}
int ftruncate(int fd, off_t size)
{
int ret;
if ((fd < 0) || (size < 0))
return -EINVAL;
ret = aos_ftruncate(fd, size);
CHECK_AOS_RET(ret);
return 0;
}
int truncate(const char *path, off_t size)
{
int ret;
if ((path == NULL) || (path[0] == '\0') || (size < 0))
return -EINVAL;
ret = aos_truncate(path, size);
CHECK_AOS_RET(ret);
return 0;
}
| YifuLiu/AliOS-Things | components/posix/src/fs.c | C | apache-2.0 | 3,154 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef __POSIX_INTERNAL_COMMON_H
#define __POSIX_INTERNAL_COMMON_H
#include <aos/errno.h>
#define CHECK_AOS_RET(ret) do {if ((ret) < 0) {errno = -(ret); return -1; } } while (0)
#define CHECK_POSIX_PARAM(param) do {if ((param) == NULL) {errno = EINVAL; return -1; } } while (0)
#endif /*__POSIX_INTERNAL_COMMON_H*/ | YifuLiu/AliOS-Things | components/posix/src/internal/common.h | C | apache-2.0 | 383 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#ifndef __POSIX_INTERNAL_PTHREAD_H
#define __POSIX_INTERNAL_PTHREAD_H
#include <pthread.h>
#include <aos/kernel.h>
#define PTHREAD_DEFAULT_STACK_SIZE 2048
#define PTHREAD_DEFAULT_GUARD_SIZE 256
#define PTHREAD_DEFAULT_PRIORITY 30
#define PTHREAD_DEFAULT_SLICE 10
#define PTHREAD_NAME_MAX_LEN 16
#define PTHREAD_TCB_MAGIC 0X11223344
#define DEFAULT_MUTEX_TYPE PTHREAD_MUTEX_DEFAULT
#define DEFAULT_MUTEX_PROCOCOL PTHREAD_PRIO_INHERIT
#define DEFAULT_MUTEX_PRIOCEILING 30
#define DEFAULT_MUTEX_PSHARED PTHREAD_PROCESS_PRIVATE
#define DEFAULT_COND_CLOCK CLOCK_REALTIME
#define DEFAULT_COND_SHARED PTHREAD_PROCESS_PRIVATE
typedef struct pthread_cleanup {
int cancel_type;
struct pthread_cleanup *prev;
void (*cleanup_routine)(void *para);
void *para;
} pthread_cleanup_t;
typedef struct pthread_tcb {
aos_task_t task; /* The rhino task handle. */
unsigned int magic; /* The pthread tcb memory magic number. */
void *(*thread_entry)(void *para); /* The start routine of the thread. */
void *thread_para; /* The parameter of start routine. */
aos_sem_t join_sem; /* The semaphore for pthread_join. */
pthread_cleanup_t *cleanup; /* The registered cleanup function for the thread.*/
void *environ;
void **tls;
void *return_value; /* The thread's return value. */
pthread_attr_t attr; /* The thread's attribute. */
char thread_name[PTHREAD_NAME_MAX_LEN + 1]; /* The thread's name. */
} pthread_tcb_t;
static inline pthread_tcb_t* __pthread_get_tcb(pthread_t thread)
{
pthread_tcb_t* ptcb = (pthread_tcb_t*)thread;
if ((ptcb == NULL) || (ptcb->magic != PTHREAD_TCB_MAGIC)) {
return NULL;
}
return ptcb;
}
void pthread_tsd_dtors(void);
#endif /* __POSIX_INTERNAL_PTHREAD_H */
| YifuLiu/AliOS-Things | components/posix/src/internal/pthread.h | C | apache-2.0 | 1,860 |
/*
* Copyright (C) 2020-2021 Alibaba Group Holding Limited
*/
#ifndef __POSIX_INTERNAL_SCHED_H
#define __POSIX_INTERNAL_SCHED_H
#include <sched.h>
#include <pthread.h>
#include <k_api.h>
/* Convert the schedule policy of posix to rhino. */
static inline int sched_policy_posix2rhino(int policy)
{
switch (policy) {
case SCHED_FIFO:
return KSCHED_FIFO;
case SCHED_RR:
return KSCHED_RR;
case SCHED_CFS:
return KSCHED_CFS;
default:
return -1;
}
}
/* Convert the schedule policy of rhino to posix. */
static inline int sched_policy_rhino2posix(int policy)
{
switch (policy) {
case KSCHED_FIFO:
return SCHED_FIFO;
case KSCHED_RR:
return SCHED_RR;
case KSCHED_CFS:
return SCHED_CFS;
default:
return -1;
}
}
/* In rhino: lower priority value means higher priority.
* In posix standard: higher priority value means higher priority.
*/
static inline int sched_priority_posix2rhino(int policy, int priority)
{
return aos_sched_get_priority_max(policy) - priority;
}
#define sched_priority_rhino2posix sched_priority_posix2rhino
#endif /*__POSIX_INTERNAL_SCHED_H*/
| YifuLiu/AliOS-Things | components/posix/src/internal/sched.h | C | apache-2.0 | 1,245 |
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
/* TODO: replace krhino apis with aos apis. */
#include <mqueue.h>
#include <k_api.h>
mqd_t mq_open(const char *name, int oflag, ...)
{
kbuf_queue_t *mq;
kstat_t ret;
ret = krhino_buf_queue_dyn_create(&mq, "buf_queue", DEFAULT_MQUEUE_SIZE, DEFAULT_MAX_MSG_SIZE);
if (ret != RHINO_SUCCESS) {
return 0;
}
return mq;
}
int mq_close(mqd_t mqdes)
{
return krhino_buf_queue_dyn_del(mqdes);
}
ssize_t mq_receive(mqd_t mqdes, char *msg_ptr, size_t msg_len, unsigned *msg_prio)
{
size_t msg_size;
kstat_t ret;
*msg_prio = 0;
ret = krhino_buf_queue_recv(mqdes, 0, msg_ptr, &msg_size);
if (ret != RHINO_SUCCESS) {
return 0;
}
return msg_size;
}
int mq_send(mqd_t mqdes, const char *msg_ptr, size_t msg_len, unsigned msg_prio)
{
kstat_t ret;
ret = krhino_buf_queue_send((kbuf_queue_t *)mqdes, (void *)msg_ptr, msg_len);
if (ret != RHINO_SUCCESS) {
return 0;
}
return msg_len;
}
int mq_setattr(mqd_t mqdes, const struct mq_attr *mqstat, struct mq_attr *omqstat)
{
return 0;
}
int mq_getattr(mqd_t mqdes, struct mq_attr *mqstat)
{
return 0;
}
ssize_t mq_timedreceive(mqd_t mqdes, char *msg_ptr, size_t msg_len,
unsigned *msg_prio, const struct timespec *abs_timeout)
{
size_t msg_size;
kstat_t ret;
tick_t ticks;
*msg_prio = 0;
ticks = abs_timeout->tv_sec * RHINO_CONFIG_TICKS_PER_SECOND +
(abs_timeout->tv_nsec * RHINO_CONFIG_TICKS_PER_SECOND) / 1000000000LL;
ret = krhino_buf_queue_recv(mqdes, ticks, msg_ptr, &msg_size);
if (ret != RHINO_SUCCESS) {
return 0;
}
return msg_size;
}
int mq_timedsend(mqd_t mqdes, const char *msg_ptr, size_t msg_len,
unsigned msg_prio, const struct timespec *abs_timeout)
{
kstat_t ret;
(void)msg_prio;
ret = krhino_buf_queue_send((kbuf_queue_t *)mqdes, (void *)msg_ptr, msg_len);
if (ret != RHINO_SUCCESS) {
return 0;
}
return msg_len;
}
| YifuLiu/AliOS-Things | components/posix/src/mqueue.c | C | apache-2.0 | 2,091 |
/*
* Copyright (C) 2021 Alibaba Group Holding Limited
*/
#include <poll.h>
extern int aos_poll(struct pollfd *fds, int nfds, int timeout);
int poll(struct pollfd fds[], nfds_t nfds, int timeout)
{
return aos_poll(fds, nfds, timeout);
}
| YifuLiu/AliOS-Things | components/posix/src/poll.c | C | apache-2.0 | 244 |
/*
* Copyright (C) 2018-2021 Alibaba Group Holding Limited
*/
#include <stdarg.h>
#include <sys/prctl.h>
#include <aos/errno.h>
#include <pthread.h>
int prctl(int option, ...)
{
va_list ap;
unsigned long arg;
if (option == PR_SET_NAME) {
va_start(ap, option);
arg = va_arg(ap, unsigned long);
va_end(ap);
if (arg == 0) {
errno = EINVAL;
return -1;
}
pthread_setname_np(pthread_self(), (char *)arg);
return 0;
} else {
errno = ENOTSUP;
return -1;
}
}
| YifuLiu/AliOS-Things | components/posix/src/prctl.c | C | apache-2.0 | 573 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
#include <sched.h>
#include <aos/errno.h>
#include <aos/kernel.h>
#include <aos/rhino.h>
#include "internal/pthread.h"
#include "internal/sched.h"
pthread_mutex_t g_pthread_lock = PTHREAD_MUTEX_INITIALIZER;
int pthread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void))
{
/* Fork is not supported. */
return ENOSYS;
}
void pthread_cleanup_pop(int execute)
{
pthread_tcb_t *ptcb = NULL;
pthread_cleanup_t *cleanup = NULL;
ptcb = __pthread_get_tcb(pthread_self());
if (ptcb == NULL) {
return;
}
cleanup = ptcb->cleanup;
if (cleanup != NULL) {
ptcb->cleanup = cleanup->prev;
if (execute != 0) {
cleanup->cleanup_routine(cleanup->para);
}
free(cleanup);
}
}
void pthread_cleanup_push(void (*routine)(void *), void *arg)
{
pthread_tcb_t *ptcb = NULL;
pthread_cleanup_t *cleanup = NULL;
ptcb = __pthread_get_tcb(pthread_self());
if (ptcb == NULL) {
return;
}
cleanup = (pthread_cleanup_t *) malloc(sizeof(pthread_cleanup_t));
if (cleanup != NULL) {
cleanup->cleanup_routine = routine;
cleanup->para = arg;
cleanup->prev = ptcb->cleanup;
ptcb->cleanup = cleanup;
}
}
static void do_pthread_cleanup(pthread_tcb_t *ptcb)
{
pthread_cleanup_t *cleanup = NULL;
/* Execute all existed cleanup functions and free it. */
do {
cleanup = ptcb->cleanup;
if (cleanup != NULL) {
ptcb->cleanup = cleanup->prev;
cleanup->cleanup_routine(cleanup->para);
free(cleanup);
}
} while (ptcb->cleanup != NULL);
}
/* Exit the pthread, never return. */
void pthread_exit(void* value_ptr)
{
pthread_tcb_t *ptcb = NULL;
ptcb = __pthread_get_tcb(pthread_self());
if (ptcb == NULL) {
return;
}
ptcb->return_value = value_ptr;
/* Run cleanup functions of the thread */
do_pthread_cleanup(ptcb);
/* Run destructor functions of the thread */
pthread_tsd_dtors();
/* The underlying task in kernel is not available, unlink it from ptcb. */
aos_task_ptcb_set(&(ptcb->task), NULL);
ptcb->task = NULL;
if (ptcb->attr.detachstate == PTHREAD_CREATE_JOINABLE) {
/* Give join sem if is joinable */
aos_sem_signal(&(ptcb->join_sem));
} else if (ptcb->attr.detachstate == PTHREAD_CREATE_DETACHED) {
/* Free the join sem */
aos_sem_free(&(ptcb->join_sem));
/* The user/kernel task stack and task tcb should be freed by kernel, here we
* only free the ptcb.
*/
ptcb->magic = 0;
free(ptcb);
} else {
;
}
/* Exit the task, never return. */
aos_task_exit(0);
}
static void start_pthread(void *arg)
{
pthread_tcb_t *ptcb = arg;
pthread_exit(ptcb->thread_entry(ptcb->thread_para));
}
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine)(void *), void *arg)
{
int ret = 0;
pthread_tcb_t *ptcb = NULL; /* The ptcb of new thread. */
pthread_tcb_t *ptcb_c = NULL; /* The ptcb of current thread. */
int kpolicy = 0;
int kpriority = 0;
if ((thread == NULL) || ((attr != NULL) && (attr->flag != PTHREAD_DYN_INIT))
|| (start_routine == NULL)) {
return EINVAL;
}
/* Init the pthread handle as NULL. */
*thread = NULL;
/* Create ptcb for the new thread. */
ptcb = (pthread_tcb_t *)malloc(sizeof(pthread_tcb_t));
if (ptcb == NULL) {
return ENOMEM;
}
memset(ptcb, 0, sizeof(pthread_tcb_t));
ptcb->magic = PTHREAD_TCB_MAGIC;
if (attr != NULL) {
ptcb->attr = *attr;
if (attr->inheritsched == PTHREAD_INHERIT_SCHED) {
ptcb_c = __pthread_get_tcb(pthread_self());
if (ptcb_c != NULL) {
ptcb->attr = ptcb_c->attr;
}
}
} else {
ret = pthread_attr_init(&(ptcb->attr));
if (ret != 0)
goto out3;
}
/* Init joinable semaphore. */
if (ptcb->attr.detachstate == PTHREAD_CREATE_JOINABLE) {
ret = aos_sem_new(&(ptcb->join_sem), 0);
if (ret != 0) {
ret = -1;
goto out3;
}
}
ptcb->thread_entry = start_routine;
ptcb->thread_para = arg;
strncpy(ptcb->thread_name, "posix_thread", PTHREAD_NAME_MAX_LEN);
kpolicy = aos_task_sched_policy_get_default();
kpriority = sched_priority_posix2rhino(kpolicy, ptcb->attr.sched_priority);
if (kpriority < 0) {
ret = -1;
goto out2;
}
ret = aos_task_create(&(ptcb->task), ptcb->thread_name, start_pthread,
ptcb, NULL, ptcb->attr.stacksize, kpriority, 0);
if (ret != 0) {
ret = -1;
goto out2;
}
/* Store ptcb in kernel task tcb, and get it back when call pthread_self. */
ret = aos_task_ptcb_set(&(ptcb->task), ptcb);
if (ret != 0) {
ret = -1;
goto out1;
}
/* Success. */
*thread = ptcb;
ret = aos_task_resume(&(ptcb->task));
if (ret != 0) {
ret = -1;
*thread = NULL;
goto out1;
}
return 0;
out1:
aos_task_delete(&(ptcb->task));
out2:
aos_sem_free(&(ptcb->join_sem));
out3:
if (ptcb != NULL) {
ptcb->magic = 0;
free(ptcb);
}
return ret;
}
int pthread_detach(pthread_t thread)
{
int ret = 0;
pthread_tcb_t *ptcb = NULL;
if (thread == NULL) {
return EINVAL;
}
ptcb = __pthread_get_tcb(thread);
if (ptcb == NULL) {
return EINVAL;
}
if (ptcb->attr.detachstate == PTHREAD_CREATE_DETACHED) {
return EINVAL;
} else {
ret = pthread_mutex_lock(&g_pthread_lock);
if (ret != 0) {
return EAGAIN;
}
ptcb->attr.detachstate = PTHREAD_CREATE_DETACHED;
pthread_mutex_unlock(&g_pthread_lock);
}
return 0;
}
int pthread_timedjoin_np(pthread_t thread, void **retval, const struct timespec *abstime)
{
int ret = 0;
pthread_tcb_t *ptcb = NULL;
struct timeval time_now = {0};
uint64_t msec = AOS_WAIT_FOREVER;
uint64_t nsec = 0;
int64_t sec = 0;
if (thread == NULL) {
return EINVAL;
}
ptcb = __pthread_get_tcb(thread);
if (ptcb == NULL) {
return EINVAL;
}
if (ptcb == pthread_self()) {
return EINVAL;
}
if (ptcb->attr.detachstate != PTHREAD_CREATE_JOINABLE) {
return EINVAL;
}
/* Get the time to wait. */
if (abstime != NULL) {
gettimeofday(&time_now, NULL);
if ((time_now.tv_usec * 1000) > abstime->tv_nsec) {
nsec = abstime->tv_nsec + 1000000000 - time_now.tv_usec * 1000;
sec = abstime->tv_sec - time_now.tv_sec - 1;
} else {
nsec = abstime->tv_nsec - time_now.tv_usec * 1000;
sec = abstime->tv_sec - time_now.tv_sec;
}
if (sec < 0) {
return EINVAL;
}
msec = sec * 1000 + nsec / 1000000;
}
ret = aos_sem_wait(&(ptcb->join_sem), msec);
if (ret == 0) {
if (retval != NULL) {
*retval = ptcb->return_value;
}
/* The task tcb struct and user/kernel stack should be freed by kernel when task delete */
aos_sem_free(&(ptcb->join_sem));
ptcb->magic = 0;
free(ptcb);
} else if (ret == -ETIMEDOUT) {
return ETIMEDOUT;
} else {
return -1;
}
return 0;
}
int pthread_join(pthread_t thread, void **retval)
{
return pthread_timedjoin_np(thread, retval, NULL);
}
int pthread_cancel(pthread_t thread)
{
return ENOSYS;
}
void pthread_testcancel(void)
{
return;
}
int pthread_setcancelstate(int state, int *oldstate)
{
return ENOSYS;
}
int pthread_setcanceltype(int type, int *oldtype)
{
return ENOSYS;
}
int pthread_kill(pthread_t thread, int sig)
{
return ENOSYS;
}
int pthread_equal(pthread_t t1, pthread_t t2)
{
return (int)(t1 == t2);
}
int pthread_getschedparam(pthread_t thread, int *policy, struct sched_param *param)
{
int ret = 0;
pthread_tcb_t *ptcb = NULL;
uint8_t priority = 0;
unsigned int slice = 0;
int kpolicy = 0;
if (policy == NULL || param == NULL) {
return EINVAL;
}
ptcb = __pthread_get_tcb(thread);
if (ptcb == NULL) {
return ESRCH;
}
ret = aos_task_sched_policy_get(&(ptcb->task), (uint8_t *)&kpolicy);
if (ret != 0) {
return EINVAL;
}
ret = aos_task_pri_get(&(ptcb->task), &priority);
if (ret != 0){
return EINVAL;
}
/* Slice should be 0 if that is not RR policy. */
ret = aos_task_time_slice_get(&(ptcb->task), (uint32_t *) &slice);
if (ret != 0) {
return EINVAL;
}
*policy = sched_policy_rhino2posix(kpolicy);
param->sched_priority = sched_priority_rhino2posix(kpolicy, priority);
param->slice = slice;
return 0;
}
int pthread_setschedparam(pthread_t thread, int policy, const struct sched_param *param)
{
int ret = 0;
pthread_tcb_t *ptcb = NULL;
uint8_t priority = 0;
int kpolicy = 0;
ptcb = __pthread_get_tcb(thread);
if (ptcb == NULL) {
return EINVAL;
}
kpolicy = sched_policy_posix2rhino(policy);
if (kpolicy == -1) {
return EINVAL;
}
if ((param == NULL) || (param->sched_priority < aos_sched_get_priority_min(kpolicy))
|| (param->sched_priority > aos_sched_get_priority_max(kpolicy))) {
return EINVAL;
}
priority = sched_priority_posix2rhino(kpolicy, param->sched_priority);
/* Change the policy and priority of the thread */
ret = aos_task_sched_policy_set(&(ptcb->task), kpolicy, priority);
if ((ret == 0) && (kpolicy == KSCHED_RR)) {
ret = aos_task_time_slice_set(&(ptcb->task), param->slice);
}
if (ret != 0) {
return -1;
}
ptcb->attr.sched_priority = param->sched_priority;
ptcb->attr.sched_slice = param->slice;
return 0;
}
pthread_t pthread_self(void)
{
int ret = 0;
pthread_tcb_t *ptcb = NULL;
aos_task_t task;
task = aos_task_self();
aos_task_ptcb_get(&task, (void **)&ptcb);
if (ptcb == NULL) {
/* Create ptcb for native task in case that call pthread_self */
ptcb = (pthread_tcb_t *)malloc(sizeof(pthread_tcb_t));
if (ptcb == NULL) {
return NULL;
}
memset(ptcb, 0, sizeof(pthread_tcb_t));
ptcb->magic = PTHREAD_TCB_MAGIC;
ptcb->task = task;
/* Set ptcb in task tcb. */
ret = aos_task_ptcb_set(&(ptcb->task), ptcb);
if (ret != 0) {
ptcb->magic = 0;
free(ptcb);
return NULL;
}
}
return ptcb;
}
int pthread_setschedprio(pthread_t thread, int prio)
{
int ret = 0;
pthread_tcb_t * ptcb = NULL;
uint8_t old_prio = 0;
int kpolicy = 0;
int kpriority = 0;
ptcb = __pthread_get_tcb(thread);
if (ptcb == NULL) {
return EINVAL;
}
ret = aos_task_sched_policy_get(&(ptcb->task), (uint8_t *)&kpolicy);
if (ret != 0) {
return -1;
}
kpriority = sched_priority_posix2rhino(kpolicy, prio);
if (kpriority < 0) {
return -1;
}
ret = aos_task_pri_change(&(ptcb->task), kpriority, &old_prio);
if (ret != 0) {
return -1;
}
return 0;
}
int pthread_once(pthread_once_t *once_control, void (*init_routine)(void))
{
int ret = 0;
ret = pthread_mutex_lock(&g_pthread_lock);
if (ret != 0) {
return EAGAIN;
}
if (*once_control == PTHREAD_ONCE_INIT)
{
*once_control = !PTHREAD_ONCE_INIT;
pthread_mutex_unlock(&g_pthread_lock);
init_routine ();
return 0;
}
pthread_mutex_unlock(&g_pthread_lock);
return 0;
}
int pthread_getcpuclockid(pthread_t thread, clockid_t *clock_id)
{
if ((thread == NULL) || (clock_id == NULL)) {
return EINVAL;
}
*clock_id = CLOCK_MONOTONIC;
return 0;
}
int pthread_getconcurrency(void)
{
/* User thread and kernel thread are one-to-one correspondence in AliOS Things,
so the concurrency is 0 */
return 0;
}
int pthread_setconcurrency(int new_level)
{
/* User thread and kernel thread are one-to-one correspondence in AliOS Things,
so the concurrency can not be set */
return ENOSYS;
}
int pthread_setname_np(pthread_t thread, const char *name)
{
pthread_tcb_t *ptcb = NULL;
if ((thread == NULL) || (name == NULL)) {
return EINVAL;
}
ptcb = __pthread_get_tcb(thread);
if (ptcb == NULL) {
return EINVAL;
}
/* Truncate the name if it's too long. */
strncpy(ptcb->thread_name, name, PTHREAD_NAME_MAX_LEN);
if (strlen(name) > PTHREAD_NAME_MAX_LEN) {
return ERANGE;
}
return 0;
}
int pthread_getname_np(pthread_t thread, char *name, size_t len)
{
pthread_tcb_t *ptcb = NULL;
if ((thread == NULL) || (name == NULL)) {
return EINVAL;
}
if (len < PTHREAD_NAME_MAX_LEN) {
return ERANGE;
}
ptcb = __pthread_get_tcb(thread);
if (ptcb == NULL) {
return EINVAL;
}
memset(name, 0, len);
strncpy(name, ptcb->thread_name, len);
return 0;
}
| YifuLiu/AliOS-Things | components/posix/src/pthread.c | C | apache-2.0 | 13,478 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <sched.h>
#include "internal/pthread.h"
int pthread_attr_init(pthread_attr_t *attr)
{
if (attr == NULL) {
return EINVAL;
}
memset(attr, 0, sizeof(pthread_attr_t));
attr->stacksize = PTHREAD_DEFAULT_STACK_SIZE;
attr->sched_priority = PTHREAD_DEFAULT_PRIORITY;
attr->sched_slice = PTHREAD_DEFAULT_SLICE;
attr->detachstate = PTHREAD_CREATE_JOINABLE;
attr->contentionscope = PTHREAD_SCOPE_SYSTEM;
attr->inheritsched = PTHREAD_EXPLICIT_SCHED;
attr->guardsize = PTHREAD_DEFAULT_GUARD_SIZE;
attr->stackaddr = NULL;
attr->flag = PTHREAD_DYN_INIT;
return 0;
}
int pthread_attr_destroy(pthread_attr_t *attr)
{
if (attr == NULL) {
return EINVAL;
}
memset(attr, 0, sizeof(pthread_attr_t));
return 0;
}
int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate)
{
if ((attr == NULL) || ((detachstate != PTHREAD_CREATE_DETACHED) &&
(detachstate != PTHREAD_CREATE_JOINABLE))) {
return EINVAL;
}
attr->detachstate = detachstate;
return 0;
}
int pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachstate)
{
if ((attr == NULL) || (detachstate == NULL)) {
return EINVAL;
}
*detachstate = attr->detachstate;
return 0;
}
int pthread_attr_setschedpolicy(pthread_attr_t *attr, int policy)
{
if ((attr == NULL) || ((policy < SCHED_OTHER) || (policy > SCHED_RR))) {
return EINVAL;
}
attr->schedpolicy = policy;
return 0;
}
int pthread_attr_getschedpolicy(const pthread_attr_t *attr, int *policy)
{
if ((attr == NULL) || (policy == NULL)) {
return EINVAL;
}
*policy = attr->schedpolicy;
return 0;
}
int pthread_attr_setschedparam(pthread_attr_t *attr, const struct sched_param *param)
{
if ((attr == NULL) || (param == NULL)) {
return EINVAL;
}
attr->sched_priority = param->sched_priority;
attr->sched_slice = param->slice;
return 0;
}
int pthread_attr_getschedparam(const pthread_attr_t *attr, struct sched_param *param)
{
if ((attr == NULL) || (param == NULL)) {
return EINVAL;
}
param->sched_priority = attr->sched_priority;
param->slice = attr->sched_slice;
return 0;
}
int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize)
{
if ((attr == NULL) || (stacksize <= 0)) {
return EINVAL;
}
attr->stacksize = stacksize;
return 0;
}
int pthread_attr_getstacksize(const pthread_attr_t *attr, size_t *stacksize)
{
if ((attr == NULL) || (stacksize == NULL)) {
return EINVAL;
}
*stacksize = attr->stacksize;
return 0;
}
int pthread_attr_setstackaddr(pthread_attr_t *attr, void *stackaddr)
{
if ((attr == NULL) || (stackaddr == NULL)) {
return EINVAL;
}
attr->stackaddr = stackaddr;
return 0;
}
int pthread_attr_getstackaddr(const pthread_attr_t *attr, void **stackaddr)
{
if ((attr == NULL) || (stackaddr == NULL)) {
return EINVAL;
}
*stackaddr = attr->stackaddr;
return 0;
}
int pthread_attr_setstack(pthread_attr_t *attr, void *stackaddr, size_t stacksize)
{
if ((attr == NULL) || (stackaddr == NULL) || (stacksize <= 0)) {
return EINVAL;
}
attr->stackaddr = stackaddr;
attr->stacksize = stacksize;
return 0;
}
int pthread_attr_getstack(const pthread_attr_t *attr, void **stackaddr, size_t *stacksize)
{
if ((attr == NULL) || (stackaddr == NULL) || (stacksize == NULL)) {
return EINVAL;
}
*stackaddr = attr->stackaddr;
*stacksize = attr->stacksize;
return 0;
}
int pthread_attr_getinheritsched(const pthread_attr_t *restrict attr, int *restrict inheritsched)
{
if ((attr == NULL) || (inheritsched == NULL)) {
return EINVAL;
}
*inheritsched = attr->inheritsched;
return 0;
}
int pthread_attr_setinheritsched(pthread_attr_t *attr, int inheritsched)
{
if ((attr == NULL) || (inheritsched < PTHREAD_INHERIT_SCHED) ||
(inheritsched > PTHREAD_EXPLICIT_SCHED)) {
return EINVAL;
}
attr->inheritsched = inheritsched;
return 0;
}
int pthread_attr_setguardsize(pthread_attr_t *attr, size_t guardsize)
{
/* guardsize stack protection is not supported by kernel */
return ENOSYS;
}
int pthread_attr_getguardsize(const pthread_attr_t *attr, size_t *guardsize)
{
/* guardsize stack protection is not supported by kernel */
return ENOSYS;
}
int pthread_attr_getscope(const pthread_attr_t *restrict attr, int *restrict contentionscope)
{
if ((attr == NULL) || (contentionscope == NULL)) {
return EINVAL;
}
*contentionscope = attr->contentionscope;
return 0;
}
int pthread_attr_setscope(pthread_attr_t *attr, int contentionscope)
{
if ((attr == NULL) ||
((contentionscope != PTHREAD_SCOPE_PROCESS) && (contentionscope != PTHREAD_SCOPE_SYSTEM))) {
return EINVAL;
}
attr->contentionscope = contentionscope;
return 0;
}
| YifuLiu/AliOS-Things | components/posix/src/pthread_attr.c | C | apache-2.0 | 5,295 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <pthread.h>
#include <aos/kernel.h>
#include "internal/pthread.h"
int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr)
{
int ret = 0;
if (cond == NULL) {
return EINVAL;
}
memset(cond, 0, sizeof(pthread_cond_t));
ret = aos_mutex_new((aos_mutex_t*)(&(cond->lock)));
if (ret != 0) {
return EAGAIN;
}
ret = aos_sem_new((aos_sem_t*)(&(cond->wait_sem)), 0);
if (ret != 0) {
aos_mutex_free((aos_mutex_t*)(&(cond->lock)));
return EAGAIN;
}
ret = aos_sem_new((aos_sem_t*)(&(cond->wait_done)), 0);
if (ret != 0) {
aos_mutex_free((aos_mutex_t*)(&(cond->lock)));
aos_sem_free((aos_sem_t*)(&(cond->wait_sem)));
return EAGAIN;
}
cond->waiting = cond->signals = 0;
cond->flag = PTHREAD_DYN_INIT;
if (attr != NULL) {
cond->attr = *attr;
}
return 0;
}
int pthread_cond_destroy(pthread_cond_t *cond)
{
if (cond == NULL) {
return EINVAL;
}
aos_mutex_free((aos_mutex_t*)(&(cond->lock)));
aos_sem_free((aos_sem_t*)(&(cond->wait_sem)));
aos_sem_free((aos_sem_t*)(&(cond->wait_done)));
return 0;
}
int pthread_cond_broadcast(pthread_cond_t *cond)
{
int i = 0;
int num_waiting = 0;
if (cond == NULL)
return EINVAL;
if (cond->flag != PTHREAD_DYN_INIT)
return 0;
/* If there are waiting threads not already signalled, then
* signal the condition and wait for the thread to respond.
*/
aos_mutex_lock((aos_mutex_t*)(&(cond->lock)), AOS_WAIT_FOREVER);
if (cond->waiting > cond->signals) {
num_waiting = (cond->waiting - cond->signals);
cond->signals = cond->waiting;
for (i = 0; i < num_waiting; ++i) {
aos_sem_signal((aos_sem_t*)(&(cond->wait_sem)));
}
/* Now all released threads are blocked here, waiting for us.
* Collect them all (and win fabulous prizes!) :-)
*/
aos_mutex_unlock((aos_mutex_t*)(&(cond->lock)));
for (i = 0; i < num_waiting; ++i) {
aos_sem_wait((aos_sem_t*)(&(cond->wait_done)), AOS_WAIT_FOREVER);
}
} else {
aos_mutex_unlock((aos_mutex_t*)(&(cond->lock)));
}
return 0;
}
int pthread_cond_signal(pthread_cond_t *cond)
{
if (cond == NULL)
return EINVAL;
if (cond->flag != PTHREAD_DYN_INIT)
return 0;
/* If there are waiting threads not already signalled, then
* signal the condition and wait for the thread to respond.
*/
aos_mutex_lock((aos_mutex_t*)(&(cond->lock)), AOS_WAIT_FOREVER);
if ( cond->waiting > cond->signals ) {
(cond->signals)++;
aos_sem_signal((aos_sem_t*)(&(cond->wait_sem)));
aos_mutex_unlock((aos_mutex_t*)(&(cond->lock)));
aos_sem_wait((aos_sem_t*)(&(cond->wait_done)), AOS_WAIT_FOREVER);
} else {
aos_mutex_unlock((aos_mutex_t*)(&(cond->lock)));
}
return 0;
}
static int pthread_cond_timedwait_ms(pthread_cond_t *cond, pthread_mutex_t *mutex, int64_t ms)
{
int ret = 0;
if (cond->flag == PTHREAD_STATIC_INIT) {
/* The cond is inited by PTHREAD_COND_INITIALIZER*/
ret = pthread_cond_init(cond, NULL);
if (ret != 0)
return ret;
}
/* Obtain the protection mutex, and increment the number of waiters.
* This allows the signal mechanism to only perform a signal if there
* are waiting threads.
*/
aos_mutex_lock((aos_mutex_t*)(&(cond->lock)), AOS_WAIT_FOREVER);
(cond->waiting)++;
aos_mutex_unlock((aos_mutex_t*)(&(cond->lock)));
/* Unlock the mutex, as is required by condition variable semantics */
aos_mutex_unlock((aos_mutex_t*)(&(mutex->mutex)));
/* Wait for a signal */
ret = aos_sem_wait((aos_sem_t*)(&(cond->wait_sem)), ms);
/* Let the signaler know we have completed the wait, otherwise
* the signaler can race ahead and get the condition semaphore
* if we are stopped between the mutex unlock and semaphore wait,
* giving a deadlock.
*/
aos_mutex_lock((aos_mutex_t*)(&(cond->lock)), AOS_WAIT_FOREVER);
if (ret == -ETIMEDOUT) {
ret = ETIMEDOUT;
}
if (cond->signals > 0) {
/* If we timed out, we need to eat a condition signal */
if (ret == ETIMEDOUT) {
aos_sem_wait((aos_sem_t*)(&(cond->wait_sem)), AOS_NO_WAIT);
}
/* We always notify the signal thread that we are done */
aos_sem_signal((aos_sem_t*)(&(cond->wait_done)));
/* Signal handshake complete */
(cond->signals)--;
}
(cond->waiting)--;
aos_mutex_unlock((aos_mutex_t*)(&(cond->lock)));
/* Lock the mutex, as is required by condition variable semantics */
aos_mutex_lock((aos_mutex_t*)(&(mutex->mutex)), AOS_WAIT_FOREVER);
return ret;
}
int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex,
const struct timespec *abstime)
{
int ret;
struct timeval now_tv = {0};
struct timespec now_tp = {0};
int64_t timeout_ms = 0;
if ((cond == NULL) || (mutex == NULL)) {
return EINVAL;
}
if (abstime == NULL) {
timeout_ms = AOS_WAIT_FOREVER;
} else {
if (cond->attr.clock == CLOCK_MONOTONIC) {
ret = clock_gettime(CLOCK_MONOTONIC, &now_tp);
if (ret != 0) {
return EINVAL;
}
timeout_ms = (abstime->tv_sec - now_tp.tv_sec) * 1000 +
((abstime->tv_nsec - now_tp.tv_nsec) / 1000000);
} else {
/* CLOCK_REALTIME */
gettimeofday(&now_tv, NULL);
timeout_ms = (abstime->tv_sec - now_tv.tv_sec) * 1000 +
((abstime->tv_nsec - now_tv.tv_usec * 1000) / 1000000);
}
if (timeout_ms <= 0) {
/* The absolute time has already passed. Do not need to wait. */
return ETIMEDOUT;
}
}
return pthread_cond_timedwait_ms(cond, mutex, timeout_ms);
}
int pthread_cond_timedwait_relative_np(pthread_cond_t *cond, pthread_mutex_t *mutex,
const struct timespec *reltime)
{
int64_t timeout_ms = 0;
if ((cond == NULL) || (mutex == NULL)) {
return EINVAL;
}
if (reltime == NULL) {
timeout_ms = AOS_WAIT_FOREVER;
} else {
timeout_ms = ((reltime->tv_sec) * 1000) + ((reltime->tv_nsec) / 1000000);
if (timeout_ms <= 0) {
return ETIMEDOUT;
}
}
return pthread_cond_timedwait_ms(cond, mutex, timeout_ms);
}
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
{
return pthread_cond_timedwait(cond, mutex, NULL);
}
int pthread_condattr_init(pthread_condattr_t *attr)
{
if (attr == NULL) {
return EINVAL;
}
attr->flag = PTHREAD_DYN_INIT;
attr->clock = DEFAULT_COND_CLOCK;
attr->pshared = DEFAULT_COND_SHARED;
return 0;
}
int pthread_condattr_destroy(pthread_condattr_t *attr)
{
if (attr == NULL) {
return EINVAL;
}
memset(attr, 0 ,sizeof(pthread_condattr_t));
return 0;
}
int pthread_condattr_getclock(const pthread_condattr_t *attr, clockid_t *clock_id)
{
if ((attr == NULL) || (clock_id == NULL)) {
return EINVAL;
}
*clock_id = attr->clock;
return 0;
}
int pthread_condattr_setclock(pthread_condattr_t *attr, clockid_t clock_id)
{
if (attr == NULL) {
return EINVAL;
}
if ((clock_id != CLOCK_REALTIME) && (clock_id != CLOCK_MONOTONIC)) {
return EINVAL;
}
attr->clock = clock_id;
return 0;
}
| YifuLiu/AliOS-Things | components/posix/src/pthread_cond.c | C | apache-2.0 | 7,823 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <errno.h>
#include <pthread.h>
#include <sched.h>
#include <aos/kernel.h>
#include "internal/pthread.h"
#define PTHREAD_MUTEXATTR_IS_INITED(x) do { if ((x)->flag != PTHREAD_DYN_INIT) return EINVAL; } \
while (0)
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
{
int ret = 0;
if (mutex == NULL) {
return EINVAL;
}
memset(mutex, 0, sizeof(pthread_mutex_t));
if (attr != NULL) {
mutex->attr = *attr;
}
ret = aos_mutex_new((aos_mutex_t*)(&(mutex->mutex)));
if (ret != 0) {
return -1;
}
mutex->flag = PTHREAD_DYN_INIT;
return 0;
}
int pthread_mutex_destroy(pthread_mutex_t *mutex)
{
if (mutex == NULL) {
return EINVAL;
}
if (mutex->flag == PTHREAD_STATIC_INIT) {
memset(mutex, 0, sizeof(pthread_mutex_t));
return 0;
} else if (mutex->flag == PTHREAD_DYN_INIT) {
aos_mutex_free((aos_mutex_t*)(&(mutex->mutex)));
memset(mutex, 0, sizeof(pthread_mutex_t));
return 0;
} else {
return EINVAL;
}
}
int pthread_mutex_lock(pthread_mutex_t *mutex)
{
int ret = 0;
if (mutex == NULL) {
return EINVAL;
}
/* The mutex is initted by PTHREAD_MUTEX_INITIALIZER */
if (mutex->flag == PTHREAD_STATIC_INIT) {
ret = pthread_mutex_init(mutex, NULL);
if (ret != 0) {
return -1;
}
}
ret = aos_mutex_lock((aos_mutex_t*)(&(mutex->mutex)), AOS_WAIT_FOREVER);
if (ret != 0) {
return -1;
}
return 0;
}
int pthread_mutex_unlock(pthread_mutex_t *mutex)
{
int ret = 0;
if (mutex == NULL) {
return EINVAL;
}
if (mutex->flag != PTHREAD_DYN_INIT) {
return -1;
}
ret = aos_mutex_unlock((aos_mutex_t*)(&(mutex->mutex)));
if (ret != 0) {
return -1;
}
return 0;
}
int pthread_mutex_trylock(pthread_mutex_t *mutex)
{
int ret = 0;
if (mutex == NULL) {
return EINVAL;
}
/* The mutex is initted by PTHREAD_MUTEX_INITIALIZER */
if (mutex->flag == PTHREAD_STATIC_INIT) {
ret = pthread_mutex_init(mutex, NULL);
if (ret != 0) {
return -1;
}
}
ret = aos_mutex_lock((aos_mutex_t*)(&(mutex->mutex)), AOS_NO_WAIT);
if (ret == -ETIMEDOUT) {
return EBUSY;
} else if (ret != 0) {
return -1;
} else {
return 0;
}
}
int pthread_mutex_timedlock(pthread_mutex_t *mutex, const struct timespec *at)
{
int ret = 0;
if (mutex == NULL) {
return EINVAL;
}
/* The mutex is initted by PTHREAD_MUTEX_INITIALIZER */
if (mutex->flag == PTHREAD_STATIC_INIT) {
ret = pthread_mutex_init(mutex, NULL);
if (ret != 0) {
return -1;
}
}
ret = pthread_mutex_trylock(mutex);
if (ret != EBUSY) {
return ret;
}
unsigned int timeout = at->tv_sec * 1000 + at->tv_nsec / 1000;
ret = aos_mutex_lock((aos_mutex_t*)(&(mutex->mutex)), timeout);
if (ret != 0) {
return -1;
}
return 0;
}
int pthread_mutex_getprioceiling(const pthread_mutex_t *mutex, int *prioceiling)
{
if ((mutex == NULL) || (prioceiling == NULL)) {
return EINVAL;
}
PTHREAD_MUTEXATTR_IS_INITED(&(mutex->attr));
*prioceiling = mutex->attr.prioceiling;
return 0;
}
int pthread_mutex_setprioceiling(pthread_mutex_t *mutex, int prioceiling,
int *old_ceiling)
{
if (mutex == NULL) {
return EINVAL;
}
if ((prioceiling < sched_get_priority_min(SCHED_FIFO)) ||
(prioceiling > sched_get_priority_max(SCHED_FIFO))) {
return EINVAL;
}
PTHREAD_MUTEXATTR_IS_INITED(&(mutex->attr));
if (old_ceiling != NULL) {
*old_ceiling = mutex->attr.prioceiling;
}
mutex->attr.prioceiling = prioceiling;
return 0;
}
int pthread_mutexattr_init(pthread_mutexattr_t *attr)
{
if (attr == NULL) {
return EINVAL;
}
attr->flag = PTHREAD_DYN_INIT;
attr->type = PTHREAD_MUTEX_DEFAULT;
attr->protocol = DEFAULT_MUTEX_PROCOCOL;
attr->prioceiling = DEFAULT_MUTEX_PRIOCEILING;
attr->pshared = DEFAULT_MUTEX_PSHARED;
return 0;
}
int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
{
if (attr == NULL) {
return EINVAL;
}
memset(attr, 0, sizeof(pthread_mutexattr_t));
return 0;
}
int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
{
if ((attr == NULL) || (type == NULL)) {
return EINVAL;
}
PTHREAD_MUTEXATTR_IS_INITED(attr);
*type = attr->type;
return 0;
}
int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
{
if (attr == NULL) {
return EINVAL;
}
if ((type < PTHREAD_MUTEX_NORMAL) || (type > PTHREAD_MUTEX_ERRORCHECK)) {
return EINVAL;
}
PTHREAD_MUTEXATTR_IS_INITED(attr);
attr->type = type;
return 0;
}
int pthread_mutexattr_getprotocol(const pthread_mutexattr_t *attr, int *protocol)
{
if ((attr == NULL) || (protocol == NULL)) {
return EINVAL;
}
PTHREAD_MUTEXATTR_IS_INITED(attr);
*protocol = attr->protocol;
return 0;
}
int pthread_mutexattr_setprotocol(pthread_mutexattr_t *attr, int protocol)
{
if (attr == NULL) {
return EINVAL;
}
if ((protocol < PTHREAD_PRIO_NONE) || (protocol > PTHREAD_PRIO_PROTECT)) {
return EINVAL;
}
PTHREAD_MUTEXATTR_IS_INITED(attr);
attr->protocol = protocol;
return 0;
}
int pthread_mutexattr_getprioceiling(const pthread_mutexattr_t *attr,
int *prioceiling)
{
if ((attr == NULL) || (prioceiling == NULL)) {
return EINVAL;
}
PTHREAD_MUTEXATTR_IS_INITED(attr);
*prioceiling = attr->prioceiling;
return 0;
}
int pthread_mutexattr_setprioceiling(pthread_mutexattr_t *attr, int prioceiling)
{
if (attr == NULL) {
return EINVAL;
}
if ((prioceiling < sched_get_priority_min(SCHED_FIFO)) ||
(prioceiling > sched_get_priority_max(SCHED_FIFO))) {
return EINVAL;
}
PTHREAD_MUTEXATTR_IS_INITED(attr);
attr->prioceiling = prioceiling;
return 0;
}
int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
{
if (attr == NULL) {
return EINVAL;
}
if ((pshared < PTHREAD_PROCESS_PRIVATE) || (pshared > PTHREAD_PROCESS_SHARED)) {
return EINVAL;
}
PTHREAD_MUTEXATTR_IS_INITED(attr);
attr->pshared = pshared;
return 0;
}
int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
{
if ((attr == NULL) || (pshared == NULL)) {
return EINVAL;
}
PTHREAD_MUTEXATTR_IS_INITED(attr);
*pshared = attr->pshared;
return 0;
}
| YifuLiu/AliOS-Things | components/posix/src/pthread_mutex.c | C | apache-2.0 | 6,933 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <stdlib.h>
#include <string.h>
#include <aos/errno.h>
#include "internal/pthread.h"
typedef struct key_value {
pthread_t thread;
const uint32_t *value;
} key_value_t;
typedef struct pthread_key_value {
key_value_t key_value;
struct pthread_key_value *next;
} pthread_key_value_t;
typedef struct pthread_key_value_head {
void (*fun)(void *);
pthread_key_value_t *next;
} pthread_key_value_head_t;
typedef struct pthread_key_list_s {
pthread_key_t key_num;
pthread_key_value_head_t head;
struct pthread_key_list_s *next;
} pthread_key_list_t;
pthread_key_list_t pthread_key_list_head;
pthread_mutex_t g_pthread_key_lock = PTHREAD_MUTEX_INITIALIZER;
void pthread_tsd_dtors(void)
{
pthread_key_list_t *pthread_key_list_s_c = NULL;
pthread_key_value_t **key_value_s_prev = NULL;
pthread_key_value_t *key_value_s_cur = NULL;
pthread_key_value_t *key_value_s_del = NULL;
pthread_mutex_lock(&g_pthread_key_lock);
pthread_key_list_s_c = &pthread_key_list_head;
while (pthread_key_list_s_c != NULL) {
key_value_s_cur = pthread_key_list_s_c->head.next;
if (key_value_s_cur == NULL) {
pthread_key_list_s_c = pthread_key_list_s_c->next;
continue;
}
key_value_s_prev = &pthread_key_list_s_c->head.next;
while (key_value_s_cur != NULL) {
if (key_value_s_cur->key_value.thread == pthread_self()) {
if (pthread_key_list_s_c->head.fun != NULL) {
pthread_key_list_s_c->head.fun((void *)key_value_s_cur->key_value.value);
}
key_value_s_del = key_value_s_cur;
*key_value_s_prev = key_value_s_cur->next;
key_value_s_cur = key_value_s_cur->next;
free(key_value_s_del);
continue;
}
key_value_s_prev = &key_value_s_cur->next;
key_value_s_cur = key_value_s_cur->next;
}
pthread_key_list_s_c = pthread_key_list_s_c->next;
}
pthread_mutex_unlock(&g_pthread_key_lock);
}
int pthread_key_create(pthread_key_t *key, void (*destructor)(void*))
{
pthread_key_list_t *pthread_key_list_s_c = NULL;
pthread_key_list_t *pthread_key_list_s_l = NULL;
if (key == NULL) {
return EINVAL;
}
pthread_mutex_lock(&g_pthread_key_lock);
/* if the key list is empty int pthread_key_list_head to save the first key */
if (pthread_key_list_head.key_num == 0) {
pthread_key_list_head.key_num = 1;
pthread_key_list_head.head.fun = destructor;
*key = pthread_key_list_head.key_num;
} else {
/* if the key list is not empty find the last key and add key */
/* find the last key */
pthread_key_list_s_c = pthread_key_list_head.next;
pthread_key_list_s_l = &pthread_key_list_head;
while (pthread_key_list_s_c != NULL) {
pthread_key_list_s_l = pthread_key_list_s_c;
pthread_key_list_s_c = pthread_key_list_s_c->next;
}
/* malloc the new key */
pthread_key_list_s_c = (pthread_key_list_t *)malloc(sizeof(pthread_key_list_t));
if (pthread_key_list_s_c == NULL) {
pthread_mutex_unlock(&g_pthread_key_lock);
return -1;
}
/* init the new key */
memset(pthread_key_list_s_c, 0, sizeof(pthread_key_list_t));
/* insert the key to the end of list */
pthread_key_list_s_c->key_num = pthread_key_list_s_l->key_num + 1;
pthread_key_list_s_c->head.fun = destructor;
pthread_key_list_s_l->next = pthread_key_list_s_c;
/* update the key value */
*key = pthread_key_list_s_c->key_num;
}
pthread_mutex_unlock(&g_pthread_key_lock);
return 0;
}
int pthread_setspecific(pthread_key_t key, const void *value)
{
pthread_key_list_t *pthread_key_list_s_c = NULL;
pthread_key_value_t *key_value_s_o = NULL;
pthread_key_value_t *key_value_s = NULL;
pthread_key_value_t *key_value_s_c = NULL;
pthread_key_value_t *key_value_s_l = NULL;
int list_flag = 0;
int value_flag = 0;
pthread_t self = pthread_self();
pthread_mutex_lock(&g_pthread_key_lock);
/* find the key in list */
pthread_key_list_s_c = &pthread_key_list_head;
while (pthread_key_list_s_c != NULL) {
if (pthread_key_list_s_c->key_num == key){
list_flag = 1;
key_value_s_o = pthread_key_list_s_c->head.next;
break;
}
pthread_key_list_s_c = pthread_key_list_s_c->next;
}
/* if can not find the key in list, return error */
if (list_flag == 0) {
pthread_mutex_unlock(&g_pthread_key_lock);
return EINVAL;
}
/* if no value store in the key, create new pthread_key_value_t to save the value */
if (key_value_s_o == NULL) {
key_value_s = (pthread_key_value_t *)malloc(sizeof(pthread_key_value_t));
if (key_value_s == NULL) {
pthread_mutex_unlock(&g_pthread_key_lock);;
return ENOMEM;
}
memset(key_value_s, 0, sizeof(pthread_key_value_t));
/* save the thread id and value */
key_value_s->key_value.value = (uint32_t*)value;
key_value_s->key_value.thread = self;
key_value_s->next = NULL;
/* and pthread_key_value_t to value list */
pthread_key_list_s_c->head.next = key_value_s;
} else {
/* if value store in the key, find the last value and add the new value */
/* sreach the value list to find if same thread had save the value */
key_value_s_c = key_value_s_o;
while (key_value_s_c != NULL) {
/* if the same thread had save the value update the value */
if (key_value_s_c->key_value.thread == self) {
key_value_s_c->key_value.value = (uint32_t*)value;
value_flag = 1;
break;
}
key_value_s_l = key_value_s_c;
key_value_s_c = key_value_s_c->next;
}
/* if no same thread had save the value before create new pthread_key_value_t */
if (value_flag == 0) {
key_value_s = (pthread_key_value_t *)malloc(sizeof(pthread_key_value_t));
if (key_value_s == NULL) {
pthread_mutex_unlock(&g_pthread_key_lock);;
return ENOMEM;
}
memset(key_value_s, 0, sizeof(pthread_key_value_t));
/* save current value to pthread_key_value_t */
key_value_s->next = key_value_s_l->next;
key_value_s->key_value.value = (uint32_t*)value;
key_value_s->key_value.thread = self;
/* add the value to the list */
key_value_s_l->next = key_value_s;
}
}
pthread_mutex_unlock(&g_pthread_key_lock);
return 0;
}
void *pthread_getspecific(pthread_key_t key)
{
pthread_key_list_t *pthread_key_list_s_c = NULL;
pthread_key_value_t *key_value_s_o = NULL;
pthread_key_value_t *key_value_s_c = NULL;
int list_flag = 0;
pthread_mutex_lock(&g_pthread_key_lock);
/* find the key in list */
pthread_key_list_s_c = &pthread_key_list_head;
while (pthread_key_list_s_c != NULL) {
if (pthread_key_list_s_c->key_num == key){
list_flag = 1;
key_value_s_o = pthread_key_list_s_c->head.next;
break;
}
pthread_key_list_s_c = pthread_key_list_s_c->next;
}
/* if can not find the key in list, or no value store in the key, return NULL */
if ((list_flag == 0) || (key_value_s_o == NULL)) {
pthread_mutex_unlock(&g_pthread_key_lock);
return NULL;
}
/* search the value list to find the value current thread saved */
key_value_s_c = key_value_s_o;
while (key_value_s_c != NULL) {
if (key_value_s_c->key_value.thread == pthread_self()) {
pthread_mutex_unlock(&g_pthread_key_lock);
return (void *)key_value_s_c->key_value.value;
}
key_value_s_c = key_value_s_c->next;
}
/* if can not find the value current thread saved return NULL */
pthread_mutex_unlock(&g_pthread_key_lock);
return NULL;
}
int pthread_key_delete(pthread_key_t key)
{
pthread_key_list_t *pthread_key_list_s_c = NULL;
pthread_key_list_t *pthread_key_list_s_l = NULL;
pthread_key_value_t *key_value_s_o = NULL;
pthread_key_value_t *key_value_s_c = NULL;
pthread_key_value_t *key_value_s_n = NULL;
int list_flag = 0;
pthread_mutex_lock(&g_pthread_key_lock);
/* if key saved in pthread_key_list_head */
if (pthread_key_list_head.key_num == key) {
key_value_s_c = pthread_key_list_head.head.next;
/* free the value saved in the key */
while (key_value_s_c != NULL) {
key_value_s_n = key_value_s_c->next;
free(key_value_s_c);
key_value_s_c = key_value_s_n;
}
/* set the list pointer to NULL */
pthread_key_list_head.head.next = NULL;
/* if no other key save in the list set key_num to 0 */
if (pthread_key_list_head.next == NULL) {
pthread_key_list_head.key_num = 0;
}
else /* else copy the next key to the head */
{
pthread_key_list_s_c = pthread_key_list_head.next;
pthread_key_list_head.key_num = pthread_key_list_head.next->key_num;
memcpy(&pthread_key_list_head.head, &pthread_key_list_head.next->head,
sizeof(pthread_key_value_head_t));
pthread_key_list_head.next = pthread_key_list_head.next->next;
free(pthread_key_list_s_c);
}
}
else /* if key is not saved in pthread_key_list_head, find the key in the list */
{
/* find the key in the list */
pthread_key_list_s_c = pthread_key_list_head.next;
while (pthread_key_list_s_c != NULL) {
if (pthread_key_list_s_c->key_num == key){
key_value_s_o = pthread_key_list_s_c->head.next;
if (pthread_key_list_s_l == NULL) {
pthread_key_list_head.next = pthread_key_list_s_c->next;
} else {
pthread_key_list_s_l->next = pthread_key_list_s_c->next;
}
free(pthread_key_list_s_c);
list_flag = 1;
break;
}
pthread_key_list_s_l = pthread_key_list_s_c;
pthread_key_list_s_c = pthread_key_list_s_c->next;
}
/* if can not find the key in list return error */
if (list_flag == 0) {
pthread_mutex_unlock(&g_pthread_key_lock);
return EINVAL;
}
/* if no value saved in the key return */
if (key_value_s_o == NULL) {
pthread_mutex_unlock(&g_pthread_key_lock);
return 0;
}
key_value_s_c = key_value_s_o;
while (key_value_s_c != NULL) {
key_value_s_n = key_value_s_c->next;
free(key_value_s_c);
key_value_s_c = key_value_s_n;
}
}
pthread_mutex_unlock(&g_pthread_key_lock);
return 0;
}
| YifuLiu/AliOS-Things | components/posix/src/pthread_tsd.c | C | apache-2.0 | 11,401 |
/*
* Copyright (C) 2020-2021 Alibaba Group Holding Limited
*/
#include <stdint.h>
#include <errno.h>
#include <time.h>
#include <pthread.h>
#include <sched.h>
#include <aos/kernel.h>
#include <aos/rhino.h>
#include "internal/pthread.h"
#include "internal/sched.h"
/* Note: pid is directly converted into pthread handle. */
static inline pthread_t _pid_to_pthread(pid_t pid)
{
if (pid == -1) {
return NULL;
}
/* todo, not surpport */
return (pthread_t)(uintptr_t)pid;
}
/* Convert pid to ptcb of the thread. */
static inline pthread_tcb_t* sched_get_ptcb(pid_t pid)
{
pthread_t thread = 0;
thread = _pid_to_pthread(pid);
if (thread == 0) {
thread = pthread_self();
}
return __pthread_get_tcb(thread);
}
int sched_yield(void)
{
aos_task_yield();
return 0;
}
int sched_setscheduler(pid_t pid, int policy, const struct sched_param *param)
{
int ret = 0;
pthread_tcb_t *ptcb = NULL;
uint8_t priority = 0;
int kpolicy = 0;
uint8_t old_policy = 0;
ptcb = sched_get_ptcb(pid);
if (ptcb == NULL) {
errno = ESRCH;
return -1;
}
kpolicy = sched_policy_posix2rhino(policy);
if (kpolicy == -1) {
errno = EINVAL;
return -1;
}
if ((param == NULL) || (param->sched_priority < aos_sched_get_priority_min(kpolicy))
|| (param->sched_priority > aos_sched_get_priority_max(kpolicy))) {
errno = EINVAL;
return -1;
}
priority = sched_priority_posix2rhino(kpolicy, param->sched_priority);
ret = aos_task_sched_policy_get(&(ptcb->task), &old_policy);
if (ret != 0) {
return -1;
}
old_policy = sched_policy_rhino2posix(old_policy);
/* Change the policy and priority of the thread */
ret = aos_task_sched_policy_set(&(ptcb->task), kpolicy, priority);
if ((ret == 0) && (kpolicy == KSCHED_RR)) {
ret = aos_task_time_slice_set(&(ptcb->task), param->slice);
}
if (ret != 0) {
return -1;
}
ptcb->attr.sched_priority = param->sched_priority;
ptcb->attr.sched_slice = param->slice;
return old_policy;
}
int sched_getscheduler(pid_t pid)
{
int ret = 0;
uint8_t policy = 0;
pthread_tcb_t *ptcb = NULL;
ptcb = sched_get_ptcb(pid);
if (ptcb == NULL) {
errno = ESRCH;
return -1;
}
ret = aos_task_sched_policy_get(&(ptcb->task), &policy);
if (ret != 0) {
errno = EINVAL;
return -1;
}
return sched_policy_rhino2posix(policy);
}
int sched_setparam(pid_t pid, const struct sched_param *param)
{
int ret = 0;
pthread_tcb_t *ptcb = NULL;
uint8_t old_priority = 0;
uint8_t priority = 0;
uint8_t kpolicy = 0;
ptcb = sched_get_ptcb(pid);
if (ptcb == NULL) {
errno = ESRCH;
return -1;
}
ret = aos_task_sched_policy_get(&(ptcb->task), &kpolicy);
if (ret != 0) {
return -1;
}
if ((param == NULL) || (param->sched_priority < aos_sched_get_priority_min(kpolicy))
|| (param->sched_priority > aos_sched_get_priority_max(kpolicy))) {
errno = EINVAL;
return -1;
}
priority = sched_priority_posix2rhino(kpolicy, param->sched_priority);
/* Change the priority of the thread. */
ret = aos_task_pri_change(&(ptcb->task), priority, &old_priority);
if (ret != 0) {
return -1;
}
ptcb->attr.sched_priority = param->sched_priority;
if (kpolicy == KSCHED_RR) {
/* Change the time slice of the thread. */
ret = aos_task_time_slice_set(&(ptcb->task), param->slice);
if (ret != 0) {
return -1;
}
ptcb->attr.sched_slice = param->slice;
}
return 0;
}
int sched_getparam(pid_t pid, struct sched_param *param)
{
int ret = 0;
pthread_tcb_t *ptcb = NULL;
int kpolicy = 0;
if (param == NULL) {
errno = EINVAL;
return -1;
}
ptcb = sched_get_ptcb(pid);
if (ptcb == NULL) {
errno = ESRCH;
return -1;
}
ret = aos_task_pri_get(&(ptcb->task), (uint8_t *)¶m->sched_priority);
if (ret != 0){
return -1;
}
ret = aos_task_sched_policy_get(&(ptcb->task), (uint8_t *)&kpolicy);
if (ret != 0) {
return -1;
}
param->sched_priority = sched_priority_rhino2posix(kpolicy, param->sched_priority);
/* Slice should be 0 if that is not RR policy. */
ret = aos_task_time_slice_get(&(ptcb->task), (uint32_t *)¶m->slice);
if (ret != 0) {
return -1;
}
return 0;
}
int sched_get_priority_max(int policy)
{
int ret = 0;
ret = sched_policy_posix2rhino(policy);
if (ret == -1) {
errno = EINVAL;
return -1;
}
ret = aos_sched_get_priority_max(ret);
if (ret < 0) {
errno = -ret;
return -1;
}
return ret;
}
int sched_get_priority_min(int policy)
{
int ret = 0;
ret = sched_policy_posix2rhino(policy);
if (ret == -1) {
errno = EINVAL;
return -1;
}
ret = aos_sched_get_priority_min(ret);
if (ret < 0) {
errno = -ret;
return -1;
}
return ret;
}
int sched_rr_get_interval(pid_t pid, struct timespec *interval)
{
int ret = 0;
pthread_tcb_t *ptcb = NULL;
uint8_t policy = 0;
uint32_t slice_ms = 0;
if (interval == NULL) {
errno = EINVAL;
return -1;
}
ptcb = sched_get_ptcb(pid);
if (ptcb == NULL) {
errno = ESRCH;
return -1;
}
ret = aos_task_sched_policy_get(&(ptcb->task), &policy);
if ((ret != 0) || (policy != KSCHED_RR)) {
errno = EINVAL;
return -1;
}
ret = aos_task_time_slice_get(&(ptcb->task), &slice_ms);
if (ret != 0) {
return -1;
}
interval->tv_sec = slice_ms / 1000;
interval->tv_nsec = (slice_ms % 1000) * 1000000;
return 0;
}
| YifuLiu/AliOS-Things | components/posix/src/sched.c | C | apache-2.0 | 5,894 |
/*
* Copyright (C) 2021 Alibaba Group Holding Limited
*/
#include <sys/select.h>
extern int aos_select(int maxfd, fd_set *readset, fd_set *writeset, fd_set *exceptset,
struct timeval *timeout);
int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds,
struct timeval *timeout)
{
return aos_select(nfds, readfds, writefds, errorfds, timeout);
}
| YifuLiu/AliOS-Things | components/posix/src/select.c | C | apache-2.0 | 410 |
/*
* Copyright (C) 2020-2021 Alibaba Group Holding Limited
*/
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include <semaphore.h>
#include <aos/kernel.h>
#include <aos/errno.h>
#define SEM_NAME_MAX 1024
/* Initialize an unnamed semaphore */
int sem_init(sem_t *sem, int pshared, unsigned int value)
{
int ret = 0;
if ((sem == NULL) || (value > SEM_VALUE_MAX)) {
errno = EINVAL;
return -1;
}
/* Sharing between processes is not supported. */
if (pshared != 0) {
errno = ENOTSUP;
return -1;
}
ret = aos_sem_new((aos_sem_t *)&(sem->aos_sem), value);
if (ret != 0) {
errno = -ret;
return -1;
}
return 0;
}
/* Initialize and open a named semaphore */
sem_t *sem_open(const char *name, int oflag, ...)
{
if ((name == NULL) || ((strlen(name) <= 0) || (strlen(name) > SEM_NAME_MAX))) {
errno = EINVAL;
return SEM_FAILED;
}
errno = ENOSYS;
return SEM_FAILED;
}
/* lock a semaphore */
int sem_wait(sem_t *sem)
{
int ret = 0;
if (sem == NULL) {
errno = EINVAL;
return -1;
}
ret = aos_sem_wait((aos_sem_t *)&(sem->aos_sem), AOS_WAIT_FOREVER);
if (ret != 0) {
errno = -ret;
return -1;
}
return 0;
}
/* try to lock a semaphore */
int sem_trywait(sem_t *sem)
{
int ret = 0;
if (sem == NULL) {
errno = EINVAL;
return -1;
}
ret = aos_sem_wait((aos_sem_t *)&(sem->aos_sem), 0);
if (ret == -ETIMEDOUT) {
errno = EAGAIN;
return -1;
} else if (ret < 0) {
errno = -ret;
return -1;
} else {
return 0;
}
return 0;
}
/* lock a semaphore */
int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout)
{
int ret = 0;
uint64_t timeout_ms = 0;
struct timespec cur_time = {0};
struct timespec rel_time = {0};
if ((sem == NULL) || (abs_timeout == NULL)) {
errno = EINVAL;
return -1;
}
if ((abs_timeout->tv_sec < 0) || (abs_timeout->tv_nsec < 0)
|| (abs_timeout->tv_nsec >= 1000000000UL)) {
errno = EINVAL;
return -1;
}
ret = clock_gettime(CLOCK_REALTIME, &cur_time);
if (ret != 0) {
return ret;
}
rel_time.tv_sec = abs_timeout->tv_sec - cur_time.tv_sec;
rel_time.tv_nsec = abs_timeout->tv_nsec - cur_time.tv_nsec;
/* Only millisecond precision is supported in AliOS Things. */
timeout_ms = ((rel_time.tv_sec > 0) ? rel_time.tv_sec : 0) * 1000 +
((rel_time.tv_nsec > 0) ? rel_time.tv_nsec : 0) / 1000000;
ret = aos_sem_wait((aos_sem_t *)&(sem->aos_sem), timeout_ms);
if (ret != 0) {
errno = -ret;
return -1;
}
return 0;
}
/* unlock a semaphore */
int sem_post(sem_t *sem)
{
if (sem == NULL) {
errno = EINVAL;
return -1;
}
aos_sem_signal((aos_sem_t *)&(sem->aos_sem));
return 0;
}
/* get the value of a semaphore */
int sem_getvalue(sem_t *sem, int *sval)
{
if ((sem == NULL) || (sval == NULL)) {
errno = EINVAL;
return -1;
}
errno = ENOSYS;
return -1;
}
/* close a named semaphore */
int sem_close(sem_t *sem)
{
if (sem == NULL) {
errno = EINVAL;
return -1;
}
errno = ENOSYS;
return -1;
}
/* remove a named semaphore */
int sem_unlink(const char *name)
{
if (name == NULL) {
errno = EINVAL;
return -1;
}
if (strlen(name) <= 0) {
errno = ENOENT;
return -1;
}
if (strlen(name) > SEM_NAME_MAX) {
errno = ENAMETOOLONG;
return -1;
}
errno = ENOSYS;
return -1;
}
/* destroy an unnamed semaphore */
int sem_destroy(sem_t *sem)
{
if (sem == NULL) {
errno = EINVAL;
return -1;
}
aos_sem_free((aos_sem_t *)&(sem->aos_sem));
return 0;
}
| YifuLiu/AliOS-Things | components/posix/src/semaphore.c | C | apache-2.0 | 3,938 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include <aos/kernel.h>
#define TEMP_PATH_MAX 64
#define TEMP_FILE_PREFIX "/data/tmp"
pthread_mutex_t g_tmpnam_lock = PTHREAD_MUTEX_INITIALIZER;
char *tmpnam(char *s)
{
int ret;
unsigned int seed;
static int temp_name_series = 0;
char *temp_name_prefix = TEMP_FILE_PREFIX;
char temp_name_series_buf[64] = {0};
if (temp_name_series >= TMP_MAX) {
return NULL;
}
seed = aos_now_ms() + random();
srandom(seed);
ret = pthread_mutex_lock(&g_tmpnam_lock);
if (ret != 0) {
return NULL;
}
temp_name_series++;
snprintf(temp_name_series_buf, sizeof(temp_name_series_buf) - 1,
"_%d%d%d", temp_name_series, random(), random());
pthread_mutex_unlock(&g_tmpnam_lock);
/* Temp file should be unpredictable names for security consideration. */
strncpy(s, temp_name_prefix, TEMP_PATH_MAX);
strncat(s, temp_name_series_buf, TEMP_PATH_MAX - strlen(s) - 1);
return s;
}
FILE *tmpfile(void)
{
char path[TEMP_PATH_MAX] = {0};
if (tmpnam(path) == NULL) {
return NULL;
}
return fopen(path, "w+");
}
| YifuLiu/AliOS-Things | components/posix/src/temp.c | C | apache-2.0 | 1,273 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <stdint.h>
#include <time.h>
#include <aos/errno.h>
#include <aos/kernel.h>
int clock_getres(clockid_t clock_id, struct timespec *res)
{
/* At now, only support CLOCK_REALTIME/CLOCK_MONOTONIC clock. */
if (((clock_id != CLOCK_REALTIME) && (clock_id != CLOCK_MONOTONIC)) || (res == NULL)) {
errno = EINVAL;
return -1;
}
res->tv_sec = 0;
res->tv_nsec = 1000000;
return 0;
}
int clock_gettime(clockid_t clock_id, struct timespec *tp)
{
uint64_t time_ms = 0;
if (tp == NULL) {
errno = EINVAL;
return -1;
}
if (clock_id == CLOCK_MONOTONIC) {
time_ms = aos_now_ms();
tp->tv_sec = time_ms / 1000;
tp->tv_nsec = (time_ms % 1000) * 1000000;
} else if (clock_id == CLOCK_REALTIME) {
time_ms = aos_calendar_time_get();
tp->tv_sec = time_ms / 1000;
tp->tv_nsec = (time_ms % 1000) * 1000000;
} else {
errno = EINVAL;
return -1;
}
return 0;
}
int clock_settime(clockid_t clock_id, const struct timespec *tp)
{
uint64_t time_ms = 0;
/* only CLOCK_REALTIME can be set */
if ((clock_id != CLOCK_REALTIME) || (tp == NULL) ||
(tp->tv_nsec < 0) || (tp->tv_nsec >= 1000000000UL)) {
errno = EINVAL;
return -1;
}
time_ms = (tp->tv_sec * 1000) + (tp->tv_nsec / 1000000);
aos_calendar_time_set(time_ms);
return 0;
}
int clock_nanosleep(clockid_t clock_id, int flags, const struct timespec *rqtp,
struct timespec *rmtp)
{
int ret = 0;
int64_t time_ms = 0;
struct timespec tp = {0};
(void)rmtp;
if ((rqtp == NULL) || (rqtp->tv_sec < 0) || (rqtp->tv_nsec < 0)
|| (rqtp->tv_nsec >= 1000000000UL)) {
return EINVAL;
}
if ((clock_id != CLOCK_MONOTONIC) && (clock_id != CLOCK_REALTIME)) {
return EINVAL;
}
if (flags == TIMER_ABSTIME) {
/* absolute time */
ret = clock_gettime(clock_id, &tp);
if (ret != 0) {
return ENOTSUP;
}
time_ms = (rqtp->tv_sec - tp.tv_sec) * 1000 + (rqtp->tv_nsec - tp.tv_nsec) / 1000000;
if (time_ms <= 0) {
/* The absolute time has passed, do not need to sleep. */
return 0;
}
} else {
/* relative time */
time_ms = rqtp->tv_sec * 1000 + rqtp->tv_nsec / 1000000;
}
aos_msleep(time_ms);
return 0;
}
/* Only support milliseconds resulation now by system tick. */
int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
{
uint64_t time_ms = 0;
/* The rmtp parameter is not supported, because signal is not supported. */
(void)rmtp;
if ((rqtp == NULL) || (rqtp->tv_sec < 0) || (rqtp->tv_nsec < 0)
|| (rqtp->tv_nsec >= 1000000000UL)) {
errno = EINVAL;
return -1;
}
time_ms = (rqtp->tv_sec * 1000) + (rqtp->tv_nsec / 1000000);
aos_msleep(time_ms);
return 0;
}
unsigned int sleep(unsigned int seconds)
{
struct timespec tv = { .tv_sec = seconds, .tv_nsec = 0 };
if (nanosleep(&tv, &tv))
return tv.tv_sec;
return 0;
}
int usleep(useconds_t us)
{
struct timespec tv = {
.tv_sec = us / 1000000,
.tv_nsec = (us % 1000000) * 1000
};
return nanosleep(&tv, &tv);
}
| YifuLiu/AliOS-Things | components/posix/src/time.c | C | apache-2.0 | 3,400 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <time.h>
#include <pthread.h>
#include <aos/errno.h>
#include <aos/kernel.h>
#define POSIX_TIMER_ID_MIN 1
typedef struct timer_list_s {
timer_t id;
aos_timer_t aos_timer;
void *evp; /* The sigevent as the parameter of timer_callback. */
struct timer_list_s *next;
} timer_list_t;
timer_list_t *g_timer_list_head = NULL; /* The timer list head. */
pthread_mutex_t g_timer_lock = PTHREAD_MUTEX_INITIALIZER; /* The lock to protect timer list. */
/* Add the unify timer_callback to avoid the argument of callback is an automatic variable,
* we malloc a sigevent and store the argument it it when timer_create, and free it when
* timer_delete.
*/
static void timer_callback(void *timer, void *arg)
{
struct sigevent *evp =(struct sigevent *)arg;
if ((evp != NULL) && (evp->sigev_notify_function != NULL)) {
evp->sigev_notify_function(evp->sigev_value);
}
}
static inline int64_t timespec_to_nanosecond(struct timespec *t)
{
return ((uint64_t)t->tv_sec * 1000000000UL + t->tv_nsec);
}
static inline struct timespec nanosecond_to_timespec(int64_t ns)
{
struct timespec ret_time;
ret_time.tv_sec = ns / 1000000000UL;
ret_time.tv_nsec = ns % 1000000000UL;
return ret_time;
}
static int timespec_abs_to_relate(struct timespec *time_abs, struct timespec *time_relate)
{
int ret = 0;
int64_t ns = 0;
struct timespec time_now;
memset(&time_now, 0, sizeof(time_now));
ret = clock_gettime(CLOCK_MONOTONIC, &time_now);
if (ret != 0) {
return -1;
}
ns = timespec_to_nanosecond(time_abs) - timespec_to_nanosecond(&time_now);
if (ns < 0) {
return -1;
}
*time_relate = nanosecond_to_timespec(ns);
return 0;
}
int timer_create(clockid_t clockid, struct sigevent * evp, timer_t * timerid)
{
int ret = 0;
timer_list_t *timer_list_m = NULL;
timer_list_t *timer_list = NULL;
if ((evp == NULL) || (timerid == NULL) ||
((clockid != CLOCK_REALTIME) && (clockid != CLOCK_MONOTONIC))) {
errno = EINVAL;
return -1;
}
/* Only support SIGEV_THREAD. */
if (evp->sigev_notify != SIGEV_THREAD) {
errno = ENOTSUP;
return -1;
}
/* The sigev_notify_function should be set for SIGEV_THREAD */
if (evp->sigev_notify_function == NULL) {
errno = EINVAL;
return -1;
}
/* malloc new timer struct */
timer_list_m = (timer_list_t *)malloc(sizeof(timer_list_t));
if (timer_list_m == NULL) {
return -1;
}
memset(timer_list_m, 0, sizeof(timer_list_t));
timer_list_m->evp = malloc(sizeof(struct sigevent));
if(timer_list_m->evp == NULL) {
free(timer_list_m);
timer_list_m = NULL;
return -1;
}
memcpy(timer_list_m->evp, evp, sizeof(struct sigevent));
ret = pthread_mutex_lock(&g_timer_lock);
if (ret != 0) {
free(timer_list_m->evp);
free(timer_list_m);
return -1;
}
/* find the last node add the new timer to the list */
if (g_timer_list_head == NULL) {
/* init the id to POSIX_TIMER_ID_MIN */
timer_list_m->id = (timer_t) POSIX_TIMER_ID_MIN;
g_timer_list_head = timer_list_m;
} else {
timer_list = g_timer_list_head;
while(timer_list->next != NULL) {
timer_list = timer_list->next;
}
/* the id of new timer equel to last id plus one */
timer_list_m->id = (int)timer_list->id + 1;
timer_list->next = timer_list_m;
}
pthread_mutex_unlock(&g_timer_lock);
/* create a timer */
ret = aos_timer_new_ext(&(timer_list_m->aos_timer), timer_callback, timer_list_m->evp,
1, 1, 0);
if (ret != 0) {
return -1;
}
/* update the timerid */
*timerid = timer_list_m->id;
return 0;
}
int timer_delete(timer_t timerid)
{
timer_list_t *timer_list = NULL;
timer_list_t *timer_list_l = NULL;
int ret = 0;
/* Timer list is empty. */
if (g_timer_list_head == NULL) {
return -1;
}
ret = pthread_mutex_lock(&g_timer_lock);
if (ret != 0) {
return -1;
}
/* Scan the list to find the timer according to timerid. */
timer_list = g_timer_list_head;
timer_list_l = g_timer_list_head;
while ((timer_list != NULL) && (timer_list->id != timerid)) {
timer_list_l = timer_list;
timer_list = timer_list->next;
}
/* Do not find the timerid. */
if (timer_list == NULL) {
pthread_mutex_unlock(&g_timer_lock);
return -1;
}
/* Stop and detete the timer. */
aos_timer_stop(&(timer_list->aos_timer));
aos_timer_free(&(timer_list->aos_timer));
/* Delete the timer from the list and free the timer. */
if (timer_list_l == g_timer_list_head) {
g_timer_list_head = timer_list->next;
} else {
timer_list_l->next = timer_list->next;
}
if (timer_list->evp != NULL) {
free(timer_list->evp);
}
free(timer_list);
pthread_mutex_unlock(&g_timer_lock);
return ret;
}
int timer_settime(timer_t timerid, int flags, const struct itimerspec *restrict value,
struct itimerspec *restrict ovalue)
{
int ret = 0;
int64_t value_ns = 0;
int64_t interval_ns = 0;
struct timespec value_spec = {0};
struct timespec interval_spec = {0};
timer_list_t *timer_list = NULL;
if (value == NULL) {
return -1;
}
if (g_timer_list_head == NULL) {
return -1;
}
/* If the time is absolute time transform it to relative time. */
if((flags & TIMER_ABSTIME) == TIMER_ABSTIME) {
ret = timespec_abs_to_relate((struct timespec *)&value->it_value, &value_spec);
ret |= timespec_abs_to_relate((struct timespec *)&value->it_interval, &interval_spec);
if (ret != 0) {
return -1;
}
value_ns = timespec_to_nanosecond(&value_spec);
interval_ns = timespec_to_nanosecond(&interval_spec);
} else {
value_ns = timespec_to_nanosecond((struct timespec *)&value->it_value);
interval_ns = timespec_to_nanosecond((struct timespec *)&value->it_interval);
}
/* Get the old parameters of timer if ovalue is not NULL. */
if (ovalue != NULL) {
ret = timer_gettime(timerid, ovalue);
if (ret != 0) {
return -1;
}
}
ret = pthread_mutex_lock(&g_timer_lock);
if (ret != 0) {
return -1;
}
/* Scan the list to find the timer according to timerid. */
timer_list = g_timer_list_head;
while ((timer_list != NULL) && (timer_list->id != timerid)) {
timer_list = timer_list->next;
}
/* Do not find the timer. */
if (timer_list == NULL) {
pthread_mutex_unlock(&g_timer_lock);
return -1;
}
aos_timer_stop(&(timer_list->aos_timer));
/* TODO: support interval and first round timer different. */
ret = aos_timer_change(&(timer_list->aos_timer), value_ns / 1000000);
aos_timer_start(&(timer_list->aos_timer));
pthread_mutex_unlock(&g_timer_lock);
return ret;
}
int timer_gettime(timer_t timerid, struct itimerspec *value)
{
int ret = 0;
uint64_t time_ns[4] = {0};
timer_list_t *timer_list = NULL;
if (value == NULL) {
return -1;
}
ret = pthread_mutex_lock(&g_timer_lock);
if (ret != 0) {
return -1;
}
/* Scan the list to find the timer according to timerid */
timer_list = g_timer_list_head;
while(timer_list != NULL) {
if (timer_list->id == timerid) {
break;
}
timer_list = timer_list->next;
}
if (timer_list == NULL) {
/* The timerid is not found. */
pthread_mutex_unlock(&g_timer_lock);
return -1;
}
ret = aos_timer_gettime(&(timer_list->aos_timer), time_ns);
if (ret != 0) {
pthread_mutex_unlock(&g_timer_lock);
return -1;
}
value->it_interval.tv_sec = time_ns[0];
value->it_interval.tv_nsec = time_ns[1];
value->it_value.tv_sec = time_ns[2];
value->it_value.tv_nsec = time_ns[3];
pthread_mutex_unlock(&g_timer_lock);
return 0;
}
int timer_getoverrun(timer_t timerid)
{
errno = ENOSYS;
return -1;
}
| YifuLiu/AliOS-Things | components/posix/src/timer.c | C | apache-2.0 | 8,454 |
# Top-level cmake file for building MicroPython on ESP32.
cmake_minimum_required(VERSION 3.12)
# Set the location of this port's directory.
set(MICROPY_PORT_DIR ${CMAKE_SOURCE_DIR})
# Set location of base MicroPython directory.
if(NOT MICROPY_DIR)
get_filename_component(MICROPY_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../engine ABSOLUTE)
endif()
# Set the location of AOS components directory.
if(NOT AOS_COMPONENTS_DIR)
get_filename_component(AOS_COMPONENTS_DIR ${MICROPY_PORT_DIR}/../../../ ABSOLUTE)
endif()
# Set the location of AOS engine directory.
if(NOT HAAS_ENGINE_DIR)
get_filename_component(HAAS_ENGINE_DIR ${MICROPY_PORT_DIR}/../../ ABSOLUTE)
endif()
# Set the location of AOS hardware directory.
if(NOT AOS_HARDWARE_DIR)
get_filename_component(AOS_HARDWARE_DIR ${MICROPY_PORT_DIR}/../../../../hardware ABSOLUTE)
endif()
# Set the board if it's not already set.
if(NOT MICROPY_BOARD)
set(MICROPY_BOARD GENERIC)
endif()
# Set the board directory and check that it exists.
if(NOT MICROPY_BOARD_DIR)
set(MICROPY_BOARD_DIR ${MICROPY_PORT_DIR}/boards/${MICROPY_BOARD})
endif()
if(NOT EXISTS ${MICROPY_BOARD_DIR}/mpconfigboard.cmake)
message(FATAL_ERROR "Invalid MICROPY_BOARD specified: ${MICROPY_BOARD}")
endif()
# Define the output sdkconfig so it goes in the build directory.
set(SDKCONFIG ${CMAKE_BINARY_DIR}/sdkconfig)
# Include board config; this is expected to set SDKCONFIG_DEFAULTS (among other options).
include(${MICROPY_BOARD_DIR}/mpconfigboard.cmake)
# Include build options for port extend modules.
include(${HAAS_ENGINE_DIR}/modules/config.cmake)
# Concatenate all sdkconfig files into a combined one for the IDF to use.
file(WRITE ${CMAKE_BINARY_DIR}/sdkconfig.combined.in "")
foreach(SDKCONFIG_DEFAULT ${SDKCONFIG_DEFAULTS})
file(READ ${SDKCONFIG_DEFAULT} CONTENTS)
file(APPEND ${CMAKE_BINARY_DIR}/sdkconfig.combined.in "${CONTENTS}")
endforeach()
configure_file(${CMAKE_BINARY_DIR}/sdkconfig.combined.in ${CMAKE_BINARY_DIR}/sdkconfig.combined COPYONLY)
set(SDKCONFIG_DEFAULTS ${CMAKE_BINARY_DIR}/sdkconfig.combined)
# Include main IDF cmake file and define the project.
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
if(MICROPY_PY_LVGL)
# Include LVGL component, ignore KCONFIG
idf_build_set_property(LV_MICROPYTHON 1)
idf_build_set_property(LV_ESPIDF_ENABLE 0)
set(LVGL_DIR ${MICROPY_DIR}/lib/lv_bindings/lvgl)
set(LV_CONFIG_DIR ${MICROPY_DIR}/../modules/display/esp32)
idf_build_component(${LVGL_DIR})
idf_build_component(${AOS_COMPONENTS_DIR}/drivers/external_device/m5driver/axp192)
idf_build_component(${AOS_COMPONENTS_DIR}/drivers/external_device/m5driver/i2c_manager)
idf_build_component(${AOS_COMPONENTS_DIR}/drivers/external_device/m5driver/lvgl_esp32_drivers)
idf_build_set_property(COMPILE_DEFINITIONS "-DLV_KCONFIG_IGNORE" APPEND)
separate_arguments(LV_CFLAGS_ENV UNIX_COMMAND $ENV{LV_CFLAGS})
list(APPEND LV_CFLAGS ${LV_CFLAGS_ENV})
idf_build_set_property(COMPILE_DEFINITIONS "${LV_CFLAGS}" APPEND)
endif()
project(micropython)
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/CMakeLists.txt | CMake | apache-2.0 | 3,068 |
# Makefile for MicroPython on ESP32.
#
# This is a simple, convenience wrapper around idf.py (which uses cmake).
# Select the board to build for, defaulting to GENERIC.
BOARD ?= GENERIC
# If the build directory is not given, make it reflect the board name.
BUILD ?= build-$(BOARD)
# Device serial settings.
PORT ?= /dev/ttyUSB0
BAUD ?= 460800
PYTHON ?= python3
GIT_SUBMODULES = lib/berkeley-db-1.xx
.PHONY: all clean deploy erase submodules menuconfig FORCE
CMAKE_ARGS =
ifdef USER_C_MODULES
CMAKE_ARGS += -DUSER_C_MODULES=${USER_C_MODULES}
endif
IDFPY_FLAGS += -D MICROPY_BOARD=$(BOARD) -B $(BUILD) $(CMAKE_ARGS)
mkfile_path := $(abspath $(lastword $(MAKEFILE_LIST)))
current_dir := $(abspath $(patsubst %/,%,$(dir $(mkfile_path))))
FROZEN_MANIFEST ?= ${current_dir}/boards/manifest_release.py
ifdef FROZEN_MANIFEST
IDFPY_FLAGS += -D MICROPY_FROZEN_MANIFEST=$(FROZEN_MANIFEST)
endif
all:
idf.py $(IDFPY_FLAGS) build
@$(PYTHON) makeimg.py \
$(BUILD)/sdkconfig \
$(BUILD)/bootloader/bootloader.bin \
$(BUILD)/partition_table/partition-table.bin \
$(BUILD)/micropython.bin \
$(BUILD)/firmware.bin
$(BUILD)/bootloader/bootloader.bin $(BUILD)/partition_table/partition-table.bin $(BUILD)/micropython.bin: FORCE
clean:
idf.py $(IDFPY_FLAGS) fullclean
deploy:
idf.py $(IDFPY_FLAGS) -p $(PORT) -b $(BAUD) flash
erase:
idf.py $(IDFPY_FLAGS) -p $(PORT) -b $(BAUD) erase_flash
submodules:
git submodule update --init $(addprefix ../../,$(GIT_SUBMODULES))
menuconfig:
idf.py $(IDFPY_FLAGS) menuconfig
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/Makefile | Makefile | apache-2.0 | 1,542 |
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __AMP_MACHINE_CONFIG_H__
#define __AMP_MACHINE_CONFIG_H__
/* python engine root dir define */
#define MP_PY_PATH "main.py"
#define MP_FS_IDF_DIR "/"
#define MP_FS_ROOT_DIR "/data"
#define MP_FS_EXT_ROOT_DIR "/sdcard"
#define AMP_FS_ROOT_DIR MP_FS_ROOT_DIR "/pyamp"
#define AMP_FS_EXT_ROOT_DIR MP_FS_EXT_ROOT_DIR "/pyamp"
#define AMP_PY_ENTRY_HAAS (AMP_FS_ROOT_DIR "/" MP_PY_PATH)
#define AMP_PY_ENTRY_ROOT "/main.py"
#define MP_REPL_UART_PORT 0
#define MP_REPL_UART_BAUDRATE 115200UL
#define MP_RECOVERY_UART_PORT 0
#define MP_RECOVERY_UART_PORT_BAUDRATE 115200UL
#endif // __AMP_MACHINE_CONFIG_H__
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/board_config.h | C | apache-2.0 | 686 |
set(IDF_TARGET esp32)
set(SDKCONFIG_DEFAULTS
boards/sdkconfig.base
boards/sdkconfig.ble
boards/GENERIC/sdkconfig.board
)
if(NOT MICROPY_FROZEN_MANIFEST)
set(MICROPY_FROZEN_MANIFEST ${MICROPY_PORT_DIR}/boards/manifest.py)
endif()
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/GENERIC/mpconfigboard.cmake | CMake | apache-2.0 | 247 |
#define MICROPY_HW_BOARD_NAME "ESP32 module"
#define MICROPY_HW_MCU_NAME "ESP32"
#define MICROPY_SW_VENDOR_NAME "HaaSPython"
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/GENERIC/mpconfigboard.h | C | apache-2.0 | 125 |
set(IDF_TARGET esp32c3)
set(SDKCONFIG_DEFAULTS
boards/sdkconfig.base
boards/sdkconfig.ble
boards/GENERIC_C3/sdkconfig.board
)
if(NOT MICROPY_FROZEN_MANIFEST)
set(MICROPY_FROZEN_MANIFEST ${MICROPY_PORT_DIR}/boards/manifest.py)
endif()
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/GENERIC_C3/mpconfigboard.cmake | CMake | apache-2.0 | 252 |
// This configuration is for a generic ESP32C3 board with 4MiB (or more) of flash.
#define MICROPY_HW_BOARD_NAME "ESP32C3 module"
#define MICROPY_HW_MCU_NAME "ESP32C3"
#define MICROPY_SW_VENDOR_NAME "HaaSPython"
#define MICROPY_HW_ENABLE_SDCARD (0)
#define MICROPY_PY_MACHINE_DAC (0)
#define MICROPY_PY_MACHINE_I2S (0)
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/GENERIC_C3/mpconfigboard.h | C | apache-2.0 | 401 |
set(IDF_TARGET esp32c3)
set(SDKCONFIG_DEFAULTS
boards/sdkconfig.base
boards/sdkconfig.ble
boards/GENERIC_C3_USB/sdkconfig.board
)
if(NOT MICROPY_FROZEN_MANIFEST)
set(MICROPY_FROZEN_MANIFEST ${MICROPY_PORT_DIR}/boards/manifest.py)
endif()
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/GENERIC_C3_USB/mpconfigboard.cmake | CMake | apache-2.0 | 256 |
// This configuration is for a generic ESP32C3 board with 4MiB (or more) of flash.
#define MICROPY_HW_BOARD_NAME "ESP32C3_USB module"
#define MICROPY_HW_MCU_NAME "ESP32-C3"
#define MICROPY_SW_VENDOR_NAME "HaaSPython"
#define MICROPY_HW_ENABLE_SDCARD (0)
#define MICROPY_PY_MACHINE_DAC (0)
#define MICROPY_PY_MACHINE_I2S (0)
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/GENERIC_C3_USB/mpconfigboard.h | C | apache-2.0 | 406 |
set(SDKCONFIG_DEFAULTS
boards/sdkconfig.base
boards/sdkconfig.ble
boards/GENERIC_D2WD/sdkconfig.board
)
if(NOT MICROPY_FROZEN_MANIFEST)
set(MICROPY_FROZEN_MANIFEST ${MICROPY_PORT_DIR}/boards/manifest.py)
endif()
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/GENERIC_D2WD/mpconfigboard.cmake | CMake | apache-2.0 | 229 |
#define MICROPY_HW_BOARD_NAME "Generic ESP32-D2WD module"
#define MICROPY_HW_MCU_NAME "ESP32-D2WD"
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/GENERIC_D2WD/mpconfigboard.h | C | apache-2.0 | 99 |
set(SDKCONFIG_DEFAULTS
boards/sdkconfig.base
boards/sdkconfig.ble
boards/GENERIC_OTA/sdkconfig.board
)
if(NOT MICROPY_FROZEN_MANIFEST)
set(MICROPY_FROZEN_MANIFEST ${MICROPY_PORT_DIR}/boards/manifest.py)
endif()
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/GENERIC_OTA/mpconfigboard.cmake | CMake | apache-2.0 | 228 |
#define MICROPY_HW_BOARD_NAME "4MB/OTA module"
#define MICROPY_HW_MCU_NAME "ESP32"
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/GENERIC_OTA/mpconfigboard.h | C | apache-2.0 | 83 |
set(IDF_TARGET esp32s2)
set(SDKCONFIG_DEFAULTS
boards/sdkconfig.base
boards/sdkconfig.usb
)
if(NOT MICROPY_FROZEN_MANIFEST)
set(MICROPY_FROZEN_MANIFEST ${MICROPY_PORT_DIR}/boards/manifest.py)
endif()
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/GENERIC_S2/mpconfigboard.cmake | CMake | apache-2.0 | 214 |
#define MICROPY_HW_BOARD_NAME "ESP32S2 module"
#define MICROPY_HW_MCU_NAME "ESP32S2"
#define MICROPY_PY_BLUETOOTH (0)
#define MICROPY_HW_ENABLE_SDCARD (0)
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/GENERIC_S2/mpconfigboard.h | C | apache-2.0 | 212 |
set(IDF_TARGET esp32s3)
set(SDKCONFIG_DEFAULTS
boards/sdkconfig.base
boards/sdkconfig.ble
boards/GENERIC_S3/sdkconfig.board
)
if(NOT MICROPY_FROZEN_MANIFEST)
set(MICROPY_FROZEN_MANIFEST ${MICROPY_PORT_DIR}/boards/manifest.py)
endif()
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/GENERIC_S3/mpconfigboard.cmake | CMake | apache-2.0 | 252 |
#define MICROPY_HW_BOARD_NAME "ESP32S3 module"
#define MICROPY_HW_MCU_NAME "ESP32-S3"
#define MICROPY_SW_VENDOR_NAME "HaaSPython"
#define MICROPY_PY_MACHINE_DAC (0)
#define MICROPY_HW_I2C0_SCL (9)
#define MICROPY_HW_I2C0_SDA (8)
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/GENERIC_S3/mpconfigboard.h | C | apache-2.0 | 241 |
set(SDKCONFIG_DEFAULTS
boards/sdkconfig.base
boards/sdkconfig.ble
boards/sdkconfig.spiram
)
if(NOT MICROPY_FROZEN_MANIFEST)
set(MICROPY_FROZEN_MANIFEST ${MICROPY_PORT_DIR}/boards/manifest.py)
endif()
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/GENERIC_SPIRAM/mpconfigboard.cmake | CMake | apache-2.0 | 217 |
#define MICROPY_HW_BOARD_NAME "ESP32 module (spiram)"
#define MICROPY_HW_MCU_NAME "ESP32"
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/GENERIC_SPIRAM/mpconfigboard.h | C | apache-2.0 | 90 |
include("$(PORT_DIR)/boards/manifest.py")
freeze("modules")
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/M5STACK_ATOM/manifest.py | Python | apache-2.0 | 60 |
# M5Stack ATOM MicroPython Helper Library
# MIT license; Copyright (c) 2021 IAMLIUBO work for M5STACK
#
# Hardware details:
# ATOM Lite https://docs.m5stack.com/en/core/atom_lite
# ATOM Matrix https://docs.m5stack.com/en/core/atom_matrix
from micropython import const
from machine import Pin
import neopixel
# M5STACK ATOM Hardware Pin Assignments
"""
FRONT
|3V3|
|G21| IR G12 |G22|
|G25| BTN G39 |G19|
| 5V| WS2812 G27 |G23|
|GNG| MPU G21 G25 |G33|
G32 G26 5V GND
Grove Port
"""
# WS2812
WS2812_PIN = const(27)
# Button
BUTTON_PIN = const(39)
# IR
IR_PIN = const(12)
# I2C
I2C0_SCL_PIN = const(21)
I2C0_SDA_PIN = const(25)
# Grove port
GROVE_PORT_PIN = (const(26), const(32))
class ATOM:
def __init__(self, np_n):
self._np = neopixel.NeoPixel(pin=Pin(WS2812_PIN), n=np_n)
self._btn = Pin(BUTTON_PIN, Pin.IN, Pin.PULL_UP)
def get_button_status(self):
return self._btn.value()
def set_button_callback(self, cb):
self._btn.irq(trigger=Pin.IRQ_FALLING, handler=cb)
def set_pixel_color(self, num, r, g, b):
if num <= self._np.n:
self._np[num] = [r, g, b]
self._np.write()
def get_pixel_color(self, num):
if num <= self._np.n:
return self._np[num]
def set_pixels_color(self, r, g, b):
self._np.fill([r, g, b])
self._np.write()
class Lite(ATOM):
# WS2812 number: 1
def __init__(self):
super(Lite, self).__init__(np_n=1)
class Matrix(ATOM):
# WS2812 number: 25
def __init__(self):
super(Matrix, self).__init__(np_n=25)
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/M5STACK_ATOM/modules/atom.py | Python | apache-2.0 | 1,652 |
set(SDKCONFIG_DEFAULTS
boards/sdkconfig.base
boards/sdkconfig.ble
boards/sdkconfig.240mhz
boards/M5STACK_ATOM/sdkconfig.board
)
if(NOT MICROPY_FROZEN_MANIFEST)
set(MICROPY_FROZEN_MANIFEST ${MICROPY_BOARD_DIR}/manifest.py)
endif()
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/M5STACK_ATOM/mpconfigboard.cmake | CMake | apache-2.0 | 251 |
#define MICROPY_HW_BOARD_NAME "M5Stack ATOM"
#define MICROPY_HW_MCU_NAME "ESP32-PICO-D4"
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/M5STACK_ATOM/mpconfigboard.h | C | apache-2.0 | 89 |
set(IDF_TARGET esp32)
set(SDKCONFIG_DEFAULTS
boards/sdkconfig.base
boards/sdkconfig.ble
boards/sdkconfig.spiram
boards/sdkconfig.240mhz
boards/M5STACK_CORE2/sdkconfig.board
boards/M5STACK_CORE2/sdkconfig.lvgl
)
if(NOT MICROPY_FROZEN_MANIFEST)
set(MICROPY_FROZEN_MANIFEST ${MICROPY_PORT_DIR}/boards/manifest.py)
endif()
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/M5STACK_CORE2/mpconfigboard.cmake | CMake | apache-2.0 | 348 |
#define MICROPY_HW_BOARD_NAME "ESP32 module (spiram)"
#define MICROPY_HW_MCU_NAME "ESP32"
#define MICROPY_HW_BOARD_TYPE "8M"
#define MICROPY_SW_VENDOR_NAME "HaaSPython"
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/M5STACK_CORE2/mpconfigboard.h | C | apache-2.0 | 169 |
set(SDKCONFIG_DEFAULTS
boards/sdkconfig.base
boards/sdkconfig.ble
boards/sdkconfig.240mhz
boards/SIL_WESP32/sdkconfig.board
)
if(NOT MICROPY_FROZEN_MANIFEST)
set(MICROPY_FROZEN_MANIFEST ${MICROPY_PORT_DIR}/boards/manifest.py)
endif()
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/SIL_WESP32/mpconfigboard.cmake | CMake | apache-2.0 | 255 |
#define MICROPY_HW_BOARD_NAME "Silicognition wESP32"
#define MICROPY_HW_MCU_NAME "ESP32"
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/SIL_WESP32/mpconfigboard.h | C | apache-2.0 | 89 |
include("$(PORT_DIR)/boards/manifest.py")
freeze("$(PORT_DIR)/boards/UM_TINYPICO/modules", "dotstar.py")
freeze("modules")
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/UM_FEATHERS2/manifest.py | Python | apache-2.0 | 123 |
# FeatherS2 MicroPython Helper Library
# 2021 Seon Rozenblum - Unexpected Maker
#
# Project home:
# https://feathers2.io
#
# 2021-Mar-21 - v0.1 - Initial implementation
# Import required libraries
from micropython import const
from machine import Pin, SPI, ADC
import machine, time
# FeatherS2 Hardware Pin Assignments
# LDO
LDO2 = const(21)
# APA102 Dotstar pins
DOTSTAR_CLK = const(45)
DOTSTAR_DATA = const(40)
# SPI
SPI_MOSI = const(35)
SPI_MISO = const(37)
SPI_CLK = const(36)
# I2C
I2C_SDA = const(8)
I2C_SCL = const(9)
# DAC
DAC1 = const(17)
DAC2 = const(18)
# LED & Ambient Light Sensor
LED = const(13)
AMB_LIGHT = const(4)
# Helper functions
# LED & Ambient Light Sensor control
def set_led(state):
l = Pin(LED, Pin.OUT)
l.value(state)
def toggle_led(state):
l = Pin(LED, Pin.OUT)
l.value(not l.value())
# Create ADC and set attenuation and return the ambient light value from the onboard sensor
def get_amb_light():
adc = ADC(Pin(AMB_LIGHT))
adc.atten(ADC.ATTN_11DB)
return adc.read()
# LDO2 power control
# When we manually turn off the second LDO we also set the DotStar DATA and CLK pins to input to
# prevent parasitic power from lighting the LED even with the LDO off, causing current use.
# The DotStar is a beautiful LED, but parasitic power makes it a terrible choice for battery use :(
def set_ldo2_power(state):
"""Set the power for the on-board Dotstar to allow no current draw when not needed."""
# Set the power pin to the inverse of state
ldo2 = Pin(LDO2, Pin.OUT)
ldo2.value(state)
if state:
Pin(DOTSTAR_CLK, Pin.OUT)
Pin(DOTSTAR_DATA, Pin.OUT) # If power is on, set CLK to be output, otherwise input
else:
Pin(DOTSTAR_CLK, Pin.IN)
Pin(DOTSTAR_DATA, Pin.IN) # If power is on, set CLK to be output, otherwise input
# A small delay to let the IO change state
time.sleep(0.035)
# Dotstar rainbow colour wheel
def dotstar_color_wheel(wheel_pos):
"""Color wheel to allow for cycling through the rainbow of RGB colors."""
wheel_pos = wheel_pos % 255
if wheel_pos < 85:
return 255 - wheel_pos * 3, 0, wheel_pos * 3
elif wheel_pos < 170:
wheel_pos -= 85
return 0, wheel_pos * 3, 255 - wheel_pos * 3
else:
wheel_pos -= 170
return wheel_pos * 3, 255 - wheel_pos * 3, 0
# Go into deep sleep but shut down the APA first to save power
# Use this if you want lowest deep sleep current
def go_deepsleep(t):
"""Deep sleep helper that also powers down the on-board Dotstar."""
set_ldo2_power(False)
machine.deepsleep(t)
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/UM_FEATHERS2/modules/feathers2.py | Python | apache-2.0 | 2,619 |
set(IDF_TARGET esp32s2)
set(SDKCONFIG_DEFAULTS
boards/sdkconfig.base
boards/sdkconfig.spiram_sx
boards/sdkconfig.usb
boards/UM_FEATHERS2/sdkconfig.board
)
set(MICROPY_FROZEN_MANIFEST ${MICROPY_BOARD_DIR}/manifest.py) | YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/UM_FEATHERS2/mpconfigboard.cmake | CMake | apache-2.0 | 233 |
#define MICROPY_HW_BOARD_NAME "FeatherS2"
#define MICROPY_HW_MCU_NAME "ESP32-S2"
#define MICROPY_PY_BLUETOOTH (0)
#define MICROPY_HW_ENABLE_SDCARD (0)
#define MICROPY_HW_I2C0_SCL (9)
#define MICROPY_HW_I2C0_SDA (8)
#define MICROPY_HW_SPI1_MOSI (35) // SDO
#define MICROPY_HW_SPI1_MISO (37) // SDI
#define MICROPY_HW_SPI1_SCK (36)
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/UM_FEATHERS2/mpconfigboard.h | C | apache-2.0 | 361 |
include("$(PORT_DIR)/boards/manifest.py")
freeze("modules")
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/UM_TINYPICO/manifest.py | Python | apache-2.0 | 60 |
# DotStar strip driver for MicroPython
#
# The MIT License (MIT)
#
# Copyright (c) 2016 Damien P. George (original Neopixel object)
# Copyright (c) 2017 Ladyada
# Copyright (c) 2017 Scott Shawcroft for Adafruit Industries
# Copyright (c) 2019 Matt Trentini (porting back to MicroPython)
#
# 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.
START_HEADER_SIZE = 4
LED_START = 0b11100000 # Three "1" bits, followed by 5 brightness bits
# Pixel color order constants
RGB = (0, 1, 2)
RBG = (0, 2, 1)
GRB = (1, 0, 2)
GBR = (1, 2, 0)
BRG = (2, 0, 1)
BGR = (2, 1, 0)
class DotStar:
"""
A sequence of dotstars.
:param SPI spi: The SPI object to write output to.
:param int n: The number of dotstars in the chain
:param float brightness: Brightness of the pixels between 0.0 and 1.0
:param bool auto_write: True if the dotstars should immediately change when
set. If False, `show` must be called explicitly.
:param tuple pixel_order: Set the pixel order on the strip - different
strips implement this differently. If you send red, and it looks blue
or green on the strip, modify this! It should be one of the values above
Example for TinyPICO:
.. code-block:: python
from dotstar import DotStar
from machine import Pin, SPI
spi = SPI(sck=Pin(12), mosi=Pin(13), miso=Pin(18)) # Configure SPI - note: miso is unused
dotstar = DotStar(spi, 1)
dotstar[0] = (128, 0, 0) # Red
"""
def __init__(self, spi, n, *, brightness=1.0, auto_write=True, pixel_order=BGR):
self._spi = spi
self._n = n
# Supply one extra clock cycle for each two pixels in the strip.
self.end_header_size = n // 16
if n % 16 != 0:
self.end_header_size += 1
self._buf = bytearray(n * 4 + START_HEADER_SIZE + self.end_header_size)
self.end_header_index = len(self._buf) - self.end_header_size
self.pixel_order = pixel_order
# Four empty bytes to start.
for i in range(START_HEADER_SIZE):
self._buf[i] = 0x00
# Mark the beginnings of each pixel.
for i in range(START_HEADER_SIZE, self.end_header_index, 4):
self._buf[i] = 0xFF
# 0xff bytes at the end.
for i in range(self.end_header_index, len(self._buf)):
self._buf[i] = 0xFF
self._brightness = 1.0
# Set auto_write to False temporarily so brightness setter does _not_
# call show() while in __init__.
self.auto_write = False
self.brightness = brightness
self.auto_write = auto_write
def deinit(self):
"""Blank out the DotStars and release the resources."""
self.auto_write = False
for i in range(START_HEADER_SIZE, self.end_header_index):
if i % 4 != 0:
self._buf[i] = 0
self.show()
if self._spi:
self._spi.deinit()
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, traceback):
self.deinit()
def __repr__(self):
return "[" + ", ".join([str(x) for x in self]) + "]"
def _set_item(self, index, value):
"""
value can be one of three things:
a (r,g,b) list/tuple
a (r,g,b, brightness) list/tuple
a single, longer int that contains RGB values, like 0xFFFFFF
brightness, if specified should be a float 0-1
Set a pixel value. You can set per-pixel brightness here, if it's not passed it
will use the max value for pixel brightness value, which is a good default.
Important notes about the per-pixel brightness - it's accomplished by
PWMing the entire output of the LED, and that PWM is at a much
slower clock than the rest of the LEDs. This can cause problems in
Persistence of Vision Applications
"""
offset = index * 4 + START_HEADER_SIZE
rgb = value
if isinstance(value, int):
rgb = (value >> 16, (value >> 8) & 0xFF, value & 0xFF)
if len(rgb) == 4:
brightness = value[3]
# Ignore value[3] below.
else:
brightness = 1
# LED startframe is three "1" bits, followed by 5 brightness bits
# then 8 bits for each of R, G, and B. The order of those 3 are configurable and
# vary based on hardware
# same as math.ceil(brightness * 31) & 0b00011111
# Idea from https://www.codeproject.com/Tips/700780/Fast-floor-ceiling-functions
brightness_byte = 32 - int(32 - brightness * 31) & 0b00011111
self._buf[offset] = brightness_byte | LED_START
self._buf[offset + 1] = rgb[self.pixel_order[0]]
self._buf[offset + 2] = rgb[self.pixel_order[1]]
self._buf[offset + 3] = rgb[self.pixel_order[2]]
def __setitem__(self, index, val):
if isinstance(index, slice):
start, stop, step = index.indices(self._n)
length = stop - start
if step != 0:
# same as math.ceil(length / step)
# Idea from https://fizzbuzzer.com/implement-a-ceil-function/
length = (length + step - 1) // step
if len(val) != length:
raise ValueError("Slice and input sequence size do not match.")
for val_i, in_i in enumerate(range(start, stop, step)):
self._set_item(in_i, val[val_i])
else:
self._set_item(index, val)
if self.auto_write:
self.show()
def __getitem__(self, index):
if isinstance(index, slice):
out = []
for in_i in range(*index.indices(self._n)):
out.append(
tuple(self._buf[in_i * 4 + (3 - i) + START_HEADER_SIZE] for i in range(3))
)
return out
if index < 0:
index += len(self)
if index >= self._n or index < 0:
raise IndexError
offset = index * 4
return tuple(self._buf[offset + (3 - i) + START_HEADER_SIZE] for i in range(3))
def __len__(self):
return self._n
@property
def brightness(self):
"""Overall brightness of the pixel"""
return self._brightness
@brightness.setter
def brightness(self, brightness):
self._brightness = min(max(brightness, 0.0), 1.0)
if self.auto_write:
self.show()
def fill(self, color):
"""Colors all pixels the given ***color***."""
auto_write = self.auto_write
self.auto_write = False
for i in range(self._n):
self[i] = color
if auto_write:
self.show()
self.auto_write = auto_write
def show(self):
"""Shows the new colors on the pixels themselves if they haven't already
been autowritten.
The colors may or may not be showing after this function returns because
it may be done asynchronously."""
# Create a second output buffer if we need to compute brightness
buf = self._buf
if self.brightness < 1.0:
buf = bytearray(self._buf)
# Four empty bytes to start.
for i in range(START_HEADER_SIZE):
buf[i] = 0x00
for i in range(START_HEADER_SIZE, self.end_header_index):
buf[i] = self._buf[i] if i % 4 == 0 else int(self._buf[i] * self._brightness)
# Four 0xff bytes at the end.
for i in range(self.end_header_index, len(buf)):
buf[i] = 0xFF
if self._spi:
self._spi.write(buf)
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/UM_TINYPICO/modules/dotstar.py | Python | apache-2.0 | 8,673 |
# TinyPICO MicroPython Helper Library
# 2019 Seon Rozenblum, Matt Trentini
#
# Project home:
# https://github.com/TinyPICO
#
# 2019-Mar-12 - v0.1 - Initial implementation
# 2019-May-20 - v1.0 - Initial Release
# 2019-Oct-23 - v1.1 - Removed temp sensor code, prep for frozen modules
# Import required libraries
from micropython import const
from machine import Pin, SPI, ADC
import machine, time, esp32
# TinyPICO Hardware Pin Assignments
# Battery
BAT_VOLTAGE = const(35)
BAT_CHARGE = const(34)
# APA102 Dotstar pins for production boards
DOTSTAR_CLK = const(12)
DOTSTAR_DATA = const(2)
DOTSTAR_PWR = const(13)
# SPI
SPI_MOSI = const(23)
SPI_CLK = const(18)
SPI_MISO = const(19)
# I2C
I2C_SDA = const(21)
I2C_SCL = const(22)
# DAC
DAC1 = const(25)
DAC2 = const(26)
# Helper functions
# Get a *rough* estimate of the current battery voltage
# If the battery is not present, the charge IC will still report it's trying to charge at X voltage
# so it will still show a voltage.
def get_battery_voltage():
"""
Returns the current battery voltage. If no battery is connected, returns 3.7V
This is an approximation only, but useful to detect of the charge state of the battery is getting low.
"""
adc = ADC(Pin(BAT_VOLTAGE)) # Assign the ADC pin to read
measuredvbat = adc.read() # Read the value
measuredvbat /= 4095 # divide by 4095 as we are using the default ADC voltage range of 0-1V
measuredvbat *= 3.7 # Multiply by 3.7V, our reference voltage
return measuredvbat
# Return the current charge state of the battery - we need to read the value multiple times
# to eliminate false negatives due to the charge IC not knowing the difference between no battery
# and a full battery not charging - This is why the charge LED flashes
def get_battery_charging():
"""
Returns the current battery charging state.
This can trigger false positives as the charge IC can't tell the difference between a full battery or no battery connected.
"""
measuredVal = 0 # start our reading at 0
io = Pin(BAT_CHARGE, Pin.IN) # Assign the pin to read
for y in range(
0, 10
): # loop through 10 times adding the read values together to ensure no false positives
measuredVal += io.value()
return measuredVal == 0 # return True if the value is 0
# Power to the on-board Dotstar is controlled by a PNP transistor, so low is ON and high is OFF
# We also need to set the Dotstar clock and data pins to be inputs to prevent power leakage when power is off
# This might be improved at a future date
# The reason we have power control for the Dotstar is that it has a quiescent current of around 1mA, so we
# need to be able to cut power to it to minimise power consumption during deep sleep or with general battery powered use
# to minimise unneeded battery drain
def set_dotstar_power(state):
"""Set the power for the on-board Dotstar to allow no current draw when not needed."""
# Set the power pin to the inverse of state
if state:
Pin(DOTSTAR_PWR, Pin.OUT, None) # Break the PULL_HOLD on the pin
Pin(DOTSTAR_PWR).value(False) # Set the pin to LOW to enable the Transistor
else:
Pin(13, Pin.IN, Pin.PULL_HOLD) # Set PULL_HOLD on the pin to allow the 3V3 pull-up to work
Pin(
DOTSTAR_CLK, Pin.OUT if state else Pin.IN
) # If power is on, set CLK to be output, otherwise input
Pin(
DOTSTAR_DATA, Pin.OUT if state else Pin.IN
) # If power is on, set DATA to be output, otherwise input
# A small delay to let the IO change state
time.sleep(0.035)
# Dotstar rainbow colour wheel
def dotstar_color_wheel(wheel_pos):
"""Color wheel to allow for cycling through the rainbow of RGB colors."""
wheel_pos = wheel_pos % 255
if wheel_pos < 85:
return 255 - wheel_pos * 3, 0, wheel_pos * 3
elif wheel_pos < 170:
wheel_pos -= 85
return 0, wheel_pos * 3, 255 - wheel_pos * 3
else:
wheel_pos -= 170
return wheel_pos * 3, 255 - wheel_pos * 3, 0
# Go into deep sleep but shut down the APA first to save power
# Use this if you want lowest deep sleep current
def go_deepsleep(t):
"""Deep sleep helper that also powers down the on-board Dotstar."""
set_dotstar_power(False)
machine.deepsleep(t)
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/UM_TINYPICO/modules/tinypico.py | Python | apache-2.0 | 4,322 |
set(SDKCONFIG_DEFAULTS
boards/sdkconfig.base
boards/sdkconfig.ble
boards/sdkconfig.240mhz
boards/sdkconfig.spiram
boards/UM_TINYPICO/sdkconfig.board
)
if(NOT MICROPY_FROZEN_MANIFEST)
set(MICROPY_FROZEN_MANIFEST ${MICROPY_BOARD_DIR}/manifest.py)
endif()
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/UM_TINYPICO/mpconfigboard.cmake | CMake | apache-2.0 | 278 |
#define MICROPY_HW_BOARD_NAME "TinyPICO"
#define MICROPY_HW_MCU_NAME "ESP32-PICO-D4"
#define MICROPY_HW_I2C0_SCL (22)
#define MICROPY_HW_I2C0_SDA (21)
#define MICROPY_HW_SPI1_SCK (18)
#define MICROPY_HW_SPI1_MOSI (23)
#define MICROPY_HW_SPI1_MISO (19)
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/UM_TINYPICO/mpconfigboard.h | C | apache-2.0 | 254 |
include("$(PORT_DIR)/boards/manifest.py")
freeze("modules")
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/UM_TINYS2/manifest.py | Python | apache-2.0 | 60 |
# TinyS2 MicroPython Helper Library
# 2021 Seon Rozenblum - Unexpected Maker
#
# Project home:
# https://tinys2.io
#
# 2021-Apr-10 - v0.1 - Initial implementation
# Import required libraries
from micropython import const
from machine import Pin, SPI, ADC
import machine, time
# TinyS2 Hardware Pin Assignments
# Sense Pins
VBUS_SENSE = const(21)
VBAT_SENSE = const(3)
# RGB LED Pins
RGB_DATA = const(1)
RGB_PWR = const(2)
# SPI
SPI_MOSI = const(35)
SPI_MISO = const(36)
SPI_CLK = const(37)
# I2C
I2C_SDA = const(8)
I2C_SCL = const(9)
# DAC
DAC1 = const(17)
DAC2 = const(18)
# Helper functions
def set_pixel_power(state):
"""Enable or Disable power to the onboard NeoPixel to either show colour, or to reduce power for deep sleep."""
Pin(RGB_PWR, Pin.OUT).value(state)
def get_battery_voltage():
"""
Returns the current battery voltage. If no battery is connected, returns 4.2V which is the charge voltage
This is an approximation only, but useful to detect if the charge state of the battery is getting low.
"""
adc = ADC(Pin(VBAT_SENSE)) # Assign the ADC pin to read
measuredvbat = adc.read() # Read the value
measuredvbat /= 8192 # divide by 8192 as we are using the default ADC voltage range of 0-1V
measuredvbat *= 4.2 # Multiply by 4.2V, our reference voltage
return round(measuredvbat, 2)
def get_vbus_present():
"""Detect if VBUS (5V) power source is present"""
return Pin(VBUS_SENSE, Pin.IN).value() == 1
# NeoPixel rainbow colour wheel
def rgb_color_wheel(wheel_pos):
"""Color wheel to allow for cycling through the rainbow of RGB colors."""
wheel_pos = wheel_pos % 255
if wheel_pos < 85:
return 255 - wheel_pos * 3, 0, wheel_pos * 3
elif wheel_pos < 170:
wheel_pos -= 85
return 0, wheel_pos * 3, 255 - wheel_pos * 3
else:
wheel_pos -= 170
return wheel_pos * 3, 255 - wheel_pos * 3, 0
# Go into deep sleep but shut down the RGB LED first to save power
# Use this if you want lowest deep sleep current
def go_deepsleep(t):
"""Deep sleep helper that also powers down the on-board NeoPixel."""
set_pixel_power(False)
machine.deepsleep(t)
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/UM_TINYS2/modules/tinys2.py | Python | apache-2.0 | 2,193 |
set(IDF_TARGET esp32s2)
set(SDKCONFIG_DEFAULTS
boards/sdkconfig.base
boards/sdkconfig.spiram_sx
boards/sdkconfig.usb
)
set(MICROPY_FROZEN_MANIFEST ${MICROPY_PORT_DIR}/boards/manifest.py)
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/UM_TINYS2/mpconfigboard.cmake | CMake | apache-2.0 | 200 |
#define MICROPY_HW_BOARD_NAME "TinyS2"
#define MICROPY_HW_MCU_NAME "ESP32-S2FN4R2"
#define MICROPY_PY_BLUETOOTH (0)
#define MICROPY_HW_ENABLE_SDCARD (0)
#define MICROPY_HW_I2C0_SCL (9)
#define MICROPY_HW_I2C0_SDA (8)
#define MICROPY_HW_SPI1_MOSI (35)
#define MICROPY_HW_SPI1_MISO (36)
#define MICROPY_HW_SPI1_SCK (37)
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/UM_TINYS2/mpconfigboard.h | C | apache-2.0 | 347 |
freeze("$(PORT_DIR)/modules")
freeze("$(MPY_DIR)/tools", ("upip.py", "upip_utarfile.py"))
freeze("$(MPY_DIR)/drivers/dht", "dht.py")
freeze("$(MPY_DIR)/drivers/onewire")
include("$(MPY_DIR)/extmod/uasyncio/manifest.py")
include("$(MPY_DIR)/extmod/webrepl/manifest.py")
include("$(MPY_DIR)/drivers/neopixel/manifest.py")
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/manifest.py | Python | apache-2.0 | 320 |
include("manifest.py")
freeze("$(MPY_LIB_DIR)/python-ecosys/urequests", "urequests.py")
freeze("$(MPY_LIB_DIR)/micropython/upysh", "upysh.py")
freeze("$(MPY_LIB_DIR)/micropython/umqtt.simple", "umqtt/simple.py")
freeze("$(MPY_LIB_DIR)/micropython/umqtt.robust", "umqtt/robust.py")
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/boards/manifest_release.py | Python | apache-2.0 | 283 |
idf_component_register(SRC_DIRS "."
) | YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/components/dummy_main/CMakeLists.txt | CMake | apache-2.0 | 41 |
#include <stdio.h>
void app_main(void)
{
printf(" ====== main_dummy enter ======\r\n");
} | YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/components/dummy_main/main_dummy.c | C | apache-2.0 | 94 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2021 by Thorsten von Eicken
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <string.h>
#include "py/runtime.h"
#include "py/mperrno.h"
#include "mphalport.h"
#include "modesp32.h"
#include "nvs_flash.h"
#include "nvs.h"
// This file implements the NVS (Non-Volatile Storage) class in the esp32 module.
// It provides simple access to the NVS feature provided by ESP-IDF.
// NVS python object that represents an NVS namespace.
typedef struct _esp32_nvs_obj_t {
mp_obj_base_t base;
nvs_handle_t namespace;
} esp32_nvs_obj_t;
// *esp32_nvs_new allocates a python NVS object given a handle to an esp-idf namespace C obj.
STATIC esp32_nvs_obj_t *esp32_nvs_new(nvs_handle_t namespace) {
esp32_nvs_obj_t *self = m_new_obj(esp32_nvs_obj_t);
self->base.type = &esp32_nvs_type;
self->namespace = namespace;
return self;
}
// esp32_nvs_print prints an NVS object, unfortunately it doesn't seem possible to extract the
// namespace string or anything else from the opaque handle provided by esp-idf.
STATIC void esp32_nvs_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
// esp32_nvs_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "<NVS namespace>");
}
// esp32_nvs_make_new constructs a handle to an NVS namespace.
STATIC mp_obj_t esp32_nvs_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
// Check args
mp_arg_check_num(n_args, n_kw, 1, 1, false);
// Get requested nvs namespace
const char *ns_name = mp_obj_str_get_str(all_args[0]);
nvs_handle_t namespace;
check_esp_err(nvs_open(ns_name, NVS_READWRITE, &namespace));
return MP_OBJ_FROM_PTR(esp32_nvs_new(namespace));
}
// esp32_nvs_set_i32 sets a 32-bit integer value
STATIC mp_obj_t esp32_nvs_set_i32(mp_obj_t self_in, mp_obj_t key_in, mp_obj_t value_in) {
esp32_nvs_obj_t *self = MP_OBJ_TO_PTR(self_in);
const char *key = mp_obj_str_get_str(key_in);
int32_t value = mp_obj_get_int(value_in);
check_esp_err(nvs_set_i32(self->namespace, key, value));
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp32_nvs_set_i32_obj, esp32_nvs_set_i32);
// esp32_nvs_get_i32 reads a 32-bit integer value
STATIC mp_obj_t esp32_nvs_get_i32(mp_obj_t self_in, mp_obj_t key_in) {
esp32_nvs_obj_t *self = MP_OBJ_TO_PTR(self_in);
const char *key = mp_obj_str_get_str(key_in);
int32_t value;
check_esp_err(nvs_get_i32(self->namespace, key, &value));
return mp_obj_new_int(value);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(esp32_nvs_get_i32_obj, esp32_nvs_get_i32);
// esp32_nvs_set_blob writes a buffer object into a binary blob value.
STATIC mp_obj_t esp32_nvs_set_blob(mp_obj_t self_in, mp_obj_t key_in, mp_obj_t value_in) {
esp32_nvs_obj_t *self = MP_OBJ_TO_PTR(self_in);
const char *key = mp_obj_str_get_str(key_in);
mp_buffer_info_t value;
mp_get_buffer_raise(value_in, &value, MP_BUFFER_READ);
check_esp_err(nvs_set_blob(self->namespace, key, value.buf, value.len));
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp32_nvs_set_blob_obj, esp32_nvs_set_blob);
// esp32_nvs_get_blob reads a binary blob value into a bytearray. Returns actual length.
STATIC mp_obj_t esp32_nvs_get_blob(mp_obj_t self_in, mp_obj_t key_in, mp_obj_t value_in) {
esp32_nvs_obj_t *self = MP_OBJ_TO_PTR(self_in);
const char *key = mp_obj_str_get_str(key_in);
// get buffer to be filled
mp_buffer_info_t value;
mp_get_buffer_raise(value_in, &value, MP_BUFFER_WRITE);
size_t length = value.len;
// fill the buffer with the value, will raise an esp-idf error if the length of
// the provided buffer (bytearray) is too small
check_esp_err(nvs_get_blob(self->namespace, key, value.buf, &length));
return MP_OBJ_NEW_SMALL_INT(length);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp32_nvs_get_blob_obj, esp32_nvs_get_blob);
// esp32_nvs_erase_key erases one key.
STATIC mp_obj_t esp32_nvs_erase_key(mp_obj_t self_in, mp_obj_t key_in) {
esp32_nvs_obj_t *self = MP_OBJ_TO_PTR(self_in);
const char *key = mp_obj_str_get_str(key_in);
check_esp_err(nvs_erase_key(self->namespace, key));
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(esp32_nvs_erase_key_obj, esp32_nvs_erase_key);
// esp32_nvs_commit commits any changes to flash.
STATIC mp_obj_t esp32_nvs_commit(mp_obj_t self_in) {
esp32_nvs_obj_t *self = MP_OBJ_TO_PTR(self_in);
check_esp_err(nvs_commit(self->namespace));
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(esp32_nvs_commit_obj, esp32_nvs_commit);
STATIC const mp_rom_map_elem_t esp32_nvs_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_get_i32), MP_ROM_PTR(&esp32_nvs_get_i32_obj) },
{ MP_ROM_QSTR(MP_QSTR_set_i32), MP_ROM_PTR(&esp32_nvs_set_i32_obj) },
{ MP_ROM_QSTR(MP_QSTR_get_blob), MP_ROM_PTR(&esp32_nvs_get_blob_obj) },
{ MP_ROM_QSTR(MP_QSTR_set_blob), MP_ROM_PTR(&esp32_nvs_set_blob_obj) },
{ MP_ROM_QSTR(MP_QSTR_erase_key), MP_ROM_PTR(&esp32_nvs_erase_key_obj) },
{ MP_ROM_QSTR(MP_QSTR_commit), MP_ROM_PTR(&esp32_nvs_commit_obj) },
};
STATIC MP_DEFINE_CONST_DICT(esp32_nvs_locals_dict, esp32_nvs_locals_dict_table);
const mp_obj_type_t esp32_nvs_type = {
{ &mp_type_type },
.name = MP_QSTR_NVS,
.print = esp32_nvs_print,
.make_new = esp32_nvs_make_new,
.locals_dict = (mp_obj_dict_t *)&esp32_nvs_locals_dict,
};
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/esp32_nvs.c | C | apache-2.0 | 6,540 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <string.h>
#include "py/runtime.h"
#include "py/mperrno.h"
#include "extmod/vfs.h"
#include "mphalport.h"
#include "modesp32.h"
#include "esp_ota_ops.h"
// esp_partition_read and esp_partition_write can operate on arbitrary bytes
// but esp_partition_erase_range operates on 4k blocks. But to make a partition
// implement the standard block protocol all operations are done on 4k blocks.
#define BLOCK_SIZE_BYTES (4096)
enum {
ESP32_PARTITION_BOOT,
ESP32_PARTITION_RUNNING,
};
typedef struct _esp32_partition_obj_t {
mp_obj_base_t base;
const esp_partition_t *part;
} esp32_partition_obj_t;
STATIC esp32_partition_obj_t *esp32_partition_new(const esp_partition_t *part) {
if (part == NULL) {
mp_raise_OSError(MP_ENOENT);
}
esp32_partition_obj_t *self = m_new_obj(esp32_partition_obj_t);
self->base.type = &esp32_partition_type;
self->part = part;
return self;
}
STATIC void esp32_partition_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
esp32_partition_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "<Partition type=%u, subtype=%u, address=%u, size=%u, label=%s, encrypted=%u>",
self->part->type, self->part->subtype,
self->part->address, self->part->size,
&self->part->label[0], self->part->encrypted
);
}
STATIC mp_obj_t esp32_partition_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
// Check args
mp_arg_check_num(n_args, n_kw, 1, 1, false);
// Get requested partition
const esp_partition_t *part;
if (mp_obj_is_int(all_args[0])) {
// Integer given, get that particular partition
switch (mp_obj_get_int(all_args[0])) {
case ESP32_PARTITION_BOOT:
part = esp_ota_get_boot_partition();
break;
case ESP32_PARTITION_RUNNING:
part = esp_ota_get_running_partition();
break;
default:
mp_raise_ValueError(NULL);
}
} else {
// String given, search for partition with that label
const char *label = mp_obj_str_get_str(all_args[0]);
part = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_ANY, label);
if (part == NULL) {
part = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_ANY, label);
}
}
// Return new object
return MP_OBJ_FROM_PTR(esp32_partition_new(part));
}
STATIC mp_obj_t esp32_partition_find(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
// Parse args
enum { ARG_type, ARG_subtype, ARG_label };
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_type, MP_ARG_INT, {.u_int = ESP_PARTITION_TYPE_APP} },
{ MP_QSTR_subtype, MP_ARG_INT, {.u_int = ESP_PARTITION_SUBTYPE_ANY} },
{ MP_QSTR_label, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
};
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
// Get optional label string
const char *label = NULL;
if (args[ARG_label].u_obj != mp_const_none) {
label = mp_obj_str_get_str(args[ARG_label].u_obj);
}
// Build list of matching partitions
mp_obj_t list = mp_obj_new_list(0, NULL);
esp_partition_iterator_t iter = esp_partition_find(args[ARG_type].u_int, args[ARG_subtype].u_int, label);
while (iter != NULL) {
mp_obj_list_append(list, MP_OBJ_FROM_PTR(esp32_partition_new(esp_partition_get(iter))));
iter = esp_partition_next(iter);
}
esp_partition_iterator_release(iter);
return list;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(esp32_partition_find_fun_obj, 0, esp32_partition_find);
STATIC MP_DEFINE_CONST_STATICMETHOD_OBJ(esp32_partition_find_obj, MP_ROM_PTR(&esp32_partition_find_fun_obj));
STATIC mp_obj_t esp32_partition_info(mp_obj_t self_in) {
esp32_partition_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_obj_t tuple[] = {
MP_OBJ_NEW_SMALL_INT(self->part->type),
MP_OBJ_NEW_SMALL_INT(self->part->subtype),
mp_obj_new_int_from_uint(self->part->address),
mp_obj_new_int_from_uint(self->part->size),
mp_obj_new_str(&self->part->label[0], strlen(&self->part->label[0])),
mp_obj_new_bool(self->part->encrypted),
};
return mp_obj_new_tuple(6, tuple);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(esp32_partition_info_obj, esp32_partition_info);
STATIC mp_obj_t esp32_partition_readblocks(size_t n_args, const mp_obj_t *args) {
esp32_partition_obj_t *self = MP_OBJ_TO_PTR(args[0]);
uint32_t offset = mp_obj_get_int(args[1]) * BLOCK_SIZE_BYTES;
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(args[2], &bufinfo, MP_BUFFER_WRITE);
if (n_args == 4) {
offset += mp_obj_get_int(args[3]);
}
check_esp_err(esp_partition_read(self->part, offset, bufinfo.buf, bufinfo.len));
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(esp32_partition_readblocks_obj, 3, 4, esp32_partition_readblocks);
STATIC mp_obj_t esp32_partition_writeblocks(size_t n_args, const mp_obj_t *args) {
esp32_partition_obj_t *self = MP_OBJ_TO_PTR(args[0]);
uint32_t offset = mp_obj_get_int(args[1]) * BLOCK_SIZE_BYTES;
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(args[2], &bufinfo, MP_BUFFER_READ);
if (n_args == 3) {
check_esp_err(esp_partition_erase_range(self->part, offset, bufinfo.len));
} else {
offset += mp_obj_get_int(args[3]);
}
check_esp_err(esp_partition_write(self->part, offset, bufinfo.buf, bufinfo.len));
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(esp32_partition_writeblocks_obj, 3, 4, esp32_partition_writeblocks);
STATIC mp_obj_t esp32_partition_ioctl(mp_obj_t self_in, mp_obj_t cmd_in, mp_obj_t arg_in) {
esp32_partition_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_int_t cmd = mp_obj_get_int(cmd_in);
switch (cmd) {
case MP_BLOCKDEV_IOCTL_INIT:
return MP_OBJ_NEW_SMALL_INT(0);
case MP_BLOCKDEV_IOCTL_DEINIT:
return MP_OBJ_NEW_SMALL_INT(0);
case MP_BLOCKDEV_IOCTL_SYNC:
return MP_OBJ_NEW_SMALL_INT(0);
case MP_BLOCKDEV_IOCTL_BLOCK_COUNT:
return MP_OBJ_NEW_SMALL_INT(self->part->size / BLOCK_SIZE_BYTES);
case MP_BLOCKDEV_IOCTL_BLOCK_SIZE:
return MP_OBJ_NEW_SMALL_INT(BLOCK_SIZE_BYTES);
case MP_BLOCKDEV_IOCTL_BLOCK_ERASE: {
uint32_t offset = mp_obj_get_int(arg_in) * BLOCK_SIZE_BYTES;
check_esp_err(esp_partition_erase_range(self->part, offset, BLOCK_SIZE_BYTES));
return MP_OBJ_NEW_SMALL_INT(0);
}
default:
return mp_const_none;
}
}
STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp32_partition_ioctl_obj, esp32_partition_ioctl);
STATIC mp_obj_t esp32_partition_set_boot(mp_obj_t self_in) {
esp32_partition_obj_t *self = MP_OBJ_TO_PTR(self_in);
check_esp_err(esp_ota_set_boot_partition(self->part));
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(esp32_partition_set_boot_obj, esp32_partition_set_boot);
STATIC mp_obj_t esp32_partition_get_next_update(mp_obj_t self_in) {
esp32_partition_obj_t *self = MP_OBJ_TO_PTR(self_in);
return MP_OBJ_FROM_PTR(esp32_partition_new(esp_ota_get_next_update_partition(self->part)));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(esp32_partition_get_next_update_obj, esp32_partition_get_next_update);
STATIC mp_obj_t esp32_partition_mark_app_valid_cancel_rollback(mp_obj_t cls_in) {
check_esp_err(esp_ota_mark_app_valid_cancel_rollback());
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(esp32_partition_mark_app_valid_cancel_rollback_fun_obj,
esp32_partition_mark_app_valid_cancel_rollback);
STATIC MP_DEFINE_CONST_CLASSMETHOD_OBJ(esp32_partition_mark_app_valid_cancel_rollback_obj,
MP_ROM_PTR(&esp32_partition_mark_app_valid_cancel_rollback_fun_obj));
STATIC const mp_rom_map_elem_t esp32_partition_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_find), MP_ROM_PTR(&esp32_partition_find_obj) },
{ MP_ROM_QSTR(MP_QSTR_info), MP_ROM_PTR(&esp32_partition_info_obj) },
{ MP_ROM_QSTR(MP_QSTR_readblocks), MP_ROM_PTR(&esp32_partition_readblocks_obj) },
{ MP_ROM_QSTR(MP_QSTR_writeblocks), MP_ROM_PTR(&esp32_partition_writeblocks_obj) },
{ MP_ROM_QSTR(MP_QSTR_ioctl), MP_ROM_PTR(&esp32_partition_ioctl_obj) },
{ MP_ROM_QSTR(MP_QSTR_set_boot), MP_ROM_PTR(&esp32_partition_set_boot_obj) },
{ MP_ROM_QSTR(MP_QSTR_mark_app_valid_cancel_rollback), MP_ROM_PTR(&esp32_partition_mark_app_valid_cancel_rollback_obj) },
{ MP_ROM_QSTR(MP_QSTR_get_next_update), MP_ROM_PTR(&esp32_partition_get_next_update_obj) },
{ MP_ROM_QSTR(MP_QSTR_BOOT), MP_ROM_INT(ESP32_PARTITION_BOOT) },
{ MP_ROM_QSTR(MP_QSTR_RUNNING), MP_ROM_INT(ESP32_PARTITION_RUNNING) },
{ MP_ROM_QSTR(MP_QSTR_TYPE_APP), MP_ROM_INT(ESP_PARTITION_TYPE_APP) },
{ MP_ROM_QSTR(MP_QSTR_TYPE_DATA), MP_ROM_INT(ESP_PARTITION_TYPE_DATA) },
};
STATIC MP_DEFINE_CONST_DICT(esp32_partition_locals_dict, esp32_partition_locals_dict_table);
const mp_obj_type_t esp32_partition_type = {
{ &mp_type_type },
.name = MP_QSTR_Partition,
.print = esp32_partition_print,
.make_new = esp32_partition_make_new,
.locals_dict = (mp_obj_dict_t *)&esp32_partition_locals_dict,
};
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/esp32_partition.c | C | apache-2.0 | 10,642 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2019 "Matt Trentini" <matt.trentini@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "py/runtime.h"
#include "modmachine.h"
#include "mphalport.h"
#include "driver/rmt.h"
// This exposes the ESP32's RMT module to MicroPython. RMT is provided by the Espressif ESP-IDF:
//
// https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/rmt.html
//
// With some examples provided:
//
// https://github.com/espressif/arduino-esp32/tree/master/libraries/ESP32/examples/RMT
//
// RMT allows accurate (down to 12.5ns resolution) transmit - and receive - of pulse signals.
// Originally designed to generate infrared remote control signals, the module is very
// flexible and quite easy-to-use.
//
// This current MicroPython implementation lacks some major features, notably receive pulses
// and carrier output.
// Forward declaration
extern const mp_obj_type_t esp32_rmt_type;
typedef struct _esp32_rmt_obj_t {
mp_obj_base_t base;
uint8_t channel_id;
gpio_num_t pin;
uint8_t clock_div;
mp_uint_t num_items;
rmt_item32_t *items;
bool loop_en;
} esp32_rmt_obj_t;
STATIC mp_obj_t esp32_rmt_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_id, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = -1} },
{ MP_QSTR_pin, MP_ARG_REQUIRED | MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
{ MP_QSTR_clock_div, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 8} }, // 100ns resolution
{ MP_QSTR_idle_level, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, // low voltage
{ MP_QSTR_tx_carrier, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, // no carrier
};
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
mp_uint_t channel_id = args[0].u_int;
gpio_num_t pin_id = machine_pin_get_id(args[1].u_obj);
mp_uint_t clock_div = args[2].u_int;
mp_uint_t idle_level = args[3].u_bool;
mp_obj_t tx_carrier_obj = args[4].u_obj;
if (clock_div < 1 || clock_div > 255) {
mp_raise_ValueError(MP_ERROR_TEXT("clock_div must be between 1 and 255"));
}
esp32_rmt_obj_t *self = m_new_obj_with_finaliser(esp32_rmt_obj_t);
self->base.type = &esp32_rmt_type;
self->channel_id = channel_id;
self->pin = pin_id;
self->clock_div = clock_div;
self->loop_en = false;
rmt_config_t config = {0};
config.rmt_mode = RMT_MODE_TX;
config.channel = (rmt_channel_t)self->channel_id;
config.gpio_num = self->pin;
config.mem_block_num = 1;
config.tx_config.loop_en = 0;
if (tx_carrier_obj != mp_const_none) {
mp_obj_t *tx_carrier_details = NULL;
mp_obj_get_array_fixed_n(tx_carrier_obj, 3, &tx_carrier_details);
mp_uint_t frequency = mp_obj_get_int(tx_carrier_details[0]);
mp_uint_t duty = mp_obj_get_int(tx_carrier_details[1]);
mp_uint_t level = mp_obj_is_true(tx_carrier_details[2]);
if (frequency == 0) {
mp_raise_ValueError(MP_ERROR_TEXT("tx_carrier frequency must be >0"));
}
if (duty > 100) {
mp_raise_ValueError(MP_ERROR_TEXT("tx_carrier duty must be 0..100"));
}
config.tx_config.carrier_en = 1;
config.tx_config.carrier_freq_hz = frequency;
config.tx_config.carrier_duty_percent = duty;
config.tx_config.carrier_level = level;
} else {
config.tx_config.carrier_en = 0;
}
config.tx_config.idle_output_en = 1;
config.tx_config.idle_level = idle_level;
config.clk_div = self->clock_div;
check_esp_err(rmt_config(&config));
check_esp_err(rmt_driver_install(config.channel, 0, 0));
return MP_OBJ_FROM_PTR(self);
}
STATIC void esp32_rmt_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
esp32_rmt_obj_t *self = MP_OBJ_TO_PTR(self_in);
if (self->pin != -1) {
bool idle_output_en;
rmt_idle_level_t idle_level;
check_esp_err(rmt_get_idle_level(self->channel_id, &idle_output_en, &idle_level));
mp_printf(print, "RMT(channel=%u, pin=%u, source_freq=%u, clock_div=%u, idle_level=%u)",
self->channel_id, self->pin, APB_CLK_FREQ, self->clock_div, idle_level);
} else {
mp_printf(print, "RMT()");
}
}
STATIC mp_obj_t esp32_rmt_deinit(mp_obj_t self_in) {
// fixme: check for valid channel. Return exception if error occurs.
esp32_rmt_obj_t *self = MP_OBJ_TO_PTR(self_in);
if (self->pin != -1) { // Check if channel has already been deinitialised.
rmt_driver_uninstall(self->channel_id);
self->pin = -1; // -1 to indicate RMT is unused
m_free(self->items);
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(esp32_rmt_deinit_obj, esp32_rmt_deinit);
// Return the source frequency.
// Currently only the APB clock (80MHz) can be used but it is possible other
// clock sources will added in the future.
STATIC mp_obj_t esp32_rmt_source_freq(mp_obj_t self_in) {
return mp_obj_new_int(APB_CLK_FREQ);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(esp32_rmt_source_freq_obj, esp32_rmt_source_freq);
// Return the clock divider.
STATIC mp_obj_t esp32_rmt_clock_div(mp_obj_t self_in) {
esp32_rmt_obj_t *self = MP_OBJ_TO_PTR(self_in);
return mp_obj_new_int(self->clock_div);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(esp32_rmt_clock_div_obj, esp32_rmt_clock_div);
// Query whether the channel has finished sending pulses. Takes an optional
// timeout (in milliseconds), returning true if the pulse stream has
// completed or false if they are still transmitting (or timeout is reached).
STATIC mp_obj_t esp32_rmt_wait_done(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_self, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = mp_const_none} },
{ MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
};
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
esp32_rmt_obj_t *self = MP_OBJ_TO_PTR(args[0].u_obj);
esp_err_t err = rmt_wait_tx_done(self->channel_id, args[1].u_int / portTICK_PERIOD_MS);
return err == ESP_OK ? mp_const_true : mp_const_false;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(esp32_rmt_wait_done_obj, 1, esp32_rmt_wait_done);
STATIC mp_obj_t esp32_rmt_loop(mp_obj_t self_in, mp_obj_t loop) {
esp32_rmt_obj_t *self = MP_OBJ_TO_PTR(self_in);
self->loop_en = mp_obj_get_int(loop);
if (!self->loop_en) {
bool loop_en;
check_esp_err(rmt_get_tx_loop_mode(self->channel_id, &loop_en));
if (loop_en) {
check_esp_err(rmt_set_tx_loop_mode(self->channel_id, false));
check_esp_err(rmt_set_tx_intr_en(self->channel_id, true));
}
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(esp32_rmt_loop_obj, esp32_rmt_loop);
STATIC mp_obj_t esp32_rmt_write_pulses(size_t n_args, const mp_obj_t *args) {
esp32_rmt_obj_t *self = MP_OBJ_TO_PTR(args[0]);
mp_obj_t duration_obj = args[1];
mp_obj_t data_obj = n_args > 2 ? args[2] : mp_const_true;
mp_uint_t duration = 0;
size_t duration_length = 0;
mp_obj_t *duration_ptr = NULL;
mp_uint_t data = 0;
size_t data_length = 0;
mp_obj_t *data_ptr = NULL;
mp_uint_t num_pulses = 0;
if (!(mp_obj_is_type(data_obj, &mp_type_tuple) || mp_obj_is_type(data_obj, &mp_type_list))) {
// Mode 1: array of durations, toggle initial data value
mp_obj_get_array(duration_obj, &duration_length, &duration_ptr);
data = mp_obj_is_true(data_obj);
num_pulses = duration_length;
} else if (mp_obj_is_int(duration_obj)) {
// Mode 2: constant duration, array of data values
duration = mp_obj_get_int(duration_obj);
mp_obj_get_array(data_obj, &data_length, &data_ptr);
num_pulses = data_length;
} else {
// Mode 3: arrays of durations and data values
mp_obj_get_array(duration_obj, &duration_length, &duration_ptr);
mp_obj_get_array(data_obj, &data_length, &data_ptr);
if (duration_length != data_length) {
mp_raise_ValueError(MP_ERROR_TEXT("duration and data must have same length"));
}
num_pulses = duration_length;
}
if (num_pulses == 0) {
mp_raise_ValueError(MP_ERROR_TEXT("No pulses"));
}
if (self->loop_en && num_pulses > 126) {
mp_raise_ValueError(MP_ERROR_TEXT("Too many pulses for loop"));
}
mp_uint_t num_items = (num_pulses / 2) + (num_pulses % 2);
if (num_items > self->num_items) {
self->items = (rmt_item32_t *)m_realloc(self->items, num_items * sizeof(rmt_item32_t *));
self->num_items = num_items;
}
for (mp_uint_t item_index = 0, pulse_index = 0; item_index < num_items; item_index++) {
self->items[item_index].duration0 = duration_length ? mp_obj_get_int(duration_ptr[pulse_index]) : duration;
self->items[item_index].level0 = data_length ? mp_obj_is_true(data_ptr[pulse_index]) : data++;
pulse_index++;
if (pulse_index < num_pulses) {
self->items[item_index].duration1 = duration_length ? mp_obj_get_int(duration_ptr[pulse_index]) : duration;
self->items[item_index].level1 = data_length ? mp_obj_is_true(data_ptr[pulse_index]) : data++;
pulse_index++;
} else {
self->items[item_index].duration1 = 0;
self->items[item_index].level1 = 0;
}
}
if (self->loop_en) {
bool loop_en;
check_esp_err(rmt_get_tx_loop_mode(self->channel_id, &loop_en));
if (loop_en) {
check_esp_err(rmt_set_tx_intr_en(self->channel_id, true));
check_esp_err(rmt_set_tx_loop_mode(self->channel_id, false));
}
check_esp_err(rmt_wait_tx_done(self->channel_id, portMAX_DELAY));
}
check_esp_err(rmt_write_items(self->channel_id, self->items, num_items, false));
if (self->loop_en) {
check_esp_err(rmt_set_tx_intr_en(self->channel_id, false));
check_esp_err(rmt_set_tx_loop_mode(self->channel_id, true));
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(esp32_rmt_write_pulses_obj, 2, 3, esp32_rmt_write_pulses);
STATIC const mp_rom_map_elem_t esp32_rmt_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&esp32_rmt_deinit_obj) },
{ MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&esp32_rmt_deinit_obj) },
{ MP_ROM_QSTR(MP_QSTR_source_freq), MP_ROM_PTR(&esp32_rmt_source_freq_obj) },
{ MP_ROM_QSTR(MP_QSTR_clock_div), MP_ROM_PTR(&esp32_rmt_clock_div_obj) },
{ MP_ROM_QSTR(MP_QSTR_wait_done), MP_ROM_PTR(&esp32_rmt_wait_done_obj) },
{ MP_ROM_QSTR(MP_QSTR_loop), MP_ROM_PTR(&esp32_rmt_loop_obj) },
{ MP_ROM_QSTR(MP_QSTR_write_pulses), MP_ROM_PTR(&esp32_rmt_write_pulses_obj) },
};
STATIC MP_DEFINE_CONST_DICT(esp32_rmt_locals_dict, esp32_rmt_locals_dict_table);
const mp_obj_type_t esp32_rmt_type = {
{ &mp_type_type },
.name = MP_QSTR_RMT,
.print = esp32_rmt_print,
.make_new = esp32_rmt_make_new,
.locals_dict = (mp_obj_dict_t *)&esp32_rmt_locals_dict,
};
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/esp32_rmt.c | C | apache-2.0 | 12,574 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2018 "Andreas Valder" <andreas.valder@serioese.gmbh>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "py/runtime.h"
#if CONFIG_IDF_TARGET_ESP32
#include "esp32/ulp.h"
#include "esp_err.h"
typedef struct _esp32_ulp_obj_t {
mp_obj_base_t base;
} esp32_ulp_obj_t;
const mp_obj_type_t esp32_ulp_type;
// singleton ULP object
STATIC const esp32_ulp_obj_t esp32_ulp_obj = {{&esp32_ulp_type}};
STATIC mp_obj_t esp32_ulp_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
// check arguments
mp_arg_check_num(n_args, n_kw, 0, 0, false);
// return constant object
return (mp_obj_t)&esp32_ulp_obj;
}
STATIC mp_obj_t esp32_ulp_set_wakeup_period(mp_obj_t self_in, mp_obj_t period_index_in, mp_obj_t period_us_in) {
mp_uint_t period_index = mp_obj_get_int(period_index_in);
mp_uint_t period_us = mp_obj_get_int(period_us_in);
int _errno = ulp_set_wakeup_period(period_index, period_us);
if (_errno != ESP_OK) {
mp_raise_OSError(_errno);
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp32_ulp_set_wakeup_period_obj, esp32_ulp_set_wakeup_period);
STATIC mp_obj_t esp32_ulp_load_binary(mp_obj_t self_in, mp_obj_t load_addr_in, mp_obj_t program_binary_in) {
mp_uint_t load_addr = mp_obj_get_int(load_addr_in);
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(program_binary_in, &bufinfo, MP_BUFFER_READ);
int _errno = ulp_load_binary(load_addr, bufinfo.buf, bufinfo.len / sizeof(uint32_t));
if (_errno != ESP_OK) {
mp_raise_OSError(_errno);
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp32_ulp_load_binary_obj, esp32_ulp_load_binary);
STATIC mp_obj_t esp32_ulp_run(mp_obj_t self_in, mp_obj_t entry_point_in) {
mp_uint_t entry_point = mp_obj_get_int(entry_point_in);
int _errno = ulp_run(entry_point / sizeof(uint32_t));
if (_errno != ESP_OK) {
mp_raise_OSError(_errno);
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(esp32_ulp_run_obj, esp32_ulp_run);
STATIC const mp_rom_map_elem_t esp32_ulp_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_set_wakeup_period), MP_ROM_PTR(&esp32_ulp_set_wakeup_period_obj) },
{ MP_ROM_QSTR(MP_QSTR_load_binary), MP_ROM_PTR(&esp32_ulp_load_binary_obj) },
{ MP_ROM_QSTR(MP_QSTR_run), MP_ROM_PTR(&esp32_ulp_run_obj) },
{ MP_ROM_QSTR(MP_QSTR_RESERVE_MEM), MP_ROM_INT(CONFIG_ESP32_ULP_COPROC_RESERVE_MEM) },
};
STATIC MP_DEFINE_CONST_DICT(esp32_ulp_locals_dict, esp32_ulp_locals_dict_table);
const mp_obj_type_t esp32_ulp_type = {
{ &mp_type_type },
.name = MP_QSTR_ULP,
.make_new = esp32_ulp_make_new,
.locals_dict = (mp_obj_t)&esp32_ulp_locals_dict,
};
#endif // CONFIG_IDF_TARGET_ESP32
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/esp32_ulp.c | C | apache-2.0 | 3,901 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* Development of the code in this file was sponsored by Microbric Pty Ltd
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014, 2016 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <sys/time.h>
#include "lib/oofatfs/ff.h"
#include "shared/timeutils/timeutils.h"
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/fatfs_port.c | C | apache-2.0 | 1,408 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
*
* 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.
*/
#ifndef MICROPY_INCLUDED_STM32_FONT_PETME128_8X8_H
#define MICROPY_INCLUDED_STM32_FONT_PETME128_8X8_H
static const uint8_t font_petme128_8x8[] = {
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // 32=
0x00,0x00,0x00,0x4f,0x4f,0x00,0x00,0x00, // 33=!
0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00, // 34="
0x14,0x7f,0x7f,0x14,0x14,0x7f,0x7f,0x14, // 35=#
0x00,0x24,0x2e,0x6b,0x6b,0x3a,0x12,0x00, // 36=$
0x00,0x63,0x33,0x18,0x0c,0x66,0x63,0x00, // 37=%
0x00,0x32,0x7f,0x4d,0x4d,0x77,0x72,0x50, // 38=&
0x00,0x00,0x00,0x04,0x06,0x03,0x01,0x00, // 39='
0x00,0x00,0x1c,0x3e,0x63,0x41,0x00,0x00, // 40=(
0x00,0x00,0x41,0x63,0x3e,0x1c,0x00,0x00, // 41=)
0x08,0x2a,0x3e,0x1c,0x1c,0x3e,0x2a,0x08, // 42=*
0x00,0x08,0x08,0x3e,0x3e,0x08,0x08,0x00, // 43=+
0x00,0x00,0x80,0xe0,0x60,0x00,0x00,0x00, // 44=,
0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, // 45=-
0x00,0x00,0x00,0x60,0x60,0x00,0x00,0x00, // 46=.
0x00,0x40,0x60,0x30,0x18,0x0c,0x06,0x02, // 47=/
0x00,0x3e,0x7f,0x49,0x45,0x7f,0x3e,0x00, // 48=0
0x00,0x40,0x44,0x7f,0x7f,0x40,0x40,0x00, // 49=1
0x00,0x62,0x73,0x51,0x49,0x4f,0x46,0x00, // 50=2
0x00,0x22,0x63,0x49,0x49,0x7f,0x36,0x00, // 51=3
0x00,0x18,0x18,0x14,0x16,0x7f,0x7f,0x10, // 52=4
0x00,0x27,0x67,0x45,0x45,0x7d,0x39,0x00, // 53=5
0x00,0x3e,0x7f,0x49,0x49,0x7b,0x32,0x00, // 54=6
0x00,0x03,0x03,0x79,0x7d,0x07,0x03,0x00, // 55=7
0x00,0x36,0x7f,0x49,0x49,0x7f,0x36,0x00, // 56=8
0x00,0x26,0x6f,0x49,0x49,0x7f,0x3e,0x00, // 57=9
0x00,0x00,0x00,0x24,0x24,0x00,0x00,0x00, // 58=:
0x00,0x00,0x80,0xe4,0x64,0x00,0x00,0x00, // 59=;
0x00,0x08,0x1c,0x36,0x63,0x41,0x41,0x00, // 60=<
0x00,0x14,0x14,0x14,0x14,0x14,0x14,0x00, // 61==
0x00,0x41,0x41,0x63,0x36,0x1c,0x08,0x00, // 62=>
0x00,0x02,0x03,0x51,0x59,0x0f,0x06,0x00, // 63=?
0x00,0x3e,0x7f,0x41,0x4d,0x4f,0x2e,0x00, // 64=@
0x00,0x7c,0x7e,0x0b,0x0b,0x7e,0x7c,0x00, // 65=A
0x00,0x7f,0x7f,0x49,0x49,0x7f,0x36,0x00, // 66=B
0x00,0x3e,0x7f,0x41,0x41,0x63,0x22,0x00, // 67=C
0x00,0x7f,0x7f,0x41,0x63,0x3e,0x1c,0x00, // 68=D
0x00,0x7f,0x7f,0x49,0x49,0x41,0x41,0x00, // 69=E
0x00,0x7f,0x7f,0x09,0x09,0x01,0x01,0x00, // 70=F
0x00,0x3e,0x7f,0x41,0x49,0x7b,0x3a,0x00, // 71=G
0x00,0x7f,0x7f,0x08,0x08,0x7f,0x7f,0x00, // 72=H
0x00,0x00,0x41,0x7f,0x7f,0x41,0x00,0x00, // 73=I
0x00,0x20,0x60,0x41,0x7f,0x3f,0x01,0x00, // 74=J
0x00,0x7f,0x7f,0x1c,0x36,0x63,0x41,0x00, // 75=K
0x00,0x7f,0x7f,0x40,0x40,0x40,0x40,0x00, // 76=L
0x00,0x7f,0x7f,0x06,0x0c,0x06,0x7f,0x7f, // 77=M
0x00,0x7f,0x7f,0x0e,0x1c,0x7f,0x7f,0x00, // 78=N
0x00,0x3e,0x7f,0x41,0x41,0x7f,0x3e,0x00, // 79=O
0x00,0x7f,0x7f,0x09,0x09,0x0f,0x06,0x00, // 80=P
0x00,0x1e,0x3f,0x21,0x61,0x7f,0x5e,0x00, // 81=Q
0x00,0x7f,0x7f,0x19,0x39,0x6f,0x46,0x00, // 82=R
0x00,0x26,0x6f,0x49,0x49,0x7b,0x32,0x00, // 83=S
0x00,0x01,0x01,0x7f,0x7f,0x01,0x01,0x00, // 84=T
0x00,0x3f,0x7f,0x40,0x40,0x7f,0x3f,0x00, // 85=U
0x00,0x1f,0x3f,0x60,0x60,0x3f,0x1f,0x00, // 86=V
0x00,0x7f,0x7f,0x30,0x18,0x30,0x7f,0x7f, // 87=W
0x00,0x63,0x77,0x1c,0x1c,0x77,0x63,0x00, // 88=X
0x00,0x07,0x0f,0x78,0x78,0x0f,0x07,0x00, // 89=Y
0x00,0x61,0x71,0x59,0x4d,0x47,0x43,0x00, // 90=Z
0x00,0x00,0x7f,0x7f,0x41,0x41,0x00,0x00, // 91=[
0x00,0x02,0x06,0x0c,0x18,0x30,0x60,0x40, // 92='\'
0x00,0x00,0x41,0x41,0x7f,0x7f,0x00,0x00, // 93=]
0x00,0x08,0x0c,0x06,0x06,0x0c,0x08,0x00, // 94=^
0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0, // 95=_
0x00,0x00,0x01,0x03,0x06,0x04,0x00,0x00, // 96=`
0x00,0x20,0x74,0x54,0x54,0x7c,0x78,0x00, // 97=a
0x00,0x7f,0x7f,0x44,0x44,0x7c,0x38,0x00, // 98=b
0x00,0x38,0x7c,0x44,0x44,0x6c,0x28,0x00, // 99=c
0x00,0x38,0x7c,0x44,0x44,0x7f,0x7f,0x00, // 100=d
0x00,0x38,0x7c,0x54,0x54,0x5c,0x58,0x00, // 101=e
0x00,0x08,0x7e,0x7f,0x09,0x03,0x02,0x00, // 102=f
0x00,0x98,0xbc,0xa4,0xa4,0xfc,0x7c,0x00, // 103=g
0x00,0x7f,0x7f,0x04,0x04,0x7c,0x78,0x00, // 104=h
0x00,0x00,0x00,0x7d,0x7d,0x00,0x00,0x00, // 105=i
0x00,0x40,0xc0,0x80,0x80,0xfd,0x7d,0x00, // 106=j
0x00,0x7f,0x7f,0x30,0x38,0x6c,0x44,0x00, // 107=k
0x00,0x00,0x41,0x7f,0x7f,0x40,0x00,0x00, // 108=l
0x00,0x7c,0x7c,0x18,0x30,0x18,0x7c,0x7c, // 109=m
0x00,0x7c,0x7c,0x04,0x04,0x7c,0x78,0x00, // 110=n
0x00,0x38,0x7c,0x44,0x44,0x7c,0x38,0x00, // 111=o
0x00,0xfc,0xfc,0x24,0x24,0x3c,0x18,0x00, // 112=p
0x00,0x18,0x3c,0x24,0x24,0xfc,0xfc,0x00, // 113=q
0x00,0x7c,0x7c,0x04,0x04,0x0c,0x08,0x00, // 114=r
0x00,0x48,0x5c,0x54,0x54,0x74,0x20,0x00, // 115=s
0x04,0x04,0x3f,0x7f,0x44,0x64,0x20,0x00, // 116=t
0x00,0x3c,0x7c,0x40,0x40,0x7c,0x3c,0x00, // 117=u
0x00,0x1c,0x3c,0x60,0x60,0x3c,0x1c,0x00, // 118=v
0x00,0x1c,0x7c,0x30,0x18,0x30,0x7c,0x1c, // 119=w
0x00,0x44,0x6c,0x38,0x38,0x6c,0x44,0x00, // 120=x
0x00,0x9c,0xbc,0xa0,0xa0,0xfc,0x7c,0x00, // 121=y
0x00,0x44,0x64,0x74,0x5c,0x4c,0x44,0x00, // 122=z
0x00,0x08,0x08,0x3e,0x77,0x41,0x41,0x00, // 123={
0x00,0x00,0x00,0xff,0xff,0x00,0x00,0x00, // 124=|
0x00,0x41,0x41,0x77,0x3e,0x08,0x08,0x00, // 125=}
0x00,0x02,0x03,0x01,0x03,0x02,0x03,0x01, // 126=~
0xaa,0x55,0xaa,0x55,0xaa,0x55,0xaa,0x55, // 127
};
#endif // MICROPY_INCLUDED_STM32_FONT_PETME128_8X8_H
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/font_petme128_8x8.h | C | apache-2.0 | 6,551 |
import kv
import time
import _thread
import uos
def _on_get_url(url):
kv.set('_amp_pyapp_url',url)
execfile('/lib/appOta.py')
def _connect_wifi():
time.sleep(5)
ssid = kv.get('_amp_wifi_ssid')
passwd = kv.get('_amp_wifi_passwd')
if isinstance(ssid,str) and isinstance(passwd,str):
import network
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
sta_if.active(True)
sta_if.connect(ssid,passwd)
bt_disabled = kv.get('disable_bt')
if bt_disabled != "no":
uos.plussys_mm()
channel = kv.get('app_upgrade_channel')
if channel == "enable":
import online_upgrade
online_upgrade.on(_on_get_url)
try:
_thread.start_new_thread(_connect_wifi, ())
#_thread.stack_size(10 * 1024)
except Exception as e:
print(e)
app_upgrade = kv.get('_amp_app_upgrade')
if app_upgrade == "enable":
print("App is being upgraded. It will take about 10 seconds.")
execfile('/lib/appUpgrade.py')
kv.remove('_amp_app_upgrade')
print("App upgrade finished.")
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/fs/boot.py | Python | apache-2.0 | 1,086 |
import uos as os
import uerrno as errno
import ujson as json
import uzlib
import upip_utarfile as tarfile
import gc
import time
import ussl
import usocket
import kv
import machine
file_buf = bytearray(128)
def install_pkg(package_url, install_path):
gzdict_sz = 16 + 15
f1 = url_open(package_url)
if (isinstance(f1, (str, bytes, bytearray)) == True):
return f1
try:
f2 = uzlib.DecompIO(f1, gzdict_sz)
f3 = tarfile.TarFile(fileobj=f2)
install_tar(f3, install_path)
except Exception as e:
print(e)
return ("UNTAR_FILE_FAIL")
finally:
f1.close()
del f3
del f2
gc.collect()
return 'SUCCESS'
def download_save_file(file_url, fname):
global file_buf
f1 = url_open(file_url)
if (isinstance(f1, (str, bytes, bytearray)) == True):
return f1
_makedirs(fname)
with open(fname, "wb") as outf:
while True:
sz = f1.readinto(file_buf)
if not sz:
break
outf.write(file_buf, sz)
outf.close()
f1.close()
del f1
return 'SUCCESS'
def url_open(url):
proto, _, host, urlpath = url.split('/', 3)
try:
port = 443
if ":" in host:
host, port = host.split(":")
port = int(port)
ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM)
except OSError as e:
print("Error:", "Unable to resolve %s (no Internet?)" % host, e)
return 'HOST_RESOLVED_FAIL'
ai = ai[0]
s = usocket.socket(ai[0], ai[1], ai[2])
try:
s.connect(ai[-1])
if proto == "https:":
s = ussl.wrap_socket(s, server_hostname=host)
s.write("GET /%s HTTP/1.0\r\nHost: %s:%s\r\n\r\n" %
(urlpath, host, port))
l = s.readline()
protover, status, msg = l.split(None, 2)
if status != b"200":
if status == b"404" or status == b"301":
return ("Package not found")
else:
print("status is {}".format(status))
return (status)
while True:
l = s.readline()
if not l:
return ("Unexpected EOF in HTTP headers")
if l == b'\r\n':
break
except Exception as e:
s.close()
print(e)
return ('SOCKET_ERROR')
return s
def _makedirs(name, mode=0o777):
ret = False
s = ""
comps = name.rstrip("/").split("/")[:-1]
if comps[0] == "":
s = "/"
for c in comps:
if s and s[-1] != "/":
s += "/"
s += c
try:
os.mkdir(s)
ret = True
except OSError as e:
if e.args[0] != errno.EEXIST and e.args[0] != errno.EISDIR:
print(e)
ret = False
return ret
def install_tar(f, prefix):
for info in f:
fname = info.name
#try:
#fname = fname[fname.index("/") + 1:]
#except ValueError:
#fname = ""
outfname = prefix + fname
if info.type != tarfile.DIRTYPE:
_makedirs(outfname)
subf = f.extractfile(info)
save_file(outfname, subf)
def save_file(fname, subf):
global file_buf
with open(fname, "wb") as outf:
while True:
sz = subf.readinto(file_buf)
if not sz:
break
outf.write(file_buf, sz)
outf.close()
#download_save_file(url,"/data/pyamp/main.py")
if __name__ == "__main__":
url = kv.get('_amp_pyapp_url')
if isinstance(url, str):
install_pkg(url, "/data/pyamp/")
kv.remove('_amp_pyapp_url')
machine.reset()
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/fs/lib/appOta.py | Python | apache-2.0 | 3,702 |
import uos as os
import uerrno as errno
import ujson as json
import uzlib
import upip_utarfile as tarfile
import gc
import time
import ussl
import usocket
import kv
import network
import time
file_buf = bytearray(128)
def install_pkg(package_url, install_path):
gzdict_sz = 16 + 15
f1 = url_open(package_url)
if(isinstance(f1, (str, bytes, bytearray)) == True):
return f1
try:
f2 = uzlib.DecompIO(f1, gzdict_sz)
f3 = tarfile.TarFile(fileobj=f2)
install_tar(f3, install_path)
except Exception as e:
print(e)
return("UNTAR_FILE_FAIL")
finally:
f1.close()
del f3
del f2
gc.collect()
return 'SUCCESS'
def download_save_file(file_url, fname):
global file_buf
f1 = url_open(file_url)
if(isinstance(f1, (str, bytes, bytearray)) == True):
return f1
_makedirs(fname)
with open(fname, "wb") as outf:
while True:
sz = f1.readinto(file_buf)
if not sz:
break
outf.write(file_buf, sz)
outf.close()
f1.close()
del f1
return 'SUCCESS'
def url_open(url):
proto, _, host, urlpath = url.split('/', 3)
try:
port = 443
if ":" in host:
host, port = host.split(":")
port = int(port)
ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM)
except OSError as e:
print("Error:", "Unable to resolve %s (no Internet?)" % host, e)
return 'HOST_RESOLVED_FAIL'
ai = ai[0]
s = usocket.socket(ai[0], ai[1], ai[2])
try:
s.connect(ai[-1])
if proto == "https:":
s = ussl.wrap_socket(s, server_hostname=host)
s.write("GET /%s HTTP/1.0\r\nHost: %s:%s\r\n\r\n" % (urlpath, host, port))
l = s.readline()
protover, status, msg = l.split(None, 2)
if status != b"200":
if status == b"404" or status == b"301":
return("Package not found")
else:
print("status is {}".format(status))
return(status)
while True:
l = s.readline()
if not l:
return("Unexpected EOF in HTTP headers")
if l == b'\r\n':
break
except Exception as e:
s.close()
print(e)
return('SOCKET_ERROR')
return s
def _makedirs(name, mode=0o777):
ret = False
s = ""
comps = name.rstrip("/").split("/")[:-1]
if comps[0] == "":
s = "/"
for c in comps:
if s and s[-1] != "/":
s += "/"
s += c
try:
os.mkdir(s)
ret = True
except OSError as e:
if e.args[0] != errno.EEXIST and e.args[0] != errno.EISDIR:
print(e)
ret = False
return ret
def install_tar(f, prefix):
for info in f:
fname = info.name
#try:
#fname = fname[fname.index("/") + 1:]
#except ValueError:
#fname = ""
outfname = prefix + fname
if info.type != tarfile.DIRTYPE:
_makedirs(outfname)
subf = f.extractfile(info)
save_file(outfname, subf)
def save_file(fname, subf):
global file_buf
with open(fname, "wb") as outf:
while True:
sz = subf.readinto(file_buf)
if not sz:
break
outf.write(file_buf, sz)
outf.close()
#download_save_file(url,"/data/pyamp/main.py")
def connect_wifi(ssid,passwd):
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.scan()
sta_if.connect(ssid,passwd)
time.sleep(5)
return sta_if.isconnected()
if __name__ == "__main__":
ssid = kv.get('_amp_wifi_ssid')
passwd = kv.get('_amp_wifi_passwd')
if isinstance(ssid,str) and isinstance(passwd,str):
if connect_wifi(ssid,passwd):
url = kv.get('_amp_pyapp_url')
if isinstance(url,str):
install_pkg(url,"/data/pyamp/")
kv.remove('_amp_pyapp_url')
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/fs/lib/appUpgrade.py | Python | apache-2.0 | 4,070 |
import bluetooth
import struct
import json
import gc
import time
import network
from micropython import const
_wlan = network.WLAN(network.STA_IF)
_ble = bluetooth.BLE()
_bleNetConfigStatus = None
_ble_adv_name = 'esp-node'
_ble_tx = None
_ble_rx = None
_ble_msg = ''
BLE_CONNECTED = const(0x00)
BLE_DISCONNECTED = const(0x01)
BLE_COMMINICATING = const(0x02)
WIFI_IDLE = 1000
WIFI_CONNECTING = 1001
WIFI_GOT_IP = network.STAT_GOT_IP
NUS_UUID = 0xFFA0
RX_UUID = 0xFFA2
TX_UUID = 0xFFA3
BLE_NUS = bluetooth.UUID(NUS_UUID)
BLE_RX = (bluetooth.UUID(RX_UUID), bluetooth.FLAG_WRITE)
BLE_TX = (bluetooth.UUID(TX_UUID),
bluetooth.FLAG_NOTIFY | bluetooth.FLAG_READ)
BLE_UART = (BLE_NUS, (BLE_TX, BLE_RX,))
SERVICES = [BLE_UART, ]
# Generate a payload to be passed to gap_advertise(adv_data=...).
# Helpers for generating BLE advertising payloads.
# Advertising payloads are repeated packets of the following form:
# 1 byte data length (N + 1)
# 1 byte type (see constants below)
# N bytes type-specific data
_ADV_TYPE_FLAGS = const(0x01)
_ADV_TYPE_NAME = const(0x09)
_ADV_TYPE_UUID16_COMPLETE = const(0x3)
_ADV_TYPE_UUID32_COMPLETE = const(0x5)
_ADV_TYPE_UUID128_COMPLETE = const(0x7)
_ADV_TYPE_UUID16_MORE = const(0x2)
_ADV_TYPE_UUID32_MORE = const(0x4)
_ADV_TYPE_UUID128_MORE = const(0x6)
_ADV_TYPE_APPEARANCE = const(0x19)
def advertising_payload(limited_disc=False, br_edr=False, name=None, services=None, appearance=0):
payload = bytearray()
def _append(adv_type, value):
nonlocal payload
payload += struct.pack("BB", len(value) + 1, adv_type) + value
_append(
_ADV_TYPE_FLAGS,
struct.pack("B", (0x01 if limited_disc else 0x02) +
(0x18 if br_edr else 0x04)),
)
if name:
_append(_ADV_TYPE_NAME, name)
if services:
for uuid in services:
b = bytes(uuid)
if len(b) == 2:
_append(_ADV_TYPE_UUID16_COMPLETE, b)
elif len(b) == 4:
_append(_ADV_TYPE_UUID32_COMPLETE, b)
elif len(b) == 16:
_append(_ADV_TYPE_UUID128_COMPLETE, b)
# See org.bluetooth.characteristic.gap.appearance.xml
if appearance:
_append(_ADV_TYPE_APPEARANCE, struct.pack("<h", appearance))
return payload
# region not used, but might be useful
def decode_field(payload, adv_type):
i = 0
result = []
while i + 1 < len(payload):
if payload[i + 1] == adv_type:
result.append(payload[i + 2: i + payload[i] + 1])
i += 1 + payload[i]
return result
def decode_name(payload):
n = decode_field(payload, _ADV_TYPE_NAME)
return str(n[0], "utf-8") if n else ""
def decode_services(payload):
services = []
for u in decode_field(payload, _ADV_TYPE_UUID16_COMPLETE):
services.append(bluetooth.UUID(struct.unpack("<h", u)[0]))
for u in decode_field(payload, _ADV_TYPE_UUID32_COMPLETE):
services.append(bluetooth.UUID(struct.unpack("<d", u)[0]))
for u in decode_field(payload, _ADV_TYPE_UUID128_COMPLETE):
services.append(bluetooth.UUID(u))
return services
# endregion
def send(data):
_ble.gatts_notify(0, _ble_tx, data + '\n')
def advertiser(name):
payload = advertising_payload(
name=name, services=[bluetooth.UUID(NUS_UUID)])
_ble.gap_advertise(interval_us=100, adv_data=payload)
def ble_irq(event, data):
global _ble_msg, _bleNetConfigStatus
if event == 1:
_bleNetConfigStatus = BLE_CONNECTED
elif event == 2:
_bleNetConfigStatus = BLE_DISCONNECTED
advertiser(_ble_adv_name)
elif event == 3:
buffer = _ble.gatts_read(_ble_rx)
_ble_msg += buffer.decode('hex').strip()
_ble_msg = '{"cmd":' + _ble_msg.split('{"cmd":')[-1]
if(_ble_msg.count('{') == _ble_msg.count('}')):
try:
cmdd = json.loads(_ble_msg)
except Exception as e:
pass
else:
if(cmdd['cmd'] == 'WiFiCon'):
_wlan.active(True)
if(_wlan.isconnected()):
_wlan.disconnect()
_wlan.connect(cmdd['param']['ssid'], cmdd['param']['pswd'])
timeout = 5
if('timeout' in cmdd['param'].keys()):
timeout = int(cmdd['param']['timeout'])
while(True):
status = _wlan.status()
if(status == network.STAT_WRONG_PASSWORD):
_bleNetConfigStatus = BLE_COMMINICATING
ret = {'cmd': 'WiFiCon', 'ret': {
'state': 'STAT_WRONG_PASSWORD'}}
send(json.dumps(ret).encode('hex'))
_bleNetConfigStatus = BLE_CONNECTED
break
if(status == network.STAT_NO_AP_FOUND):
_bleNetConfigStatus = BLE_COMMINICATING
ret = {'cmd': 'WiFiCon', 'ret': {
'state': 'STAT_NO_AP_FOUND'}}
send(json.dumps(ret).encode('hex'))
_bleNetConfigStatus = BLE_CONNECTED
break
if(status == network.STAT_GOT_IP):
_bleNetConfigStatus = BLE_COMMINICATING
ret = {'cmd': 'WiFiCon', 'ret': {
'state': 'STAT_GOT_IP', 'ifconfig': _wlan.ifconfig()}}
send(json.dumps(ret).encode('hex'))
_bleNetConfigStatus = BLE_CONNECTED
break
if(status == 1001):
pass
if(timeout < 0):
_bleNetConfigStatus = BLE_COMMINICATING
ret = {'cmd': 'WiFiCon', 'ret': {
'state': 'STAT_CONNECT_TIMEOUT'}}
send(json.dumps(ret).encode('hex'))
_bleNetConfigStatus = BLE_CONNECTED
break
time.sleep(1)
timeout -= 1
_ble_msg = ''
gc.collect()
# set name as start parm rather than another func like 'setName' to prevent user change name when ble processing
def start(name):
global _ble, _ble_tx, _ble_rx, _bleNetConfigStatus, _ble_adv_name
_ble_adv_name = name
_ble.active(True)
((_ble_tx, _ble_rx,), ) = _ble.gatts_register_services(SERVICES)
_ble.irq(ble_irq)
advertiser(_ble_adv_name)
_bleNetConfigStatus = BLE_DISCONNECTED
def stop():
global _ble, _bleNetConfigStatus
_ble.irq(None)
_ble.active(False)
_bleNetConfigStatus = BLE_DISCONNECTED
def getWLAN():
return _wlan
def getBleStatus():
return _bleNetConfigStatus
def getWiFiStatus():
return _wlan.status()
def getWiFiConfig():
return _wlan.ifconfig()
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/fs/lib/bleNetConfig.py | Python | apache-2.0 | 7,111 |
"""
Copyright (C) 2015-2021 Alibaba Group Holding Limited
MicroPython's driver for CHT8305
Author: HaaS
Date: 2022/05/11
"""
import lvgl as lv
import lvgl_display
print("display_driver init")
if not lv.is_initialized():
#print("lv.init")
lv.init()
if not lvgl_display.is_initialized():
#print("lvgl_display.init")
lvgl_display.init()
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/fs/lib/display_driver.py | Python | apache-2.0 | 369 |
print('enable OneMinuteOnCloud')
import ubluetooth
import uos as os
import uerrno as errno
import ujson as json
import uzlib
import upip_utarfile as tarfile
import gc
import time
import machine
import ussl
import usocket
import network
_wlan = network.WLAN(network.STA_IF)
_ble = ubluetooth.BLE()
_ble_adv_name = 'esp-node'
pull_code_state = []
file_buf = bytearray(128)
def download_file_task(filelist):
global pull_code_state
for file_task in filelist:
if('needunpack' in file_task.keys() and file_task['needunpack'] == True):
gc.collect()
print(gc.mem_free())
pull_code_state.append(install_pkg(file_task['url'], file_task['path']))
gc.collect()
else:
gc.collect()
print(gc.mem_free())
pull_code_state.append(download_save_file(file_task['url'], file_task['path']+file_task['name']))
gc.collect()
def download_save_file(file_url, fname):
global file_buf
f1 = url_open(file_url)
if(isinstance(f1, (str, bytes, bytearray)) == True):
print(f1)
return f1
print(fname)
_makedirs(fname)
with open(fname, "wb") as outf:
while True:
sz = f1.readinto(file_buf)
if not sz:
break
outf.write(file_buf, sz)
outf.close()
f1.close()
del f1
print('download_save_file success')
return 'SUCCESS'
def install_pkg(package_url, install_path):
gzdict_sz = 16 + 15
f1 = url_open(package_url)
if(isinstance(f1, (str, bytes, bytearray)) == True):
print(f1)
return f1
try:
f2 = uzlib.DecompIO(f1, gzdict_sz)
f3 = tarfile.TarFile(fileobj=f2)
install_tar(f3, install_path)
except Exception as e:
print(e)
return("UNTAR_FILE_FAIL")
finally:
f1.close()
del f3
del f2
gc.collect()
print('install_pkg success')
return 'SUCCESS'
def url_open(url):
proto, _, host, urlpath = url.split('/', 3)
try:
port = 443
if ":" in host:
host, port = host.split(":")
port = int(port)
ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM)
except OSError as e:
print("Error:", "Unable to resolve %s (no Internet?)" % host, e)
return 'HOST_RESOLVED_FAIL'
print("Address infos:", ai)
ai = ai[0]
s = usocket.socket(ai[0], ai[1], ai[2])
try:
s.connect(ai[-1])
if proto == "https:":
s = ussl.wrap_socket(s, server_hostname=host)
s.write("GET /%s HTTP/1.0\r\nHost: %s:%s\r\n\r\n" % (urlpath, host, port))
l = s.readline()
protover, status, msg = l.split(None, 2)
if status != b"200":
if status == b"404" or status == b"301":
return("Package not found")
return(status)
while True:
l = s.readline()
if not l:
return("Unexpected EOF in HTTP headers")
if l == b'\r\n':
break
except Exception as e:
s.close()
print(e)
return('SOCKET_ERROR')
return s
def save_file(fname, subf):
global file_buf
with open(fname, "wb") as outf:
while True:
sz = subf.readinto(file_buf)
if not sz:
break
outf.write(file_buf, sz)
outf.close()
def _makedirs(name, mode=0o777):
ret = False
s = ""
comps = name.rstrip("/").split("/")[:-1]
if comps[0] == "":
s = "/"
for c in comps:
if s and s[-1] != "/":
s += "/"
s += c
try:
os.mkdir(s)
ret = True
except OSError as e:
if e.args[0] != errno.EEXIST and e.args[0] != errno.EISDIR:
print(e)
ret = False
return ret
def install_tar(f, prefix):
for info in f:
print(info)
fname = info.name
try:
fname = fname[fname.index("/") + 1:]
except ValueError:
fname = ""
outfname = prefix + fname
if info.type != tarfile.DIRTYPE:
print("Extracting " + outfname)
_makedirs(outfname)
subf = f.extractfile(info)
save_file(outfname, subf)
def rmvdir(dir):
for i in os.ilistdir(dir):
if i[1] == 16384:
rmvdir('{}/{}'.format(dir,i))
elif i[1] == 32678:
os.remove('{}/{}'.format(dir,i[0]))
os.rmdir(dir)
def send(data):
_ble.gatts_notify(0, _ble_tx, data + '\n')
def advertiser(name):
_name = bytes(name, 'UTF-8')
_ble.gap_advertise(100, bytearray('\x02\x01\x02') + bytearray((len(_name) + 1, 0x09)) + _name)
def ble_irq(event, data):
global ble_msg
if event == 1:
print('Central connected')
global pull_code_state
if(pull_code_state!=[]):
ret = {'cmd':'PullCode', 'ret':{'state':pull_code_state}}
send(json.dumps(ret).encode('hex'))
elif event == 2:
print('Central disconnected')
advertiser("esp-node")
elif event == 3:
buffer = _ble.gatts_read(_ble_rx)
ble_msg += buffer.decode('hex').strip()
ble_msg = '{"cmd":' + ble_msg.split('{"cmd":')[-1]
# only save one cmd
print(ble_msg)
if(ble_msg.count('{') == ble_msg.count('}')):
try:
cmdd = json.loads(ble_msg)
print(cmdd)
if(cmdd['cmd'] == 'WiFiCon'):
_wlan.active(True)
if(_wlan.isconnected()):
_wlan.disconnect()
print(cmdd['param']['ssid'], cmdd['param']['pswd'])
_wlan.connect(cmdd['param']['ssid'], cmdd['param']['pswd'])
timeout = 5
if('timeout' in cmdd['param'].keys()):
timeout = int(cmdd['param']['timeout'])
while(True):
status = _wlan.status()
print(status)
if(status == network.STAT_WRONG_PASSWORD):
print('STAT_WRONG_PASSWORD')
ret = {'cmd':'WiFiCon', 'ret':{'state':'STAT_WRONG_PASSWORD'}}
send(json.dumps(ret).encode('hex'))
break
if(status == network.STAT_NO_AP_FOUND):
print('STAT_NO_AP_FOUND')
ret = {'cmd':'WiFiCon', 'ret':{'state':'STAT_NO_AP_FOUND'}}
send(json.dumps(ret).encode('hex'))
break
if(status == network.STAT_GOT_IP):
print('STAT_GOT_IP')
ret = {'cmd':'WiFiCon', 'ret':{'state':'STAT_GOT_IP', 'ifconfig':_wlan.ifconfig()}}
send(json.dumps(ret).encode('hex'))
wificonf = {"ssid":cmdd['param']['ssid'],"pswd":cmdd['param']['pswd'],"autoConnect":True}
with open('/WiFi.json', "w") as f:
f.write(json.dumps(wificonf) + "\n")
break
if(status == 1001):
print('scaning for ap ...')
if(timeout < 0):
print('STAT_CONNECT_TIMEOUT')
ret = {'cmd':'WiFiCon', 'ret':{'state':'STAT_CONNECT_TIMEOUT'}}
send(json.dumps(ret).encode('hex'))
break
time.sleep(1)
timeout -= 1
if(cmdd['cmd'] == 'PullCode'):
global pull_code_state
if('main.py' in os.listdir('/data/pyamp')):
os.remove('/data/pyamp/main.py')
if(_wlan.isconnected() is False):
print(_wlan.isconnected())
ret = {'cmd':'PullCode', 'ret':{'state':'NO_NETWORK'}}
send(json.dumps(ret).encode('hex'))
else:
# _thread.start_new_thread(download_file_task, (cmdd['param']['filelist'], ))
try:
f = open('/afterlife.json', "w")
f.write(json.dumps(cmdd) + "\n")
f.close()
except Exception as e:
print(e)
pass
else:
# see you afterlife
ret = {'cmd':'PullCode', 'ret':{'state':'START_DOWNLOAD'}}
send(json.dumps(ret).encode('hex'))
if(cmdd['cmd'] == 'DeviceInfo'):
with open('/DeviceInfo.json', "w") as f:
f.write(cmdd['param'] + "\n")
ret = {'cmd':'DeviceInfo', 'ret':{'state':'DeviceInfoRecved'}}
send(json.dumps(ret).encode('hex'))
if(cmdd['cmd'] == 'PullCodeCheck'):
ret = {'cmd':'PullCode', 'ret':{'state':pull_code_state}}
send(json.dumps(ret).encode('hex'))
if(cmdd['cmd'] == 'Reset'):
machine.reset()
ble_msg = ''
gc.collect()
except Exception as e:
pass
if('WiFi.json' in os.listdir('/')):
try:
f = open('/WiFi.json', "r")
wificonf = f.readline()
wificonf = json.loads(wificonf)
f.close()
if('autoConnect' in wificonf.keys() and wificonf['autoConnect'] == True):
print('autoConnect')
_wlan.active(True)
_wlan.connect(wificonf['ssid'], wificonf['pswd'],)
if('main.py' in os.listdir('/data/pyamp')):
os.remove('/WiFi.json')
except Exception as e:
print('try WiFi autoConnect, found')
print(e)
pass
if('afterlife.json' in os.listdir('/')):
try:
f = open('/afterlife.json', "r")
wish = f.readline()
wish = json.loads(wish)
f.close()
print(wish)
time.sleep(5)
if(_wlan.isconnected() == False):
pull_code_state = 'NO_NETWORK'
print('NO_NETWORK')
raise
print('wifi connected')
if('cmd' in wish.keys() and wish['cmd'] == 'PullCode'):
download_file_task(wish['param']['filelist'])
except Exception as e:
raise (e)
_ble.active(True)
NUS_UUID = 0xFFA0
RX_UUID = 0xFFA2
TX_UUID = 0xFFA3
BLE_NUS = ubluetooth.UUID(NUS_UUID)
BLE_RX = (ubluetooth.UUID(RX_UUID), ubluetooth.FLAG_WRITE)
BLE_TX = (ubluetooth.UUID(TX_UUID), ubluetooth.FLAG_NOTIFY | ubluetooth.FLAG_READ)
BLE_UART = (BLE_NUS, (BLE_TX, BLE_RX,))
SERVICES = [BLE_UART, ]
_ble_tx = None
_ble_rx = None
ble_msg = ''
((_ble_tx, _ble_rx,), ) = _ble.gatts_register_services(SERVICES)
_ble.irq(ble_irq)
advertiser(_ble_adv_name)
if('afterlife.json' in os.listdir('/')):
os.remove('/afterlife.json')
time.sleep(10)
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/fs/lib/oneMinuteOnCloud.py | Python | apache-2.0 | 11,221 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* Development of the code in this file was sponsored by Microbric Pty Ltd
*
* The MIT License (MIT)
*
* Copyright (c) 2014 Damien P. George
* Copyright (c) 2017 Pycom Limited
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <stdio.h>
#include "py/mpconfig.h"
#include "py/mpstate.h"
#include "py/gc.h"
#include "py/mpthread.h"
#include "gccollect.h"
#include "soc/cpu.h"
#if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3
#include "xtensa/hal.h"
static void gc_collect_inner(int level) {
if (level < XCHAL_NUM_AREGS / 8) {
gc_collect_inner(level + 1);
if (level != 0) {
return;
}
}
if (level == XCHAL_NUM_AREGS / 8) {
// get the sp
volatile uint32_t sp = (uint32_t)get_sp();
gc_collect_root((void **)sp, ((mp_uint_t)MP_STATE_THREAD(stack_top) - sp) / sizeof(uint32_t));
return;
}
// trace root pointers from any threads
#if MICROPY_PY_THREAD
mp_thread_gc_others();
#endif
}
void gc_collect(void) {
gc_collect_start();
gc_collect_inner(0);
gc_collect_end();
}
#elif CONFIG_IDF_TARGET_ESP32C3
#include "shared/runtime/gchelper.h"
void gc_collect(void) {
gc_collect_start();
gc_helper_collect_regs_and_stack();
#if MICROPY_PY_THREAD
mp_thread_gc_others();
#endif
gc_collect_end();
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/gccollect.c | C | apache-2.0 | 2,494 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* Development of the code in this file was sponsored by Microbric Pty Ltd
*
* The MIT License (MIT)
*
* Copyright (c) 2014 Damien P. George
*
* 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.
*/
extern uint32_t _text_start;
extern uint32_t _text_end;
extern uint32_t _irom0_text_start;
extern uint32_t _irom0_text_end;
extern uint32_t _data_start;
extern uint32_t _data_end;
extern uint32_t _rodata_start;
extern uint32_t _rodata_end;
extern uint32_t _bss_start;
extern uint32_t _bss_end;
extern uint32_t _heap_start;
extern uint32_t _heap_end;
void gc_collect(void);
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/gccollect.h | C | apache-2.0 | 1,678 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* Development of the code in this file was sponsored by Microbric Pty Ltd
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2016 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "py/builtin.h"
const char esp32_help_text[] =
"Welcome to MicroPython on the ESP32, Authorized by HaaS!\n"
"\n"
"For generic online docs please visit http://docs.micropython.org/\n"
"\n"
"For access to the hardware use the 'machine' module:\n"
"\n"
"import machine\n"
"pin12 = machine.Pin(12, machine.Pin.OUT)\n"
"pin12.value(1)\n"
"pin13 = machine.Pin(13, machine.Pin.IN, machine.Pin.PULL_UP)\n"
"print(pin13.value())\n"
"i2c = machine.I2C(scl=machine.Pin(21), sda=machine.Pin(22))\n"
"i2c.scan()\n"
"i2c.writeto(addr, b'1234')\n"
"i2c.readfrom(addr, 4)\n"
"\n"
"Basic WiFi configuration:\n"
"\n"
"import network\n"
"sta_if = network.WLAN(network.STA_IF); sta_if.active(True)\n"
"sta_if.scan() # Scan for available access points\n"
"sta_if.connect(\"<AP_name>\", \"<password>\") # Connect to an AP\n"
"sta_if.isconnected() # Check for successful connection\n"
"\n"
"Control commands:\n"
" CTRL-A -- on a blank line, enter raw REPL mode\n"
" CTRL-B -- on a blank line, enter normal REPL mode\n"
" CTRL-C -- interrupt a running program\n"
" CTRL-D -- on a blank line, do a soft reset of the board\n"
" CTRL-E -- on a blank line, enter paste mode\n"
"\n"
"For further help on a specific object, type help(obj)\n"
"For a list of available modules, type help('modules')\n"
;
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/help.c | C | apache-2.0 | 2,811 |
/*
* This file is part of the MicroPython ESP32 project, https://github.com/loboris/MicroPython_ESP32_psRAM_LoBo
*
* The MIT License (MIT)
*
* Copyright (c) 2018 LoBo (https://github.com/loboris)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <math.h>
#include <string.h>
#include "driver/gpio.h"
#include "driver/rmt.h"
#include "soc/dport_reg.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "libs/neopixel.h"
#include "esp_log.h"
static xSemaphoreHandle neopixel_sem = NULL;
static intr_handle_t rmt_intr_handle = NULL;
static rmt_channel_t RMTchannel = RMT_CHANNEL_0;
static uint16_t neopixel_pos, neopixel_half, neopixel_bufIsDirty, neopixel_termsent;
static uint16_t neopixel_buf_len = 0;
static pixel_settings_t *neopixel_px;
static uint8_t *neopixel_buffer = NULL;
static uint8_t neopixel_brightness = 255;
static uint8_t used_channels[RMT_CHANNEL_MAX] = {0};
// Get color value of RGB component
//---------------------------------------------------
static uint8_t offset_color(char o, uint32_t color) {
uint8_t clr = 0;
switch(o) {
case 'R':
clr = (uint8_t)(color >> 24);
break;
case 'G':
clr = (uint8_t)(color >> 16);
break;
case 'B':
clr = (uint8_t)(color >> 8);
break;
case 'W':
clr = (uint8_t)(color & 0xFF);
break;
default:
clr = 0;
}
return clr;
}
// Set pixel color at buffer position from RGB color value
//=========================================================================
void np_set_pixel_color(pixel_settings_t *px, uint16_t idx, uint32_t color)
{
uint16_t ofs = idx * (px->nbits / 8);
px->pixels[ofs] = offset_color(px->color_order[0], color);
px->pixels[ofs+1] = offset_color(px->color_order[1], color);
px->pixels[ofs+2] = offset_color(px->color_order[2], color);
if (px->nbits == 32) px->pixels[ofs+3] = offset_color(px->color_order[3], color);
}
// Set pixel color at buffer position from HSB color value
//============================================================================================================
void np_set_pixel_color_hsb(pixel_settings_t *px, uint16_t idx, float hue, float saturation, float brightness)
{
uint32_t color = hsb_to_rgb(hue, saturation, brightness);
np_set_pixel_color(px, idx, color);
}
// Get RGB color value from RGB components corrected by brightness factor
//=============================================================================
uint32_t np_get_pixel_color(pixel_settings_t *px, uint16_t idx, uint8_t *white)
{
uint32_t clr = 0;
uint32_t color = 0;
uint8_t bpp = px->nbits/8;
uint16_t ofs = idx * bpp;
for (int i=0; i < bpp; i++) {
clr = (uint16_t)px->pixels[ofs+i];
switch(px->color_order[i]) {
case 'R':
color |= (uint32_t)clr << 16;
break;
case 'G':
color |= (uint32_t)clr << 8;
break;
case 'B':
color |= (uint32_t)clr;
break;
case 'W':
*white = px->pixels[ofs+i];
break;
}
}
return color;
}
// Set two levels of RMT output to the Neopixel value for bit value "1".
//--------------------------------------------------------------------
static void neopixel_mark(rmt_item32_t *pItem, pixel_settings_t *px) {
pItem->level0 = px->timings.mark.level0;
pItem->duration0 = px->timings.mark.duration0;
pItem->level1 = px->timings.mark.level1;
pItem->duration1 = px->timings.mark.duration1;
}
// Set two levels of RMT output to the Neopixel value for bit value "0".
//---------------------------------------------------------------------
static void neopixel_space(rmt_item32_t *pItem, pixel_settings_t *px) {
pItem->level0 = px->timings.space.level0;
pItem->duration0 = px->timings.space.duration0;
pItem->level1 = px->timings.space.level1;
pItem->duration1 = px->timings.space.duration1;
}
// Set levels and duration of RMT output to the Neopixel value for Reset.
//--------------------------------------------------------------------
static void rmt_terminate(rmt_item32_t *pItem, pixel_settings_t *px) {
pItem->level0 = px->timings.reset.level0;
pItem->duration0 = px->timings.reset.duration0;
pItem->level1 = px->timings.reset.level1;
pItem->duration1 = px->timings.reset.duration1;
}
// Transfer pixels from buffer to Neopixel strip
//-------------------------------
static void copyToRmtBlock_half()
{
// This fills half an RMT block
// When wrap around is happening, we want to keep the inactive half of the RMT block filled
uint16_t i, offset, len, byteval;
rmt_item32_t CurrentItem;
offset = neopixel_half * MAX_PULSES;
neopixel_half = !neopixel_half; // for next offset calculation
int j;
len = neopixel_buf_len - neopixel_pos; // remaining bytes in buffer
if (len > (MAX_PULSES / 8)) len = (MAX_PULSES / 8);
if (!len) {
if (!neopixel_bufIsDirty) return;
// Clear the channel's data block and return
j = 0;
if (!neopixel_termsent) {
i++;
rmt_terminate(&CurrentItem, neopixel_px);
RMTMEM.chan[RMTchannel].data32[0].val = CurrentItem.val;
neopixel_termsent = 1;
j++;
}
for (i = j; i < MAX_PULSES; i++) {
RMTMEM.chan[RMTchannel].data32[i + offset].val = 0;
}
neopixel_bufIsDirty = 0;
return;
}
neopixel_bufIsDirty = 1;
// Populate RMT bit buffer from 'neopixel_buffer' containing one byte for each RGB(W) value
for (i = 0; i < len; i++) {
byteval = (uint16_t)neopixel_buffer[i+neopixel_pos];
// Correct by brightness factor
byteval = (byteval * neopixel_brightness) / 255;
// Shift bits out, MSB first, setting RMTMEM.chan[n].data32[x] to the rmtPulsePair value corresponding to the buffered bit value
for (j=7; j>=0; j--) {
if (byteval & (1<<j)) neopixel_mark(&CurrentItem, neopixel_px);
else neopixel_space(&CurrentItem, neopixel_px);
RMTMEM.chan[RMTchannel].data32[(i * 8) + offset + (7-j)].val = CurrentItem.val;
}
if ((i < ((MAX_PULSES / 8)-1)) && (i + neopixel_pos == neopixel_buf_len - 1)) {
i++;
rmt_terminate(&CurrentItem, neopixel_px);
RMTMEM.chan[RMTchannel].data32[(i * 8) + offset + 7].val = CurrentItem.val;
neopixel_termsent = 1;
break;
}
}
// Clear the remainder of the channel's data not set above
for (i *= 8; i < MAX_PULSES; i++) {
RMTMEM.chan[RMTchannel].data32[i + offset].val = 0;
}
neopixel_pos += len;
return;
}
// RMT interrupt handler
//---------------------------------------------
static void neopixel_handleInterrupt(void *arg)
{
portBASE_TYPE taskAwoken = 0;
uint32_t tx_thr_event_mask = 0x01000000 << RMTchannel;
uint32_t tx_end_event_mask = 1 << (RMTchannel*3);
uint32_t intr_st = RMT.int_st.val;
if (intr_st & tx_thr_event_mask) {
copyToRmtBlock_half();
RMT.int_clr.val = tx_thr_event_mask;
}
else if ((intr_st & tx_end_event_mask) && neopixel_sem) {
xSemaphoreGiveFromISR(neopixel_sem, &taskAwoken);
RMT.int_clr.val = tx_end_event_mask;
}
return;
}
// Initialize Neopixel RMT interface on specific GPIO
//===================================================
int neopixel_init(int gpioNum, rmt_channel_t channel)
{
esp_err_t res;
// Create semaphore if needed
if (neopixel_sem == NULL) {
neopixel_sem = xSemaphoreCreateBinary();
if (neopixel_sem == NULL) return ESP_FAIL;
// Note: binary semaphores created using xSemaphoreCreateBinary() are created in a state
// such that the semaphore must first be 'given' before it can be 'taken' !
xSemaphoreGive(neopixel_sem);
DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_RMT_CLK_EN);
DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_RMT_RST);
}
// Allocate RMT interrupt if needed
if (rmt_intr_handle == NULL) {
res = esp_intr_alloc(ETS_RMT_INTR_SOURCE, 0, neopixel_handleInterrupt, NULL, &rmt_intr_handle);
if (res != ESP_OK) return res;
}
xSemaphoreTake(neopixel_sem, portMAX_DELAY);
uint32_t tx_thr_event_mask = 0x01000000 << channel;
uint32_t tx_end_event_mask = 1 << (channel*3);
res = rmt_set_pin(channel, RMT_MODE_TX, (gpio_num_t)gpioNum);
if (res != ESP_OK) {
xSemaphoreGive(neopixel_sem);
return res;
}
RMT.apb_conf.fifo_mask = 1; //enable memory access, instead of FIFO mode.
RMT.apb_conf.mem_tx_wrap_en = 1; //wrap around when hitting end of buffer
RMT.conf_ch[channel].conf0.div_cnt = DIVIDER;
RMT.conf_ch[channel].conf0.mem_size = 1;
RMT.conf_ch[channel].conf0.carrier_en = 0;
RMT.conf_ch[channel].conf0.carrier_out_lv = 1;
RMT.conf_ch[channel].conf0.mem_pd = 0;
RMT.conf_ch[channel].conf1.rx_en = 0;
RMT.conf_ch[channel].conf1.mem_owner = 0;
RMT.conf_ch[channel].conf1.tx_conti_mode = 0; //loop back mode.
RMT.conf_ch[channel].conf1.ref_always_on = 1; // use apb clock: 80M
RMT.conf_ch[channel].conf1.idle_out_en = 1;
RMT.conf_ch[channel].conf1.idle_out_lv = 0;
RMT.tx_lim_ch[channel].limit = MAX_PULSES;
RMT.int_ena.val = tx_thr_event_mask | tx_end_event_mask;
used_channels[channel] = 1;
xSemaphoreGive(neopixel_sem);
return ESP_OK;
}
// Deinitialize RMT interface
//=========================================
void neopixel_deinit(rmt_channel_t channel)
{
xSemaphoreTake(neopixel_sem, portMAX_DELAY);
rmt_set_rx_intr_en(channel, 0);
rmt_set_err_intr_en(channel, 0);
rmt_set_tx_intr_en(channel, 0);
rmt_set_tx_thr_intr_en(channel, 0, 0xffff);
used_channels[channel] = 0;
uint8_t nused = 0;
for (int i=0; i<RMT_CHANNEL_MAX; i++ ) {
if (used_channels[i]) nused++;
}
if (nused == 0) {
// No RMT channels used, cleanup
if (rmt_intr_handle) {
esp_intr_free(rmt_intr_handle);
rmt_intr_handle = NULL;
}
if (neopixel_buffer) {
free(neopixel_buffer);
neopixel_buffer = NULL;
}
xSemaphoreGive(neopixel_sem);
vSemaphoreDelete(neopixel_sem);
neopixel_sem = NULL;
}
else {
xSemaphoreGive(neopixel_sem);
}
}
// Start the transfer of Neopixel color bytes from buffer
//=======================================================
void np_show(pixel_settings_t *px, rmt_channel_t channel)
{
// Wait for previous operation to finish
xSemaphoreTake(neopixel_sem, portMAX_DELAY);
RMTchannel = channel;
// Enable interrupt for neopixel RMT channel
uint32_t tx_thr_event_mask = 0x01000000 << channel;
uint32_t tx_end_event_mask = 1 << (channel*3);
RMT.int_ena.val = tx_thr_event_mask | tx_end_event_mask;
uint16_t blen = px->pixel_count * (px->nbits / 8);
// Allocate neopixel buffer if needed
if (neopixel_buffer == NULL) {
neopixel_buffer = (uint8_t *)malloc(blen);
if (neopixel_buffer == NULL) return;
neopixel_buf_len = blen;
}
// Resize neopixel buffer if needed
if (neopixel_buf_len < blen) {
// larger buffer needed
free(neopixel_buffer);
neopixel_buffer = (uint8_t *)malloc(blen);
if (neopixel_buffer == NULL) return;
}
memcpy(neopixel_buffer, px->pixels, blen);
neopixel_buf_len = blen;
neopixel_pos = 0;
neopixel_half = 0;
neopixel_px = px;
neopixel_half = 0;
neopixel_termsent = 0;
neopixel_brightness = px->brightness;
copyToRmtBlock_half();
if (neopixel_pos < neopixel_buf_len) {
// Fill the other half of the buffer block
copyToRmtBlock_half();
}
// Start sending
RMT.conf_ch[RMTchannel].conf1.mem_rd_rst = 1;
RMT.conf_ch[RMTchannel].conf1.tx_start = 1;
// Wait for operation to finish
if (xSemaphoreTake(neopixel_sem, 0) == pdTRUE) {
xSemaphoreTake(neopixel_sem, portMAX_DELAY);
}
xSemaphoreGive(neopixel_sem);
}
// Clear the Neopixel color buffer
//=================================
void np_clear(pixel_settings_t *px)
{
memset(px->pixels, 0, px->pixel_count * (px->nbits/8));
}
//------------------------------------
static float Min(double a, double b) {
return a <= b ? a : b;
}
//------------------------------------
static float Max(double a, double b) {
return a >= b ? a : b;
}
// Convert 24-bit color to HSB representation
//===================================================================
void rgb_to_hsb( uint32_t color, float *hue, float *sat, float *bri )
{
float delta, min;
float h = 0, s, v;
uint8_t red = (color >> 16) & 0xFF;
uint8_t green = (color >> 8) & 0xFF;
uint8_t blue = color & 0xFF;
min = Min(Min(red, green), blue);
v = Max(Max(red, green), blue);
delta = v - min;
if (v == 0.0) s = 0;
else s = delta / v;
if (s == 0) h = 0.0;
else
{
if (red == v)
h = (green - blue) / delta;
else if (green == v)
h = 2 + (blue - red) / delta;
else if (blue == v)
h = 4 + (red - green) / delta;
h *= 60;
if (h < 0.0) h = h + 360;
}
*hue = h;
*sat = s;
*bri = v / 255;
}
// Convert HSB color to 24-bit color representation
//============================================================
uint32_t hsb_to_rgb(float _hue, float _sat, float _brightness)
{
float red = 0.0;
float green = 0.0;
float blue = 0.0;
if (_sat == 0.0) {
red = _brightness;
green = _brightness;
blue = _brightness;
}
else {
if (_hue >= 360.0) _hue = fmod(_hue, 360);
int slice = (int)(_hue / 60.0);
float hue_frac = (_hue / 60.0) - slice;
float aa = _brightness * (1.0 - _sat);
float bb = _brightness * (1.0 - _sat * hue_frac);
float cc = _brightness * (1.0 - _sat * (1.0 - hue_frac));
switch(slice) {
case 0:
red = _brightness;
green = cc;
blue = aa;
break;
case 1:
red = bb;
green = _brightness;
blue = aa;
break;
case 2:
red = aa;
green = _brightness;
blue = cc;
break;
case 3:
red = aa;
green = bb;
blue = _brightness;
break;
case 4:
red = cc;
green = aa;
blue = _brightness;
break;
case 5:
red = _brightness;
green = aa;
blue = bb;
break;
default:
red = 0.0;
green = 0.0;
blue = 0.0;
break;
}
}
return (uint32_t)((uint8_t)(red * 255.0) << 16) | ((uint8_t)(green * 255.0) << 8) | ((uint8_t)(blue * 255.0));
}
// Convert HSB color to 24-bit color representation
// _hue: 0 ~ 359
// _sat: 0 ~ 255
// _bri: 0 ~ 255
//=======================================================
uint32_t hsb_to_rgb_int(int hue, int sat, int brightness)
{
float _hue = (float)hue;
float _sat = (float)((float)sat / 1000.0);
float _brightness = (float)((float)brightness / 1000.0);
float red = 0.0;
float green = 0.0;
float blue = 0.0;
if (_sat == 0.0) {
red = _brightness;
green = _brightness;
blue = _brightness;
}
else {
if (_hue >= 360.0) _hue = fmod(_hue, 360);
int slice = (int)(_hue / 60.0);
float hue_frac = (_hue / 60.0) - slice;
float aa = _brightness * (1.0 - _sat);
float bb = _brightness * (1.0 - _sat * hue_frac);
float cc = _brightness * (1.0 - _sat * (1.0 - hue_frac));
switch(slice) {
case 0:
red = _brightness;
green = cc;
blue = aa;
break;
case 1:
red = bb;
green = _brightness;
blue = aa;
break;
case 2:
red = aa;
green = _brightness;
blue = cc;
break;
case 3:
red = aa;
green = bb;
blue = _brightness;
break;
case 4:
red = cc;
green = aa;
blue = _brightness;
break;
case 5:
red = _brightness;
green = aa;
blue = bb;
break;
default:
red = 0.0;
green = 0.0;
blue = 0.0;
break;
}
}
return (uint32_t)((uint8_t)(red * 255.0) << 16) | ((uint8_t)(green * 255.0) << 8) | ((uint8_t)(blue * 255.0));
}
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/libs/neopixel.c | C | apache-2.0 | 16,108 |
/*
* This file is part of the MicroPython ESP32 project, https://github.com/loboris/MicroPython_ESP32_psRAM_LoBo
*
* The MIT License (MIT)
*
* Copyright (c) 2018 LoBo (https://github.com/loboris)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include "driver/gpio.h"
#include "driver/rmt.h"
#define DIVIDER 4 // 80 MHz clock divider
#define RMT_DURATION_NS 12.5 // minimum time of a single RMT duration based on 80 MHz clock (ns)
#define RMT_PERIOD_NS 50 // minimum bit time based on 80 MHz clock and divider of 4
#define RTM_PIXEL_BUFFER_SIZE 1 //
#define MAX_PULSES 32 // A channel has a 64 "pulse" buffer - we use half per pass
typedef struct bit_timing {
uint8_t level0;
uint16_t duration0;
uint8_t level1;
uint16_t duration1;
} bit_timing_t;
typedef struct pixel_timing {
bit_timing_t mark;
bit_timing_t space;
bit_timing_t reset;
} pixel_timing_t;
typedef struct pixel_settings {
uint8_t *pixels; // buffer containing pixel values, 3 (RGB) or 4 (RGBW) bytes per pixel
pixel_timing_t timings; // timing data from which the pixels BIT data are formed
uint16_t pixel_count; // number of used pixels
uint8_t brightness; // brightness factor applied to pixel color
char color_order[5];
uint8_t nbits; // number of bits used (24 for RGB devices, 32 for RGBW devices)
} pixel_settings_t;
void np_set_pixel_color(pixel_settings_t *px, uint16_t idx, uint32_t color);
void np_set_pixel_color_hsb(pixel_settings_t *px, uint16_t idx, float hue, float saturation, float brightness);
uint32_t np_get_pixel_color(pixel_settings_t *px, uint16_t idx, uint8_t *white);
void np_show(pixel_settings_t *px, rmt_channel_t channel);
void np_clear(pixel_settings_t *px);
int neopixel_init(int gpioNum, rmt_channel_t channel);
void neopixel_deinit(rmt_channel_t channel);
void rgb_to_hsb( uint32_t color, float *hue, float *sat, float *bri );
uint32_t hsb_to_rgb(float hue, float saturation, float brightness);
uint32_t hsb_to_rgb_int(int hue, int sat, int brightness);
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/libs/neopixel.h | C | apache-2.0 | 3,060 |
import axp192
import kv
import uos
try:
# for m5stack-core2 only
axp = axp192.Axp192()
axp.powerAll()
axp.setLCDBrightness(80) # 设置背光亮度 0~100
except OSError:
print("make sure axp192.py is in libs folder")
def _on_get_url(url):
kv.set('_amp_pyapp_url', url)
execfile('/lib/appOta.py')
def _connect_wifi(ssid, passwd):
import network
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
sta_if.active(True)
sta_if.scan()
sta_if.connect(ssid, passwd)
bt_disabled = kv.get('disable_bt')
if bt_disabled != "no":
uos.plussys_mm()
channel = kv.get('app_upgrade_channel')
if channel == "enable":
ssid = kv.get('_amp_wifi_ssid')
passwd = kv.get('_amp_wifi_passwd')
if isinstance(ssid, str) and isinstance(passwd, str):
_connect_wifi(ssid, passwd)
import online_upgrade
online_upgrade.on(_on_get_url)
app_upgrade = kv.get('_amp_app_upgrade')
if app_upgrade == "enable":
print("App is being upgraded. It will take about 10 seconds.")
execfile('/lib/appUpgrade.py')
kv.remove('_amp_app_upgrade')
print("App upgrade finished.")
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/m5stackcore2/boot.py | Python | apache-2.0 | 1,167 |
import lvgl as lv
RESOURCES_ROOT = "S:/data/pyamp/images/"
class Airpressure:
scr = None
iconImg = None
airpressureLable = None
unityLabel = None
tipLabel = None
def __init__(self, screen):
self.scr = screen
self.createAirpressureItem(self.scr, RESOURCES_ROOT + "airpressure.png", "Air pressure")
def createAirpressureItem(self, parent, iconPath, tips):
self.iconImg = lv.img(parent)
self.iconImg.set_src(iconPath)
self.iconImg.align(lv.ALIGN.TOP_LEFT, 0, 0)
self.airpressureLable = lv.label(parent)
self.airpressureLable.set_text("None")
self.airpressureLable.set_style_text_color(lv.color_white(), 0)
self.airpressureLable.set_style_text_font(lv.font_montserrat_48, 0)
self.airpressureLable.align_to(self.iconImg, lv.ALIGN.OUT_RIGHT_TOP, 0, 0)
self.unityLabel = lv.label(parent)
self.unityLabel.set_text(" HPA")
self.unityLabel.set_style_text_color(lv.color_white(), 0)
self.unityLabel.set_style_text_font(lv.font_montserrat_18, 0)
self.unityLabel.align_to(self.airpressureLable, lv.ALIGN.OUT_RIGHT_BOTTOM, 0, -5)
self.tipLabel = lv.label(parent)
self.tipLabel.set_text(tips)
self.tipLabel.set_style_text_color(lv.color_make(0xCC, 0xCC, 0xCC), 0)
self.tipLabel.set_style_text_font(lv.font_montserrat_14, 0)
self.tipLabel.align_to(self.airpressureLable, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 0)
def setValue(self, humidity):
self.airpressureLable.set_text(str(int(humidity)))
def setXY(self, x, y):
self.iconImg.align(lv.ALIGN.TOP_LEFT, x, y)
self.airpressureLable.align_to(self.iconImg, lv.ALIGN.OUT_RIGHT_TOP, 0, 0)
self.unityLabel.align_to(self.airpressureLable, lv.ALIGN.OUT_RIGHT_BOTTOM, 0, -5)
self.tipLabel.align_to(self.airpressureLable, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 0)
def setScale(self, scale):
print("To be done")
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/m5stackcore2/data/pyamp/airpressure.py | Python | apache-2.0 | 1,977 |
import lvgl as lv
RESOURCES_ROOT = "S:/data/pyamp/images/"
class Angle:
scr = None
iconImg = None
angleLable = None
unityLabel = None
tipLabel = None
def __init__(self, screen):
self.scr = screen
self.createAngleItem(self.scr, RESOURCES_ROOT + "angle.png", "Angle")
def createAngleItem(self, parent, iconPath, tips):
self.iconImg = lv.img(parent)
self.iconImg.set_src(iconPath)
self.iconImg.align(lv.ALIGN.TOP_LEFT, 0, 0)
self.angleLable = lv.label(parent)
self.angleLable.set_text("None")
self.angleLable.set_style_text_color(lv.color_white(), 0)
self.angleLable.set_style_text_font(lv.font_montserrat_48, 0)
self.angleLable.align_to(self.iconImg, lv.ALIGN.OUT_RIGHT_TOP, 0, 0)
self.unityLabel = lv.label(parent)
self.unityLabel.set_text(" o")
self.unityLabel.set_style_text_color(lv.color_white(), 0)
self.unityLabel.set_style_text_font(lv.font_montserrat_18, 0)
self.unityLabel.align_to(self.angleLable, lv.ALIGN.OUT_RIGHT_BOTTOM, 0, -5)
self.tipLabel = lv.label(parent)
self.tipLabel.set_text(tips)
self.tipLabel.set_style_text_color(lv.color_make(0xCC, 0xCC, 0xCC), 0)
self.tipLabel.set_style_text_font(lv.font_montserrat_14, 0)
self.tipLabel.align_to(self.angleLable, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 0)
def setValue(self, humidity):
self.angleLable.set_text(str(int(humidity)))
def setXY(self, x, y):
self.iconImg.align(lv.ALIGN.TOP_LEFT, x, y)
self.angleLable.align_to(self.iconImg, lv.ALIGN.OUT_RIGHT_TOP, 0, 0)
self.unityLabel.align_to(self.angleLable, lv.ALIGN.OUT_RIGHT_BOTTOM, 0, -5)
self.tipLabel.align_to(self.angleLable, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 0)
def setScale(self, scale):
print("To be done")
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/m5stackcore2/data/pyamp/angle.py | Python | apache-2.0 | 1,872 |
import lvgl as lv
RESOURCES_ROOT = "S:/data/pyamp/"
compass_ttf_alive = False
def compass_back_click_callback(e, win):
global compass_ttf_alive
if (compass_ttf_alive):
from smart_panel import load_smart_panel
load_smart_panel()
compass_ttf_alive = False
def compass_back_press_callback(e, image):
image.set_zoom(280)
def compass_back_release_callback(e, image):
image.set_zoom(250)
value = 0
class Compass:
def createPage(self):
global value
global compass_ttf_alive
print("Enter Compass")
# init scr
scr = lv.obj()
win = lv.obj(scr)
win.set_size(scr.get_width(), scr.get_height())
win.set_style_border_opa(0, 0)
win.set_style_radius(0, 0)
win.set_style_bg_color(lv.color_black(), 0)
win.clear_flag(lv.obj.FLAG.SCROLLABLE)
backImg=lv.img(win)
backImg.set_src(RESOURCES_ROOT + "images/back.png")
backImg.set_style_align(lv.ALIGN.LEFT_MID, 0)
backImg.add_flag(lv.obj.FLAG.CLICKABLE)
backImg.add_event_cb(lambda e: compass_back_click_callback(e, win), lv.EVENT.CLICKED, None)
backImg.add_event_cb(lambda e: compass_back_press_callback(e, backImg), lv.EVENT.PRESSED, None)
backImg.add_event_cb(lambda e: compass_back_release_callback(e, backImg), lv.EVENT.RELEASED, None)
backImg.set_ext_click_area(30)
# -------------- compass image ----------------
compass_dial = lv.img(win)
compass_dial.set_src(RESOURCES_ROOT + "images/compass_dial.png")
compass_dial.set_style_max_height(scr.get_height(), 0)
compass_dial.set_angle(value * 10)
compass_dial.center()
# -------------- indicator --------------------
compass_indicator = lv.img(win)
compass_indicator.set_src(RESOURCES_ROOT + "images/compass_indicator.png")
# compass_indicator.set_style_max_height(scr.get_height(), 0)
compass_indicator.set_angle(value * 10)
compass_indicator.center()
col_dsc = [35, 10, 25, lv.GRID_TEMPLATE.LAST]
row_dsc = [20, 35, 20, lv.GRID_TEMPLATE.LAST]
degreeArea = lv.obj(win)
degreeArea.set_size(95, 100)
degreeArea.set_style_bg_opa(0, 0)
degreeArea.set_style_border_opa(0, 0)
degreeArea.set_style_pad_all(0, 0)
degreeArea.set_layout(lv.LAYOUT_GRID.value)
degreeArea.set_grid_dsc_array(col_dsc, row_dsc)
degreeArea.center()
# degreeArea.set_style_pad_left(5, 0)
degreeArea.clear_flag(lv.obj.FLAG.SCROLLABLE)
red = lv.img(degreeArea)
red.set_src(RESOURCES_ROOT + "images/angle_red.png")
red.set_grid_cell(lv.GRID_ALIGN.CENTER, 0, 3, lv.GRID_ALIGN.CENTER, 0, 1)
degreeLable = lv.label(degreeArea)
degreeLable.set_text(str(value))
degreeLable.set_style_text_color(lv.color_white(), 0)
degreeLable.set_style_text_font(lv.font_montserrat_36, 0)
degreeLable.set_grid_cell(lv.GRID_ALIGN.CENTER, 0, 1, lv.GRID_ALIGN.CENTER, 1, 1)
degreeIcon = lv.img(degreeArea)
degreeIcon.set_src(RESOURCES_ROOT + "images/degree.png")
degreeIcon.set_style_pad_top(5, 0)
degreeIcon.set_grid_cell(lv.GRID_ALIGN.START, 1, 1, lv.GRID_ALIGN.START, 1, 1)
directionLable = lv.label(degreeArea)
directionLable.set_text("N")
directionLable.set_style_text_color(lv.color_white(), 0)
directionLable.set_style_text_font(lv.font_montserrat_36, 0)
directionLable.set_grid_cell(lv.GRID_ALIGN.START, 2, 1, lv.GRID_ALIGN.CENTER, 1, 1)
tips = lv.label(degreeArea)
tips.set_text("Compass")
tips.set_style_text_color(lv.color_white(), 0)
tips.set_style_text_font(lv.font_montserrat_12, 0)
tips.set_grid_cell(lv.GRID_ALIGN.CENTER, 0, 3, lv.GRID_ALIGN.CENTER, 2, 1)
from smart_panel import needAnimation
if (needAnimation):
lv.scr_load_anim(scr, lv.SCR_LOAD_ANIM.MOVE_LEFT, 500, 0, True)
else:
lv.scr_load_anim(scr, lv.SCR_LOAD_ANIM.NONE, 0, 0, True)
compass_ttf_alive = True
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/m5stackcore2/data/pyamp/compass.py | Python | apache-2.0 | 4,147 |
import lvgl as lv
RESOURCES_ROOT = "S:/data/pyamp/images/"
class Distance:
scr = None
iconImg = None
distanceLable = None
unityLabel = None
tipLabel = None
def __init__(self, screen):
self.scr = screen
self.createDistanceItem(self.scr, RESOURCES_ROOT + "distance.png", "DST")
def createDistanceItem(self, parent, iconPath, tips):
self.iconImg = lv.img(parent)
self.iconImg.set_src(iconPath)
self.iconImg.align(lv.ALIGN.TOP_LEFT, 0, 0)
self.distanceLable = lv.label(parent)
self.distanceLable.set_text("None")
self.distanceLable.set_style_text_color(lv.color_white(), 0)
self.distanceLable.set_style_text_font(lv.font_montserrat_48, 0)
self.distanceLable.align_to(self.iconImg, lv.ALIGN.OUT_RIGHT_TOP, 0, 0)
self.unityLabel = lv.label(parent)
self.unityLabel.set_text(" M")
self.unityLabel.set_style_text_color(lv.color_white(), 0)
self.unityLabel.set_style_text_font(lv.font_montserrat_18, 0)
self.unityLabel.align_to(self.distanceLable, lv.ALIGN.OUT_RIGHT_BOTTOM, 0, -5)
self.tipLabel = lv.label(parent)
self.tipLabel.set_text(tips)
self.tipLabel.set_style_text_color(lv.color_make(0xCC, 0xCC, 0xCC), 0)
self.tipLabel.set_style_text_font(lv.font_montserrat_14, 0)
self.tipLabel.align_to(self.distanceLable, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 0)
def setValue(self, humidity):
self.distanceLable.set_text(str(int(humidity)))
def setXY(self, x, y):
self.iconImg.align(lv.ALIGN.TOP_LEFT, x, y)
self.distanceLable.align_to(self.iconImg, lv.ALIGN.OUT_RIGHT_TOP, 0, 0)
self.unityLabel.align_to(self.distanceLable, lv.ALIGN.OUT_RIGHT_BOTTOM, 0, -5)
self.tipLabel.align_to(self.distanceLable, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 0)
def setScale(self, scale):
print("To be done")
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/m5stackcore2/data/pyamp/distance.py | Python | apache-2.0 | 1,918 |
import lvgl as lv
import utime
RESOURCES_ROOT = "S:/data/pyamp/"
def drawOver(e):
global g_clickTime
if (g_clickTime != 0):
currentTime = utime.ticks_ms()
print("create Environment page use: %dms" % int((currentTime - g_clickTime)))
g_clickTime = 0
environment_alive = False
def environment_back_click_callback(e, win):
global environment_alive
if (environment_alive):
from smart_panel import load_smart_panel
load_smart_panel()
environment_alive = False
def environment_back_press_callback(e, back_image):
back_image.set_zoom(280)
def environment_back_release_callback(e, back_image):
back_image.set_zoom(250)
class Environment:
def createPage(self):
global environment_alive
global g_clickTime
g_clickTime = utime.ticks_ms()
# init scr
scr = lv.obj()
win = lv.obj(scr)
win.set_size(scr.get_width(), scr.get_height())
win.set_style_border_opa(0, 0)
win.set_style_bg_color(lv.color_black(), 0)
win.set_style_radius(0, 0)
win.clear_flag(lv.obj.FLAG.SCROLLABLE)
win.add_event_cb(drawOver, lv.EVENT.DRAW_POST_END, None)
backImg=lv.img(win)
backImg.set_src(RESOURCES_ROOT + "images/back.png")
backImg.set_style_align(lv.ALIGN.LEFT_MID, 0)
backImg.add_flag(lv.obj.FLAG.CLICKABLE)
backImg.add_event_cb(lambda e: environment_back_click_callback(e, win), lv.EVENT.CLICKED, None)
backImg.add_event_cb(lambda e: environment_back_press_callback(e, backImg), lv.EVENT.PRESSED, None)
backImg.add_event_cb(lambda e: environment_back_release_callback(e, backImg), lv.EVENT.RELEASED, None)
backImg.set_ext_click_area(20)
container = lv.obj(win)
container.set_style_bg_opa(0, 0)
container.set_style_border_opa(0, 0)
container.set_size(lv.SIZE.CONTENT, lv.SIZE.CONTENT)
container.set_flex_flow(lv.FLEX_FLOW.COLUMN)
container.set_style_align(lv.ALIGN.CENTER, 0)
container.set_style_pad_left(0, 0)
self.createItem(container, RESOURCES_ROOT + "images/temperature.png", "25",
RESOURCES_ROOT + "images/centigrade_l.png", "Temperature")
self.createInterval(container, 25)
self.createItem(container, RESOURCES_ROOT + "images/humidity.png", "41 %", "", "Humidity")
from smart_panel import needAnimation
if (needAnimation):
lv.scr_load_anim(scr, lv.SCR_LOAD_ANIM.MOVE_LEFT, 500, 0, True)
else:
lv.scr_load_anim(scr, lv.SCR_LOAD_ANIM.NONE, 0, 0, True)
environment_alive = True
currentTime = utime.ticks_ms()
print("run python code use: %dms" % int((currentTime - g_clickTime)))
def createItem(self, parent, iconPath, value, unityPath, tips):
col_dsc = [lv.GRID.CONTENT, 5, lv.GRID.CONTENT, lv.GRID.CONTENT, lv.GRID_TEMPLATE.LAST]
row_dsc = [lv.GRID.CONTENT, lv.GRID.CONTENT, lv.GRID_TEMPLATE.LAST]
cont = lv.obj(parent)
cont.set_style_bg_opa(0, 0)
cont.set_style_border_opa(0, 0)
cont.set_style_pad_all(0, 0)
cont.set_size(lv.SIZE.CONTENT, lv.SIZE.CONTENT)
cont.set_style_grid_column_dsc_array(col_dsc, 0)
cont.set_style_grid_row_dsc_array(row_dsc, 0)
cont.set_layout(lv.LAYOUT_GRID.value)
img = lv.img(cont)
img.set_src(iconPath)
img.set_grid_cell(lv.GRID_ALIGN.START, 0, 1, lv.GRID_ALIGN.CENTER, 0, 2)
label = lv.label(cont)
label.set_text(value)
label.set_style_text_color(lv.color_white(), 0)
label.set_style_text_font(lv.font_montserrat_48, 0)
label.set_style_pad_all(0, 0)
label.set_grid_cell(lv.GRID_ALIGN.START, 2, 1, lv.GRID_ALIGN.CENTER, 0, 1)
if (unityPath.strip()):
iconImg = lv.img(cont)
iconImg.set_src(unityPath)
iconImg.set_zoom(205)
iconImg.set_style_pad_bottom(0, 0)
iconImg.set_grid_cell(lv.GRID_ALIGN.START, 3, 1, lv.GRID_ALIGN.CENTER, 0, 1)
tip = lv.label(cont)
tip.set_text(tips)
tip.set_style_text_color(lv.color_make(0xCC, 0xCC, 0xCC), 0)
tip.set_grid_cell(lv.GRID_ALIGN.START, 2, 2, lv.GRID_ALIGN.START, 1, 1)
def createInterval(self, parent, size):
interval = lv.obj(parent)
interval.set_style_bg_opa(0, 0)
interval.set_style_border_opa(0, 0)
interval.set_height(size)
interval.set_width(0)
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/m5stackcore2/data/pyamp/environment.py | Python | apache-2.0 | 4,518 |
import lvgl as lv
RESOURCES_ROOT = "S:/data/pyamp/images/"
class Fm:
scr = None
iconImg = None
fmLable = None
unityLabel = None
tipLabel = None
def __init__(self, screen):
self.scr = screen
self.createFmItem(self.scr, RESOURCES_ROOT + "FM.png", "FM")
def createFmItem(self, parent, iconPath, tips):
self.iconImg = lv.img(parent)
self.iconImg.set_src(iconPath)
self.iconImg.align(lv.ALIGN.TOP_LEFT, 0, 0)
self.fmLable = lv.label(parent)
self.fmLable.set_text("None")
self.fmLable.set_style_text_color(lv.color_white(), 0)
self.fmLable.set_style_text_font(lv.font_montserrat_48, 0)
self.fmLable.align_to(self.iconImg, lv.ALIGN.OUT_RIGHT_TOP, 0, 0)
self.unityLabel = lv.label(parent)
self.unityLabel.set_text(" MHz")
self.unityLabel.set_style_text_color(lv.color_white(), 0)
self.unityLabel.set_style_text_font(lv.font_montserrat_18, 0)
self.unityLabel.align_to(self.fmLable, lv.ALIGN.OUT_RIGHT_BOTTOM, 0, -5)
self.tipLabel = lv.label(parent)
self.tipLabel.set_text(tips)
self.tipLabel.set_style_text_color(lv.color_make(0xCC, 0xCC, 0xCC), 0)
self.tipLabel.set_style_text_font(lv.font_montserrat_14, 0)
self.tipLabel.align_to(self.fmLable, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 0)
def setValue(self, humidity):
self.fmLable.set_text(str(int(humidity)))
def setXY(self, x, y):
self.iconImg.align(lv.ALIGN.TOP_LEFT, x, y)
self.fmLable.align_to(self.iconImg, lv.ALIGN.OUT_RIGHT_TOP, 0, 0)
self.unityLabel.align_to(self.fmLable, lv.ALIGN.OUT_RIGHT_BOTTOM, 0, -5)
self.tipLabel.align_to(self.fmLable, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 0)
def setScale(self, scale):
print("To be done")
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/m5stackcore2/data/pyamp/fm.py | Python | apache-2.0 | 1,823 |
import lvgl as lv
font_not_load_16 = True
info_16 = None
style_16 = None
def set_text_size_16(parent):
global font_not_load_16
global info_16
global style_16
if (font_not_load_16):
info_16 = lv.ft_info_t()
info_16.name ="/data/pyamp/font/AlibabaPuHuiTiM_16.ttf"
info_16.weight = 16
info_16.style = lv.FT_FONT_STYLE.NORMAL
info_16.font_init()
style_16 = lv.style_t()
style_16.init()
style_16.set_text_font(info_16.font)
font_not_load_16 = False
parent.add_style(style_16, 0)
font_not_load_20 = True
info_20 = None
style_20 = None
def set_text_size_20(parent):
global font_not_load_20
global info_20
global style_20
if (font_not_load_20):
info_20 = lv.ft_info_t()
info_20.name ="/data/pyamp/font/AlibabaPuHuiTiM_20.ttf"
info_20.weight = 20
info_20.style = lv.FT_FONT_STYLE.NORMAL
info_20.font_init()
style_20 = lv.style_t()
style_20.init()
style_20.set_text_font(info_20.font)
font_not_load_20 = False
parent.add_style(style_20, 0)
font_not_load_22 = True
info_22 = None
style_22 = None
def set_text_size_22(parent):
global font_not_load_22
global info_22
global style_22
if (font_not_load_22):
info_22 = lv.ft_info_t()
info_22.name ="/data/pyamp/font/AlibabaPuHuiTiM_22.ttf"
info_22.weight = 22
info_22.style = lv.FT_FONT_STYLE.NORMAL
info_22.font_init()
style_22 = lv.style_t()
style_22.init()
style_22.set_text_font(info_22.font)
font_not_load_22 = False
parent.add_style(style_22, 0)
font_not_load_38 = True
info_38 = None
style_38 = None
def set_text_size_38(parent):
global font_not_load_38
global info_38
global style_38
if (font_not_load_38):
info_38 = lv.ft_info_t()
info_38.name ="/data/pyamp/font/AlibabaPuHuiTiM_38.ttf"
info_38.weight = 38
info_38.style = lv.FT_FONT_STYLE.NORMAL
info_38.font_init()
style_38 = lv.style_t()
style_38.init()
style_38.set_text_font(info_38.font)
font_not_load_38 = False
parent.add_style(style_38, 0)
def set_text_size(parent, size):
if (size == 38):
set_text_size_38(parent)
elif (size == 22):
set_text_size_22(parent)
elif (size == 20):
set_text_size_20(parent)
else:
set_text_size_16(parent)
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/m5stackcore2/data/pyamp/font_Alibaba_PuHuiTi.py | Python | apache-2.0 | 2,463 |
import lvgl as lv
RESOURCES_ROOT = "S:/data/pyamp/images/"
class Gas:
scr = None
iconImg = None
gasLable = None
unityLabel = None
tipLabel = None
def __init__(self, screen):
self.scr = screen
self.createGasItem(self.scr, RESOURCES_ROOT + "gas.png", "Nature Gas")
def createGasItem(self, parent, iconPath, tips):
self.iconImg = lv.img(parent)
self.iconImg.set_src(iconPath)
self.iconImg.align(lv.ALIGN.TOP_LEFT, 0, 0)
self.gasLable = lv.label(parent)
self.gasLable.set_text("None")
self.gasLable.set_style_text_color(lv.color_white(), 0)
self.gasLable.set_style_text_font(lv.font_montserrat_48, 0)
self.gasLable.align_to(self.iconImg, lv.ALIGN.OUT_RIGHT_TOP, 0, 0)
self.unityLabel = lv.label(parent)
self.unityLabel.set_text(" %LEL")
self.unityLabel.set_style_text_color(lv.color_white(), 0)
self.unityLabel.set_style_text_font(lv.font_montserrat_18, 0)
self.unityLabel.align_to(self.gasLable, lv.ALIGN.OUT_RIGHT_BOTTOM, 0, -5)
self.tipLabel = lv.label(parent)
self.tipLabel.set_text(tips)
self.tipLabel.set_style_text_color(lv.color_make(0xCC, 0xCC, 0xCC), 0)
self.tipLabel.set_style_text_font(lv.font_montserrat_14, 0)
self.tipLabel.align_to(self.gasLable, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 0)
def setValue(self, humidity):
self.gasLable.set_text(str(int(humidity)))
def setXY(self, x, y):
self.iconImg.align(lv.ALIGN.TOP_LEFT, x, y)
self.gasLable.align_to(self.iconImg, lv.ALIGN.OUT_RIGHT_TOP, 0, 0)
self.unityLabel.align_to(self.gasLable, lv.ALIGN.OUT_RIGHT_BOTTOM, 0, -5)
self.tipLabel.align_to(self.gasLable, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 0)
def setScale(self, scale):
print("To be done")
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/m5stackcore2/data/pyamp/gas.py | Python | apache-2.0 | 1,848 |
import lvgl as lv
RESOURCES_ROOT = "S:/data/pyamp/images/"
class Hcho:
scr = None
iconImg = None
hchoLable = None
unityLabel = None
tipLabel = None
def __init__(self, screen):
self.scr = screen
self.createHchoItem(self.scr, RESOURCES_ROOT + "hcho.png", "PA")
def createHchoItem(self, parent, iconPath, tips):
self.iconImg = lv.img(parent)
self.iconImg.set_src(iconPath)
self.iconImg.align(lv.ALIGN.TOP_LEFT, 0, 0)
self.hchoLable = lv.label(parent)
self.hchoLable.set_text("None")
self.hchoLable.set_style_text_color(lv.color_white(), 0)
self.hchoLable.set_style_text_font(lv.font_montserrat_48, 0)
self.hchoLable.align_to(self.iconImg, lv.ALIGN.OUT_RIGHT_TOP, 0, 0)
self.unityLabel = lv.label(parent)
self.unityLabel.set_text(" mg/m3")
self.unityLabel.set_style_text_color(lv.color_white(), 0)
self.unityLabel.set_style_text_font(lv.font_montserrat_18, 0)
self.unityLabel.align_to(self.hchoLable, lv.ALIGN.OUT_RIGHT_BOTTOM, 0, -5)
self.tipLabel = lv.label(parent)
self.tipLabel.set_text(tips)
self.tipLabel.set_style_text_color(lv.color_make(0xCC, 0xCC, 0xCC), 0)
self.tipLabel.set_style_text_font(lv.font_montserrat_14, 0)
self.tipLabel.align_to(self.hchoLable, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 0)
def setValue(self, humidity):
self.hchoLable.set_text(str(int(humidity)))
def setXY(self, x, y):
self.iconImg.align(lv.ALIGN.TOP_LEFT, x, y)
self.hchoLable.align_to(self.iconImg, lv.ALIGN.OUT_RIGHT_TOP, 0, 0)
self.unityLabel.align_to(self.hchoLable, lv.ALIGN.OUT_RIGHT_BOTTOM, 0, -5)
self.tipLabel.align_to(self.hchoLable, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 0)
def setScale(self, scale):
print("To be done")
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/m5stackcore2/data/pyamp/hcho.py | Python | apache-2.0 | 1,857 |
import lvgl as lv
RESOURCES_ROOT = "S:/data/pyamp/images/"
class Heartrate:
scr = None
iconImg = None
heartrateLable = None
unityLabel = None
tipLabel = None
def __init__(self, screen):
self.scr = screen
self.createHeartrateItem(self.scr, RESOURCES_ROOT + "heartrate.png", "HR")
def createHeartrateItem(self, parent, iconPath, tips):
self.iconImg = lv.img(parent)
self.iconImg.set_src(iconPath)
self.iconImg.align(lv.ALIGN.TOP_LEFT, 0, 0)
self.heartrateLable = lv.label(parent)
self.heartrateLable.set_text("None")
self.heartrateLable.set_style_text_color(lv.color_white(), 0)
self.heartrateLable.set_style_text_font(lv.font_montserrat_48, 0)
self.heartrateLable.align_to(self.iconImg, lv.ALIGN.OUT_RIGHT_TOP, 0, 0)
self.unityLabel = lv.label(parent)
self.unityLabel.set_text(" BPM")
self.unityLabel.set_style_text_color(lv.color_white(), 0)
self.unityLabel.set_style_text_font(lv.font_montserrat_18, 0)
self.unityLabel.align_to(self.heartrateLable, lv.ALIGN.OUT_RIGHT_BOTTOM, 0, -5)
self.tipLabel = lv.label(parent)
self.tipLabel.set_text(tips)
self.tipLabel.set_style_text_color(lv.color_make(0xCC, 0xCC, 0xCC), 0)
self.tipLabel.set_style_text_font(lv.font_montserrat_14, 0)
self.tipLabel.align_to(self.heartrateLable, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 0)
def setValue(self, humidity):
self.heartrateLable.set_text(str(int(humidity)))
def setXY(self, x, y):
self.iconImg.align(lv.ALIGN.TOP_LEFT, x, y)
self.heartrateLable.align_to(self.iconImg, lv.ALIGN.OUT_RIGHT_TOP, 0, 0)
self.unityLabel.align_to(self.heartrateLable, lv.ALIGN.OUT_RIGHT_BOTTOM, 0, -5)
self.tipLabel.align_to(self.heartrateLable, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 0)
def setScale(self, scale):
print("To be done")
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/m5stackcore2/data/pyamp/heartrate.py | Python | apache-2.0 | 1,935 |
import lvgl as lv
RESOURCES_ROOT = "S:/data/pyamp/images/"
class Humidity:
scr = None
iconImg = None
humidityLable = None
unityLabel = None
tipLabel = None
def __init__(self, screen):
self.scr = screen
self.createHumidityItem(self.scr, RESOURCES_ROOT + "humidity.png", "TDS")
def createHumidityItem(self, parent, iconPath, tips):
self.iconImg = lv.img(parent)
self.iconImg.set_src(iconPath)
self.iconImg.align(lv.ALIGN.TOP_LEFT, 0, 0)
self.humidityLable = lv.label(parent)
self.humidityLable.set_text("None")
self.humidityLable.set_style_text_color(lv.color_white(), 0)
self.humidityLable.set_style_text_font(lv.font_montserrat_48, 0)
self.humidityLable.align_to(self.iconImg, lv.ALIGN.OUT_RIGHT_TOP, 0, 0)
self.unityLabel = lv.label(parent)
self.unityLabel.set_text(" PPM")
self.unityLabel.set_style_text_color(lv.color_white(), 0)
self.unityLabel.set_style_text_font(lv.font_montserrat_18, 0)
self.unityLabel.align_to(self.humidityLable, lv.ALIGN.OUT_RIGHT_BOTTOM, 0, -5)
self.tipLabel = lv.label(parent)
self.tipLabel.set_text(tips)
self.tipLabel.set_style_text_color(lv.color_make(0xCC, 0xCC, 0xCC), 0)
self.tipLabel.set_style_text_font(lv.font_montserrat_14, 0)
self.tipLabel.align_to(self.humidityLable, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 0)
def setValue(self, humidity):
self.humidityLable.set_text(str(int(humidity)))
def setXY(self, x, y):
self.iconImg.align(lv.ALIGN.TOP_LEFT, x, y)
self.humidityLable.align_to(self.iconImg, lv.ALIGN.OUT_RIGHT_TOP, 0, 0)
self.unityLabel.align_to(self.humidityLable, lv.ALIGN.OUT_RIGHT_BOTTOM, 0, -5)
self.tipLabel.align_to(self.humidityLable, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 0)
def setScale(self, scale):
print("To be done")
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/m5stackcore2/data/pyamp/humidity.py | Python | apache-2.0 | 1,920 |
import lvgl as lv
RESOURCES_ROOT = "S:/data/pyamp/"
environment_alive = False
functionImage = [
RESOURCES_ROOT + "images/refrigeration.png",
RESOURCES_ROOT + "images/heating.png",
RESOURCES_ROOT + "images/dehumidification.png",
RESOURCES_ROOT + "images/ventilation.png"]
functionImageSelected = [
RESOURCES_ROOT + "images/refrigeration_selected.png",
RESOURCES_ROOT + "images/heating_selected.png",
RESOURCES_ROOT + "images/dehumidification_selected.png",
RESOURCES_ROOT + "images/ventilation_selected.png"]
currentFunc = 0
currentSelected = None
hvac_alive = False
def hvac_back_click_callback(e, win):
global hvac_alive
if (hvac_alive):
from smart_panel import load_smart_panel
load_smart_panel()
hvac_alive = False
def hvac_back_press_callback(e, image):
image.set_zoom(280)
def hvac_back_release_callback(e, image):
image.set_zoom(250)
def sub_pressed_cb(e, self):
print("sub")
if (self.value > 16):
self.value -= 1
print("value %d" % (self.value))
self.label.set_text(str(self.value))
def add_pressed_cb(e, self):
print("add")
if (self.value < 30):
self.value += 1
print("value %d" % (self.value))
self.label.set_text(str(self.value))
def func_pressed_cb(e, index):
global currentFunc
global currentSelected
print(index)
if (index != currentFunc):
currentSelected.set_src(functionImage[currentFunc])
selectedImage = e.get_target()
currentFunc = index
selectedImage.set_src(functionImageSelected[currentFunc])
currentSelected = selectedImage
class Hvac:
value = 25
def createPage(self):
global currentFunc
global currentSelected
global hvac_alive
print("Enter Hvac")
# init scr
scr = lv.obj()
win = lv.obj(scr)
win.set_size(scr.get_width(), scr.get_height())
win.set_style_border_opa(0, 0)
win.set_style_radius(0, 0)
win.set_style_bg_color(lv.color_black(), 0)
win.clear_flag(lv.obj.FLAG.SCROLLABLE)
# --------- value container ---------
col_dsc = [60, 65, 40, 60, lv.GRID_TEMPLATE.LAST]
row_dsc = [48, lv.GRID_TEMPLATE.LAST]
valueLayout = lv.obj(win)
valueLayout.set_layout(lv.LAYOUT_GRID.value)
valueLayout.set_style_bg_opa(0, 0)
valueLayout.set_style_border_opa(0, 0)
valueLayout.set_size(lv.SIZE.CONTENT, lv.SIZE.CONTENT)
valueLayout.set_grid_align(lv.GRID_ALIGN.SPACE_BETWEEN, lv.GRID_ALIGN.SPACE_BETWEEN)
valueLayout.set_style_grid_column_dsc_array(col_dsc, 0)
valueLayout.set_style_grid_row_dsc_array(row_dsc, 0)
valueLayout.set_style_pad_top(20, 0)
valueLayout.set_style_align(lv.ALIGN.TOP_MID, 0)
# ----------- - --------------
subImage = lv.img(valueLayout)
subImage.set_src(RESOURCES_ROOT + "images/subtraction.png")
subImage.set_grid_cell(lv.GRID_ALIGN.START, 0, 1, lv.GRID_ALIGN.CENTER, 0, 1)
subImage.add_flag(lv.obj.FLAG.CLICKABLE)
subImage.add_event_cb(lambda e: sub_pressed_cb(e, self), lv.EVENT.PRESSED, None)
# subImage.add_event_cb(lambda e: hvac_back_press_callback(e, subImage), lv.EVENT.PRESSED, None)
# subImage.add_event_cb(lambda e: hvac_back_release_callback(e, subImage), lv.EVENT.RELEASED, None)
subImage.set_ext_click_area(40)
# ----------- value -----------
self.label = lv.label(valueLayout)
self.label.set_text(str(self.value))
self.label.set_style_text_color(lv.color_white(), 0)
self.label.set_style_text_font(lv.font_montserrat_48, 0)
self.label.set_grid_cell(lv.GRID_ALIGN.CENTER, 1, 1, lv.GRID_ALIGN.CENTER, 0, 1)
# ----------- ºC ------------
centigradeImage = lv.img(valueLayout)
centigradeImage.set_src(RESOURCES_ROOT + "images/centigrade_s.png")
centigradeImage.set_style_pad_bottom(8, 0)
centigradeImage.set_grid_cell(lv.GRID_ALIGN.START, 2, 1, lv.GRID_ALIGN.END, 0, 1)
# ----------- + ----------------
addImage = lv.img(valueLayout)
addImage.set_src(RESOURCES_ROOT + "images/addition.png")
addImage.set_grid_cell(lv.GRID_ALIGN.CENTER, 3, 1, lv.GRID_ALIGN.CENTER, 0, 1)
addImage.add_flag(lv.obj.FLAG.CLICKABLE)
addImage.add_event_cb(lambda e: add_pressed_cb(e, self), lv.EVENT.PRESSED, None)
# addImage.add_event_cb(lambda e: hvac_back_press_callback(e, addImage), lv.EVENT.PRESSED, None)
# addImage.add_event_cb(lambda e: hvac_back_release_callback(e, addImage), lv.EVENT.RELEASED, None)
addImage.set_ext_click_area(40)
# ----------- tips ----------
tips = lv.label(win)
tips.set_text("Temperature")
tips.set_style_text_color(lv.color_make(0xCC, 0xCC, 0xCC), 0)
tips.set_style_pad_bottom(20, 0)
tips.set_align(lv.ALIGN.CENTER)
# ----------- function ----------
func_col_dsc = [70, 70, 70, 70, lv.GRID_TEMPLATE.LAST]
func_row_dsc = [40, lv.GRID_TEMPLATE.LAST]
funcContainer = lv.obj(win)
funcContainer.set_style_bg_opa(0, 0)
funcContainer.set_style_border_opa(0, 0)
funcContainer.set_grid_dsc_array(func_col_dsc, func_row_dsc)
funcContainer.set_width(300)
funcContainer.set_height(90)
funcContainer.set_layout(lv.LAYOUT_GRID.value)
funcContainer.set_align(lv.ALIGN.BOTTOM_MID)
funcContainer.set_grid_align(lv.GRID_ALIGN.SPACE_BETWEEN, lv.GRID_ALIGN.SPACE_BETWEEN)
image = lv.img(funcContainer)
image.set_src(functionImage[0])
image.add_flag(lv.obj.FLAG.CLICKABLE)
image.set_ext_click_area(20)
image.add_event_cb(lambda e: func_pressed_cb(e, 0), lv.EVENT.PRESSED, None)
image.set_grid_cell(lv.GRID_ALIGN.CENTER, 0, 1, lv.GRID_ALIGN.CENTER, 0, 1)
currentSelected = image
currentSelected.set_src(functionImageSelected[0])
image1 = lv.img(funcContainer)
image1.set_src(functionImage[1])
image1.add_flag(lv.obj.FLAG.CLICKABLE)
image1.set_ext_click_area(20)
image1.add_event_cb(lambda e: func_pressed_cb(e, 1), lv.EVENT.PRESSED, None)
image1.set_grid_cell(lv.GRID_ALIGN.CENTER, 1, 1, lv.GRID_ALIGN.CENTER, 0, 1)
image2 = lv.img(funcContainer)
image2.set_src(functionImage[2])
image2.add_flag(lv.obj.FLAG.CLICKABLE)
image2.set_ext_click_area(20)
image2.add_event_cb(lambda e: func_pressed_cb(e, 2), lv.EVENT.PRESSED, None)
image2.set_grid_cell(lv.GRID_ALIGN.CENTER, 2, 1, lv.GRID_ALIGN.CENTER, 0, 1)
image3 = lv.img(funcContainer)
image3.set_src(functionImage[3])
image3.add_flag(lv.obj.FLAG.CLICKABLE)
image3.set_ext_click_area(20)
image3.add_event_cb(lambda e: func_pressed_cb(e, 3), lv.EVENT.PRESSED, None)
image3.set_grid_cell(lv.GRID_ALIGN.CENTER, 3, 1, lv.GRID_ALIGN.CENTER, 0, 1)
# for i in range(4):
# image = lv.img(funcContainer)
# image.set_src(functionImage[i])
# image.add_flag(lv.obj.FLAG.CLICKABLE)
# image.set_ext_click_area(20)
# image.add_event_cb(lambda e: func_pressed_cb(e, i), lv.EVENT.PRESSED, None)
# image.set_grid_cell(lv.GRID_ALIGN.CENTER, i, 1, lv.GRID_ALIGN.CENTER, 0, 1)
# if (currentFunc == i):
# currentSelected = image
# currentSelected.set_src(functionImageSelected[i])
backImg=lv.img(win)
backImg.set_src(RESOURCES_ROOT + "images/back.png")
backImg.set_style_align(lv.ALIGN.LEFT_MID, 0)
backImg.add_flag(lv.obj.FLAG.CLICKABLE)
backImg.add_event_cb(lambda e: hvac_back_click_callback(e, win), lv.EVENT.CLICKED, None)
backImg.add_event_cb(lambda e: hvac_back_press_callback(e, backImg), lv.EVENT.PRESSED, None)
backImg.add_event_cb(lambda e: hvac_back_release_callback(e, backImg), lv.EVENT.RELEASED, None)
backImg.set_ext_click_area(20)
from smart_panel import needAnimation
if (needAnimation):
lv.scr_load_anim(scr, lv.SCR_LOAD_ANIM.MOVE_LEFT, 500, 0, True)
else:
lv.scr_load_anim(scr, lv.SCR_LOAD_ANIM.NONE, 0, 0, True)
hvac_alive = True
| YifuLiu/AliOS-Things | components/py_engine/adapter/esp32/m5stackcore2/data/pyamp/hvac.py | Python | apache-2.0 | 8,415 |