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 |
|---|---|---|---|---|---|
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* 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.
*/
#ifndef MICROPY_INCLUDED_LIB_UTILS_INTERRUPT_CHAR_H
#define MICROPY_INCLUDED_LIB_UTILS_INTERRUPT_CHAR_H
extern int mp_interrupt_char;
void mp_hal_set_interrupt_char(int c);
#endif // MICROPY_INCLUDED_LIB_UTILS_INTERRUPT_CHAR_H
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/runtime/interrupt_char.h | C | apache-2.0 | 1,459 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Daniel Campora
* 2018 Tobias Badertscher
*
* 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/runtime.h"
#include "py/gc.h"
#include "shared/runtime/mpirq.h"
#if MICROPY_ENABLE_SCHEDULER
/******************************************************************************
DECLARE PUBLIC DATA
******************************************************************************/
const mp_arg_t mp_irq_init_args[] = {
{ MP_QSTR_handler, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
{ MP_QSTR_trigger, MP_ARG_INT, {.u_int = 0} },
{ MP_QSTR_hard, MP_ARG_BOOL, {.u_bool = false} },
};
/******************************************************************************
DECLARE PRIVATE DATA
******************************************************************************/
/******************************************************************************
DEFINE PUBLIC FUNCTIONS
******************************************************************************/
mp_irq_obj_t *mp_irq_new(const mp_irq_methods_t *methods, mp_obj_t parent) {
mp_irq_obj_t *self = m_new0(mp_irq_obj_t, 1);
mp_irq_init(self, methods, parent);
return self;
}
void mp_irq_init(mp_irq_obj_t *self, const mp_irq_methods_t *methods, mp_obj_t parent) {
self->base.type = &mp_irq_type;
self->methods = (mp_irq_methods_t *)methods;
self->parent = parent;
self->handler = mp_const_none;
self->ishard = false;
}
void mp_irq_handler(mp_irq_obj_t *self) {
if (self->handler != mp_const_none) {
if (self->ishard) {
// When executing code within a handler we must lock the scheduler to
// prevent any scheduled callbacks from running, and lock the GC to
// prevent any memory allocations.
mp_sched_lock();
gc_lock();
nlr_buf_t nlr;
if (nlr_push(&nlr) == 0) {
mp_call_function_1(self->handler, self->parent);
nlr_pop();
} else {
// Uncaught exception; disable the callback so that it doesn't run again
self->methods->trigger(self->parent, 0);
self->handler = mp_const_none;
printf("Uncaught exception in IRQ callback handler\n");
mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val));
}
gc_unlock();
mp_sched_unlock();
} else {
// Schedule call to user function
mp_sched_schedule(self->handler, self->parent);
}
}
}
/******************************************************************************/
// MicroPython bindings
STATIC mp_obj_t mp_irq_flags(mp_obj_t self_in) {
mp_irq_obj_t *self = MP_OBJ_TO_PTR(self_in);
return mp_obj_new_int(self->methods->info(self->parent, MP_IRQ_INFO_FLAGS));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_irq_flags_obj, mp_irq_flags);
STATIC mp_obj_t mp_irq_trigger(size_t n_args, const mp_obj_t *args) {
mp_irq_obj_t *self = MP_OBJ_TO_PTR(args[0]);
mp_obj_t ret_obj = mp_obj_new_int(self->methods->info(self->parent, MP_IRQ_INFO_TRIGGERS));
if (n_args == 2) {
// Set trigger
self->methods->trigger(self->parent, mp_obj_get_int(args[1]));
}
return ret_obj;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_irq_trigger_obj, 1, 2, mp_irq_trigger);
STATIC mp_obj_t mp_irq_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
mp_arg_check_num(n_args, n_kw, 0, 0, false);
mp_irq_handler(MP_OBJ_TO_PTR(self_in));
return mp_const_none;
}
STATIC const mp_rom_map_elem_t mp_irq_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_flags), MP_ROM_PTR(&mp_irq_flags_obj) },
{ MP_ROM_QSTR(MP_QSTR_trigger), MP_ROM_PTR(&mp_irq_trigger_obj) },
};
STATIC MP_DEFINE_CONST_DICT(mp_irq_locals_dict, mp_irq_locals_dict_table);
const mp_obj_type_t mp_irq_type = {
{ &mp_type_type },
.name = MP_QSTR_irq,
.call = mp_irq_call,
.locals_dict = (mp_obj_dict_t *)&mp_irq_locals_dict,
};
#endif // MICROPY_ENABLE_SCHEDULER
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/runtime/mpirq.c | C | apache-2.0 | 5,257 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Daniel Campora
*
* 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_LIB_UTILS_MPIRQ_H
#define MICROPY_INCLUDED_LIB_UTILS_MPIRQ_H
#include "py/runtime.h"
/******************************************************************************
DEFINE CONSTANTS
******************************************************************************/
enum {
MP_IRQ_ARG_INIT_handler = 0,
MP_IRQ_ARG_INIT_trigger,
MP_IRQ_ARG_INIT_hard,
MP_IRQ_ARG_INIT_NUM_ARGS,
};
/******************************************************************************
DEFINE TYPES
******************************************************************************/
typedef mp_uint_t (*mp_irq_trigger_fun_t)(mp_obj_t self, mp_uint_t trigger);
typedef mp_uint_t (*mp_irq_info_fun_t)(mp_obj_t self, mp_uint_t info_type);
enum {
MP_IRQ_INFO_FLAGS,
MP_IRQ_INFO_TRIGGERS,
};
typedef struct _mp_irq_methods_t {
mp_irq_trigger_fun_t trigger;
mp_irq_info_fun_t info;
} mp_irq_methods_t;
typedef struct _mp_irq_obj_t {
mp_obj_base_t base;
mp_irq_methods_t *methods;
mp_obj_t parent;
mp_obj_t handler;
bool ishard;
} mp_irq_obj_t;
/******************************************************************************
DECLARE EXPORTED DATA
******************************************************************************/
extern const mp_arg_t mp_irq_init_args[];
extern const mp_obj_type_t mp_irq_type;
/******************************************************************************
DECLARE PUBLIC FUNCTIONS
******************************************************************************/
mp_irq_obj_t *mp_irq_new(const mp_irq_methods_t *methods, mp_obj_t parent);
void mp_irq_init(mp_irq_obj_t *self, const mp_irq_methods_t *methods, mp_obj_t parent);
void mp_irq_handler(mp_irq_obj_t *self);
#endif // MICROPY_INCLUDED_LIB_UTILS_MPIRQ_H
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/runtime/mpirq.h | C | apache-2.0 | 3,022 |
/*
* 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.
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include "py/compile.h"
#include "py/runtime.h"
#include "py/repl.h"
#include "py/gc.h"
#include "py/frozenmod.h"
#include "py/mphal.h"
#if MICROPY_HW_ENABLE_USB
#include "irq.h"
#include "usb.h"
#endif
#include "shared/readline/readline.h"
#include "shared/runtime/pyexec.h"
#include "genhdr/mpversion.h"
pyexec_mode_kind_t pyexec_mode_kind = PYEXEC_MODE_FRIENDLY_REPL;
int pyexec_system_exit = 0;
#if MICROPY_REPL_INFO
STATIC bool repl_display_debugging_info = 0;
#endif
#define EXEC_FLAG_PRINT_EOF (1)
#define EXEC_FLAG_ALLOW_DEBUGGING (2)
#define EXEC_FLAG_IS_REPL (4)
#define EXEC_FLAG_SOURCE_IS_RAW_CODE (8)
#define EXEC_FLAG_SOURCE_IS_VSTR (16)
#define EXEC_FLAG_SOURCE_IS_FILENAME (32)
#define EXEC_FLAG_SOURCE_IS_READER (64)
// parses, compiles and executes the code in the lexer
// frees the lexer before returning
// EXEC_FLAG_PRINT_EOF prints 2 EOF chars: 1 after normal output, 1 after exception output
// EXEC_FLAG_ALLOW_DEBUGGING allows debugging info to be printed after executing the code
// EXEC_FLAG_IS_REPL is used for REPL inputs (flag passed on to mp_compile)
STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input_kind, int exec_flags) {
int ret = 0;
#if MICROPY_REPL_INFO
uint32_t start = 0;
#endif
#ifdef MICROPY_BOARD_BEFORE_PYTHON_EXEC
MICROPY_BOARD_BEFORE_PYTHON_EXEC(input_kind, exec_flags);
#endif
// by default a SystemExit exception returns 0
pyexec_system_exit = 0;
nlr_buf_t nlr;
nlr.ret_val = NULL;
if (nlr_push(&nlr) == 0) {
mp_obj_t module_fun;
#if MICROPY_MODULE_FROZEN_MPY
if (exec_flags & EXEC_FLAG_SOURCE_IS_RAW_CODE) {
// source is a raw_code object, create the function
module_fun = mp_make_function_from_raw_code(source, MP_OBJ_NULL, MP_OBJ_NULL);
} else
#endif
{
#if MICROPY_ENABLE_COMPILER
mp_lexer_t *lex;
if (exec_flags & EXEC_FLAG_SOURCE_IS_VSTR) {
const vstr_t *vstr = source;
lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, vstr->buf, vstr->len, 0);
} else if (exec_flags & EXEC_FLAG_SOURCE_IS_READER) {
lex = mp_lexer_new(MP_QSTR__lt_stdin_gt_, *(mp_reader_t *)source);
} else if (exec_flags & EXEC_FLAG_SOURCE_IS_FILENAME) {
lex = mp_lexer_new_from_file(source);
} else {
lex = (mp_lexer_t *)source;
}
// source is a lexer, parse and compile the script
qstr source_name = lex->source_name;
mp_parse_tree_t parse_tree = mp_parse(lex, input_kind);
module_fun = mp_compile(&parse_tree, source_name, exec_flags & EXEC_FLAG_IS_REPL);
#else
mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("script compilation not supported"));
#endif
}
// execute code
mp_hal_set_interrupt_char(CHAR_CTRL_C); // allow ctrl-C to interrupt us
#if MICROPY_REPL_INFO
start = mp_hal_ticks_ms();
#endif
mp_call_function_0(module_fun);
mp_hal_set_interrupt_char(-1); // disable interrupt
mp_handle_pending(true); // handle any pending exceptions (and any callbacks)
nlr_pop();
ret = 1;
if (exec_flags & EXEC_FLAG_PRINT_EOF) {
mp_hal_stdout_tx_strn("\x04", 1);
}
} else {
// uncaught exception
mp_hal_set_interrupt_char(-1); // disable interrupt
mp_handle_pending(false); // clear any pending exceptions (and run any callbacks)
if (exec_flags & EXEC_FLAG_SOURCE_IS_READER) {
const mp_reader_t *reader = source;
reader->close(reader->data);
}
// print EOF after normal output
if (exec_flags & EXEC_FLAG_PRINT_EOF) {
mp_hal_stdout_tx_strn("\x04", 1);
}
// check for SystemExit
if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t *)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_SystemExit))) {
// at the moment, the value of SystemExit is unused
ret = pyexec_system_exit;
} else {
mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val));
ret = 0;
}
}
#if MICROPY_REPL_INFO
// display debugging info if wanted
if ((exec_flags & EXEC_FLAG_ALLOW_DEBUGGING) && repl_display_debugging_info) {
mp_uint_t ticks = mp_hal_ticks_ms() - start; // TODO implement a function that does this properly
printf("took " UINT_FMT " ms\n", ticks);
// qstr info
{
size_t n_pool, n_qstr, n_str_data_bytes, n_total_bytes;
qstr_pool_info(&n_pool, &n_qstr, &n_str_data_bytes, &n_total_bytes);
printf("qstr:\n n_pool=%u\n n_qstr=%u\n "
"n_str_data_bytes=%u\n n_total_bytes=%u\n",
(unsigned)n_pool, (unsigned)n_qstr, (unsigned)n_str_data_bytes, (unsigned)n_total_bytes);
}
#if MICROPY_ENABLE_GC
// run collection and print GC info
gc_collect();
gc_dump_info();
#endif
}
#endif
if (exec_flags & EXEC_FLAG_PRINT_EOF) {
mp_hal_stdout_tx_strn("\x04", 1);
}
#ifdef MICROPY_BOARD_AFTER_PYTHON_EXEC
MICROPY_BOARD_AFTER_PYTHON_EXEC(input_kind, exec_flags, nlr.ret_val, &ret);
#endif
return ret;
}
#if MICROPY_ENABLE_COMPILER
// This can be configured by a port (and even configured to a function to be
// computed dynamically) to indicate the maximum number of bytes that can be
// held in the stdin buffer.
#ifndef MICROPY_REPL_STDIN_BUFFER_MAX
#define MICROPY_REPL_STDIN_BUFFER_MAX (256)
#endif
typedef struct _mp_reader_stdin_t {
bool eof;
uint16_t window_max;
uint16_t window_remain;
} mp_reader_stdin_t;
STATIC mp_uint_t mp_reader_stdin_readbyte(void *data) {
mp_reader_stdin_t *reader = (mp_reader_stdin_t *)data;
if (reader->eof) {
return MP_READER_EOF;
}
int c = mp_hal_stdin_rx_chr();
#if MICROPY_PY_AOS_QUIT
if (c == CHAR_CTRL_C || c == CHAR_CTRL_D || c == CHAR_CTRL_X) {
#else
if (c == CHAR_CTRL_C || c == CHAR_CTRL_D) {
#endif
reader->eof = true;
mp_hal_stdout_tx_strn("\x04", 1); // indicate end to host
if (c == CHAR_CTRL_C) {
#if MICROPY_KBD_EXCEPTION
MP_STATE_VM(mp_kbd_exception).traceback_data = NULL;
nlr_raise(MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_kbd_exception)));
#else
mp_raise_type(&mp_type_KeyboardInterrupt);
#endif
} else {
return MP_READER_EOF;
}
}
if (--reader->window_remain == 0) {
mp_hal_stdout_tx_strn("\x01", 1); // indicate window available to host
reader->window_remain = reader->window_max;
}
return c;
}
STATIC void mp_reader_stdin_close(void *data) {
mp_reader_stdin_t *reader = (mp_reader_stdin_t *)data;
if (!reader->eof) {
reader->eof = true;
mp_hal_stdout_tx_strn("\x04", 1); // indicate end to host
for (;;) {
int c = mp_hal_stdin_rx_chr();
#if MICROPY_PY_AOS_QUIT
if (c == CHAR_CTRL_C || c == CHAR_CTRL_D || c == CHAR_CTRL_X) {
#else
if (c == CHAR_CTRL_C || c == CHAR_CTRL_D) {
#endif
break;
}
}
}
}
STATIC void mp_reader_new_stdin(mp_reader_t *reader, mp_reader_stdin_t *reader_stdin, uint16_t buf_max) {
// Make flow-control window half the buffer size, and indicate to the host that 2x windows are
// free (sending the window size implicitly indicates that a window is free, and then the 0x01
// indicates that another window is free).
size_t window = buf_max / 2;
char reply[3] = { window & 0xff, window >> 8, 0x01 };
mp_hal_stdout_tx_strn(reply, sizeof(reply));
reader_stdin->eof = false;
reader_stdin->window_max = window;
reader_stdin->window_remain = window;
reader->data = reader_stdin;
reader->readbyte = mp_reader_stdin_readbyte;
reader->close = mp_reader_stdin_close;
}
STATIC int do_reader_stdin(int c) {
if (c != 'A') {
// Unsupported command.
mp_hal_stdout_tx_strn("R\x00", 2);
return 0;
}
// Indicate reception of command.
mp_hal_stdout_tx_strn("R\x01", 2);
mp_reader_t reader;
mp_reader_stdin_t reader_stdin;
mp_reader_new_stdin(&reader, &reader_stdin, MICROPY_REPL_STDIN_BUFFER_MAX);
int exec_flags = EXEC_FLAG_PRINT_EOF | EXEC_FLAG_SOURCE_IS_READER;
return parse_compile_execute(&reader, MP_PARSE_FILE_INPUT, exec_flags);
}
#if MICROPY_REPL_EVENT_DRIVEN
typedef struct _repl_t {
// This structure originally also held current REPL line,
// but it was moved to MP_STATE_VM(repl_line) as containing
// root pointer. Still keep structure in case more state
// will be added later.
// vstr_t line;
bool cont_line;
bool paste_mode;
} repl_t;
repl_t repl;
STATIC int pyexec_raw_repl_process_char(int c);
STATIC int pyexec_friendly_repl_process_char(int c);
void pyexec_event_repl_init(void) {
MP_STATE_VM(repl_line) = vstr_new(32);
repl.cont_line = false;
repl.paste_mode = false;
// no prompt before printing friendly REPL banner or entering raw REPL
readline_init(MP_STATE_VM(repl_line), "");
if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
pyexec_raw_repl_process_char(CHAR_CTRL_A);
} else {
pyexec_friendly_repl_process_char(CHAR_CTRL_B);
}
}
STATIC int pyexec_raw_repl_process_char(int c) {
if (c == CHAR_CTRL_A) {
// reset raw REPL
if (vstr_len(MP_STATE_VM(repl_line)) == 2 && vstr_str(MP_STATE_VM(repl_line))[0] == CHAR_CTRL_E) {
int ret = do_reader_stdin(vstr_str(MP_STATE_VM(repl_line))[1]);
if (ret & PYEXEC_FORCED_EXIT) {
return ret;
}
goto reset;
}
mp_hal_stdout_tx_str("raw REPL; CTRL-B to exit\r\n");
goto reset;
} else if (c == CHAR_CTRL_B) {
// change to friendly REPL
pyexec_mode_kind = PYEXEC_MODE_FRIENDLY_REPL;
vstr_reset(MP_STATE_VM(repl_line));
repl.cont_line = false;
repl.paste_mode = false;
pyexec_friendly_repl_process_char(CHAR_CTRL_B);
return 0;
} else if (c == CHAR_CTRL_C) {
// clear line
vstr_reset(MP_STATE_VM(repl_line));
return 0;
} else if (c == CHAR_CTRL_D) {
// input finished
#if MICROPY_PY_AOS_QUIT
} else if (c == CHAR_CTRL_X) {
// input finished
#endif
} else {
// let through any other raw 8-bit value
vstr_add_byte(MP_STATE_VM(repl_line), c);
return 0;
}
// indicate reception of command
mp_hal_stdout_tx_str("OK");
if (MP_STATE_VM(repl_line)->len == 0) {
// exit for a soft reset
mp_hal_stdout_tx_str("\r\n");
vstr_clear(MP_STATE_VM(repl_line));
return PYEXEC_FORCED_EXIT;
}
int ret = parse_compile_execute(MP_STATE_VM(repl_line), MP_PARSE_FILE_INPUT, EXEC_FLAG_PRINT_EOF | EXEC_FLAG_SOURCE_IS_VSTR);
if (ret & PYEXEC_FORCED_EXIT) {
return ret;
}
reset:
vstr_reset(MP_STATE_VM(repl_line));
mp_hal_stdout_tx_str(">");
return 0;
}
STATIC int pyexec_friendly_repl_process_char(int c) {
if (repl.paste_mode) {
if (c == CHAR_CTRL_C) {
// cancel everything
mp_hal_stdout_tx_str("\r\n");
goto input_restart;
} else if (c == CHAR_CTRL_D) {
// end of input
mp_hal_stdout_tx_str("\r\n");
int ret = parse_compile_execute(MP_STATE_VM(repl_line), MP_PARSE_FILE_INPUT, EXEC_FLAG_ALLOW_DEBUGGING | EXEC_FLAG_IS_REPL | EXEC_FLAG_SOURCE_IS_VSTR);
if (ret & PYEXEC_FORCED_EXIT) {
return ret;
}
goto input_restart;
#if MICROPY_PY_AOS_QUIT
} else if (c == CHAR_CTRL_X) {
// end of input
mp_hal_stdout_tx_str("\r\n");
int ret = parse_compile_execute(MP_STATE_VM(repl_line), MP_PARSE_FILE_INPUT, EXEC_FLAG_ALLOW_DEBUGGING | EXEC_FLAG_IS_REPL | EXEC_FLAG_SOURCE_IS_VSTR);
if (ret & PYEXEC_FORCED_QUIT) {
return ret;
}
goto input_restart;
#endif
} else {
// add char to buffer and echo
vstr_add_byte(MP_STATE_VM(repl_line), c);
if (c == '\r') {
mp_hal_stdout_tx_str("\r\n=== ");
} else {
char buf[1] = {c};
mp_hal_stdout_tx_strn(buf, 1);
}
return 0;
}
}
int ret = readline_process_char(c);
if (!repl.cont_line) {
if (ret == CHAR_CTRL_A) {
// change to raw REPL
pyexec_mode_kind = PYEXEC_MODE_RAW_REPL;
mp_hal_stdout_tx_str("\r\n");
pyexec_raw_repl_process_char(CHAR_CTRL_A);
return 0;
} else if (ret == CHAR_CTRL_B) {
// reset friendly REPL
mp_hal_stdout_tx_str("\r\n");
mp_hal_stdout_tx_str("MicroPython " MICROPY_GIT_TAG " on " MICROPY_BUILD_DATE "; " MICROPY_HW_BOARD_NAME " with " MICROPY_HW_MCU_NAME "\r\n");
#if MICROPY_PY_BUILTINS_HELP
mp_hal_stdout_tx_str("Type \"help()\" for more information.\r\n");
#endif
goto input_restart;
} else if (ret == CHAR_CTRL_C) {
// break
mp_hal_stdout_tx_str("\r\n");
goto input_restart;
} else if (ret == CHAR_CTRL_D) {
// exit for a soft reset
mp_hal_stdout_tx_str("\r\n");
vstr_clear(MP_STATE_VM(repl_line));
return PYEXEC_FORCED_EXIT;
#if MICROPY_PY_AOS_QUIT
} else if (ret == CHAR_CTRL_X) {
// exit for a soft reset
mp_hal_stdout_tx_str("\r\n");
vstr_clear(MP_STATE_VM(repl_line));
return PYEXEC_FORCED_QUIT;
#endif
} else if (ret == CHAR_CTRL_E) {
// paste mode
mp_hal_stdout_tx_str("\r\npaste mode; Ctrl-C to cancel, Ctrl-D to finish\r\n=== ");
vstr_reset(MP_STATE_VM(repl_line));
repl.paste_mode = true;
return 0;
}
if (ret < 0) {
return 0;
}
if (!mp_repl_continue_with_input(vstr_null_terminated_str(MP_STATE_VM(repl_line)))) {
goto exec;
}
vstr_add_byte(MP_STATE_VM(repl_line), '\n');
repl.cont_line = true;
readline_note_newline("... ");
return 0;
} else {
if (ret == CHAR_CTRL_C) {
// cancel everything
mp_hal_stdout_tx_str("\r\n");
repl.cont_line = false;
goto input_restart;
} else if (ret == CHAR_CTRL_D) {
// stop entering compound statement
goto exec;
#if MICROPY_PY_AOS_QUIT
} else if (ret == CHAR_CTRL_X) {
// stop entering compound statement
goto exec;
#endif
}
if (ret < 0) {
return 0;
}
if (mp_repl_continue_with_input(vstr_null_terminated_str(MP_STATE_VM(repl_line)))) {
vstr_add_byte(MP_STATE_VM(repl_line), '\n');
readline_note_newline("... ");
return 0;
}
exec:;
int ret = parse_compile_execute(MP_STATE_VM(repl_line), MP_PARSE_SINGLE_INPUT, EXEC_FLAG_ALLOW_DEBUGGING | EXEC_FLAG_IS_REPL | EXEC_FLAG_SOURCE_IS_VSTR);
if (ret & PYEXEC_FORCED_EXIT) {
return ret;
}
input_restart:
vstr_reset(MP_STATE_VM(repl_line));
repl.cont_line = false;
repl.paste_mode = false;
readline_init(MP_STATE_VM(repl_line), ">>> ");
return 0;
}
}
uint8_t pyexec_repl_active;
int pyexec_event_repl_process_char(int c) {
pyexec_repl_active = 1;
int res;
if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
res = pyexec_raw_repl_process_char(c);
} else {
res = pyexec_friendly_repl_process_char(c);
}
pyexec_repl_active = 0;
return res;
}
#else // MICROPY_REPL_EVENT_DRIVEN
int pyexec_raw_repl(void) {
vstr_t line;
vstr_init(&line, 32);
#if MICROPY_PY_AOS_QUIT
int exit_engine_flag = 0;
#endif
raw_repl_reset:
mp_hal_stdout_tx_str("raw REPL; CTRL-B to exit\r\n");
for (;;) {
vstr_reset(&line);
mp_hal_stdout_tx_str(">");
for (;;) {
int c = mp_hal_stdin_rx_chr();
if (c == CHAR_CTRL_A) {
// reset raw REPL
if (vstr_len(&line) == 2 && vstr_str(&line)[0] == CHAR_CTRL_E) {
int ret = do_reader_stdin(vstr_str(&line)[1]);
if (ret & PYEXEC_FORCED_EXIT) {
return ret;
}
vstr_reset(&line);
mp_hal_stdout_tx_str(">");
continue;
}
goto raw_repl_reset;
} else if (c == CHAR_CTRL_B) {
// change to friendly REPL
mp_hal_stdout_tx_str("\r\n");
vstr_clear(&line);
pyexec_mode_kind = PYEXEC_MODE_FRIENDLY_REPL;
return 0;
} else if (c == CHAR_CTRL_C) {
// clear line
vstr_reset(&line);
} else if (c == CHAR_CTRL_D) {
// input finished
break;
#if MICROPY_PY_AOS_QUIT
} else if (c == CHAR_CTRL_X) {
// quit python engine
exit_engine_flag = 1;
break;
#endif
} else {
// let through any other raw 8-bit value
vstr_add_byte(&line, c);
}
}
// indicate reception of command
mp_hal_stdout_tx_str("OK");
if (line.len == 0) {
// exit for a soft reset
mp_hal_stdout_tx_str("\r\n");
vstr_clear(&line);
#if MICROPY_PY_AOS_QUIT
if (exit_engine_flag == 1) {
return PYEXEC_FORCED_QUIT;
} else {
return PYEXEC_FORCED_EXIT;
}
#else
return PYEXEC_FORCED_EXIT;
#endif
}
int ret = parse_compile_execute(&line, MP_PARSE_FILE_INPUT, EXEC_FLAG_PRINT_EOF | EXEC_FLAG_SOURCE_IS_VSTR);
if (ret & PYEXEC_FORCED_EXIT) {
return ret;
#if MICROPY_PY_AOS_QUIT
} else if (ret & PYEXEC_FORCED_QUIT) {
return ret;
#endif
}
}
}
int pyexec_friendly_repl(void) {
vstr_t line;
vstr_init(&line, 32);
friendly_repl_reset:
mp_hal_stdout_tx_str("MicroPython " MICROPY_GIT_TAG " on " MICROPY_BUILD_DATE "; " MICROPY_HW_BOARD_NAME " with " MICROPY_HW_MCU_NAME "\r\n");
#if MICROPY_PY_BUILTINS_HELP
mp_hal_stdout_tx_str("Type \"help()\" for more information.\r\n");
#endif
// to test ctrl-C
/*
{
uint32_t x[4] = {0x424242, 0xdeaddead, 0x242424, 0xdeadbeef};
for (;;) {
nlr_buf_t nlr;
printf("pyexec_repl: %p\n", x);
mp_hal_set_interrupt_char(CHAR_CTRL_C);
if (nlr_push(&nlr) == 0) {
for (;;) {
}
} else {
printf("break\n");
}
}
}
*/
for (;;) {
input_restart:
#if MICROPY_HW_ENABLE_USB
if (usb_vcp_is_enabled()) {
// If the user gets to here and interrupts are disabled then
// they'll never see the prompt, traceback etc. The USB REPL needs
// interrupts to be enabled or no transfers occur. So we try to
// do the user a favor and reenable interrupts.
if (query_irq() == IRQ_STATE_DISABLED) {
enable_irq(IRQ_STATE_ENABLED);
mp_hal_stdout_tx_str("MPY: enabling IRQs\r\n");
}
}
#endif
// If the GC is locked at this point there is no way out except a reset,
// so force the GC to be unlocked to help the user debug what went wrong.
if (MP_STATE_MEM(gc_lock_depth) != 0) {
MP_STATE_MEM(gc_lock_depth) = 0;
}
vstr_reset(&line);
int ret = readline(&line, ">>> ");
mp_parse_input_kind_t parse_input_kind = MP_PARSE_SINGLE_INPUT;
if (ret == CHAR_CTRL_A) {
// change to raw REPL
mp_hal_stdout_tx_str("\r\n");
vstr_clear(&line);
pyexec_mode_kind = PYEXEC_MODE_RAW_REPL;
return 0;
} else if (ret == CHAR_CTRL_B) {
// reset friendly REPL
mp_hal_stdout_tx_str("\r\n");
goto friendly_repl_reset;
} else if (ret == CHAR_CTRL_C) {
// break
mp_hal_stdout_tx_str("\r\n");
continue;
} else if (ret == CHAR_CTRL_D) {
// exit for a soft reset
mp_hal_stdout_tx_str("\r\n");
vstr_clear(&line);
return PYEXEC_FORCED_EXIT;
#if MICROPY_PY_AOS_QUIT
} else if (ret == CHAR_CTRL_X) {
// exit for a soft reset
mp_hal_stdout_tx_str("\r\n");
vstr_clear(&line);
return PYEXEC_FORCED_QUIT;
#endif
} else if (ret == CHAR_CTRL_E) {
// paste mode
mp_hal_stdout_tx_str("\r\npaste mode; Ctrl-C to cancel, Ctrl-D to finish\r\n=== ");
vstr_reset(&line);
for (;;) {
char c = mp_hal_stdin_rx_chr();
if (c == CHAR_CTRL_C) {
// cancel everything
mp_hal_stdout_tx_str("\r\n");
goto input_restart;
} else if (c == CHAR_CTRL_D) {
// end of input
mp_hal_stdout_tx_str("\r\n");
break;
#if MICROPY_PY_AOS_QUIT
} else if (c == CHAR_CTRL_X) {
// end of input
mp_hal_stdout_tx_str("\r\n");
break;
#endif
} else {
// add char to buffer and echo
vstr_add_byte(&line, c);
if (c == '\r') {
mp_hal_stdout_tx_str("\r\n=== ");
} else {
mp_hal_stdout_tx_strn(&c, 1);
}
}
}
parse_input_kind = MP_PARSE_FILE_INPUT;
} else if (vstr_len(&line) == 0) {
continue;
} else {
// got a line with non-zero length, see if it needs continuing
while (mp_repl_continue_with_input(vstr_null_terminated_str(&line))) {
vstr_add_byte(&line, '\n');
ret = readline(&line, "... ");
if (ret == CHAR_CTRL_C) {
// cancel everything
mp_hal_stdout_tx_str("\r\n");
goto input_restart;
} else if (ret == CHAR_CTRL_D) {
// stop entering compound statement
break;
#if MICROPY_PY_AOS_QUIT
} else if (ret == CHAR_CTRL_X) {
// stop entering compound statement
break;
#endif
}
}
}
ret = parse_compile_execute(&line, parse_input_kind, EXEC_FLAG_ALLOW_DEBUGGING | EXEC_FLAG_IS_REPL | EXEC_FLAG_SOURCE_IS_VSTR);
if (ret & PYEXEC_FORCED_EXIT) {
return ret;
}
}
}
#endif // MICROPY_REPL_EVENT_DRIVEN
#endif // MICROPY_ENABLE_COMPILER
int pyexec_file(const char *filename) {
return parse_compile_execute(filename, MP_PARSE_FILE_INPUT, EXEC_FLAG_SOURCE_IS_FILENAME);
}
int pyexec_file_if_exists(const char *filename) {
#if MICROPY_MODULE_FROZEN
if (mp_frozen_stat(filename) == MP_IMPORT_STAT_FILE) {
return pyexec_frozen_module(filename);
}
#endif
if (mp_import_stat(filename) != MP_IMPORT_STAT_FILE) {
return 1; // success (no file is the same as an empty file executing without fail)
}
return pyexec_file(filename);
}
#if MICROPY_MODULE_FROZEN
int pyexec_frozen_module(const char *name) {
void *frozen_data;
int frozen_type = mp_find_frozen_module(name, strlen(name), &frozen_data);
switch (frozen_type) {
#if MICROPY_MODULE_FROZEN_STR
case MP_FROZEN_STR:
return parse_compile_execute(frozen_data, MP_PARSE_FILE_INPUT, 0);
#endif
#if MICROPY_MODULE_FROZEN_MPY
case MP_FROZEN_MPY:
return parse_compile_execute(frozen_data, MP_PARSE_FILE_INPUT, EXEC_FLAG_SOURCE_IS_RAW_CODE);
#endif
default:
printf("could not find module '%s'\n", name);
return false;
}
}
#endif
#if MICROPY_REPL_INFO
mp_obj_t pyb_set_repl_info(mp_obj_t o_value) {
repl_display_debugging_info = mp_obj_get_int(o_value);
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_1(pyb_set_repl_info_obj, pyb_set_repl_info);
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/runtime/pyexec.c | C | apache-2.0 | 26,617 |
/*
* 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_LIB_UTILS_PYEXEC_H
#define MICROPY_INCLUDED_LIB_UTILS_PYEXEC_H
#include "py/obj.h"
typedef enum {
PYEXEC_MODE_FRIENDLY_REPL,
PYEXEC_MODE_RAW_REPL,
} pyexec_mode_kind_t;
extern pyexec_mode_kind_t pyexec_mode_kind;
// Set this to the value (eg PYEXEC_FORCED_EXIT) that will be propagated through
// the pyexec functions if a SystemExit exception is raised by the running code.
// It will reset to 0 at the start of each execution (eg each REPL entry).
extern int pyexec_system_exit;
#define PYEXEC_FORCED_EXIT (0x100)
#define PYEXEC_FORCED_QUIT (0x200)
int pyexec_raw_repl(void);
int pyexec_friendly_repl(void);
int pyexec_file(const char *filename);
int pyexec_file_if_exists(const char *filename);
int pyexec_frozen_module(const char *name);
void pyexec_event_repl_init(void);
int pyexec_event_repl_process_char(int c);
extern uint8_t pyexec_repl_active;
#if MICROPY_REPL_INFO
mp_obj_t pyb_set_repl_info(mp_obj_t o_value);
MP_DECLARE_CONST_FUN_OBJ_1(pyb_set_repl_info_obj);
#endif
#endif // MICROPY_INCLUDED_LIB_UTILS_PYEXEC_H
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/runtime/pyexec.h | C | apache-2.0 | 2,300 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2018 Ayke van Laethem
*
* 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 "semihosting.h"
// Resources:
// http://embed.rs/articles/2016/semi-hosting-rust/
// https://wiki.dlang.org/Minimal_semihosted_ARM_Cortex-M_%22Hello_World%22
// https://github.com/arduino/OpenOCD/blob/master/src/target/arm_semihosting.c
#define SYS_OPEN 0x01
#define SYS_WRITEC 0x03
#define SYS_WRITE 0x05
#define SYS_READC 0x07
// Constants:
#define OPEN_MODE_READ (0) // mode "r"
#define OPEN_MODE_WRITE (4) // mode "w"
#ifndef __thumb__
#error Semihosting is only implemented for ARM microcontrollers.
#endif
static int mp_semihosting_stdout;
static uint32_t mp_semihosting_call(uint32_t num, const void *arg) {
// A semihosting call works as follows, similar to a SVCall:
// * the call is invoked by a special breakpoint: 0xAB
// * the command is placed in r0
// * a pointer to the arguments is placed in r1
// * the return value is placed in r0
// Note that because it uses the breakpoint instruction, applications
// will hang if they're not connected to a debugger. And they'll be
// stuck in a breakpoint if semihosting is not specifically enabled in
// the debugger.
// Also note that semihosting is extremely slow (sometimes >100ms per
// call).
register uint32_t num_reg __asm__ ("r0") = num;
register const void *args_reg __asm__ ("r1") = arg;
__asm__ __volatile__ (
"bkpt 0xAB\n" // invoke semihosting call
: "+r" (num_reg) // call number and result
: "r" (args_reg) // arguments
: "memory"); // make sure args aren't optimized away
return num_reg; // r0, which became the result
}
static int mp_semihosting_open_console(uint32_t mode) {
struct {
char *name;
uint32_t mode;
uint32_t name_len;
} args = {
.name = ":tt", // magic path to console
.mode = mode, // e.g. "r", "w" (see OPEN_MODE_* constants)
.name_len = 3, // strlen(":tt")
};
return mp_semihosting_call(SYS_OPEN, &args);
}
void mp_semihosting_init() {
mp_semihosting_stdout = mp_semihosting_open_console(OPEN_MODE_WRITE);
}
int mp_semihosting_rx_char() {
return mp_semihosting_call(SYS_READC, NULL);
}
static void mp_semihosting_tx_char(char c) {
mp_semihosting_call(SYS_WRITEC, &c);
}
uint32_t mp_semihosting_tx_strn(const char *str, size_t len) {
if (len == 0) {
return 0; // nothing to do
}
if (len == 1) {
mp_semihosting_tx_char(*str); // maybe faster?
return 0;
}
struct {
uint32_t fd;
const char *str;
uint32_t len;
} args = {
.fd = mp_semihosting_stdout,
.str = str,
.len = len,
};
return mp_semihosting_call(SYS_WRITE, &args);
}
uint32_t mp_semihosting_tx_strn_cooked(const char *str, size_t len) {
// Write chunks of data until (excluding) the first '\n' character,
// insert a '\r' character, and then continue with the next chunk
// (starting with '\n').
// Doing byte-by-byte writes would be easier to implement but is far
// too slow.
size_t start = 0;
for (size_t i = 0; i < len; i++) {
if (str[i] == '\n') {
mp_semihosting_tx_strn(str + start, i - start);
mp_semihosting_tx_char('\r');
start = i;
}
}
return mp_semihosting_tx_strn(str + start, len - start);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/runtime/semihosting.c | C | apache-2.0 | 4,611 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2018 Ayke van Laethem
*
* 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_LIB_UTILS_SEMIHOSTING_H
#define MICROPY_INCLUDED_LIB_UTILS_SEMIHOSTING_H
/*
To use semi-hosting for a replacement UART:
- Add lib/semihosting/semihosting.c to the Makefile sources.
- Call mp_semihosting_init() in main(), around the time UART is initialized.
- Replace mp_hal_stdin_rx_chr and similar in mphalport.c with the semihosting equivalent.
- Include lib/semihosting/semihosting.h in the relevant files.
Then make sure the debugger is attached and enables semihosting. In OpenOCD this is
done with ARM semihosting enable followed by reset. The terminal will need further
configuration to work with MicroPython (bash: stty raw -echo).
*/
#include <stddef.h>
#include <stdint.h>
void mp_semihosting_init();
int mp_semihosting_rx_char();
uint32_t mp_semihosting_tx_strn(const char *str, size_t len);
uint32_t mp_semihosting_tx_strn_cooked(const char *str, size_t len);
#endif // MICROPY_INCLUDED_LIB_UTILS_SEMIHOSTING_H
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/runtime/semihosting.h | C | apache-2.0 | 2,183 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2021 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/mphal.h"
#if !MICROPY_PY_AOS_SPECIFIC // disabled by HaaS-AMP
/*
* Extra stdout functions
* These can be either optimized for a particular port, or reference
* implementation below can be used.
*/
// Send "cooked" string of given length, where every occurrence of
// LF character is replaced with CR LF ("\n" is converted to "\r\n").
// This is an optimised version to reduce the number of calls made
// to mp_hal_stdout_tx_strn.
void mp_hal_stdout_tx_strn_cooked(const char *str, size_t len) {
const char *last = str;
while (len--) {
if (*str == '\n') {
if (str > last) {
mp_hal_stdout_tx_strn(last, str - last);
}
mp_hal_stdout_tx_strn("\r\n", 2);
++str;
last = str;
} else {
++str;
}
}
if (str > last) {
mp_hal_stdout_tx_strn(last, str - last);
}
}
// Send zero-terminated string
void mp_hal_stdout_tx_str(const char *str) {
mp_hal_stdout_tx_strn(str, strlen(str));
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/runtime/stdout_helpers.c | C | apache-2.0 | 2,288 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013-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 <stdio.h>
#include <string.h>
#include "py/obj.h"
#include "py/stream.h"
#include "py/mperrno.h"
#include "py/mphal.h"
// TODO make stdin, stdout and stderr writable objects so they can
// be changed by Python code. This requires some changes, as these
// objects are in a read-only module (py/modsys.c).
/******************************************************************************/
// MicroPython bindings
#define STDIO_FD_IN (0)
#define STDIO_FD_OUT (1)
#define STDIO_FD_ERR (2)
typedef struct _sys_stdio_obj_t {
mp_obj_base_t base;
int fd;
} sys_stdio_obj_t;
#if MICROPY_PY_SYS_STDIO_BUFFER
STATIC const sys_stdio_obj_t stdio_buffer_obj;
#endif
void stdio_obj_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
sys_stdio_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "<io.FileIO %d>", self->fd);
}
STATIC mp_uint_t stdio_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) {
sys_stdio_obj_t *self = MP_OBJ_TO_PTR(self_in);
if (self->fd == STDIO_FD_IN) {
for (uint i = 0; i < size; i++) {
int c = mp_hal_stdin_rx_chr();
if (c == '\r') {
c = '\n';
}
((byte *)buf)[i] = c;
}
return size;
} else {
*errcode = MP_EPERM;
return MP_STREAM_ERROR;
}
}
STATIC mp_uint_t stdio_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) {
sys_stdio_obj_t *self = MP_OBJ_TO_PTR(self_in);
if (self->fd == STDIO_FD_OUT || self->fd == STDIO_FD_ERR) {
mp_hal_stdout_tx_strn_cooked(buf, size);
return size;
} else {
*errcode = MP_EPERM;
return MP_STREAM_ERROR;
}
}
STATIC mp_uint_t stdio_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) {
(void)self_in;
if (request == MP_STREAM_POLL) {
return mp_hal_stdio_poll(arg);
} else {
*errcode = MP_EINVAL;
return MP_STREAM_ERROR;
}
}
STATIC mp_obj_t stdio_obj___exit__(size_t n_args, const mp_obj_t *args) {
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(stdio_obj___exit___obj, 4, 4, stdio_obj___exit__);
// TODO gc hook to close the file if not already closed
STATIC const mp_rom_map_elem_t stdio_locals_dict_table[] = {
#if MICROPY_PY_SYS_STDIO_BUFFER
{ MP_ROM_QSTR(MP_QSTR_buffer), MP_ROM_PTR(&stdio_buffer_obj) },
#endif
{ MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
{ MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
{ MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj)},
{ MP_ROM_QSTR(MP_QSTR_readlines), MP_ROM_PTR(&mp_stream_unbuffered_readlines_obj)},
{ MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
{ MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_identity_obj) },
{ MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_identity_obj) },
{ MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&mp_identity_obj) },
{ MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&stdio_obj___exit___obj) },
};
STATIC MP_DEFINE_CONST_DICT(stdio_locals_dict, stdio_locals_dict_table);
STATIC const mp_stream_p_t stdio_obj_stream_p = {
.read = stdio_read,
.write = stdio_write,
.ioctl = stdio_ioctl,
.is_text = true,
};
STATIC const mp_obj_type_t stdio_obj_type = {
{ &mp_type_type },
.name = MP_QSTR_FileIO,
// TODO .make_new?
.print = stdio_obj_print,
.getiter = mp_identity_getiter,
.iternext = mp_stream_unbuffered_iter,
.protocol = &stdio_obj_stream_p,
.locals_dict = (mp_obj_dict_t *)&stdio_locals_dict,
};
const sys_stdio_obj_t mp_sys_stdin_obj = {{&stdio_obj_type}, .fd = STDIO_FD_IN};
const sys_stdio_obj_t mp_sys_stdout_obj = {{&stdio_obj_type}, .fd = STDIO_FD_OUT};
const sys_stdio_obj_t mp_sys_stderr_obj = {{&stdio_obj_type}, .fd = STDIO_FD_ERR};
#if MICROPY_PY_SYS_STDIO_BUFFER
STATIC mp_uint_t stdio_buffer_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) {
for (uint i = 0; i < size; i++) {
((byte *)buf)[i] = mp_hal_stdin_rx_chr();
}
return size;
}
STATIC mp_uint_t stdio_buffer_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) {
mp_hal_stdout_tx_strn(buf, size);
return size;
}
STATIC const mp_stream_p_t stdio_buffer_obj_stream_p = {
.read = stdio_buffer_read,
.write = stdio_buffer_write,
.ioctl = stdio_ioctl,
.is_text = false,
};
STATIC const mp_obj_type_t stdio_buffer_obj_type = {
{ &mp_type_type },
.name = MP_QSTR_FileIO,
.print = stdio_obj_print,
.getiter = mp_identity_getiter,
.iternext = mp_stream_unbuffered_iter,
.protocol = &stdio_buffer_obj_stream_p,
.locals_dict = (mp_obj_dict_t *)&stdio_locals_dict,
};
STATIC const sys_stdio_obj_t stdio_buffer_obj = {{&stdio_buffer_obj_type}, .fd = 0}; // fd unused
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/runtime/sys_stdio_mphal.c | C | apache-2.0 | 6,119 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
* Copyright (c) 2015 Daniel Campora
*
* 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/obj.h"
#include "shared/timeutils/timeutils.h"
// LEAPOCH corresponds to 2000-03-01, which is a mod-400 year, immediately
// after Feb 29. We calculate seconds as a signed integer relative to that.
//
// Our timebase is relative to 2000-01-01.
#define LEAPOCH ((31 + 29) * 86400)
#define DAYS_PER_400Y (365 * 400 + 97)
#define DAYS_PER_100Y (365 * 100 + 24)
#define DAYS_PER_4Y (365 * 4 + 1)
STATIC const uint16_t days_since_jan1[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
bool timeutils_is_leap_year(mp_uint_t year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
// month is one based
mp_uint_t timeutils_days_in_month(mp_uint_t year, mp_uint_t month) {
mp_uint_t mdays = days_since_jan1[month] - days_since_jan1[month - 1];
if (month == 2 && timeutils_is_leap_year(year)) {
mdays++;
}
return mdays;
}
// compute the day of the year, between 1 and 366
// month should be between 1 and 12, date should start at 1
mp_uint_t timeutils_year_day(mp_uint_t year, mp_uint_t month, mp_uint_t date) {
mp_uint_t yday = days_since_jan1[month - 1] + date;
if (month >= 3 && timeutils_is_leap_year(year)) {
yday += 1;
}
return yday;
}
void timeutils_seconds_since_2000_to_struct_time(mp_uint_t t, timeutils_struct_time_t *tm) {
// The following algorithm was adapted from musl's __secs_to_tm and adapted
// for differences in MicroPython's timebase.
mp_int_t seconds = t - LEAPOCH;
mp_int_t days = seconds / 86400;
seconds %= 86400;
if (seconds < 0) {
seconds += 86400;
days -= 1;
}
tm->tm_hour = seconds / 3600;
tm->tm_min = seconds / 60 % 60;
tm->tm_sec = seconds % 60;
mp_int_t wday = (days + 2) % 7; // Mar 1, 2000 was a Wednesday (2)
if (wday < 0) {
wday += 7;
}
tm->tm_wday = wday;
mp_int_t qc_cycles = days / DAYS_PER_400Y;
days %= DAYS_PER_400Y;
if (days < 0) {
days += DAYS_PER_400Y;
qc_cycles--;
}
mp_int_t c_cycles = days / DAYS_PER_100Y;
if (c_cycles == 4) {
c_cycles--;
}
days -= (c_cycles * DAYS_PER_100Y);
mp_int_t q_cycles = days / DAYS_PER_4Y;
if (q_cycles == 25) {
q_cycles--;
}
days -= q_cycles * DAYS_PER_4Y;
mp_int_t years = days / 365;
if (years == 4) {
years--;
}
days -= (years * 365);
/* We will compute tm_yday at the very end
mp_int_t leap = !years && (q_cycles || !c_cycles);
tm->tm_yday = days + 31 + 28 + leap;
if (tm->tm_yday >= 365 + leap) {
tm->tm_yday -= 365 + leap;
}
tm->tm_yday++; // Make one based
*/
tm->tm_year = 2000 + years + 4 * q_cycles + 100 * c_cycles + 400 * qc_cycles;
// Note: days_in_month[0] corresponds to March
STATIC const int8_t days_in_month[] = {31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29};
mp_int_t month;
for (month = 0; days_in_month[month] <= days; month++) {
days -= days_in_month[month];
}
tm->tm_mon = month + 2;
if (tm->tm_mon >= 12) {
tm->tm_mon -= 12;
tm->tm_year++;
}
tm->tm_mday = days + 1; // Make one based
tm->tm_mon++; // Make one based
tm->tm_yday = timeutils_year_day(tm->tm_year, tm->tm_mon, tm->tm_mday);
}
// returns the number of seconds, as an integer, since 2000-01-01
mp_uint_t timeutils_seconds_since_2000(mp_uint_t year, mp_uint_t month,
mp_uint_t date, mp_uint_t hour, mp_uint_t minute, mp_uint_t second) {
return
second
+ minute * 60
+ hour * 3600
+ (timeutils_year_day(year, month, date) - 1
+ ((year - 2000 + 3) / 4) // add a day each 4 years starting with 2001
- ((year - 2000 + 99) / 100) // subtract a day each 100 years starting with 2001
+ ((year - 2000 + 399) / 400) // add a day each 400 years starting with 2001
) * 86400
+ (year - 2000) * 31536000;
}
mp_uint_t timeutils_mktime_2000(mp_uint_t year, mp_int_t month, mp_int_t mday,
mp_int_t hours, mp_int_t minutes, mp_int_t seconds) {
// Normalize the tuple. This allows things like:
//
// tm_tomorrow = list(time.localtime())
// tm_tomorrow[2] += 1 # Adds 1 to mday
// tomorrow = time.mktime(tm_tomorrow)
//
// And not have to worry about all the weird overflows.
//
// You can subtract dates/times this way as well.
minutes += seconds / 60;
if ((seconds = seconds % 60) < 0) {
seconds += 60;
minutes--;
}
hours += minutes / 60;
if ((minutes = minutes % 60) < 0) {
minutes += 60;
hours--;
}
mday += hours / 24;
if ((hours = hours % 24) < 0) {
hours += 24;
mday--;
}
month--; // make month zero based
year += month / 12;
if ((month = month % 12) < 0) {
month += 12;
year--;
}
month++; // back to one based
while (mday < 1) {
if (--month == 0) {
month = 12;
year--;
}
mday += timeutils_days_in_month(year, month);
}
while ((mp_uint_t)mday > timeutils_days_in_month(year, month)) {
mday -= timeutils_days_in_month(year, month);
if (++month == 13) {
month = 1;
year++;
}
}
return timeutils_seconds_since_2000(year, month, mday, hours, minutes, seconds);
}
// Calculate the weekday from the date.
// The result is zero based with 0 = Monday.
// by Michael Keith and Tom Craver, 1990.
int timeutils_calc_weekday(int y, int m, int d) {
return ((d += m < 3 ? y-- : y - 2, 23 * m / 9 + d + 4 + y / 4 - y / 100 + y / 400) + 6) % 7;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/timeutils/timeutils.c | C | apache-2.0 | 6,948 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
* Copyright (c) 2015 Daniel Campora
*
* 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_LIB_TIMEUTILS_TIMEUTILS_H
#define MICROPY_INCLUDED_LIB_TIMEUTILS_TIMEUTILS_H
// Modified bt HaaS begin
#if !MICROPY_PY_AOS_SPECIFIC
#include <stdbool.h>
#include "py/mpconfig.h"
#endif
// Modified bt HaaS end
// The number of seconds between 1970/1/1 and 2000/1/1 is calculated using:
// time.mktime((2000,1,1,0,0,0,0,0,0)) - time.mktime((1970,1,1,0,0,0,0,0,0))
#define TIMEUTILS_SECONDS_1970_TO_2000 (946684800ULL)
typedef struct _timeutils_struct_time_t {
uint16_t tm_year; // i.e. 2014
uint8_t tm_mon; // 1..12
uint8_t tm_mday; // 1..31
uint8_t tm_hour; // 0..23
uint8_t tm_min; // 0..59
uint8_t tm_sec; // 0..59
uint8_t tm_wday; // 0..6 0 = Monday
uint16_t tm_yday; // 1..366
} timeutils_struct_time_t;
bool timeutils_is_leap_year(mp_uint_t year);
mp_uint_t timeutils_days_in_month(mp_uint_t year, mp_uint_t month);
mp_uint_t timeutils_year_day(mp_uint_t year, mp_uint_t month, mp_uint_t date);
void timeutils_seconds_since_2000_to_struct_time(mp_uint_t t,
timeutils_struct_time_t *tm);
mp_uint_t timeutils_seconds_since_2000(mp_uint_t year, mp_uint_t month,
mp_uint_t date, mp_uint_t hour, mp_uint_t minute, mp_uint_t second);
mp_uint_t timeutils_mktime_2000(mp_uint_t year, mp_int_t month, mp_int_t mday,
mp_int_t hours, mp_int_t minutes, mp_int_t seconds);
// Select the Epoch used by the port.
#if MICROPY_EPOCH_IS_1970
static inline void timeutils_seconds_since_epoch_to_struct_time(uint64_t t, timeutils_struct_time_t *tm) {
// TODO this will give incorrect results for dates before 2000/1/1
return timeutils_seconds_since_2000_to_struct_time(t - TIMEUTILS_SECONDS_1970_TO_2000, tm);
}
static inline uint64_t timeutils_mktime(mp_uint_t year, mp_int_t month, mp_int_t mday, mp_int_t hours, mp_int_t minutes, mp_int_t seconds) {
return timeutils_mktime_2000(year, month, mday, hours, minutes, seconds) + TIMEUTILS_SECONDS_1970_TO_2000;
}
static inline uint64_t timeutils_seconds_since_epoch(mp_uint_t year, mp_uint_t month,
mp_uint_t date, mp_uint_t hour, mp_uint_t minute, mp_uint_t second) {
return timeutils_seconds_since_2000(year, month, date, hour, minute, second) + TIMEUTILS_SECONDS_1970_TO_2000;
}
static inline mp_uint_t timeutils_seconds_since_epoch_from_nanoseconds_since_1970(uint64_t ns) {
return ns / 1000000000ULL;
}
static inline uint64_t timeutils_nanoseconds_since_epoch_to_nanoseconds_since_1970(uint64_t ns) {
return ns;
}
#else // Epoch is 2000
#define timeutils_seconds_since_epoch_to_struct_time timeutils_seconds_since_2000_to_struct_time
#define timeutils_seconds_since_epoch timeutils_seconds_since_2000
#define timeutils_mktime timeutils_mktime_2000
static inline uint64_t timeutils_seconds_since_epoch_to_nanoseconds_since_1970(mp_uint_t s) {
return ((uint64_t)s + TIMEUTILS_SECONDS_1970_TO_2000) * 1000000000ULL;
}
static inline mp_uint_t timeutils_seconds_since_epoch_from_nanoseconds_since_1970(uint64_t ns) {
return ns / 1000000000ULL - TIMEUTILS_SECONDS_1970_TO_2000;
}
static inline int64_t timeutils_nanoseconds_since_epoch_to_nanoseconds_since_1970(int64_t ns) {
return ns + TIMEUTILS_SECONDS_1970_TO_2000 * 1000000000ULL;
}
#endif
int timeutils_calc_weekday(int y, int m, int d);
#endif // MICROPY_INCLUDED_LIB_TIMEUTILS_TIMEUTILS_H
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/timeutils/timeutils.h | C | apache-2.0 | 4,637 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2017 Linaro 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 <string.h>
#include "py/mphal.h"
#include "py/gc.h"
#include "py/runtime.h"
#include "py/compile.h"
#include "upytesthelper.h"
static const char *test_exp_output;
static int test_exp_output_len, test_rem_output_len;
static int test_failed;
static void *heap_start, *heap_end;
void upytest_set_heap(void *start, void *end) {
heap_start = start;
heap_end = end;
}
void upytest_set_expected_output(const char *output, unsigned len) {
test_exp_output = output;
test_exp_output_len = test_rem_output_len = len;
test_failed = false;
}
bool upytest_is_failed(void) {
if (test_failed) {
return true;
}
#if 0
if (test_rem_output_len != 0) {
printf("remaining len: %d\n", test_rem_output_len);
}
#endif
return test_rem_output_len != 0;
}
// MP_PLAT_PRINT_STRN() should be redirected to this function.
// It will pass-thru any content to mp_hal_stdout_tx_strn_cooked()
// (the dfault value of MP_PLAT_PRINT_STRN), but will also match
// it to the expected output as set by upytest_set_expected_output().
// If mismatch happens, upytest_is_failed() returns true.
void upytest_output(const char *str, mp_uint_t len) {
if (!test_failed) {
if (len > test_rem_output_len) {
test_failed = true;
} else {
test_failed = memcmp(test_exp_output, str, len);
#if 0
if (test_failed) {
printf("failed after char %u, within %d chars, res: %d\n",
test_exp_output_len - test_rem_output_len, (int)len, test_failed);
for (int i = 0; i < len; i++) {
if (str[i] != test_exp_output[i]) {
printf("%d %02x %02x\n", i, str[i], test_exp_output[i]);
}
}
}
#endif
test_exp_output += len;
test_rem_output_len -= len;
}
}
mp_hal_stdout_tx_strn_cooked(str, len);
}
void upytest_execute_test(const char *src) {
// To provide clean room for each test, interpreter and heap are
// reinitialized before running each.
gc_init(heap_start, heap_end);
mp_init();
mp_obj_list_init(mp_sys_path, 0);
mp_obj_list_init(mp_sys_argv, 0);
nlr_buf_t nlr;
if (nlr_push(&nlr) == 0) {
mp_lexer_t *lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, src, strlen(src), 0);
qstr source_name = lex->source_name;
mp_parse_tree_t parse_tree = mp_parse(lex, MP_PARSE_FILE_INPUT);
mp_obj_t module_fun = mp_compile(&parse_tree, source_name, false);
mp_call_function_0(module_fun);
nlr_pop();
} else {
mp_obj_t exc = (mp_obj_t)nlr.ret_val;
if (mp_obj_is_subclass_fast(mp_obj_get_type(exc), &mp_type_SystemExit)) {
// Assume that sys.exit() is called to skip the test.
// TODO: That can be always true, we should set up convention to
// use specific exit code as skip indicator.
tinytest_set_test_skipped_();
goto end;
}
mp_obj_print_exception(&mp_plat_print, exc);
tt_abort_msg("Uncaught exception\n");
}
if (upytest_is_failed()) {
tinytest_set_test_failed_();
}
end:
mp_deinit();
}
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/upytesthelper/upytesthelper.c | C | apache-2.0 | 4,492 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2017 Linaro 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 <stdbool.h>
#include <stdio.h>
#include "py/mpconfig.h"
#include "lib/tinytest/tinytest.h"
#include "lib/tinytest/tinytest_macros.h"
void upytest_set_heap(void *start, void *end);
void upytest_set_expected_output(const char *output, unsigned len);
void upytest_execute_test(const char *src);
void upytest_output(const char *str, mp_uint_t len);
bool upytest_is_failed(void);
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/upytesthelper/upytesthelper.h | C | apache-2.0 | 1,609 |
#!/usr/bin/env python3
"""
This is a middle-processor for MicroPython source files. It takes the output
of the C preprocessor, has the option to change it, then feeds this into the
C compiler.
It currently has the ability to reorder static hash tables so they are actually
hashed, resulting in faster lookup times at runtime.
To use, configure the Python variables below, and add the following line to the
Makefile:
CFLAGS += -no-integrated-cpp -B$(shell pwd)/../tools
"""
import sys
import os
import re
################################################################################
# these are the configuration variables
# TODO somehow make them externally configurable
# this is the path to the true C compiler
cc1_path = '/usr/lib/gcc/x86_64-unknown-linux-gnu/5.3.0/cc1'
#cc1_path = '/usr/lib/gcc/arm-none-eabi/5.3.0/cc1'
# this must be the same as MICROPY_QSTR_BYTES_IN_HASH
bytes_in_qstr_hash = 2
# this must be 1 or more (can be a decimal)
# larger uses more code size but yields faster lookups
table_size_mult = 1
# these control output during processing
print_stats = True
print_debug = False
# end configuration variables
################################################################################
# precompile regexs
re_preproc_line = re.compile(r'# [0-9]+ ')
re_map_entry = re.compile(r'\{.+?\(MP_QSTR_([A-Za-z0-9_]+)\).+\},')
re_mp_obj_dict_t = re.compile(r'(?P<head>(static )?const mp_obj_dict_t (?P<id>[a-z0-9_]+) = \{ \.base = \{&mp_type_dict\}, \.map = \{ \.all_keys_are_qstrs = 1, \.is_fixed = 1, \.is_ordered = )1(?P<tail>, \.used = .+ };)$')
re_mp_map_t = re.compile(r'(?P<head>(static )?const mp_map_t (?P<id>[a-z0-9_]+) = \{ \.all_keys_are_qstrs = 1, \.is_fixed = 1, \.is_ordered = )1(?P<tail>, \.used = .+ };)$')
re_mp_rom_map_elem_t = re.compile(r'static const mp_rom_map_elem_t [a-z_0-9]+\[\] = {$')
# this must match the equivalent function in qstr.c
def compute_hash(qstr):
hash = 5381
for char in qstr:
hash = (hash * 33) ^ ord(char)
# Make sure that valid hash is never zero, zero means "hash not computed"
return (hash & ((1 << (8 * bytes_in_qstr_hash)) - 1)) or 1
# this algo must match the equivalent in map.c
def hash_insert(map, key, value):
hash = compute_hash(key)
pos = hash % len(map)
start_pos = pos
if print_debug:
print(' insert %s: start at %u/%u -- ' % (key, pos, len(map)), end='')
while True:
if map[pos] is None:
# found empty slot, so key is not in table
if print_debug:
print('put at %u' % pos)
map[pos] = (key, value)
return
else:
# not yet found, keep searching
if map[pos][0] == key:
raise AssertionError("duplicate key '%s'" % (key,))
pos = (pos + 1) % len(map)
assert pos != start_pos
def hash_find(map, key):
hash = compute_hash(key)
pos = hash % len(map)
start_pos = pos
attempts = 0
while True:
attempts += 1
if map[pos] is None:
return attempts, None
elif map[pos][0] == key:
return attempts, map[pos][1]
else:
pos = (pos + 1) % len(map)
if pos == start_pos:
return attempts, None
def process_map_table(file, line, output):
output.append(line)
# consume all lines that are entries of the table and concat them
# (we do it this way because there can be multiple entries on one line)
table_contents = []
while True:
line = file.readline()
if len(line) == 0:
print('unexpected end of input')
sys.exit(1)
line = line.strip()
if len(line) == 0:
# empty line
continue
if re_preproc_line.match(line):
# preprocessor line number comment
continue
if line == '};':
# end of table (we assume it appears on a single line)
break
table_contents.append(line)
# make combined string of entries
entries_str = ''.join(table_contents)
# split into individual entries
entries = []
while entries_str:
# look for single entry, by matching nested braces
match = None
if entries_str[0] == '{':
nested_braces = 0
for i in range(len(entries_str)):
if entries_str[i] == '{':
nested_braces += 1
elif entries_str[i] == '}':
nested_braces -= 1
if nested_braces == 0:
match = re_map_entry.match(entries_str[:i + 2])
break
if not match:
print('unknown line in table:', entries_str)
sys.exit(1)
# extract single entry
line = match.group(0)
qstr = match.group(1)
entries_str = entries_str[len(line):].lstrip()
# add the qstr and the whole line to list of all entries
entries.append((qstr, line))
# sort entries so hash table construction is deterministic
entries.sort()
# create hash table
map = [None] * int(len(entries) * table_size_mult)
for qstr, line in entries:
# We assume that qstr does not have any escape sequences in it.
# This is reasonably safe, since keys in a module or class dict
# should be standard identifiers.
# TODO verify this and raise an error if escape sequence found
hash_insert(map, qstr, line)
# compute statistics
total_attempts = 0
for qstr, _ in entries:
attempts, line = hash_find(map, qstr)
assert line is not None
if print_debug:
print(' %s lookup took %u attempts' % (qstr, attempts))
total_attempts += attempts
if len(entries):
stats = len(map), len(entries) / len(map), total_attempts / len(entries)
else:
stats = 0, 0, 0
if print_debug:
print(' table stats: size=%d, load=%.2f, avg_lookups=%.1f' % stats)
# output hash table
for row in map:
if row is None:
output.append('{ 0, 0 },\n')
else:
output.append(row[1] + '\n')
output.append('};\n')
# skip to next non-blank line
while True:
line = file.readline()
if len(line) == 0:
print('unexpected end of input')
sys.exit(1)
line = line.strip()
if len(line) == 0:
continue
break
# transform the is_ordered param from 1 to 0
match = re_mp_obj_dict_t.match(line)
if match is None:
match = re_mp_map_t.match(line)
if match is None:
print('expecting mp_obj_dict_t or mp_map_t definition')
print(output[0])
print(line)
sys.exit(1)
line = match.group('head') + '0' + match.group('tail') + '\n'
output.append(line)
return (match.group('id'),) + stats
def process_file(filename):
output = []
file_changed = False
with open(filename, 'rt') as f:
while True:
line = f.readline()
if not line:
break
if re_mp_rom_map_elem_t.match(line):
file_changed = True
stats = process_map_table(f, line, output)
if print_stats:
print(' [%s: size=%d, load=%.2f, avg_lookups=%.1f]' % stats)
else:
output.append(line)
if file_changed:
if print_debug:
print(' modifying static maps in', output[0].strip())
with open(filename, 'wt') as f:
for line in output:
f.write(line)
def main():
# run actual C compiler
# need to quote args that have special characters in them
def quote(s):
if s.find('<') != -1 or s.find('>') != -1:
return "'" + s + "'"
else:
return s
ret = os.system(cc1_path + ' ' + ' '.join(quote(s) for s in sys.argv[1:]))
if ret != 0:
ret = (ret & 0x7f) or 127 # make it in range 0-127, but non-zero
sys.exit(ret)
if sys.argv[1] == '-E':
# CPP has been run, now do our processing stage
for i, arg in enumerate(sys.argv):
if arg == '-o':
return process_file(sys.argv[i + 1])
print('%s: could not find "-o" option' % (sys.argv[0],))
sys.exit(1)
elif sys.argv[1] == '-fpreprocessed':
# compiler has been run, nothing more to do
return
else:
# unknown processing stage
print('%s: unknown first option "%s"' % (sys.argv[0], sys.argv[1]))
sys.exit(1)
if __name__ == '__main__':
main()
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/cc1 | Python | apache-2.0 | 8,667 |
#!/bin/bash
if which nproc > /dev/null; then
MAKEOPTS="-j$(nproc)"
else
MAKEOPTS="-j$(sysctl -n hw.ncpu)"
fi
########################################################################################
# general helper functions
function ci_gcc_arm_setup {
sudo apt-get install gcc-arm-none-eabi libnewlib-arm-none-eabi
arm-none-eabi-gcc --version
}
########################################################################################
# code formatting
function ci_code_formatting_setup {
sudo apt-add-repository --yes --update ppa:pybricks/ppa
sudo apt-get install uncrustify
pip3 install black
uncrustify --version
black --version
}
function ci_code_formatting_run {
tools/codeformat.py -v
}
########################################################################################
# commit formatting
function ci_commit_formatting_run {
git remote add upstream https://github.com/micropython/micropython.git
git fetch --depth=100 upstream master
# For a PR, upstream/master..HEAD ends with a merge commit into master, exlude that one.
tools/verifygitlog.py -v upstream/master..HEAD --no-merges
}
########################################################################################
# code size
function ci_code_size_setup {
sudo apt-get update
sudo apt-get install gcc-multilib
gcc --version
ci_gcc_arm_setup
}
function ci_code_size_build {
# starts off at either the ref/pull/N/merge FETCH_HEAD, or the current branch HEAD
git checkout -b pull_request # save the current location
git remote add upstream https://github.com/micropython/micropython.git
git fetch --depth=100 upstream master
# build reference, save to size0
# ignore any errors with this build, in case master is failing
git checkout `git merge-base --fork-point upstream/master pull_request`
git show -s
tools/metrics.py clean bm
tools/metrics.py build bm | tee ~/size0 || true
# build PR/branch, save to size1
git checkout pull_request
git log upstream/master..HEAD
tools/metrics.py clean bm
tools/metrics.py build bm | tee ~/size1
}
########################################################################################
# ports/cc3200
function ci_cc3200_setup {
ci_gcc_arm_setup
}
function ci_cc3200_build {
make ${MAKEOPTS} -C ports/cc3200 BTARGET=application BTYPE=release
make ${MAKEOPTS} -C ports/cc3200 BTARGET=bootloader BTYPE=release
}
########################################################################################
# ports/esp32
function ci_esp32_setup_helper {
git clone https://github.com/espressif/esp-idf.git
git -C esp-idf checkout $1
git -C esp-idf submodule update --init \
components/bt/host/nimble/nimble \
components/esp_wifi \
components/esptool_py/esptool \
components/lwip/lwip \
components/mbedtls/mbedtls
if [ -d esp-idf/components/bt/controller/esp32 ]; then
git -C esp-idf submodule update --init \
components/bt/controller/lib_esp32 \
components/bt/controller/lib_esp32c3_family
else
git -C esp-idf submodule update --init \
components/bt/controller/lib
fi
./esp-idf/install.sh
}
function ci_esp32_idf402_setup {
ci_esp32_setup_helper v4.0.2
}
function ci_esp32_idf43_setup {
ci_esp32_setup_helper v4.3
}
function ci_esp32_build {
source esp-idf/export.sh
make ${MAKEOPTS} -C mpy-cross
make ${MAKEOPTS} -C ports/esp32 submodules
make ${MAKEOPTS} -C ports/esp32
make ${MAKEOPTS} -C ports/esp32 clean
make ${MAKEOPTS} -C ports/esp32 USER_C_MODULES=../../../examples/usercmodule/micropython.cmake FROZEN_MANIFEST=$(pwd)/ports/esp32/boards/manifest.py
if [ -d $IDF_PATH/components/esp32c3 ]; then
make ${MAKEOPTS} -C ports/esp32 BOARD=GENERIC_C3
fi
if [ -d $IDF_PATH/components/esp32s2 ]; then
make ${MAKEOPTS} -C ports/esp32 BOARD=GENERIC_S2
fi
}
########################################################################################
# ports/esp8266
function ci_esp8266_setup {
sudo pip install pyserial esptool
wget https://github.com/jepler/esp-open-sdk/releases/download/2018-06-10/xtensa-lx106-elf-standalone.tar.gz
zcat xtensa-lx106-elf-standalone.tar.gz | tar x
# Remove this esptool.py so pip version is used instead
rm xtensa-lx106-elf/bin/esptool.py
}
function ci_esp8266_path {
echo $(pwd)/xtensa-lx106-elf/bin
}
function ci_esp8266_build {
make ${MAKEOPTS} -C mpy-cross
make ${MAKEOPTS} -C ports/esp8266 submodules
make ${MAKEOPTS} -C ports/esp8266
make ${MAKEOPTS} -C ports/esp8266 BOARD=GENERIC_512K
make ${MAKEOPTS} -C ports/esp8266 BOARD=GENERIC_1M
}
########################################################################################
# ports/javascript
function ci_javascript_setup {
git clone https://github.com/emscripten-core/emsdk.git
(cd emsdk && ./emsdk install latest && ./emsdk activate latest)
}
function ci_javascript_build {
source emsdk/emsdk_env.sh
make ${MAKEOPTS} -C ports/javascript
}
function ci_javascript_run_tests {
# This port is very slow at running, so only run a few of the tests.
(cd tests && MICROPY_MICROPYTHON=../ports/javascript/node_run.sh ./run-tests.py -j1 basics/builtin_*.py)
}
########################################################################################
# ports/mimxrt
function ci_mimxrt_setup {
ci_gcc_arm_setup
}
function ci_mimxrt_build {
make ${MAKEOPTS} -C mpy-cross
make ${MAKEOPTS} -C ports/mimxrt submodules
make ${MAKEOPTS} -C ports/mimxrt BOARD=MIMXRT1020_EVK
make ${MAKEOPTS} -C ports/mimxrt BOARD=TEENSY40
}
########################################################################################
# ports/nrf
function ci_nrf_setup {
ci_gcc_arm_setup
}
function ci_nrf_build {
ports/nrf/drivers/bluetooth/download_ble_stack.sh s140_nrf52_6_1_1
make ${MAKEOPTS} -C mpy-cross
make ${MAKEOPTS} -C ports/nrf submodules
make ${MAKEOPTS} -C ports/nrf BOARD=pca10040
make ${MAKEOPTS} -C ports/nrf BOARD=microbit
make ${MAKEOPTS} -C ports/nrf BOARD=pca10056 SD=s140
make ${MAKEOPTS} -C ports/nrf BOARD=pca10090
}
########################################################################################
# ports/powerpc
function ci_powerpc_setup {
sudo apt-get update
sudo apt-get install gcc-powerpc64le-linux-gnu libc6-dev-ppc64el-cross
}
function ci_powerpc_build {
make ${MAKEOPTS} -C ports/powerpc UART=potato
make ${MAKEOPTS} -C ports/powerpc UART=lpc_serial
}
########################################################################################
# ports/qemu-arm
function ci_qemu_arm_setup {
ci_gcc_arm_setup
sudo apt-get update
sudo apt-get install qemu-system
qemu-system-arm --version
}
function ci_qemu_arm_build {
make ${MAKEOPTS} -C mpy-cross
make ${MAKEOPTS} -C ports/qemu-arm CFLAGS_EXTRA=-DMP_ENDIANNESS_BIG=1
make ${MAKEOPTS} -C ports/qemu-arm clean
make ${MAKEOPTS} -C ports/qemu-arm -f Makefile.test test
make ${MAKEOPTS} -C ports/qemu-arm -f Makefile.test clean
make ${MAKEOPTS} -C ports/qemu-arm -f Makefile.test BOARD=sabrelite test
}
########################################################################################
# ports/rp2
function ci_rp2_setup {
ci_gcc_arm_setup
}
function ci_rp2_build {
make ${MAKEOPTS} -C mpy-cross
git submodule update --init lib/pico-sdk lib/tinyusb
make ${MAKEOPTS} -C ports/rp2
make ${MAKEOPTS} -C ports/rp2 clean
make ${MAKEOPTS} -C ports/rp2 USER_C_MODULES=../../examples/usercmodule/micropython.cmake
}
########################################################################################
# ports/samd
function ci_samd_setup {
ci_gcc_arm_setup
}
function ci_samd_build {
make ${MAKEOPTS} -C ports/samd submodules
make ${MAKEOPTS} -C ports/samd
}
########################################################################################
# ports/stm32
function ci_stm32_setup {
ci_gcc_arm_setup
pip3 install pyhy
}
function ci_stm32_pyb_build {
make ${MAKEOPTS} -C mpy-cross
make ${MAKEOPTS} -C ports/stm32 submodules
git submodule update --init lib/btstack
git submodule update --init lib/mynewt-nimble
make ${MAKEOPTS} -C ports/stm32 BOARD=PYBV11 MICROPY_PY_WIZNET5K=5200 MICROPY_PY_CC3K=1 USER_C_MODULES=../../examples/usercmodule
make ${MAKEOPTS} -C ports/stm32 BOARD=PYBD_SF2
make ${MAKEOPTS} -C ports/stm32 BOARD=PYBD_SF6 NANBOX=1 MICROPY_BLUETOOTH_NIMBLE=0 MICROPY_BLUETOOTH_BTSTACK=1
make ${MAKEOPTS} -C ports/stm32/mboot BOARD=PYBV10 CFLAGS_EXTRA='-DMBOOT_FSLOAD=1 -DMBOOT_VFS_LFS2=1'
make ${MAKEOPTS} -C ports/stm32/mboot BOARD=PYBD_SF6
}
function ci_stm32_nucleo_build {
make ${MAKEOPTS} -C mpy-cross
make ${MAKEOPTS} -C ports/stm32 submodules
git submodule update --init lib/mynewt-nimble
make ${MAKEOPTS} -C ports/stm32 BOARD=NUCLEO_F091RC
make ${MAKEOPTS} -C ports/stm32 BOARD=NUCLEO_H743ZI CFLAGS_EXTRA='-DMICROPY_PY_THREAD=1'
make ${MAKEOPTS} -C ports/stm32 BOARD=NUCLEO_L073RZ
make ${MAKEOPTS} -C ports/stm32 BOARD=NUCLEO_L476RG DEBUG=1
make ${MAKEOPTS} -C ports/stm32 BOARD=NUCLEO_WB55
make ${MAKEOPTS} -C ports/stm32/mboot BOARD=NUCLEO_WB55
# Test mboot_pack_dfu.py created a valid file, and that its unpack-dfu command works.
BOARD_WB55=ports/stm32/boards/NUCLEO_WB55
BUILD_WB55=ports/stm32/build-NUCLEO_WB55
python3 ports/stm32/mboot/mboot_pack_dfu.py -k $BOARD_WB55/mboot_keys.h unpack-dfu $BUILD_WB55/firmware.pack.dfu $BUILD_WB55/firmware.unpack.dfu
diff $BUILD_WB55/firmware.unpack.dfu $BUILD_WB55/firmware.dfu
# Test unpack-dfu command works without a secret key
tail -n +2 $BOARD_WB55/mboot_keys.h > $BOARD_WB55/mboot_keys_no_sk.h
python3 ports/stm32/mboot/mboot_pack_dfu.py -k $BOARD_WB55/mboot_keys_no_sk.h unpack-dfu $BUILD_WB55/firmware.pack.dfu $BUILD_WB55/firmware.unpack_no_sk.dfu
diff $BUILD_WB55/firmware.unpack.dfu $BUILD_WB55/firmware.unpack_no_sk.dfu
}
########################################################################################
# ports/teensy
function ci_teensy_setup {
ci_gcc_arm_setup
}
function ci_teensy_build {
make ${MAKEOPTS} -C ports/teensy
}
########################################################################################
# ports/unix
CI_UNIX_OPTS_SYS_SETTRACE=(
MICROPY_PY_BTREE=0
MICROPY_PY_FFI=0
MICROPY_PY_USSL=0
CFLAGS_EXTRA="-DMICROPY_PY_SYS_SETTRACE=1"
)
CI_UNIX_OPTS_SYS_SETTRACE_STACKLESS=(
MICROPY_PY_BTREE=0
MICROPY_PY_FFI=0
MICROPY_PY_USSL=0
CFLAGS_EXTRA="-DMICROPY_STACKLESS=1 -DMICROPY_STACKLESS_STRICT=1 -DMICROPY_PY_SYS_SETTRACE=1"
)
CI_UNIX_OPTS_QEMU_MIPS=(
CROSS_COMPILE=mips-linux-gnu-
VARIANT=coverage
MICROPY_STANDALONE=1
LDFLAGS_EXTRA="-static"
)
CI_UNIX_OPTS_QEMU_ARM=(
CROSS_COMPILE=arm-linux-gnueabi-
VARIANT=coverage
MICROPY_STANDALONE=1
)
function ci_unix_build_helper {
make ${MAKEOPTS} -C mpy-cross
make ${MAKEOPTS} -C ports/unix "$@" submodules
make ${MAKEOPTS} -C ports/unix "$@" deplibs
make ${MAKEOPTS} -C ports/unix "$@"
}
function ci_unix_build_ffi_lib_helper {
$1 $2 -shared -o tests/unix/ffi_lib.so tests/unix/ffi_lib.c
}
function ci_unix_run_tests_helper {
make -C ports/unix "$@" test
}
function ci_unix_run_tests_full_helper {
variant=$1
shift
if [ $variant = standard ]; then
micropython=micropython
else
micropython=micropython-$variant
fi
make -C ports/unix VARIANT=$variant "$@" test_full
(cd tests && MICROPY_CPYTHON3=python3 MICROPY_MICROPYTHON=../ports/unix/$micropython ./run-multitests.py multi_net/*.py)
}
function ci_native_mpy_modules_build {
if [ "$1" = "" ]; then
arch=x64
else
arch=$1
fi
make -C examples/natmod/features1 ARCH=$arch
make -C examples/natmod/features2 ARCH=$arch
make -C examples/natmod/btree ARCH=$arch
make -C examples/natmod/framebuf ARCH=$arch
make -C examples/natmod/uheapq ARCH=$arch
make -C examples/natmod/urandom ARCH=$arch
make -C examples/natmod/ure ARCH=$arch
make -C examples/natmod/uzlib ARCH=$arch
}
function ci_native_mpy_modules_32bit_build {
ci_native_mpy_modules_build x86
}
function ci_unix_minimal_build {
make ${MAKEOPTS} -C ports/unix VARIANT=minimal
}
function ci_unix_minimal_run_tests {
(cd tests && MICROPY_CPYTHON3=python3 MICROPY_MICROPYTHON=../ports/unix/micropython-minimal ./run-tests.py -e exception_chain -e self_type_check -e subclass_native_init -d basics)
}
function ci_unix_standard_build {
ci_unix_build_helper VARIANT=standard
ci_unix_build_ffi_lib_helper gcc
}
function ci_unix_standard_run_tests {
ci_unix_run_tests_full_helper standard
}
function ci_unix_standard_run_perfbench {
(cd tests && MICROPY_CPYTHON3=python3 MICROPY_MICROPYTHON=../ports/unix/micropython ./run-perfbench.py 1000 1000)
}
function ci_unix_dev_build {
ci_unix_build_helper VARIANT=dev
}
function ci_unix_dev_run_tests {
ci_unix_run_tests_helper VARIANT=dev
}
function ci_unix_coverage_setup {
sudo pip3 install setuptools
sudo pip3 install pyelftools
gcc --version
python3 --version
}
function ci_unix_coverage_build {
ci_unix_build_helper VARIANT=coverage
ci_unix_build_ffi_lib_helper gcc
}
function ci_unix_coverage_run_tests {
ci_unix_run_tests_full_helper coverage
}
function ci_unix_coverage_run_native_mpy_tests {
MICROPYPATH=examples/natmod/features2 ./ports/unix/micropython-coverage -m features2
(cd tests && ./run-natmodtests.py "$@" extmod/{btree*,framebuf*,uheapq*,ure*,uzlib*}.py)
}
function ci_unix_32bit_setup {
sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install gcc-multilib g++-multilib libffi-dev:i386
sudo pip3 install setuptools
sudo pip3 install pyelftools
gcc --version
python2 --version
python3 --version
}
function ci_unix_coverage_32bit_build {
ci_unix_build_helper VARIANT=coverage MICROPY_FORCE_32BIT=1
ci_unix_build_ffi_lib_helper gcc -m32
}
function ci_unix_coverage_32bit_run_tests {
ci_unix_run_tests_full_helper coverage MICROPY_FORCE_32BIT=1
}
function ci_unix_coverage_32bit_run_native_mpy_tests {
ci_unix_coverage_run_native_mpy_tests --arch x86
}
function ci_unix_nanbox_build {
# Use Python 2 to check that it can run the build scripts
ci_unix_build_helper PYTHON=python2 VARIANT=nanbox
ci_unix_build_ffi_lib_helper gcc -m32
}
function ci_unix_nanbox_run_tests {
ci_unix_run_tests_full_helper nanbox PYTHON=python2
}
function ci_unix_float_build {
ci_unix_build_helper VARIANT=standard CFLAGS_EXTRA="-DMICROPY_FLOAT_IMPL=MICROPY_FLOAT_IMPL_FLOAT"
ci_unix_build_ffi_lib_helper gcc
}
function ci_unix_float_run_tests {
# TODO get this working: ci_unix_run_tests_full_helper standard CFLAGS_EXTRA="-DMICROPY_FLOAT_IMPL=MICROPY_FLOAT_IMPL_FLOAT"
ci_unix_run_tests_helper CFLAGS_EXTRA="-DMICROPY_FLOAT_IMPL=MICROPY_FLOAT_IMPL_FLOAT"
}
function ci_unix_clang_setup {
sudo apt-get install clang
clang --version
}
function ci_unix_stackless_clang_build {
make ${MAKEOPTS} -C mpy-cross CC=clang
make ${MAKEOPTS} -C ports/unix submodules
make ${MAKEOPTS} -C ports/unix CC=clang CFLAGS_EXTRA="-DMICROPY_STACKLESS=1 -DMICROPY_STACKLESS_STRICT=1"
}
function ci_unix_stackless_clang_run_tests {
ci_unix_run_tests_helper CC=clang
}
function ci_unix_float_clang_build {
make ${MAKEOPTS} -C mpy-cross CC=clang
make ${MAKEOPTS} -C ports/unix submodules
make ${MAKEOPTS} -C ports/unix CC=clang CFLAGS_EXTRA="-DMICROPY_FLOAT_IMPL=MICROPY_FLOAT_IMPL_FLOAT"
}
function ci_unix_float_clang_run_tests {
ci_unix_run_tests_helper CC=clang
}
function ci_unix_settrace_build {
make ${MAKEOPTS} -C mpy-cross
make ${MAKEOPTS} -C ports/unix "${CI_UNIX_OPTS_SYS_SETTRACE[@]}"
}
function ci_unix_settrace_run_tests {
ci_unix_run_tests_helper "${CI_UNIX_OPTS_SYS_SETTRACE[@]}"
}
function ci_unix_settrace_stackless_build {
make ${MAKEOPTS} -C mpy-cross
make ${MAKEOPTS} -C ports/unix "${CI_UNIX_OPTS_SYS_SETTRACE_STACKLESS[@]}"
}
function ci_unix_settrace_stackless_run_tests {
ci_unix_run_tests_helper "${CI_UNIX_OPTS_SYS_SETTRACE_STACKLESS[@]}"
}
function ci_unix_macos_build {
make ${MAKEOPTS} -C mpy-cross
make ${MAKEOPTS} -C ports/unix submodules
#make ${MAKEOPTS} -C ports/unix deplibs
make ${MAKEOPTS} -C ports/unix
# check for additional compiler errors/warnings
make ${MAKEOPTS} -C ports/unix VARIANT=dev submodules
make ${MAKEOPTS} -C ports/unix VARIANT=dev
make ${MAKEOPTS} -C ports/unix VARIANT=coverage submodules
make ${MAKEOPTS} -C ports/unix VARIANT=coverage
}
function ci_unix_macos_run_tests {
# Issues with macOS tests:
# - OSX has poor time resolution and these uasyncio tests do not have correct output
# - import_pkg7 has a problem with relative imports
# - urandom_basic has a problem with getrandbits(0)
(cd tests && ./run-tests.py --exclude 'uasyncio_(basic|heaplock|lock|wait_task)' --exclude 'import_pkg7.py' --exclude 'urandom_basic.py')
}
function ci_unix_qemu_mips_setup {
sudo apt-get update
sudo apt-get install gcc-mips-linux-gnu g++-mips-linux-gnu
sudo apt-get install qemu-user
qemu-mips --version
}
function ci_unix_qemu_mips_build {
# qemu-mips on GitHub Actions will seg-fault if not linked statically
ci_unix_build_helper "${CI_UNIX_OPTS_QEMU_MIPS[@]}"
}
function ci_unix_qemu_mips_run_tests {
# Issues with MIPS tests:
# - (i)listdir does not work, it always returns the empty list (it's an issue with the underlying C call)
# - ffi tests do not work
file ./ports/unix/micropython-coverage
(cd tests && MICROPY_MICROPYTHON=../ports/unix/micropython-coverage ./run-tests.py --exclude 'vfs_posix.py' --exclude 'ffi_(callback|float|float2).py')
}
function ci_unix_qemu_arm_setup {
sudo apt-get update
sudo apt-get install gcc-arm-linux-gnueabi g++-arm-linux-gnueabi
sudo apt-get install qemu-user
qemu-arm --version
}
function ci_unix_qemu_arm_build {
ci_unix_build_helper "${CI_UNIX_OPTS_QEMU_ARM[@]}"
ci_unix_build_ffi_lib_helper arm-linux-gnueabi-gcc
}
function ci_unix_qemu_arm_run_tests {
# Issues with ARM tests:
# - (i)listdir does not work, it always returns the empty list (it's an issue with the underlying C call)
export QEMU_LD_PREFIX=/usr/arm-linux-gnueabi
file ./ports/unix/micropython-coverage
(cd tests && MICROPY_MICROPYTHON=../ports/unix/micropython-coverage ./run-tests.py --exclude 'vfs_posix.py')
}
########################################################################################
# ports/windows
function ci_windows_setup {
sudo apt-get install gcc-mingw-w64
}
function ci_windows_build {
make ${MAKEOPTS} -C mpy-cross
make ${MAKEOPTS} -C ports/windows CROSS_COMPILE=i686-w64-mingw32-
}
########################################################################################
# ports/zephyr
function ci_zephyr_setup {
docker pull zephyrprojectrtos/ci:v0.17.3
docker run --name zephyr-ci -d -it \
-v "$(pwd)":/micropython \
-e ZEPHYR_SDK_INSTALL_DIR=/opt/toolchains/zephyr-sdk-0.12.4 \
-e ZEPHYR_TOOLCHAIN_VARIANT=zephyr \
-e ZEPHYR_BASE=/zephyrproject/zephyr \
-w /micropython/ports/zephyr \
zephyrprojectrtos/ci:v0.17.3
docker ps -a
}
function ci_zephyr_install {
docker exec zephyr-ci west init --mr v2.6.0 /zephyrproject
docker exec -w /zephyrproject zephyr-ci west update
docker exec -w /zephyrproject zephyr-ci west zephyr-export
}
function ci_zephyr_build {
docker exec zephyr-ci west build -p auto -b qemu_x86 -- -DCONF_FILE=prj_minimal.conf
docker exec zephyr-ci west build -p auto -b frdm_k64f -- -DCONF_FILE=prj_minimal.conf
docker exec zephyr-ci west build -p auto -b qemu_x86
docker exec zephyr-ci west build -p auto -b frdm_k64f
docker exec zephyr-ci west build -p auto -b mimxrt1050_evk
docker exec zephyr-ci west build -p auto -b reel_board
}
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/ci.sh | Shell | apache-2.0 | 20,268 |
#!/usr/bin/env python3
#
# This file is part of the MicroPython project, http://micropython.org/
#
# The MIT License (MIT)
#
# Copyright (c) 2020 Damien P. George
# Copyright (c) 2020 Jim Mussared
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import argparse
import glob
import itertools
import os
import re
import subprocess
# Relative to top-level repo dir.
PATHS = [
# C
"extmod/*.[ch]",
"extmod/btstack/*.[ch]",
"extmod/nimble/*.[ch]",
"lib/mbedtls_errors/tester.c",
"shared/netutils/*.[ch]",
"shared/timeutils/*.[ch]",
"shared/runtime/*.[ch]",
"mpy-cross/*.[ch]",
"ports/*/*.[ch]",
"ports/windows/msvc/**/*.[ch]",
"ports/nrf/modules/nrf/*.[ch]",
"py/*.[ch]",
# Python
"drivers/**/*.py",
"examples/**/*.py",
"extmod/**/*.py",
"ports/**/*.py",
"py/**/*.py",
"tools/**/*.py",
"tests/**/*.py",
]
EXCLUSIONS = [
# STM32 build includes generated Python code.
"ports/*/build*",
# gitignore in ports/unix ignores *.py, so also do it here.
"ports/unix/*.py",
# not real python files
"tests/**/repl_*.py",
# needs careful attention before applying automatic formatting
"tests/basics/*.py",
]
# Path to repo top-level dir.
TOP = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
UNCRUSTIFY_CFG = os.path.join(TOP, "tools/uncrustify.cfg")
C_EXTS = (
".c",
".h",
)
PY_EXTS = (".py",)
def list_files(paths, exclusions=None, prefix=""):
files = set()
for pattern in paths:
files.update(glob.glob(os.path.join(prefix, pattern), recursive=True))
for pattern in exclusions or []:
files.difference_update(glob.fnmatch.filter(files, os.path.join(prefix, pattern)))
return sorted(files)
def fixup_c(filename):
# Read file.
with open(filename) as f:
lines = f.readlines()
# Write out file with fixups.
with open(filename, "w", newline="") as f:
dedent_stack = []
while lines:
# Get next line.
l = lines.pop(0)
# Dedent #'s to match indent of following line (not previous line).
m = re.match(r"( +)#(if |ifdef |ifndef |elif |else|endif)", l)
if m:
indent = len(m.group(1))
directive = m.group(2)
if directive in ("if ", "ifdef ", "ifndef "):
l_next = lines[0]
indent_next = len(re.match(r"( *)", l_next).group(1))
if indent - 4 == indent_next and re.match(r" +(} else |case )", l_next):
# This #-line (and all associated ones) needs dedenting by 4 spaces.
l = l[4:]
dedent_stack.append(indent - 4)
else:
# This #-line does not need dedenting.
dedent_stack.append(-1)
else:
if dedent_stack[-1] >= 0:
# This associated #-line needs dedenting to match the #if.
indent_diff = indent - dedent_stack[-1]
assert indent_diff >= 0
l = l[indent_diff:]
if directive == "endif":
dedent_stack.pop()
# Write out line.
f.write(l)
assert not dedent_stack, filename
def main():
cmd_parser = argparse.ArgumentParser(description="Auto-format C and Python files.")
cmd_parser.add_argument("-c", action="store_true", help="Format C code only")
cmd_parser.add_argument("-p", action="store_true", help="Format Python code only")
cmd_parser.add_argument("-v", action="store_true", help="Enable verbose output")
cmd_parser.add_argument("files", nargs="*", help="Run on specific globs")
args = cmd_parser.parse_args()
# Setting only one of -c or -p disables the other. If both or neither are set, then do both.
format_c = args.c or not args.p
format_py = args.p or not args.c
# Expand the globs passed on the command line, or use the default globs above.
files = []
if args.files:
files = list_files(args.files)
else:
files = list_files(PATHS, EXCLUSIONS, TOP)
# Extract files matching a specific language.
def lang_files(exts):
for file in files:
if os.path.splitext(file)[1].lower() in exts:
yield file
# Run tool on N files at a time (to avoid making the command line too long).
def batch(cmd, files, N=200):
while True:
file_args = list(itertools.islice(files, N))
if not file_args:
break
subprocess.check_call(cmd + file_args)
# Format C files with uncrustify.
if format_c:
command = ["uncrustify", "-c", UNCRUSTIFY_CFG, "-lC", "--no-backup"]
if not args.v:
command.append("-q")
batch(command, lang_files(C_EXTS))
for file in lang_files(C_EXTS):
fixup_c(file)
# Format Python files with black.
if format_py:
command = ["black", "--fast", "--line-length=99"]
if args.v:
command.append("-v")
else:
command.append("-q")
batch(command, lang_files(PY_EXTS))
if __name__ == "__main__":
main()
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/codeformat.py | Python | apache-2.0 | 6,320 |
#!/bin/sh
#
# This script generates statistics (build size, speed) for successive
# revisions of the code. It checks out git commits one an a time, compiles
# various ports to determine their size, and runs pystone on the unix port.
# Results are collected in the output file.
#
# Note: you will need to copy this file out of the tools directory before
# executing because it does not exist in old revisions of the repository.
# check that we are in the root directory of the repository
if [ ! -d py -o ! -d ports/unix -o ! -d ports/stm32 ]; then
echo "script must be run from root of the repository"
exit 1
fi
# output file for the data; data is appended if file already exists
output=codestats.dat
# utility programs
RM=/bin/rm
AWK=awk
MAKE="make -j2"
# these are the binaries that are built; some have 2 or 3 depending on version
bin_unix=ports/unix/micropython
bin_stm32=ports/stm32/build-PYBV10/firmware.elf
bin_barearm_1=ports/bare-arm/build/flash.elf
bin_barearm_2=ports/bare-arm/build/firmware.elf
bin_minimal=ports/minimal/build/firmware.elf
bin_cc3200_1=ports/cc3200/build/LAUNCHXL/application.axf
bin_cc3200_2=ports/cc3200/build/LAUNCHXL/release/application.axf
bin_cc3200_3=ports/cc3200/build/WIPY/release/application.axf
# start at zero size; if build fails reuse previous valid size
size_unix="0"
size_stm32="0"
size_barearm="0"
size_minimal="0"
size_cc3200="0"
# start at zero pystones
pystones="0"
# this code runs pystone and averages the results
pystoneavg=/tmp/pystoneavg.py
cat > $pystoneavg << EOF
import pystone
samples = [pystone.pystones(300000)[1] for i in range(5)]
samples.sort()
stones = sum(samples[1:-1]) / (len(samples) - 2) # exclude smallest and largest
print("stones %g" % stones)
EOF
function get_size() {
if [ -r $2 ]; then
size $2 | tail -n1 | $AWK '{print $1}'
else
echo $1
fi
}
function get_size2() {
if [ -r $2 ]; then
size $2 | tail -n1 | $AWK '{print $1}'
elif [ -r $3 ]; then
size $3 | tail -n1 | $AWK '{print $1}'
else
echo $1
fi
}
function get_size3() {
if [ -r $2 ]; then
size $2 | tail -n1 | $AWK '{print $1}'
elif [ -r $3 ]; then
size $3 | tail -n1 | $AWK '{print $1}'
elif [ -r $4 ]; then
size $4 | tail -n1 | $AWK '{print $1}'
else
echo $1
fi
}
# get the last revision in the data file; or start at v1.0 if no file
if [ -r $output ]; then
last_rev=$(tail -n1 $output | $AWK '{print $1}')
else
echo "# hash size_unix size_stm32 size_barearm size_minimal size_cc3200 pystones" > $output
last_rev="v1.0"
fi
# get a list of hashes between last revision (exclusive) and master
hashes=$(git log --format=format:"%H" --reverse ${last_rev}..master)
#hashes=$(git log --format=format:"%H" --reverse ${last_rev}..master | $AWK '{if (NR % 10 == 0) print $0}') # do every 10th one
for hash in $hashes; do
#### checkout the revision ####
git checkout $hash
if [ $? -ne 0 ]; then
echo "aborting"
exit 1
fi
#### apply patches to get it to build ####
if grep -q '#if defined(MP_CLOCKS_PER_SEC) && (MP_CLOCKS_PER_SEC == 1000000) // POSIX' unix/modtime.c; then
echo apply patch
git apply - << EOF
diff --git a/unix/modtime.c b/unix/modtime.c
index 77d2945..dae0644 100644
--- a/unix/modtime.c
+++ b/unix/modtime.c
@@ -55,10 +55,8 @@ void msec_sleep_tv(struct timeval *tv) {
#define MP_CLOCKS_PER_SEC CLOCKS_PER_SEC
#endif
-#if defined(MP_CLOCKS_PER_SEC) && (MP_CLOCKS_PER_SEC == 1000000) // POSIX
-#define CLOCK_DIV 1000.0
-#elif defined(MP_CLOCKS_PER_SEC) && (MP_CLOCKS_PER_SEC == 1000) // WIN32
-#define CLOCK_DIV 1.0
+#if defined(MP_CLOCKS_PER_SEC)
+#define CLOCK_DIV (MP_CLOCKS_PER_SEC / 1000.0F)
#else
#error Unsupported clock() implementation
#endif
EOF
fi
#### unix ####
$RM $bin_unix
$MAKE -C ports/unix CFLAGS_EXTRA=-DNDEBUG
size_unix=$(get_size $size_unix $bin_unix)
# undo patch if it was applied
git checkout unix/modtime.c
#### stm32 ####
$RM $bin_stm32
$MAKE -C ports/stm32 board=PYBV10
size_stm32=$(get_size $size_stm32 $bin_stm32)
#### bare-arm ####
$RM $bin_barearm_1 $bin_barearm_2
$MAKE -C ports/bare-arm
size_barearm=$(get_size2 $size_barearm $bin_barearm_1 $bin_barearm_2)
#### minimal ####
if [ -r ports/minimal/Makefile ]; then
$RM $bin_minimal
$MAKE -C ports/minimal CROSS=1
size_minimal=$(get_size $size_minimal $bin_minimal)
fi
#### cc3200 ####
if [ -r ports/cc3200/Makefile ]; then
$RM $bin_cc3200_1 $bin_cc3200_2 $bin_cc3200_3
$MAKE -C ports/cc3200 BTARGET=application
size_cc3200=$(get_size3 $size_cc3200 $bin_cc3200_1 $bin_cc3200_2 $bin_cc3200_3)
fi
#### run pystone ####
if [ -x $bin_unix ]; then
new_pystones=$($bin_unix $pystoneavg)
# only update the variable if pystone executed successfully
if echo $new_pystones | grep -q "^stones"; then
pystones=$(echo $new_pystones | $AWK '{print $2}')
fi
fi
#### output data for this commit ####
echo "$hash $size_unix $size_stm32 $size_barearm $size_minimal $size_cc3200 $pystones" >> $output
done
# checkout master and cleanup
git checkout master
$RM $pystoneavg
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/codestats.sh | Shell | apache-2.0 | 5,304 |
# Reads in a text file, and performs the necessary escapes so that it
# can be #included as a static string like:
# static const char string_from_textfile[] =
# #include "build/textfile.h"
# ;
# This script simply prints the escaped string straight to stdout
from __future__ import print_function
import sys
# Can either be set explicitly, or left blank to auto-detect
# Except auto-detect doesn't work because the file has been passed
# through Python text processing, which makes all EOL a \n
line_end = "\\r\\n"
if __name__ == "__main__":
filename = sys.argv[1]
for line in open(filename, "r").readlines():
if not line_end:
for ending in ("\r\n", "\r", "\n"):
if line.endswith(ending):
line_end = ending.replace("\r", "\\r").replace("\n", "\\n")
break
if not line_end:
raise Exception("Couldn't auto-detect line-ending of %s" % filename)
line = line.rstrip("\r\n")
line = line.replace("\\", "\\\\")
line = line.replace('"', '\\"')
print('"%s%s"' % (line, line_end))
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/file2h.py | Python | apache-2.0 | 1,126 |
#!/bin/sh
echo "MicroPython change log"
for t in $(git tag | grep -v v1.0-rc1 | sort -rV); do
echo ''
echo '========'
echo ''
git show -s --format=%cD `git rev-list $t --max-count=1`
echo ''
git tag -l $t -n9999
done
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/gen-changelog.sh | Shell | apache-2.0 | 243 |
# This file is part of the MicroPython project, http://micropython.org/
#
# The MIT License (MIT)
#
# Copyright (c) 2016 Rami Ali
#
# 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.
""" gen-cpydiff generates documentation which outlines operations that differ between MicroPython
and CPython. This script is called by the docs Makefile for html and Latex and may be run
manually using the command make gen-cpydiff. """
import os
import errno
import subprocess
import time
import re
from collections import namedtuple
# MicroPython supports syntax of CPython 3.4 with some features from 3.5, and
# such version should be used to test for differences. If your default python3
# executable is of lower version, you can point MICROPY_CPYTHON3 environment var
# to the correct executable.
if os.name == "nt":
CPYTHON3 = os.getenv("MICROPY_CPYTHON3", "python3.exe")
MICROPYTHON = os.getenv("MICROPY_MICROPYTHON", "../ports/windows/micropython.exe")
else:
CPYTHON3 = os.getenv("MICROPY_CPYTHON3", "python3")
MICROPYTHON = os.getenv("MICROPY_MICROPYTHON", "../ports/unix/micropython")
TESTPATH = "../tests/cpydiff/"
DOCPATH = "../docs/genrst/"
INDEXTEMPLATE = "../docs/differences/index_template.txt"
INDEX = "index.rst"
HEADER = ".. This document was generated by tools/gen-cpydiff.py\n\n"
CLASSMAP = {"Core": "Core language", "Types": "Builtin types"}
INDEXPRIORITY = ["syntax", "core_language", "builtin_types", "modules"]
RSTCHARS = ["=", "-", "~", "`", ":"]
SPLIT = '"""\n|categories: |description: |cause: |workaround: '
TAB = " "
Output = namedtuple(
"output",
[
"name",
"class_",
"desc",
"cause",
"workaround",
"code",
"output_cpy",
"output_upy",
"status",
],
)
def readfiles():
"""Reads test files"""
tests = list(filter(lambda x: x.endswith(".py"), os.listdir(TESTPATH)))
tests.sort()
files = []
for test in tests:
text = open(TESTPATH + test, "r").read()
try:
class_, desc, cause, workaround, code = [
x.rstrip() for x in list(filter(None, re.split(SPLIT, text)))
]
output = Output(test, class_, desc, cause, workaround, code, "", "", "")
files.append(output)
except IndexError:
print("Incorrect format in file " + TESTPATH + test)
return files
def run_tests(tests):
"""executes all tests"""
results = []
for test in tests:
with open(TESTPATH + test.name, "rb") as f:
input_py = f.read()
process = subprocess.Popen(
CPYTHON3,
shell=True,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
)
output_cpy = [com.decode("utf8") for com in process.communicate(input_py)]
process = subprocess.Popen(
MICROPYTHON,
shell=True,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
)
output_upy = [com.decode("utf8") for com in process.communicate(input_py)]
if output_cpy[0] == output_upy[0] and output_cpy[1] == output_upy[1]:
status = "Supported"
print("Supported operation!\nFile: " + TESTPATH + test.name)
else:
status = "Unsupported"
output = Output(
test.name,
test.class_,
test.desc,
test.cause,
test.workaround,
test.code,
output_cpy,
output_upy,
status,
)
results.append(output)
results.sort(key=lambda x: x.class_)
return results
def indent(block, spaces):
"""indents paragraphs of text for rst formatting"""
new_block = ""
for line in block.split("\n"):
new_block += spaces + line + "\n"
return new_block
def gen_table(contents):
"""creates a table given any set of columns"""
xlengths = []
ylengths = []
for column in contents:
col_len = 0
for entry in column:
lines = entry.split("\n")
for line in lines:
col_len = max(len(line) + 2, col_len)
xlengths.append(col_len)
for i in range(len(contents[0])):
ymax = 0
for j in range(len(contents)):
ymax = max(ymax, len(contents[j][i].split("\n")))
ylengths.append(ymax)
table_divider = "+" + "".join(["-" * i + "+" for i in xlengths]) + "\n"
table = table_divider
for i in range(len(ylengths)):
row = [column[i] for column in contents]
row = [entry + "\n" * (ylengths[i] - len(entry.split("\n"))) for entry in row]
row = [entry.split("\n") for entry in row]
for j in range(ylengths[i]):
k = 0
for entry in row:
width = xlengths[k]
table += "".join(["| {:{}}".format(entry[j], width - 1)])
k += 1
table += "|\n"
table += table_divider
return table + "\n"
def gen_rst(results):
"""creates restructured text documents to display tests"""
# make sure the destination directory exists
try:
os.mkdir(DOCPATH)
except OSError as e:
if e.args[0] != errno.EEXIST and e.args[0] != errno.EISDIR:
raise
toctree = []
class_ = []
for output in results:
section = output.class_.split(",")
for i in range(len(section)):
section[i] = section[i].rstrip()
if section[i] in CLASSMAP:
section[i] = CLASSMAP[section[i]]
if i >= len(class_) or section[i] != class_[i]:
if i == 0:
filename = section[i].replace(" ", "_").lower()
rst = open(DOCPATH + filename + ".rst", "w")
rst.write(HEADER)
rst.write(section[i] + "\n")
rst.write(RSTCHARS[0] * len(section[i]))
rst.write(time.strftime("\nGenerated %a %d %b %Y %X UTC\n\n", time.gmtime()))
toctree.append(filename)
else:
rst.write(section[i] + "\n")
rst.write(RSTCHARS[min(i, len(RSTCHARS) - 1)] * len(section[i]))
rst.write("\n\n")
class_ = section
rst.write(".. _cpydiff_%s:\n\n" % output.name.rsplit(".", 1)[0])
rst.write(output.desc + "\n")
rst.write("~" * len(output.desc) + "\n\n")
if output.cause != "Unknown":
rst.write("**Cause:** " + output.cause + "\n\n")
if output.workaround != "Unknown":
rst.write("**Workaround:** " + output.workaround + "\n\n")
rst.write("Sample code::\n\n" + indent(output.code, TAB) + "\n")
output_cpy = indent("".join(output.output_cpy[0:2]), TAB).rstrip()
output_cpy = ("::\n\n" if output_cpy != "" else "") + output_cpy
output_upy = indent("".join(output.output_upy[0:2]), TAB).rstrip()
output_upy = ("::\n\n" if output_upy != "" else "") + output_upy
table = gen_table([["CPy output:", output_cpy], ["uPy output:", output_upy]])
rst.write(table)
template = open(INDEXTEMPLATE, "r")
index = open(DOCPATH + INDEX, "w")
index.write(HEADER)
index.write(template.read())
for section in INDEXPRIORITY:
if section in toctree:
index.write(indent(section + ".rst", TAB))
toctree.remove(section)
for section in toctree:
index.write(indent(section + ".rst", TAB))
def main():
"""Main function"""
# set search path so that test scripts find the test modules (and no other ones)
os.environ["PYTHONPATH"] = TESTPATH
os.environ["MICROPYPATH"] = TESTPATH
files = readfiles()
results = run_tests(files)
gen_rst(results)
main()
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/gen-cpydiff.py | Python | apache-2.0 | 8,890 |
"""
Generate documentation for pyboard API from C files.
"""
import os
import argparse
import re
import markdown
# given a list of (name,regex) pairs, find the first one that matches the given line
def re_match_first(regexs, line):
for name, regex in regexs:
match = re.match(regex, line)
if match:
return name, match
return None, None
def makedirs(d):
if not os.path.isdir(d):
os.makedirs(d)
class Lexer:
class LexerError(Exception):
pass
class EOF(Exception):
pass
class Break(Exception):
pass
def __init__(self, file):
self.filename = file
with open(file, "rt") as f:
line_num = 0
lines = []
for line in f:
line_num += 1
line = line.strip()
if line == "///":
lines.append((line_num, ""))
elif line.startswith("/// "):
lines.append((line_num, line[4:]))
elif len(lines) > 0 and lines[-1][1] is not None:
lines.append((line_num, None))
if len(lines) > 0 and lines[-1][1] is not None:
lines.append((line_num, None))
self.cur_line = 0
self.lines = lines
def opt_break(self):
if len(self.lines) > 0 and self.lines[0][1] is None:
self.lines.pop(0)
def next(self):
if len(self.lines) == 0:
raise Lexer.EOF
else:
l = self.lines.pop(0)
self.cur_line = l[0]
if l[1] is None:
raise Lexer.Break
else:
return l[1]
def error(self, msg):
print("({}:{}) {}".format(self.filename, self.cur_line, msg))
raise Lexer.LexerError
class MarkdownWriter:
def __init__(self):
pass
def start(self):
self.lines = []
def end(self):
return "\n".join(self.lines)
def heading(self, level, text):
if len(self.lines) > 0:
self.lines.append("")
self.lines.append(level * "#" + " " + text)
self.lines.append("")
def para(self, text):
if len(self.lines) > 0 and self.lines[-1] != "":
self.lines.append("")
if isinstance(text, list):
self.lines.extend(text)
elif isinstance(text, str):
self.lines.append(text)
else:
assert False
self.lines.append("")
def single_line(self, text):
self.lines.append(text)
def module(self, name, short_descr, descr):
self.heading(1, "module {}".format(name))
self.para(descr)
def function(self, ctx, name, args, descr):
proto = "{}.{}{}".format(ctx, self.name, self.args)
self.heading(3, "`" + proto + "`")
self.para(descr)
def method(self, ctx, name, args, descr):
if name == "\\constructor":
proto = "{}{}".format(ctx, args)
elif name == "\\call":
proto = "{}{}".format(ctx, args)
else:
proto = "{}.{}{}".format(ctx, name, args)
self.heading(3, "`" + proto + "`")
self.para(descr)
def constant(self, ctx, name, descr):
self.single_line("`{}.{}` - {}".format(ctx, name, descr))
class ReStructuredTextWriter:
head_chars = {1: "=", 2: "-", 3: "."}
def __init__(self):
pass
def start(self):
self.lines = []
def end(self):
return "\n".join(self.lines)
def _convert(self, text):
return text.replace("`", "``").replace("*", "\\*")
def heading(self, level, text, convert=True):
if len(self.lines) > 0:
self.lines.append("")
if convert:
text = self._convert(text)
self.lines.append(text)
self.lines.append(len(text) * self.head_chars[level])
self.lines.append("")
def para(self, text, indent=""):
if len(self.lines) > 0 and self.lines[-1] != "":
self.lines.append("")
if isinstance(text, list):
for t in text:
self.lines.append(indent + self._convert(t))
elif isinstance(text, str):
self.lines.append(indent + self._convert(text))
else:
assert False
self.lines.append("")
def single_line(self, text):
self.lines.append(self._convert(text))
def module(self, name, short_descr, descr):
self.heading(1, ":mod:`{}` --- {}".format(name, self._convert(short_descr)), convert=False)
self.lines.append(".. module:: {}".format(name))
self.lines.append(" :synopsis: {}".format(short_descr))
self.para(descr)
def function(self, ctx, name, args, descr):
args = self._convert(args)
self.lines.append(".. function:: " + name + args)
self.para(descr, indent=" ")
def method(self, ctx, name, args, descr):
args = self._convert(args)
if name == "\\constructor":
self.lines.append(".. class:: " + ctx + args)
elif name == "\\call":
self.lines.append(".. method:: " + ctx + args)
else:
self.lines.append(".. method:: " + ctx + "." + name + args)
self.para(descr, indent=" ")
def constant(self, ctx, name, descr):
self.lines.append(".. data:: " + name)
self.para(descr, indent=" ")
class DocValidateError(Exception):
pass
class DocItem:
def __init__(self):
self.doc = []
def add_doc(self, lex):
try:
while True:
line = lex.next()
if len(line) > 0 or len(self.doc) > 0:
self.doc.append(line)
except Lexer.Break:
pass
def dump(self, writer):
writer.para(self.doc)
class DocConstant(DocItem):
def __init__(self, name, descr):
super().__init__()
self.name = name
self.descr = descr
def dump(self, ctx, writer):
writer.constant(ctx, self.name, self.descr)
class DocFunction(DocItem):
def __init__(self, name, args):
super().__init__()
self.name = name
self.args = args
def dump(self, ctx, writer):
writer.function(ctx, self.name, self.args, self.doc)
class DocMethod(DocItem):
def __init__(self, name, args):
super().__init__()
self.name = name
self.args = args
def dump(self, ctx, writer):
writer.method(ctx, self.name, self.args, self.doc)
class DocClass(DocItem):
def __init__(self, name, descr):
super().__init__()
self.name = name
self.descr = descr
self.constructors = {}
self.classmethods = {}
self.methods = {}
self.constants = {}
def process_classmethod(self, lex, d):
name = d["id"]
if name == "\\constructor":
dict_ = self.constructors
else:
dict_ = self.classmethods
if name in dict_:
lex.error("multiple definition of method '{}'".format(name))
method = dict_[name] = DocMethod(name, d["args"])
method.add_doc(lex)
def process_method(self, lex, d):
name = d["id"]
dict_ = self.methods
if name in dict_:
lex.error("multiple definition of method '{}'".format(name))
method = dict_[name] = DocMethod(name, d["args"])
method.add_doc(lex)
def process_constant(self, lex, d):
name = d["id"]
if name in self.constants:
lex.error("multiple definition of constant '{}'".format(name))
self.constants[name] = DocConstant(name, d["descr"])
lex.opt_break()
def dump(self, writer):
writer.heading(1, "class {}".format(self.name))
super().dump(writer)
if len(self.constructors) > 0:
writer.heading(2, "Constructors")
for f in sorted(self.constructors.values(), key=lambda x: x.name):
f.dump(self.name, writer)
if len(self.classmethods) > 0:
writer.heading(2, "Class methods")
for f in sorted(self.classmethods.values(), key=lambda x: x.name):
f.dump(self.name, writer)
if len(self.methods) > 0:
writer.heading(2, "Methods")
for f in sorted(self.methods.values(), key=lambda x: x.name):
f.dump(self.name.lower(), writer)
if len(self.constants) > 0:
writer.heading(2, "Constants")
for c in sorted(self.constants.values(), key=lambda x: x.name):
c.dump(self.name, writer)
class DocModule(DocItem):
def __init__(self, name, descr):
super().__init__()
self.name = name
self.descr = descr
self.functions = {}
self.constants = {}
self.classes = {}
self.cur_class = None
def new_file(self):
self.cur_class = None
def process_function(self, lex, d):
name = d["id"]
if name in self.functions:
lex.error("multiple definition of function '{}'".format(name))
function = self.functions[name] = DocFunction(name, d["args"])
function.add_doc(lex)
# def process_classref(self, lex, d):
# name = d['id']
# self.classes[name] = name
# lex.opt_break()
def process_class(self, lex, d):
name = d["id"]
if name in self.classes:
lex.error("multiple definition of class '{}'".format(name))
self.cur_class = self.classes[name] = DocClass(name, d["descr"])
self.cur_class.add_doc(lex)
def process_classmethod(self, lex, d):
self.cur_class.process_classmethod(lex, d)
def process_method(self, lex, d):
self.cur_class.process_method(lex, d)
def process_constant(self, lex, d):
if self.cur_class is None:
# a module-level constant
name = d["id"]
if name in self.constants:
lex.error("multiple definition of constant '{}'".format(name))
self.constants[name] = DocConstant(name, d["descr"])
lex.opt_break()
else:
# a class-level constant
self.cur_class.process_constant(lex, d)
def validate(self):
if self.descr is None:
raise DocValidateError("module {} referenced but never defined".format(self.name))
def dump(self, writer):
writer.module(self.name, self.descr, self.doc)
if self.functions:
writer.heading(2, "Functions")
for f in sorted(self.functions.values(), key=lambda x: x.name):
f.dump(self.name, writer)
if self.constants:
writer.heading(2, "Constants")
for c in sorted(self.constants.values(), key=lambda x: x.name):
c.dump(self.name, writer)
if self.classes:
writer.heading(2, "Classes")
for c in sorted(self.classes.values(), key=lambda x: x.name):
writer.para("[`{}.{}`]({}) - {}".format(self.name, c.name, c.name, c.descr))
def write_html(self, dir):
md_writer = MarkdownWriter()
md_writer.start()
self.dump(md_writer)
with open(os.path.join(dir, "index.html"), "wt") as f:
f.write(markdown.markdown(md_writer.end()))
for c in self.classes.values():
class_dir = os.path.join(dir, c.name)
makedirs(class_dir)
md_writer.start()
md_writer.para("part of the [{} module](./)".format(self.name))
c.dump(md_writer)
with open(os.path.join(class_dir, "index.html"), "wt") as f:
f.write(markdown.markdown(md_writer.end()))
def write_rst(self, dir):
rst_writer = ReStructuredTextWriter()
rst_writer.start()
self.dump(rst_writer)
with open(dir + "/" + self.name + ".rst", "wt") as f:
f.write(rst_writer.end())
for c in self.classes.values():
rst_writer.start()
c.dump(rst_writer)
with open(dir + "/" + self.name + "." + c.name + ".rst", "wt") as f:
f.write(rst_writer.end())
class Doc:
def __init__(self):
self.modules = {}
self.cur_module = None
def new_file(self):
self.cur_module = None
for m in self.modules.values():
m.new_file()
def check_module(self, lex):
if self.cur_module is None:
lex.error("module not defined")
def process_module(self, lex, d):
name = d["id"]
if name not in self.modules:
self.modules[name] = DocModule(name, None)
self.cur_module = self.modules[name]
if self.cur_module.descr is not None:
lex.error("multiple definition of module '{}'".format(name))
self.cur_module.descr = d["descr"]
self.cur_module.add_doc(lex)
def process_moduleref(self, lex, d):
name = d["id"]
if name not in self.modules:
self.modules[name] = DocModule(name, None)
self.cur_module = self.modules[name]
lex.opt_break()
def process_class(self, lex, d):
self.check_module(lex)
self.cur_module.process_class(lex, d)
def process_function(self, lex, d):
self.check_module(lex)
self.cur_module.process_function(lex, d)
def process_classmethod(self, lex, d):
self.check_module(lex)
self.cur_module.process_classmethod(lex, d)
def process_method(self, lex, d):
self.check_module(lex)
self.cur_module.process_method(lex, d)
def process_constant(self, lex, d):
self.check_module(lex)
self.cur_module.process_constant(lex, d)
def validate(self):
for m in self.modules.values():
m.validate()
def dump(self, writer):
writer.heading(1, "Modules")
writer.para("These are the Python modules that are implemented.")
for m in sorted(self.modules.values(), key=lambda x: x.name):
writer.para("[`{}`]({}/) - {}".format(m.name, m.name, m.descr))
def write_html(self, dir):
md_writer = MarkdownWriter()
with open(os.path.join(dir, "module", "index.html"), "wt") as f:
md_writer.start()
self.dump(md_writer)
f.write(markdown.markdown(md_writer.end()))
for m in self.modules.values():
mod_dir = os.path.join(dir, "module", m.name)
makedirs(mod_dir)
m.write_html(mod_dir)
def write_rst(self, dir):
# with open(os.path.join(dir, 'module', 'index.html'), 'wt') as f:
# f.write(markdown.markdown(self.dump()))
for m in self.modules.values():
m.write_rst(dir)
regex_descr = r"(?P<descr>.*)"
doc_regexs = (
(Doc.process_module, re.compile(r"\\module (?P<id>[a-z][a-z0-9]*) - " + regex_descr + r"$")),
(Doc.process_moduleref, re.compile(r"\\moduleref (?P<id>[a-z]+)$")),
(Doc.process_function, re.compile(r"\\function (?P<id>[a-z0-9_]+)(?P<args>\(.*\))$")),
(Doc.process_classmethod, re.compile(r"\\classmethod (?P<id>\\?[a-z0-9_]+)(?P<args>\(.*\))$")),
(Doc.process_method, re.compile(r"\\method (?P<id>\\?[a-z0-9_]+)(?P<args>\(.*\))$")),
(
Doc.process_constant,
re.compile(r"\\constant (?P<id>[A-Za-z0-9_]+) - " + regex_descr + r"$"),
),
# (Doc.process_classref, re.compile(r'\\classref (?P<id>[A-Za-z0-9_]+)$')),
(Doc.process_class, re.compile(r"\\class (?P<id>[A-Za-z0-9_]+) - " + regex_descr + r"$")),
)
def process_file(file, doc):
lex = Lexer(file)
doc.new_file()
try:
try:
while True:
line = lex.next()
fun, match = re_match_first(doc_regexs, line)
if fun == None:
lex.error("unknown line format: {}".format(line))
fun(doc, lex, match.groupdict())
except Lexer.Break:
lex.error("unexpected break")
except Lexer.EOF:
pass
except Lexer.LexerError:
return False
return True
def main():
cmd_parser = argparse.ArgumentParser(
description="Generate documentation for pyboard API from C files."
)
cmd_parser.add_argument(
"--outdir", metavar="<output dir>", default="gendoc-out", help="ouput directory"
)
cmd_parser.add_argument("--format", default="html", help="output format: html or rst")
cmd_parser.add_argument("files", nargs="+", help="input files")
args = cmd_parser.parse_args()
doc = Doc()
for file in args.files:
print("processing", file)
if not process_file(file, doc):
return
try:
doc.validate()
except DocValidateError as e:
print(e)
makedirs(args.outdir)
if args.format == "html":
doc.write_html(args.outdir)
elif args.format == "rst":
doc.write_rst(args.outdir)
else:
print("unknown format:", args.format)
return
print("written to", args.outdir)
if __name__ == "__main__":
main()
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/gendoc.py | Python | apache-2.0 | 17,076 |
#!/usr/bin/env python3
#
# This file is part of the MicroPython project, http://micropython.org/
#
# The MIT License (MIT)
#
# Copyright (c) 2014-2019 Damien P. George
# Copyright (c) 2017 Paul Sokolovsky
#
# 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.
"""
haasboard interface
This module provides the HaaSboard class, used to communicate with and
control a MicroPython device over a communication channel. Both real
boards and emulated devices (e.g. running in QEMU) are supported.
Various communication channels are supported, including a serial
connection, telnet-style network connection, external process
connection.
Example usage:
import haasboard
pyb = haasboard.HaaSboard('/dev/ttyACM0')
Or:
pyb = haasboard.HaaSboard('192.168.1.1')
Then:
pyb.enter_raw_repl()
pyb.exec('import pyb')
pyb.exec('pyb.LED(1).on()')
pyb.exit_raw_repl()
Note: if using Python2 then pyb.exec must be written as pyb.exec_.
To run a script from the local machine on the board and print out the results:
import haasboard
haasboard.execfile('test.py', device='/dev/ttyACM0')
This script can also be run directly. To execute a local script, use:
./haasboard.py test.py
Or:
python haasboard.py test.py
"""
import sys
import time
import os
import ast
try:
stdout = sys.stdout.buffer
except AttributeError:
# Python2 doesn't have buffer attr
stdout = sys.stdout
def stdout_write_bytes(b):
b = b.replace(b"\x04", b"")
stdout.write(b)
stdout.flush()
class HaaSboardError(Exception):
pass
class TelnetToSerial:
def __init__(self, ip, user, password, read_timeout=None):
self.tn = None
import telnetlib
self.tn = telnetlib.Telnet(ip, timeout=15)
self.read_timeout = read_timeout
if b"Login as:" in self.tn.read_until(b"Login as:", timeout=read_timeout):
self.tn.write(bytes(user, "ascii") + b"\r\n")
if b"Password:" in self.tn.read_until(b"Password:", timeout=read_timeout):
# needed because of internal implementation details of the telnet server
time.sleep(0.2)
self.tn.write(bytes(password, "ascii") + b"\r\n")
if b"for more information." in self.tn.read_until(
b'Type "help()" for more information.', timeout=read_timeout
):
# login successful
from collections import deque
self.fifo = deque()
return
raise HaaSboardError("Failed to establish a telnet connection with the board")
def __del__(self):
self.close()
def close(self):
if self.tn:
self.tn.close()
def read(self, size=1):
while len(self.fifo) < size:
timeout_count = 0
data = self.tn.read_eager()
if len(data):
self.fifo.extend(data)
timeout_count = 0
else:
time.sleep(0.25)
if self.read_timeout is not None and timeout_count > 4 * self.read_timeout:
break
timeout_count += 1
data = b""
while len(data) < size and len(self.fifo) > 0:
data += bytes([self.fifo.popleft()])
return data
def write(self, data):
self.tn.write(data)
return len(data)
def inWaiting(self):
n_waiting = len(self.fifo)
if not n_waiting:
data = self.tn.read_eager()
self.fifo.extend(data)
return len(data)
else:
return n_waiting
class ProcessToSerial:
"Execute a process and emulate serial connection using its stdin/stdout."
def __init__(self, cmd):
import subprocess
self.subp = subprocess.Popen(
cmd,
bufsize=0,
shell=True,
preexec_fn=os.setsid,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
)
# Initially was implemented with selectors, but that adds Python3
# dependency. However, there can be race conditions communicating
# with a particular child process (like QEMU), and selectors may
# still work better in that case, so left inplace for now.
#
# import selectors
# self.sel = selectors.DefaultSelector()
# self.sel.register(self.subp.stdout, selectors.EVENT_READ)
import select
self.poll = select.poll()
self.poll.register(self.subp.stdout.fileno())
def close(self):
import signal
os.killpg(os.getpgid(self.subp.pid), signal.SIGTERM)
def read(self, size=1):
data = b""
while len(data) < size:
data += self.subp.stdout.read(size - len(data))
return data
def write(self, data):
self.subp.stdin.write(data)
return len(data)
def inWaiting(self):
# res = self.sel.select(0)
res = self.poll.poll(0)
if res:
return 1
return 0
class ProcessPtyToTerminal:
"""Execute a process which creates a PTY and prints slave PTY as
first line of its output, and emulate serial connection using
this PTY."""
def __init__(self, cmd):
import subprocess
import re
import serial
self.subp = subprocess.Popen(
cmd.split(),
bufsize=0,
shell=False,
preexec_fn=os.setsid,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
pty_line = self.subp.stderr.readline().decode("utf-8")
m = re.search(r"/dev/pts/[0-9]+", pty_line)
if not m:
print("Error: unable to find PTY device in startup line:", pty_line)
self.close()
sys.exit(1)
pty = m.group()
# rtscts, dsrdtr params are to workaround pyserial bug:
# http://stackoverflow.com/questions/34831131/pyserial-does-not-play-well-with-virtual-port
self.ser = serial.Serial(pty, interCharTimeout=1, rtscts=True, dsrdtr=True)
def close(self):
import signal
os.killpg(os.getpgid(self.subp.pid), signal.SIGTERM)
def read(self, size=1):
return self.ser.read(size)
def write(self, data):
return self.ser.write(data)
def inWaiting(self):
return self.ser.inWaiting()
class HaaSboard:
def __init__(self, device, baudrate=1500000, user="micro", password="python", wait=0):
self.use_raw_paste = True
if device.startswith("exec:"):
self.serial = ProcessToSerial(device[len("exec:") :])
elif device.startswith("execpty:"):
self.serial = ProcessPtyToTerminal(device[len("qemupty:") :])
elif device and device[0].isdigit() and device[-1].isdigit() and device.count(".") == 3:
# device looks like an IP address
self.serial = TelnetToSerial(device, user, password, read_timeout=10)
else:
import serial
delayed = False
for attempt in range(wait + 1):
self.serial = serial.Serial()
self.serial.port = device
self.serial.baudrate = baudrate
self.serial.parity = "N"
self.serial.bytesize = 8
self.serial.stopbits = 1
self.serial.timeout = 0.05
try:
self.serial.open()
except Exception as e:
raise Exception("Failed to open serial port: %s!" % device)
break
time.sleep(1)
sys.stdout.write(".")
sys.stdout.flush()
else:
if delayed:
print("")
raise HaaSboardError("failed to access " + device)
if delayed:
print("")
def close(self):
self.serial.close()
def run_cmd(self,cmd):
self.serial.write(cmd)
def run_cmd_follow(self,cmd,ending,timeout = 10):
self.serial.write(cmd)
return self.read_until(1,ending,timeout)
def read_until(self, min_num_bytes, ending, timeout=10, data_consumer=None):
# if data_consumer is used then data is not accumulated and the ending must be 1 byte long
assert data_consumer is None or len(ending) == 1
data = self.serial.read(min_num_bytes)
if data_consumer:
data_consumer(data)
timeout_count = 0
while True:
if data.endswith(ending):
break
elif self.serial.inWaiting() > 0:
new_data = self.serial.read(1)
if data_consumer:
data_consumer(new_data)
data = new_data
else:
data = data + new_data
timeout_count = 0
else:
timeout_count += 1
if timeout is not None and timeout_count >= 100 * timeout:
print("Error:Waiting for %s timeout" %(ending.decode('utf-8')))
print('read data = ', data)
break
time.sleep(0.01)
return data
def enter_raw_repl(self):
# interrupt running python
# print('step1 exit running thread')
self.serial.write(b"\r\x03") # exit running code
time.sleep(0.05)
self.serial.write(b"\r\x02")
time.sleep(0.2)
self.serial.write(b"\r\n")
time.sleep(0.05)
# inter python cmd
# print('enter python mode')
self.serial.write(b"python\r\n") # ctrl-C twice: interrupt any running program
time.sleep(0.5)
# flush input (without relying on serial.flushInput())
# print('python mode checked')
n = self.serial.inWaiting()
while n > 0:
self.serial.read(n)
n = self.serial.inWaiting()
# print('enter raw repl mode')
self.serial.write(b"\r\n")
time.sleep(0.2)
self.serial.write(b"\r\x01") # ctrl-A: enter raw REPL
time.sleep(0.2)
data = self.read_until(1, b"raw REPL; CTRL-B to exit\r\r\n", 2)
# print(data)
if not data.endswith(b"raw REPL; CTRL-B to exit\r\r\n"):
# recovery
self.serial.write(b"\r\x01") # ctrl-A: enter raw REPL
data = self.read_until(1, b"raw REPL; CTRL-B to exit\r\r\n", 2)
if not data.endswith(b"raw REPL; CTRL-B to exit\r\r\n"):
raise HaaSboardError("could not enter raw repl")
# self.serial.write(b"\x04") # ctrl-D: soft reset
# data = self.read_until(1, b"soft reboot\r\n")
# if not data.endswith(b"soft reboot\r\n"):
# print(data)
# raise HaaSboardError("could not enter raw repl")
# By splitting this into 2 reads, it allows boot.py to print stuff,
# which will show up after the soft reboot and before the raw REPL.
# data = self.read_until(1, b"raw REPL; CTRL-B to exit\r\n")
# if not data.endswith(b"raw REPL; CTRL-B to exit\r\n"):
# print(data)
# raise HaaSboardError("could not enter raw repl")
def exit_raw_repl(self):
time.sleep(0.05)
self.serial.write(b"\r\x02") # ctrl-B: enter friendly REPL
def exit_python_mode(self):
time.sleep(0.05)
self.serial.write(b"\r\x04") # ctrl-D: enter friendly REPL
def follow(self, timeout, data_consumer=None):
# wait for normal output
data = self.read_until(1, b"\x04", timeout=timeout, data_consumer=data_consumer)
if not data.endswith(b"\x04"):
raise HaaSboardError("timeout waiting for first EOF reception")
data = data[:-1]
# wait for error output
data_err = self.read_until(1, b"\x04", timeout=timeout)
if not data_err.endswith(b"\x04"):
raise HaaSboardError("timeout waiting for second EOF reception")
data_err = data_err[:-1]
# return normal and error output
return data, data_err
def raw_paste_write(self, command_bytes):
# Read initial header, with window size.
data = self.serial.read(2)
window_size = data[0] | data[1] << 8
window_remain = window_size
# Write out the command_bytes data.
i = 0
while i < len(command_bytes):
while window_remain == 0 or self.serial.inWaiting():
data = self.serial.read(1)
if data == b"\x01":
# Device indicated that a new window of data can be sent.
window_remain += window_size
elif data == b"\x04":
# Device indicated abrupt end. Acknowledge it and finish.
self.serial.write(b"\x04")
return
else:
# Unexpected data from device.
raise HaaSboardError("unexpected read during raw paste: {}".format(data))
# Send out as much data as possible that fits within the allowed window.
b = command_bytes[i : min(i + window_remain, len(command_bytes))]
self.serial.write(b)
window_remain -= len(b)
i += len(b)
# Indicate end of data.
self.serial.write(b"\x04")
# Wait for device to acknowledge end of data.
data = self.read_until(1, b"\x04")
if not data.endswith(b"\x04"):
raise HaaSboardError("could not complete raw paste: {}".format(data))
def exec_raw_no_follow(self, command):
if isinstance(command, bytes):
command_bytes = command
else:
command_bytes = bytes(command, encoding="utf8")
# check we have a prompt
data = self.read_until(1, b">")
if not data.endswith(b">"):
raise HaaSboardError("could not enter raw repl")
if self.use_raw_paste:
# Try to enter raw-paste mode.
self.serial.write(b"\x05A\x01")
data = self.serial.read(2)
if data == b"R\x00":
# Device understood raw-paste command but doesn't support it.
pass
elif data == b"R\x01":
# Device supports raw-paste mode, write out the command using this mode.
return self.raw_paste_write(command_bytes)
else:
# Device doesn't support raw-paste, fall back to normal raw REPL.
data = self.read_until(1, b"w REPL; CTRL-B to exit\r\n>")
if not data.endswith(b"w REPL; CTRL-B to exit\r\n>"):
raise HaaSboardError("could not enter raw repl")
# Don't try to use raw-paste mode again for this connection.
self.use_raw_paste = False
# Write command using standard raw REPL, 256 bytes every 10ms.
for i in range(0, len(command_bytes), 256):
self.serial.write(command_bytes[i : min(i + 256, len(command_bytes))])
time.sleep(0.01)
self.serial.write(b"\x04")
# check if we could exec command
data = self.serial.read(2)
if data != b"OK":
raise HaaSboardError("could not exec command (response: %r)" % data)
def exec_raw(self, command, timeout=10, data_consumer=None):
self.exec_raw_no_follow(command)
return self.follow(timeout, data_consumer)
def eval(self, expression):
ret = self.exec_("print({})".format(expression))
ret = ret.strip()
return ret
def exec_(self, command, data_consumer=None):
ret, ret_err = self.exec_raw(command, data_consumer=data_consumer)
if ret_err:
raise HaaSboardError("exception", ret, ret_err)
return ret
def execfile(self, filename):
with open(filename, "rb") as f:
pyfile = f.read()
return self.exec_(pyfile)
def get_time(self):
t = str(self.eval("pyb.RTC().datetime()"), encoding="utf8")[1:-1].split(", ")
return int(t[4]) * 3600 + int(t[5]) * 60 + int(t[6])
def fs_ls(self, src):
cmd = (
"import uos\nfor f in uos.ilistdir(%s):\n"
" print('{:12} {}{}'.format(f[3]if len(f)>3 else 0,f[0],'/'if f[1]&0x4000 else ''))"
% (("'%s'" % src) if src else "")
)
self.exec_(cmd, data_consumer=stdout_write_bytes)
def fs_cat(self, src, chunk_size=256):
cmd = (
"with open('%s') as f:\n while 1:\n"
" b=f.read(%u)\n if not b:break\n print(b,end='')" % (src, chunk_size)
)
self.exec_(cmd, data_consumer=stdout_write_bytes)
def fs_get(self, src, dest, chunk_size=256):
self.exec_("f=open('%s','rb')\nr=f.read" % src)
with open(dest, "wb") as f:
while True:
data = bytearray()
self.exec_("print(r(%u))" % chunk_size, data_consumer=lambda d: data.extend(d))
assert data.endswith(b"\r\n\x04")
try:
data = ast.literal_eval(str(data[:-3], "ascii"))
if not isinstance(data, bytes):
raise ValueError("Not bytes")
except (UnicodeError, ValueError) as e:
raise HaaSboardError("fs_get: Could not interpret received data: %s" % str(e))
if not data:
break
f.write(data)
self.exec_("f.close()")
def fs_put(self, src, dest, chunk_size=256):
self.exec_("f=open('%s','wb')\nw=f.write" % dest)
with open(src, "rb") as f:
while True:
data = f.read(chunk_size)
if not data:
break
if sys.version_info < (3,):
self.exec_("w(b" + repr(data) + ")")
else:
self.exec_("w(" + repr(data) + ")")
self.exec_("f.close()")
def fs_mkdir(self, dir):
self.exec_("import uos\nuos.mkdir('%s')" % dir)
def fs_rmdir(self, dir):
self.exec_("import uos\nuos.rmdir('%s')" % dir)
def fs_rm(self, src):
self.exec_("import uos\nuos.remove('%s')" % src)
# in Python2 exec is a keyword so one must use "exec_"
# but for Python3 we want to provide the nicer version "exec"
setattr(HaaSboard, "exec", HaaSboard.exec_)
def execfile(filename, device="/dev/ttyACM0", baudrate=1500000, user="micro", password="python"):
pyb = HaaSboard(device, baudrate, user, password)
pyb.enter_raw_repl()
output = pyb.execfile(filename)
stdout_write_bytes(output)
pyb.exit_raw_repl()
pyb.exit_python_mode()
pyb.close()
def filesystem_command(pyb, args):
def fname_remote(src):
if src.startswith(":"):
src = src[1:]
return src
def fname_cp_dest(src, dest):
src = src.rsplit("/", 1)[-1]
if dest is None or dest == "":
dest = src
elif dest == ".":
dest = "./" + src
elif dest.endswith("/"):
dest += src
return dest
cmd = args[0]
args = args[1:]
try:
if cmd == "cp":
srcs = args[:-1]
dest = args[-1]
if srcs[0].startswith("./") or dest.startswith(":"):
op = pyb.fs_put
fmt = "cp %s :%s"
dest = fname_remote(dest)
else:
op = pyb.fs_get
fmt = "cp :%s %s"
for src in srcs:
src = fname_remote(src)
dest2 = fname_cp_dest(src, dest)
print(fmt % (src, dest2))
op(src, dest2)
else:
op = {
"ls": pyb.fs_ls,
"cat": pyb.fs_cat,
"mkdir": pyb.fs_mkdir,
"rmdir": pyb.fs_rmdir,
"rm": pyb.fs_rm,
}[cmd]
if cmd == "ls" and not args:
args = [""]
for src in args:
src = fname_remote(src)
print("%s :%s" % (cmd, src))
op(src)
except HaaSboardError as er:
print(str(er.args[2], "ascii"))
pyb.exit_raw_repl()
pyb.close()
sys.exit(1)
_injected_import_hook_code = """\
import uos, uio
class _FS:
class File(uio.IOBase):
def __init__(self):
self.off = 0
def ioctl(self, request, arg):
return 0
def readinto(self, buf):
buf[:] = memoryview(_injected_buf)[self.off:self.off + len(buf)]
self.off += len(buf)
return len(buf)
mount = umount = chdir = lambda *args: None
def stat(self, path):
if path == '_injected.mpy':
return tuple(0 for _ in range(10))
else:
raise OSError(-2) # ENOENT
def open(self, path, mode):
return self.File()
uos.mount(_FS(), '/_')
uos.chdir('/_')
from _injected import *
uos.umount('/_')
del _injected_buf, _FS
"""
def main():
import argparse
cmd_parser = argparse.ArgumentParser(description="Run scripts on the haasboard.")
cmd_parser.add_argument(
"-d",
"--device",
default=os.environ.get("HAASBOARD_DEVICE", "/dev/ttyACM0"),
help="the serial device or the IP address of the haasboard",
)
cmd_parser.add_argument(
"-b",
"--baudrate",
default=os.environ.get("HAASBOARD_BAUDRATE", "115200"),
help="the baud rate of the serial device",
)
cmd_parser.add_argument("-u", "--user", default="micro", help="the telnet login username")
cmd_parser.add_argument("-p", "--password", default="python", help="the telnet login password")
cmd_parser.add_argument("-c", "--command", help="program passed in as string")
cmd_parser.add_argument(
"-w",
"--wait",
default=0,
type=int,
help="seconds to wait for USB connected board to become available",
)
group = cmd_parser.add_mutually_exclusive_group()
group.add_argument(
"--follow",
action="store_true",
help="follow the output after running the scripts [default if no scripts given]",
)
group.add_argument(
"--no-follow",
action="store_true",
help="Do not follow the output after running the scripts.",
)
cmd_parser.add_argument(
"-f", "--filesystem", action="store_true", help="perform a filesystem action"
)
cmd_parser.add_argument("files", nargs="*", help="input files")
args = cmd_parser.parse_args()
# open the connection to the haasboard
try:
pyb = HaaSboard(args.device, args.baudrate, args.user, args.password, args.wait)
except HaaSboardError as er:
print(er)
sys.exit(1)
# run any command or file(s)
if args.command is not None or args.filesystem or len(args.files):
# we must enter raw-REPL mode to execute commands
# this will do a soft-reset of the board
try:
pyb.enter_raw_repl()
except HaaSboardError as er:
print(er)
pyb.close()
sys.exit(1)
def execbuffer(buf):
try:
if args.no_follow:
pyb.exec_raw_no_follow(buf)
ret_err = None
else:
ret, ret_err = pyb.exec_raw(
buf, timeout=None, data_consumer=stdout_write_bytes
)
except HaaSboardError as er:
print(er)
pyb.close()
sys.exit(1)
except KeyboardInterrupt:
sys.exit(1)
if ret_err:
pyb.exit_raw_repl()
pyb.close()
stdout_write_bytes(ret_err)
sys.exit(1)
# do filesystem commands, if given
if args.filesystem:
filesystem_command(pyb, args.files)
del args.files[:]
# run the command, if given
if args.command is not None:
execbuffer(args.command.encode("utf-8"))
# run any files
for filename in args.files:
with open(filename, "rb") as f:
pyfile = f.read()
if filename.endswith(".mpy") and pyfile[0] == ord("M"):
pyb.exec_("_injected_buf=" + repr(pyfile))
pyfile = _injected_import_hook_code
execbuffer(pyfile)
# exiting raw-REPL just drops to friendly-REPL mode
pyb.exit_raw_repl()
# if asked explicitly, or no files given, then follow the output
if args.follow or (args.command is None and not args.filesystem and len(args.files) == 0):
try:
ret, ret_err = pyb.follow(timeout=None, data_consumer=stdout_write_bytes)
except HaaSboardError as er:
print(er)
sys.exit(1)
except KeyboardInterrupt:
sys.exit(1)
if ret_err:
pyb.close()
stdout_write_bytes(ret_err)
sys.exit(1)
# close the connection to the haasboard
pyb.close()
if __name__ == "__main__":
main()
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/haasboard.py | Python | apache-2.0 | 26,216 |
# Reads the USB VID and PID from the file specified by sys.argv[1] and then
# inserts those values into the template file specified by sys.argv[2],
# printing the result to stdout
from __future__ import print_function
import sys
import re
import string
config_prefix = "MICROPY_HW_USB_"
needed_keys = ("USB_PID_CDC_MSC", "USB_PID_CDC_HID", "USB_PID_CDC", "USB_VID")
def parse_usb_ids(filename):
rv = dict()
for line in open(filename).readlines():
line = line.rstrip("\r\n")
match = re.match("^#define\s+(\w+)\s+\(0x([0-9A-Fa-f]+)\)$", line)
if match and match.group(1).startswith(config_prefix):
key = match.group(1).replace(config_prefix, "USB_")
val = match.group(2)
# print("key =", key, "val =", val)
if key in needed_keys:
rv[key] = val
for k in needed_keys:
if k not in rv:
raise Exception("Unable to parse %s from %s" % (k, filename))
return rv
if __name__ == "__main__":
usb_ids_file = sys.argv[1]
template_file = sys.argv[2]
replacements = parse_usb_ids(usb_ids_file)
for line in open(template_file, "r").readlines():
print(string.Template(line).safe_substitute(replacements), end="")
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/insert-usb-ids.py | Python | apache-2.0 | 1,249 |
#!/usr/bin/env python
#
# Create frozen modules structure for MicroPython.
#
# Usage:
#
# Have a directory with modules to be frozen (only modules, not packages
# supported so far):
#
# frozen/foo.py
# frozen/bar.py
#
# Run script, passing path to the directory above:
#
# ./make-frozen.py frozen > frozen.c
#
# Include frozen.c in your build, having defined MICROPY_MODULE_FROZEN_STR in
# config.
#
from __future__ import print_function
import sys
import os
def module_name(f):
return f
modules = []
if len(sys.argv) > 1:
root = sys.argv[1].rstrip("/")
root_len = len(root)
for dirpath, dirnames, filenames in os.walk(root):
for f in filenames:
fullpath = dirpath + "/" + f
st = os.stat(fullpath)
modules.append((fullpath[root_len + 1 :], st))
print("#include <stdint.h>")
print("const char mp_frozen_str_names[] = {")
for f, st in modules:
m = module_name(f)
print('"%s\\0"' % m)
print('"\\0"};')
print("const uint32_t mp_frozen_str_sizes[] = {")
for f, st in modules:
print("%d," % st.st_size)
print("0};")
print("const char mp_frozen_str_content[] = {")
for f, st in modules:
data = open(sys.argv[1] + "/" + f, "rb").read()
# We need to properly escape the script data to create a C string.
# When C parses hex characters of the form \x00 it keeps parsing the hex
# data until it encounters a non-hex character. Thus one must create
# strings of the form "data\x01" "abc" to properly encode this kind of
# data. We could just encode all characters as hex digits but it's nice
# to be able to read the resulting C code as ASCII when possible.
data = bytearray(data) # so Python2 extracts each byte as an integer
esc_dict = {ord("\n"): "\\n", ord("\r"): "\\r", ord('"'): '\\"', ord("\\"): "\\\\"}
chrs = ['"']
break_str = False
for c in data:
try:
chrs.append(esc_dict[c])
except KeyError:
if 32 <= c <= 126:
if break_str:
chrs.append('" "')
break_str = False
chrs.append(chr(c))
else:
chrs.append("\\x%02x" % c)
break_str = True
chrs.append('\\0"')
print("".join(chrs))
print('"\\0"};')
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/make-frozen.py | Python | apache-2.0 | 2,291 |
#!/usr/bin/env python3
#
# 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.
from __future__ import print_function
import sys
import os
import subprocess
###########################################################################
# Public functions to be used in the manifest
def include(manifest, **kwargs):
"""Include another manifest.
The manifest argument can be a string (filename) or an iterable of
strings.
Relative paths are resolved with respect to the current manifest file.
Optional kwargs can be provided which will be available to the
included script via the `options` variable.
e.g. include("path.py", extra_features=True)
in path.py:
options.defaults(standard_features=True)
# freeze minimal modules.
if options.standard_features:
# freeze standard modules.
if options.extra_features:
# freeze extra modules.
"""
if not isinstance(manifest, str):
for m in manifest:
include(m)
else:
manifest = convert_path(manifest)
with open(manifest) as f:
# Make paths relative to this manifest file while processing it.
# Applies to includes and input files.
prev_cwd = os.getcwd()
os.chdir(os.path.dirname(manifest))
exec(f.read(), globals(), {"options": IncludeOptions(**kwargs)})
os.chdir(prev_cwd)
def freeze(path, script=None, opt=0):
"""Freeze the input, automatically determining its type. A .py script
will be compiled to a .mpy first then frozen, and a .mpy file will be
frozen directly.
`path` must be a directory, which is the base directory to search for
files from. When importing the resulting frozen modules, the name of
the module will start after `path`, ie `path` is excluded from the
module name.
If `path` is relative, it is resolved to the current manifest.py.
Use $(MPY_DIR), $(MPY_LIB_DIR), $(PORT_DIR), $(BOARD_DIR) if you need
to access specific paths.
If `script` is None all files in `path` will be frozen.
If `script` is an iterable then freeze() is called on all items of the
iterable (with the same `path` and `opt` passed through).
If `script` is a string then it specifies the file or directory to
freeze, and can include extra directories before the file or last
directory. The file or directory will be searched for in `path`. If
`script` is a directory then all files in that directory will be frozen.
`opt` is the optimisation level to pass to mpy-cross when compiling .py
to .mpy.
"""
freeze_internal(KIND_AUTO, path, script, opt)
def freeze_as_str(path):
"""Freeze the given `path` and all .py scripts within it as a string,
which will be compiled upon import.
"""
freeze_internal(KIND_AS_STR, path, None, 0)
def freeze_as_mpy(path, script=None, opt=0):
"""Freeze the input (see above) by first compiling the .py scripts to
.mpy files, then freezing the resulting .mpy files.
"""
freeze_internal(KIND_AS_MPY, path, script, opt)
def freeze_mpy(path, script=None, opt=0):
"""Freeze the input (see above), which must be .mpy files that are
frozen directly.
"""
freeze_internal(KIND_MPY, path, script, opt)
###########################################################################
# Internal implementation
KIND_AUTO = 0
KIND_AS_STR = 1
KIND_AS_MPY = 2
KIND_MPY = 3
VARS = {}
manifest_list = []
class IncludeOptions:
def __init__(self, **kwargs):
self._kwargs = kwargs
self._defaults = {}
def defaults(self, **kwargs):
self._defaults = kwargs
def __getattr__(self, name):
return self._kwargs.get(name, self._defaults.get(name, None))
class FreezeError(Exception):
pass
def system(cmd):
try:
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
return 0, output
except subprocess.CalledProcessError as er:
return -1, er.output
def convert_path(path):
# Perform variable substituion.
for name, value in VARS.items():
path = path.replace("$({})".format(name), value)
# Convert to absolute path (so that future operations don't rely on
# still being chdir'ed).
return os.path.abspath(path)
def get_timestamp(path, default=None):
try:
stat = os.stat(path)
return stat.st_mtime
except OSError:
if default is None:
raise FreezeError("cannot stat {}".format(path))
return default
def get_timestamp_newest(path):
ts_newest = 0
for dirpath, dirnames, filenames in os.walk(path, followlinks=True):
for f in filenames:
ts_newest = max(ts_newest, get_timestamp(os.path.join(dirpath, f)))
return ts_newest
def mkdir(filename):
path = os.path.dirname(filename)
if not os.path.isdir(path):
os.makedirs(path)
def freeze_internal(kind, path, script, opt):
path = convert_path(path)
if not os.path.isdir(path):
raise FreezeError("freeze path must be a directory: {}".format(path))
if script is None and kind == KIND_AS_STR:
if any(f[0] == KIND_AS_STR for f in manifest_list):
raise FreezeError("can only freeze one str directory")
manifest_list.append((KIND_AS_STR, path, script, opt))
elif script is None or isinstance(script, str) and script.find(".") == -1:
# Recursively search `path` for files to freeze, optionally restricted
# to a subdirectory specified by `script`
if script is None:
subdir = ""
else:
subdir = "/" + script
for dirpath, dirnames, filenames in os.walk(path + subdir, followlinks=True):
for f in filenames:
freeze_internal(kind, path, (dirpath + "/" + f)[len(path) + 1 :], opt)
elif not isinstance(script, str):
# `script` is an iterable of items to freeze
for s in script:
freeze_internal(kind, path, s, opt)
else:
# `script` should specify an individual file to be frozen
extension_kind = {KIND_AS_MPY: ".py", KIND_MPY: ".mpy"}
if kind == KIND_AUTO:
for k, ext in extension_kind.items():
if script.endswith(ext):
kind = k
break
else:
print("warn: unsupported file type, skipped freeze: {}".format(script))
return
wanted_extension = extension_kind[kind]
if not script.endswith(wanted_extension):
raise FreezeError("expecting a {} file, got {}".format(wanted_extension, script))
manifest_list.append((kind, path, script, opt))
def main():
# Parse arguments
import argparse
cmd_parser = argparse.ArgumentParser(
description="A tool to generate frozen content in MicroPython firmware images."
)
cmd_parser.add_argument("-o", "--output", help="output path")
cmd_parser.add_argument("-b", "--build-dir", help="output path")
cmd_parser.add_argument(
"-f", "--mpy-cross-flags", default="", help="flags to pass to mpy-cross"
)
cmd_parser.add_argument("-v", "--var", action="append", help="variables to substitute")
cmd_parser.add_argument("--mpy-tool-flags", default="", help="flags to pass to mpy-tool")
cmd_parser.add_argument("files", nargs="+", help="input manifest list")
args = cmd_parser.parse_args()
# Extract variables for substitution.
for var in args.var:
name, value = var.split("=", 1)
if os.path.exists(value):
value = os.path.abspath(value)
VARS[name] = value
if "MPY_DIR" not in VARS or "PORT_DIR" not in VARS:
print("MPY_DIR and PORT_DIR variables must be specified")
sys.exit(1)
# Get paths to tools
MAKE_FROZEN = VARS["MPY_DIR"] + "/tools/make-frozen.py"
MPY_CROSS = VARS["MPY_DIR"] + "/mpy-cross/mpy-cross"
if sys.platform == "win32":
MPY_CROSS += ".exe"
MPY_CROSS = os.getenv("MICROPY_MPYCROSS", MPY_CROSS)
MPY_TOOL = VARS["MPY_DIR"] + "/tools/mpy-tool.py"
# Ensure mpy-cross is built
if not os.path.exists(MPY_CROSS):
print("mpy-cross not found at {}, please build it first".format(MPY_CROSS))
sys.exit(1)
# Include top-level inputs, to generate the manifest
for input_manifest in args.files:
try:
if input_manifest.endswith(".py"):
include(input_manifest)
else:
exec(input_manifest)
except FreezeError as er:
print('freeze error executing "{}": {}'.format(input_manifest, er.args[0]))
sys.exit(1)
# Process the manifest
str_paths = []
mpy_files = []
ts_newest = 0
for kind, path, script, opt in manifest_list:
if kind == KIND_AS_STR:
str_paths.append(path)
ts_outfile = get_timestamp_newest(path)
elif kind == KIND_AS_MPY:
infile = "{}/{}".format(path, script)
outfile = "{}/frozen_mpy/{}.mpy".format(args.build_dir, script[:-3])
ts_infile = get_timestamp(infile)
ts_outfile = get_timestamp(outfile, 0)
if ts_infile >= ts_outfile:
print("MPY", script)
mkdir(outfile)
res, out = system(
[MPY_CROSS]
+ args.mpy_cross_flags.split()
+ ["-o", outfile, "-s", script, "-O{}".format(opt), infile]
)
if res != 0:
print("error compiling {}:".format(infile))
sys.stdout.buffer.write(out)
raise SystemExit(1)
ts_outfile = get_timestamp(outfile)
mpy_files.append(outfile)
else:
assert kind == KIND_MPY
infile = "{}/{}".format(path, script)
mpy_files.append(infile)
ts_outfile = get_timestamp(infile)
ts_newest = max(ts_newest, ts_outfile)
# Check if output file needs generating
if ts_newest < get_timestamp(args.output, 0):
# No files are newer than output file so it does not need updating
return
# Freeze paths as strings
res, output_str = system([sys.executable, MAKE_FROZEN] + str_paths)
if res != 0:
print("error freezing strings {}: {}".format(str_paths, output_str))
sys.exit(1)
# Freeze .mpy files
if mpy_files:
res, output_mpy = system(
[
sys.executable,
MPY_TOOL,
"-f",
"-q",
args.build_dir + "/genhdr/qstrdefs.preprocessed.h",
]
+ args.mpy_tool_flags.split()
+ mpy_files
)
if res != 0:
print("error freezing mpy {}:".format(mpy_files))
print(str(output_mpy, "utf8"))
sys.exit(1)
else:
output_mpy = (
b'#include "py/emitglue.h"\n'
b"extern const qstr_pool_t mp_qstr_const_pool;\n"
b"const qstr_pool_t mp_qstr_frozen_const_pool = {\n"
b" (qstr_pool_t*)&mp_qstr_const_pool, MP_QSTRnumber_of, 0, false, 0\n"
b"};\n"
b'const char mp_frozen_mpy_names[1] = {"\\0"};\n'
b"const mp_raw_code_t *const mp_frozen_mpy_content[1] = {NULL};\n"
)
# Generate output
print("GEN", args.output)
mkdir(args.output)
with open(args.output, "wb") as f:
f.write(b"//\n// Content for MICROPY_MODULE_FROZEN_STR\n//\n")
f.write(output_str)
f.write(b"//\n// Content for MICROPY_MODULE_FROZEN_MPY\n//\n")
f.write(output_mpy)
if __name__ == "__main__":
main()
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/makemanifest.py | Python | apache-2.0 | 12,921 |
#!/usr/bin/env python3
#
# This file is part of the MicroPython project, http://micropython.org/
#
# The MIT License (MIT)
#
# Copyright (c) 2020 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.
"""
This script is used to compute metrics, like code size, of the various ports.
Typical usage is:
$ ./tools/metrics.py build | tee size0
<wait for build to complete>
$ git switch new-feature-branch
$ ./tools/metrics.py build | tee size1
<wait for build to complete>
$ ./tools/metrics.py diff size0 size1
Other commands:
$ ./tools/metrics.py sizes # print all firmware sizes
$ ./tools/metrics.py clean # clean all ports
"""
import collections, sys, re, subprocess
MAKE_FLAGS = ["-j3", "CFLAGS_EXTRA=-DNDEBUG"]
class PortData:
def __init__(self, name, dir, output, make_flags=None):
self.name = name
self.dir = dir
self.output = output
self.make_flags = make_flags
self.needs_mpy_cross = dir not in ("bare-arm", "minimal")
port_data = {
"b": PortData("bare-arm", "bare-arm", "build/firmware.elf"),
"m": PortData("minimal x86", "minimal", "build/firmware.elf"),
"u": PortData("unix x64", "unix", "micropython"),
"n": PortData("unix nanbox", "unix", "micropython-nanbox", "VARIANT=nanbox"),
"s": PortData("stm32", "stm32", "build-PYBV10/firmware.elf", "BOARD=PYBV10"),
"c": PortData("cc3200", "cc3200", "build/WIPY/release/application.axf", "BTARGET=application"),
"8": PortData("esp8266", "esp8266", "build-GENERIC/firmware.elf"),
"3": PortData("esp32", "esp32", "build-GENERIC/micropython.elf"),
"r": PortData("nrf", "nrf", "build-pca10040/firmware.elf"),
"p": PortData("rp2", "rp2", "build-PICO/firmware.elf"),
"d": PortData("samd", "samd", "build-ADAFRUIT_ITSYBITSY_M4_EXPRESS/firmware.elf"),
}
def syscmd(*args):
sys.stdout.flush()
a2 = []
for a in args:
if isinstance(a, str):
a2.append(a)
elif a:
a2.extend(a)
subprocess.check_call(a2)
def parse_port_list(args):
if not args:
return list(port_data.values())
else:
ports = []
for arg in args:
for port_char in arg:
try:
ports.append(port_data[port_char])
except KeyError:
print("unknown port:", port_char)
sys.exit(1)
return ports
def read_build_log(filename):
data = collections.OrderedDict()
lines = []
found_sizes = False
with open(filename) as f:
for line in f:
line = line.strip()
if line.strip() == "COMPUTING SIZES":
found_sizes = True
elif found_sizes:
lines.append(line)
is_size_line = False
for line in lines:
if is_size_line:
fields = line.split()
data[fields[-1]] = [int(f) for f in fields[:-2]]
is_size_line = False
else:
is_size_line = line.startswith("text\t ")
return data
def do_diff(args):
"""Compute the difference between firmware sizes."""
# Parse arguments.
error_threshold = None
if len(args) >= 2 and args[0] == "--error-threshold":
args.pop(0)
error_threshold = int(args.pop(0))
if len(args) != 2:
print("usage: %s diff [--error-threshold <x>] <out1> <out2>" % sys.argv[0])
sys.exit(1)
data1 = read_build_log(args[0])
data2 = read_build_log(args[1])
max_delta = None
for key, value1 in data1.items():
value2 = data2[key]
for port in port_data.values():
if key == "ports/{}/{}".format(port.dir, port.output):
name = port.name
break
data = [v2 - v1 for v1, v2 in zip(value1, value2)]
warn = ""
board = re.search(r"/build-([A-Za-z0-9_]+)/", key)
if board:
board = board.group(1)
else:
board = ""
if name == "cc3200":
delta = data[0]
percent = 100 * delta / value1[0]
if data[1] != 0:
warn += " %+u(data)" % data[1]
else:
delta = data[3]
percent = 100 * delta / value1[3]
if data[1] != 0:
warn += " %+u(data)" % data[1]
if data[2] != 0:
warn += " %+u(bss)" % data[2]
if warn:
warn = "[incl%s]" % warn
print("%11s: %+5u %+.3f%% %s%s" % (name, delta, percent, board, warn))
max_delta = delta if max_delta is None else max(max_delta, delta)
if error_threshold is not None and max_delta is not None:
if max_delta > error_threshold:
sys.exit(1)
def do_clean(args):
"""Clean ports."""
ports = parse_port_list(args)
print("CLEANING")
for port in ports:
syscmd("make", "-C", "ports/{}".format(port.dir), port.make_flags, "clean")
def do_build(args):
"""Build ports and print firmware sizes."""
ports = parse_port_list(args)
if any(port.needs_mpy_cross for port in ports):
print("BUILDING MPY-CROSS")
syscmd("make", "-C", "mpy-cross", MAKE_FLAGS)
print("BUILDING PORTS")
for port in ports:
syscmd("make", "-C", "ports/{}".format(port.dir), MAKE_FLAGS, port.make_flags)
do_sizes(args)
def do_sizes(args):
"""Compute and print sizes of firmware."""
ports = parse_port_list(args)
print("COMPUTING SIZES")
for port in ports:
syscmd("size", "ports/{}/{}".format(port.dir, port.output))
def main():
# Get command to execute
if len(sys.argv) == 1:
print("Available commands:")
for cmd in globals():
if cmd.startswith("do_"):
print(" {:9} {}".format(cmd[3:], globals()[cmd].__doc__))
sys.exit(1)
cmd = sys.argv.pop(1)
# Dispatch to desired command
try:
cmd = globals()["do_{}".format(cmd)]
except KeyError:
print("{}: unknown command '{}'".format(sys.argv[0], cmd))
sys.exit(1)
cmd(sys.argv[1:])
if __name__ == "__main__":
main()
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/metrics.py | Python | apache-2.0 | 7,146 |
#!/usr/bin/env python3
import sys
from mpremote import main
sys.exit(main.main())
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/mpremote/mpremote.py | Python | apache-2.0 | 84 |
# empty
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/mpremote/mpremote/__init__.py | Python | apache-2.0 | 8 |
import sys, time
try:
import select, termios
except ImportError:
termios = None
select = None
import msvcrt, signal
class ConsolePosix:
def __init__(self):
self.infd = sys.stdin.fileno()
self.infile = sys.stdin.buffer.raw
self.outfile = sys.stdout.buffer.raw
self.orig_attr = termios.tcgetattr(self.infd)
def enter(self):
# attr is: [iflag, oflag, cflag, lflag, ispeed, ospeed, cc]
attr = termios.tcgetattr(self.infd)
attr[0] &= ~(
termios.BRKINT | termios.ICRNL | termios.INPCK | termios.ISTRIP | termios.IXON
)
attr[1] = 0
attr[2] = attr[2] & ~(termios.CSIZE | termios.PARENB) | termios.CS8
attr[3] = 0
attr[6][termios.VMIN] = 1
attr[6][termios.VTIME] = 0
termios.tcsetattr(self.infd, termios.TCSANOW, attr)
def exit(self):
termios.tcsetattr(self.infd, termios.TCSANOW, self.orig_attr)
def waitchar(self, pyb_serial):
# TODO pyb_serial might not have fd
select.select([self.infd, pyb_serial.fd], [], [])
def readchar(self):
res = select.select([self.infd], [], [], 0)
if res[0]:
return self.infile.read(1)
else:
return None
def write(self, buf):
self.outfile.write(buf)
class ConsoleWindows:
KEY_MAP = {
b"H": b"A", # UP
b"P": b"B", # DOWN
b"M": b"C", # RIGHT
b"K": b"D", # LEFT
b"G": b"H", # POS1
b"O": b"F", # END
b"Q": b"6~", # PGDN
b"I": b"5~", # PGUP
b"s": b"1;5D", # CTRL-LEFT,
b"t": b"1;5C", # CTRL-RIGHT,
b"\x8d": b"1;5A", # CTRL-UP,
b"\x91": b"1;5B", # CTRL-DOWN,
b"w": b"1;5H", # CTRL-POS1
b"u": b"1;5F", # CTRL-END
b"\x98": b"1;3A", # ALT-UP,
b"\xa0": b"1;3B", # ALT-DOWN,
b"\x9d": b"1;3C", # ALT-RIGHT,
b"\x9b": b"1;3D", # ALT-LEFT,
b"\x97": b"1;3H", # ALT-POS1,
b"\x9f": b"1;3F", # ALT-END,
b"S": b"3~", # DEL,
b"\x93": b"3;5~", # CTRL-DEL
b"R": b"2~", # INS
b"\x92": b"2;5~", # CTRL-INS
b"\x94": b"Z", # Ctrl-Tab = BACKTAB,
}
def __init__(self):
self.ctrl_c = 0
def _sigint_handler(self, signo, frame):
self.ctrl_c += 1
def enter(self):
signal.signal(signal.SIGINT, self._sigint_handler)
def exit(self):
signal.signal(signal.SIGINT, signal.SIG_DFL)
def inWaiting(self):
return 1 if self.ctrl_c or msvcrt.kbhit() else 0
def waitchar(self, pyb_serial):
while not (self.inWaiting() or pyb_serial.inWaiting()):
time.sleep(0.01)
def readchar(self):
if self.ctrl_c:
self.ctrl_c -= 1
return b"\x03"
if msvcrt.kbhit():
ch = msvcrt.getch()
while ch in b"\x00\xe0": # arrow or function key prefix?
if not msvcrt.kbhit():
return None
ch = msvcrt.getch() # second call returns the actual key code
try:
ch = b"\x1b[" + self.KEY_MAP[ch]
except KeyError:
return None
return ch
def write(self, buf):
buf = buf.decode() if isinstance(buf, bytes) else buf
sys.stdout.write(buf)
sys.stdout.flush()
# for b in buf:
# if isinstance(b, bytes):
# msvcrt.putch(b)
# else:
# msvcrt.putwch(b)
if termios:
Console = ConsolePosix
VT_ENABLED = True
else:
Console = ConsoleWindows
# Windows VT mode ( >= win10 only)
# https://bugs.python.org/msg291732
import ctypes, os
from ctypes import wintypes
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
ERROR_INVALID_PARAMETER = 0x0057
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
def _check_bool(result, func, args):
if not result:
raise ctypes.WinError(ctypes.get_last_error())
return args
LPDWORD = ctypes.POINTER(wintypes.DWORD)
kernel32.GetConsoleMode.errcheck = _check_bool
kernel32.GetConsoleMode.argtypes = (wintypes.HANDLE, LPDWORD)
kernel32.SetConsoleMode.errcheck = _check_bool
kernel32.SetConsoleMode.argtypes = (wintypes.HANDLE, wintypes.DWORD)
def set_conout_mode(new_mode, mask=0xFFFFFFFF):
# don't assume StandardOutput is a console.
# open CONOUT$ instead
fdout = os.open("CONOUT$", os.O_RDWR)
try:
hout = msvcrt.get_osfhandle(fdout)
old_mode = wintypes.DWORD()
kernel32.GetConsoleMode(hout, ctypes.byref(old_mode))
mode = (new_mode & mask) | (old_mode.value & ~mask)
kernel32.SetConsoleMode(hout, mode)
return old_mode.value
finally:
os.close(fdout)
# def enable_vt_mode():
mode = mask = ENABLE_VIRTUAL_TERMINAL_PROCESSING
try:
set_conout_mode(mode, mask)
VT_ENABLED = True
except WindowsError as e:
VT_ENABLED = False
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/mpremote/mpremote/console.py | Python | apache-2.0 | 5,125 |
"""
MicroPython Remote - Interaction and automation tool for MicroPython
MIT license; Copyright (c) 2019-2021 Damien P. George
This program provides a set of utilities to interact with and automate a
MicroPython device over a serial connection. Commands supported are:
mpremote -- auto-detect, connect and enter REPL
mpremote <device-shortcut> -- connect to given device
mpremote connect <device> -- connect to given device
mpremote disconnect -- disconnect current device
mpremote mount <local-dir> -- mount local directory on device
mpremote eval <string> -- evaluate and print the string
mpremote exec <string> -- execute the string
mpremote run <script> -- run the given local script
mpremote fs <command> <args...> -- execute filesystem commands on the device
mpremote repl -- enter REPL
"""
import os, sys
import serial.tools.list_ports
from . import pyboardextended as pyboard
from .console import Console, ConsolePosix
_PROG = "mpremote"
_BUILTIN_COMMAND_EXPANSIONS = {
# Device connection shortcuts.
"devs": "connect list",
"a0": "connect /dev/ttyACM0",
"a1": "connect /dev/ttyACM1",
"a2": "connect /dev/ttyACM2",
"a3": "connect /dev/ttyACM3",
"u0": "connect /dev/ttyUSB0",
"u1": "connect /dev/ttyUSB1",
"u2": "connect /dev/ttyUSB2",
"u3": "connect /dev/ttyUSB3",
"c0": "connect COM0",
"c1": "connect COM1",
"c2": "connect COM2",
"c3": "connect COM3",
# Filesystem shortcuts.
"cat": "fs cat",
"ls": "fs ls",
"cp": "fs cp",
"rm": "fs rm",
"mkdir": "fs mkdir",
"rmdir": "fs rmdir",
"df": [
"exec",
"import uos\nprint('mount \\tsize \\tused \\tavail \\tuse%')\nfor _m in [''] + uos.listdir('/'):\n _s = uos.stat('/' + _m)\n if not _s[0] & 1 << 14: continue\n _s = uos.statvfs(_m)\n if _s[0]:\n _size = _s[0] * _s[2]; _free = _s[0] * _s[3]; print(_m, _size, _size - _free, _free, int(100 * (_size - _free) / _size), sep='\\t')",
],
# Other shortcuts.
"reset t_ms=100": [
"exec",
"--no-follow",
"import utime, umachine; utime.sleep_ms(t_ms); umachine.reset()",
],
"bootloader t_ms=100": [
"exec",
"--no-follow",
"import utime, umachine; utime.sleep_ms(t_ms); umachine.bootloader()",
],
"setrtc": [
"exec",
"import machine; machine.RTC().datetime((2020, 1, 1, 0, 10, 0, 0, 0))",
],
}
def load_user_config():
# Create empty config object.
config = __build_class__(lambda: None, "Config")()
config.commands = {}
# Get config file name.
path = os.getenv("XDG_CONFIG_HOME")
if path is None:
path = os.getenv("HOME")
if path is None:
return config
path = os.path.join(path, ".config")
path = os.path.join(path, _PROG)
config_file = os.path.join(path, "config.py")
# Check if config file exists.
if not os.path.exists(config_file):
return config
# Exec the config file in its directory.
with open(config_file) as f:
config_data = f.read()
prev_cwd = os.getcwd()
os.chdir(path)
exec(config_data, config.__dict__)
os.chdir(prev_cwd)
return config
def prepare_command_expansions(config):
global _command_expansions
_command_expansions = {}
for command_set in (_BUILTIN_COMMAND_EXPANSIONS, config.commands):
for cmd, sub in command_set.items():
cmd = cmd.split()
if len(cmd) == 1:
args = ()
else:
args = tuple(c.split("=") for c in cmd[1:])
if isinstance(sub, str):
sub = sub.split()
_command_expansions[cmd[0]] = (args, sub)
def do_command_expansion(args):
def usage_error(cmd, exp_args, msg):
print(f"Command {cmd} {msg}; signature is:")
print(" ", cmd, " ".join("=".join(a) for a in exp_args))
sys.exit(1)
last_arg_idx = len(args)
pre = []
while args and args[0] in _command_expansions:
cmd = args.pop(0)
exp_args, exp_sub = _command_expansions[cmd]
for exp_arg in exp_args:
exp_arg_name = exp_arg[0]
if args and "=" not in args[0]:
# Argument given without a name.
value = args.pop(0)
elif args and args[0].startswith(exp_arg_name + "="):
# Argument given with correct name.
value = args.pop(0).split("=", 1)[1]
else:
# No argument given, or argument given with a different name.
if len(exp_arg) == 1:
# Required argument (it has no default).
usage_error(cmd, exp_args, f"missing argument {exp_arg_name}")
else:
# Optional argument with a default.
value = exp_arg[1]
pre.append(f"{exp_arg_name}={value}")
args[0:0] = exp_sub
last_arg_idx = len(exp_sub)
if last_arg_idx < len(args) and "=" in args[last_arg_idx]:
# Extra unknown arguments given.
arg = args[last_arg_idx].split("=", 1)[0]
usage_error(cmd, exp_args, f"given unexpected argument {arg}")
sys.exit(1)
# Insert expansion with optional setting of arguments.
if pre:
args[0:0] = ["exec", ";".join(pre)]
def do_connect(args):
dev = args.pop(0)
try:
if dev == "list":
# List attached devices.
for p in sorted(serial.tools.list_ports.comports()):
print(
"{} {} {:04x}:{:04x} {} {}".format(
p.device,
p.serial_number,
p.vid if isinstance(p.vid, int) else 0,
p.pid if isinstance(p.pid, int) else 0,
p.manufacturer,
p.product,
)
)
return None
elif dev == "auto":
# Auto-detect and auto-connect to the first available device.
for p in sorted(serial.tools.list_ports.comports()):
try:
return pyboard.PyboardExtended(p.device, baudrate=115200)
except pyboard.PyboardError as er:
if not er.args[0].startswith("failed to access"):
raise er
raise pyboard.PyboardError("no device found")
elif dev.startswith("id:"):
# Search for a device with the given serial number.
serial_number = dev[len("id:") :]
dev = None
for p in serial.tools.list_ports.comports():
if p.serial_number == serial_number:
return pyboard.PyboardExtended(p.device, baudrate=115200)
raise pyboard.PyboardError("no device with serial number {}".format(serial_number))
else:
# Connect to the given device.
if dev.startswith("port:"):
dev = dev[len("port:") :]
return pyboard.PyboardExtended(dev, baudrate=115200)
except pyboard.PyboardError as er:
msg = er.args[0]
if msg.startswith("failed to access"):
msg += " (it may be in use by another program)"
print(msg)
sys.exit(1)
def do_disconnect(pyb):
try:
if pyb.mounted:
if not pyb.in_raw_repl:
pyb.enter_raw_repl(soft_reset=False)
pyb.umount_local()
if pyb.in_raw_repl:
pyb.exit_raw_repl()
except OSError:
# Ignore any OSError exceptions when shutting down, eg:
# - pyboard.filesystem_command will close the connecton if it had an error
# - umounting will fail if serial port disappeared
pass
pyb.close()
def do_filesystem(pyb, args):
def _list_recursive(files, path):
if os.path.isdir(path):
for entry in os.listdir(path):
_list_recursive(files, os.path.join(path, entry))
else:
files.append(os.path.split(path))
if args[0] == "cp" and args[1] == "-r":
args.pop(0)
args.pop(0)
assert args[-1] == ":"
args.pop()
src_files = []
for path in args:
_list_recursive(src_files, path)
known_dirs = {""}
pyb.exec_("import uos")
for dir, file in src_files:
dir_parts = dir.split("/")
for i in range(len(dir_parts)):
d = "/".join(dir_parts[: i + 1])
if d not in known_dirs:
pyb.exec_("try:\n uos.mkdir('%s')\nexcept OSError as e:\n print(e)" % d)
known_dirs.add(d)
pyboard.filesystem_command(pyb, ["cp", os.path.join(dir, file), ":" + dir + "/"])
else:
pyboard.filesystem_command(pyb, args)
args.clear()
def do_repl_main_loop(pyb, console_in, console_out_write, *, code_to_inject, file_to_inject):
while True:
console_in.waitchar(pyb.serial)
c = console_in.readchar()
if c:
if c == b"\x1d": # ctrl-], quit
break
elif c == b"\x04": # ctrl-D
# do a soft reset and reload the filesystem hook
pyb.soft_reset_with_mount(console_out_write)
elif c == b"\x0a" and code_to_inject is not None: # ctrl-j, inject code
pyb.serial.write(code_to_inject)
elif c == b"\x0b" and file_to_inject is not None: # ctrl-k, inject script
console_out_write(bytes("Injecting %s\r\n" % file_to_inject, "utf8"))
pyb.enter_raw_repl(soft_reset=False)
with open(file_to_inject, "rb") as f:
pyfile = f.read()
try:
pyb.exec_raw_no_follow(pyfile)
except pyboard.PyboardError as er:
console_out_write(b"Error:\r\n")
console_out_write(er)
pyb.exit_raw_repl()
else:
pyb.serial.write(c)
try:
n = pyb.serial.inWaiting()
except OSError as er:
if er.args[0] == 5: # IO error, device disappeared
print("device disconnected")
break
if n > 0:
c = pyb.serial.read(1)
if c is not None:
# pass character through to the console
oc = ord(c)
if oc in (8, 9, 10, 13, 27) or 32 <= oc <= 126:
console_out_write(c)
else:
console_out_write(b"[%02x]" % ord(c))
def do_repl(pyb, args):
capture_file = None
code_to_inject = None
file_to_inject = None
while len(args):
if args[0] == "--capture":
args.pop(0)
capture_file = args.pop(0)
elif args[0] == "--inject-code":
args.pop(0)
code_to_inject = bytes(args.pop(0).replace("\\n", "\r\n"), "utf8")
elif args[0] == "--inject-file":
args.pop(0)
file_to_inject = args.pop(0)
else:
break
print("Connected to MicroPython at %s" % pyb.device_name)
print("Use Ctrl-] to exit this shell")
if capture_file is not None:
print('Capturing session to file "%s"' % capture_file)
capture_file = open(capture_file, "wb")
if code_to_inject is not None:
print("Use Ctrl-J to inject", code_to_inject)
if file_to_inject is not None:
print('Use Ctrl-K to inject file "%s"' % file_to_inject)
console = Console()
console.enter()
def console_out_write(b):
console.write(b)
if capture_file is not None:
capture_file.write(b)
capture_file.flush()
try:
do_repl_main_loop(
pyb,
console,
console_out_write,
code_to_inject=code_to_inject,
file_to_inject=file_to_inject,
)
finally:
console.exit()
if capture_file is not None:
capture_file.close()
def execbuffer(pyb, buf, follow):
ret_val = 0
try:
pyb.exec_raw_no_follow(buf)
if follow:
ret, ret_err = pyb.follow(timeout=None, data_consumer=pyboard.stdout_write_bytes)
if ret_err:
pyboard.stdout_write_bytes(ret_err)
ret_val = 1
except pyboard.PyboardError as er:
print(er)
ret_val = 1
except KeyboardInterrupt:
ret_val = 1
return ret_val
def main():
config = load_user_config()
prepare_command_expansions(config)
args = sys.argv[1:]
pyb = None
did_action = False
try:
while args:
do_command_expansion(args)
cmds = {
"connect": (False, False, 1),
"disconnect": (False, False, 0),
"mount": (True, False, 1),
"repl": (False, True, 0),
"eval": (True, True, 1),
"exec": (True, True, 1),
"run": (True, True, 1),
"fs": (True, True, 1),
}
cmd = args.pop(0)
try:
need_raw_repl, is_action, num_args_min = cmds[cmd]
except KeyError:
print(f"{_PROG}: '{cmd}' is not a command")
return 1
if len(args) < num_args_min:
print(f"{_PROG}: '{cmd}' neads at least {num_args_min} argument(s)")
return 1
if cmd == "connect":
if pyb is not None:
do_disconnect(pyb)
pyb = do_connect(args)
if pyb is None:
did_action = True
continue
if pyb is None:
pyb = do_connect(["auto"])
if need_raw_repl:
if not pyb.in_raw_repl:
pyb.enter_raw_repl()
else:
if pyb.in_raw_repl:
pyb.exit_raw_repl()
if is_action:
did_action = True
if cmd == "disconnect":
do_disconnect(pyb)
pyb = None
elif cmd == "mount":
path = args.pop(0)
pyb.mount_local(path)
print(f"Local directory {path} is mounted at /remote")
elif cmd in ("exec", "eval", "run"):
follow = True
if args[0] == "--no-follow":
args.pop(0)
follow = False
if cmd == "exec":
buf = args.pop(0)
elif cmd == "eval":
buf = "print(" + args.pop(0) + ")"
else:
filename = args.pop(0)
try:
with open(filename, "rb") as f:
buf = f.read()
except OSError:
print(f"{_PROG}: could not read file '{filename}'")
return 1
ret = execbuffer(pyb, buf, follow)
if ret:
return ret
elif cmd == "fs":
do_filesystem(pyb, args)
elif cmd == "repl":
do_repl(pyb, args)
if not did_action:
if pyb is None:
pyb = do_connect(["auto"])
if pyb.in_raw_repl:
pyb.exit_raw_repl()
do_repl(pyb, args)
finally:
if pyb is not None:
do_disconnect(pyb)
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/mpremote/mpremote/main.py | Python | apache-2.0 | 15,680 |
import io, os, re, serial, struct, time
from errno import EPERM
from .console import VT_ENABLED
try:
from .pyboard import Pyboard, PyboardError, stdout_write_bytes, filesystem_command
except ImportError:
import sys
sys.path.append(os.path.dirname(__file__) + "/../..")
from pyboard import Pyboard, PyboardError, stdout_write_bytes, filesystem_command
fs_hook_cmds = {
"CMD_STAT": 1,
"CMD_ILISTDIR_START": 2,
"CMD_ILISTDIR_NEXT": 3,
"CMD_OPEN": 4,
"CMD_CLOSE": 5,
"CMD_READ": 6,
"CMD_WRITE": 7,
"CMD_SEEK": 8,
"CMD_REMOVE": 9,
"CMD_RENAME": 10,
}
fs_hook_code = """\
import uos, uio, ustruct, micropython
SEEK_SET = 0
class RemoteCommand:
def __init__(self):
import uselect, usys
self.buf4 = bytearray(4)
self.fout = usys.stdout.buffer
self.fin = usys.stdin.buffer
self.poller = uselect.poll()
self.poller.register(self.fin, uselect.POLLIN)
def poll_in(self):
for _ in self.poller.ipoll(1000):
return
self.end()
raise Exception('timeout waiting for remote')
def rd(self, n):
buf = bytearray(n)
self.rd_into(buf, n)
return buf
def rd_into(self, buf, n):
# implement reading with a timeout in case other side disappears
if n == 0:
return
self.poll_in()
r = self.fin.readinto(buf, n)
if r < n:
mv = memoryview(buf)
while r < n:
self.poll_in()
r += self.fin.readinto(mv[r:], n - r)
def begin(self, type):
micropython.kbd_intr(-1)
buf4 = self.buf4
buf4[0] = 0x18
buf4[1] = type
self.fout.write(buf4, 2)
# Wait for sync byte 0x18, but don't get stuck forever
for i in range(30):
self.poller.poll(1000)
self.fin.readinto(buf4, 1)
if buf4[0] == 0x18:
break
def end(self):
micropython.kbd_intr(3)
def rd_s8(self):
self.rd_into(self.buf4, 1)
n = self.buf4[0]
if n & 0x80:
n -= 0x100
return n
def rd_s32(self):
buf4 = self.buf4
self.rd_into(buf4, 4)
n = buf4[0] | buf4[1] << 8 | buf4[2] << 16 | buf4[3] << 24
if buf4[3] & 0x80:
n -= 0x100000000
return n
def rd_u32(self):
buf4 = self.buf4
self.rd_into(buf4, 4)
return buf4[0] | buf4[1] << 8 | buf4[2] << 16 | buf4[3] << 24
def rd_bytes(self, buf):
# TODO if n is large (eg >256) then we may miss bytes on stdin
n = self.rd_s32()
if buf is None:
ret = buf = bytearray(n)
else:
ret = n
self.rd_into(buf, n)
return ret
def rd_str(self):
n = self.rd_s32()
if n == 0:
return ''
else:
return str(self.rd(n), 'utf8')
def wr_s8(self, i):
self.buf4[0] = i
self.fout.write(self.buf4, 1)
def wr_s32(self, i):
ustruct.pack_into('<i', self.buf4, 0, i)
self.fout.write(self.buf4)
def wr_bytes(self, b):
self.wr_s32(len(b))
self.fout.write(b)
# str and bytes act the same in MicroPython
wr_str = wr_bytes
class RemoteFile(uio.IOBase):
def __init__(self, cmd, fd, is_text):
self.cmd = cmd
self.fd = fd
self.is_text = is_text
def __enter__(self):
return self
def __exit__(self, a, b, c):
self.close()
def ioctl(self, request, arg):
if request == 4: # CLOSE
self.close()
return 0
def flush(self):
pass
def close(self):
if self.fd is None:
return
c = self.cmd
c.begin(CMD_CLOSE)
c.wr_s8(self.fd)
c.end()
self.fd = None
def read(self, n=-1):
c = self.cmd
c.begin(CMD_READ)
c.wr_s8(self.fd)
c.wr_s32(n)
data = c.rd_bytes(None)
c.end()
if self.is_text:
data = str(data, 'utf8')
else:
data = bytes(data)
return data
def readinto(self, buf):
c = self.cmd
c.begin(CMD_READ)
c.wr_s8(self.fd)
c.wr_s32(len(buf))
n = c.rd_bytes(buf)
c.end()
return n
def readline(self):
l = ''
while 1:
c = self.read(1)
l += c
if c == '\\n' or c == '':
return l
def readlines(self):
ls = []
while 1:
l = self.readline()
if not l:
return ls
ls.append(l)
def write(self, buf):
c = self.cmd
c.begin(CMD_WRITE)
c.wr_s8(self.fd)
c.wr_bytes(buf)
n = c.rd_s32()
c.end()
return n
def seek(self, n, whence=SEEK_SET):
c = self.cmd
c.begin(CMD_SEEK)
c.wr_s8(self.fd)
c.wr_s32(n)
c.wr_s8(whence)
n = c.rd_s32()
c.end()
if n < 0:
raise OSError(n)
return n
class RemoteFS:
def __init__(self, cmd):
self.cmd = cmd
def mount(self, readonly, mkfs):
pass
def umount(self):
pass
def chdir(self, path):
if not path.startswith("/"):
path = self.path + path
if not path.endswith("/"):
path += "/"
if path != "/":
self.stat(path)
self.path = path
def getcwd(self):
return self.path
def remove(self, path):
c = self.cmd
c.begin(CMD_REMOVE)
c.wr_str(self.path + path)
res = c.rd_s32()
c.end()
if res < 0:
raise OSError(-res)
def rename(self, old, new):
c = self.cmd
c.begin(CMD_RENAME)
c.wr_str(self.path + old)
c.wr_str(self.path + new)
res = c.rd_s32()
c.end()
if res < 0:
raise OSError(-res)
def stat(self, path):
c = self.cmd
c.begin(CMD_STAT)
c.wr_str(self.path + path)
res = c.rd_s8()
if res < 0:
c.end()
raise OSError(-res)
mode = c.rd_u32()
size = c.rd_u32()
atime = c.rd_u32()
mtime = c.rd_u32()
ctime = c.rd_u32()
c.end()
return mode, 0, 0, 0, 0, 0, size, atime, mtime, ctime
def ilistdir(self, path):
c = self.cmd
c.begin(CMD_ILISTDIR_START)
c.wr_str(self.path + path)
res = c.rd_s8()
c.end()
if res < 0:
raise OSError(-res)
def next():
while True:
c.begin(CMD_ILISTDIR_NEXT)
name = c.rd_str()
if name:
type = c.rd_u32()
c.end()
yield (name, type, 0)
else:
c.end()
break
return next()
def open(self, path, mode):
c = self.cmd
c.begin(CMD_OPEN)
c.wr_str(self.path + path)
c.wr_str(mode)
fd = c.rd_s8()
c.end()
if fd < 0:
raise OSError(-fd)
return RemoteFile(c, fd, mode.find('b') == -1)
def __mount():
uos.mount(RemoteFS(RemoteCommand()), '/remote')
uos.chdir('/remote')
"""
# Apply basic compression on hook code.
for key, value in fs_hook_cmds.items():
fs_hook_code = re.sub(key, str(value), fs_hook_code)
fs_hook_code = re.sub(" *#.*$", "", fs_hook_code, flags=re.MULTILINE)
fs_hook_code = re.sub("\n\n+", "\n", fs_hook_code)
fs_hook_code = re.sub(" ", " ", fs_hook_code)
fs_hook_code = re.sub("rd_", "r", fs_hook_code)
fs_hook_code = re.sub("wr_", "w", fs_hook_code)
fs_hook_code = re.sub("buf4", "b4", fs_hook_code)
class PyboardCommand:
def __init__(self, fin, fout, path):
self.fin = fin
self.fout = fout
self.root = path + "/"
self.data_ilistdir = ["", []]
self.data_files = []
def rd_s8(self):
return struct.unpack("<b", self.fin.read(1))[0]
def rd_s32(self):
return struct.unpack("<i", self.fin.read(4))[0]
def rd_bytes(self):
n = self.rd_s32()
return self.fin.read(n)
def rd_str(self):
n = self.rd_s32()
if n == 0:
return ""
else:
return str(self.fin.read(n), "utf8")
def wr_s8(self, i):
self.fout.write(struct.pack("<b", i))
def wr_s32(self, i):
self.fout.write(struct.pack("<i", i))
def wr_u32(self, i):
self.fout.write(struct.pack("<I", i))
def wr_bytes(self, b):
self.wr_s32(len(b))
self.fout.write(b)
def wr_str(self, s):
b = bytes(s, "utf8")
self.wr_s32(len(b))
self.fout.write(b)
def log_cmd(self, msg):
print(f"[{msg}]", end="\r\n")
def path_check(self, path):
parent = os.path.realpath(self.root)
child = os.path.realpath(path)
if parent != os.path.commonpath([parent, child]):
raise OSError(EPERM, "") # File is outside mounted dir
def do_stat(self):
path = self.root + self.rd_str()
# self.log_cmd(f"stat {path}")
try:
self.path_check(path)
stat = os.stat(path)
except OSError as er:
self.wr_s8(-abs(er.errno))
else:
self.wr_s8(0)
# Note: st_ino would need to be 64-bit if added here
self.wr_u32(stat.st_mode)
self.wr_u32(stat.st_size)
self.wr_u32(int(stat.st_atime))
self.wr_u32(int(stat.st_mtime))
self.wr_u32(int(stat.st_ctime))
def do_ilistdir_start(self):
path = self.root + self.rd_str()
try:
self.path_check(path)
self.wr_s8(0)
except OSError as er:
self.wr_s8(-abs(er.errno))
else:
self.data_ilistdir[0] = path
self.data_ilistdir[1] = os.listdir(path)
def do_ilistdir_next(self):
if self.data_ilistdir[1]:
entry = self.data_ilistdir[1].pop(0)
try:
stat = os.lstat(self.data_ilistdir[0] + "/" + entry)
mode = stat.st_mode & 0xC000
except OSError as er:
mode = 0
self.wr_str(entry)
self.wr_u32(mode)
else:
self.wr_str("")
def do_open(self):
path = self.root + self.rd_str()
mode = self.rd_str()
# self.log_cmd(f"open {path} {mode}")
try:
self.path_check(path)
f = open(path, mode)
except OSError as er:
self.wr_s8(-abs(er.errno))
else:
is_text = mode.find("b") == -1
try:
fd = self.data_files.index(None)
self.data_files[fd] = (f, is_text)
except ValueError:
fd = len(self.data_files)
self.data_files.append((f, is_text))
self.wr_s8(fd)
def do_close(self):
fd = self.rd_s8()
# self.log_cmd(f"close {fd}")
self.data_files[fd][0].close()
self.data_files[fd] = None
def do_read(self):
fd = self.rd_s8()
n = self.rd_s32()
buf = self.data_files[fd][0].read(n)
if self.data_files[fd][1]:
buf = bytes(buf, "utf8")
self.wr_bytes(buf)
# self.log_cmd(f"read {fd} {n} -> {len(buf)}")
def do_seek(self):
fd = self.rd_s8()
n = self.rd_s32()
whence = self.rd_s8()
# self.log_cmd(f"seek {fd} {n}")
try:
n = self.data_files[fd][0].seek(n, whence)
except io.UnsupportedOperation:
n = -1
self.wr_s32(n)
def do_write(self):
fd = self.rd_s8()
buf = self.rd_bytes()
if self.data_files[fd][1]:
buf = str(buf, "utf8")
n = self.data_files[fd][0].write(buf)
self.wr_s32(n)
# self.log_cmd(f"write {fd} {len(buf)} -> {n}")
def do_remove(self):
path = self.root + self.rd_str()
# self.log_cmd(f"remove {path}")
try:
self.path_check(path)
os.remove(path)
ret = 0
except OSError as er:
ret = -abs(er.errno)
self.wr_s32(ret)
def do_rename(self):
old = self.root + self.rd_str()
new = self.root + self.rd_str()
# self.log_cmd(f"rename {old} {new}")
try:
self.path_check(old)
self.path_check(new)
os.rename(old, new)
ret = 0
except OSError as er:
ret = -abs(er.errno)
self.wr_s32(ret)
cmd_table = {
fs_hook_cmds["CMD_STAT"]: do_stat,
fs_hook_cmds["CMD_ILISTDIR_START"]: do_ilistdir_start,
fs_hook_cmds["CMD_ILISTDIR_NEXT"]: do_ilistdir_next,
fs_hook_cmds["CMD_OPEN"]: do_open,
fs_hook_cmds["CMD_CLOSE"]: do_close,
fs_hook_cmds["CMD_READ"]: do_read,
fs_hook_cmds["CMD_WRITE"]: do_write,
fs_hook_cmds["CMD_SEEK"]: do_seek,
fs_hook_cmds["CMD_REMOVE"]: do_remove,
fs_hook_cmds["CMD_RENAME"]: do_rename,
}
class SerialIntercept:
def __init__(self, serial, cmd):
self.orig_serial = serial
self.cmd = cmd
self.buf = b""
self.orig_serial.timeout = 5.0
def _check_input(self, blocking):
if blocking or self.orig_serial.inWaiting() > 0:
c = self.orig_serial.read(1)
if c == b"\x18":
# a special command
c = self.orig_serial.read(1)[0]
self.orig_serial.write(b"\x18") # Acknowledge command
PyboardCommand.cmd_table[c](self.cmd)
elif not VT_ENABLED and c == b"\x1b":
# ESC code, ignore these on windows
esctype = self.orig_serial.read(1)
if esctype == b"[": # CSI
while not (0x40 < self.orig_serial.read(1)[0] < 0x7E):
# Looking for "final byte" of escape sequence
pass
else:
self.buf += c
@property
def fd(self):
return self.orig_serial.fd
def close(self):
self.orig_serial.close()
def inWaiting(self):
self._check_input(False)
return len(self.buf)
def read(self, n):
while len(self.buf) < n:
self._check_input(True)
out = self.buf[:n]
self.buf = self.buf[n:]
return out
def write(self, buf):
self.orig_serial.write(buf)
class PyboardExtended(Pyboard):
def __init__(self, dev, *args, **kwargs):
super().__init__(dev, *args, **kwargs)
self.device_name = dev
self.mounted = False
def mount_local(self, path):
fout = self.serial
self.mounted = True
if self.eval('"RemoteFS" in globals()') == b"False":
self.exec_(fs_hook_code)
self.exec_("__mount()")
self.cmd = PyboardCommand(self.serial, fout, path)
self.serial = SerialIntercept(self.serial, self.cmd)
def soft_reset_with_mount(self, out_callback):
self.serial.write(b"\x04")
if not self.mounted:
return
# Wait for a response to the soft-reset command.
for i in range(10):
if self.serial.inWaiting():
break
time.sleep(0.05)
else:
# Device didn't respond so it wasn't in a state to do a soft reset.
return
out_callback(self.serial.read(1))
self.serial = self.serial.orig_serial
n = self.serial.inWaiting()
while n > 0:
buf = self.serial.read(n)
out_callback(buf)
time.sleep(0.1)
n = self.serial.inWaiting()
self.serial.write(b"\x01")
self.exec_(fs_hook_code)
self.exec_("__mount()")
self.exit_raw_repl()
self.read_until(4, b">>> ")
self.serial = SerialIntercept(self.serial, self.cmd)
def umount_local(self):
if self.mounted:
self.exec_('uos.umount("/remote")')
self.mounted = False
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/mpremote/mpremote/pyboardextended.py | Python | apache-2.0 | 16,259 |
#!/usr/bin/env python3
#
# This file is part of the MicroPython project, http://micropython.org/
#
# The MIT License (MIT)
#
# Copyright (c) 2016-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.
# Python 2/3 compatibility code
from __future__ import print_function
import platform
if platform.python_version_tuple()[0] == "2":
str_cons = lambda val, enc=None: val
bytes_cons = lambda val, enc=None: bytearray(val)
is_str_type = lambda o: type(o) is str
is_bytes_type = lambda o: type(o) is bytearray
is_int_type = lambda o: type(o) is int or type(o) is long
else:
str_cons = str
bytes_cons = bytes
is_str_type = lambda o: type(o) is str
is_bytes_type = lambda o: type(o) is bytes
is_int_type = lambda o: type(o) is int
# end compatibility code
import sys
import struct
from collections import namedtuple
sys.path.append(sys.path[0] + "/../py")
import makeqstrdata as qstrutil
class FreezeError(Exception):
def __init__(self, rawcode, msg):
self.rawcode = rawcode
self.msg = msg
def __str__(self):
return "error while freezing %s: %s" % (self.rawcode.source_file, self.msg)
class Config:
MPY_VERSION = 5
MICROPY_LONGINT_IMPL_NONE = 0
MICROPY_LONGINT_IMPL_LONGLONG = 1
MICROPY_LONGINT_IMPL_MPZ = 2
config = Config()
class QStrType:
def __init__(self, str):
self.str = str
self.qstr_esc = qstrutil.qstr_escape(self.str)
self.qstr_id = "MP_QSTR_" + self.qstr_esc
# Initialise global list of qstrs with static qstrs
global_qstrs = [None] # MP_QSTRnull should never be referenced
for n in qstrutil.static_qstr_list:
global_qstrs.append(QStrType(n))
class QStrWindow:
def __init__(self, size):
self.window = []
self.size = size
def push(self, val):
self.window = [val] + self.window[: self.size - 1]
def access(self, idx):
val = self.window[idx]
self.window = [val] + self.window[:idx] + self.window[idx + 1 :]
return val
MP_CODE_BYTECODE = 2
MP_CODE_NATIVE_PY = 3
MP_CODE_NATIVE_VIPER = 4
MP_CODE_NATIVE_ASM = 5
MP_NATIVE_ARCH_NONE = 0
MP_NATIVE_ARCH_X86 = 1
MP_NATIVE_ARCH_X64 = 2
MP_NATIVE_ARCH_ARMV6 = 3
MP_NATIVE_ARCH_ARMV6M = 4
MP_NATIVE_ARCH_ARMV7M = 5
MP_NATIVE_ARCH_ARMV7EM = 6
MP_NATIVE_ARCH_ARMV7EMSP = 7
MP_NATIVE_ARCH_ARMV7EMDP = 8
MP_NATIVE_ARCH_XTENSA = 9
MP_NATIVE_ARCH_XTENSAWIN = 10
MP_BC_MASK_EXTRA_BYTE = 0x9E
MP_BC_FORMAT_BYTE = 0
MP_BC_FORMAT_QSTR = 1
MP_BC_FORMAT_VAR_UINT = 2
MP_BC_FORMAT_OFFSET = 3
# extra byte if caching enabled:
MP_BC_LOAD_NAME = 0x11
MP_BC_LOAD_GLOBAL = 0x12
MP_BC_LOAD_ATTR = 0x13
MP_BC_STORE_ATTR = 0x18
# this function mirrors that in py/bc.c
def mp_opcode_format(bytecode, ip, count_var_uint):
opcode = bytecode[ip]
ip_start = ip
f = (0x000003A4 >> (2 * ((opcode) >> 4))) & 3
if f == MP_BC_FORMAT_QSTR:
if config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE:
if (
opcode == MP_BC_LOAD_NAME
or opcode == MP_BC_LOAD_GLOBAL
or opcode == MP_BC_LOAD_ATTR
or opcode == MP_BC_STORE_ATTR
):
ip += 1
ip += 3
else:
extra_byte = (opcode & MP_BC_MASK_EXTRA_BYTE) == 0
ip += 1
if f == MP_BC_FORMAT_VAR_UINT:
if count_var_uint:
while bytecode[ip] & 0x80 != 0:
ip += 1
ip += 1
elif f == MP_BC_FORMAT_OFFSET:
ip += 2
ip += extra_byte
return f, ip - ip_start
def read_prelude_sig(read_byte):
z = read_byte()
# xSSSSEAA
S = (z >> 3) & 0xF
E = (z >> 2) & 0x1
F = 0
A = z & 0x3
K = 0
D = 0
n = 0
while z & 0x80:
z = read_byte()
# xFSSKAED
S |= (z & 0x30) << (2 * n)
E |= (z & 0x02) << n
F |= ((z & 0x40) >> 6) << n
A |= (z & 0x4) << n
K |= ((z & 0x08) >> 3) << n
D |= (z & 0x1) << n
n += 1
S += 1
return S, E, F, A, K, D
def read_prelude_size(read_byte):
I = 0
C = 0
n = 0
while True:
z = read_byte()
# xIIIIIIC
I |= ((z & 0x7E) >> 1) << (6 * n)
C |= (z & 1) << n
if not (z & 0x80):
break
n += 1
return I, C
def extract_prelude(bytecode, ip):
def local_read_byte():
b = bytecode[ip_ref[0]]
ip_ref[0] += 1
return b
ip_ref = [ip] # to close over ip in Python 2 and 3
(
n_state,
n_exc_stack,
scope_flags,
n_pos_args,
n_kwonly_args,
n_def_pos_args,
) = read_prelude_sig(local_read_byte)
n_info, n_cell = read_prelude_size(local_read_byte)
ip = ip_ref[0]
ip2 = ip
ip = ip2 + n_info + n_cell
# ip now points to first opcode
# ip2 points to simple_name qstr
return ip, ip2, (n_state, n_exc_stack, scope_flags, n_pos_args, n_kwonly_args, n_def_pos_args)
class MPFunTable:
pass
class RawCode(object):
# a set of all escaped names, to make sure they are unique
escaped_names = set()
# convert code kind number to string
code_kind_str = {
MP_CODE_BYTECODE: "MP_CODE_BYTECODE",
MP_CODE_NATIVE_PY: "MP_CODE_NATIVE_PY",
MP_CODE_NATIVE_VIPER: "MP_CODE_NATIVE_VIPER",
MP_CODE_NATIVE_ASM: "MP_CODE_NATIVE_ASM",
}
def __init__(self, code_kind, bytecode, prelude_offset, qstrs, objs, raw_codes):
# set core variables
self.code_kind = code_kind
self.bytecode = bytecode
self.prelude_offset = prelude_offset
self.qstrs = qstrs
self.objs = objs
self.raw_codes = raw_codes
if self.prelude_offset is None:
# no prelude, assign a dummy simple_name
self.prelude_offset = 0
self.simple_name = global_qstrs[1]
else:
# extract prelude
self.ip, self.ip2, self.prelude = extract_prelude(self.bytecode, self.prelude_offset)
self.simple_name = self._unpack_qstr(self.ip2)
self.source_file = self._unpack_qstr(self.ip2 + 2)
self.line_info_offset = self.ip2 + 4
def _unpack_qstr(self, ip):
qst = self.bytecode[ip] | self.bytecode[ip + 1] << 8
return global_qstrs[qst]
def dump(self):
# dump children first
for rc in self.raw_codes:
rc.freeze("")
# TODO
def freeze_children(self, parent_name):
self.escaped_name = parent_name + self.simple_name.qstr_esc
# make sure the escaped name is unique
i = 2
while self.escaped_name in RawCode.escaped_names:
self.escaped_name = parent_name + self.simple_name.qstr_esc + str(i)
i += 1
RawCode.escaped_names.add(self.escaped_name)
# emit children first
for rc in self.raw_codes:
rc.freeze(self.escaped_name + "_")
def freeze_constants(self):
# generate constant objects
for i, obj in enumerate(self.objs):
obj_name = "const_obj_%s_%u" % (self.escaped_name, i)
if obj is MPFunTable:
pass
elif obj is Ellipsis:
print("#define %s mp_const_ellipsis_obj" % obj_name)
elif is_str_type(obj) or is_bytes_type(obj):
if is_str_type(obj):
obj = bytes_cons(obj, "utf8")
obj_type = "mp_type_str"
else:
obj_type = "mp_type_bytes"
print(
'STATIC const mp_obj_str_t %s = {{&%s}, %u, %u, (const byte*)"%s"};'
% (
obj_name,
obj_type,
qstrutil.compute_hash(obj, config.MICROPY_QSTR_BYTES_IN_HASH),
len(obj),
"".join(("\\x%02x" % b) for b in obj),
)
)
elif is_int_type(obj):
if config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_NONE:
# TODO check if we can actually fit this long-int into a small-int
raise FreezeError(self, "target does not support long int")
elif config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_LONGLONG:
# TODO
raise FreezeError(self, "freezing int to long-long is not implemented")
elif config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_MPZ:
neg = 0
if obj < 0:
obj = -obj
neg = 1
bits_per_dig = config.MPZ_DIG_SIZE
digs = []
z = obj
while z:
digs.append(z & ((1 << bits_per_dig) - 1))
z >>= bits_per_dig
ndigs = len(digs)
digs = ",".join(("%#x" % d) for d in digs)
print(
"STATIC const mp_obj_int_t %s = {{&mp_type_int}, "
"{.neg=%u, .fixed_dig=1, .alloc=%u, .len=%u, .dig=(uint%u_t*)(const uint%u_t[]){%s}}};"
% (obj_name, neg, ndigs, ndigs, bits_per_dig, bits_per_dig, digs)
)
elif type(obj) is float:
print(
"#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B"
)
print(
"STATIC const mp_obj_float_t %s = {{&mp_type_float}, (mp_float_t)%.16g};"
% (obj_name, obj)
)
print("#endif")
elif type(obj) is complex:
print(
"STATIC const mp_obj_complex_t %s = {{&mp_type_complex}, (mp_float_t)%.16g, (mp_float_t)%.16g};"
% (obj_name, obj.real, obj.imag)
)
else:
raise FreezeError(self, "freezing of object %r is not implemented" % (obj,))
# generate constant table, if it has any entries
const_table_len = len(self.qstrs) + len(self.objs) + len(self.raw_codes)
if const_table_len:
print(
"STATIC const mp_rom_obj_t const_table_data_%s[%u] = {"
% (self.escaped_name, const_table_len)
)
for qst in self.qstrs:
print(" MP_ROM_QSTR(%s)," % global_qstrs[qst].qstr_id)
for i in range(len(self.objs)):
if self.objs[i] is MPFunTable:
print(" &mp_fun_table,")
elif type(self.objs[i]) is float:
print(
"#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B"
)
print(" MP_ROM_PTR(&const_obj_%s_%u)," % (self.escaped_name, i))
print("#elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C")
n = struct.unpack("<I", struct.pack("<f", self.objs[i]))[0]
n = ((n & ~0x3) | 2) + 0x80800000
print(" (mp_rom_obj_t)(0x%08x)," % (n,))
print("#elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D")
n = struct.unpack("<Q", struct.pack("<d", self.objs[i]))[0]
n += 0x8004000000000000
print(" (mp_rom_obj_t)(0x%016x)," % (n,))
print("#endif")
else:
print(" MP_ROM_PTR(&const_obj_%s_%u)," % (self.escaped_name, i))
for rc in self.raw_codes:
print(" MP_ROM_PTR(&raw_code_%s)," % rc.escaped_name)
print("};")
def freeze_module(self, qstr_links=(), type_sig=0):
# generate module
if self.simple_name.str != "<module>":
print("STATIC ", end="")
print("const mp_raw_code_t raw_code_%s = {" % self.escaped_name)
print(" .kind = %s," % RawCode.code_kind_str[self.code_kind])
print(" .scope_flags = 0x%02x," % self.prelude[2])
print(" .n_pos_args = %u," % self.prelude[3])
print(" .fun_data = fun_data_%s," % self.escaped_name)
if len(self.qstrs) + len(self.objs) + len(self.raw_codes):
print(" .const_table = (mp_uint_t*)const_table_data_%s," % self.escaped_name)
else:
print(" .const_table = NULL,")
print(" #if MICROPY_PERSISTENT_CODE_SAVE")
print(" .fun_data_len = %u," % len(self.bytecode))
print(" .n_obj = %u," % len(self.objs))
print(" .n_raw_code = %u," % len(self.raw_codes))
if self.code_kind == MP_CODE_BYTECODE:
print(" #if MICROPY_PY_SYS_SETTRACE")
print(" .prelude = {")
print(" .n_state = %u," % self.prelude[0])
print(" .n_exc_stack = %u," % self.prelude[1])
print(" .scope_flags = %u," % self.prelude[2])
print(" .n_pos_args = %u," % self.prelude[3])
print(" .n_kwonly_args = %u," % self.prelude[4])
print(" .n_def_pos_args = %u," % self.prelude[5])
print(" .qstr_block_name = %s," % self.simple_name.qstr_id)
print(" .qstr_source_file = %s," % self.source_file.qstr_id)
print(
" .line_info = fun_data_%s + %u,"
% (self.escaped_name, self.line_info_offset)
)
print(" .opcodes = fun_data_%s + %u," % (self.escaped_name, self.ip))
print(" },")
print(" .line_of_definition = %u," % 0) # TODO
print(" #endif")
print(" #if MICROPY_EMIT_MACHINE_CODE")
print(" .prelude_offset = %u," % self.prelude_offset)
print(" .n_qstr = %u," % len(qstr_links))
print(" .qstr_link = NULL,") # TODO
print(" #endif")
print(" #endif")
print(" #if MICROPY_EMIT_MACHINE_CODE")
print(" .type_sig = %u," % type_sig)
print(" #endif")
print("};")
class RawCodeBytecode(RawCode):
def __init__(self, bytecode, qstrs, objs, raw_codes):
super(RawCodeBytecode, self).__init__(
MP_CODE_BYTECODE, bytecode, 0, qstrs, objs, raw_codes
)
def freeze(self, parent_name):
self.freeze_children(parent_name)
# generate bytecode data
print()
print(
"// frozen bytecode for file %s, scope %s%s"
% (self.source_file.str, parent_name, self.simple_name.str)
)
print("STATIC ", end="")
if not config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE:
print("const ", end="")
print("byte fun_data_%s[%u] = {" % (self.escaped_name, len(self.bytecode)))
print(" ", end="")
for i in range(self.ip2):
print(" 0x%02x," % self.bytecode[i], end="")
print()
print(" ", self.simple_name.qstr_id, "& 0xff,", self.simple_name.qstr_id, ">> 8,")
print(" ", self.source_file.qstr_id, "& 0xff,", self.source_file.qstr_id, ">> 8,")
print(" ", end="")
for i in range(self.ip2 + 4, self.ip):
print(" 0x%02x," % self.bytecode[i], end="")
print()
ip = self.ip
while ip < len(self.bytecode):
f, sz = mp_opcode_format(self.bytecode, ip, True)
if f == 1:
qst = self._unpack_qstr(ip + 1).qstr_id
extra = "" if sz == 3 else " 0x%02x," % self.bytecode[ip + 3]
print(" ", "0x%02x," % self.bytecode[ip], qst, "& 0xff,", qst, ">> 8,", extra)
else:
print(" ", "".join("0x%02x, " % self.bytecode[ip + i] for i in range(sz)))
ip += sz
print("};")
self.freeze_constants()
self.freeze_module()
class RawCodeNative(RawCode):
def __init__(
self,
code_kind,
fun_data,
prelude_offset,
prelude,
qstr_links,
qstrs,
objs,
raw_codes,
type_sig,
):
super(RawCodeNative, self).__init__(
code_kind, fun_data, prelude_offset, qstrs, objs, raw_codes
)
self.prelude = prelude
self.qstr_links = qstr_links
self.type_sig = type_sig
if config.native_arch in (
MP_NATIVE_ARCH_X86,
MP_NATIVE_ARCH_X64,
MP_NATIVE_ARCH_XTENSA,
MP_NATIVE_ARCH_XTENSAWIN,
):
self.fun_data_attributes = '__attribute__((section(".text,\\"ax\\",@progbits # ")))'
else:
self.fun_data_attributes = '__attribute__((section(".text,\\"ax\\",%progbits @ ")))'
# Allow single-byte alignment by default for x86/x64.
# ARM needs word alignment, ARM Thumb needs halfword, due to instruction size.
# Xtensa needs word alignment due to the 32-bit constant table embedded in the code.
if config.native_arch in (
MP_NATIVE_ARCH_ARMV6,
MP_NATIVE_ARCH_XTENSA,
MP_NATIVE_ARCH_XTENSAWIN,
):
# ARMV6 or Xtensa -- four byte align.
self.fun_data_attributes += " __attribute__ ((aligned (4)))"
elif MP_NATIVE_ARCH_ARMV6M <= config.native_arch <= MP_NATIVE_ARCH_ARMV7EMDP:
# ARMVxxM -- two byte align.
self.fun_data_attributes += " __attribute__ ((aligned (2)))"
def _asm_thumb_rewrite_mov(self, pc, val):
print(" (%u & 0xf0) | (%s >> 12)," % (self.bytecode[pc], val), end="")
print(" (%u & 0xfb) | (%s >> 9 & 0x04)," % (self.bytecode[pc + 1], val), end="")
print(" (%s & 0xff)," % (val,), end="")
print(" (%u & 0x07) | (%s >> 4 & 0x70)," % (self.bytecode[pc + 3], val))
def _link_qstr(self, pc, kind, qst):
if kind == 0:
# Generic 16-bit link
print(" %s & 0xff, %s >> 8," % (qst, qst))
return 2
else:
# Architecture-specific link
is_obj = kind == 2
if is_obj:
qst = "((uintptr_t)MP_OBJ_NEW_QSTR(%s))" % qst
if config.native_arch in (
MP_NATIVE_ARCH_X86,
MP_NATIVE_ARCH_X64,
MP_NATIVE_ARCH_ARMV6,
MP_NATIVE_ARCH_XTENSA,
MP_NATIVE_ARCH_XTENSAWIN,
):
print(
" %s & 0xff, (%s >> 8) & 0xff, (%s >> 16) & 0xff, %s >> 24,"
% (qst, qst, qst, qst)
)
return 4
elif MP_NATIVE_ARCH_ARMV6M <= config.native_arch <= MP_NATIVE_ARCH_ARMV7EMDP:
if is_obj:
# qstr object, movw and movt
self._asm_thumb_rewrite_mov(pc, qst)
self._asm_thumb_rewrite_mov(pc + 4, "(%s >> 16)" % qst)
return 8
else:
# qstr number, movw instruction
self._asm_thumb_rewrite_mov(pc, qst)
return 4
else:
assert 0
def freeze(self, parent_name):
if self.prelude[2] & ~0x0F:
raise FreezeError("unable to freeze code with relocations")
self.freeze_children(parent_name)
# generate native code data
print()
if self.code_kind == MP_CODE_NATIVE_PY:
print(
"// frozen native code for file %s, scope %s%s"
% (self.source_file.str, parent_name, self.simple_name.str)
)
elif self.code_kind == MP_CODE_NATIVE_VIPER:
print("// frozen viper code for scope %s" % (parent_name,))
else:
print("// frozen assembler code for scope %s" % (parent_name,))
print(
"STATIC const byte fun_data_%s[%u] %s = {"
% (self.escaped_name, len(self.bytecode), self.fun_data_attributes)
)
if self.code_kind == MP_CODE_NATIVE_PY:
i_top = self.prelude_offset
else:
i_top = len(self.bytecode)
i = 0
qi = 0
while i < i_top:
if qi < len(self.qstr_links) and i == self.qstr_links[qi][0]:
# link qstr
qi_off, qi_kind, qi_val = self.qstr_links[qi]
qst = global_qstrs[qi_val].qstr_id
i += self._link_qstr(i, qi_kind, qst)
qi += 1
else:
# copy machine code (max 16 bytes)
i16 = min(i + 16, i_top)
if qi < len(self.qstr_links):
i16 = min(i16, self.qstr_links[qi][0])
print(" ", end="")
for ii in range(i, i16):
print(" 0x%02x," % self.bytecode[ii], end="")
print()
i = i16
if self.code_kind == MP_CODE_NATIVE_PY:
print(" ", end="")
for i in range(self.prelude_offset, self.ip2):
print(" 0x%02x," % self.bytecode[i], end="")
print()
print(" ", self.simple_name.qstr_id, "& 0xff,", self.simple_name.qstr_id, ">> 8,")
print(" ", self.source_file.qstr_id, "& 0xff,", self.source_file.qstr_id, ">> 8,")
print(" ", end="")
for i in range(self.ip2 + 4, self.ip):
print(" 0x%02x," % self.bytecode[i], end="")
print()
print("};")
self.freeze_constants()
self.freeze_module(self.qstr_links, self.type_sig)
class BytecodeBuffer:
def __init__(self, size):
self.buf = bytearray(size)
self.idx = 0
def is_full(self):
return self.idx == len(self.buf)
def append(self, b):
self.buf[self.idx] = b
self.idx += 1
def read_byte(f, out=None):
b = bytes_cons(f.read(1))[0]
if out is not None:
out.append(b)
return b
def read_uint(f, out=None):
i = 0
while True:
b = read_byte(f, out)
i = (i << 7) | (b & 0x7F)
if b & 0x80 == 0:
break
return i
def read_qstr(f, qstr_win):
ln = read_uint(f)
if ln == 0:
# static qstr
return bytes_cons(f.read(1))[0]
if ln & 1:
# qstr in table
return qstr_win.access(ln >> 1)
ln >>= 1
data = str_cons(f.read(ln), "utf8")
global_qstrs.append(QStrType(data))
qstr_win.push(len(global_qstrs) - 1)
return len(global_qstrs) - 1
def read_obj(f):
obj_type = f.read(1)
if obj_type == b"e":
return Ellipsis
else:
buf = f.read(read_uint(f))
if obj_type == b"s":
return str_cons(buf, "utf8")
elif obj_type == b"b":
return bytes_cons(buf)
elif obj_type == b"i":
return int(str_cons(buf, "ascii"), 10)
elif obj_type == b"f":
return float(str_cons(buf, "ascii"))
elif obj_type == b"c":
return complex(str_cons(buf, "ascii"))
else:
assert 0
def read_prelude(f, bytecode, qstr_win):
(
n_state,
n_exc_stack,
scope_flags,
n_pos_args,
n_kwonly_args,
n_def_pos_args,
) = read_prelude_sig(lambda: read_byte(f, bytecode))
n_info, n_cell = read_prelude_size(lambda: read_byte(f, bytecode))
read_qstr_and_pack(f, bytecode, qstr_win) # simple_name
read_qstr_and_pack(f, bytecode, qstr_win) # source_file
for _ in range(n_info - 4 + n_cell):
read_byte(f, bytecode)
return n_state, n_exc_stack, scope_flags, n_pos_args, n_kwonly_args, n_def_pos_args
def read_qstr_and_pack(f, bytecode, qstr_win):
qst = read_qstr(f, qstr_win)
bytecode.append(qst & 0xFF)
bytecode.append(qst >> 8)
def read_bytecode(file, bytecode, qstr_win):
while not bytecode.is_full():
op = read_byte(file, bytecode)
f, sz = mp_opcode_format(bytecode.buf, bytecode.idx - 1, False)
sz -= 1
if f == MP_BC_FORMAT_QSTR:
read_qstr_and_pack(file, bytecode, qstr_win)
sz -= 2
elif f == MP_BC_FORMAT_VAR_UINT:
while read_byte(file, bytecode) & 0x80:
pass
for _ in range(sz):
read_byte(file, bytecode)
def read_raw_code(f, qstr_win):
kind_len = read_uint(f)
kind = (kind_len & 3) + MP_CODE_BYTECODE
fun_data_len = kind_len >> 2
fun_data = BytecodeBuffer(fun_data_len)
if kind == MP_CODE_BYTECODE:
prelude = read_prelude(f, fun_data, qstr_win)
read_bytecode(f, fun_data, qstr_win)
else:
fun_data.buf[:] = f.read(fun_data_len)
qstr_links = []
if kind in (MP_CODE_NATIVE_PY, MP_CODE_NATIVE_VIPER):
# load qstr link table
n_qstr_link = read_uint(f)
for _ in range(n_qstr_link):
off = read_uint(f)
qst = read_qstr(f, qstr_win)
qstr_links.append((off >> 2, off & 3, qst))
type_sig = 0
if kind == MP_CODE_NATIVE_PY:
prelude_offset = read_uint(f)
_, name_idx, prelude = extract_prelude(fun_data.buf, prelude_offset)
fun_data.idx = name_idx # rewind to where qstrs are in prelude
read_qstr_and_pack(f, fun_data, qstr_win) # simple_name
read_qstr_and_pack(f, fun_data, qstr_win) # source_file
else:
prelude_offset = None
scope_flags = read_uint(f)
n_pos_args = 0
if kind == MP_CODE_NATIVE_ASM:
n_pos_args = read_uint(f)
type_sig = read_uint(f)
prelude = (None, None, scope_flags, n_pos_args, 0)
qstrs = []
objs = []
raw_codes = []
if kind != MP_CODE_NATIVE_ASM:
# load constant table
n_obj = read_uint(f)
n_raw_code = read_uint(f)
qstrs = [read_qstr(f, qstr_win) for _ in range(prelude[3] + prelude[4])]
if kind != MP_CODE_BYTECODE:
objs.append(MPFunTable)
objs.extend([read_obj(f) for _ in range(n_obj)])
raw_codes = [read_raw_code(f, qstr_win) for _ in range(n_raw_code)]
if kind == MP_CODE_BYTECODE:
return RawCodeBytecode(fun_data.buf, qstrs, objs, raw_codes)
else:
return RawCodeNative(
kind,
fun_data.buf,
prelude_offset,
prelude,
qstr_links,
qstrs,
objs,
raw_codes,
type_sig,
)
def read_mpy(filename):
with open(filename, "rb") as f:
header = bytes_cons(f.read(4))
if header[0] != ord("M"):
raise Exception("not a valid .mpy file")
if header[1] != config.MPY_VERSION:
raise Exception("incompatible .mpy version")
feature_byte = header[2]
qw_size = read_uint(f)
config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE = (feature_byte & 1) != 0
config.MICROPY_PY_BUILTINS_STR_UNICODE = (feature_byte & 2) != 0
mpy_native_arch = feature_byte >> 2
if mpy_native_arch != MP_NATIVE_ARCH_NONE:
if config.native_arch == MP_NATIVE_ARCH_NONE:
config.native_arch = mpy_native_arch
elif config.native_arch != mpy_native_arch:
raise Exception("native architecture mismatch")
config.mp_small_int_bits = header[3]
qstr_win = QStrWindow(qw_size)
rc = read_raw_code(f, qstr_win)
rc.mpy_source_file = filename
rc.qstr_win_size = qw_size
return rc
def dump_mpy(raw_codes):
for rc in raw_codes:
rc.dump()
def freeze_mpy(base_qstrs, raw_codes):
# add to qstrs
new = {}
for q in global_qstrs:
# don't add duplicates
if q is None or q.qstr_esc in base_qstrs or q.qstr_esc in new:
continue
new[q.qstr_esc] = (len(new), q.qstr_esc, q.str)
new = sorted(new.values(), key=lambda x: x[2])
print('#include "py/mpconfig.h"')
print('#include "py/objint.h"')
print('#include "py/objstr.h"')
print('#include "py/emitglue.h"')
print('#include "py/nativeglue.h"')
print()
print(
"#if MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE != %u"
% config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE
)
print('#error "incompatible MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE"')
print("#endif")
print()
print("#if MICROPY_LONGINT_IMPL != %u" % config.MICROPY_LONGINT_IMPL)
print('#error "incompatible MICROPY_LONGINT_IMPL"')
print("#endif")
print()
if config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_MPZ:
print("#if MPZ_DIG_SIZE != %u" % config.MPZ_DIG_SIZE)
print('#error "incompatible MPZ_DIG_SIZE"')
print("#endif")
print()
print("#if MICROPY_PY_BUILTINS_FLOAT")
print("typedef struct _mp_obj_float_t {")
print(" mp_obj_base_t base;")
print(" mp_float_t value;")
print("} mp_obj_float_t;")
print("#endif")
print()
print("#if MICROPY_PY_BUILTINS_COMPLEX")
print("typedef struct _mp_obj_complex_t {")
print(" mp_obj_base_t base;")
print(" mp_float_t real;")
print(" mp_float_t imag;")
print("} mp_obj_complex_t;")
print("#endif")
print()
if len(new) > 0:
print("enum {")
for i in range(len(new)):
if i == 0:
print(" MP_QSTR_%s = MP_QSTRnumber_of," % new[i][1])
else:
print(" MP_QSTR_%s," % new[i][1])
print("};")
# As in qstr.c, set so that the first dynamically allocated pool is twice this size; must be <= the len
qstr_pool_alloc = min(len(new), 10)
print()
print("extern const qstr_pool_t mp_qstr_const_pool;")
print("const qstr_pool_t mp_qstr_frozen_const_pool = {")
print(" (qstr_pool_t*)&mp_qstr_const_pool, // previous pool")
print(" MP_QSTRnumber_of, // previous pool size")
print(" %u, // allocated entries" % qstr_pool_alloc)
print(" %u, // used entries" % len(new))
print(" true, // entries are sorted")
print(" {")
for _, _, qstr in new:
print(
" %s,"
% qstrutil.make_bytes(
config.MICROPY_QSTR_BYTES_IN_LEN, config.MICROPY_QSTR_BYTES_IN_HASH, qstr
)
)
print(" },")
print("};")
for rc in raw_codes:
rc.freeze(rc.source_file.str.replace("/", "_")[:-3] + "_")
print()
print("const char mp_frozen_mpy_names[] = {")
for rc in raw_codes:
module_name = rc.source_file.str
print('"%s\\0"' % module_name)
print('"\\0"};')
print("const mp_raw_code_t *const mp_frozen_mpy_content[] = {")
for rc in raw_codes:
print(" &raw_code_%s," % rc.escaped_name)
print("};")
# If a port defines MICROPY_FROZEN_LIST_ITEM then list all modules wrapped in that macro.
print("#ifdef MICROPY_FROZEN_LIST_ITEM")
for rc in raw_codes:
module_name = rc.source_file.str
if module_name.endswith("/__init__.py"):
short_name = module_name[: -len("/__init__.py")]
else:
short_name = module_name[: -len(".py")]
print('MICROPY_FROZEN_LIST_ITEM("%s", "%s")' % (short_name, module_name))
print("#endif")
def merge_mpy(raw_codes, output_file):
assert len(raw_codes) <= 31 # so var-uints all fit in 1 byte
merged_mpy = bytearray()
if len(raw_codes) == 1:
with open(raw_codes[0].mpy_source_file, "rb") as f:
merged_mpy.extend(f.read())
else:
header = bytearray(5)
header[0] = ord("M")
header[1] = config.MPY_VERSION
header[2] = (
config.native_arch << 2
| config.MICROPY_PY_BUILTINS_STR_UNICODE << 1
| config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE
)
header[3] = config.mp_small_int_bits
header[4] = 32 # qstr_win_size
merged_mpy.extend(header)
bytecode = bytearray()
bytecode_len = 6 + len(raw_codes) * 5 + 2
bytecode.append(bytecode_len << 2) # kind and length
bytecode.append(0b00000000) # signature prelude
bytecode.append(0b00001000) # size prelude
bytecode.extend(b"\x00\x01") # MP_QSTR_
bytecode.extend(b"\x00\x01") # MP_QSTR_
for idx in range(len(raw_codes)):
bytecode.append(0x32) # MP_BC_MAKE_FUNCTION
bytecode.append(idx) # index raw code
bytecode.extend(b"\x34\x00\x59") # MP_BC_CALL_FUNCTION, 0 args, MP_BC_POP_TOP
bytecode.extend(b"\x51\x63") # MP_BC_LOAD_NONE, MP_BC_RETURN_VALUE
bytecode.append(0) # n_obj
bytecode.append(len(raw_codes)) # n_raw_code
merged_mpy.extend(bytecode)
for rc in raw_codes:
with open(rc.mpy_source_file, "rb") as f:
f.read(4) # skip header
read_uint(f) # skip qstr_win_size
data = f.read() # read rest of mpy file
merged_mpy.extend(data)
if output_file is None:
sys.stdout.buffer.write(merged_mpy)
else:
with open(output_file, "wb") as f:
f.write(merged_mpy)
def main():
import argparse
cmd_parser = argparse.ArgumentParser(description="A tool to work with MicroPython .mpy files.")
cmd_parser.add_argument("-d", "--dump", action="store_true", help="dump contents of files")
cmd_parser.add_argument("-f", "--freeze", action="store_true", help="freeze files")
cmd_parser.add_argument(
"--merge", action="store_true", help="merge multiple .mpy files into one"
)
cmd_parser.add_argument("-q", "--qstr-header", help="qstr header file to freeze against")
cmd_parser.add_argument(
"-mlongint-impl",
choices=["none", "longlong", "mpz"],
default="mpz",
help="long-int implementation used by target (default mpz)",
)
cmd_parser.add_argument(
"-mmpz-dig-size",
metavar="N",
type=int,
default=16,
help="mpz digit size used by target (default 16)",
)
cmd_parser.add_argument("-o", "--output", default=None, help="output file")
cmd_parser.add_argument("files", nargs="+", help="input .mpy files")
args = cmd_parser.parse_args()
# set config values relevant to target machine
config.MICROPY_LONGINT_IMPL = {
"none": config.MICROPY_LONGINT_IMPL_NONE,
"longlong": config.MICROPY_LONGINT_IMPL_LONGLONG,
"mpz": config.MICROPY_LONGINT_IMPL_MPZ,
}[args.mlongint_impl]
config.MPZ_DIG_SIZE = args.mmpz_dig_size
config.native_arch = MP_NATIVE_ARCH_NONE
# set config values for qstrs, and get the existing base set of qstrs
if args.qstr_header:
qcfgs, base_qstrs = qstrutil.parse_input_headers([args.qstr_header])
config.MICROPY_QSTR_BYTES_IN_LEN = int(qcfgs["BYTES_IN_LEN"])
config.MICROPY_QSTR_BYTES_IN_HASH = int(qcfgs["BYTES_IN_HASH"])
else:
config.MICROPY_QSTR_BYTES_IN_LEN = 1
config.MICROPY_QSTR_BYTES_IN_HASH = 1
base_qstrs = {}
raw_codes = [read_mpy(file) for file in args.files]
if args.dump:
dump_mpy(raw_codes)
elif args.freeze:
try:
freeze_mpy(base_qstrs, raw_codes)
except FreezeError as er:
print(er, file=sys.stderr)
sys.exit(1)
elif args.merge:
merged_mpy = merge_mpy(raw_codes, args.output)
if __name__ == "__main__":
main()
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/mpy-tool.py | Python | apache-2.0 | 36,613 |
#!/usr/bin/env python3
#
# This tool converts binary resource files passed on the command line
# into a Python source file containing data from these files, which can
# be accessed using standard pkg_resources.resource_stream() function
# from micropython-lib:
# https://github.com/micropython/micropython-lib/tree/master/pkg_resources
#
import sys
print("R = {")
for fname in sys.argv[1:]:
with open(fname, "rb") as f:
b = f.read()
print("%r: %r," % (fname, b))
print("}")
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/mpy_bin2res.py | Python | apache-2.0 | 497 |
#!/usr/bin/env python3
import argparse
import os
import os.path
argparser = argparse.ArgumentParser(description="Compile all .py files to .mpy recursively")
argparser.add_argument("-o", "--out", help="output directory (default: input dir)")
argparser.add_argument("--target", help="select MicroPython target config")
argparser.add_argument(
"-mcache-lookup-bc", action="store_true", help="cache map lookups in the bytecode"
)
argparser.add_argument("dir", help="input directory")
args = argparser.parse_args()
TARGET_OPTS = {
"unix": "-mcache-lookup-bc",
"baremetal": "",
}
args.dir = args.dir.rstrip("/")
if not args.out:
args.out = args.dir
path_prefix_len = len(args.dir) + 1
for path, subdirs, files in os.walk(args.dir):
for f in files:
if f.endswith(".py"):
fpath = path + "/" + f
# print(fpath)
out_fpath = args.out + "/" + fpath[path_prefix_len:-3] + ".mpy"
out_dir = os.path.dirname(out_fpath)
if not os.path.isdir(out_dir):
os.makedirs(out_dir)
cmd = "mpy-cross -v -v %s -s %s %s -o %s" % (
TARGET_OPTS.get(args.target, ""),
fpath[path_prefix_len:],
fpath,
out_fpath,
)
# print(cmd)
res = os.system(cmd)
assert res == 0
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/mpy_cross_all.py | Python | apache-2.0 | 1,364 |
#!/usr/bin/env python3
#
# 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.
"""
Link .o files to .mpy
"""
import sys, os, struct, re
from elftools.elf import elffile
sys.path.append(os.path.dirname(__file__) + "/../py")
import makeqstrdata as qstrutil
# MicroPython constants
MPY_VERSION = 5
MP_NATIVE_ARCH_X86 = 1
MP_NATIVE_ARCH_X64 = 2
MP_NATIVE_ARCH_ARMV7M = 5
MP_NATIVE_ARCH_ARMV7EMSP = 7
MP_NATIVE_ARCH_ARMV7EMDP = 8
MP_NATIVE_ARCH_XTENSA = 9
MP_NATIVE_ARCH_XTENSAWIN = 10
MP_CODE_BYTECODE = 2
MP_CODE_NATIVE_VIPER = 4
MP_SCOPE_FLAG_VIPERRELOC = 0x10
MP_SCOPE_FLAG_VIPERRODATA = 0x20
MP_SCOPE_FLAG_VIPERBSS = 0x40
MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE = 1
MICROPY_PY_BUILTINS_STR_UNICODE = 2
MP_SMALL_INT_BITS = 31
QSTR_WINDOW_SIZE = 32
# ELF constants
R_386_32 = 1
R_X86_64_64 = 1
R_XTENSA_32 = 1
R_386_PC32 = 2
R_X86_64_PC32 = 2
R_ARM_ABS32 = 2
R_386_GOT32 = 3
R_ARM_REL32 = 3
R_386_PLT32 = 4
R_X86_64_PLT32 = 4
R_XTENSA_PLT = 6
R_386_GOTOFF = 9
R_386_GOTPC = 10
R_ARM_THM_CALL = 10
R_XTENSA_DIFF32 = 19
R_XTENSA_SLOT0_OP = 20
R_ARM_BASE_PREL = 25 # aka R_ARM_GOTPC
R_ARM_GOT_BREL = 26 # aka R_ARM_GOT32
R_ARM_THM_JUMP24 = 30
R_X86_64_GOTPCREL = 9
R_X86_64_REX_GOTPCRELX = 42
R_386_GOT32X = 43
################################################################################
# Architecture configuration
def asm_jump_x86(entry):
return struct.pack("<BI", 0xE9, entry - 5)
def asm_jump_arm(entry):
b_off = entry - 4
if b_off >> 11 == 0 or b_off >> 11 == -1:
# Signed value fits in 12 bits
b0 = 0xE000 | (b_off >> 1 & 0x07FF)
b1 = 0
else:
# Use large jump
b0 = 0xF000 | (b_off >> 12 & 0x07FF)
b1 = 0xB800 | (b_off >> 1 & 0x7FF)
return struct.pack("<HH", b0, b1)
def asm_jump_xtensa(entry):
jump_offset = entry - 4
jump_op = jump_offset << 6 | 6
return struct.pack("<BH", jump_op & 0xFF, jump_op >> 8)
class ArchData:
def __init__(self, name, mpy_feature, qstr_entry_size, word_size, arch_got, asm_jump):
self.name = name
self.mpy_feature = mpy_feature
self.qstr_entry_size = qstr_entry_size
self.word_size = word_size
self.arch_got = arch_got
self.asm_jump = asm_jump
self.separate_rodata = name == "EM_XTENSA" and qstr_entry_size == 4
ARCH_DATA = {
"x86": ArchData(
"EM_386",
MP_NATIVE_ARCH_X86 << 2
| MICROPY_PY_BUILTINS_STR_UNICODE
| MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE,
2,
4,
(R_386_PC32, R_386_GOT32, R_386_GOT32X),
asm_jump_x86,
),
"x64": ArchData(
"EM_X86_64",
MP_NATIVE_ARCH_X64 << 2
| MICROPY_PY_BUILTINS_STR_UNICODE
| MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE,
2,
8,
(R_X86_64_GOTPCREL, R_X86_64_REX_GOTPCRELX),
asm_jump_x86,
),
"armv7m": ArchData(
"EM_ARM",
MP_NATIVE_ARCH_ARMV7M << 2 | MICROPY_PY_BUILTINS_STR_UNICODE,
2,
4,
(R_ARM_GOT_BREL,),
asm_jump_arm,
),
"armv7emsp": ArchData(
"EM_ARM",
MP_NATIVE_ARCH_ARMV7EMSP << 2 | MICROPY_PY_BUILTINS_STR_UNICODE,
2,
4,
(R_ARM_GOT_BREL,),
asm_jump_arm,
),
"armv7emdp": ArchData(
"EM_ARM",
MP_NATIVE_ARCH_ARMV7EMDP << 2 | MICROPY_PY_BUILTINS_STR_UNICODE,
2,
4,
(R_ARM_GOT_BREL,),
asm_jump_arm,
),
"xtensa": ArchData(
"EM_XTENSA",
MP_NATIVE_ARCH_XTENSA << 2 | MICROPY_PY_BUILTINS_STR_UNICODE,
2,
4,
(R_XTENSA_32, R_XTENSA_PLT),
asm_jump_xtensa,
),
"xtensawin": ArchData(
"EM_XTENSA",
MP_NATIVE_ARCH_XTENSAWIN << 2 | MICROPY_PY_BUILTINS_STR_UNICODE,
4,
4,
(R_XTENSA_32, R_XTENSA_PLT),
asm_jump_xtensa,
),
}
################################################################################
# Helper functions
def align_to(value, align):
return (value + align - 1) & ~(align - 1)
def unpack_u24le(data, offset):
return data[offset] | data[offset + 1] << 8 | data[offset + 2] << 16
def pack_u24le(data, offset, value):
data[offset] = value & 0xFF
data[offset + 1] = value >> 8 & 0xFF
data[offset + 2] = value >> 16 & 0xFF
def xxd(text):
for i in range(0, len(text), 16):
print("{:08x}:".format(i), end="")
for j in range(4):
off = i + j * 4
if off < len(text):
d = int.from_bytes(text[off : off + 4], "little")
print(" {:08x}".format(d), end="")
print()
# Smaller numbers are enabled first
LOG_LEVEL_1 = 1
LOG_LEVEL_2 = 2
LOG_LEVEL_3 = 3
log_level = LOG_LEVEL_1
def log(level, msg):
if level <= log_level:
print(msg)
################################################################################
# Qstr extraction
def extract_qstrs(source_files):
def read_qstrs(f):
with open(f) as f:
vals = set()
objs = set()
for line in f:
while line:
m = re.search(r"MP_OBJ_NEW_QSTR\((MP_QSTR_[A-Za-z0-9_]*)\)", line)
if m:
objs.add(m.group(1))
else:
m = re.search(r"MP_QSTR_[A-Za-z0-9_]*", line)
if m:
vals.add(m.group())
if m:
s = m.span()
line = line[: s[0]] + line[s[1] :]
else:
line = ""
return vals, objs
static_qstrs = ["MP_QSTR_" + qstrutil.qstr_escape(q) for q in qstrutil.static_qstr_list]
qstr_vals = set()
qstr_objs = set()
for f in source_files:
vals, objs = read_qstrs(f)
qstr_vals.update(vals)
qstr_objs.update(objs)
qstr_vals.difference_update(static_qstrs)
return static_qstrs, qstr_vals, qstr_objs
################################################################################
# Linker
class LinkError(Exception):
pass
class Section:
def __init__(self, name, data, alignment, filename=None):
self.filename = filename
self.name = name
self.data = data
self.alignment = alignment
self.addr = 0
self.reloc = []
@staticmethod
def from_elfsec(elfsec, filename):
assert elfsec.header.sh_addr == 0
return Section(elfsec.name, elfsec.data(), elfsec.data_alignment, filename)
class GOTEntry:
def __init__(self, name, sym, link_addr=0):
self.name = name
self.sym = sym
self.offset = None
self.link_addr = link_addr
def isexternal(self):
return self.sec_name.startswith(".external")
def istext(self):
return self.sec_name.startswith(".text")
def isrodata(self):
return self.sec_name.startswith((".rodata", ".data.rel.ro"))
def isbss(self):
return self.sec_name.startswith(".bss")
class LiteralEntry:
def __init__(self, value, offset):
self.value = value
self.offset = offset
class LinkEnv:
def __init__(self, arch):
self.arch = ARCH_DATA[arch]
self.sections = [] # list of sections in order of output
self.literal_sections = [] # list of literal sections (xtensa only)
self.known_syms = {} # dict of symbols that are defined
self.unresolved_syms = [] # list of unresolved symbols
self.mpy_relocs = [] # list of relocations needed in the output .mpy file
def check_arch(self, arch_name):
if arch_name != self.arch.name:
raise LinkError("incompatible arch")
def print_sections(self):
log(LOG_LEVEL_2, "sections:")
for sec in self.sections:
log(LOG_LEVEL_2, " {:08x} {} size={}".format(sec.addr, sec.name, len(sec.data)))
def find_addr(self, name):
if name in self.known_syms:
s = self.known_syms[name]
return s.section.addr + s["st_value"]
raise LinkError("unknown symbol: {}".format(name))
def build_got_generic(env):
env.got_entries = {}
for sec in env.sections:
for r in sec.reloc:
s = r.sym
if not (
s.entry["st_info"]["bind"] == "STB_GLOBAL"
and r["r_info_type"] in env.arch.arch_got
):
continue
s_type = s.entry["st_info"]["type"]
assert s_type in ("STT_NOTYPE", "STT_FUNC", "STT_OBJECT"), s_type
assert s.name
if s.name in env.got_entries:
continue
env.got_entries[s.name] = GOTEntry(s.name, s)
def build_got_xtensa(env):
env.got_entries = {}
env.lit_entries = {}
env.xt_literals = {}
# Extract the values from the literal table
for sec in env.literal_sections:
assert len(sec.data) % env.arch.word_size == 0
# Look through literal relocations to find any global pointers that should be GOT entries
for r in sec.reloc:
s = r.sym
s_type = s.entry["st_info"]["type"]
assert s_type in ("STT_NOTYPE", "STT_FUNC", "STT_OBJECT", "STT_SECTION"), s_type
assert r["r_info_type"] in env.arch.arch_got
assert r["r_offset"] % env.arch.word_size == 0
# This entry is a global pointer
existing = struct.unpack_from("<I", sec.data, r["r_offset"])[0]
if s_type == "STT_SECTION":
assert r["r_addend"] == 0
name = "{}+0x{:x}".format(s.section.name, existing)
else:
assert existing == 0
name = s.name
if r["r_addend"] != 0:
name = "{}+0x{:x}".format(name, r["r_addend"])
idx = "{}+0x{:x}".format(sec.filename, r["r_offset"])
env.xt_literals[idx] = name
if name in env.got_entries:
# Deduplicate GOT entries
continue
env.got_entries[name] = GOTEntry(name, s, existing)
# Go through all literal entries finding those that aren't global pointers so must be actual literals
for i in range(0, len(sec.data), env.arch.word_size):
idx = "{}+0x{:x}".format(sec.filename, i)
if idx not in env.xt_literals:
# This entry is an actual literal
value = struct.unpack_from("<I", sec.data, i)[0]
env.xt_literals[idx] = value
if value in env.lit_entries:
# Deduplicate literals
continue
env.lit_entries[value] = LiteralEntry(
value, len(env.lit_entries) * env.arch.word_size
)
def populate_got(env):
# Compute GOT destination addresses
for got_entry in env.got_entries.values():
sym = got_entry.sym
if hasattr(sym, "resolved"):
sym = sym.resolved
sec = sym.section
addr = sym["st_value"]
got_entry.sec_name = sec.name
got_entry.link_addr += sec.addr + addr
# Get sorted GOT, sorted by external, text, rodata, bss so relocations can be combined
got_list = sorted(
env.got_entries.values(),
key=lambda g: g.isexternal() + 2 * g.istext() + 3 * g.isrodata() + 4 * g.isbss(),
)
# Layout and populate the GOT
offset = 0
for got_entry in got_list:
got_entry.offset = offset
offset += env.arch.word_size
o = env.got_section.addr + got_entry.offset
env.full_text[o : o + env.arch.word_size] = got_entry.link_addr.to_bytes(
env.arch.word_size, "little"
)
# Create a relocation for each GOT entry
for got_entry in got_list:
if got_entry.name == "mp_fun_table":
dest = "mp_fun_table"
elif got_entry.name.startswith("mp_fun_table+0x"):
dest = int(got_entry.name.split("+")[1], 16) // env.arch.word_size
elif got_entry.sec_name.startswith(".text"):
dest = ".text"
elif got_entry.sec_name.startswith(".rodata"):
dest = ".rodata"
elif got_entry.sec_name.startswith(".data.rel.ro"):
dest = ".data.rel.ro"
elif got_entry.sec_name.startswith(".bss"):
dest = ".bss"
else:
assert 0, (got_entry.name, got_entry.sec_name)
env.mpy_relocs.append((".text", env.got_section.addr + got_entry.offset, dest))
# Print out the final GOT
log(LOG_LEVEL_2, "GOT: {:08x}".format(env.got_section.addr))
for g in got_list:
log(
LOG_LEVEL_2,
" {:08x} {} -> {}+{:08x}".format(g.offset, g.name, g.sec_name, g.link_addr),
)
def populate_lit(env):
log(LOG_LEVEL_2, "LIT: {:08x}".format(env.lit_section.addr))
for lit_entry in env.lit_entries.values():
value = lit_entry.value
log(LOG_LEVEL_2, " {:08x} = {:08x}".format(lit_entry.offset, value))
o = env.lit_section.addr + lit_entry.offset
env.full_text[o : o + env.arch.word_size] = value.to_bytes(env.arch.word_size, "little")
def do_relocation_text(env, text_addr, r):
# Extract relevant info about symbol that's being relocated
s = r.sym
s_bind = s.entry["st_info"]["bind"]
s_shndx = s.entry["st_shndx"]
s_type = s.entry["st_info"]["type"]
r_offset = r["r_offset"] + text_addr
r_info_type = r["r_info_type"]
try:
# only for RELA sections
r_addend = r["r_addend"]
except KeyError:
r_addend = 0
# Default relocation type and name for logging
reloc_type = "le32"
log_name = None
if (
env.arch.name == "EM_386"
and r_info_type in (R_386_PC32, R_386_PLT32)
or env.arch.name == "EM_X86_64"
and r_info_type in (R_X86_64_PC32, R_X86_64_PLT32)
or env.arch.name == "EM_ARM"
and r_info_type in (R_ARM_REL32, R_ARM_THM_CALL, R_ARM_THM_JUMP24)
or s_bind == "STB_LOCAL"
and env.arch.name == "EM_XTENSA"
and r_info_type == R_XTENSA_32 # not GOT
):
# Standard relocation to fixed location within text/rodata
if hasattr(s, "resolved"):
s = s.resolved
sec = s.section
if env.arch.separate_rodata and sec.name.startswith(".rodata"):
raise LinkError("fixed relocation to rodata with rodata referenced via GOT")
if sec.name.startswith(".bss"):
raise LinkError(
"{}: fixed relocation to bss (bss variables can't be static)".format(s.filename)
)
if sec.name.startswith(".external"):
raise LinkError(
"{}: fixed relocation to external symbol: {}".format(s.filename, s.name)
)
addr = sec.addr + s["st_value"]
reloc = addr - r_offset + r_addend
if r_info_type in (R_ARM_THM_CALL, R_ARM_THM_JUMP24):
# Both relocations have the same bit pattern to rewrite:
# R_ARM_THM_CALL: bl
# R_ARM_THM_JUMP24: b.w
reloc_type = "thumb_b"
elif (
env.arch.name == "EM_386"
and r_info_type == R_386_GOTPC
or env.arch.name == "EM_ARM"
and r_info_type == R_ARM_BASE_PREL
):
# Relocation to GOT address itself
assert s.name == "_GLOBAL_OFFSET_TABLE_"
addr = env.got_section.addr
reloc = addr - r_offset + r_addend
elif (
env.arch.name == "EM_386"
and r_info_type in (R_386_GOT32, R_386_GOT32X)
or env.arch.name == "EM_ARM"
and r_info_type == R_ARM_GOT_BREL
):
# Relcation pointing to GOT
reloc = addr = env.got_entries[s.name].offset
elif env.arch.name == "EM_X86_64" and r_info_type in (
R_X86_64_GOTPCREL,
R_X86_64_REX_GOTPCRELX,
):
# Relcation pointing to GOT
got_entry = env.got_entries[s.name]
addr = env.got_section.addr + got_entry.offset
reloc = addr - r_offset + r_addend
elif env.arch.name == "EM_386" and r_info_type == R_386_GOTOFF:
# Relocation relative to GOT
addr = s.section.addr + s["st_value"]
reloc = addr - env.got_section.addr + r_addend
elif env.arch.name == "EM_XTENSA" and r_info_type == R_XTENSA_SLOT0_OP:
# Relocation pointing to GOT, xtensa specific
sec = s.section
if sec.name.startswith(".text"):
# it looks like R_XTENSA_SLOT0_OP into .text is already correctly relocated
return
assert sec.name.startswith(".literal"), sec.name
lit_idx = "{}+0x{:x}".format(sec.filename, r_addend)
lit_ptr = env.xt_literals[lit_idx]
if isinstance(lit_ptr, str):
addr = env.got_section.addr + env.got_entries[lit_ptr].offset
log_name = "GOT {}".format(lit_ptr)
else:
addr = env.lit_section.addr + env.lit_entries[lit_ptr].offset
log_name = "LIT"
reloc = addr - r_offset
reloc_type = "xtensa_l32r"
elif env.arch.name == "EM_XTENSA" and r_info_type == R_XTENSA_DIFF32:
if s.section.name.startswith(".text"):
# it looks like R_XTENSA_DIFF32 into .text is already correctly relocated
return
assert 0
else:
# Unknown/unsupported relocation
assert 0, r_info_type
# Write relocation
if reloc_type == "le32":
(existing,) = struct.unpack_from("<I", env.full_text, r_offset)
struct.pack_into("<I", env.full_text, r_offset, (existing + reloc) & 0xFFFFFFFF)
elif reloc_type == "thumb_b":
b_h, b_l = struct.unpack_from("<HH", env.full_text, r_offset)
existing = (b_h & 0x7FF) << 12 | (b_l & 0x7FF) << 1
if existing >= 0x400000: # 2's complement
existing -= 0x800000
new = existing + reloc
b_h = (b_h & 0xF800) | (new >> 12) & 0x7FF
b_l = (b_l & 0xF800) | (new >> 1) & 0x7FF
struct.pack_into("<HH", env.full_text, r_offset, b_h, b_l)
elif reloc_type == "xtensa_l32r":
l32r = unpack_u24le(env.full_text, r_offset)
assert l32r & 0xF == 1 # RI16 encoded l32r
l32r_imm16 = l32r >> 8
l32r_imm16 = (l32r_imm16 + reloc >> 2) & 0xFFFF
l32r = l32r & 0xFF | l32r_imm16 << 8
pack_u24le(env.full_text, r_offset, l32r)
else:
assert 0, reloc_type
# Log information about relocation
if log_name is None:
if s_type == "STT_SECTION":
log_name = s.section.name
else:
log_name = s.name
log(LOG_LEVEL_3, " {:08x} {} -> {:08x}".format(r_offset, log_name, addr))
def do_relocation_data(env, text_addr, r):
s = r.sym
s_type = s.entry["st_info"]["type"]
r_offset = r["r_offset"] + text_addr
r_info_type = r["r_info_type"]
try:
# only for RELA sections
r_addend = r["r_addend"]
except KeyError:
r_addend = 0
if (
env.arch.name == "EM_386"
and r_info_type == R_386_32
or env.arch.name == "EM_X86_64"
and r_info_type == R_X86_64_64
or env.arch.name == "EM_ARM"
and r_info_type == R_ARM_ABS32
or env.arch.name == "EM_XTENSA"
and r_info_type == R_XTENSA_32
):
# Relocation in data.rel.ro to internal/external symbol
if env.arch.word_size == 4:
struct_type = "<I"
elif env.arch.word_size == 8:
struct_type = "<Q"
sec = s.section
assert r_offset % env.arch.word_size == 0
addr = sec.addr + s["st_value"] + r_addend
if s_type == "STT_SECTION":
log_name = sec.name
else:
log_name = s.name
log(LOG_LEVEL_3, " {:08x} -> {} {:08x}".format(r_offset, log_name, addr))
if env.arch.separate_rodata:
data = env.full_rodata
else:
data = env.full_text
(existing,) = struct.unpack_from(struct_type, data, r_offset)
if sec.name.startswith((".text", ".rodata", ".data.rel.ro", ".bss")):
struct.pack_into(struct_type, data, r_offset, existing + addr)
kind = sec.name
elif sec.name == ".external.mp_fun_table":
assert addr == 0
kind = s.mp_fun_table_offset
else:
assert 0, sec.name
if env.arch.separate_rodata:
base = ".rodata"
else:
base = ".text"
env.mpy_relocs.append((base, r_offset, kind))
else:
# Unknown/unsupported relocation
assert 0, r_info_type
def load_object_file(env, felf):
with open(felf, "rb") as f:
elf = elffile.ELFFile(f)
env.check_arch(elf["e_machine"])
# Get symbol table
symtab = list(elf.get_section_by_name(".symtab").iter_symbols())
# Load needed sections from ELF file
sections_shndx = {} # maps elf shndx to Section object
for idx, s in enumerate(elf.iter_sections()):
if s.header.sh_type in ("SHT_PROGBITS", "SHT_NOBITS"):
if s.data_size == 0:
# Ignore empty sections
pass
elif s.name.startswith((".literal", ".text", ".rodata", ".data.rel.ro", ".bss")):
sec = Section.from_elfsec(s, felf)
sections_shndx[idx] = sec
if s.name.startswith(".literal"):
env.literal_sections.append(sec)
else:
env.sections.append(sec)
elif s.name.startswith(".data"):
raise LinkError("{}: {} non-empty".format(felf, s.name))
else:
# Ignore section
pass
elif s.header.sh_type in ("SHT_REL", "SHT_RELA"):
shndx = s.header.sh_info
if shndx in sections_shndx:
sec = sections_shndx[shndx]
sec.reloc_name = s.name
sec.reloc = list(s.iter_relocations())
for r in sec.reloc:
r.sym = symtab[r["r_info_sym"]]
# Link symbols to their sections, and update known and unresolved symbols
for sym in symtab:
sym.filename = felf
shndx = sym.entry["st_shndx"]
if shndx in sections_shndx:
# Symbol with associated section
sym.section = sections_shndx[shndx]
if sym["st_info"]["bind"] == "STB_GLOBAL":
# Defined global symbol
if sym.name in env.known_syms and not sym.name.startswith(
"__x86.get_pc_thunk."
):
raise LinkError("duplicate symbol: {}".format(sym.name))
env.known_syms[sym.name] = sym
elif sym.entry["st_shndx"] == "SHN_UNDEF" and sym["st_info"]["bind"] == "STB_GLOBAL":
# Undefined global symbol, needs resolving
env.unresolved_syms.append(sym)
def link_objects(env, native_qstr_vals_len, native_qstr_objs_len):
# Build GOT information
if env.arch.name == "EM_XTENSA":
build_got_xtensa(env)
else:
build_got_generic(env)
# Creat GOT section
got_size = len(env.got_entries) * env.arch.word_size
env.got_section = Section("GOT", bytearray(got_size), env.arch.word_size)
if env.arch.name == "EM_XTENSA":
env.sections.insert(0, env.got_section)
else:
env.sections.append(env.got_section)
# Create optional literal section
if env.arch.name == "EM_XTENSA":
lit_size = len(env.lit_entries) * env.arch.word_size
env.lit_section = Section("LIT", bytearray(lit_size), env.arch.word_size)
env.sections.insert(1, env.lit_section)
# Create section to contain mp_native_qstr_val_table
env.qstr_val_section = Section(
".text.QSTR_VAL",
bytearray(native_qstr_vals_len * env.arch.qstr_entry_size),
env.arch.qstr_entry_size,
)
env.sections.append(env.qstr_val_section)
# Create section to contain mp_native_qstr_obj_table
env.qstr_obj_section = Section(
".text.QSTR_OBJ", bytearray(native_qstr_objs_len * env.arch.word_size), env.arch.word_size
)
env.sections.append(env.qstr_obj_section)
# Resolve unknown symbols
mp_fun_table_sec = Section(".external.mp_fun_table", b"", 0)
fun_table = {
key: 67 + idx
for idx, key in enumerate(
[
"mp_type_type",
"mp_type_str",
"mp_type_list",
"mp_type_dict",
"mp_type_fun_builtin_0",
"mp_type_fun_builtin_1",
"mp_type_fun_builtin_2",
"mp_type_fun_builtin_3",
"mp_type_fun_builtin_var",
"mp_stream_read_obj",
"mp_stream_readinto_obj",
"mp_stream_unbuffered_readline_obj",
"mp_stream_write_obj",
]
)
}
for sym in env.unresolved_syms:
assert sym["st_value"] == 0
if sym.name == "_GLOBAL_OFFSET_TABLE_":
pass
elif sym.name == "mp_fun_table":
sym.section = Section(".external", b"", 0)
elif sym.name == "mp_native_qstr_val_table":
sym.section = env.qstr_val_section
elif sym.name == "mp_native_qstr_obj_table":
sym.section = env.qstr_obj_section
elif sym.name in env.known_syms:
sym.resolved = env.known_syms[sym.name]
else:
if sym.name in fun_table:
sym.section = mp_fun_table_sec
sym.mp_fun_table_offset = fun_table[sym.name]
else:
raise LinkError("{}: undefined symbol: {}".format(sym.filename, sym.name))
# Align sections, assign their addresses, and create full_text
env.full_text = bytearray(env.arch.asm_jump(8)) # dummy, to be filled in later
env.full_rodata = bytearray(0)
env.full_bss = bytearray(0)
for sec in env.sections:
if env.arch.separate_rodata and sec.name.startswith((".rodata", ".data.rel.ro")):
data = env.full_rodata
elif sec.name.startswith(".bss"):
data = env.full_bss
else:
data = env.full_text
sec.addr = align_to(len(data), sec.alignment)
data.extend(b"\x00" * (sec.addr - len(data)))
data.extend(sec.data)
env.print_sections()
populate_got(env)
if env.arch.name == "EM_XTENSA":
populate_lit(env)
# Fill in relocations
for sec in env.sections:
if not sec.reloc:
continue
log(
LOG_LEVEL_3,
"{}: {} relocations via {}:".format(sec.filename, sec.name, sec.reloc_name),
)
for r in sec.reloc:
if sec.name.startswith((".text", ".rodata")):
do_relocation_text(env, sec.addr, r)
elif sec.name.startswith(".data.rel.ro"):
do_relocation_data(env, sec.addr, r)
else:
assert 0, sec.name
################################################################################
# .mpy output
class MPYOutput:
def open(self, fname):
self.f = open(fname, "wb")
self.prev_base = -1
self.prev_offset = -1
def close(self):
self.f.close()
def write_bytes(self, buf):
self.f.write(buf)
def write_uint(self, val):
b = bytearray()
b.insert(0, val & 0x7F)
val >>= 7
while val:
b.insert(0, 0x80 | (val & 0x7F))
val >>= 7
self.write_bytes(b)
def write_qstr(self, s):
if s in qstrutil.static_qstr_list:
self.write_bytes(bytes([0, qstrutil.static_qstr_list.index(s) + 1]))
else:
s = bytes(s, "ascii")
self.write_uint(len(s) << 1)
self.write_bytes(s)
def write_reloc(self, base, offset, dest, n):
need_offset = not (base == self.prev_base and offset == self.prev_offset + 1)
self.prev_offset = offset + n - 1
if dest <= 2:
dest = (dest << 1) | (n > 1)
else:
assert 6 <= dest <= 127
assert n == 1
dest = dest << 1 | need_offset
assert 0 <= dest <= 0xFE, dest
self.write_bytes(bytes([dest]))
if need_offset:
if base == ".text":
base = 0
elif base == ".rodata":
base = 1
self.write_uint(offset << 1 | base)
if n > 1:
self.write_uint(n)
def build_mpy(env, entry_offset, fmpy, native_qstr_vals, native_qstr_objs):
# Write jump instruction to start of text
jump = env.arch.asm_jump(entry_offset)
env.full_text[: len(jump)] = jump
log(LOG_LEVEL_1, "arch: {}".format(env.arch.name))
log(LOG_LEVEL_1, "text size: {}".format(len(env.full_text)))
if len(env.full_rodata):
log(LOG_LEVEL_1, "rodata size: {}".format(len(env.full_rodata)))
log(LOG_LEVEL_1, "bss size: {}".format(len(env.full_bss)))
log(LOG_LEVEL_1, "GOT entries: {}".format(len(env.got_entries)))
# xxd(env.full_text)
out = MPYOutput()
out.open(fmpy)
# MPY: header
out.write_bytes(
bytearray(
[ord("M"), MPY_VERSION, env.arch.mpy_feature, MP_SMALL_INT_BITS, QSTR_WINDOW_SIZE]
)
)
# MPY: kind/len
out.write_uint(len(env.full_text) << 2 | (MP_CODE_NATIVE_VIPER - MP_CODE_BYTECODE))
# MPY: machine code
out.write_bytes(env.full_text)
# MPY: n_qstr_link (assumes little endian)
out.write_uint(len(native_qstr_vals) + len(native_qstr_objs))
for q in range(len(native_qstr_vals)):
off = env.qstr_val_section.addr + q * env.arch.qstr_entry_size
out.write_uint(off << 2)
out.write_qstr(native_qstr_vals[q])
for q in range(len(native_qstr_objs)):
off = env.qstr_obj_section.addr + q * env.arch.word_size
out.write_uint(off << 2 | 3)
out.write_qstr(native_qstr_objs[q])
# MPY: scope_flags
scope_flags = MP_SCOPE_FLAG_VIPERRELOC
if len(env.full_rodata):
scope_flags |= MP_SCOPE_FLAG_VIPERRODATA
if len(env.full_bss):
scope_flags |= MP_SCOPE_FLAG_VIPERBSS
out.write_uint(scope_flags)
# MPY: n_obj
out.write_uint(0)
# MPY: n_raw_code
out.write_uint(0)
# MPY: rodata and/or bss
if len(env.full_rodata):
rodata_const_table_idx = 1
out.write_uint(len(env.full_rodata))
out.write_bytes(env.full_rodata)
if len(env.full_bss):
bss_const_table_idx = bool(env.full_rodata) + 1
out.write_uint(len(env.full_bss))
# MPY: relocation information
prev_kind = None
for base, addr, kind in env.mpy_relocs:
if isinstance(kind, str) and kind.startswith(".text"):
kind = 0
elif kind in (".rodata", ".data.rel.ro"):
if env.arch.separate_rodata:
kind = rodata_const_table_idx
else:
kind = 0
elif isinstance(kind, str) and kind.startswith(".bss"):
kind = bss_const_table_idx
elif kind == "mp_fun_table":
kind = 6
else:
kind = 7 + kind
assert addr % env.arch.word_size == 0, addr
offset = addr // env.arch.word_size
if kind == prev_kind and base == prev_base and offset == prev_offset + 1:
prev_n += 1
prev_offset += 1
else:
if prev_kind is not None:
out.write_reloc(prev_base, prev_offset - prev_n + 1, prev_kind, prev_n)
prev_kind = kind
prev_base = base
prev_offset = offset
prev_n = 1
if prev_kind is not None:
out.write_reloc(prev_base, prev_offset - prev_n + 1, prev_kind, prev_n)
# MPY: sentinel for end of relocations
out.write_bytes(b"\xff")
out.close()
################################################################################
# main
def do_preprocess(args):
if args.output is None:
assert args.files[0].endswith(".c")
args.output = args.files[0][:-1] + "config.h"
static_qstrs, qstr_vals, qstr_objs = extract_qstrs(args.files)
with open(args.output, "w") as f:
print(
"#include <stdint.h>\n"
"typedef uintptr_t mp_uint_t;\n"
"typedef intptr_t mp_int_t;\n"
"typedef uintptr_t mp_off_t;",
file=f,
)
for i, q in enumerate(static_qstrs):
print("#define %s (%u)" % (q, i + 1), file=f)
for i, q in enumerate(sorted(qstr_vals)):
print("#define %s (mp_native_qstr_val_table[%d])" % (q, i), file=f)
for i, q in enumerate(sorted(qstr_objs)):
print(
"#define MP_OBJ_NEW_QSTR_%s ((mp_obj_t)mp_native_qstr_obj_table[%d])" % (q, i),
file=f,
)
if args.arch == "xtensawin":
qstr_type = "uint32_t" # esp32 can only read 32-bit values from IRAM
else:
qstr_type = "uint16_t"
print("extern const {} mp_native_qstr_val_table[];".format(qstr_type), file=f)
print("extern const mp_uint_t mp_native_qstr_obj_table[];", file=f)
def do_link(args):
if args.output is None:
assert args.files[0].endswith(".o")
args.output = args.files[0][:-1] + "mpy"
native_qstr_vals = []
native_qstr_objs = []
if args.qstrs is not None:
with open(args.qstrs) as f:
for l in f:
m = re.match(r"#define MP_QSTR_([A-Za-z0-9_]*) \(mp_native_", l)
if m:
native_qstr_vals.append(m.group(1))
else:
m = re.match(r"#define MP_OBJ_NEW_QSTR_MP_QSTR_([A-Za-z0-9_]*)", l)
if m:
native_qstr_objs.append(m.group(1))
log(LOG_LEVEL_2, "qstr vals: " + ", ".join(native_qstr_vals))
log(LOG_LEVEL_2, "qstr objs: " + ", ".join(native_qstr_objs))
env = LinkEnv(args.arch)
try:
for file in args.files:
load_object_file(env, file)
link_objects(env, len(native_qstr_vals), len(native_qstr_objs))
build_mpy(env, env.find_addr("mpy_init"), args.output, native_qstr_vals, native_qstr_objs)
except LinkError as er:
print("LinkError:", er.args[0])
sys.exit(1)
def main():
import argparse
cmd_parser = argparse.ArgumentParser(description="Run scripts on the pyboard.")
cmd_parser.add_argument(
"--verbose", "-v", action="count", default=1, help="increase verbosity"
)
cmd_parser.add_argument("--arch", default="x64", help="architecture")
cmd_parser.add_argument("--preprocess", action="store_true", help="preprocess source files")
cmd_parser.add_argument("--qstrs", default=None, help="file defining additional qstrs")
cmd_parser.add_argument(
"--output", "-o", default=None, help="output .mpy file (default to input with .o->.mpy)"
)
cmd_parser.add_argument("files", nargs="+", help="input files")
args = cmd_parser.parse_args()
global log_level
log_level = args.verbose
if args.preprocess:
do_preprocess(args)
else:
do_link(args)
if __name__ == "__main__":
main()
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/mpy_ld.py | Python | apache-2.0 | 36,566 |
#!/usr/bin/env python3
#
# This file is part of the MicroPython project, http://micropython.org/
#
# The MIT License (MIT)
#
# Copyright (c) 2014-2021 Damien P. George
# Copyright (c) 2017 Paul Sokolovsky
#
# 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.
"""
pyboard interface
This module provides the Pyboard class, used to communicate with and
control a MicroPython device over a communication channel. Both real
boards and emulated devices (e.g. running in QEMU) are supported.
Various communication channels are supported, including a serial
connection, telnet-style network connection, external process
connection.
Example usage:
import pyboard
pyb = pyboard.Pyboard('/dev/ttyACM0')
Or:
pyb = pyboard.Pyboard('192.168.1.1')
Then:
pyb.enter_raw_repl()
pyb.exec('import pyb')
pyb.exec('pyb.LED(1).on()')
pyb.exit_raw_repl()
Note: if using Python2 then pyb.exec must be written as pyb.exec_.
To run a script from the local machine on the board and print out the results:
import pyboard
pyboard.execfile('test.py', device='/dev/ttyACM0')
This script can also be run directly. To execute a local script, use:
./pyboard.py test.py
Or:
python pyboard.py test.py
"""
import sys
import time
import os
import ast
try:
stdout = sys.stdout.buffer
except AttributeError:
# Python2 doesn't have buffer attr
stdout = sys.stdout
def stdout_write_bytes(b):
b = b.replace(b"\x04", b"")
stdout.write(b)
stdout.flush()
class PyboardError(Exception):
pass
class TelnetToSerial:
def __init__(self, ip, user, password, read_timeout=None):
self.tn = None
import telnetlib
self.tn = telnetlib.Telnet(ip, timeout=15)
self.read_timeout = read_timeout
if b"Login as:" in self.tn.read_until(b"Login as:", timeout=read_timeout):
self.tn.write(bytes(user, "ascii") + b"\r\n")
if b"Password:" in self.tn.read_until(b"Password:", timeout=read_timeout):
# needed because of internal implementation details of the telnet server
time.sleep(0.2)
self.tn.write(bytes(password, "ascii") + b"\r\n")
if b"for more information." in self.tn.read_until(
b'Type "help()" for more information.', timeout=read_timeout
):
# login successful
from collections import deque
self.fifo = deque()
return
raise PyboardError("Failed to establish a telnet connection with the board")
def __del__(self):
self.close()
def close(self):
if self.tn:
self.tn.close()
def read(self, size=1):
while len(self.fifo) < size:
timeout_count = 0
data = self.tn.read_eager()
if len(data):
self.fifo.extend(data)
timeout_count = 0
else:
time.sleep(0.25)
if self.read_timeout is not None and timeout_count > 4 * self.read_timeout:
break
timeout_count += 1
data = b""
while len(data) < size and len(self.fifo) > 0:
data += bytes([self.fifo.popleft()])
return data
def write(self, data):
self.tn.write(data)
return len(data)
def inWaiting(self):
n_waiting = len(self.fifo)
if not n_waiting:
data = self.tn.read_eager()
self.fifo.extend(data)
return len(data)
else:
return n_waiting
class ProcessToSerial:
"Execute a process and emulate serial connection using its stdin/stdout."
def __init__(self, cmd):
import subprocess
self.subp = subprocess.Popen(
cmd,
bufsize=0,
shell=True,
preexec_fn=os.setsid,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
)
# Initially was implemented with selectors, but that adds Python3
# dependency. However, there can be race conditions communicating
# with a particular child process (like QEMU), and selectors may
# still work better in that case, so left inplace for now.
#
# import selectors
# self.sel = selectors.DefaultSelector()
# self.sel.register(self.subp.stdout, selectors.EVENT_READ)
import select
self.poll = select.poll()
self.poll.register(self.subp.stdout.fileno())
def close(self):
import signal
os.killpg(os.getpgid(self.subp.pid), signal.SIGTERM)
def read(self, size=1):
data = b""
while len(data) < size:
data += self.subp.stdout.read(size - len(data))
return data
def write(self, data):
self.subp.stdin.write(data)
return len(data)
def inWaiting(self):
# res = self.sel.select(0)
res = self.poll.poll(0)
if res:
return 1
return 0
class ProcessPtyToTerminal:
"""Execute a process which creates a PTY and prints slave PTY as
first line of its output, and emulate serial connection using
this PTY."""
def __init__(self, cmd):
import subprocess
import re
import serial
self.subp = subprocess.Popen(
cmd.split(),
bufsize=0,
shell=False,
preexec_fn=os.setsid,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
pty_line = self.subp.stderr.readline().decode("utf-8")
m = re.search(r"/dev/pts/[0-9]+", pty_line)
if not m:
print("Error: unable to find PTY device in startup line:", pty_line)
self.close()
sys.exit(1)
pty = m.group()
# rtscts, dsrdtr params are to workaround pyserial bug:
# http://stackoverflow.com/questions/34831131/pyserial-does-not-play-well-with-virtual-port
self.ser = serial.Serial(pty, interCharTimeout=1, rtscts=True, dsrdtr=True)
def close(self):
import signal
os.killpg(os.getpgid(self.subp.pid), signal.SIGTERM)
def read(self, size=1):
return self.ser.read(size)
def write(self, data):
return self.ser.write(data)
def inWaiting(self):
return self.ser.inWaiting()
class Pyboard:
def __init__(
self, device, baudrate=115200, user="micro", password="python", wait=0, exclusive=True
):
self.in_raw_repl = False
self.use_raw_paste = True
if device.startswith("exec:"):
self.serial = ProcessToSerial(device[len("exec:") :])
elif device.startswith("execpty:"):
self.serial = ProcessPtyToTerminal(device[len("qemupty:") :])
elif device and device[0].isdigit() and device[-1].isdigit() and device.count(".") == 3:
# device looks like an IP address
self.serial = TelnetToSerial(device, user, password, read_timeout=10)
else:
import serial
# Set options, and exclusive if pyserial supports it
serial_kwargs = {"baudrate": baudrate, "interCharTimeout": 1}
if serial.__version__ >= "3.3":
serial_kwargs["exclusive"] = exclusive
delayed = False
for attempt in range(wait + 1):
try:
self.serial = serial.Serial(device, **serial_kwargs)
break
except (OSError, IOError): # Py2 and Py3 have different errors
if wait == 0:
continue
if attempt == 0:
sys.stdout.write("Waiting {} seconds for pyboard ".format(wait))
delayed = True
time.sleep(1)
sys.stdout.write(".")
sys.stdout.flush()
else:
if delayed:
print("")
raise PyboardError("failed to access " + device)
if delayed:
print("")
def close(self):
self.serial.close()
def read_until(self, min_num_bytes, ending, timeout=10, data_consumer=None):
# if data_consumer is used then data is not accumulated and the ending must be 1 byte long
assert data_consumer is None or len(ending) == 1
data = self.serial.read(min_num_bytes)
if data_consumer:
data_consumer(data)
timeout_count = 0
while True:
if data.endswith(ending):
break
elif self.serial.inWaiting() > 0:
new_data = self.serial.read(1)
if data_consumer:
data_consumer(new_data)
data = new_data
else:
data = data + new_data
timeout_count = 0
else:
timeout_count += 1
if timeout is not None and timeout_count >= 100 * timeout:
break
time.sleep(0.01)
return data
def enter_raw_repl(self, soft_reset=True):
self.serial.write(b"\r\x03\x03") # ctrl-C twice: interrupt any running program
# flush input (without relying on serial.flushInput())
n = self.serial.inWaiting()
while n > 0:
self.serial.read(n)
n = self.serial.inWaiting()
self.serial.write(b"\r\x01") # ctrl-A: enter raw REPL
if soft_reset:
data = self.read_until(1, b"raw REPL; CTRL-B to exit\r\n>")
if not data.endswith(b"raw REPL; CTRL-B to exit\r\n>"):
print(data)
raise PyboardError("could not enter raw repl")
self.serial.write(b"\x04") # ctrl-D: soft reset
# Waiting for "soft reboot" independently to "raw REPL" (done below)
# allows boot.py to print, which will show up after "soft reboot"
# and before "raw REPL".
data = self.read_until(1, b"soft reboot\r\n")
if not data.endswith(b"soft reboot\r\n"):
print(data)
raise PyboardError("could not enter raw repl")
data = self.read_until(1, b"raw REPL; CTRL-B to exit\r\n")
if not data.endswith(b"raw REPL; CTRL-B to exit\r\n"):
print(data)
raise PyboardError("could not enter raw repl")
self.in_raw_repl = True
def exit_raw_repl(self):
self.serial.write(b"\r\x02") # ctrl-B: enter friendly REPL
self.in_raw_repl = False
def follow(self, timeout, data_consumer=None):
# wait for normal output
data = self.read_until(1, b"\x04", timeout=timeout, data_consumer=data_consumer)
if not data.endswith(b"\x04"):
raise PyboardError("timeout waiting for first EOF reception")
data = data[:-1]
# wait for error output
data_err = self.read_until(1, b"\x04", timeout=timeout)
if not data_err.endswith(b"\x04"):
raise PyboardError("timeout waiting for second EOF reception")
data_err = data_err[:-1]
# return normal and error output
return data, data_err
def raw_paste_write(self, command_bytes):
# Read initial header, with window size.
data = self.serial.read(2)
window_size = data[0] | data[1] << 8
window_remain = window_size
# Write out the command_bytes data.
i = 0
while i < len(command_bytes):
while window_remain == 0 or self.serial.inWaiting():
data = self.serial.read(1)
if data == b"\x01":
# Device indicated that a new window of data can be sent.
window_remain += window_size
elif data == b"\x04":
# Device indicated abrupt end. Acknowledge it and finish.
self.serial.write(b"\x04")
return
else:
# Unexpected data from device.
raise PyboardError("unexpected read during raw paste: {}".format(data))
# Send out as much data as possible that fits within the allowed window.
b = command_bytes[i : min(i + window_remain, len(command_bytes))]
self.serial.write(b)
window_remain -= len(b)
i += len(b)
# Indicate end of data.
self.serial.write(b"\x04")
# Wait for device to acknowledge end of data.
data = self.read_until(1, b"\x04")
if not data.endswith(b"\x04"):
raise PyboardError("could not complete raw paste: {}".format(data))
def exec_raw_no_follow(self, command):
if isinstance(command, bytes):
command_bytes = command
else:
command_bytes = bytes(command, encoding="utf8")
# check we have a prompt
data = self.read_until(1, b">")
if not data.endswith(b">"):
raise PyboardError("could not enter raw repl")
if self.use_raw_paste:
# Try to enter raw-paste mode.
self.serial.write(b"\x05A\x01")
data = self.serial.read(2)
if data == b"R\x00":
# Device understood raw-paste command but doesn't support it.
pass
elif data == b"R\x01":
# Device supports raw-paste mode, write out the command using this mode.
return self.raw_paste_write(command_bytes)
else:
# Device doesn't support raw-paste, fall back to normal raw REPL.
data = self.read_until(1, b"w REPL; CTRL-B to exit\r\n>")
if not data.endswith(b"w REPL; CTRL-B to exit\r\n>"):
print(data)
raise PyboardError("could not enter raw repl")
# Don't try to use raw-paste mode again for this connection.
self.use_raw_paste = False
# Write command using standard raw REPL, 256 bytes every 10ms.
for i in range(0, len(command_bytes), 256):
self.serial.write(command_bytes[i : min(i + 256, len(command_bytes))])
time.sleep(0.01)
self.serial.write(b"\x04")
# check if we could exec command
data = self.serial.read(2)
if data != b"OK":
raise PyboardError("could not exec command (response: %r)" % data)
def exec_raw(self, command, timeout=10, data_consumer=None):
self.exec_raw_no_follow(command)
return self.follow(timeout, data_consumer)
def eval(self, expression):
ret = self.exec_("print({})".format(expression))
ret = ret.strip()
return ret
def exec_(self, command, data_consumer=None):
ret, ret_err = self.exec_raw(command, data_consumer=data_consumer)
if ret_err:
raise PyboardError("exception", ret, ret_err)
return ret
def execfile(self, filename):
with open(filename, "rb") as f:
pyfile = f.read()
return self.exec_(pyfile)
def get_time(self):
t = str(self.eval("pyb.RTC().datetime()"), encoding="utf8")[1:-1].split(", ")
return int(t[4]) * 3600 + int(t[5]) * 60 + int(t[6])
def fs_ls(self, src):
cmd = (
"import uos\nfor f in uos.ilistdir(%s):\n"
" print('{:12} {}{}'.format(f[3]if len(f)>3 else 0,f[0],'/'if f[1]&0x4000 else ''))"
% (("'%s'" % src) if src else "")
)
self.exec_(cmd, data_consumer=stdout_write_bytes)
def fs_cat(self, src, chunk_size=256):
cmd = (
"with open('%s') as f:\n while 1:\n"
" b=f.read(%u)\n if not b:break\n print(b,end='')" % (src, chunk_size)
)
self.exec_(cmd, data_consumer=stdout_write_bytes)
def fs_get(self, src, dest, chunk_size=256):
self.exec_("f=open('%s','rb')\nr=f.read" % src)
with open(dest, "wb") as f:
while True:
data = bytearray()
self.exec_("print(r(%u))" % chunk_size, data_consumer=lambda d: data.extend(d))
assert data.endswith(b"\r\n\x04")
try:
data = ast.literal_eval(str(data[:-3], "ascii"))
if not isinstance(data, bytes):
raise ValueError("Not bytes")
except (UnicodeError, ValueError) as e:
raise PyboardError("fs_get: Could not interpret received data: %s" % str(e))
if not data:
break
f.write(data)
self.exec_("f.close()")
def fs_put(self, src, dest, chunk_size=256):
self.exec_("f=open('%s','wb')\nw=f.write" % dest)
with open(src, "rb") as f:
while True:
data = f.read(chunk_size)
if not data:
break
if sys.version_info < (3,):
self.exec_("w(b" + repr(data) + ")")
else:
self.exec_("w(" + repr(data) + ")")
self.exec_("f.close()")
def fs_mkdir(self, dir):
self.exec_("import uos\nuos.mkdir('%s')" % dir)
def fs_rmdir(self, dir):
self.exec_("import uos\nuos.rmdir('%s')" % dir)
def fs_rm(self, src):
self.exec_("import uos\nuos.remove('%s')" % src)
# in Python2 exec is a keyword so one must use "exec_"
# but for Python3 we want to provide the nicer version "exec"
setattr(Pyboard, "exec", Pyboard.exec_)
def execfile(filename, device="/dev/ttyACM0", baudrate=115200, user="micro", password="python"):
pyb = Pyboard(device, baudrate, user, password)
pyb.enter_raw_repl()
output = pyb.execfile(filename)
stdout_write_bytes(output)
pyb.exit_raw_repl()
pyb.close()
def filesystem_command(pyb, args):
def fname_remote(src):
if src.startswith(":"):
src = src[1:]
return src
def fname_cp_dest(src, dest):
src = src.rsplit("/", 1)[-1]
if dest is None or dest == "":
dest = src
elif dest == ".":
dest = "./" + src
elif dest.endswith("/"):
dest += src
return dest
cmd = args[0]
args = args[1:]
try:
if cmd == "cp":
srcs = args[:-1]
dest = args[-1]
if srcs[0].startswith("./") or dest.startswith(":"):
op = pyb.fs_put
fmt = "cp %s :%s"
dest = fname_remote(dest)
else:
op = pyb.fs_get
fmt = "cp :%s %s"
for src in srcs:
src = fname_remote(src)
dest2 = fname_cp_dest(src, dest)
print(fmt % (src, dest2))
op(src, dest2)
else:
op = {
"ls": pyb.fs_ls,
"cat": pyb.fs_cat,
"mkdir": pyb.fs_mkdir,
"rmdir": pyb.fs_rmdir,
"rm": pyb.fs_rm,
}[cmd]
if cmd == "ls" and not args:
args = [""]
for src in args:
src = fname_remote(src)
print("%s :%s" % (cmd, src))
op(src)
except PyboardError as er:
print(str(er.args[2], "ascii"))
pyb.exit_raw_repl()
pyb.close()
sys.exit(1)
_injected_import_hook_code = """\
import uos, uio
class _FS:
class File(uio.IOBase):
def __init__(self):
self.off = 0
def ioctl(self, request, arg):
return 0
def readinto(self, buf):
buf[:] = memoryview(_injected_buf)[self.off:self.off + len(buf)]
self.off += len(buf)
return len(buf)
mount = umount = chdir = lambda *args: None
def stat(self, path):
if path == '_injected.mpy':
return tuple(0 for _ in range(10))
else:
raise OSError(-2) # ENOENT
def open(self, path, mode):
return self.File()
uos.mount(_FS(), '/_')
uos.chdir('/_')
from _injected import *
uos.umount('/_')
del _injected_buf, _FS
"""
def main():
import argparse
cmd_parser = argparse.ArgumentParser(description="Run scripts on the pyboard.")
cmd_parser.add_argument(
"-d",
"--device",
default=os.environ.get("PYBOARD_DEVICE", "/dev/ttyACM0"),
help="the serial device or the IP address of the pyboard",
)
cmd_parser.add_argument(
"-b",
"--baudrate",
default=os.environ.get("PYBOARD_BAUDRATE", "115200"),
help="the baud rate of the serial device",
)
cmd_parser.add_argument("-u", "--user", default="micro", help="the telnet login username")
cmd_parser.add_argument("-p", "--password", default="python", help="the telnet login password")
cmd_parser.add_argument("-c", "--command", help="program passed in as string")
cmd_parser.add_argument(
"-w",
"--wait",
default=0,
type=int,
help="seconds to wait for USB connected board to become available",
)
group = cmd_parser.add_mutually_exclusive_group()
group.add_argument(
"--soft-reset",
default=True,
action="store_true",
help="Whether to perform a soft reset when connecting to the board [default]",
)
group.add_argument(
"--no-soft-reset",
action="store_false",
dest="soft_reset",
)
group = cmd_parser.add_mutually_exclusive_group()
group.add_argument(
"--follow",
action="store_true",
default=None,
help="follow the output after running the scripts [default if no scripts given]",
)
group.add_argument(
"--no-follow",
action="store_false",
dest="follow",
)
group = cmd_parser.add_mutually_exclusive_group()
group.add_argument(
"--exclusive",
action="store_true",
default=True,
help="Open the serial device for exclusive access [default]",
)
group.add_argument(
"--no-exclusive",
action="store_false",
dest="exclusive",
)
cmd_parser.add_argument(
"-f",
"--filesystem",
action="store_true",
help="perform a filesystem action: "
"cp local :device | cp :device local | cat path | ls [path] | rm path | mkdir path | rmdir path",
)
cmd_parser.add_argument("files", nargs="*", help="input files")
args = cmd_parser.parse_args()
# open the connection to the pyboard
try:
pyb = Pyboard(
args.device, args.baudrate, args.user, args.password, args.wait, args.exclusive
)
except PyboardError as er:
print(er)
sys.exit(1)
# run any command or file(s)
if args.command is not None or args.filesystem or len(args.files):
# we must enter raw-REPL mode to execute commands
# this will do a soft-reset of the board
try:
pyb.enter_raw_repl(args.soft_reset)
except PyboardError as er:
print(er)
pyb.close()
sys.exit(1)
def execbuffer(buf):
try:
if args.follow is None or args.follow:
ret, ret_err = pyb.exec_raw(
buf, timeout=None, data_consumer=stdout_write_bytes
)
else:
pyb.exec_raw_no_follow(buf)
ret_err = None
except PyboardError as er:
print(er)
pyb.close()
sys.exit(1)
except KeyboardInterrupt:
sys.exit(1)
if ret_err:
pyb.exit_raw_repl()
pyb.close()
stdout_write_bytes(ret_err)
sys.exit(1)
# do filesystem commands, if given
if args.filesystem:
filesystem_command(pyb, args.files)
del args.files[:]
# run the command, if given
if args.command is not None:
execbuffer(args.command.encode("utf-8"))
# run any files
for filename in args.files:
with open(filename, "rb") as f:
pyfile = f.read()
if filename.endswith(".mpy") and pyfile[0] == ord("M"):
pyb.exec_("_injected_buf=" + repr(pyfile))
pyfile = _injected_import_hook_code
execbuffer(pyfile)
# exiting raw-REPL just drops to friendly-REPL mode
pyb.exit_raw_repl()
# if asked explicitly, or no files given, then follow the output
if args.follow or (args.command is None and not args.filesystem and len(args.files) == 0):
try:
ret, ret_err = pyb.follow(timeout=None, data_consumer=stdout_write_bytes)
except PyboardError as er:
print(er)
sys.exit(1)
except KeyboardInterrupt:
sys.exit(1)
if ret_err:
pyb.close()
stdout_write_bytes(ret_err)
sys.exit(1)
# close the connection to the pyboard
pyb.close()
if __name__ == "__main__":
main()
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/pyboard.py | Python | apache-2.0 | 26,157 |
#!/usr/bin/env python
# This file is part of the OpenMV project.
# Copyright (c) 2013/2014 Ibrahim Abdelkader <i.abdalkader@gmail.com>
# This work is licensed under the MIT license, see the file LICENSE for
# details.
"""This module implements enough functionality to program the STM32F4xx over
DFU, without requiring dfu-util.
See app note AN3156 for a description of the DFU protocol.
See document UM0391 for a dscription of the DFuse file.
"""
from __future__ import print_function
import argparse
import collections
import inspect
import re
import struct
import sys
import usb.core
import usb.util
import zlib
# USB request __TIMEOUT
__TIMEOUT = 4000
# DFU commands
__DFU_DETACH = 0
__DFU_DNLOAD = 1
__DFU_UPLOAD = 2
__DFU_GETSTATUS = 3
__DFU_CLRSTATUS = 4
__DFU_GETSTATE = 5
__DFU_ABORT = 6
# DFU status
__DFU_STATE_APP_IDLE = 0x00
__DFU_STATE_APP_DETACH = 0x01
__DFU_STATE_DFU_IDLE = 0x02
__DFU_STATE_DFU_DOWNLOAD_SYNC = 0x03
__DFU_STATE_DFU_DOWNLOAD_BUSY = 0x04
__DFU_STATE_DFU_DOWNLOAD_IDLE = 0x05
__DFU_STATE_DFU_MANIFEST_SYNC = 0x06
__DFU_STATE_DFU_MANIFEST = 0x07
__DFU_STATE_DFU_MANIFEST_WAIT_RESET = 0x08
__DFU_STATE_DFU_UPLOAD_IDLE = 0x09
__DFU_STATE_DFU_ERROR = 0x0A
_DFU_DESCRIPTOR_TYPE = 0x21
__DFU_STATUS_STR = {
__DFU_STATE_APP_IDLE: "STATE_APP_IDLE",
__DFU_STATE_APP_DETACH: "STATE_APP_DETACH",
__DFU_STATE_DFU_IDLE: "STATE_DFU_IDLE",
__DFU_STATE_DFU_DOWNLOAD_SYNC: "STATE_DFU_DOWNLOAD_SYNC",
__DFU_STATE_DFU_DOWNLOAD_BUSY: "STATE_DFU_DOWNLOAD_BUSY",
__DFU_STATE_DFU_DOWNLOAD_IDLE: "STATE_DFU_DOWNLOAD_IDLE",
__DFU_STATE_DFU_MANIFEST_SYNC: "STATE_DFU_MANIFEST_SYNC",
__DFU_STATE_DFU_MANIFEST: "STATE_DFU_MANIFEST",
__DFU_STATE_DFU_MANIFEST_WAIT_RESET: "STATE_DFU_MANIFEST_WAIT_RESET",
__DFU_STATE_DFU_UPLOAD_IDLE: "STATE_DFU_UPLOAD_IDLE",
__DFU_STATE_DFU_ERROR: "STATE_DFU_ERROR",
}
# USB device handle
__dev = None
# Configuration descriptor of the device
__cfg_descr = None
__verbose = None
# USB DFU interface
__DFU_INTERFACE = 0
# Python 3 deprecated getargspec in favour of getfullargspec, but
# Python 2 doesn't have the latter, so detect which one to use
getargspec = getattr(inspect, "getfullargspec", inspect.getargspec)
if "length" in getargspec(usb.util.get_string).args:
# PyUSB 1.0.0.b1 has the length argument
def get_string(dev, index):
return usb.util.get_string(dev, 255, index)
else:
# PyUSB 1.0.0.b2 dropped the length argument
def get_string(dev, index):
return usb.util.get_string(dev, index)
def find_dfu_cfg_descr(descr):
if len(descr) == 9 and descr[0] == 9 and descr[1] == _DFU_DESCRIPTOR_TYPE:
nt = collections.namedtuple(
"CfgDescr",
[
"bLength",
"bDescriptorType",
"bmAttributes",
"wDetachTimeOut",
"wTransferSize",
"bcdDFUVersion",
],
)
return nt(*struct.unpack("<BBBHHH", bytearray(descr)))
return None
def init(**kwargs):
"""Initializes the found DFU device so that we can program it."""
global __dev, __cfg_descr
devices = get_dfu_devices(**kwargs)
if not devices:
raise ValueError("No DFU device found")
if len(devices) > 1:
raise ValueError("Multiple DFU devices found")
__dev = devices[0]
__dev.set_configuration()
# Claim DFU interface
usb.util.claim_interface(__dev, __DFU_INTERFACE)
# Find the DFU configuration descriptor, either in the device or interfaces
__cfg_descr = None
for cfg in __dev.configurations():
__cfg_descr = find_dfu_cfg_descr(cfg.extra_descriptors)
if __cfg_descr:
break
for itf in cfg.interfaces():
__cfg_descr = find_dfu_cfg_descr(itf.extra_descriptors)
if __cfg_descr:
break
# Get device into idle state
for attempt in range(4):
status = get_status()
if status == __DFU_STATE_DFU_IDLE:
break
elif status == __DFU_STATE_DFU_DOWNLOAD_IDLE or status == __DFU_STATE_DFU_UPLOAD_IDLE:
abort_request()
else:
clr_status()
def abort_request():
"""Sends an abort request."""
__dev.ctrl_transfer(0x21, __DFU_ABORT, 0, __DFU_INTERFACE, None, __TIMEOUT)
def clr_status():
"""Clears any error status (perhaps left over from a previous session)."""
__dev.ctrl_transfer(0x21, __DFU_CLRSTATUS, 0, __DFU_INTERFACE, None, __TIMEOUT)
def get_status():
"""Get the status of the last operation."""
stat = __dev.ctrl_transfer(0xA1, __DFU_GETSTATUS, 0, __DFU_INTERFACE, 6, 20000)
# firmware can provide an optional string for any error
if stat[5]:
message = get_string(__dev, stat[5])
if message:
print(message)
return stat[4]
def check_status(stage, expected):
status = get_status()
if status != expected:
raise SystemExit("DFU: %s failed (%s)" % (stage, __DFU_STATUS_STR.get(status, status)))
def mass_erase():
"""Performs a MASS erase (i.e. erases the entire device)."""
# Send DNLOAD with first byte=0x41
__dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, "\x41", __TIMEOUT)
# Execute last command
check_status("erase", __DFU_STATE_DFU_DOWNLOAD_BUSY)
# Check command state
check_status("erase", __DFU_STATE_DFU_DOWNLOAD_IDLE)
def page_erase(addr):
"""Erases a single page."""
if __verbose:
print("Erasing page: 0x%x..." % (addr))
# Send DNLOAD with first byte=0x41 and page address
buf = struct.pack("<BI", 0x41, addr)
__dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, buf, __TIMEOUT)
# Execute last command
check_status("erase", __DFU_STATE_DFU_DOWNLOAD_BUSY)
# Check command state
check_status("erase", __DFU_STATE_DFU_DOWNLOAD_IDLE)
def set_address(addr):
"""Sets the address for the next operation."""
# Send DNLOAD with first byte=0x21 and page address
buf = struct.pack("<BI", 0x21, addr)
__dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, buf, __TIMEOUT)
# Execute last command
check_status("set address", __DFU_STATE_DFU_DOWNLOAD_BUSY)
# Check command state
check_status("set address", __DFU_STATE_DFU_DOWNLOAD_IDLE)
def write_memory(addr, buf, progress=None, progress_addr=0, progress_size=0):
"""Writes a buffer into memory. This routine assumes that memory has
already been erased.
"""
xfer_count = 0
xfer_bytes = 0
xfer_total = len(buf)
xfer_base = addr
while xfer_bytes < xfer_total:
if __verbose and xfer_count % 512 == 0:
print(
"Addr 0x%x %dKBs/%dKBs..."
% (xfer_base + xfer_bytes, xfer_bytes // 1024, xfer_total // 1024)
)
if progress and xfer_count % 2 == 0:
progress(progress_addr, xfer_base + xfer_bytes - progress_addr, progress_size)
# Set mem write address
set_address(xfer_base + xfer_bytes)
# Send DNLOAD with fw data
chunk = min(__cfg_descr.wTransferSize, xfer_total - xfer_bytes)
__dev.ctrl_transfer(
0x21, __DFU_DNLOAD, 2, __DFU_INTERFACE, buf[xfer_bytes : xfer_bytes + chunk], __TIMEOUT
)
# Execute last command
check_status("write memory", __DFU_STATE_DFU_DOWNLOAD_BUSY)
# Check command state
check_status("write memory", __DFU_STATE_DFU_DOWNLOAD_IDLE)
xfer_count += 1
xfer_bytes += chunk
def write_page(buf, xfer_offset):
"""Writes a single page. This routine assumes that memory has already
been erased.
"""
xfer_base = 0x08000000
# Set mem write address
set_address(xfer_base + xfer_offset)
# Send DNLOAD with fw data
__dev.ctrl_transfer(0x21, __DFU_DNLOAD, 2, __DFU_INTERFACE, buf, __TIMEOUT)
# Execute last command
check_status("write memory", __DFU_STATE_DFU_DOWNLOAD_BUSY)
# Check command state
check_status("write memory", __DFU_STATE_DFU_DOWNLOAD_IDLE)
if __verbose:
print("Write: 0x%x " % (xfer_base + xfer_offset))
def exit_dfu():
"""Exit DFU mode, and start running the program."""
# Set jump address
set_address(0x08000000)
# Send DNLOAD with 0 length to exit DFU
__dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, None, __TIMEOUT)
try:
# Execute last command
if get_status() != __DFU_STATE_DFU_MANIFEST:
print("Failed to reset device")
# Release device
usb.util.dispose_resources(__dev)
except:
pass
def named(values, names):
"""Creates a dict with `names` as fields, and `values` as values."""
return dict(zip(names.split(), values))
def consume(fmt, data, names):
"""Parses the struct defined by `fmt` from `data`, stores the parsed fields
into a named tuple using `names`. Returns the named tuple, and the data
with the struct stripped off."""
size = struct.calcsize(fmt)
return named(struct.unpack(fmt, data[:size]), names), data[size:]
def cstring(string):
"""Extracts a null-terminated string from a byte array."""
return string.decode("utf-8").split("\0", 1)[0]
def compute_crc(data):
"""Computes the CRC32 value for the data passed in."""
return 0xFFFFFFFF & -zlib.crc32(data) - 1
def read_dfu_file(filename):
"""Reads a DFU file, and parses the individual elements from the file.
Returns an array of elements. Each element is a dictionary with the
following keys:
num - The element index.
address - The address that the element data should be written to.
size - The size of the element data.
data - The element data.
If an error occurs while parsing the file, then None is returned.
"""
print("File: {}".format(filename))
with open(filename, "rb") as fin:
data = fin.read()
crc = compute_crc(data[:-4])
elements = []
# Decode the DFU Prefix
#
# <5sBIB
# < little endian Endianness
# 5s char[5] signature "DfuSe"
# B uint8_t version 1
# I uint32_t size Size of the DFU file (without suffix)
# B uint8_t targets Number of targets
dfu_prefix, data = consume("<5sBIB", data, "signature version size targets")
print(
" %(signature)s v%(version)d, image size: %(size)d, "
"targets: %(targets)d" % dfu_prefix
)
for target_idx in range(dfu_prefix["targets"]):
# Decode the Image Prefix
#
# <6sBI255s2I
# < little endian Endianness
# 6s char[6] signature "Target"
# B uint8_t altsetting
# I uint32_t named Bool indicating if a name was used
# 255s char[255] name Name of the target
# I uint32_t size Size of image (without prefix)
# I uint32_t elements Number of elements in the image
img_prefix, data = consume(
"<6sBI255s2I", data, "signature altsetting named name " "size elements"
)
img_prefix["num"] = target_idx
if img_prefix["named"]:
img_prefix["name"] = cstring(img_prefix["name"])
else:
img_prefix["name"] = ""
print(
" %(signature)s %(num)d, alt setting: %(altsetting)s, "
'name: "%(name)s", size: %(size)d, elements: %(elements)d' % img_prefix
)
target_size = img_prefix["size"]
target_data = data[:target_size]
data = data[target_size:]
for elem_idx in range(img_prefix["elements"]):
# Decode target prefix
#
# <2I
# < little endian Endianness
# I uint32_t element Address
# I uint32_t element Size
elem_prefix, target_data = consume("<2I", target_data, "addr size")
elem_prefix["num"] = elem_idx
print(" %(num)d, address: 0x%(addr)08x, size: %(size)d" % elem_prefix)
elem_size = elem_prefix["size"]
elem_data = target_data[:elem_size]
target_data = target_data[elem_size:]
elem_prefix["data"] = elem_data
elements.append(elem_prefix)
if len(target_data):
print("target %d PARSE ERROR" % target_idx)
# Decode DFU Suffix
#
# <4H3sBI
# < little endian Endianness
# H uint16_t device Firmware version
# H uint16_t product
# H uint16_t vendor
# H uint16_t dfu 0x11a (DFU file format version)
# 3s char[3] ufd "UFD"
# B uint8_t len 16
# I uint32_t crc32 Checksum
dfu_suffix = named(
struct.unpack("<4H3sBI", data[:16]), "device product vendor dfu ufd len crc"
)
print(
" usb: %(vendor)04x:%(product)04x, device: 0x%(device)04x, "
"dfu: 0x%(dfu)04x, %(ufd)s, %(len)d, 0x%(crc)08x" % dfu_suffix
)
if crc != dfu_suffix["crc"]:
print("CRC ERROR: computed crc32 is 0x%08x" % crc)
return
data = data[16:]
if data:
print("PARSE ERROR")
return
return elements
class FilterDFU(object):
"""Class for filtering USB devices to identify devices which are in DFU
mode.
"""
def __call__(self, device):
for cfg in device:
for intf in cfg:
return intf.bInterfaceClass == 0xFE and intf.bInterfaceSubClass == 1
def get_dfu_devices(*args, **kwargs):
"""Returns a list of USB devices which are currently in DFU mode.
Additional filters (like idProduct and idVendor) can be passed in
to refine the search.
"""
# Convert to list for compatibility with newer PyUSB
return list(usb.core.find(*args, find_all=True, custom_match=FilterDFU(), **kwargs))
def get_memory_layout(device):
"""Returns an array which identifies the memory layout. Each entry
of the array will contain a dictionary with the following keys:
addr - Address of this memory segment.
last_addr - Last address contained within the memory segment.
size - Size of the segment, in bytes.
num_pages - Number of pages in the segment.
page_size - Size of each page, in bytes.
"""
cfg = device[0]
intf = cfg[(0, 0)]
mem_layout_str = get_string(device, intf.iInterface)
mem_layout = mem_layout_str.split("/")
result = []
for mem_layout_index in range(1, len(mem_layout), 2):
addr = int(mem_layout[mem_layout_index], 0)
segments = mem_layout[mem_layout_index + 1].split(",")
seg_re = re.compile(r"(\d+)\*(\d+)(.)(.)")
for segment in segments:
seg_match = seg_re.match(segment)
num_pages = int(seg_match.groups()[0], 10)
page_size = int(seg_match.groups()[1], 10)
multiplier = seg_match.groups()[2]
if multiplier == "K":
page_size *= 1024
if multiplier == "M":
page_size *= 1024 * 1024
size = num_pages * page_size
last_addr = addr + size - 1
result.append(
named(
(addr, last_addr, size, num_pages, page_size),
"addr last_addr size num_pages page_size",
)
)
addr += size
return result
def list_dfu_devices(*args, **kwargs):
"""Prints a lits of devices detected in DFU mode."""
devices = get_dfu_devices(*args, **kwargs)
if not devices:
raise SystemExit("No DFU capable devices found")
for device in devices:
print(
"Bus {} Device {:03d}: ID {:04x}:{:04x}".format(
device.bus, device.address, device.idVendor, device.idProduct
)
)
layout = get_memory_layout(device)
print("Memory Layout")
for entry in layout:
print(
" 0x{:x} {:2d} pages of {:3d}K bytes".format(
entry["addr"], entry["num_pages"], entry["page_size"] // 1024
)
)
def write_elements(elements, mass_erase_used, progress=None):
"""Writes the indicated elements into the target memory,
erasing as needed.
"""
mem_layout = get_memory_layout(__dev)
for elem in elements:
addr = elem["addr"]
size = elem["size"]
data = elem["data"]
elem_size = size
elem_addr = addr
if progress and elem_size:
progress(elem_addr, 0, elem_size)
while size > 0:
write_size = size
if not mass_erase_used:
for segment in mem_layout:
if addr >= segment["addr"] and addr <= segment["last_addr"]:
# We found the page containing the address we want to
# write, erase it
page_size = segment["page_size"]
page_addr = addr & ~(page_size - 1)
if addr + write_size > page_addr + page_size:
write_size = page_addr + page_size - addr
page_erase(page_addr)
break
write_memory(addr, data[:write_size], progress, elem_addr, elem_size)
data = data[write_size:]
addr += write_size
size -= write_size
if progress:
progress(elem_addr, addr - elem_addr, elem_size)
def cli_progress(addr, offset, size):
"""Prints a progress report suitable for use on the command line."""
width = 25
done = offset * width // size
print(
"\r0x{:08x} {:7d} [{}{}] {:3d}% ".format(
addr, size, "=" * done, " " * (width - done), offset * 100 // size
),
end="",
)
try:
sys.stdout.flush()
except OSError:
pass # Ignore Windows CLI "WinError 87" on Python 3.6
if offset == size:
print("")
def main():
"""Test program for verifying this files functionality."""
global __verbose
# Parse CMD args
parser = argparse.ArgumentParser(description="DFU Python Util")
parser.add_argument(
"-l", "--list", help="list available DFU devices", action="store_true", default=False
)
parser.add_argument("--vid", help="USB Vendor ID", type=lambda x: int(x, 0), default=None)
parser.add_argument("--pid", help="USB Product ID", type=lambda x: int(x, 0), default=None)
parser.add_argument(
"-m", "--mass-erase", help="mass erase device", action="store_true", default=False
)
parser.add_argument(
"-u", "--upload", help="read file from DFU device", dest="path", default=False
)
parser.add_argument("-x", "--exit", help="Exit DFU", action="store_true", default=False)
parser.add_argument(
"-v", "--verbose", help="increase output verbosity", action="store_true", default=False
)
args = parser.parse_args()
__verbose = args.verbose
kwargs = {}
if args.vid:
kwargs["idVendor"] = args.vid
if args.pid:
kwargs["idProduct"] = args.pid
if args.list:
list_dfu_devices(**kwargs)
return
init(**kwargs)
command_run = False
if args.mass_erase:
print("Mass erase...")
mass_erase()
command_run = True
if args.path:
elements = read_dfu_file(args.path)
if not elements:
print("No data in dfu file")
return
print("Writing memory...")
write_elements(elements, args.mass_erase, progress=cli_progress)
print("Exiting DFU...")
exit_dfu()
command_run = True
if args.exit:
print("Exiting DFU...")
exit_dfu()
command_run = True
if command_run:
print("Finished")
else:
print("No command specified")
if __name__ == "__main__":
main()
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/pydfu.py | Python | apache-2.0 | 20,109 |
#!/usr/bin/env python3
import os, sys
from glob import glob
from re import sub
import argparse
def escape(s):
s = s.decode()
lookup = {
"\0": "\\0",
"\t": "\\t",
"\n": '\\n"\n"',
"\r": "\\r",
"\\": "\\\\",
'"': '\\"',
}
return '""\n"{}"'.format("".join([lookup[x] if x in lookup else x for x in s]))
def chew_filename(t):
return {"func": "test_{}_fn".format(sub(r"/|\.|-", "_", t)), "desc": t}
def script_to_map(test_file):
r = {"name": chew_filename(test_file)["func"]}
with open(test_file, "rb") as f:
r["script"] = escape(f.read())
with open(test_file + ".exp", "rb") as f:
r["output"] = escape(f.read())
return r
test_function = (
"void {name}(void* data) {{\n"
" static const char pystr[] = {script};\n"
" static const char exp[] = {output};\n"
' printf("\\n");\n'
" upytest_set_expected_output(exp, sizeof(exp) - 1);\n"
" upytest_execute_test(pystr);\n"
' printf("result: ");\n'
"}}"
)
testcase_struct = "struct testcase_t {name}_tests[] = {{\n{body}\n END_OF_TESTCASES\n}};"
testcase_member = ' {{ "{desc}", {func}, TT_ENABLED_, 0, 0 }},'
testgroup_struct = "struct testgroup_t groups[] = {{\n{body}\n END_OF_GROUPS\n}};"
testgroup_member = ' {{ "{name}", {name}_tests }},'
## XXX: may be we could have `--without <groups>` argument...
# currently these tests are selected because they pass on qemu-arm
test_dirs = (
"basics",
"micropython",
"misc",
"extmod",
"float",
"inlineasm",
"qemu-arm",
) # 'import', 'io',)
exclude_tests = (
# pattern matching in .exp
"basics/bytes_compare3.py",
"extmod/ticks_diff.py",
"extmod/time_ms_us.py",
"extmod/uheapq_timeq.py",
# unicode char issue
"extmod/ujson_loads.py",
# doesn't output to python stdout
"extmod/ure_debug.py",
"extmod/vfs_basic.py",
"extmod/vfs_fat_ramdisk.py",
"extmod/vfs_fat_fileio.py",
"extmod/vfs_fat_fsusermount.py",
"extmod/vfs_fat_oldproto.py",
# rounding issues
"float/float_divmod.py",
# requires double precision floating point to work
"float/float2int_doubleprec_intbig.py",
"float/float_parse_doubleprec.py",
# inline asm FP tests (require Cortex-M4)
"inlineasm/asmfpaddsub.py",
"inlineasm/asmfpcmp.py",
"inlineasm/asmfpldrstr.py",
"inlineasm/asmfpmuldiv.py",
"inlineasm/asmfpsqrt.py",
# different filename in output
"micropython/emg_exc.py",
"micropython/heapalloc_traceback.py",
# don't have emergency exception buffer
"micropython/heapalloc_exc_compressed_emg_exc.py",
# pattern matching in .exp
"micropython/meminfo.py",
# needs sys stdfiles
"misc/print_exception.py",
# settrace .exp files are too large
"misc/sys_settrace_loop.py",
"misc/sys_settrace_generator.py",
"misc/sys_settrace_features.py",
# don't have f-string
"basics/string_fstring.py",
"basics/string_fstring_debug.py",
)
output = []
tests = []
argparser = argparse.ArgumentParser(
description="Convert native MicroPython tests to tinytest/upytesthelper C code"
)
argparser.add_argument("--stdin", action="store_true", help="read list of tests from stdin")
argparser.add_argument("--exclude", action="append", help="exclude test by name")
args = argparser.parse_args()
if not args.stdin:
if args.exclude:
exclude_tests += tuple(args.exclude)
for group in test_dirs:
tests += [test for test in glob("{}/*.py".format(group)) if test not in exclude_tests]
else:
for l in sys.stdin:
tests.append(l.rstrip())
output.extend([test_function.format(**script_to_map(test)) for test in tests])
testcase_members = [testcase_member.format(**chew_filename(test)) for test in tests]
output.append(testcase_struct.format(name="", body="\n".join(testcase_members)))
testgroup_members = [testgroup_member.format(name=group) for group in [""]]
output.append(testgroup_struct.format(body="\n".join(testgroup_members)))
## XXX: may be we could have `--output <filename>` argument...
# Don't depend on what system locale is set, use utf8 encoding.
sys.stdout.buffer.write("\n\n".join(output).encode("utf8"))
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/tinytest-codegen.py | Python | apache-2.0 | 4,224 |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Add by HaaS
# version = 1.1.1
import os, sys, re, codecs, time, json
import argparse
import inspect
from ymodemfile import YModemfile
import logging
logging.basicConfig(level=logging.INFO,
format='%(filename)s[line:%(lineno)d]: %(message)s')
try:
import serial
from serial.tools import miniterm
from serial.tools.list_ports import comports
except:
logging.debug("\n\nNot found pyserial, please install:\nsudo pip install pyserial")
sys.exit(0)
def read_json(json_file):
data = None
if os.path.isfile(json_file):
with open(json_file, 'r') as f:
data = json.load(f)
return data
def write_json(json_file, data):
with open(json_file, 'w') as f:
f.write(json.dumps(data, indent=4, separators=(',', ': ')))
def ymodemTrans(serialport, filename):
def sender_getc(size):
return serialport.read(size) or None
def sender_putc(data, timeout=15):
return serialport.write(data)
sender = YModemfile(sender_getc, sender_putc)
sent = sender.send_file(filename)
def received_data_check(pattern, buff):
matcher = re.compile(pattern)
if matcher.search(buff):
return True
return False
def send_check_recv_data_count_down(serialport, pattern, timeout, countUnit):
""" receive serial data, and check it with pattern """
matcher = re.compile(pattern)
tic = time.time()
cnt = 0
unit = countUnit
buff = serialport.read(128)
currentTic = time.time()
while (currentTic - tic) < timeout:
# show count down
if((currentTic - tic) > unit):
cnt = unit
unit = countUnit + unit
print("*****", (timeout-cnt), "*****")
buff += serialport.read(128)
if matcher.search(buff):
print("")
return True
# reset currentTic
currentTic = time.time()
# give more 5S to read buffer
while (time.time() - tic) < (timeout + 10):
buff += serialport.read(128)
if matcher.search(buff):
print("")
return True
print("")
return False
def send_check_recv_data(serialport, pattern, timeout):
""" receive serial data, and check it with pattern """
matcher = re.compile(pattern)
tic = time.time()
buff = serialport.read(128)
while (time.time() - tic) < timeout:
buff += serialport.read(128)
if matcher.search(buff):
return True
return False
def file_transfer_handshake_function(serialport):
count = 0
handshake_data = [0xA5]
shakehand_result = False
print("***** handsharking *****")
print("")
for i in range(300):
serialport.write(serial.to_bytes(handshake_data))
time.sleep(0.1)
buff = serialport.read(2)
# logging.debug(buff)
if((buff) == b'Z'):
# logging.debug('Read data OK');
count +=1
if(count >= 4):
shakehand_result = True
if shakehand_result:
break
if i > 5:
logging.debug("Please reboot the board manually.")
break
return shakehand_result
def download_file(portnum, baudrate, filepath, devpath):
# open serial port first
serialport = serial.Serial()
serialport.port = portnum
serialport.baudrate = baudrate
serialport.parity = "N"
serialport.bytesize = 8
serialport.stopbits = 1
serialport.timeout = 0.05
try:
serialport.open()
except Exception as e:
raise Exception("Failed to open serial port: %s!" % portnum)
# send handshark world for check amp boot mode
checkstatuslist = [0x5A]
bmatched = False
shakehand = False
reboot_cmd_cli = 'reboot()\n'
reboot_cmd = 'reboot\n'
reboot_count = 0;
reboot_method = 0;
# step 1: check system status
for i in range(300):
serialport.write(serial.to_bytes(checkstatuslist))
time.sleep(0.1)
buff = serialport.read(2)
# logging.debug(buff)
# case 1: input == output is cli or repl mode
if((buff) == b'Z'):
# logging.debug('Read data OK');
reboot_count +=1
else:
# not cli or repl mode is running mode
# reboot_method = 1;
time.sleep(0.2)
serialport.write(reboot_cmd_cli.encode())
time.sleep(0.2)
serialport.write(reboot_cmd.encode())
break;
if(reboot_count >= 4):
# need reboot system
# send Enter CMD
# print("send enter")
time.sleep(0.2)
# send a cmd
serialport.write(b'a\r\n')
time.sleep(0.2)
enter_buff = serialport.read(100)
# print(enter_buff)
repl_mode = received_data_check(b'Traceback', enter_buff)
if repl_mode:
# exit python repl mode
# print('repl mode')
serialport.write(reboot_cmd_cli.encode())
else:
# cli mode
cli_mode = received_data_check(b'cmd not found', enter_buff)
if cli_mode:
# print('cli mode')
serialport.write(reboot_cmd.encode())
else:
# print('abnomarl')
reboot_method = 1;
break;
# print(enter_buff)
print("***** Device is rebooting *****")
print("")
break;
# step 2: wait reboot and hand shakend cmd
# judge reset dev
if(reboot_method == 1):
# need reset dev
bmatched = False
else:
time.sleep(1)
bmatched = send_check_recv_data(serialport, b'amp shakehand begin...', 10)
if bmatched:
print("***** Device reboot OK *****")
else:
print("***** Device reboot Failed *****")
# logging.debug(buff)
if bmatched:
shakehand = file_transfer_handshake_function(serialport)
if shakehand:
print("***** recived handshark data *****")
else:
print("***** can not recived handshark data *****")
print("")
print("***** Please reboot the board manually, and try it again *****")
print("")
serialport.close()
return
else:
print("***** Please reboot the board within 10 seconds *****")
print("")
bmatched_retry = send_check_recv_data_count_down(serialport, b'amp shakehand begin...', 10, 1)
if bmatched_retry:
shakehand = file_transfer_handshake_function(serialport)
if shakehand:
print("***** recived handshark data *****")
else:
print("***** can not recived handshark data *****")
print("")
print("***** Please reboot the board manually, and try it again *****")
print("")
serialport.close()
return
else:
print("")
print("***** Please reboot the board manually, and try it again *****")
print("")
serialport.close()
return
# start send amp boot cmd
time.sleep(0.1)
logging.debug("start to send amp_boot cmd")
save_path = devpath
cmd = 'amp_boot'
if((save_path == 'NULL') or (save_path == 'DATA')):
logging.debug('save file in /data')
cmd = 'amp_boot'
elif (save_path == 'SDCARD'):
logging.debug('save file in /sdcard')
cmd = 'amp_boot_sd'
serialport.write(cmd.encode())
# serialport.write(b'amp_boot')
# send file transfer cmd
time.sleep(0.1)
# logging.debug("start to send file cmd")
# cmd = 'cmd_file_transfer\n'
# serialport.write(cmd.encode())
bmatched = send_check_recv_data(serialport, b'amp shakehand success', 5)
# serialport.write(b'cmd_flash_js\n')
# send file
if bmatched:
print("***** Handshark success *****")
print("")
print("***** Start file transfer *****")
print("")
cmd = 'cmd_file_transfer\n'
serialport.write(cmd.encode())
time.sleep(0.1)
serialport.timeout = 0.5
ymodemTrans(serialport, filepath)
# logging.debug("Ymodem transfer file finish")
# send file transfer cmd
time.sleep(0.1)
print("***** File transfer End *****")
print("")
cmd = 'cmd_exit\n'
serialport.write(cmd.encode())
else:
print("***** Handshark failed *****")
print("***** Please reboot the board manually, and try it again *****")
# close serialport
serialport.close()
def get_downloadconfig():
""" get configuration from .config_burn file, if it is not existed,
generate default configuration of chip_haas1000 """
configs = {}
configs['chip_haas1000'] = {}
configs['chip_haas1000']['serialport'] = ''
configs['chip_haas1000']['baudrate'] = ''
configs['chip_haas1000']['savepath'] = ''
configs['chip_haas1000']['filepath'] = ''
return configs['chip_haas1000']
def main2():
cmd_parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description='''Run and transfer file to system.''',)
cmd_parser.add_argument('-d', '--device', default='', help='the serial device or the IP address of the pyboard')
cmd_parser.add_argument('-b', '--baudrate', default=115200, help='the baud rate of the serial device')
cmd_parser.add_argument('-p', '--path', default='NULL', help='the save file path: SDCARD or DATA or NULL')
cmd_parser.add_argument('files', nargs='*', help='input transfer files')
args = cmd_parser.parse_args()
logging.debug(args)
# download file
# step 1: set config
downloadconfig = get_downloadconfig()
# step 2: get serial port
if not downloadconfig["serialport"]:
downloadconfig["serialport"] = args.device
if not downloadconfig["serialport"]:
downloadconfig["serialport"] = miniterm.ask_for_port()
if not downloadconfig["serialport"]:
logging.debug("no specified serial port")
return
else:
needsave = True
# step 3: get baudrate
if not downloadconfig["baudrate"]:
downloadconfig["baudrate"] = args.baudrate
if not downloadconfig["baudrate"]:
downloadconfig["baudrate"] = "115200"
# step 4: get saved file path of devices
if not downloadconfig["savepath"]:
downloadconfig["savepath"] = args.path
if not downloadconfig["savepath"]:
logging.debug('use default path')
return
# step 4: get transfer file
if not downloadconfig["filepath"]:
downloadconfig["filepath"] = args.files
if not downloadconfig["filepath"]:
logging.debug('no file wait to transfer')
return
if os.path.isabs("".join(downloadconfig["filepath"])):
filepath = "".join(downloadconfig["filepath"])
logging.debug('the filepath is abs path')
else:
basepath = os.path.abspath('.')
filepath = basepath + '/' + "".join(downloadconfig["filepath"])
logging.debug('the filepath is not abs path')
print("")
print("***** Params setting *****")
print("serial port is %s" % downloadconfig["serialport"])
print("transfer baudrate is %s" % downloadconfig["baudrate"])
print("savepath is %s" % downloadconfig["savepath"])
print("filepath is %s" % filepath)
print("***** Params setting end *****")
print("")
# step 3: download file
download_file(downloadconfig["serialport"], downloadconfig['baudrate'], filepath, downloadconfig['savepath'])
if __name__ == "__main__":
main2()
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/transymodem.py | Python | apache-2.0 | 11,942 |
#!/usr/bin/env python3
# Microsoft UF2
#
# The MIT License (MIT)
#
# Copyright (c) Microsoft Corporation
#
# All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import sys
import struct
import subprocess
import re
import os
import os.path
import argparse
UF2_MAGIC_START0 = 0x0A324655 # "UF2\n"
UF2_MAGIC_START1 = 0x9E5D5157 # Randomly selected
UF2_MAGIC_END = 0x0AB16F30 # Ditto
families = {
"SAMD21": 0x68ED2B88,
"SAMD51": 0x55114460,
"NRF52": 0x1B57745F,
"STM32F1": 0x5EE21072,
"STM32F4": 0x57755A57,
"ATMEGA32": 0x16573617,
}
INFO_FILE = "/INFO_UF2.TXT"
appstartaddr = 0x2000
familyid = 0x0
def is_uf2(buf):
w = struct.unpack("<II", buf[0:8])
return w[0] == UF2_MAGIC_START0 and w[1] == UF2_MAGIC_START1
def is_hex(buf):
try:
w = buf[0:30].decode("utf-8")
except UnicodeDecodeError:
return False
if w[0] == ":" and re.match(b"^[:0-9a-fA-F\r\n]+$", buf):
return True
return False
def convert_from_uf2(buf):
global appstartaddr
numblocks = len(buf) // 512
curraddr = None
outp = b""
for blockno in range(numblocks):
ptr = blockno * 512
block = buf[ptr : ptr + 512]
hd = struct.unpack(b"<IIIIIIII", block[0:32])
if hd[0] != UF2_MAGIC_START0 or hd[1] != UF2_MAGIC_START1:
print("Skipping block at " + ptr + "; bad magic")
continue
if hd[2] & 1:
# NO-flash flag set; skip block
continue
datalen = hd[4]
if datalen > 476:
assert False, "Invalid UF2 data size at " + ptr
newaddr = hd[3]
if curraddr == None:
appstartaddr = newaddr
curraddr = newaddr
padding = newaddr - curraddr
if padding < 0:
assert False, "Block out of order at " + ptr
if padding > 10 * 1024 * 1024:
assert False, "More than 10M of padding needed at " + ptr
if padding % 4 != 0:
assert False, "Non-word padding size at " + ptr
while padding > 0:
padding -= 4
outp += b"\x00\x00\x00\x00"
outp += block[32 : 32 + datalen]
curraddr = newaddr + datalen
return outp
def convert_to_carray(file_content):
outp = "const unsigned char bindata[] __attribute__((aligned(16))) = {"
for i in range(len(file_content)):
if i % 16 == 0:
outp += "\n"
outp += "0x%02x, " % ord(file_content[i])
outp += "\n};\n"
return outp
def convert_to_uf2(file_content):
global familyid
datapadding = b""
while len(datapadding) < 512 - 256 - 32 - 4:
datapadding += b"\x00\x00\x00\x00"
numblocks = (len(file_content) + 255) // 256
outp = b""
for blockno in range(numblocks):
ptr = 256 * blockno
chunk = file_content[ptr : ptr + 256]
flags = 0x0
if familyid:
flags |= 0x2000
hd = struct.pack(
b"<IIIIIIII",
UF2_MAGIC_START0,
UF2_MAGIC_START1,
flags,
ptr + appstartaddr,
256,
blockno,
numblocks,
familyid,
)
while len(chunk) < 256:
chunk += b"\x00"
block = hd + chunk + datapadding + struct.pack(b"<I", UF2_MAGIC_END)
assert len(block) == 512
outp += block
return outp
class Block:
def __init__(self, addr):
self.addr = addr
self.bytes = bytearray(256)
def encode(self, blockno, numblocks):
global familyid
flags = 0x0
if familyid:
flags |= 0x2000
hd = struct.pack(
"<IIIIIIII",
UF2_MAGIC_START0,
UF2_MAGIC_START1,
flags,
self.addr,
256,
blockno,
numblocks,
familyid,
)
hd += self.bytes[0:256]
while len(hd) < 512 - 4:
hd += b"\x00"
hd += struct.pack("<I", UF2_MAGIC_END)
return hd
def convert_from_hex_to_uf2(buf):
global appstartaddr
appstartaddr = None
upper = 0
currblock = None
blocks = []
for line in buf.split("\n"):
if line[0] != ":":
continue
i = 1
rec = []
while i < len(line) - 1:
rec.append(int(line[i : i + 2], 16))
i += 2
tp = rec[3]
if tp == 4:
upper = ((rec[4] << 8) | rec[5]) << 16
elif tp == 2:
upper = ((rec[4] << 8) | rec[5]) << 4
assert (upper & 0xFFFF) == 0
elif tp == 1:
break
elif tp == 0:
addr = upper | (rec[1] << 8) | rec[2]
if appstartaddr == None:
appstartaddr = addr
i = 4
while i < len(rec) - 1:
if not currblock or currblock.addr & ~0xFF != addr & ~0xFF:
currblock = Block(addr & ~0xFF)
blocks.append(currblock)
currblock.bytes[addr & 0xFF] = rec[i]
addr += 1
i += 1
numblocks = len(blocks)
resfile = b""
for i in range(0, numblocks):
resfile += blocks[i].encode(i, numblocks)
return resfile
def get_drives():
drives = []
if sys.platform == "win32":
r = subprocess.check_output(
[
"wmic",
"PATH",
"Win32_LogicalDisk",
"get",
"DeviceID,",
"VolumeName,",
"FileSystem,",
"DriveType",
]
)
for line in r.split("\n"):
words = re.split("\s+", line)
if len(words) >= 3 and words[1] == "2" and words[2] == "FAT":
drives.append(words[0])
else:
rootpath = "/media"
if sys.platform == "darwin":
rootpath = "/Volumes"
elif sys.platform == "linux":
tmp = rootpath + "/" + os.environ["USER"]
if os.path.isdir(tmp):
rootpath = tmp
for d in os.listdir(rootpath):
drives.append(os.path.join(rootpath, d))
def has_info(d):
try:
return os.path.isfile(d + INFO_FILE)
except:
return False
return list(filter(has_info, drives))
def board_id(path):
with open(path + INFO_FILE, mode="r") as file:
file_content = file.read()
return re.search("Board-ID: ([^\r\n]*)", file_content).group(1)
def list_drives():
for d in get_drives():
print(d, board_id(d))
def write_file(name, buf):
with open(name, "wb") as f:
f.write(buf)
print("Wrote %d bytes to %s." % (len(buf), name))
def main():
global appstartaddr, familyid
def error(msg):
print(msg)
sys.exit(1)
parser = argparse.ArgumentParser(description="Convert to UF2 or flash directly.")
parser.add_argument(
"input", metavar="INPUT", type=str, nargs="?", help="input file (HEX, BIN or UF2)"
)
parser.add_argument(
"-b",
"--base",
dest="base",
type=str,
default="0x2000",
help="set base address of application for BIN format (default: 0x2000)",
)
parser.add_argument(
"-o",
"--output",
metavar="FILE",
dest="output",
type=str,
help='write output to named file; defaults to "flash.uf2" or "flash.bin" where sensible',
)
parser.add_argument("-d", "--device", dest="device_path", help="select a device path to flash")
parser.add_argument("-l", "--list", action="store_true", help="list connected devices")
parser.add_argument("-c", "--convert", action="store_true", help="do not flash, just convert")
parser.add_argument(
"-f",
"--family",
dest="family",
type=str,
default="0x0",
help="specify familyID - number or name (default: 0x0)",
)
parser.add_argument(
"-C", "--carray", action="store_true", help="convert binary file to a C array, not UF2"
)
args = parser.parse_args()
appstartaddr = int(args.base, 0)
if args.family.upper() in families:
familyid = families[args.family.upper()]
else:
try:
familyid = int(args.family, 0)
except ValueError:
error("Family ID needs to be a number or one of: " + ", ".join(families.keys()))
if args.list:
list_drives()
else:
if not args.input:
error("Need input file")
with open(args.input, mode="rb") as f:
inpbuf = f.read()
from_uf2 = is_uf2(inpbuf)
ext = "uf2"
if from_uf2:
outbuf = convert_from_uf2(inpbuf)
ext = "bin"
elif is_hex(inpbuf):
outbuf = convert_from_hex_to_uf2(inpbuf.decode("utf-8"))
elif args.carray:
outbuf = convert_to_carray(inpbuf)
ext = "h"
else:
outbuf = convert_to_uf2(inpbuf)
print(
"Converting to %s, output size: %d, start address: 0x%x"
% (ext, len(outbuf), appstartaddr)
)
if args.convert:
drives = []
if args.output == None:
args.output = "flash." + ext
else:
drives = get_drives()
if args.output:
write_file(args.output, outbuf)
else:
if len(drives) == 0:
error("No drive to deploy.")
for d in drives:
print("Flashing %s (%s)" % (d, board_id(d)))
write_file(d + "/NEW.UF2", outbuf)
if __name__ == "__main__":
main()
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/uf2conv.py | Python | apache-2.0 | 10,694 |
#
# upip - Package manager for MicroPython
#
# Copyright (c) 2015-2018 Paul Sokolovsky
#
# Licensed under the MIT license.
#
import sys
import gc
import uos as os
import uerrno as errno
import ujson as json
import uzlib
import upip_utarfile as tarfile
gc.collect()
debug = False
index_urls = ["https://micropython.org/pi", "https://pypi.org/pypi"]
install_path = None
cleanup_files = []
gzdict_sz = 16 + 15
file_buf = bytearray(512)
class NotFoundError(Exception):
pass
def op_split(path):
if path == "":
return ("", "")
r = path.rsplit("/", 1)
if len(r) == 1:
return ("", path)
head = r[0]
if not head:
head = "/"
return (head, r[1])
def op_basename(path):
return op_split(path)[1]
# Expects *file* name
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.errno != errno.EEXIST and e.errno != errno.EISDIR:
raise e
ret = False
return ret
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)
def install_tar(f, prefix):
meta = {}
for info in f:
# print(info)
fname = info.name
try:
fname = fname[fname.index("/") + 1 :]
except ValueError:
fname = ""
save = True
for p in ("setup.", "PKG-INFO", "README"):
# print(fname, p)
if fname.startswith(p) or ".egg-info" in fname:
if fname.endswith("/requires.txt"):
meta["deps"] = f.extractfile(info).read()
save = False
if debug:
print("Skipping", fname)
break
if save:
outfname = prefix + fname
if info.type != tarfile.DIRTYPE:
if debug:
print("Extracting " + outfname)
_makedirs(outfname)
subf = f.extractfile(info)
save_file(outfname, subf)
return meta
def expandhome(s):
if "~/" in s:
h = os.getenv("HOME")
s = s.replace("~/", h + "/")
return s
import ussl
import usocket
warn_ussl = True
def url_open(url):
global warn_ussl
if debug:
print(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:
fatal("Unable to resolve %s (no Internet?)" % host, e)
# print("Address infos:", ai)
ai = ai[0]
s = usocket.socket(ai[0], ai[1], ai[2])
try:
# print("Connect address:", addr)
s.connect(ai[-1])
if proto == "https:":
s = ussl.wrap_socket(s, server_hostname=host)
if warn_ussl:
print("Warning: %s SSL certificate is not validated" % host)
warn_ussl = False
# MicroPython rawsocket module supports file interface directly
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":
raise NotFoundError("Package not found")
raise ValueError(status)
while 1:
l = s.readline()
if not l:
raise ValueError("Unexpected EOF in HTTP headers")
if l == b"\r\n":
break
except Exception as e:
s.close()
raise e
return s
def get_pkg_metadata(name):
for url in index_urls:
try:
f = url_open("%s/%s/json" % (url, name))
except NotFoundError:
continue
try:
return json.load(f)
finally:
f.close()
raise NotFoundError("Package not found")
def fatal(msg, exc=None):
print("Error:", msg)
if exc and debug:
raise exc
sys.exit(1)
def install_pkg(pkg_spec, install_path):
data = get_pkg_metadata(pkg_spec)
latest_ver = data["info"]["version"]
packages = data["releases"][latest_ver]
del data
gc.collect()
assert len(packages) == 1
package_url = packages[0]["url"]
print("Installing %s %s from %s" % (pkg_spec, latest_ver, package_url))
package_fname = op_basename(package_url)
f1 = url_open(package_url)
try:
f2 = uzlib.DecompIO(f1, gzdict_sz)
f3 = tarfile.TarFile(fileobj=f2)
meta = install_tar(f3, install_path)
finally:
f1.close()
del f3
del f2
gc.collect()
return meta
def install(to_install, install_path=None):
# Calculate gzip dictionary size to use
global gzdict_sz
sz = gc.mem_free() + gc.mem_alloc()
if sz <= 65536:
gzdict_sz = 16 + 12
if install_path is None:
install_path = get_install_path()
if install_path[-1] != "/":
install_path += "/"
if not isinstance(to_install, list):
to_install = [to_install]
print("Installing to: " + install_path)
# sets would be perfect here, but don't depend on them
installed = []
try:
while to_install:
if debug:
print("Queue:", to_install)
pkg_spec = to_install.pop(0)
if pkg_spec in installed:
continue
meta = install_pkg(pkg_spec, install_path)
installed.append(pkg_spec)
if debug:
print(meta)
deps = meta.get("deps", "").rstrip()
if deps:
deps = deps.decode("utf-8").split("\n")
to_install.extend(deps)
except Exception as e:
print(
"Error installing '{}': {}, packages may be partially installed".format(pkg_spec, e),
file=sys.stderr,
)
def get_install_path():
global install_path
if install_path is None:
# sys.path[0] is current module's path
install_path = sys.path[1]
install_path = expandhome(install_path)
return install_path
def cleanup():
for fname in cleanup_files:
try:
os.unlink(fname)
except OSError:
print("Warning: Cannot delete " + fname)
def help():
print(
"""\
upip - Simple PyPI package manager for MicroPython
Usage: micropython -m upip install [-p <path>] <package>... | -r <requirements.txt>
import upip; upip.install(package_or_list, [<path>])
If <path> is not given, packages will be installed into sys.path[1]
(can be set from MICROPYPATH environment variable, if current system
supports that)."""
)
print("Current value of sys.path[1]:", sys.path[1])
print(
"""\
Note: only MicroPython packages (usually, named micropython-*) are supported
for installation, upip does not support arbitrary code in setup.py.
"""
)
def main():
global debug
global index_urls
global install_path
install_path = None
if len(sys.argv) < 2 or sys.argv[1] == "-h" or sys.argv[1] == "--help":
help()
return
if sys.argv[1] != "install":
fatal("Only 'install' command supported")
to_install = []
i = 2
while i < len(sys.argv) and sys.argv[i][0] == "-":
opt = sys.argv[i]
i += 1
if opt == "-h" or opt == "--help":
help()
return
elif opt == "-p":
install_path = sys.argv[i]
i += 1
elif opt == "-r":
list_file = sys.argv[i]
i += 1
with open(list_file) as f:
while True:
l = f.readline()
if not l:
break
if l[0] == "#":
continue
to_install.append(l.rstrip())
elif opt == "-i":
index_urls = [sys.argv[i]]
i += 1
elif opt == "--debug":
debug = True
else:
fatal("Unknown/unsupported option: " + opt)
to_install.extend(sys.argv[i:])
if not to_install:
help()
return
install(to_install)
if not debug:
cleanup()
if __name__ == "__main__":
main()
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/upip.py | Python | apache-2.0 | 8,673 |
import uctypes
# http://www.gnu.org/software/tar/manual/html_node/Standard.html
TAR_HEADER = {
"name": (uctypes.ARRAY | 0, uctypes.UINT8 | 100),
"size": (uctypes.ARRAY | 124, uctypes.UINT8 | 11),
}
DIRTYPE = "dir"
REGTYPE = "file"
def roundup(val, align):
return (val + align - 1) & ~(align - 1)
class FileSection:
def __init__(self, f, content_len, aligned_len):
self.f = f
self.content_len = content_len
self.align = aligned_len - content_len
def read(self, sz=65536):
if self.content_len == 0:
return b""
if sz > self.content_len:
sz = self.content_len
data = self.f.read(sz)
sz = len(data)
self.content_len -= sz
return data
def readinto(self, buf):
if self.content_len == 0:
return 0
if len(buf) > self.content_len:
buf = memoryview(buf)[: self.content_len]
sz = self.f.readinto(buf)
self.content_len -= sz
return sz
def skip(self):
sz = self.content_len + self.align
if sz:
buf = bytearray(16)
while sz:
s = min(sz, 16)
self.f.readinto(buf, s)
sz -= s
class TarInfo:
def __str__(self):
return "TarInfo(%r, %s, %d)" % (self.name, self.type, self.size)
class TarFile:
def __init__(self, name=None, fileobj=None):
if fileobj:
self.f = fileobj
else:
self.f = open(name, "rb")
self.subf = None
def next(self):
if self.subf:
self.subf.skip()
buf = self.f.read(512)
if not buf:
return None
h = uctypes.struct(uctypes.addressof(buf), TAR_HEADER, uctypes.LITTLE_ENDIAN)
# Empty block means end of archive
if h.name[0] == 0:
return None
d = TarInfo()
d.name = str(h.name, "utf-8").rstrip("\0")
d.size = int(bytes(h.size), 8)
d.type = [REGTYPE, DIRTYPE][d.name[-1] == "/"]
self.subf = d.subf = FileSection(self.f, d.size, roundup(d.size, 512))
return d
def __iter__(self):
return self
def __next__(self):
v = self.next()
if v is None:
raise StopIteration
return v
def extractfile(self, tarinfo):
return tarinfo.subf
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/upip_utarfile.py | Python | apache-2.0 | 2,371 |
#!/usr/bin/env python3
import re
import subprocess
import sys
verbosity = 0 # Show what's going on, 0 1 or 2.
suggestions = 1 # Set to 0 to not include lengthy suggestions in error messages.
def verbose(*args):
if verbosity:
print(*args)
def very_verbose(*args):
if verbosity > 1:
print(*args)
def git_log(pretty_format, *args):
# Delete pretty argument from user args so it doesn't interfere with what we do.
args = ["git", "log"] + [arg for arg in args if "--pretty" not in args]
args.append("--pretty=format:" + pretty_format)
very_verbose("git_log", *args)
# Generator yielding each output line.
for line in subprocess.Popen(args, stdout=subprocess.PIPE).stdout:
yield line.decode().rstrip("\r\n")
def verify(sha):
verbose("verify", sha)
errors = []
warnings = []
def error_text(err):
return "commit " + sha + ": " + err
def error(err):
errors.append(error_text(err))
def warning(err):
warnings.append(error_text(err))
# Author and committer email.
for line in git_log("%ae%n%ce", sha, "-n1"):
very_verbose("email", line)
if "noreply" in line:
error("Unwanted email address: " + line)
# Message body.
raw_body = list(git_log("%B", sha, "-n1"))
if not raw_body:
error("Message is empty")
return errors, warnings
# Subject line.
subject_line = raw_body[0]
very_verbose("subject_line", subject_line)
subject_line_format = r"^[^!]+: [A-Z]+.+ .+\.$"
if not re.match(subject_line_format, subject_line):
error("Subject line should match " + repr(subject_line_format) + ": " + subject_line)
if len(subject_line) >= 73:
error("Subject line should be 72 or less characters: " + subject_line)
# Second one divides subject and body.
if len(raw_body) > 1 and raw_body[1]:
error("Second message line should be empty: " + raw_body[1])
# Message body lines.
for line in raw_body[2:]:
if len(line) >= 76:
error("Message lines should be 75 or less characters: " + line)
if not raw_body[-1].startswith("Signed-off-by: ") or "@" not in raw_body[-1]:
warning("Message should be signed-off")
return errors, warnings
def run(args):
verbose("run", *args)
has_errors = False
has_warnings = False
for sha in git_log("%h", *args):
errors, warnings = verify(sha)
has_errors |= any(errors)
has_warnings |= any(warnings)
for err in errors:
print("error:", err)
for err in warnings:
print("warning:", err)
if has_errors or has_warnings:
if suggestions:
print("See https://github.com/micropython/micropython/blob/master/CODECONVENTIONS.md")
else:
print("ok")
if has_errors:
sys.exit(1)
def show_help():
print("usage: verifygitlog.py [-v -n -h] ...")
print("-v : increase verbosity, can be speficied multiple times")
print("-n : do not print multi-line suggestions")
print("-h : print this help message and exit")
print("... : arguments passed to git log to retrieve commits to verify")
print(" see https://www.git-scm.com/docs/git-log")
print(" passing no arguments at all will verify all commits")
print("examples:")
print("verifygitlog.py -n10 # Check last 10 commits")
print("verifygitlog.py -v master..HEAD # Check commits since master")
if __name__ == "__main__":
args = sys.argv[1:]
verbosity = args.count("-v")
suggestions = args.count("-n") == 0
if "-h" in args:
show_help()
else:
args = [arg for arg in args if arg not in ["-v", "-n", "-h"]]
run(args)
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/verifygitlog.py | Python | apache-2.0 | 3,756 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Add by HaaS
# version = 1.1.1
"""
MIT License
Copyright (c) 2018 Alex Woo
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import os, sys, math, time, string, re, struct
import logging
logging.basicConfig(level=logging.INFO,
format='%(filename)s[line:%(lineno)d]: %(message)s')
# ymodem data header byte
SOH = b'\x01'
STX = b'\x02'
EOT = b'\x04'
ACK = b'\x06'
NAK = b'\x15'
CAN = b'\x18'
CRC = b'C'
class SendTask(object):
def __init__(self):
self._task_name = ""
self._task_size = 0
self._task_packets = 0
self._last_valid_packets_size = 0
self._sent_packets = 0
self._missing_sent_packets = 0
self._valid_sent_packets = 0
self._valid_sent_bytes = 0
def inc_sent_packets(self):
self._sent_packets += 1
def inc_missing_sent_packets(self):
self._missing_sent_packets += 1
def inc_valid_sent_packets(self):
self._valid_sent_packets += 1
def add_valid_sent_bytes(self, this_valid_sent_bytes):
self._valid_sent_bytes += this_valid_sent_bytes
def get_valid_sent_packets(self):
return self._valid_sent_packets
def get_valid_sent_bytes(self):
return self._valid_sent_bytes
def set_task_name(self, data_name):
self._task_name = data_name
def set_task_size(self, data_size):
self._task_size = data_size
self._task_packets = math.ceil(data_size / 1024)
self._last_valid_packets_size = data_size % 1024
class ReceiveTask(object):
def __init__(self):
self._task_name = ""
self._task_size = 0
self._task_packets = 0
self._last_valid_packets_size = 0
self._received_packets = 0
self._missing_received_packets = 0
self._valid_received_packets = 0
self._valid_received_bytes = 0
def inc_received_packets(self):
self._received_packets += 1
def inc_missing_received_packets(self):
self._missing_received_packets += 1
def inc_valid_received_packets(self):
self._valid_received_packets += 1
def add_valid_received_bytes(self, this_valid_received_bytes):
self._valid_received_bytes += this_valid_received_bytes
def get_task_packets(self):
return self._task_packets
def get_last_valid_packet_size(self):
return self._last_valid_packets_size
def get_valid_received_packets(self):
return self._valid_received_packets
def get_valid_received_bytes(self):
return self._valid_received_bytes
def set_task_name(self, data_name):
self._task_name = data_name
def set_task_size(self, data_size):
self._task_size = data_size
self._task_packets = math.ceil(data_size / 1024)
self._last_valid_packets_size = data_size % 1024
def get_task_name(self):
return self._task_name
def get_task_size(self):
return self._task_size
class YModemfile(object):
def __init__(self, getc, putc, header_pad=b'\x00', data_pad=b'\x1a'):
self.getc = getc
self.putc = putc
self.st = SendTask()
self.rt = ReceiveTask()
self.header_pad = header_pad
self.data_pad = data_pad
def abort(self, count=2):
for _ in range(count):
self.putc(CAN)
def send_file(self, file_path, retry=20, callback=None):
try:
file_stream = open(file_path, 'rb')
file_name = os.path.basename(file_path)
file_size = os.path.getsize(file_path)
file_sent = self.send(file_stream, file_name, file_size, retry, callback)
except IOError as e:
logging.debug(str(e))
finally:
file_stream.close()
print("***** File tranfer succeeded *****")
print("File: " + file_name)
print("Size: " + str(file_sent) + "Bytes")
return file_sent
def wait_for_next(self, ch):
cancel_count = 0
while True:
c = self.getc(1)
if c:
if c == ch:
logging.debug("<<< " + hex(ord(ch)))
break
elif c == CAN:
if cancel_count == 2:
return -1
else:
cancel_count += 1
else:
# logging.debug("Expected " + hex(ord(ch)) + ", but got " + hex(ord(c)))
logging.debug("Expected " + hex(ord(ch)) + ", but got " + str(c))
return 0
def received_data_found(self, pattern, buff):
matcher = re.compile(pattern)
if matcher.search(buff):
return True
return False
def send(self, data_stream, data_name, data_size, retry=20, callback=None):
packet_size = 1024
# [<<< CRC]
self.wait_for_next(CRC)
# [first packet >>>]
header = self._make_edge_packet_header()
if len(data_name) > 100:
data_name = data_name[:100]
self.st.set_task_name(data_name)
data_name += bytes.decode(self.header_pad)
data_size = str(data_size)
if len(data_size) > 20:
raise Exception("Data volume is too large!")
self.st.set_task_size(int(data_size))
data_size += bytes.decode(self.header_pad)
data = data_name + data_size
data = data.ljust(128, bytes.decode(self.header_pad))
checksum = self._make_send_checksum(data)
data_for_send = header + data.encode() + checksum
self.putc(data_for_send)
self.st.inc_sent_packets()
# data_in_hexstring = "".join("%02x" % b for b in data_for_send)
print("Packet 0 >>>")
# logging.debug(str(data_for_send))
# [<<< ACK]
# [<<< CRC]
self.wait_for_next(ACK)
self.wait_for_next(CRC)
# [data packet >>>]
# [<<< ACK]
error_count = 0
sequence = 1
while True:
data = data_stream.read(packet_size)
if not data:
logging.debug('EOF')
break
extracted_data_bytes = len(data)
if extracted_data_bytes <= 128:
packet_size = 128
header = self._make_data_packet_header(packet_size, sequence)
data = data.ljust(packet_size, self.data_pad)
checksum = self._make_send_checksum(data)
data_for_send = header + data + checksum
# data_in_hexstring = "".join("%02x" % b for b in data_for_send)
while True:
self.putc(data_for_send)
self.st.inc_sent_packets()
print("Packet " + str(sequence) + " >>>")
# logging.debug(str(data_for_send))
# time.sleep(0.1)
c = self.getc(1)
# logging.debug(str(c))
if c == ACK:
logging.debug("<<< ACK")
self.st.inc_valid_sent_packets()
self.st.add_valid_sent_bytes(extracted_data_bytes)
error_count = 0
break
elif c == NAK:
error_count += 1
self.st.inc_missing_sent_packets()
logging.debug("RETRY NAK" + str(error_count))
if error_count > retry:
self.abort()
print("")
print("***** File transfer failed . NAK received aborting *****")
print("")
return -2
else:
# c = self.getc(120)
logging.debug(str(c))
error_message = self.getc(128)
no_space_flag = self.received_data_found(b'No more free space', error_message)
if no_space_flag:
print("***** No more free space . aborting *****")
return -2
error_count += 1
self.st.inc_missing_sent_packets()
logging.debug("RETRY " + str(error_count))
if error_count > retry:
self.abort()
print("")
print("***** File transfer failed . aborting *****")
print("")
return -2
sequence = (sequence + 1) % 0x100
# [EOT >>>]
# [<<< NAK]
# [EOT >>>]
# [<<< ACK]
self.putc(EOT)
logging.debug(">>> EOT")
self.wait_for_next(NAK)
self.putc(EOT)
logging.debug(">>> EOT")
self.wait_for_next(ACK)
# [<<< CRC]
self.wait_for_next(CRC)
# [Final packet >>>]
header = self._make_edge_packet_header()
if sys.version_info.major == 2:
data = bytes.decode("").ljust(128, bytes.decode(self.header_pad))
else:
data = "".ljust(128, bytes.decode(self.header_pad))
checksum = self._make_send_checksum(data)
data_for_send = header + data.encode() + checksum
self.putc(data_for_send)
self.st.inc_sent_packets()
logging.debug("Packet End >>>")
print("")
print("***** File transfer completed *****")
print("")
self.wait_for_next(ACK)
return self.st.get_valid_sent_bytes()
def wait_for_header(self):
cancel_count = 0
while True:
c = self.getc(1)
if c:
if c == SOH or c == STX:
return c
elif c == CAN:
if cancel_count == 2:
return -1
else:
cancel_count += 1
else:
logging.debug("Expected 0x01(SOH)/0x02(STX)/0x18(CAN), but got " + hex(ord(c)))
def wait_for_eot(self):
eot_count = 0
while True:
c = self.getc(1)
if c:
if c == EOT:
eot_count += 1
if eot_count == 1:
logging.debug("EOT >>>")
self.putc(NAK)
logging.debug("<<< NAK")
elif eot_count == 2:
logging.debug("EOT >>>")
self.putc(ACK)
logging.debug("<<< ACK")
self.putc(CRC)
logging.debug("<<< CRC")
break
else:
logging.debug("Expected 0x04(EOT), but got " + hex(ord(c)))
def recv_file(self, root_path, callback=None):
while True:
self.putc(CRC)
logging.debug("<<< CRC")
c = self.getc(1)
if c:
if c == SOH:
packet_size = 128
break
elif c == STX:
packet_size = 1024
break
else:
logging.debug("Expected 0x01(SOH)/0x02(STX)/0x18(CAN), but got " + hex(ord(c)))
IS_FIRST_PACKET = True
FIRST_PACKET_RECEIVED = False
WAIT_FOR_EOT = False
WAIT_FOR_END_PACKET = False
sequence = 0
while True:
if WAIT_FOR_EOT:
self.wait_for_eot()
WAIT_FOR_EOT = False
WAIT_FOR_END_PACKET = True
sequence = 0
else:
if IS_FIRST_PACKET:
IS_FIRST_PACKET = False
else:
c = self.wait_for_header()
if c == SOH:
packet_size = 128
elif c == STX:
packet_size = 1024
else:
return c
seq = self.getc(1)
if seq is None:
seq_oc = None
else:
seq = ord(seq)
c = self.getc(1)
if c is not None:
seq_oc = 0xFF - ord(c)
data = self.getc(packet_size + 2)
if not (seq == seq_oc == sequence):
continue
else:
valid, _ = self._verify_recv_checksum(data)
if valid:
# first packet
# [<<< ACK]
# [<<< CRC]
if seq == 0 and not FIRST_PACKET_RECEIVED and not WAIT_FOR_END_PACKET:
logging.debug("Packet 0 >>>")
self.putc(ACK)
logging.debug("<<< ACK")
self.putc(CRC)
logging.debug("<<< CRC")
file_name_bytes, data_size_bytes = (data[:-2]).rstrip(self.header_pad).split(self.header_pad)
file_name = bytes.decode(file_name_bytes)
data_size = bytes.decode(data_size_bytes)
logging.debug("TASK: " + file_name + " " + data_size + "Bytes")
self.rt.set_task_name(file_name)
self.rt.set_task_size(int(data_size))
file_stream = open(os.path.join(root_path, file_name), 'wb+')
FIRST_PACKET_RECEIVED = True
sequence = (sequence + 1) % 0x100
# data packet
# [data packet >>>]
# [<<< ACK]
elif not WAIT_FOR_END_PACKET:
self.rt.inc_valid_received_packets()
logging.debug("Packet " + str(sequence) + " >>>")
valid_data = data[:-2]
# last data packet
if self.rt.get_valid_received_packets() == self.rt.get_task_packets():
valid_data = valid_data[:self.rt.get_last_valid_packet_size()]
WAIT_FOR_EOT = True
self.rt.add_valid_received_bytes(len(valid_data))
file_stream.write(valid_data)
self.putc(ACK)
logging.debug("<<< ACK")
sequence = (sequence + 1) % 0x100
# final packet
# [<<< ACK]
else:
logging.debug("Packet End >>>")
self.putc(ACK)
logging.debug("<<< ACK")
break
file_stream.close()
logging.debug("File: " + self.rt.get_task_name())
logging.debug("Size: " + str(self.rt.get_task_size()) + "Bytes")
return self.rt.get_valid_received_bytes()
# Header byte
def _make_edge_packet_header(self):
_bytes = [ord(SOH), 0, 0xff]
return bytearray(_bytes)
def _make_data_packet_header(self, packet_size, sequence):
assert packet_size in (128, 1024), packet_size
_bytes = []
if packet_size == 128:
_bytes.append(ord(SOH))
elif packet_size == 1024:
_bytes.append(ord(STX))
_bytes.extend([sequence, 0xff - sequence])
return bytearray(_bytes)
# Make check code
def _make_send_checksum(self, data):
_bytes = []
crc = self.calc_crc(data)
_bytes.extend([crc >> 8, crc & 0xff])
return bytearray(_bytes)
def _verify_recv_checksum(self, data):
_checksum = bytearray(data[-2:])
their_sum = (_checksum[0] << 8) + _checksum[1]
data = data[:-2]
our_sum = self.calc_crc(data)
valid = bool(their_sum == our_sum)
return valid, data
# For CRC algorithm
crctable = [
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0,
]
# CRC algorithm: CCITT-0
def calc_crc(self, data, crc=0):
if sys.version_info.major == 2:
ba = struct.unpack("@%dB" % len(data), data)
else:
if isinstance(data, str):
ba = bytearray(data, 'utf-8')
else:
ba = bytearray(data)
for char in ba:
crctbl_idx = ((crc >> 8) ^ char) & 0xff
crc = ((crc << 8) ^ self.crctable[crctbl_idx]) & 0xffff
return crc & 0xffff
| YifuLiu/AliOS-Things | components/py_engine/engine/tools/ymodemfile.py | Python | apache-2.0 | 19,883 |
"""
Copyright (C) 2015-2020 Alibaba Group Holding Limited
The driver for AP3216C chip, The AP3216C is an integrated ALS & PS module
that includes a digital ambient light sensor [ALS], a proximity sensor [PS],
and an IR LED in a single package.
"""
from micropython import const
from driver import I2C
from utime import sleep_ms
import math
AP3216C_ADDR = const(0x1e)
# System Register
AP3216C_SYS_CONFIGURATION_REG = const(0x00)
AP3216C_SYS_INT_STATUS_REG = const(0x01)
AP3216C_SYS_INT_CLEAR_MANNER_REG = const(0x02)
AP3216C_IR_DATA_L_REG = const(0x0A)
AP3216C_IR_DATA_H_REG = const(0x0B)
AP3216C_ALS_DATA_L_REG = const(0x0C)
AP3216C_ALS_DATA_H_REG = const(0x0D)
AP3216C_PS_DATA_L_REG = const(0x0E)
AP3216C_PS_DATA_H_REG = const(0x0F)
# ALS Register
AP3216C_ALS_CONFIGURATION_REG = const(0x10)
AP3216C_ALS_CALIBRATION_REG = const(0x19)
AP3216C_ALS_THRESHOLD_LOW_L_REG = const(0x1A)
AP3216C_ALS_THRESHOLD_LOW_H_REG = const(0x1B)
AP3216C_ALS_THRESHOLD_HIGH_L_REG = const(0x1C)
AP3216C_ALS_THRESHOLD_HIGH_H_REG = const(0x1D)
# PS Register
AP3216C_PS_CONFIGURATION_REG = const(0x20)
AP3216C_PS_LED_DRIVER_REG = const(0x21)
AP3216C_PS_INT_FORM_REG = const(0x22)
AP3216C_PS_MEAN_TIME_REG = const(0x23)
AP3216C_PS_LED_WAITING_TIME_REG = const(0x24)
AP3216C_PS_CALIBRATION_L_REG = const(0x28)
AP3216C_PS_CALIBRATION_H_REG = const(0x29)
AP3216C_PS_THRESHOLD_LOW_L_REG = const(0x2A)
AP3216C_PS_THRESHOLD_LOW_H_REG = const(0x2B)
AP3216C_PS_THRESHOLD_HIGH_L_REG = const(0x2C)
AP3216C_PS_THRESHOLD_HIGH_H_REG = const(0x2D)
#mode value
AP3216C_MODE_POWER_DOWN = const(0x0)
AP3216C_MODE_ALS = const(0x1)
AP3216C_MODE_PS = const(0x2)
AP3216C_MODE_ALS_AND_PS = const(0x3)
AP3216C_MODE_SW_RESET = const(0x4)
AP3216C_MODE_ALS_ONCE = const(0x5)
AP3216C_MODE_PS_ONCE = const(0x6)
AP3216C_MODE_ALS_AND_PS_ONCE = const(0x7)
#ap3216c_int_clear_manner
AP3216C_INT_CLEAR_MANNER_BY_READING = const(0x0)
AP3216C_ALS_CLEAR_MANNER_BY_SOFTWARE = const(0x1)
#als_range
AP3216C_ALS_RANGE_20661 = const(0x0)
AP3216C_ALS_RANGE_5162 = const(0x1)
AP3216C_ALS_RANGE_1291 = const(0x2)
AP3216C_ALS_RANGE_323 = const(0x3)
#als_range
AP3216C_PS_GAIN1 = const(0x0)
AP3216C_PS_GAIN2 = const(0x1)
AP3216C_PS_GAIN4 = const(0x2)
AP3216C_PS_GAIN8 = const(0x3)
AP3216C_SYSTEM_MODE = const(0x0)
AP3216C_INT_PARAM = const(0x1)
AP3216C_ALS_RANGE = const(0x2)
AP3216C_ALS_PERSIST = const(0x3)
AP3216C_ALS_CALIBRATION = const(0x4)
AP3216C_ALS_LOW_THRESHOLD_L = const(0x5)
AP3216C_ALS_LOW_THRESHOLD_H = const(0x6)
AP3216C_ALS_HIGH_THRESHOLD_L = const(0x7)
AP3216C_ALS_HIGH_THRESHOLD_H = const(0x8)
AP3216C_PS_INTEGRATED_TIME = const(0x9)
AP3216C_PS_GAIN = const(0xa)
AP3216C_PS_PERSIST = const(0xb)
AP3216C_PS_LED_CONTROL = const(0xc)
AP3216C_PS_LED_DRIVER_RATIO = const(0xd)
AP3216C_PS_INT_MODE = const(0xe)
AP3216C_PS_MEAN_TIME = const(0xf)
AP3216C_PS_WAITING_TIME = const(0x10)
AP3216C_PS_CALIBRATION_L = const(0x11)
AP3216C_PS_CALIBRATION_H = const(0x12)
AP3216C_PS_LOW_THRESHOLD_L = const(0x13)
AP3216C_PS_LOW_THRESHOLD_H = const(0x14)
AP3216C_PS_HIGH_THRESHOLD_L = const(0x15)
AP3216C_PS_HIGH_THRESHOLD_H = const(0x16)
class AP3216CError(Exception):
def __init__(self, value=0, msg="ap3216c common error"):
self.value = value
self.msg = msg
def __str__(self):
return "Error code:%d, Error message: %s" % (self.value, str(self.msg))
__repr__ = __str__
class AP3216C(object):
"""
This class implements ap3216c chip's defs.
"""
def __init__(self):
self.i2cDev = None
def open(self, devid):
self.i2cDev = I2C()
self.i2cDev.open(devid)
# 写寄存器的值
def write_reg(self, addr, data):
msgbuf = bytearray([data])
self.i2cDev.writeReg(addr, msgbuf)
print("--> write addr " + str(addr) + ", value = " + str(msgbuf))
# 读寄存器的值
def read_regs(self, addr, len):
buf = bytearray(len)
self.i2cDev.readReg(addr, buf)
print("--> read " + str(len) + " bytes from addr " + str(addr) + ", " + str(len) + " bytes value = " + str(buf))
return buf;
# 软件复位传感器
def reset_sensor(self):
self.write_reg(AP3216C_SYS_CONFIGURATION_REG, AP3216C_MODE_SW_RESET); # reset
def read_low_and_high(self, reg, len):
# buf
# buf[0] = self.read_regs(reg, len) # 读低字节
# buf[1] = self.read_regs(reg + 1, len) # 读高字节
data = self.read_regs(reg, len)[0] | (self.read_regs(reg + 1, len)[0] << len * 8) # 合并数据
if (data > (1 << 15)):
data = data - (1<<16)
return data
def ap3216c_get_IntStatus(self):
# 读中断状态寄存器
IntStatus = self.read_regs(AP3216C_SYS_INT_STATUS_REG, 1)[0]
# IntStatus 第 0 位表示 ALS 中断,第 1 位表示 PS 中断。
return IntStatus # 返回状态
def ap3216c_int_init(self):
print("ap3216c_int_init")
#配置 中断输入引脚
def ap3216c_int_Config(self):
print("ap3216c_int_Config")
#初始化入口
def init(self):
# reset ap3216c
self.reset_sensor()
sleep_ms(100)
self.ap3216c_set_param(AP3216C_SYSTEM_MODE, AP3216C_MODE_ALS_AND_PS)
sleep_ms(150) # delay at least 112.5ms
self.ap3216c_int_Config()
self.ap3216c_int_init()
# This function reads light by ap3216c sensor measurement
# @param no
# @return the ambient light converted to float data.
#
def ap3216c_read_ambient_light(self):
read_data = self.read_low_and_high(AP3216C_ALS_DATA_L_REG, 1)
range = self.ap3216c_get_param(AP3216C_ALS_RANGE)
print("ap3216c_read_ambient_light read_data is " , read_data, range)
if (range == AP3216C_ALS_RANGE_20661):
brightness = 0.35 * read_data # sensor ambient light converse to reality
elif (range == AP3216C_ALS_RANGE_5162):
brightness = 0.0788 * read_data # sensor ambient light converse to reality
elif (range == AP3216C_ALS_RANGE_1291):
brightness = 0.0197 * read_data # sensor ambient light converse to reality
elif (range == AP3216C_ALS_RANGE_323):
brightness = 0.0049 * read_data # sensor ambient light converse to reality
return brightness
#This function reads proximity by ap3216c sensor measurement
#@param no
#@return the proximity data.
def ap3216c_read_ps_data(self):
read_data = self.read_low_and_high(AP3216C_PS_DATA_L_REG, 1) # read two data
print("ap3216c_read_ps_data read_data is " , read_data);
if (1 == ((read_data >> 6) & 0x01 or (read_data >> 14) & 0x01)) :
return 55555 # 红外过高(IR),PS无效 返回一个 55555 的无效数据
proximity = (read_data & 0x000f) + (((read_data >> 8) & 0x3f) << 4)
# sensor proximity converse to reality
if (proximity > (1 << 15)) :
proximity = proximity - (1<<16)
proximity |= read_data & 0x8000 # 取最高位,0 表示物体远离,1 表示物体靠近
return proximity # proximity 后十位是数据位,最高位为状态位
#This function reads ir by ap3216c sensor measurement
#@param no
#@return the ir data.
def ap3216c_read_ir_data(self):
read_data = self.read_low_and_high(AP3216C_IR_DATA_L_REG, 1) # read two data
print("ap3216c_read_ir_data read_data is" , read_data);
proximity = (read_data & 0x0003) + ((read_data >> 8) & 0xFF)
# sensor proximity converse to reality
if (proximity > (1 << 15)) :
proximity = proximity - (1<<16)
return proximity
#This function sets parameter of ap3216c sensor
#@param cmd the parameter cmd of device
#@param value for setting value in cmd register
#@return the setting parameter status,RT_EOK reprensents setting successfully.
def ap3216c_set_param(self, cmd, value):
if cmd == AP3216C_SYSTEM_MODE:
# default 000,power down
self.write_reg(AP3216C_SYS_CONFIGURATION_REG, value)
elif cmd == AP3216C_INT_PARAM:
self.write_reg(AP3216C_SYS_INT_CLEAR_MANNER_REG, value)
elif cmd == AP3216C_ALS_RANGE:
args = self.read_regs(AP3216C_ALS_CONFIGURATION_REG, 1)[0]
args &= 0xcf
args |= value << 4
self.write_reg(AP3216C_ALS_CONFIGURATION_REG, args)
elif cmd == AP3216C_ALS_PERSIST:
args = self.read_regs(AP3216C_ALS_CONFIGURATION_REG, 1)[0]
args &= 0xf0
args |= value
self.write_reg(AP3216C_ALS_CONFIGURATION_REG, args)
elif cmd == AP3216C_ALS_LOW_THRESHOLD_L:
self.write_reg(AP3216C_ALS_THRESHOLD_LOW_L_REG, value)
elif cmd == AP3216C_ALS_LOW_THRESHOLD_H:
self.write_reg(AP3216C_ALS_THRESHOLD_LOW_H_REG, value)
elif cmd == AP3216C_ALS_HIGH_THRESHOLD_L:
self.write_reg(AP3216C_ALS_THRESHOLD_HIGH_L_REG, value)
elif cmd == AP3216C_ALS_HIGH_THRESHOLD_H:
self.write_reg(AP3216C_ALS_THRESHOLD_HIGH_H_REG, value)
elif cmd == AP3216C_PS_GAIN:
args = self.read_regs(AP3216C_PS_CONFIGURATION_REG, 1)[0]
args &= 0xf3
args |= value
self.write_reg(AP3216C_PS_CONFIGURATION_REG, args)
elif cmd == AP3216C_PS_PERSIST:
args = self.read_regs(AP3216C_PS_CONFIGURATION_REG, 1)[0]
args &= 0xfc
args |= value
self.write_reg(AP3216C_PS_CONFIGURATION_REG, args)
elif cmd == AP3216C_PS_LOW_THRESHOLD_L:
self.write_reg(AP3216C_PS_THRESHOLD_LOW_L_REG, value)
elif cmd == AP3216C_PS_LOW_THRESHOLD_H:
self.write_reg(AP3216C_PS_THRESHOLD_LOW_H_REG, value)
elif cmd == AP3216C_PS_HIGH_THRESHOLD_L:
self.write_reg(AP3216C_PS_THRESHOLD_HIGH_L_REG, value)
elif cmd == AP3216C_PS_HIGH_THRESHOLD_H:
self.write_reg(AP3216C_PS_THRESHOLD_HIGH_H_REG, value)
#This function gets parameter of ap3216c sensor
#@param cmd the parameter cmd of device
#@param value to get value in cmd register
#@return the getting parameter status,RT_EOK reprensents getting successfully.
def ap3216c_get_param(self, cmd):
if cmd == AP3216C_SYSTEM_MODE:
value = self.read_regs(AP3216C_SYS_CONFIGURATION_REG, 1)[0]
elif cmd == AP3216C_INT_PARAM:
value = self.read_regs(AP3216C_SYS_INT_CLEAR_MANNER_REG, 1)[0]
elif cmd == AP3216C_ALS_RANGE:
value = self.read_regs(AP3216C_ALS_CONFIGURATION_REG, 1)[0]
temp = (value & 0xff) >> 4
value = temp
elif cmd == AP3216C_ALS_PERSIST:
temp = self.read_regs(AP3216C_ALS_CONFIGURATION_REG, 1)[0]
temp = value & 0x0f
value = temp
elif cmd == AP3216C_ALS_LOW_THRESHOLD_L:
value = self.read_regs(AP3216C_ALS_THRESHOLD_LOW_L_REG, 1)[0]
elif cmd == AP3216C_ALS_LOW_THRESHOLD_H:
value = self.read_regs(AP3216C_ALS_THRESHOLD_LOW_H_REG, 1)[0]
elif cmd == AP3216C_ALS_HIGH_THRESHOLD_L:
value = self.read_regs(AP3216C_ALS_THRESHOLD_HIGH_L_REG, 1)[0]
elif cmd == AP3216C_ALS_HIGH_THRESHOLD_H:
value = self.read_regs(AP3216C_ALS_THRESHOLD_HIGH_H_REG, 1)[0]
elif cmd == AP3216C_PS_GAIN:
temp = self.read_regs(AP3216C_PS_CONFIGURATION_REG, 1)[0]
value = (temp & 0xc) >> 2
elif cmd == AP3216C_PS_PERSIST:
temp = self.read_regs(AP3216C_PS_CONFIGURATION_REG, 1)[0]
value = temp & 0x3
elif cmd == AP3216C_PS_LOW_THRESHOLD_L:
value = self.read_regs(AP3216C_PS_THRESHOLD_LOW_L_REG, 1)[0]
elif cmd == AP3216C_PS_LOW_THRESHOLD_H:
value = self.read_regs(AP3216C_PS_THRESHOLD_LOW_H_REG, 1)[0]
elif cmd == AP3216C_PS_HIGH_THRESHOLD_L:
value = self.read_regs(AP3216C_PS_THRESHOLD_HIGH_L_REG, 1)[0]
elif cmd == AP3216C_PS_HIGH_THRESHOLD_H:
value = self.read_regs(AP3216C_PS_THRESHOLD_HIGH_H_REG, 1)[0]
return value
def close(self):
self.i2cDev.close()
| YifuLiu/AliOS-Things | components/py_engine/framework/ap3216c.py | Python | apache-2.0 | 12,470 |
# -*- coding: UTF-8 -*-
import _linkkit as _lk
import ujson
"""
阿里云物联网平台提供安全可靠的设备连接通信能力,支持设备数据采集上云,规则引擎流转数据和云端数据下发设备端。此外,也提供方便快捷的设备管理能力,支持物模型定义,数据结构化存储,和远程调试、监控、运维。 基于iot模块可以简单快速的使用阿里云物联网平台能力。
iot模块的主要实现是一个Device 类,通过它的构造函数获取device实例,就可以轻松设置相关回调函数和调用相关方法。阿里云物联网平台中涉及三个基本概念如下:
- 属性(prop)
云端/设备端数据互通的通道,云端通过改变prop值,反馈到设备端,设备端修改prop值,保存到云端
- 事件(event)
设备端到云端的事件通知
- 服务(service)
云端到设备端的服务调用
详细使用示例请参考主页”参考案例”中的云端连接/控制部分
"""
class Device(object):
"""
初始化物联网平台Device类,获取device实例
:param data(dict): data字典的key信息如下
.. list-table::
* - 属性
- 类型
- 是否必填
- 说明
* - deviceName
- 字符串
- Y
- 物联网平台上注册的设备名称
* - deviceSecret
- 字符串
- Y
- 物联网平台上注册的deviceSecret
* - productKey
- 字符串
- Y
- 物联网平台上注册的productKey
* - productSecret
- 字符串
- 可选
- 物联网平台上注册的productSecret
* - region
- 字符串
- 可选
- 默认值是'cn-shanghai'
使用示例::
import iot
productKey = "a1uTFk4xjko"
productSecret = "xxxxxxx"
deviceName = "mpy_001"
deviceSecret = "xxxxxxxxxxxxxxx"
key_info = {
'region' : 'cn-shanghai' ,
'productKey': productKey ,
'deviceName': deviceName ,
'deviceSecret': deviceSecret ,
'productSecret': productSecret
}
device = iot.Device(key_info)
"""
def __init__(self,data):
def __str_is_empty(value):
if value is None or value == "":
return True
else:
return False
if not isinstance(data,dict):
raise ValueError("Class Device init param must be dict")
if not 'productKey' in data:
raise ValueError('Device init : param must have key "productKey"')
elif __str_is_empty(data['productKey']):
raise ValueError("productKey wrong")
if not 'deviceName' in data:
raise ValueError('Device init : param must have key "deviceName"')
elif __str_is_empty(data['deviceName']):
raise ValueError("deviceName wrong")
if not 'deviceSecret' in data:
raise ValueError('Device init : param must have key "deviceSecret"')
elif __str_is_empty(data['deviceSecret']):
raise ValueError("deviceSecret wrong")
if 'productSecret' in data:
self.productSecret = data['productSecret']
else:
self.productSecret = ""
if 'region' in data:
self.region = data['region']
else:
self.region = "cn-shanghai"
self.data = data
# ret = _lk.init(region,data['productKey'],data['deviceName'],data['deviceSecret'],productSecret)
# print("init return :")
# print(ret)
# _lk.register_dyn_dev()
self._callback = {}
# def publish(self):
# pass
# def subscribe(self):
# pass
# def unsubscribe(self):
# pass
def on(self,event,callback):
"""
通过这个函数,可以设置物联网平台各种事件的处理函数,函数接收两个参数分别是事件名称和事件处理函数
:param event(str)): 需要注册的事件名称,类型是字符串
.. list-table::
* - 事件名称
- 事件说明
* - connect
- 当iot设备连接到物联网平台的时候触发'connect' 事件
* - disconnect
- 当连接断开时,触发'disconnect'事件
* - props
- 当iot云端下发属性设置时,触发'props'事件
* - service
- 当iot云端调用设备service时,触发'service'事件
* - error
- 当设备跟iot平台通信过程中遇到错误时,触发'error'事件
:param callback: 回调函数
使用示例::
def on_connect():
print('linkkit is connected')
device.on('connect',on_connect)
def on_disconnect():
print('linkkit is disconnected')
device.on('disconnect',on_disconnect)
def on_props(request):
print('clound req data is %s' %(request))
device.on('props',on_props)
def on_service(id,request):
print('clound req id is %d , req is %s' %(id,request))
device.on('service',on_service)
def on_error(err):
print('err msg is %s '%(err))
device.on('error',on_error)
"""
# if not callable(callback):
# raise ValueError("the 2nd param of function on must be function")
# if (event == 'connect'):
# _lk.register_call_back(_lk.ON_CONNECT,callback)
# elif (event == 'disconnect'):
# _lk.register_call_back(_lk.ON_DISCONNECT,callback)
# elif (event == 'close'):
# _lk.register_call_back(_lk.ON_CLOSE,callback)
# elif (event == 'error'):
# _lk.register_call_back(_lk.ON_ERROR,callback)
# elif (event == 'props'):
# _lk.register_call_back(_lk.ON_PROPS,callback)
# elif (event == 'service'):
# _lk.register_call_back(_lk.ON_SERVICE,callback)
self._callback[event] = callback
def connect(self):
'''
连接物联网平台连接函数,该函数是异步调用
'''
for key in self._callback:
event = key
callback = self._callback[key]
print(event)
# if not callable(callback):
# raise ValueError("the 2nd param of function on must be function")
if (event == 'connect'):
_lk.register_call_back(_lk.ON_CONNECT,callback)
elif (event == 'disconnect'):
_lk.register_call_back(_lk.ON_DISCONNECT,callback)
elif (event == 'close'):
_lk.register_call_back(_lk.ON_CLOSE,callback)
elif (event == 'error'):
_lk.register_call_back(_lk.ON_ERROR,callback)
elif (event == 'props'):
_lk.register_call_back(_lk.ON_PROPS,callback)
elif (event == 'service'):
_lk.register_call_back(_lk.ON_SERVICE,callback)
ret = _lk.init(self.region,self.data['productKey'],self.data['deviceName'],self.data['deviceSecret'],self.productSecret)
_lk.register_dyn_dev()
_lk.connect()
def postProps(self,data):
"""
上报设备属性
:param data(dict): 字典的key信息如下
.. list-table::
* - 属性
- 类型
- 是否必填
- 说明
* - params
- 字典
- Y
- 属性的值对应的是物联网平台的json数据
使用示例::
data = {
'params': {
'test_prop' : 100
}
}
device.postProps(data)
"""
if not isinstance(data, dict):
raise ValueError("postProps func param must be dict")
if not 'params' in data:
raise ValueError('data must have key: "params"')
return _lk.post_property(ujson.dumps(data['params']))
def postEvent(self,data):
"""
上报设备的事件
:param data(dict): 字典的key信息如下
.. list-table::
* - 属性
- 类型
- 是否必填
- 说明
* - params
- 字典
- Y
- 属性的值对应的是物联网平台的json数据
* - id
- 字符串
- Y
- 事件名称,请参考物模型上定义的事件id
使用示例::
data = {
'id': 'EventTest' ,
'params': {
'test_event' : 100
}
}
device.postEvent(data)
"""
if isinstance(data, dict):
if not 'id' in data:
raise ValueError('data must have key: "id"')
if not 'params' in data:
raise ValueError('data must have key: "params"')
else:
raise ValueError("postEvent func param must be dict")
return _lk.post_event(data['id'],ujson.dumps(data['params']))
def close(self):
'''
关闭物联网设备节点,断开连接
'''
return _lk.close()
def do_yield(self,time):
"""
激活物联网平台接收云端消息,并设置接收超时时间为:timeout, 单位是 ms.为了保证云端消息被接收到,执行了异步命令以后,需要循环执行这个方法,直到拿云端的返回
"""
_lk.do_yield(time)
# def __register_callback(self):
# _lk.register_call_back(1,self.__on_connect)
# _lk.register_call_back(3,self.__on_disconnect)
# _lk.register_call_back(5,self.__on_service_request)
# _lk.register_call_back(7,self.__on_prop_set)
# _lk.register_call_back(9,self.__on_thing_prop_post)
# _lk.register_call_back(10,self.__on_thing_event_post)
# class GateWay(object):
# def addTopo(self):
# pass
# def getTopo(self):
# pass
# def removeTopo(self):
# pass
# def login(self):
# pass
# def logout(self):
# pass
# def regiestSubDevice(self):
# pass
# def register():
# pass
| YifuLiu/AliOS-Things | components/py_engine/framework/iot.py | Python | apache-2.0 | 10,913 |
# -*- coding: UTF-8 -*-
"""
The driver for mpu6050 chip, it is a temperature and humidity sensor.
"""
from micropython import const
from driver import I2C
from utime import sleep_ms
import math
MPU_SELF_TESTX_REG = const(0X0D) #自检寄存器X
MPU_SELF_TESTY_REG = const(0X0E) #自检寄存器Y
MPU_SELF_TESTZ_REG = const(0X0F) #自检寄存器Z
MPU_SELF_TESTA_REG = const(0X10) #自检寄存器A
MPU_SAMPLE_RATE_REG = const(0X19) #采样频率分频器
MPU_CFG_REG = const(0X1A) #配置寄存器
MPU_GYRO_CFG_REG = const(0X1B) #陀螺仪配置寄存器
MPU_ACCEL_CFG_REG = const(0X1C) #加速度计配置寄存器
MPU_MOTION_DET_REG = const(0X1F) #运动检测阀值设置寄存器
MPU_FIFO_EN_REG = const(0X23) #FIFO使能寄存器
MPU_I2CMST_CTRL_REG = const(0X24) #IIC主机控制寄存器
MPU_I2CSLV0_ADDR_REG = const(0X25) #IIC从机0器件地址寄存器
MPU_I2CSLV0_REG = const(0X26) #IIC从机0数据地址寄存器
MPU_I2CSLV0_CTRL_REG = const(0X27) #IIC从机0控制寄存器
MPU_I2CSLV1_ADDR_REG = const(0X28) #IIC从机1器件地址寄存器
MPU_I2CSLV1_REG = const(0X29) #IIC从机1数据地址寄存器
MPU_I2CSLV1_CTRL_REG = const(0X2A) #IIC从机1控制寄存器
MPU_I2CSLV2_ADDR_REG = const(0X2B) #IIC从机2器件地址寄存器
MPU_I2CSLV2_REG = const(0X2C) #IIC从机2数据地址寄存器
MPU_I2CSLV2_CTRL_REG = const(0X2D) #IIC从机2控制寄存器
MPU_I2CSLV3_ADDR_REG = const(0X2E) #IIC从机3器件地址寄存器
MPU_I2CSLV3_REG = const(0X2F) #IC从机3数据地址寄存器
MPU_I2CSLV3_CTRL_REG = const(0X30) #IIC从机3控制寄存器
MPU_I2CSLV4_ADDR_REG = const(0X31) #IIC从机4器件地址寄存器
MPU_I2CSLV4_REG = const(0X32) #IIC从机4数据地址寄存器
MPU_I2CSLV4_DO_REG = const(0X33) #IIC从机4写数据寄存器
MPU_I2CSLV4_CTRL_REG = const(0X34) #IIC从机4控制寄存器
MPU_I2CSLV4_DI_REG = const(0X35) #IIC从机4读数据寄存器
MPU_I2CMST_STA_REG = const(0X36) #IIC主机状态寄存器
MPU_INTBP_CFG_REG = const(0X37) #中断/旁路设置寄存器
MPU_INT_EN_REG = const(0X38) #中断使能寄存器
MPU_INT_STA_REG = const(0X3A) #中断状态寄存器
MPU_ACCEL_XOUTH_REG = const(0X3B) #加速度值,X轴高8位寄存器
MPU_ACCEL_XOUTL_REG = const(0X3C) #速度值,X轴低8位寄存器
MPU_ACCEL_YOUTH_REG = const(0X3D) #加速度值,Y轴高8位寄存器
MPU_ACCEL_YOUTL_REG = const(0X3E) #加速度值,Y轴低8位寄存器
MPU_ACCEL_ZOUTH_REG = const(0X3F) #加速度值,Z轴高8位寄存器
MPU_ACCEL_ZOUTL_REG = const(0X40) #加速度值,Z轴低8位寄存器
MPU_TEMP_OUTH_REG = const(0X41) #温度值高八位寄存器
MPU_TEMP_OUTL_REG = const(0X42) #温度值低8位寄存器
MPU_GYRO_XOUTH_REG = const(0X43) #陀螺仪值,X轴高8位寄存器
MPU_GYRO_XOUTL_REG = const(0X44) #陀螺仪值,X轴低8位寄存器
MPU_GYRO_YOUTH_REG = const(0X45) #陀螺仪值,Y轴高8位寄存器
MPU_GYRO_YOUTL_REG = const(0X46) #陀螺仪值,Y轴低8位寄存器
MPU_GYRO_ZOUTH_REG = const(0X47) #陀螺仪值,Z轴高8位寄存器
MPU_GYRO_ZOUTL_REG = const(0X48) #陀螺仪值,Z轴低8位寄存器
MPU_I2CSLV0_DO_REG = const(0X63) #IIC从机0数据寄存器
MPU_I2CSLV1_DO_REG = const(0X64) #IIC从机1数据寄存器
MPU_I2CSLV2_DO_REG = const(0X65) #IIC从机2数据寄存器
MPU_I2CSLV3_DO_REG = const(0X66) #IIC从机3数据寄存器
MPU_I2CMST_DELAY_REG = const(0X67) #IIC主机延时管理寄存器
MPU_SIGPATH_RST_REG = const(0X68) #信号通道复位寄存器
MPU_MDETECT_CTRL_REG = const(0X69) #运动检测控制寄存器
MPU_USER_CTRL_REG = const(0X6A) #用户控制寄存器
MPU_PWR_MGMT1_REG = const(0X6B) #电源管理寄存器1
MPU_PWR_MGMT2_REG = const(0X6C) #电源管理寄存器2
MPU_FIFO_CNTH_REG = const(0X72) #FIFO计数寄存器高八位
MPU_FIFO_CNTL_REG = const(0X73) #FIFO计数寄存器低八位
MPU_FIFO_RW_REG = const(0X74) #FIFO读写寄存器
MPU_DEVICE_ID_REG = const(0X75) #器件ID寄存器
# 如果AD0脚(9脚)接地,IIC地址为0X68(不包含最低位).
# 如果接V3.3,则IIC地址为0X69(不包含最低位).
MPU_ADDR = const(0X69)
MPU_DEV_ID = const(0x68)
class MPU6050Error(Exception):
def __init__(self, value=0, msg="mpu6050 common error"):
self.value = value
self.msg = msg
def __str__(self):
return "Error code:%d, Error message: %s" % (self.value, str(self.msg))
__repr__ = __str__
class MPU6050(object):
"""
This class implements mpu6050 chip's defs.
"""
def __init__(self):
self.i2cDev = None
def open(self, devid):
self.i2cDev = I2C()
self.i2cDev.open(devid)
def i2c_write_byte(self, addr, value):
Reg = bytearray([addr, value])
self.i2cDev.write(Reg)
print("--> write addr " + str(addr) + ", value = " + str(value))
def i2c_read_byte(self, addr):
Reg = bytearray([addr])
self.i2cDev.write(Reg)
tmp = bytearray(1)
self.i2cDev.read(tmp)
print("<-- read addr " + str(addr) + ", value = " + str(tmp[0]))
return tmp[0]
def i2c_read_len(self, addr, len):
reg = bytearray([addr])
data = bytearray(len)
self.i2cDev.write(reg)
sleep_ms(20)
self.i2cDev.read(data)
# print("--> read " + str(len) + " bytes from addr " + str(addr) + ", " + str(len) + " bytes value = " + str(data))
return data
# 设置MPU6050陀螺仪传感器满量程范围
# fsr:0,±250dps;1,±500dps;2,±1000dps;3,±2000dps
# 返回值:0,设置成功
# 其他,设置失败
def MPU_Set_Gyro_Fsr(self, fsr):
return self.i2c_write_byte(MPU_GYRO_CFG_REG, fsr << 3) # 设置陀螺仪满量程范围
# 设置MPU6050加速度传感器满量程范围
# fsr:0,±2g;1,±4g;2,±8g;3,±16g
# 返回值:0,设置成功
# 其他,设置失败
def MPU_Set_Accel_Fsr(self, fsr):
return self.i2c_write_byte(MPU_ACCEL_CFG_REG, fsr << 3) # 设置加速度传感器满量程范围
# 设置MPU6050的数字低通滤波器
# lpf:数字低通滤波频率(Hz)
# 返回值:0,设置成功
# 其他,设置失败
def MPU_Set_LPF(self, lpf):
if (lpf >= 188):
data = 1
elif (lpf >= 98):
data = 2
elif (lpf >= 42):
data = 3
elif (lpf >= 20):
data = 4
elif (lpf >= 10):
data = 5
else:
data = 6
return self.i2c_write_byte(MPU_CFG_REG, data) # 设置数字低通滤波器
# 设置MPU6050的采样率(假定Fs=1KHz)
# rate:4~1000(Hz)
# 返回值:0,设置成功
# 其他,设置失败
def MPU_Set_Rate(self, rate):
if (rate > 1000):
rate = 1000
if (rate < 4):
rate = 4
data = 1000 // rate - 1
self.i2c_write_byte(MPU_SAMPLE_RATE_REG, data) # 设置数字低通滤波器
return self.MPU_Set_LPF(rate / 2) # 自动设置LPF为采样率的一半
# 得到温度值
# 返回值:温度值(扩大了100倍)
def get_Temperature(self):
buf = bytearray(2)
buf = self.i2c_read_len(MPU_TEMP_OUTH_REG, 2)
raw = (buf[0] << 8) | buf[1]
print("get_Temperature:",buf[0], buf[1], raw)
if (raw > (1 << 15)):
raw = raw - (1<<16)
temp = 36.53 + (raw) / 340
return temp * 100
# 得到陀螺仪值(原始值)
# gx,gy,gz:陀螺仪x,y,z轴的原始读数(带符号)
# 返回值:0,成功
# 其他,错误代码
def get_Gyroscope(self):
arr = [1, 2, 3]
buf = bytearray(6)
buf = self.i2c_read_len(MPU_GYRO_XOUTH_REG, 6)
gx = (buf[0] << 8) | buf[1]
gy = (buf[2] << 8) | buf[3]
gz = (buf[4] << 8) | buf[5]
if (gx > (1 << 15)):
gx = gx - (1<<16)
if (gy > (1 << 15)):
gy = gy - (1<<16)
if (gz > (1 << 15)):
gz = gz - (1<<16)
arr[0] = gx
arr[1] = gy
arr[2] = gz
return arr
# 得到加速度值(原始值)
# gx,gy,gz:陀螺仪x,y,z轴的原始读数(带符号)
# 返回值:0,成功
# 其他,错误代码
def get_Accelerometer(self):
arr = [1, 2, 3]
buf = bytearray(6)
buf = self.i2c_read_len(MPU_ACCEL_XOUTH_REG, 6)
ax = (buf[0] << 8) | buf[1]
ay = (buf[2] << 8) | buf[3]
az = (buf[4] << 8) | buf[5]
if (ax > (1 << 15)):
ax = ax - (1<<16)
if (ay > (1 << 15)):
ay = ay - (1<<16)
if (az > (1 << 15)) :
az = az - (1<<16)
arr[0] = ax
arr[1] = ay
arr[2] = az
return arr
# 初始化MPU6050
# 返回值:0,成功
# 其他,错误代码
def init(self):
device_id = 0
self.i2c_write_byte(MPU_PWR_MGMT1_REG, 0X80) # 复位MPU6050
sleep_ms(200)
self.i2c_write_byte(MPU_PWR_MGMT1_REG, 0X00) # 唤醒MPU6050
self.MPU_Set_Gyro_Fsr(3) # 陀螺仪传感器,±2000dps
self.MPU_Set_Accel_Fsr(0) # 加速度传感器,±2g
self.MPU_Set_Rate(50) # 设置采样率50Hz
self.i2c_write_byte(MPU_INT_EN_REG, 0X00) # 关闭所有中断
self.i2c_write_byte(MPU_USER_CTRL_REG, 0X00) # I2C主模式关闭
self.i2c_write_byte(MPU_FIFO_EN_REG, 0X00) # 关闭FIFO
self.i2c_write_byte(MPU_INTBP_CFG_REG, 0X80) # INT引脚低电平有效
device_id = self.i2c_read_byte(MPU_DEVICE_ID_REG)
if (device_id == MPU_DEV_ID):
# 器件ID正确
self.i2c_write_byte(MPU_PWR_MGMT1_REG, 0X01) # 设置CLKSEL,PLL X轴为参考
self.i2c_write_byte(MPU_PWR_MGMT2_REG, 0X00) # 加速度与陀螺仪都工作
self.MPU_Set_Rate(50) # 设置采样率为50Hz
return 0
else:
return 1
def close(self):
self.i2cDev.close()
| YifuLiu/AliOS-Things | components/py_engine/framework/mpu6050.py | Python | apache-2.0 | 10,046 |
# -*- coding: UTF-8 -*-
import netmgr as nm
import time
_wifi_connected = False
def singleton(cls, *args, **kw):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls(*args, **kw)
nm.init()
return instances[cls]
return getinstance
def _on_wifi_cb(data):
print('Get Wifi CallBack for wifi.py')
_wifi_connected = True
@singleton
class NetWorkClient:
"""
该模块实现网络管理相关的功能,包括初始化,联网,状态信息等.
"""
global _on_wifi_cb
def __init__(self):
nm.register_call_back(1,_on_wifi_cb)
def __str_is_empty(self,value):
if value is None or value == "":
return True
else:
return False
def connect(self,data):
"""
连接网络
:param data(dict): data的key信息如下
.. list-table::
* - 属性
- 类型
- 必填
- 说明
* - ssid
- 字符串
- 必填
- 需要连接的wifi热点名称
* - password
- 字符串
- 必填
- 需要连接的wifi密码
使用示例::
# -*- coding: UTF-8 -*-
import network
net = network.NetWorkClient()
net.connect({
'ssid' : 'KIDS' ,
'password' : '12345678'
}
)
"""
global _wifi_cb
if isinstance(data, dict):
pass
else:
raise ValueError("connect func param must be dict")
if not 'ssid' in data:
raise ValueError('connect : param must have key "ssid"')
elif self.__str_is_empty(data['ssid']):
raise ValueError("ssid wrong")
if not 'password' in data:
raise ValueError('connect : param must have key "password"')
elif self.__str_is_empty(data['password']):
raise ValueError("password wrong")
return nm.connect(data['ssid'],data['password'])
def disconnect(self):
"""
断开网络
"""
nm.disconnect()
def getType(self):
"""
获取当前网络类型:
:param 空:
:returns:
.. list-table::
* - 返回值
- 网络类型
* - 0
- WIFI
* - 1
- 蜂窝网络
* - 2
- 以太网
* - 3
- 未知网络
"""
return nm.getType()
def getStatus(self):
"""
获取当前网络状态
:param 空:
:returns:
.. list-table::
* - 返回值
- 连接状态
* - 0
- 断开连接中
* - 1
- 断开连接
* - 2
- 连接中
* - 3
- 连接成功
* - 4
- 获取ip中
* - 5
- 获取ip成功
* - 6
- 连接失败
* - 7
- 位置状态
- ``True`` 已连接
- ``False`` 未连接
"""
return nm.getStatus()
def getInfo(self):
"""
获取当前网络信息
:param 空:
:returns: 返回一个字典,字典信息如下
.. list-table::
* - key名称
- value类型
* - SSID
- 字符串
* - IP
- 字符串
* - MAC
- 字符串
* - RSSI
- Int
"""
return nm.getInfo()
def on(self,id,func):
nm.register_call_back(1,func)
| YifuLiu/AliOS-Things | components/py_engine/framework/network.py | Python | apache-2.0 | 4,101 |
# -*- coding: UTF-8 -*-
"""
The driver for qmc5883 chip
"""
from driver import I2C
from utime import sleep_ms
import math
QMC5883L_ADDR = 0x0D;
x_max = 0;
x_min = 0;
z_min = 0;
y_max = 0;
y_min = 0;
z_max = 0;
addr = 0;
mode = 0;
rate = 0;
g_range = 0;
oversampling = 0;
INT16_MIN = (-32767-1)
INT16_MAX = 32767
# Register numbers
QMC5883L_X_LSB = 0
QMC5883L_X_MSB = 1
QMC5883L_Y_LSB = 2
QMC5883L_Y_MSB = 3
QMC5883L_Z_LSB = 4
QMC5883L_Z_MSB = 5
QMC5883L_STATUS = 6
QMC5883L_TEMP_LSB = 7
QMC5883L_TEMP_MSB = 8
QMC5883L_CONFIG = 9
QMC5883L_CONFIG2 = 10
QMC5883L_RESET = 11
QMC5883L_RESERVED = 12
QMC5883L_CHIP_ID = 13
QMC5883L_STATUS_DRDY = 1
QMC5883L_STATUS_OVL = 2
QMC5883L_STATUS_DOR = 4
# Oversampling values for the CONFIG register
QMC5883L_CONFIG_OS512 = 0b00000000
QMC5883L_CONFIG_OS256 = 0b01000000
QMC5883L_CONFIG_OS128 = 0b10000000
QMC5883L_CONFIG_OS64 = 0b11000000
# Range values for the CONFIG register
QMC5883L_CONFIG_2GAUSS = 0b00000000
QMC5883L_CONFIG_8GAUSS = 0b00010000
# Rate values for the CONFIG register
QMC5883L_CONFIG_10HZ = 0b00000000
QMC5883L_CONFIG_50HZ = 0b00000100
QMC5883L_CONFIG_100HZ = 0b00001000
QMC5883L_CONFIG_200HZ = 0b00001100
# Mode values for the CONFIG register
QMC5883L_CONFIG_STANDBY = 0b00000000
QMC5883L_CONFIG_CONT = 0b00000001
# Apparently M_PI isn't available in all environments.
M_PI = 3.14159265358979323846264338327950288
class qmc5883Error(Exception):
def __init__(self, value=0, msg="qmc5883 common error"):
self.value = value
self.msg = msg
def __str__(self):
return "Error code:%d, Error message: %s" % (self.value, str(self.msg))
__repr__ = __str__
class QMC5883(object):
"""
This class implements qmc5883 chip's defs.
"""
def __init__(self):
self.i2cDev = None
def open(self, devid):
self.i2cDev = I2C()
self.i2cDev.open(devid)
def devRegRead1Byte(self, addr):
return self.devRegReadWrite1Byte(0, addr, 0);
def devRegReadWrite1Byte(self, mode, addr, value):
#0 read mode
#1 write mode
if (mode == 0):
Reg = bytearray([addr])
self.i2cDev.write(Reg);
sleep_ms(30)
tmp = bytearray(1)
self.i2cDev.read(tmp)
print("<-- read addr " + str(addr) + ", value = " + str(tmp[0]));
return tmp[0];
else:
Reg = bytearray([addr, value])
self.i2cDev.write(Reg);
print("--> write addr " + str(addr) + ", value = " + str(value));
return 0;
def devRegWrite1Byte(self, data):
Reg = bytearray([data])
self.i2cDev.write(Reg);
print("--> write value = " + str(Reg[0]));
def devRegReadNByte(self, addr, len):
reg = bytearray([addr]);
data = bytearray(len);
self.i2cDev.write(reg);
sleep_ms(20)
self.i2cDev.read(data);
print("--> read " + str(len) + " bytes from addr " + str(addr) + ", " + str(len) + " bytes value = " + str(data));
return data;
def qmc5883l_write_register(self, addr, reg, data):
print(">>>> wirte reg: %d, data: %d\n" %(reg, data))
self.devRegReadWrite1Byte(1, reg, data);
def qmc5883l_read_register(self, addr, reg):
return self.devRegRead1Byte(reg);
def qmc5883l_read_len(self, reg, len):
return self.devRegReadNByte(reg, len);
def qmc5883l_reconfig(self):
self.qmc5883l_write_register(addr, QMC5883L_CONFIG, oversampling | g_range | rate | mode);
sleep_ms(50)
self.qmc5883l_write_register(addr, QMC5883L_CONFIG2, 0x1);
def qmc5883l_reset(self):
self.qmc5883l_write_register(addr, QMC5883L_RESET, 0x01);
sleep_ms(500)
self.qmc5883l_reconfig();
sleep_ms(50)
self.qmc5883l_resetCalibration();
def qmc5883l_setOversampling(self, x):
global oversampling
if (x == 512):
oversampling = QMC5883L_CONFIG_OS512;
elif (x == 256):
oversampling = QMC5883L_CONFIG_OS256;
elif (x == 128):
oversampling = QMC5883L_CONFIG_OS128;
elif (x == 64):
oversampling = QMC5883L_CONFIG_OS64;
self.qmc5883l_reconfig();
def qmc5883l_setRange(self, x):
global g_range
if (x == 2):
g_range = QMC5883L_CONFIG_2GAUSS;
elif (x == 8):
g_range = QMC5883L_CONFIG_8GAUSS;
self.qmc5883l_reconfig();
def qmc5883l_setSamplingRate(self, x):
global rate
if (x == 10):
rate = QMC5883L_CONFIG_10HZ;
elif (x == 50):
rate = QMC5883L_CONFIG_50HZ;
elif (x == 100):
rate = QMC5883L_CONFIG_100HZ;
elif (x == 200):
rate = QMC5883L_CONFIG_200HZ;
self.qmc5883l_reconfig();
def _qmc5883l_init(self):
global addr
global oversampling
global g_range
global rate
global mode
# This assumes the wire library has been initialized.
addr = QMC5883L_ADDR;
oversampling = QMC5883L_CONFIG_OS512;
g_range = QMC5883L_CONFIG_8GAUSS;
rate = QMC5883L_CONFIG_200HZ;
mode = QMC5883L_CONFIG_CONT;
print("addr %d,oversampling %d,g_range %d,rate %d, mode %d" %(addr, oversampling, g_range, rate, mode))
self.qmc5883l_reset();
def qmc5883l_ready(self):
sleep_ms(200);
tmp = self.qmc5883l_read_register(addr, QMC5883L_STATUS) & QMC5883L_STATUS_DRDY
return tmp;
def qmc5883l_readRaw(self):
timeout = 10000;
arr = [1, 2, 3];
data = bytearray(6);
ready = self.qmc5883l_ready();
while (ready == 0 and timeout):
ready = self.qmc5883l_ready();
timeout -= 1;
print("ready = %d" %(ready))
data = self.qmc5883l_read_len(QMC5883L_X_LSB, 6);
x = data[0] | (data[1] << 8);
y = data[2] | (data[3] << 8);
z = data[4] | (data[5] << 8);
print("read_raw[%f,%f,%f],\n" %(x ,y, z));
if (x > (1 << 15)):
x = x - (1<<16)
if (y > (1 << 15)):
y = y - (1<<16)
if (z > (1 << 15)):
z = z - (1<<16)
arr[0] = x;
arr[1] = y;
arr[2] = z;
return arr;
def qmc5883l_resetCalibration(self):
global x_max
global x_min
global z_min
global y_max
global y_min
global z_max
x_max = y_max = z_max = INT16_MIN;
x_min = y_min = z_min = INT16_MAX;
def qmc5883l_readHeading(self):
global x_max
global x_min
global z_min
global y_max
global y_min
global z_max
global addr
global mode
global rate
global g_range
global oversampling
tmp = self.qmc5883l_read_register(addr, QMC5883L_STATUS) & QMC5883L_STATUS_DRDY;
print("read QMC5883L_STATUS: %d\n" %(tmp))
xyz_org = self.qmc5883l_readRaw();
x_org = xyz_org[0];
y_org = xyz_org[1];
z_org = xyz_org[2];
print("org[%f,%f,%f]\n" %(x_org ,y_org, z_org));
# Update the observed boundaries of the measurements
if (x_org < x_min):
x_min = x_org;
if (x_org > x_max):
x_max = x_org;
if (y_org < y_min):
y_min = y_org;
if (y_org > y_max):
y_max = y_org;
if (z_org < z_min):
z_min = z_org;
if (z_org > z_max):
z_max = z_org;
# Bail out if not enough data is available.
if ((x_min == x_max) or (y_min == y_max) or (z_max == z_min)):
print("x_min %f == x_max %f or y_min %f == y_max %f or z_max%f == z_min%f\n" %(x_min, x_max, y_min, y_max, z_max, z_min))
return 0;
# Recenter the measurement by subtracting the average
x_offset = (x_max + x_min) / 2.0;
y_offset = (y_max + y_min) / 2.0;
z_offset = (z_max + z_min) / 2.0;
x_fit = (x_org - x_offset) * 1000.0 / (x_max - x_min);
y_fit = (y_org - y_offset) * 1000.0 / (y_max - y_min);
z_fit = (z_org - z_offset) * 1000.0 / (z_max - z_min);
print("fix[%f,%f,%f],\n" %(x_fit ,y_fit, z_fit));
heading = 180.0 * math.atan2(x_fit, y_fit) / M_PI;
if (heading <= 0):
heading = heading + 360;
print("heading = %f\n", heading);
return heading;
def init(self):
self._qmc5883l_init();
def close(self):
self.i2cDev.close()
| YifuLiu/AliOS-Things | components/py_engine/framework/qmc5883.py | Python | apache-2.0 | 8,651 |
from micropython import const
import utime
import framebuf
from driver import SPI
from driver import GPIO
# register definitions
SET_SCAN_DIR = const(0xc0)
LOW_COLUMN_ADDRESS = const(0x00)
HIGH_COLUMN_ADDRESS = const(0x10)
SET_PAGE_ADDRESS = const(0xB0)
SET_CONTRAST = const(0x81)
SET_ENTIRE_ON = const(0xa4)
SET_NORM_INV = const(0xa6)
SET_DISP = const(0xae)
SET_MEM_ADDR = const(0x20)
SET_COL_ADDR = const(0x21)
SET_PAGE_ADDR = const(0x22)
SET_DISP_START_LINE = const(0x40)
SET_SEG_REMAP = const(0xa0)
SET_MUX_RATIO = const(0xa8)
SET_COM_OUT_DIR = const(0xc0)
SET_DISP_OFFSET = const(0xd3)
SET_COM_PIN_CFG = const(0xda)
SET_DISP_CLK_DIV = const(0xd5)
SET_PRECHARGE = const(0xd9)
SET_VCOM_DESEL = const(0xdb)
SET_CHARGE_PUMP = const(0x8d)
class SH1106:
def __init__(self, width, height):
self.width = width
self.height = height
self.pages = self.height // 8
self.buffer = bytearray(self.pages * self.width)
fb = framebuf.FrameBuffer(
self.buffer, self.width, self.height, framebuf.MVLSB)
self.framebuf = fb
# set shortcuts for the methods of framebuf
self.fill = fb.fill
self.fill_rect = fb.fill_rect
self.hline = fb.hline
self.vline = fb.vline
self.line = fb.line
self.rect = fb.rect
self.pixel = fb.pixel
self.scroll = fb.scroll
self.text = fb.text
self.blit = fb.blit
# print("init done")
self.init_display()
def init_display(self):
self.reset()
for cmd in (
SET_DISP | 0x00, # 关闭显示
SET_DISP_CLK_DIV, 0x80, # 设置时钟分频因子
SET_MUX_RATIO, self.height - 1, # 设置驱动路数 路数默认0x3F(1/64)
SET_DISP_OFFSET, 0x00, # 设置显示偏移 偏移默认为0
SET_DISP_START_LINE | 0x00, # 设置显示开始行[5:0]
SET_CHARGE_PUMP, 0x14, # 电荷泵设置 bit2,开启/关闭
# 设置内存地址模式 [1:0],00,列地址模式;01,行地址模式;10,页地址模式;默认10;
SET_MEM_ADDR, 0x02,
SET_SEG_REMAP | 0x01, # 段重定义设置,bit0:0,0->0;1,0->127;
# 设置COM扫描方向;bit3:0,普通模式;1,重定义模式 COM[N-1]->COM0;N:驱动路数
SET_COM_OUT_DIR | 0x08,
SET_COM_PIN_CFG, 0x12, # 设置COM硬件引脚配置 [5:4]配置
SET_PRECHARGE, 0xf1, # 设置预充电周期 [3:0],PHASE 1;[7:4],PHASE 2;
# 设置VCOMH 电压倍率 [6:4] 000,0.65*vcc;001,0.77*vcc;011,0.83*vcc;
SET_VCOM_DESEL, 0x30,
SET_CONTRAST, 0xff, # 对比度设置 默认0x7F(范围1~255,越大越亮)
SET_ENTIRE_ON, # 全局显示开启;bit0:1,开启;0,关闭;(白屏/黑屏)
SET_NORM_INV, # 设置显示方式;bit0:1,反相显示;0,正常显示
SET_DISP | 0x01): # 开启显示
self.write_cmd(cmd)
self.fill(1)
self.show()
def poweroff(self):
self.write_cmd(SET_DISP | 0x00)
def poweron(self):
self.write_cmd(SET_DISP | 0x01)
def rotate(self, flag, update=True):
if flag:
self.write_cmd(SET_SEG_REMAP | 0x01) # mirror display vertically
self.write_cmd(SET_SCAN_DIR | 0x08) # mirror display hor.
else:
self.write_cmd(SET_SEG_REMAP | 0x00)
self.write_cmd(SET_SCAN_DIR | 0x00)
if update:
self.show()
def sleep(self, value):
self.write_cmd(SET_DISP | (not value))
def contrast(self, contrast):
self.write_cmd(SET_CONTRAST)
self.write_cmd(contrast)
def invert(self, invert):
self.write_cmd(SET_NORM_INV | (invert & 1))
def show(self):
for page in range(self.height // 8):
self.write_cmd(SET_PAGE_ADDRESS | page)
self.write_cmd(LOW_COLUMN_ADDRESS)
self.write_cmd(HIGH_COLUMN_ADDRESS)
page_buffer = bytearray(self.width)
for i in range(self.width):
page_buffer[i] = self.buffer[self.width * page + i]
self.write_data(page_buffer)
def set_buffer(self, buffer):
for i in range(len(buffer)):
self.buffer[i] = buffer[i]
def draw_XBM(self, x, y, w, h, bitmap):
x_byte = (w//8) + (w % 8 != 0)
for nbyte in range(len(bitmap)):
for bit in range(8):
if(bitmap[nbyte] & (0b10000000 >> bit)):
p_x = (nbyte % x_byte)*8+bit
p_y = nbyte//x_byte
self.pixel(x + p_x, y + p_y, 1)
# 以屏幕GRAM的原始制式去填充Buffer
def draw_buffer(self, x, y, w, h, bitmap):
y_byte = (h//8) + (h % 8 != 0)
for nbyte in range(len(bitmap)):
for bit in range(8):
if(bitmap[nbyte] & (1 << bit)):
p_y = (nbyte % y_byte)*8+bit
p_x = nbyte//y_byte
self.pixel(x + p_x, y + p_y, 1)
def fill_rect(self, x, y, w, h, c):
self.fill_rect(x, y, w, h, c)
def fill_circle(self, x0, y0, r, c):
x = 0
y = r
deltax = 3
deltay = 2 - r - r
d = 1 - r
#print(x)
#print(y)
#print(deltax)
#print(deltay)
#print(d)
self.pixel(x + x0, y + y0, c)
self.pixel(x + x0, -y + y0, c)
for i in range(-r + x0, r + x0):
self.pixel(i, y0, c)
while x < y:
if d < 0:
d += deltax
deltax += 2
x = x +1
else:
d += (deltax + deltay)
deltax += 2
deltay += 2
x = x +1
y = y -1
for i in range(-x + x0, x + x0):
self.pixel(i, -y + y0, c)
self.pixel(i, y + y0, c)
for i in range(-y + x0, y + x0):
self.pixel(i, -x + y0, c)
self.pixel(i, x + y0, c)
def draw_circle(self, x0, y0, r, w, c):
self.fill_circle(x0, y0, r, c)
self.fill_circle(x0, y0, r -w, 0)
def reset(self, res):
if res is not None:
res.write(1)
utime.sleep_ms(1)
res.write(0)
utime.sleep_ms(20)
res.write(1)
utime.sleep_ms(20)
class SH1106_I2C(SH1106):
def __init__(self, width, height, i2c, res=None, addr=0x3c):
self.i2c = i2c
self.addr = addr
self.res = res
self.temp = bytearray(2)
super().__init__(width, height)
def write_cmd(self, cmd):
self.temp[0] = 0x80 # Co=1, D/C#=0
self.temp[1] = cmd
self.i2c.write(self.temp)
def write_data(self, buf):
send_buf = bytearray(1 + len(buf))
send_buf[0] = 0x40
for i in range(len(buf)):
send_buf[i+1] = buf[i]
print(send_buf)
self.i2c.write(send_buf)
def reset(self):
super().reset(self.res)
class SH1106_SPI(SH1106):
def __init__(self, width, height, spi, dc, res=None, cs=None):
self.spi = spi
self.dc = dc
self.res = res
self.cs = cs
super().__init__(width, height)
def write_cmd(self, cmd):
if self.cs is not None:
self.cs.write(1)
self.dc.write(0)
self.cs.write(0)
self.spi.write(bytearray([cmd]))
self.cs.write(1)
else:
self.dc.write(0)
self.spi.write(bytearray([cmd]))
def write_data(self, buf):
if self.cs is not None:
self.cs.write(1)
self.dc.write(1)
self.cs.write(0)
self.spi.write(buf)
self.cs.write(1)
else:
self.dc.write(1)
self.spi.write(buf)
def reset(self):
super().reset(self.res)
| YifuLiu/AliOS-Things | components/py_engine/framework/sh1106.py | Python | apache-2.0 | 7,928 |
# -*- coding: UTF-8 -*-
"""
The driver for Si7006 chip, it is a temperature and humidity sensor.
"""
from driver import I2C
from utime import sleep_ms
# The register address in Si7006 controller.
Si7006_MEAS_REL_HUMIDITY_MASTER_MODE = 0xE5
Si7006_MEAS_REL_HUMIDITY_NO_MASTER_MODE = 0xF5
Si7006_MEAS_TEMP_MASTER_MODE = 0xE3
Si7006_MEAS_TEMP_NO_MASTER_MODE = 0xF3
Si7006_READ_OLD_TEMP = 0xE0
Si7006_RESET = 0xFE
Si7006_READ_ID_LOW_0 = 0xFA
Si7006_READ_ID_LOW_1 = 0x0F
Si7006_READ_ID_HIGH_0 = 0xFC
Si7006_READ_ID_HIGH_1 = 0xC9
Si7006_READ_Firmware_Revision_0 = 0x84
Si7006_READ_Firmware_Revision_1 = 0xB8
class SI7006Error(Exception):
def __init__(self, value=0, msg="si7006 common error"):
self.value = value
self.msg = msg
def __str__(self):
return "Error code:%d, Error message: %s" % (self.value, str(self.msg))
__repr__ = __str__
class SI7006(object):
"""
This class implements SI7006 chip's functions.
"""
def __init__(self):
self.i2cDev = None
def open(self, devid):
self.i2cDev = I2C()
self.i2cDev.open(devid)
def getVer(self):
"""
Get the firmware version of the chip.
"""
reg = bytearray([Si7006_READ_Firmware_Revision_0, Si7006_READ_Firmware_Revision_1])
self.i2cDev.write(reg)
sleep_ms(30)
version = bytearray(1)
self.i2cDev.read(version)
return version[0]
def getID(self):
"""Get the chip ID."""
reg = bytearray([Si7006_READ_ID_LOW_0, Si7006_READ_ID_LOW_1])
self.i2cDev.write(reg)
sleep_ms(30)
id_buf_low = bytearray(4)
self.i2cDev.read(id_buf_low)
reg = bytearray([Si7006_READ_ID_HIGH_0, Si7006_READ_ID_HIGH_1])
id_buf_high = bytearray(4)
self.i2cDev.read(id_buf_high)
return id_buf_low + id_buf_high
def getTemperature(self):
"""Get temperature."""
reg = bytearray([Si7006_MEAS_TEMP_NO_MASTER_MODE])
self.i2cDev.write(reg)
sleep_ms(30)
readData = bytearray(2)
self.i2cDev.read(readData)
value = (readData[0] << 8 | readData[1])
if (value & 0xFFFC):
temperature = (175.72 * value) / 65536.0 - 46.85
return temperature
else:
raise SI7006Error("failed to get temperature.")
def getHumidity(self):
"""Get humidity."""
reg = bytearray([Si7006_MEAS_REL_HUMIDITY_NO_MASTER_MODE])
self.i2cDev.write(reg)
sleep_ms(30)
readData = bytearray(2)
self.i2cDev.read(readData)
value = (readData[0] << 8) | readData[1]
if (value & 0xFFFE):
humidity = (125.0 * value) / 65535.0 - 6.0
return humidity
else:
raise SI7006Error("failed to get humidity.")
def getTempHumidity(self):
"""Get temperature and humidity."""
temphumidity = [0, 0]
temphumidity[0] = self.getTemperature()
temphumidity[1] = self.getHumidity()
return temphumidity
def close(self):
self.i2cDev.close()
| YifuLiu/AliOS-Things | components/py_engine/framework/si7006.py | Python | apache-2.0 | 3,267 |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
'''
@File : speech_utils.py
@Description: file description
@Date : 2021/05/17 11:43:06
@Author : guoliang.wgl
@version : 1.0
'''
import math
import http
import json
import time
from audio import Player,Snd
import uos
toneDir = "/sdcard/resource/"
tonenameSuffix = [".wav", ".mp3"]
tonenameNumb = ["SYS_TONE_0", "SYS_TONE_1", "SYS_TONE_2", "SYS_TONE_3", "SYS_TONE_4", "SYS_TONE_5", "SYS_TONE_6", "SYS_TONE_7", "SYS_TONE_8", "SYS_TONE_9"]
tonenameNumb1 = "SYS_TONE_yao"
tonenameDot = "SYS_TONE_dian"
tonenameUnit = ["SYS_TONE_MEASURE_WORD_ge", "SYS_TONE_MEASURE_WORD_shi", "SYS_TONE_MEASURE_WORD_bai", "SYS_TONE_MEASURE_WORD_qian"]
tonenameHunit = ["SYS_TONE_MEASURE_WORD_wan", "SYS_TONE_MEASURE_WORD_yi", "SYS_TONE_MEASURE_WORD_sw", "SYS_TONE_MEASURE_WORD_bw", "SYS_TONE_MEASURE_WORD_qw"]
on_callback = False
on_download = False
cb_data = None
player = None
def init_audio():
global player
Snd.init()
player = Player()
player.open()
player.setVolume(8)
def play(path):
global player
player.play(path)
player.waitComplete()
def playlist(pathlist):
for path in pathlist:
play('fs:'+path)
print('********end playlist*******')
def play_voice(data,dir_info):
"""
{"format":"wav","speechs":["zfbGet","{$10000}","yuan"],"id":"Xc14Erf9skwt5kj5YHepXGEiTa8DIxZJ","timestamp":"1633943696513"}
"""
global toneDir, tonenameSuffix, playlist
print('************* play_voice***********')
print('*************data: %s' % data)
print('*************dir_info: %s' % dir_info)
toneDir = dir_info
format = data['format']
audioResFormat = 0
if (format == 'mp3'):
audioResFormat = 1
speechs = data['speechs']
toneList = []
for speech in speechs:
print(speech)
# length = len(speech)
if speech.endswith('}') and speech.startswith('{') and (speech[1] == '$'):
speech_num = speech.strip('{').strip('$').strip('}')
toneList = add_amount(speech_num,toneList,audioResFormat)
else:
toneList.append(toneDir + speech + tonenameSuffix[audioResFormat])
print(toneList)
playlist(toneList)
def add_amount(num_str, toneList, formatFlag):
global toneDir,tonenameSuffix,tonenameNumb,tonenameNumb1,tonenameDot,tonenameUnit,tonenameHunit
num_f = float(num_str)
numb = int(num_f)
deci = num_f - numb
target = numb
subTarget = 0
subNumber = None
slot = 0
factor = 0
count = 0
prevSlotZero = False
hundredMillionExist = False
tenThousandExist = False
if (numb < 0 or numb >= 1000000000000):
print('amount overrange')
return toneIndex
if (deci < 0.0001 and deci > 0.0):
deci = 0.0001
i = 2
while(i >= 0):
factor = math.pow(10000,i)
if target < factor:
i = i -1
continue
subTarget = int(target / factor)
target %= factor
if (subTarget == 0):
i = i -1
continue
if (i == 2):
hundredMillionExist = True
elif (i == 1):
tenThousandExist = True
subNumber = subTarget
prevSlotZero = False
depth = 3
while(depth >= 0):
if(subNumber == 0):
break
factor = math.pow(10, depth)
if ((hundredMillionExist == True or tenThousandExist == True) and i == 0):
pass
elif (hundredMillionExist == True and tenThousandExist == True and depth > 0 and subTarget < factor):
pass
elif (subTarget < factor):
depth = depth - 1
continue
slot = int(subNumber / factor)
subNumber %= factor
if (slot == 0 and depth == 0):
depth = depth - 1
continue
if ((subTarget < 20 and depth == 1) or (slot == 0 and prevSlotZero) or (slot == 0 and depth == 0)):
pass
else:
toneList.append(toneDir + tonenameNumb[slot] + tonenameSuffix[formatFlag])
count += 1
if (slot == 0 and prevSlotZero == False):
prevSlotZero = True
elif (prevSlotZero == True and slot != 0):
prevSlotZero = False
if (slot > 0 and depth > 0) :
toneList.append(toneDir + tonenameUnit[depth] + tonenameSuffix[formatFlag])
count += 1
depth = depth - 1
if (i > 0):
toneList.append(toneDir + tonenameHunit[i - 1] + tonenameSuffix[formatFlag])
count += 1
i = i - 1
if (count == 0 and numb == 0):
toneList.append(toneDir + tonenameNumb[0] + tonenameSuffix[formatFlag])
if (deci >= 0.0001) :
toneList.append(toneDir + tonenameDot + tonenameSuffix[formatFlag])
deci ="{:.4f}".format(deci)
deci_tmp = str(deci).strip().rstrip('0')
deci_str = ''
got_dot = False
for j in range(len(deci_tmp)):
if(got_dot):
deci_str = deci_str + deci_tmp[j]
elif deci_tmp[j] == '.':
got_dot = True
deciArray = deci_str
for item in deciArray:
if (item >= '0' and item <= '9'):
toneList.append(toneDir + tonenameNumb[int(item)] + tonenameSuffix[formatFlag])
return toneList
def download_resource_file(on_request,resDir):
global toneDir,on_callback,on_download,cb_data
toneDir = resDir
data = {
'url':on_request['url'],
'method': 'GET',
'headers': {
'content-type' :'application/x-www-form-urlencoded'
},
'timeout': 30000,
'params' : ''
}
def cb(data):
global on_callback,cb_data
on_callback = True
cb_data = data
http.request(data,cb)
while True:
if on_callback:
on_callback = False
break
else:
time.sleep(1)
# {
# "audios":
# [
# { "format":"wav",
# "id":"zfbGet",
# "size":40204,
# "type":"custom",
# "url":"http://speech-solution.oss-cn-shanghai.aliyuncs.com/xxxx"
# }
# ],
# "format":"wav",
# "size":40204
# }
print(cb_data)
response = json.loads(cb_data['body'])
audio = response['audios'][0]
format = audio['format']
id = audio['id']
size = audio['size']
path = toneDir +id+'.'+format
print('************ begin to download: ' + path)
d_data = {
'url': audio['url'],
'filepath': path
}
def d_cb(data):
global on_download
on_download = True
http.download(d_data,d_cb)
while True:
if on_download:
on_download = False
break
else:
time.sleep(1)
print('download succeed :' + path)
| YifuLiu/AliOS-Things | components/py_engine/framework/speech_utils.py | Python | apache-2.0 | 7,047 |
# -*- coding: UTF-8 -*-
"""
The driver for spl06 chip, it is a temperature and humidity sensor.
"""
from driver import I2C
from utime import sleep_ms
import math
EEPROM_CHIP_ADDRESS = 0x77;
class spl06Error(Exception):
def __init__(self, value=0, msg="spl06 common error"):
self.value = value
self.msg = msg
def __str__(self):
return "Error code:%d, Error message: %s" % (self.value, str(self.msg))
__repr__ = __str__
class SPL06(object):
"""
This class implements spl06 chip's defs.
"""
def __init__(self):
self.i2cDev = None
def open(self, devid):
self.i2cDev = I2C()
self.i2cDev.open(devid)
def i2c_eeprom_read_var(self, chipAddress, addr):
return self.devRegReadWrite1Byte(0, addr, 0);
def devRegRead1Byte(self, addr):
return self.devRegReadWrite1Byte(0, addr, 0);
def devRegReadWrite1Byte(self, mode, addr, value):
#0 read mode
#1 write mode
if (mode == 0):
Reg = bytearray([addr])
self.i2cDev.write(Reg);
sleep_ms(30)
tmp = bytearray(1)
self.i2cDev.read(tmp)
print("<-- read addr " + str(addr) + ", value = " + str(tmp[0]));
return tmp[0];
else:
Reg = bytearray([addr, value])
self.i2cDev.write(Reg);
print("--> write addr " + str(addr) + ", value = " + str(value));
return 0;
def init(self):
tmp = 0;
rRegID = bytearray([0x0D, 0x0]);
wRegPressure8xOversampling = bytearray([0x06, 0x03]);
wRegTemperature8xOversampling = bytearray([0x07, 0x83]);
wRegContinuousTempAndPressureMeasurement = bytearray([0x08, 0B0111]);
wRegFIFOPressureMeasurement = bytearray([0x09, 0x00]);
tmp = rRegID;
self.devRegReadWrite1Byte(0, tmp[0], tmp[1]);
tmp = wRegPressure8xOversampling;
self.devRegReadWrite1Byte(1, tmp[0], tmp[1]);
tmp = wRegTemperature8xOversampling;
self.devRegReadWrite1Byte(1, tmp[0], tmp[1]);
tmp = wRegContinuousTempAndPressureMeasurement;
self.devRegReadWrite1Byte(1, tmp[0], tmp[1]);
tmp = wRegFIFOPressureMeasurement;
self.devRegReadWrite1Byte(1, tmp[0], tmp[1]);
# Get the firmware version of the chip.
def getID(self) :
reg = bytearray([0x0D]);
version = bytearray(1);
self.i2cDev.write(reg);
self.i2cDev.read(version);
print("spl06 ID is " + str(version[0]));
return version[0];
def get_altitude(self, pressure, seaLevelhPa):
if (seaLevelhPa == 0):
return -1;
pressure /= 100;
altitude = 44330 * (1.0 - math.pow(pressure / seaLevelhPa, 0.1903));
return altitude;
def get_temperature_scale_factor(self):
tmp_Byte = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X07); # MSB
tmp_Byte = tmp_Byte & 0B00000111;
print("tmp_Byte: %d\n" %tmp_Byte);
if (tmp_Byte == 0B000):
k = 524288.0;
elif (tmp_Byte == 0B001):
k = 1572864.0;
elif (tmp_Byte == 0B010):
k = 3670016.0;
elif (tmp_Byte == 0B011):
k = 7864320.0;
elif (tmp_Byte == 0B100):
k = 253952.0;
elif (tmp_Byte == 0B101):
k = 516096.0;
elif (tmp_Byte == 0B110):
k = 1040384.0;
elif (tmp_Byte == 0B111):
k = 2088960.0;
print("k=%d\n" %k);
return k;
def get_pressure_scale_factor(self):
tmp_Byte = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X06); # MSB
# tmp_Byte = tmp_Byte >> 4; #Focus on bits 6-4 - measurement rate
tmp_Byte = tmp_Byte & 0B00000111; # Focus on 2-0 oversampling rate
# tmp_Byte = 0B011;
# oversampling rate
if (tmp_Byte == 0B000):
k = 524288.0;
elif (tmp_Byte == 0B001):
k = 1572864.0;
elif (tmp_Byte == 0B010):
k = 3670016.0;
elif (tmp_Byte == 0B011):
k = 7864320.0;
elif (tmp_Byte == 0B100):
k = 253952.0;
elif (tmp_Byte == 0B101):
k = 516096.0;
elif (tmp_Byte == 0B110):
k = 1040384.0;
elif (tmp_Byte == 0B111):
k = 2088960.0;
print("k=%d\n" %k);
return k;
def get_traw(self):
tmp_MSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X03); # MSB
tmp_LSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X04); # LSB
tmp_XLSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X05); # XLSB
tmp = (tmp_MSB << 8) | tmp_LSB;
tmp = (tmp << 8) | tmp_XLSB;
if (tmp & (1 << 23)):
tmp = tmp | 0XFF000000; # Set left bits to one for 2's complement
# conversion of negitive number
print("get_traw: tmp_MSB=%d, tmp_LSB=%d, tmp_XLSB=%d\n" %(tmp_MSB, tmp_LSB, tmp_XLSB));
return tmp;
def get_praw(self):
tmp_MSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X00); # MSB
tmp_LSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X01); # LSB
tmp_XLSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X02); # XLSB
tmp = (tmp_MSB << 8) | tmp_LSB;
tmp = (tmp << 8) | tmp_XLSB;
if (tmp & (1 << 23)):
tmp = -((2 << 23) - tmp)
return tmp;
def get_c0(self):
tmp_MSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X10);
tmp_LSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X11);
tmp_LSB = tmp_LSB >> 4;
tmp = (tmp_MSB << 4) | tmp_LSB;
if (tmp & (1 << 11)):
# Check for 2's complement negative number
tmp = tmp | 0XF000; # Set left bits to one for 2's complement
# conversion of negitive number
if (tmp > (1 << 15)):
tmp &= 0xFFFF
tmp = tmp - (1<<16)
print("get_c0: tmp_MSB=%d, tmp_LSB=%d, tmp=%d\n" %(tmp_MSB, tmp_LSB, tmp));
return tmp;
def get_c1(self):
tmp_MSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X11);
tmp_LSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X12);
tmp_MSB = tmp_MSB & 0XF;
tmp = (tmp_MSB << 8) | tmp_LSB;
if (tmp & (1 << 11)):
# Check for 2's complement negative number
tmp = tmp | 0XF000; # Set left bits to one for 2's complement
# conversion of negitive number
if (tmp > (1 << 15)):
tmp = tmp - (1<<16)
print("get_c1: tmp_MSB=%d, tmp_LSB=%d, tmp=%d\n" %(tmp_MSB, tmp_LSB, tmp));
return tmp;
def get_c00(self):
tmp_MSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X13);
tmp_LSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X14);
tmp_XLSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X15);
tmp_XLSB = tmp_XLSB >> 4;
tmp = (tmp_MSB << 8) | tmp_LSB;
tmp = (tmp << 4) | tmp_XLSB;
tmp = tmp_MSB << 12 | tmp_LSB << 4 | tmp_XLSB >> 4;
if (tmp & (1 << 19)):
tmp = tmp | 0XFFF00000; # Set left bits to one for 2's complement
# conversion of negitive number
return tmp;
def get_c10(self):
tmp_MSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X15); # 4 bits
tmp_LSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X16); # 8 bits
tmp_XLSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X17); # 8 bits
tmp_MSB = tmp_MSB & 0b00001111;
tmp = (tmp_MSB << 4) | tmp_LSB;
tmp = (tmp << 8) | tmp_XLSB;
tmp = tmp_MSB << 16 | tmp_LSB << 8 | tmp_XLSB;
if (tmp & (1 << 19)):
tmp = tmp | 0XFFF00000; # Set left bits to one for 2's complement
# conversion of negitive number
if (tmp > (1 << 15)):
tmp &= 0xFFFF
tmp = tmp - (1<<16);
return tmp;
def get_c01(self):
tmp_MSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X18);
tmp_LSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X19);
tmp = (tmp_MSB << 8) | tmp_LSB;
if (tmp > (1 << 15)):
tmp = tmp - (1<<16);
return tmp;
def get_c11(self):
tmp_MSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X1A);
tmp_LSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X1B);
tmp = (tmp_MSB << 8) | tmp_LSB;
if (tmp > (1 << 15)):
tmp = tmp - (1<<16);
return tmp;
def get_c20(self):
tmp_MSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X1C);
tmp_LSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X1D);
tmp = (tmp_MSB << 8) | tmp_LSB;
if (tmp > (1 << 15)):
tmp = tmp - (1<<16);
return tmp;
def get_c21(self):
tmp_MSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X1E);
tmp_LSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X1F);
tmp = (tmp_MSB << 8) | tmp_LSB;
if (tmp > (1 << 15)):
tmp = tmp - (1<<16);
return tmp;
def get_c30(self):
tmp_MSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X20);
tmp_LSB = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X21);
tmp = (tmp_MSB << 8) | tmp_LSB;
if (tmp > (1 << 15)):
tmp = tmp - (1<<16);
return tmp;
def spl06_getdata(self):
# Serial.println("\nDevice Reset\n");
# i2c_eeprom_write_var(EEPROM_CHIP_ADDRESS, 0x0C, 0b1001);
# delay(1000);
tmp = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0x0D);
tmp = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0x06);
tmp = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0x07);
tmp = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0x08);
tmp = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0x09);
tmp = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0x0A);
tmp = self.i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0x0B);
c0 = self.get_c0();
c1 = self.get_c1();
c00 = self.get_c00();
c10 = self.get_c10();
c01 = self.get_c01();
c11 = self.get_c11();
c20 = self.get_c20();
c21 = self.get_c21();
c30 = self.get_c30();
traw = self.get_traw();
traw_sc = traw / self.get_temperature_scale_factor();
traw_sc = round(traw_sc,2)
print("traw_sc: %0.2f\n" %traw_sc);
Ctemp = c0 * 0.5 + c1 * traw_sc;
Ctemp = round(Ctemp,2)
print("Ctemp:" + str(Ctemp) + ". " + "c0:" + str(c0) + " c1" + str(c1) + " traw_sc:" + str(traw_sc));
Ftemp = (Ctemp * 9 / 5) + 32;
Ftemp = round(Ftemp,2)
print("Ftemp: %d" %Ftemp)
praw = self.get_praw();
praw_sc = (praw) / self.get_pressure_scale_factor();
print("praw: %d" %praw)
print("praw_sc: %d" %praw_sc)
print("c00: %d" %c00)
print("c10: %d" %c10)
print("c20: %d" %c20)
print("c30: %d" %c30)
print("c01: %d" %c01)
print("c11: %d" %c11)
print("c21: %d" %c21)
pcomp =\
(c00) + \
praw_sc * ((c10) + \
praw_sc * ((c20) + praw_sc * (c30))) + \
traw_sc * (c01) + \
traw_sc * praw_sc * ((c11) + praw_sc * (c21));
pressure = pcomp / 100; # convert to mb
print("pressure: %d" %pressure)
# local_pressure = 1010.5; # Look up local sea level pressure on
# google
local_pressure = \
1011.1; # Look up local sea level pressure on google # Local pressure
# from airport website 8/22
print("Local Airport Sea Level Pressure: %0.2f mb\n" %local_pressure);
altitude = self.get_altitude(pcomp, local_pressure);
print("altitude: %d" %altitude)
def close(self):
self.i2cDev.close()
| YifuLiu/AliOS-Things | components/py_engine/framework/spl06.py | Python | apache-2.0 | 12,412 |
"""
Copyright (c) 2020, 2021 Russ Hughes
This file incorporates work covered by the following copyright and
permission notice and is licensed under the same terms:
The MIT License (MIT)
Copyright (c) 2019 Ivan Belokobylskiy
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.
The driver is based on devbis' st7789py_mpy module from
https://github.com/devbis/st7789py_mpy.
This driver adds support for:
- 320x240, 240x240 and 135x240 pixel displays
- Display rotation
- Hardware based scrolling
- Drawing text using 8 and 16 bit wide bitmap fonts with heights that are
multiples of 8. Included are 12 bitmap fonts derived from classic pc
BIOS text mode fonts.
- Drawing text using converted TrueType fonts.
- Drawing converted bitmaps
"""
import time
from micropython import const
import ustruct as struct
# commands
ST7789_NOP = const(0x00)
ST7789_SWRESET = const(0x01)
ST7789_RDDID = const(0x04)
ST7789_RDDST = const(0x09)
ST7789_SLPIN = const(0x10)
ST7789_SLPOUT = const(0x11)
ST7789_PTLON = const(0x12)
ST7789_NORON = const(0x13)
ST7789_INVOFF = const(0x20)
ST7789_INVON = const(0x21)
ST7789_DISPOFF = const(0x28)
ST7789_DISPON = const(0x29)
ST7789_CASET = const(0x2A)
ST7789_RASET = const(0x2B)
ST7789_RAMWR = const(0x2C)
ST7789_RAMRD = const(0x2E)
ST7789_PTLAR = const(0x30)
ST7789_VSCRDEF = const(0x33)
ST7789_COLMOD = const(0x3A)
ST7789_MADCTL = const(0x36)
ST7789_VSCSAD = const(0x37)
ST7789_MADCTL_MY = const(0x80)
ST7789_MADCTL_MX = const(0x40)
ST7789_MADCTL_MV = const(0x20)
ST7789_MADCTL_ML = const(0x10)
ST7789_MADCTL_BGR = const(0x08)
ST7789_MADCTL_MH = const(0x04)
ST7789_MADCTL_RGB = const(0x00)
ST7789_RDID1 = const(0xDA)
ST7789_RDID2 = const(0xDB)
ST7789_RDID3 = const(0xDC)
ST7789_RDID4 = const(0xDD)
COLOR_MODE_65K = const(0x50)
COLOR_MODE_262K = const(0x60)
COLOR_MODE_12BIT = const(0x03)
COLOR_MODE_16BIT = const(0x05)
COLOR_MODE_18BIT = const(0x06)
COLOR_MODE_16M = const(0x07)
# Color definitions
BLACK = const(0x0000)
BLUE = const(0x001F)
RED = const(0xF800)
GREEN = const(0x07E0)
CYAN = const(0x07FF)
MAGENTA = const(0xF81F)
YELLOW = const(0xFFE0)
WHITE = const(0xFFFF)
_ENCODE_PIXEL = ">H"
_ENCODE_POS = ">HH"
_DECODE_PIXEL = ">BBB"
_BUFFER_SIZE = const(256)
_BIT7 = const(0x80)
_BIT6 = const(0x40)
_BIT5 = const(0x20)
_BIT4 = const(0x10)
_BIT3 = const(0x08)
_BIT2 = const(0x04)
_BIT1 = const(0x02)
_BIT0 = const(0x01)
# Rotation tables (width, height, xstart, ystart)[rotation % 4]
WIDTH_320 = [(320, 240, 0, 0),
(240, 320, 0, 0),
(320, 240, 0, 0),
(240, 320, 0, 0)]
WIDTH_240 = [(240, 240, 0, 0),
(240, 240, 0, 0),
(240, 240, 0, 80),
(240, 240, 80, 0)]
WIDTH_135 = [(135, 240, 52, 40),
(240, 135, 40, 53),
(135, 240, 53, 40),
(240, 135, 40, 52)]
# MADCTL ROTATIONS[rotation % 4]
ROTATIONS = [0x00, 0x60, 0xc0, 0xa0]
def color565(red, green=0, blue=0):
"""
Convert red, green and blue values (0-255) into a 16-bit 565 encoding.
"""
try:
red, green, blue = red # see if the first var is a tuple/list
except TypeError:
pass
return (red & 0xf8) << 8 | (green & 0xfc) << 3 | blue >> 3
def _encode_pos(x, y):
"""Encode a postion into bytes."""
return struct.pack(_ENCODE_POS, x, y)
def _encode_pixel(color):
"""Encode a pixel color into bytes."""
return struct.pack(_ENCODE_PIXEL, color)
class ST7789():
"""
ST7789 driver class
Args:
spi (spi): spi object
width (int): display width
height (int): display height
reset (pin): reset pin
dc (pin): dc pin
cs (pin): cs pin
backlight(pin): backlight pin
rotation (int): display rotation
- 0-Portrait
- 1-Landscape
- 2-Inverted Portrait
- 3-Inverted Landscape
"""
def __init__(self, spi, width, height, reset, dc,
cs=None, backlight=None, xstart=-1, ystart=-1, rotation=0):
"""
Initialize display.
"""
if height != 240 or width not in [320, 240, 135]:
raise ValueError(
"Unsupported display. 320x240, 240x240 and 135x240 are supported."
)
self._display_width = self.width = width
self._display_height = self.height = height
self.xstart = xstart
self.ystart = ystart
self.spi = spi
self.reset = reset
self.dc = dc
self.cs = cs
self.backlight = backlight
self._rotation = rotation % 4
print(" begin to init")
self.hard_reset()
self.soft_reset()
self.sleep_mode(False)
self._set_color_mode(COLOR_MODE_65K | COLOR_MODE_16BIT)
time.sleep_ms(50)
self.rotation(self._rotation)
self.inversion_mode(True)
time.sleep_ms(10)
self._write(ST7789_NORON)
time.sleep_ms(10)
if backlight is not None:
backlight.value(1)
self.fill(0)
self._write(ST7789_DISPON)
time.sleep_ms(500)
def _write(self, command=None, data=None):
"""SPI write to the device: commands and data."""
if self.cs:
self.cs.off()
if command is not None:
self.dc.off()
self.spi.write(bytes([command]))
if data is not None:
self.dc.on()
self.spi.write(data)
if self.cs:
self.cs.on()
def hard_reset(self):
"""
Hard reset display.
"""
if self.cs:
self.cs.off()
if self.reset:
self.reset.on()
time.sleep_ms(50)
if self.reset:
self.reset.off()
time.sleep_ms(50)
if self.reset:
self.reset.on()
time.sleep_ms(150)
if self.cs:
self.cs.on()
def soft_reset(self):
"""
Soft reset display.
"""
self._write(ST7789_SWRESET)
time.sleep_ms(150)
def sleep_mode(self, value):
"""
Enable or disable display sleep mode.
Args:
value (bool): if True enable sleep mode. if False disable sleep
mode
"""
if value:
self._write(ST7789_SLPIN)
else:
self._write(ST7789_SLPOUT)
def inversion_mode(self, value):
"""
Enable or disable display inversion mode.
Args:
value (bool): if True enable inversion mode. if False disable
inversion mode
"""
if value:
self._write(ST7789_INVON)
else:
self._write(ST7789_INVOFF)
def _set_color_mode(self, mode):
"""
Set display color mode.
Args:
mode (int): color mode
COLOR_MODE_65K, COLOR_MODE_262K, COLOR_MODE_12BIT,
COLOR_MODE_16BIT, COLOR_MODE_18BIT, COLOR_MODE_16M
"""
self._write(ST7789_COLMOD, bytes([mode & 0x77]))
def rotation(self, rotation):
"""
Set display rotation.
Args:
rotation (int):
- 0-Portrait
- 1-Landscape
- 2-Inverted Portrait
- 3-Inverted Landscape
"""
rotation %= 4
self._rotation = rotation
madctl = ROTATIONS[rotation]
if self._display_width == 320:
table = WIDTH_320
elif self._display_width == 240:
table = WIDTH_240
elif self._display_width == 135:
table = WIDTH_135
else:
raise ValueError(
"Unsupported display. 320x240, 240x240 and 135x240 are supported."
)
self.width, self.height, self.xstart, self.ystart = table[rotation]
self._write(ST7789_MADCTL, bytes([madctl]))
def _set_columns(self, start, end):
"""
Send CASET (column address set) command to display.
Args:
start (int): column start address
end (int): column end address
"""
if start <= end <= self.width:
self._write(ST7789_CASET, _encode_pos(
start+self.xstart, end + self.xstart))
def _set_rows(self, start, end):
"""
Send RASET (row address set) command to display.
Args:
start (int): row start address
end (int): row end address
"""
if start <= end <= self.height:
self._write(ST7789_RASET, _encode_pos(
start+self.ystart, end+self.ystart))
def _set_window(self, x0, y0, x1, y1):
"""
Set window to column and row address.
Args:
x0 (int): column start address
y0 (int): row start address
x1 (int): column end address
y1 (int): row end address
"""
self._set_columns(x0, x1)
self._set_rows(y0, y1)
self._write(ST7789_RAMWR)
def vline(self, x, y, length, color):
"""
Draw vertical line at the given location and color.
Args:
x (int): x coordinate
Y (int): y coordinate
length (int): length of line
color (int): 565 encoded color
"""
self.fill_rect(x, y, 1, length, color)
def hline(self, x, y, length, color):
"""
Draw horizontal line at the given location and color.
Args:
x (int): x coordinate
Y (int): y coordinate
length (int): length of line
color (int): 565 encoded color
"""
self.fill_rect(x, y, length, 1, color)
def pixel(self, x, y, color):
"""
Draw a pixel at the given location and color.
Args:
x (int): x coordinate
Y (int): y coordinate
color (int): 565 encoded color
"""
self._set_window(x, y, x, y)
self._write(None, _encode_pixel(color))
def blit_buffer(self, buffer, x, y, width, height):
"""
Copy buffer to display at the given location.
Args:
buffer (bytes): Data to copy to display
x (int): Top left corner x coordinate
Y (int): Top left corner y coordinate
width (int): Width
height (int): Height
"""
self._set_window(x, y, x + width - 1, y + height - 1)
self._write(None, buffer)
def rect(self, x, y, w, h, color):
"""
Draw a rectangle at the given location, size and color.
Args:
x (int): Top left corner x coordinate
y (int): Top left corner y coordinate
width (int): Width in pixels
height (int): Height in pixels
color (int): 565 encoded color
"""
self.hline(x, y, w, color)
self.vline(x, y, h, color)
self.vline(x + w - 1, y, h, color)
self.hline(x, y + h - 1, w, color)
def fill_rect(self, x, y, width, height, color):
"""
Draw a rectangle at the given location, size and filled with color.
Args:
x (int): Top left corner x coordinate
y (int): Top left corner y coordinate
width (int): Width in pixels
height (int): Height in pixels
color (int): 565 encoded color
"""
self._set_window(x, y, x + width - 1, y + height - 1)
chunks, rest = divmod(width * height, _BUFFER_SIZE)
pixel = _encode_pixel(color)
self.dc.on()
if chunks:
data = pixel * _BUFFER_SIZE
for _ in range(chunks):
self._write(None, data)
if rest:
self._write(None, pixel * rest)
def fill(self, color):
"""
Fill the entire FrameBuffer with the specified color.
Args:
color (int): 565 encoded color
"""
self.fill_rect(0, 0, self.width, self.height, color)
def line(self, x0, y0, x1, y1, color):
"""
Draw a single pixel wide line starting at x0, y0 and ending at x1, y1.
Args:
x0 (int): Start point x coordinate
y0 (int): Start point y coordinate
x1 (int): End point x coordinate
y1 (int): End point y coordinate
color (int): 565 encoded color
"""
steep = abs(y1 - y0) > abs(x1 - x0)
if steep:
x0, y0 = y0, x0
x1, y1 = y1, x1
if x0 > x1:
x0, x1 = x1, x0
y0, y1 = y1, y0
dx = x1 - x0
dy = abs(y1 - y0)
err = dx // 2
if y0 < y1:
ystep = 1
else:
ystep = -1
while x0 <= x1:
if steep:
self.pixel(y0, x0, color)
else:
self.pixel(x0, y0, color)
err -= dy
if err < 0:
y0 += ystep
err += dx
x0 += 1
def vscrdef(self, tfa, vsa, bfa):
"""
Set Vertical Scrolling Definition.
To scroll a 135x240 display these values should be 40, 240, 40.
There are 40 lines above the display that are not shown followed by
240 lines that are shown followed by 40 more lines that are not shown.
You could write to these areas off display and scroll them into view by
changing the TFA, VSA and BFA values.
Args:
tfa (int): Top Fixed Area
vsa (int): Vertical Scrolling Area
bfa (int): Bottom Fixed Area
"""
struct.pack(">HHH", tfa, vsa, bfa)
self._write(ST7789_VSCRDEF, struct.pack(">HHH", tfa, vsa, bfa))
def vscsad(self, vssa):
"""
Set Vertical Scroll Start Address of RAM.
Defines which line in the Frame Memory will be written as the first
line after the last line of the Top Fixed Area on the display
Example:
for line in range(40, 280, 1):
tft.vscsad(line)
utime.sleep(0.01)
Args:
vssa (int): Vertical Scrolling Start Address
"""
self._write(ST7789_VSCSAD, struct.pack(">H", vssa))
def _text8(self, font, text, x0, y0, color=WHITE, background=BLACK):
"""
Internal method to write characters with width of 8 and
heights of 8 or 16.
Args:
font (module): font module to use
text (str): text to write
x0 (int): column to start drawing at
y0 (int): row to start drawing at
color (int): 565 encoded color to use for characters
background (int): 565 encoded color to use for background
"""
for char in text:
ch = ord(char)
if (font.FIRST <= ch < font.LAST
and x0+font.WIDTH <= self.width
and y0+font.HEIGHT <= self.height):
if font.HEIGHT == 8:
passes = 1
size = 8
each = 0
else:
passes = 2
size = 16
each = 8
for line in range(passes):
idx = (ch-font.FIRST)*size+(each*line)
buffer = struct.pack(
'>64H',
color if font.FONT[idx] & _BIT7 else background,
color if font.FONT[idx] & _BIT6 else background,
color if font.FONT[idx] & _BIT5 else background,
color if font.FONT[idx] & _BIT4 else background,
color if font.FONT[idx] & _BIT3 else background,
color if font.FONT[idx] & _BIT2 else background,
color if font.FONT[idx] & _BIT1 else background,
color if font.FONT[idx] & _BIT0 else background,
color if font.FONT[idx+1] & _BIT7 else background,
color if font.FONT[idx+1] & _BIT6 else background,
color if font.FONT[idx+1] & _BIT5 else background,
color if font.FONT[idx+1] & _BIT4 else background,
color if font.FONT[idx+1] & _BIT3 else background,
color if font.FONT[idx+1] & _BIT2 else background,
color if font.FONT[idx+1] & _BIT1 else background,
color if font.FONT[idx+1] & _BIT0 else background,
color if font.FONT[idx+2] & _BIT7 else background,
color if font.FONT[idx+2] & _BIT6 else background,
color if font.FONT[idx+2] & _BIT5 else background,
color if font.FONT[idx+2] & _BIT4 else background,
color if font.FONT[idx+2] & _BIT3 else background,
color if font.FONT[idx+2] & _BIT2 else background,
color if font.FONT[idx+2] & _BIT1 else background,
color if font.FONT[idx+2] & _BIT0 else background,
color if font.FONT[idx+3] & _BIT7 else background,
color if font.FONT[idx+3] & _BIT6 else background,
color if font.FONT[idx+3] & _BIT5 else background,
color if font.FONT[idx+3] & _BIT4 else background,
color if font.FONT[idx+3] & _BIT3 else background,
color if font.FONT[idx+3] & _BIT2 else background,
color if font.FONT[idx+3] & _BIT1 else background,
color if font.FONT[idx+3] & _BIT0 else background,
color if font.FONT[idx+4] & _BIT7 else background,
color if font.FONT[idx+4] & _BIT6 else background,
color if font.FONT[idx+4] & _BIT5 else background,
color if font.FONT[idx+4] & _BIT4 else background,
color if font.FONT[idx+4] & _BIT3 else background,
color if font.FONT[idx+4] & _BIT2 else background,
color if font.FONT[idx+4] & _BIT1 else background,
color if font.FONT[idx+4] & _BIT0 else background,
color if font.FONT[idx+5] & _BIT7 else background,
color if font.FONT[idx+5] & _BIT6 else background,
color if font.FONT[idx+5] & _BIT5 else background,
color if font.FONT[idx+5] & _BIT4 else background,
color if font.FONT[idx+5] & _BIT3 else background,
color if font.FONT[idx+5] & _BIT2 else background,
color if font.FONT[idx+5] & _BIT1 else background,
color if font.FONT[idx+5] & _BIT0 else background,
color if font.FONT[idx+6] & _BIT7 else background,
color if font.FONT[idx+6] & _BIT6 else background,
color if font.FONT[idx+6] & _BIT5 else background,
color if font.FONT[idx+6] & _BIT4 else background,
color if font.FONT[idx+6] & _BIT3 else background,
color if font.FONT[idx+6] & _BIT2 else background,
color if font.FONT[idx+6] & _BIT1 else background,
color if font.FONT[idx+6] & _BIT0 else background,
color if font.FONT[idx+7] & _BIT7 else background,
color if font.FONT[idx+7] & _BIT6 else background,
color if font.FONT[idx+7] & _BIT5 else background,
color if font.FONT[idx+7] & _BIT4 else background,
color if font.FONT[idx+7] & _BIT3 else background,
color if font.FONT[idx+7] & _BIT2 else background,
color if font.FONT[idx+7] & _BIT1 else background,
color if font.FONT[idx+7] & _BIT0 else background
)
self.blit_buffer(buffer, x0, y0+8*line, 8, 8)
x0 += 8
def _text16(self, font, text, x0, y0, color=WHITE, background=BLACK):
"""
Internal method to draw characters with width of 16 and heights of 16
or 32.
Args:
font (module): font module to use
text (str): text to write
x0 (int): column to start drawing at
y0 (int): row to start drawing at
color (int): 565 encoded color to use for characters
background (int): 565 encoded color to use for background
"""
for char in text:
ch = ord(char)
if (font.FIRST <= ch < font.LAST
and x0+font.WIDTH <= self.width
and y0+font.HEIGHT <= self.height):
if font.HEIGHT == 16:
passes = 2
size = 32
each = 16
else:
passes = 4
size = 64
each = 16
for line in range(passes):
idx = (ch-font.FIRST)*size+(each*line)
buffer = struct.pack(
'>128H',
color if font.FONT[idx] & _BIT7 else background,
color if font.FONT[idx] & _BIT6 else background,
color if font.FONT[idx] & _BIT5 else background,
color if font.FONT[idx] & _BIT4 else background,
color if font.FONT[idx] & _BIT3 else background,
color if font.FONT[idx] & _BIT2 else background,
color if font.FONT[idx] & _BIT1 else background,
color if font.FONT[idx] & _BIT0 else background,
color if font.FONT[idx+1] & _BIT7 else background,
color if font.FONT[idx+1] & _BIT6 else background,
color if font.FONT[idx+1] & _BIT5 else background,
color if font.FONT[idx+1] & _BIT4 else background,
color if font.FONT[idx+1] & _BIT3 else background,
color if font.FONT[idx+1] & _BIT2 else background,
color if font.FONT[idx+1] & _BIT1 else background,
color if font.FONT[idx+1] & _BIT0 else background,
color if font.FONT[idx+2] & _BIT7 else background,
color if font.FONT[idx+2] & _BIT6 else background,
color if font.FONT[idx+2] & _BIT5 else background,
color if font.FONT[idx+2] & _BIT4 else background,
color if font.FONT[idx+2] & _BIT3 else background,
color if font.FONT[idx+2] & _BIT2 else background,
color if font.FONT[idx+2] & _BIT1 else background,
color if font.FONT[idx+2] & _BIT0 else background,
color if font.FONT[idx+3] & _BIT7 else background,
color if font.FONT[idx+3] & _BIT6 else background,
color if font.FONT[idx+3] & _BIT5 else background,
color if font.FONT[idx+3] & _BIT4 else background,
color if font.FONT[idx+3] & _BIT3 else background,
color if font.FONT[idx+3] & _BIT2 else background,
color if font.FONT[idx+3] & _BIT1 else background,
color if font.FONT[idx+3] & _BIT0 else background,
color if font.FONT[idx+4] & _BIT7 else background,
color if font.FONT[idx+4] & _BIT6 else background,
color if font.FONT[idx+4] & _BIT5 else background,
color if font.FONT[idx+4] & _BIT4 else background,
color if font.FONT[idx+4] & _BIT3 else background,
color if font.FONT[idx+4] & _BIT2 else background,
color if font.FONT[idx+4] & _BIT1 else background,
color if font.FONT[idx+4] & _BIT0 else background,
color if font.FONT[idx+5] & _BIT7 else background,
color if font.FONT[idx+5] & _BIT6 else background,
color if font.FONT[idx+5] & _BIT5 else background,
color if font.FONT[idx+5] & _BIT4 else background,
color if font.FONT[idx+5] & _BIT3 else background,
color if font.FONT[idx+5] & _BIT2 else background,
color if font.FONT[idx+5] & _BIT1 else background,
color if font.FONT[idx+5] & _BIT0 else background,
color if font.FONT[idx+6] & _BIT7 else background,
color if font.FONT[idx+6] & _BIT6 else background,
color if font.FONT[idx+6] & _BIT5 else background,
color if font.FONT[idx+6] & _BIT4 else background,
color if font.FONT[idx+6] & _BIT3 else background,
color if font.FONT[idx+6] & _BIT2 else background,
color if font.FONT[idx+6] & _BIT1 else background,
color if font.FONT[idx+6] & _BIT0 else background,
color if font.FONT[idx+7] & _BIT7 else background,
color if font.FONT[idx+7] & _BIT6 else background,
color if font.FONT[idx+7] & _BIT5 else background,
color if font.FONT[idx+7] & _BIT4 else background,
color if font.FONT[idx+7] & _BIT3 else background,
color if font.FONT[idx+7] & _BIT2 else background,
color if font.FONT[idx+7] & _BIT1 else background,
color if font.FONT[idx+7] & _BIT0 else background,
color if font.FONT[idx+8] & _BIT7 else background,
color if font.FONT[idx+8] & _BIT6 else background,
color if font.FONT[idx+8] & _BIT5 else background,
color if font.FONT[idx+8] & _BIT4 else background,
color if font.FONT[idx+8] & _BIT3 else background,
color if font.FONT[idx+8] & _BIT2 else background,
color if font.FONT[idx+8] & _BIT1 else background,
color if font.FONT[idx+8] & _BIT0 else background,
color if font.FONT[idx+9] & _BIT7 else background,
color if font.FONT[idx+9] & _BIT6 else background,
color if font.FONT[idx+9] & _BIT5 else background,
color if font.FONT[idx+9] & _BIT4 else background,
color if font.FONT[idx+9] & _BIT3 else background,
color if font.FONT[idx+9] & _BIT2 else background,
color if font.FONT[idx+9] & _BIT1 else background,
color if font.FONT[idx+9] & _BIT0 else background,
color if font.FONT[idx+10] & _BIT7 else background,
color if font.FONT[idx+10] & _BIT6 else background,
color if font.FONT[idx+10] & _BIT5 else background,
color if font.FONT[idx+10] & _BIT4 else background,
color if font.FONT[idx+10] & _BIT3 else background,
color if font.FONT[idx+10] & _BIT2 else background,
color if font.FONT[idx+10] & _BIT1 else background,
color if font.FONT[idx+10] & _BIT0 else background,
color if font.FONT[idx+11] & _BIT7 else background,
color if font.FONT[idx+11] & _BIT6 else background,
color if font.FONT[idx+11] & _BIT5 else background,
color if font.FONT[idx+11] & _BIT4 else background,
color if font.FONT[idx+11] & _BIT3 else background,
color if font.FONT[idx+11] & _BIT2 else background,
color if font.FONT[idx+11] & _BIT1 else background,
color if font.FONT[idx+11] & _BIT0 else background,
color if font.FONT[idx+12] & _BIT7 else background,
color if font.FONT[idx+12] & _BIT6 else background,
color if font.FONT[idx+12] & _BIT5 else background,
color if font.FONT[idx+12] & _BIT4 else background,
color if font.FONT[idx+12] & _BIT3 else background,
color if font.FONT[idx+12] & _BIT2 else background,
color if font.FONT[idx+12] & _BIT1 else background,
color if font.FONT[idx+12] & _BIT0 else background,
color if font.FONT[idx+13] & _BIT7 else background,
color if font.FONT[idx+13] & _BIT6 else background,
color if font.FONT[idx+13] & _BIT5 else background,
color if font.FONT[idx+13] & _BIT4 else background,
color if font.FONT[idx+13] & _BIT3 else background,
color if font.FONT[idx+13] & _BIT2 else background,
color if font.FONT[idx+13] & _BIT1 else background,
color if font.FONT[idx+13] & _BIT0 else background,
color if font.FONT[idx+14] & _BIT7 else background,
color if font.FONT[idx+14] & _BIT6 else background,
color if font.FONT[idx+14] & _BIT5 else background,
color if font.FONT[idx+14] & _BIT4 else background,
color if font.FONT[idx+14] & _BIT3 else background,
color if font.FONT[idx+14] & _BIT2 else background,
color if font.FONT[idx+14] & _BIT1 else background,
color if font.FONT[idx+14] & _BIT0 else background,
color if font.FONT[idx+15] & _BIT7 else background,
color if font.FONT[idx+15] & _BIT6 else background,
color if font.FONT[idx+15] & _BIT5 else background,
color if font.FONT[idx+15] & _BIT4 else background,
color if font.FONT[idx+15] & _BIT3 else background,
color if font.FONT[idx+15] & _BIT2 else background,
color if font.FONT[idx+15] & _BIT1 else background,
color if font.FONT[idx+15] & _BIT0 else background
)
self.blit_buffer(buffer, x0, y0+8*line, 16, 8)
x0 += font.WIDTH
def text(self, font, text, x0, y0, color=WHITE, background=BLACK):
"""
Draw text on display in specified font and colors. 8 and 16 bit wide
fonts are supported.
Args:
font (module): font module to use.
text (str): text to write
x0 (int): column to start drawing at
y0 (int): row to start drawing at
color (int): 565 encoded color to use for characters
background (int): 565 encoded color to use for background
"""
if font.WIDTH == 8:
self._text8(font, text, x0, y0, color, background)
else:
self._text16(font, text, x0, y0, color, background)
def bitmap(self, bitmap, x, y, index=0):
"""
Draw a bitmap on display at the specified column and row
Args:
bitmap (bitmap_module): The module containing the bitmap to draw
x (int): column to start drawing at
y (int): row to start drawing at
index (int): Optional index of bitmap to draw from multiple bitmap
module
"""
bitmap_size = bitmap.HEIGHT * bitmap.WIDTH
buffer_len = bitmap_size * 2
buffer = bytearray(buffer_len)
bs_bit = bitmap.BPP * bitmap_size * index if index > 0 else 0
for i in range(0, buffer_len, 2):
color_index = 0
for bit in range(bitmap.BPP):
color_index <<= 1
color_index |= (bitmap.BITMAP[bs_bit // 8]
& 1 << (7 - (bs_bit % 8))) > 0
bs_bit += 1
color = bitmap.PALETTE[color_index]
buffer[i] = color & 0xff00 >> 8
buffer[i + 1] = color_index & 0xff
to_col = x + bitmap.WIDTH - 1
to_row = y + bitmap.HEIGHT - 1
if self.width > to_col and self.height > to_row:
self._set_window(x, y, to_col, to_row)
self._write(None, buffer)
# @micropython.native
def write(self, font, string, x, y, fg=WHITE, bg=BLACK):
"""
Write a string using a converted true-type font on the display starting
at the specified column and row
Args:
font (font): The module containing the converted true-type font
s (string): The string to write
x (int): column to start writing
y (int): row to start writing
fg (int): foreground color, optional, defaults to WHITE
bg (int): background color, optional, defaults to BLACK
"""
buffer_len = font.HEIGHT * font.MAX_WIDTH * 2
buffer = bytearray(buffer_len)
fg_hi = (fg & 0xff00) >> 8
fg_lo = fg & 0xff
bg_hi = (bg & 0xff00) >> 8
bg_lo = bg & 0xff
for character in string:
try:
char_index = font.MAP.index(character)
offset = char_index * font.OFFSET_WIDTH
bs_bit = font.OFFSETS[offset]
if font.OFFSET_WIDTH > 1:
bs_bit = (bs_bit << 8) + font.OFFSETS[offset + 1]
if font.OFFSET_WIDTH > 2:
bs_bit = (bs_bit << 8) + font.OFFSETS[offset + 2]
char_width = font.WIDTHS[char_index]
buffer_needed = char_width * font.HEIGHT * 2
for i in range(0, buffer_needed, 2):
if font.BITMAPS[bs_bit // 8] & 1 << (7 - (bs_bit % 8)) > 0:
buffer[i] = fg_hi
buffer[i + 1] = fg_lo
else:
buffer[i] = bg_hi
buffer[i + 1] = bg_lo
bs_bit += 1
to_col = x + char_width - 1
to_row = y + font.HEIGHT - 1
if self.width > to_col and self.height > to_row:
self._set_window(x, y, to_col, to_row)
self._write(None, buffer[0:buffer_needed])
x += char_width
except ValueError:
pass
def write_width(self, font, string):
"""
Returns the width in pixels of the string if it was written with the
specified font
Args:
font (font): The module containing the converted true-type font
string (string): The string to measure
"""
width = 0
for character in string:
try:
char_index = font.MAP.index(character)
width += font.WIDTHS[char_index]
except ValueError:
pass
return width
| YifuLiu/AliOS-Things | components/py_engine/framework/st7789py.py | Python | apache-2.0 | 36,749 |
import time
from umqtt.robust import MQTTClient
def sub_cb(topic, msg):
print((topic, msg))
c = MQTTClient("umqtt_client", "localhost")
# Print diagnostic messages when retries/reconnects happens
c.DEBUG = True
c.set_callback(sub_cb)
# Connect to server, requesting not to clean session for this
# client. If there was no existing session (False return value
# from connect() method), we perform the initial setup of client
# session - subscribe to needed topics. Afterwards, these
# subscriptions will be stored server-side, and will be persistent,
# (as we use clean_session=False).
#
# There can be a problem when a session for a given client exists,
# but doesn't have subscriptions a particular application expects.
# In this case, a session needs to be cleaned first. See
# example_reset_session.py for an obvious way how to do that.
#
# In an actual application, it's up to its developer how to
# manage these issues. One extreme is to have external "provisioning"
# phase, where initial session setup, and any further management of
# a session, is done by external tools. This allows to save resources
# on a small embedded device. Another extreme is to have an application
# to perform auto-setup (e.g., clean session, then re-create session
# on each restart). This example shows mid-line between these 2
# approaches, where initial setup of session is done by application,
# but if anything goes wrong, there's an external tool to clean session.
if not c.connect(clean_session=False):
print("New session being set up")
c.subscribe(b"foo_topic")
while 1:
c.wait_msg()
c.disconnect()
| YifuLiu/AliOS-Things | components/py_engine/micropython-lib/micropython/umqtt.robust/example_sub_robust.py | Python | apache-2.0 | 1,615 |
import sys
# Remove current dir from sys.path, otherwise setuptools will peek up our
# module instead of system's.
sys.path.pop(0)
from setuptools import setup
sys.path.append("..")
import sdist_upip
setup(
name="micropython-umqtt.robust",
version="1.0.1",
description='Lightweight MQTT client for MicroPython ("robust" version).',
long_description=open("README.rst").read(),
url="https://github.com/micropython/micropython-lib",
author="Paul Sokolovsky",
author_email="micro-python@googlegroups.com",
maintainer="micropython-lib Developers",
maintainer_email="micro-python@googlegroups.com",
license="MIT",
cmdclass={"sdist": sdist_upip.sdist},
packages=["umqtt"],
)
| YifuLiu/AliOS-Things | components/py_engine/micropython-lib/micropython/umqtt.robust/setup.py | Python | apache-2.0 | 719 |
import utime
from . import simple
class MQTTClient(simple.MQTTClient):
DELAY = 2
DEBUG = False
def delay(self, i):
utime.sleep(self.DELAY)
def log(self, in_reconnect, e):
if self.DEBUG:
if in_reconnect:
print("mqtt reconnect: %r" % e)
else:
print("mqtt: %r" % e)
def reconnect(self):
i = 0
while 1:
try:
return super().connect(False)
except OSError as e:
self.log(True, e)
i += 1
self.delay(i)
def publish(self, topic, msg, retain=False, qos=0):
while 1:
try:
return super().publish(topic, msg, retain, qos)
except OSError as e:
self.log(False, e)
self.reconnect()
def wait_msg(self):
while 1:
try:
return super().wait_msg()
except OSError as e:
self.log(False, e)
self.reconnect()
| YifuLiu/AliOS-Things | components/py_engine/micropython-lib/micropython/umqtt.robust/umqtt/robust.py | Python | apache-2.0 | 1,046 |
from umqtt.simple import MQTTClient
# Test reception e.g. with:
# mosquitto_sub -t foo_topic
def main(server="localhost"):
c = MQTTClient("umqtt_client", server)
c.connect()
c.publish(b"foo_topic", b"hello")
c.disconnect()
if __name__ == "__main__":
main()
| YifuLiu/AliOS-Things | components/py_engine/micropython-lib/micropython/umqtt.simple/example_pub.py | Python | apache-2.0 | 282 |
import time
import ubinascii
import machine
from umqtt.simple import MQTTClient
from machine import Pin
# Many ESP8266 boards have active-low "flash" button on GPIO0.
button = Pin(0, Pin.IN)
# Default MQTT server to connect to
SERVER = "192.168.1.35"
CLIENT_ID = ubinascii.hexlify(machine.unique_id())
TOPIC = b"led"
def main(server=SERVER):
c = MQTTClient(CLIENT_ID, server)
c.connect()
print("Connected to %s, waiting for button presses" % server)
while True:
while True:
if button.value() == 0:
break
time.sleep_ms(20)
print("Button pressed")
c.publish(TOPIC, b"toggle")
time.sleep_ms(200)
c.disconnect()
| YifuLiu/AliOS-Things | components/py_engine/micropython-lib/micropython/umqtt.simple/example_pub_button.py | Python | apache-2.0 | 706 |
import time
from umqtt.simple import MQTTClient
# Publish test messages e.g. with:
# mosquitto_pub -t foo_topic -m hello
# Received messages from subscriptions will be delivered to this callback
def sub_cb(topic, msg):
print((topic, msg))
def main(server="localhost"):
c = MQTTClient("umqtt_client", server)
c.set_callback(sub_cb)
c.connect()
c.subscribe(b"foo_topic")
while True:
if True:
# Blocking wait for message
c.wait_msg()
else:
# Non-blocking wait for message
c.check_msg()
# Then need to sleep to avoid 100% CPU usage (in a real
# app other useful actions would be performed instead)
time.sleep(1)
c.disconnect()
if __name__ == "__main__":
main()
| YifuLiu/AliOS-Things | components/py_engine/micropython-lib/micropython/umqtt.simple/example_sub.py | Python | apache-2.0 | 796 |
from umqtt.simple import MQTTClient
from machine import Pin
import ubinascii
import machine
import micropython
# ESP8266 ESP-12 modules have blue, active-low LED on GPIO2, replace
# with something else if needed.
led = Pin(2, Pin.OUT, value=1)
# Default MQTT server to connect to
SERVER = "192.168.1.35"
CLIENT_ID = ubinascii.hexlify(machine.unique_id())
TOPIC = b"led"
state = 0
def sub_cb(topic, msg):
global state
print((topic, msg))
if msg == b"on":
led.value(0)
state = 1
elif msg == b"off":
led.value(1)
state = 0
elif msg == b"toggle":
# LED is inversed, so setting it to current state
# value will make it toggle
led.value(state)
state = 1 - state
def main(server=SERVER):
c = MQTTClient(CLIENT_ID, server)
# Subscribed messages will be delivered to this callback
c.set_callback(sub_cb)
c.connect()
c.subscribe(TOPIC)
print("Connected to %s, subscribed to %s topic" % (server, TOPIC))
try:
while 1:
# micropython.mem_info()
c.wait_msg()
finally:
c.disconnect()
| YifuLiu/AliOS-Things | components/py_engine/micropython-lib/micropython/umqtt.simple/example_sub_led.py | Python | apache-2.0 | 1,135 |
import sys
# Remove current dir from sys.path, otherwise setuptools will peek up our
# module instead of system's.
sys.path.pop(0)
from setuptools import setup
sys.path.append("..")
import sdist_upip
setup(
name="micropython-umqtt.simple",
version="1.3.4",
description="Lightweight MQTT client for MicroPython.",
long_description=open("README.rst").read(),
url="https://github.com/micropython/micropython-lib",
author="Paul Sokolovsky",
author_email="micro-python@googlegroups.com",
maintainer="micropython-lib Developers",
maintainer_email="micro-python@googlegroups.com",
license="MIT",
cmdclass={"sdist": sdist_upip.sdist},
packages=["umqtt"],
)
| YifuLiu/AliOS-Things | components/py_engine/micropython-lib/micropython/umqtt.simple/setup.py | Python | apache-2.0 | 700 |
import usocket as socket
import ustruct as struct
from ubinascii import hexlify
class MQTTException(Exception):
pass
class MQTTClient:
def __init__(
self,
client_id,
server,
port=0,
user=None,
password=None,
keepalive=0,
ssl=False,
ssl_params={},
):
if port == 0:
port = 8883 if ssl else 1883
self.client_id = client_id
self.sock = None
self.server = server
self.port = port
self.ssl = ssl
self.ssl_params = ssl_params
self.pid = 0
self.cb = None
self.user = user
self.pswd = password
self.keepalive = keepalive
self.lw_topic = None
self.lw_msg = None
self.lw_qos = 0
self.lw_retain = False
def _send_str(self, s):
self.sock.write(struct.pack("!H", len(s)))
self.sock.write(s)
def _recv_len(self):
n = 0
sh = 0
while 1:
b = self.sock.read(1)[0]
n |= (b & 0x7F) << sh
if not b & 0x80:
return n
sh += 7
def set_callback(self, f):
self.cb = f
def set_last_will(self, topic, msg, retain=False, qos=0):
assert 0 <= qos <= 2
assert topic
self.lw_topic = topic
self.lw_msg = msg
self.lw_qos = qos
self.lw_retain = retain
def connect(self, clean_session=True):
self.sock = socket.socket()
addr = socket.getaddrinfo(self.server, self.port)[0][-1]
self.sock.connect(addr)
if self.ssl:
import ussl
self.sock = ussl.wrap_socket(self.sock, **self.ssl_params)
premsg = bytearray(b"\x10\0\0\0\0\0")
msg = bytearray(b"\x04MQTT\x04\x02\0\0")
sz = 10 + 2 + len(self.client_id)
msg[6] = clean_session << 1
if self.user is not None:
sz += 2 + len(self.user) + 2 + len(self.pswd)
msg[6] |= 0xC0
if self.keepalive:
assert self.keepalive < 65536
msg[7] |= self.keepalive >> 8
msg[8] |= self.keepalive & 0x00FF
if self.lw_topic:
sz += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)
msg[6] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3
msg[6] |= self.lw_retain << 5
i = 1
while sz > 0x7F:
premsg[i] = (sz & 0x7F) | 0x80
sz >>= 7
i += 1
premsg[i] = sz
self.sock.write(premsg, i + 2)
self.sock.write(msg)
# print(hex(len(msg)), hexlify(msg, ":"))
self._send_str(self.client_id)
if self.lw_topic:
self._send_str(self.lw_topic)
self._send_str(self.lw_msg)
if self.user is not None:
self._send_str(self.user)
self._send_str(self.pswd)
resp = self.sock.read(4)
assert resp[0] == 0x20 and resp[1] == 0x02
if resp[3] != 0:
raise MQTTException(resp[3])
return resp[2] & 1
def disconnect(self):
self.sock.write(b"\xe0\0")
self.sock.close()
def ping(self):
self.sock.write(b"\xc0\0")
def publish(self, topic, msg, retain=False, qos=0):
pkt = bytearray(b"\x30\0\0\0")
pkt[0] |= qos << 1 | retain
sz = 2 + len(topic) + len(msg)
if qos > 0:
sz += 2
assert sz < 2097152
i = 1
while sz > 0x7F:
pkt[i] = (sz & 0x7F) | 0x80
sz >>= 7
i += 1
pkt[i] = sz
# print(hex(len(pkt)), hexlify(pkt, ":"))
self.sock.write(pkt, i + 1)
self._send_str(topic)
if qos > 0:
self.pid += 1
pid = self.pid
struct.pack_into("!H", pkt, 0, pid)
self.sock.write(pkt, 2)
self.sock.write(msg)
if qos == 1:
while 1:
op = self.wait_msg()
if op == 0x40:
sz = self.sock.read(1)
assert sz == b"\x02"
rcv_pid = self.sock.read(2)
rcv_pid = rcv_pid[0] << 8 | rcv_pid[1]
if pid == rcv_pid:
return
elif qos == 2:
assert 0
def subscribe(self, topic, qos=0):
assert self.cb is not None, "Subscribe callback is not set"
pkt = bytearray(b"\x82\0\0\0")
self.pid += 1
struct.pack_into("!BH", pkt, 1, 2 + 2 + len(topic) + 1, self.pid)
# print(hex(len(pkt)), hexlify(pkt, ":"))
self.sock.write(pkt)
self._send_str(topic)
self.sock.write(qos.to_bytes(1, "little"))
while 1:
op = self.wait_msg()
if op == 0x90:
resp = self.sock.read(4)
# print(resp)
assert resp[1] == pkt[2] and resp[2] == pkt[3]
if resp[3] == 0x80:
raise MQTTException(resp[3])
return
# Wait for a single incoming MQTT message and process it.
# Subscribed messages are delivered to a callback previously
# set by .set_callback() method. Other (internal) MQTT
# messages processed internally.
def wait_msg(self):
res = self.sock.read(1)
self.sock.setblocking(True)
if res is None:
return None
if res == b"":
raise OSError(-1)
if res == b"\xd0": # PINGRESP
sz = self.sock.read(1)[0]
assert sz == 0
return None
op = res[0]
if op & 0xF0 != 0x30:
return op
sz = self._recv_len()
topic_len = self.sock.read(2)
topic_len = (topic_len[0] << 8) | topic_len[1]
topic = self.sock.read(topic_len)
sz -= topic_len + 2
if op & 6:
pid = self.sock.read(2)
pid = pid[0] << 8 | pid[1]
sz -= 2
msg = self.sock.read(sz)
self.cb(topic, msg)
if op & 6 == 2:
pkt = bytearray(b"\x40\x02\0\0")
struct.pack_into("!H", pkt, 2, pid)
self.sock.write(pkt)
elif op & 6 == 4:
assert 0
# Checks whether a pending message from server is available.
# If not, returns immediately with None. Otherwise, does
# the same processing as wait_msg.
def check_msg(self):
self.sock.setblocking(False)
return self.wait_msg()
| YifuLiu/AliOS-Things | components/py_engine/micropython-lib/micropython/umqtt.simple/umqtt/simple.py | Python | apache-2.0 | 6,479 |
all:
# This target prepares snapshot of all dependency modules, for
# self-contained install
deps: upip_gzip.py upip_utarfile.py
upip_gzip.py: ../gzip/gzip.py
cp $^ $@
upip_utarfile.py: ../utarfile/utarfile.py
cp $^ $@
clean:
rm upip_*.py
| YifuLiu/AliOS-Things | components/py_engine/micropython-lib/micropython/upip/Makefile | Makefile | apache-2.0 | 245 |
# This script performs bootstrap installation of upip package manager from PyPI
# All the other packages can be installed using it.
if [ -z "$TMPDIR" ]; then
cd /tmp
else
cd $TMPDIR
fi
# Remove any stale old version
rm -rf micropython-upip-*
wget -nd -rH -l1 -D files.pythonhosted.org https://pypi.org/project/micropython-upip/ --reject=html
tar xfz micropython-upip-*.tar.gz
mkdir -p ~/.micropython/lib/
cp micropython-upip-*/upip*.py ~/.micropython/lib/
echo "upip is installed. To use:"
echo "micropython -m upip --help"
| YifuLiu/AliOS-Things | components/py_engine/micropython-lib/micropython/upip/bootstrap_upip.sh | Shell | apache-2.0 | 536 |
import sys
# Remove current dir from sys.path, otherwise setuptools will peek up our
# module instead of system's.
sys.path.pop(0)
from setuptools import setup
sys.path.append("..")
import sdist_upip
setup(
name="micropython-upip",
version="1.2.4",
description="Simple package manager for MicroPython.",
long_description="Simple self-hosted package manager for MicroPython (requires usocket, ussl, uzlib, uctypes builtin modules). Compatible only with packages without custom setup.py code.",
url="https://github.com/micropython/micropython-lib",
author="Paul Sokolovsky",
author_email="micro-python@googlegroups.com",
maintainer="micropython-lib Developers",
maintainer_email="micro-python@googlegroups.com",
license="MIT",
cmdclass={"sdist": sdist_upip.sdist},
py_modules=["upip", "upip_utarfile"],
)
| YifuLiu/AliOS-Things | components/py_engine/micropython-lib/micropython/upip/setup.py | Python | apache-2.0 | 854 |
#
# upip - Package manager for MicroPython
#
# Copyright (c) 2015-2018 Paul Sokolovsky
#
# Licensed under the MIT license.
#
import sys
import gc
import uos as os
import uerrno as errno
import ujson as json
import uzlib
import upip_utarfile as tarfile
gc.collect()
debug = False
install_path = None
cleanup_files = []
gzdict_sz = 16 + 15
file_buf = bytearray(512)
class NotFoundError(Exception):
pass
def op_split(path):
if path == "":
return ("", "")
r = path.rsplit("/", 1)
if len(r) == 1:
return ("", path)
head = r[0]
if not head:
head = "/"
return (head, r[1])
def op_basename(path):
return op_split(path)[1]
# Expects *file* name
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:
raise
ret = False
return ret
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)
def install_tar(f, prefix):
meta = {}
for info in f:
# print(info)
fname = info.name
try:
fname = fname[fname.index("/") + 1 :]
except ValueError:
fname = ""
save = True
for p in ("setup.", "PKG-INFO", "README"):
# print(fname, p)
if fname.startswith(p) or ".egg-info" in fname:
if fname.endswith("/requires.txt"):
meta["deps"] = f.extractfile(info).read()
save = False
if debug:
print("Skipping", fname)
break
if save:
outfname = prefix + fname
if info.type != tarfile.DIRTYPE:
if debug:
print("Extracting " + outfname)
_makedirs(outfname)
subf = f.extractfile(info)
save_file(outfname, subf)
return meta
def expandhome(s):
if "~/" in s:
h = os.getenv("HOME")
s = s.replace("~/", h + "/")
return s
import ussl
import usocket
warn_ussl = True
def url_open(url):
global warn_ussl
if debug:
print(url)
proto, _, host, urlpath = url.split("/", 3)
try:
ai = usocket.getaddrinfo(host, 443, 0, usocket.SOCK_STREAM)
except OSError as e:
fatal("Unable to resolve %s (no Internet?)" % host, e)
# print("Address infos:", ai)
ai = ai[0]
s = usocket.socket(ai[0], ai[1], ai[2])
try:
# print("Connect address:", addr)
s.connect(ai[-1])
if proto == "https:":
s = ussl.wrap_socket(s, server_hostname=host)
if warn_ussl:
print("Warning: %s SSL certificate is not validated" % host)
warn_ussl = False
# MicroPython rawsocket module supports file interface directly
s.write("GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n" % (urlpath, host))
l = s.readline()
protover, status, msg = l.split(None, 2)
if status != b"200":
if status == b"404" or status == b"301":
raise NotFoundError("Package not found")
raise ValueError(status)
while 1:
l = s.readline()
if not l:
raise ValueError("Unexpected EOF in HTTP headers")
if l == b"\r\n":
break
except Exception as e:
s.close()
raise e
return s
def get_pkg_metadata(name):
f = url_open("https://pypi.org/pypi/%s/json" % name)
try:
return json.load(f)
finally:
f.close()
def fatal(msg, exc=None):
print("Error:", msg)
if exc and debug:
raise exc
sys.exit(1)
def install_pkg(pkg_spec, install_path):
data = get_pkg_metadata(pkg_spec)
latest_ver = data["info"]["version"]
packages = data["releases"][latest_ver]
del data
gc.collect()
assert len(packages) == 1
package_url = packages[0]["url"]
print("Installing %s %s from %s" % (pkg_spec, latest_ver, package_url))
package_fname = op_basename(package_url)
f1 = url_open(package_url)
try:
f2 = uzlib.DecompIO(f1, gzdict_sz)
f3 = tarfile.TarFile(fileobj=f2)
meta = install_tar(f3, install_path)
finally:
f1.close()
del f3
del f2
gc.collect()
return meta
def install(to_install, install_path=None):
# Calculate gzip dictionary size to use
global gzdict_sz
sz = gc.mem_free() + gc.mem_alloc()
if sz <= 65536:
gzdict_sz = 16 + 12
if install_path is None:
install_path = get_install_path()
if install_path[-1] != "/":
install_path += "/"
if not isinstance(to_install, list):
to_install = [to_install]
print("Installing to: " + install_path)
# sets would be perfect here, but don't depend on them
installed = []
try:
while to_install:
if debug:
print("Queue:", to_install)
pkg_spec = to_install.pop(0)
if pkg_spec in installed:
continue
meta = install_pkg(pkg_spec, install_path)
installed.append(pkg_spec)
if debug:
print(meta)
deps = meta.get("deps", "").rstrip()
if deps:
deps = deps.decode("utf-8").split("\n")
to_install.extend(deps)
except Exception as e:
print(
"Error installing '{}': {}, packages may be partially installed".format(pkg_spec, e),
file=sys.stderr,
)
def get_install_path():
global install_path
if install_path is None:
# sys.path[0] is current module's path
install_path = sys.path[1]
install_path = expandhome(install_path)
return install_path
def cleanup():
for fname in cleanup_files:
try:
os.unlink(fname)
except OSError:
print("Warning: Cannot delete " + fname)
def help():
print(
"""\
upip - Simple PyPI package manager for MicroPython
Usage: micropython -m upip install [-p <path>] <package>... | -r <requirements.txt>
import upip; upip.install(package_or_list, [<path>])
If <path> is not given, packages will be installed into sys.path[1]
(can be set from MICROPYPATH environment variable, if current system
supports that)."""
)
print("Current value of sys.path[1]:", sys.path[1])
print(
"""\
Note: only MicroPython packages (usually, named micropython-*) are supported
for installation, upip does not support arbitrary code in setup.py.
"""
)
def main():
global debug
global install_path
install_path = None
if len(sys.argv) < 2 or sys.argv[1] == "-h" or sys.argv[1] == "--help":
help()
return
if sys.argv[1] != "install":
fatal("Only 'install' command supported")
to_install = []
i = 2
while i < len(sys.argv) and sys.argv[i][0] == "-":
opt = sys.argv[i]
i += 1
if opt == "-h" or opt == "--help":
help()
return
elif opt == "-p":
install_path = sys.argv[i]
i += 1
elif opt == "-r":
list_file = sys.argv[i]
i += 1
with open(list_file) as f:
while True:
l = f.readline()
if not l:
break
if l[0] == "#":
continue
to_install.append(l.rstrip())
elif opt == "--debug":
debug = True
else:
fatal("Unknown/unsupported option: " + opt)
to_install.extend(sys.argv[i:])
if not to_install:
help()
return
install(to_install)
if not debug:
cleanup()
if __name__ == "__main__":
main()
| YifuLiu/AliOS-Things | components/py_engine/micropython-lib/micropython/upip/upip.py | Python | apache-2.0 | 8,229 |
import uctypes
# http://www.gnu.org/software/tar/manual/html_node/Standard.html
TAR_HEADER = {
"name": (uctypes.ARRAY | 0, uctypes.UINT8 | 100),
"size": (uctypes.ARRAY | 124, uctypes.UINT8 | 11),
}
DIRTYPE = "dir"
REGTYPE = "file"
def roundup(val, align):
return (val + align - 1) & ~(align - 1)
class FileSection:
def __init__(self, f, content_len, aligned_len):
self.f = f
self.content_len = content_len
self.align = aligned_len - content_len
def read(self, sz=65536):
if self.content_len == 0:
return b""
if sz > self.content_len:
sz = self.content_len
data = self.f.read(sz)
sz = len(data)
self.content_len -= sz
return data
def readinto(self, buf):
if self.content_len == 0:
return 0
if len(buf) > self.content_len:
buf = memoryview(buf)[: self.content_len]
sz = self.f.readinto(buf)
self.content_len -= sz
return sz
def skip(self):
sz = self.content_len + self.align
if sz:
buf = bytearray(16)
while sz:
s = min(sz, 16)
self.f.readinto(buf, s)
sz -= s
class TarInfo:
def __str__(self):
return "TarInfo(%r, %s, %d)" % (self.name, self.type, self.size)
class TarFile:
def __init__(self, name=None, fileobj=None):
if fileobj:
self.f = fileobj
else:
self.f = open(name, "rb")
self.subf = None
def next(self):
if self.subf:
self.subf.skip()
buf = self.f.read(512)
if not buf:
return None
h = uctypes.struct(uctypes.addressof(buf), TAR_HEADER, uctypes.LITTLE_ENDIAN)
# Empty block means end of archive
if h.name[0] == 0:
return None
d = TarInfo()
d.name = str(h.name, "utf-8").rstrip("\0")
d.size = int(bytes(h.size), 8)
d.type = [REGTYPE, DIRTYPE][d.name[-1] == "/"]
self.subf = d.subf = FileSection(self.f, d.size, roundup(d.size, 512))
return d
def __iter__(self):
return self
def __next__(self):
v = self.next()
if v is None:
raise StopIteration
return v
def extractfile(self, tarinfo):
return tarinfo.subf
| YifuLiu/AliOS-Things | components/py_engine/micropython-lib/micropython/upip/upip_utarfile.py | Python | apache-2.0 | 2,371 |
import sys
# Remove current dir from sys.path, otherwise setuptools will peek up our
# module instead of system's.
sys.path.pop(0)
from setuptools import setup
sys.path.append("..")
import sdist_upip
setup(
name="micropython-upysh",
version="0.6.1",
description="Minimalistic file shell using native Python syntax.",
long_description="Minimalistic file shell using native Python syntax.",
url="https://github.com/micropython/micropython-lib",
author="micropython-lib Developers",
author_email="micro-python@googlegroups.com",
maintainer="micropython-lib Developers",
maintainer_email="micro-python@googlegroups.com",
license="MIT",
cmdclass={"sdist": sdist_upip.sdist},
py_modules=["upysh"],
)
| YifuLiu/AliOS-Things | components/py_engine/micropython-lib/micropython/upysh/setup.py | Python | apache-2.0 | 745 |
import sys
import os
class LS:
def __repr__(self):
self.__call__()
return ""
def __call__(self, path="."):
l = os.listdir(path)
l.sort()
for f in l:
st = os.stat("%s/%s" % (path, f))
if st[0] & 0x4000: # stat.S_IFDIR
print(" <dir> %s" % f)
else:
print("% 8d %s" % (st[6], f))
class PWD:
def __repr__(self):
return os.getcwd()
def __call__(self):
return self.__repr__()
class CLEAR:
def __repr__(self):
return "\x1b[2J\x1b[H"
def __call__(self):
return self.__repr__()
pwd = PWD()
ls = LS()
clear = CLEAR()
cd = os.chdir
mkdir = os.mkdir
mv = os.rename
rm = os.remove
rmdir = os.rmdir
def head(f, n=10):
with open(f) as f:
for i in range(n):
l = f.readline()
if not l:
break
sys.stdout.write(l)
def cat(f):
head(f, 1 << 30)
def newfile(path):
print("Type file contents line by line, finish with EOF (Ctrl+D).")
with open(path, "w") as f:
while 1:
try:
l = input()
except EOFError:
break
f.write(l)
f.write("\n")
class Man:
def __repr__(self):
return """
upysh is intended to be imported using:
from upysh import *
To see this help text again, type "man".
upysh commands:
pwd, cd("new_dir"), ls, ls(...), head(...), cat(...)
newfile(...), mv("old", "new"), rm(...), mkdir(...), rmdir(...),
clear
"""
man = Man()
print(man)
| YifuLiu/AliOS-Things | components/py_engine/micropython-lib/micropython/upysh/upysh.py | Python | apache-2.0 | 1,589 |
try:
import urequests as requests
except ImportError:
import requests
r = requests.get("http://api.xively.com/")
print(r)
print(r.content)
print(r.text)
print(r.content)
print(r.json())
# It's mandatory to close response objects as soon as you finished
# working with them. On MicroPython platforms without full-fledged
# OS, not doing so may lead to resource leaks and malfunction.
r.close()
| YifuLiu/AliOS-Things | components/py_engine/micropython-lib/python-ecosys/urequests/example_xively.py | Python | apache-2.0 | 403 |
import sys
# Remove current dir from sys.path, otherwise setuptools will peek up our
# module instead of system's.
sys.path.pop(0)
from setuptools import setup
sys.path.append("..")
import sdist_upip
setup(
name="micropython-urequests",
version="0.6",
description="urequests module for MicroPython",
long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.",
url="https://github.com/micropython/micropython-lib",
author="Paul Sokolovsky",
author_email="micro-python@googlegroups.com",
maintainer="micropython-lib Developers",
maintainer_email="micro-python@googlegroups.com",
license="MIT",
cmdclass={"sdist": sdist_upip.sdist},
py_modules=["urequests"],
)
| YifuLiu/AliOS-Things | components/py_engine/micropython-lib/python-ecosys/urequests/setup.py | Python | apache-2.0 | 980 |
import usocket
class Response:
def __init__(self, f):
self.raw = f
self.encoding = "utf-8"
self._cached = None
def close(self):
if self.raw:
self.raw.close()
self.raw = None
self._cached = None
@property
def content(self):
if self._cached is None:
try:
self._cached = self.raw.read()
finally:
self.raw.close()
self.raw = None
return self._cached
@property
def text(self):
return str(self.content, self.encoding)
def json(self):
import ujson
return ujson.loads(self.content)
def request(method, url, data=None, json=None, headers={}, stream=None):
try:
proto, dummy, host, path = url.split("/", 3)
except ValueError:
proto, dummy, host = url.split("/", 2)
path = ""
if proto == "http:":
port = 80
elif proto == "https:":
import ussl
port = 443
else:
raise ValueError("Unsupported protocol: " + proto)
if ":" in host:
host, port = host.split(":", 1)
port = int(port)
ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM)
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(b"%s /%s HTTP/1.0\r\n" % (method, path))
if not "Host" in headers:
s.write(b"Host: %s\r\n" % host)
# Iterate over keys to avoid tuple alloc
for k in headers:
s.write(k)
s.write(b": ")
s.write(headers[k])
s.write(b"\r\n")
if json is not None:
assert data is None
import ujson
data = ujson.dumps(json)
s.write(b"Content-Type: application/json\r\n")
if data:
s.write(b"Content-Length: %d\r\n" % len(data))
s.write(b"\r\n")
if data:
s.write(data)
l = s.readline()
# print(l)
l = l.split(None, 2)
status = int(l[1])
reason = ""
if len(l) > 2:
reason = l[2].rstrip()
while True:
l = s.readline()
if not l or l == b"\r\n":
break
# print(l)
if l.startswith(b"Transfer-Encoding:"):
if b"chunked" in l:
raise ValueError("Unsupported " + l)
elif l.startswith(b"Location:") and not 200 <= status <= 299:
raise NotImplementedError("Redirects not yet supported")
except OSError:
s.close()
raise
resp = Response(s)
resp.status_code = status
resp.reason = reason
return resp
def head(url, **kw):
return request("HEAD", url, **kw)
def get(url, **kw):
return request("GET", url, **kw)
def post(url, **kw):
return request("POST", url, **kw)
def put(url, **kw):
return request("PUT", url, **kw)
def patch(url, **kw):
return request("PATCH", url, **kw)
def delete(url, **kw):
return request("DELETE", url, **kw)
| YifuLiu/AliOS-Things | components/py_engine/micropython-lib/python-ecosys/urequests/urequests.py | Python | apache-2.0 | 3,191 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "aiagent_engine.h"
#include "py/builtin.h"
#include "py/mperrno.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "ulog/ulog.h"
#define LOG_TAG "MOD_AIAGENT"
extern const mp_obj_type_t aiagent_type;
#define AIAGENT_CHECK_PARAMS() \
aiagent_obj_t *self = (aiagent_obj_t *)MP_OBJ_TO_PTR(self_in); \
do { \
if (self == NULL || self->engine_obj == NULL) { \
mp_raise_OSError(EINVAL); \
return mp_const_none; \
} \
} while (0)
// this is the actual C-structure for our new object
typedef struct {
// base represents some basic information, like type
mp_obj_base_t base;
// a member created by us
char *modName;
char *engine_name;
aiagent_engine_t *engine_obj;
mp_obj_t callback;
} aiagent_obj_t;
static aiagent_obj_t *aiagent_obj = NULL;
STATIC mp_obj_t aiagent_new(const mp_obj_type_t *type, size_t n_args,
size_t n_kw, const mp_obj_t *args)
{
aiagent_obj = m_new_obj(aiagent_obj_t);
if (!aiagent_obj) {
mp_raise_OSError(ENOMEM);
return mp_const_none;
}
memset(aiagent_obj, 0, sizeof(aiagent_obj_t));
aiagent_obj->base.type = &aiagent_type;
aiagent_obj->modName = "aiagent";
aiagent_obj->engine_name = (char *)mp_obj_str_get_str(args[0]);
printf("aiagent_obj->engine_name: %s\n", aiagent_obj->engine_name);
aiagent_obj->engine_obj = NULL;
return MP_OBJ_FROM_PTR(aiagent_obj);
}
void aiagent_print(const mp_print_t *print, mp_obj_t self_in,
mp_print_kind_t kind)
{
aiagent_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "modName(%s)", self->modName);
}
STATIC mp_obj_t aiagent_init(mp_obj_t self_in)
{
aiagent_obj_t *self = (aiagent_obj_t *)MP_OBJ_TO_PTR(self_in);
if (self == NULL) {
LOGE(LOG_TAG, "aiagent_obj_t NULL");
return mp_const_none;
}
if (self->engine_obj == NULL) {
self->engine_obj = aiagent_engine_init(self->engine_name);
if (self->engine_obj == NULL) {
LOGE(LOG_TAG, "create aiagent engine failed !\n");
}
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(aiagent_obj_init, aiagent_init);
STATIC mp_obj_t aiagent_uninit(mp_obj_t self_in)
{
AIAGENT_CHECK_PARAMS();
int status = -1;
if (self->engine_obj != NULL) {
aiagent_engine_uninit();
self->engine_obj = NULL;
}
self->callback = NULL;
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(aiagent_obj_uninit, aiagent_uninit);
STATIC mp_obj_t aiagent_config(mp_obj_t self_in, const mp_obj_t channel_in)
{
int32_t ret;
AIAGENT_CHECK_PARAMS();
ai_config_t config;
int channel = mp_obj_get_int(channel_in);
self->engine_obj->config = (ai_config_t *)&config;
self->engine_obj->ai_engine_config(self->engine_obj);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(aiagent_obj_config, aiagent_config);
STATIC int aiagent_python_cb(ai_result_t *result)
{
/*TODO, need to optimize for callback*/
if (aiagent_obj && (aiagent_obj->callback != mp_const_none)) {
callback_to_python_LoBo(aiagent_obj->callback, mp_const_none, NULL);
}
return 0;
}
STATIC mp_obj_t aiagent_infer(size_t n_args, const mp_obj_t *args)
{
int32_t ret;
if (n_args < 4) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__,
n_args);
return mp_const_none;
}
mp_obj_t self_in = args[0];
AIAGENT_CHECK_PARAMS();
self->callback =
(mp_obj_get_type(args[3]) == &mp_type_NoneType) ? NULL : args[3];
self->engine_obj->src1 =
mp_obj_is_str(args[1]) ? (char *)mp_obj_str_get_str(args[1]) : NULL;
self->engine_obj->src2 =
mp_obj_is_str(args[2]) ? (char *)mp_obj_str_get_str(args[2]) : NULL;
self->engine_obj->callback = aiagent_python_cb;
ret = self->engine_obj->ai_engine_model_infer(self->engine_obj);
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(aiagent_obj_model_infer, 4, aiagent_infer);
STATIC const mp_rom_map_elem_t aiagent_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&aiagent_obj_init) },
{ MP_ROM_QSTR(MP_QSTR_uninit), MP_ROM_PTR(&aiagent_obj_uninit) },
{ MP_ROM_QSTR(MP_QSTR_infer), MP_ROM_PTR(&aiagent_obj_model_infer) },
{ MP_ROM_QSTR(MP_QSTR_config), MP_ROM_PTR(&aiagent_obj_config) },
{ MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&aiagent_obj_uninit) },
};
STATIC MP_DEFINE_CONST_DICT(aiagent_locals_dict, aiagent_locals_dict_table);
const mp_obj_type_t aiagent_type = {
.base = { &mp_type_type },
.name = MP_QSTR_AIAgent,
.print = aiagent_print,
.make_new = aiagent_new,
.locals_dict = (mp_obj_dict_t *)&aiagent_locals_dict,
};
| YifuLiu/AliOS-Things | components/py_engine/modules/aiagent/aiagent.c | C | apache-2.0 | 5,065 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if MICROPY_PY_AIAGENT
#include "py/builtin.h"
#include "py/mperrno.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "ulog/ulog.h"
extern const mp_obj_type_t aiagent_type;
// this is the actual C-structure for our new object
STATIC const mp_rom_map_elem_t aiagent_locals_dict_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_aiagent) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_AIAgent), MP_ROM_PTR(&aiagent_type) },
};
STATIC MP_DEFINE_CONST_DICT(aiagent_locals_dict, aiagent_locals_dict_table);
const mp_obj_module_t aiagent_module = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&aiagent_locals_dict,
};
MP_REGISTER_MODULE(MP_QSTR_aiagent, aiagent_module, MICROPY_PY_AIAGENT);
#endif
| YifuLiu/AliOS-Things | components/py_engine/modules/aiagent/modaiagent.c | C | apache-2.0 | 795 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "py/builtin.h"
#include "py/mperrno.h"
#include "py/obj.h"
#include "py/runtime.h"
#if MICROPY_PY_ALIYUNIOT
extern const mp_obj_type_t linksdk_device_type;
extern const mp_obj_type_t linksdk_gateway_type;
STATIC const mp_rom_map_elem_t linksdk_locals_dict_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_aliyunIoT) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_Device), MP_ROM_PTR(&linksdk_device_type) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_Gateway), MP_ROM_PTR(&linksdk_gateway_type) },
};
STATIC MP_DEFINE_CONST_DICT(linksdk_locals_dict, linksdk_locals_dict_table);
const mp_obj_module_t mp_module_aliyunIoT = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&linksdk_locals_dict,
};
MP_REGISTER_MODULE(MP_QSTR_aliyunIoT, mp_module_aliyunIoT, MICROPY_PY_ALIYUNIOT);
#endif
| YifuLiu/AliOS-Things | components/py_engine/modules/aliyunIoT/modaliyunIoT.c | C | apache-2.0 | 875 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include "aos/kernel.h"
#include "aiot_dm_api.h"
#include "aiot_mqtt_api.h"
#include "py/obj.h"
#include "py_defines.h"
#include "stdint.h"
/* device active info report */
#define APPLICATION "soundbox" // product of application
// #define MODULE_NAME aos_get_platform_type() // module type
#define MODULE_NAME "AliOS Things" // module type
#ifndef countof
#define countof(x) (sizeof(x) / sizeof((x)[0]))
#endif
/* device info report format */
#define DEVICE_INFO_UPDATE_FMT \
"[" \
"{\"attrKey\":\"SYS_SDK_LANGUAGE\",\"attrValue\":\"C\",\"domain\":" \
"\"SYSTEM\"}" \
"{\"attrKey\":\"SYS_LP_SDK_VERSION\",\"attrValue\":\"aos-r-3.0.0\"," \
"\"domain\":\"SYSTEM\"}" \
"{\"attrKey\":\"SYS_PARTNER_ID\",\"attrValue\":\"AliOS Things " \
"Team\",\"domain\":\"SYSTEM\"}" \
"{\"attrKey\":\"SYS_MODULE_ID\",\"attrValue\":\"haas-amp-%s@%s\"," \
"\"domain\":\"SYSTEM\"}" \
"]"
typedef enum {
AIOT_MQTT_CONNECT,
AIOT_MQTT_RECONNECT,
AIOT_MQTT_DISCONNECT,
AIOT_MQTT_MESSAGE
} aiot_mqtt_res_type_t;
/**
* @brief dev模块内部发生值得用户关注的状态变化时, 通知用户的事件类型
*/
typedef enum {
/**
* @brief 非法的应答报文
*/
AIOT_DEV_JSCALLBACK_INVALID_REF,
/**
* @brief 应答报文的id字段非法
*/
AIOT_DEV_JSCALLBACK_CREATE_DEV_REF,
/**
* @brief 应答报文的id字段非法
*/
AIOT_DEV_JSCALLBACK_SUBSCRIBE_REF,
/**
* @brief 应答报文的id字段非法
*/
AIOT_DEV_JSCALLBACK_UNSUBSCRIBE_REF,
/**
* @brief 应答报文的id字段非法
*/
AIOT_DEV_JSCALLBACK_PUBLISH_REF,
/**
* @brief 应答报文的id字段非法
*/
AIOT_DEV_JSCALLBACK_POST_PROPS_REF,
/**
* @brief 应答报文的id字段非法
*/
AIOT_DEV_JSCALLBACK_POST_EVENT_REF,
/**
* @brief 应答报文的id字段非法
*/
AIOT_DEV_JSCALLBACK_ONPROPS_REF,
/**
* @brief 应答报文的id字段非法
*/
AIOT_DEV_JSCALLBACK_ONSERVICE_REF,
/**
* @brief 应答报文的id字段非法
*/
AIOT_DEV_JSCALLBACK_REGISTER_DEV_REF,
/**
* @brief 应答报文的id字段非法
*/
AIOT_DEV_JSCALLBACK_END_CLIENT_REF,
/**
* @brief 应答报文的code字段非法
*/
AIOT_DEV_JSCALLBACK_INVALID_CODE
} aiot_dev_jscallback_type_t;
/**
* @brief subdev模块内部发生值得用户关注的状态变化时, 通知用户的事件类型
*/
typedef enum {
/**
* @brief 非法的应答报文
*/
AIOT_SUBDEV_JSCALLBACK_INVALID_REF,
/**
* @brief 应答报文的id字段非法
*/
AIOT_SUBDEV_JSCALLBACK_CREATE_GATEWAY_REF,
/**
* @brief 应答报文的id字段非法
*/
AIOT_SUBDEV_JSCALLBACK_ADD_TOPO_REF,
/**
* @brief 应答报文的id字段非法
*/
AIOT_SUBDEV_JSCALLBACK_GET_TOPO_REF,
/**
* @brief 应答报文的id字段非法
*/
AIOT_SUBDEV_JSCALLBACK_REMOVE_TOPO_REF,
/**
* @brief 应答报文的id字段非法
*/
AIOT_SUBDEV_JSCALLBACK_LOGIN_REF,
/**
* @brief 应答报文的id字段非法
*/
AIOT_SUBDEV_JSCALLBACK_LOGOUT_REF,
/**
* @brief 应答报文的id字段非法
*/
AIOT_SUBDEV_JSCALLBACK_ON_MQTT_MESSAGE_REF,
/**
* @brief 应答报文的code字段非法
*/
AIOT_SUBDEV_JSCALLBACK_REGISTER_SUBDEV_REF,
/**
* @brief 应答报文的id字段非法
*/
AIOT_SUBDEV_JSCALLBACK_SUBSCRIBE_REF,
/**
* @brief 应答报文的id字段非法
*/
AIOT_SUBDEV_JSCALLBACK_UNSUBSCRIBE_REF,
/**
* @brief 应答报文的id字段非法
*/
AIOT_SUBDEV_JSCALLBACK_PUBLISH_REF,
/**
* @brief 应答报文的code字段非法
*/
AIOT_SUBDEV_JSCALLBACK_INVALID_CODE
} aiot_subdev_jscallback_type_t;
typedef struct iot_device_hanlde {
void *mqtt_handle;
void *dm_handle;
char *region;
uint16_t keepaliveSec;
int res;
mp_obj_t *callback;
char g_iot_close_flag;
char g_iot_conn_flag;
aos_sem_t g_iot_close_sem;
aos_sem_t g_iot_connect_sem;
} iot_device_handle_t;
typedef struct iot_gateway_handle {
void *mqtt_handle;
void *subdev_handle;
uint16_t keepaliveSec;
mp_obj_t *callback;
char g_iot_close_flag;
char g_iot_conn_flag;
aos_sem_t g_iot_close_sem;
aos_sem_t g_iot_connect_sem;
} iot_gateway_handle_t;
typedef struct iot_gateway_response {
int js_cb_ref;
int msg_id;
int code;
char productkey[IOTX_PRODUCT_KEY_LEN];
char devicename[IOTX_DEVICE_NAME_LEN];
char message[128];
} iot_gateway_response_t;
typedef struct {
aiot_mqtt_recv_type_t type;
int code;
int topic_len;
int payload_len;
char *topic;
char *payload;
} iot_mqtt_recv_t;
typedef struct {
aiot_mqtt_event_type_t type;
int code;
} iot_mqtt_event_t;
typedef struct {
aiot_mqtt_option_t option;
iot_mqtt_recv_t recv;
iot_mqtt_event_t event;
} iot_mqtt_message_t;
typedef struct {
void (*callback)(iot_mqtt_message_t *message, void *userdata);
void *handle;
} iot_mqtt_userdata_t;
/* create mqtt client */
int32_t pyamp_aiot_mqtt_client_start(void **handle, int keepaliveSec, iot_mqtt_userdata_t *userdata);
/* destroy mqtt client */
int32_t pyamp_aiot_mqtt_client_stop(void **handle);
/* app mqtt process thread */
void pyamp_aiot_app_mqtt_process_thread(void *args);
/* app mqtt recv thread */
void pyamp_aiot_app_mqtt_recv_thread(void *args);
/* property post */
int32_t pyamp_aiot_app_send_property_post(void *dm_handle, char *params);
/* event post */
int32_t pyamp_aiot_app_send_event_post(void *dm_handle, char *event_id, char *params);
/* device dynmic register */
int32_t pyamp_aiot_dynreg_http(mp_obj_t cb);
/* upload by mqtt */
char *pyamp_aiot_upload_mqtt(void *mqtt_handle, char *file_name, char *data, int32_t data_len, mp_obj_t cb);
/* device active info report */
int32_t pyamp_amp_app_devinfo_report(void *mqtt_handle);
| YifuLiu/AliOS-Things | components/py_engine/modules/aliyunIoT/module_aiot.h | C | apache-2.0 | 6,391 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include "aiot_devinfo_api.h"
#include "aiot_mqtt_api.h"
#include "aiot_state_api.h"
#include "aiot_sysdep_api.h"
#ifdef AOS_COMP_KV
#include "aos/kv.h"
#endif
#include "module_aiot.h"
#include "py_defines.h"
#define MOD_STR "AIOT_ACTINFO"
int32_t pyamp_amp_app_devinfo_report(void *mqtt_handle)
{
int32_t res = STATE_SUCCESS;
void *devinfo_handle = NULL;
aiot_devinfo_msg_t *devinfo = NULL;
char *msg = NULL;
int32_t msg_len = 0;
char product_key[IOTX_PRODUCT_KEY_LEN + 1] = { 0 };
char device_name[IOTX_DEVICE_NAME_LEN + 1] = { 0 };
int productkey_len = IOTX_PRODUCT_KEY_LEN;
int devicename_len = IOTX_DEVICE_NAME_LEN;
devinfo_handle = aiot_devinfo_init();
if (devinfo_handle == NULL) {
amp_debug(MOD_STR, "ntp service init failed");
return -1;
}
res = aiot_devinfo_setopt(devinfo_handle, AIOT_DEVINFOOPT_MQTT_HANDLE, (void *)mqtt_handle);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "devinfo set mqtt handle failed, res:-0x%04X.\n", -res);
aiot_devinfo_deinit(&devinfo_handle);
return -1;
}
aos_kv_get(AMP_CUSTOMER_PRODUCTKEY, product_key, &productkey_len);
aos_kv_get(AMP_CUSTOMER_DEVICENAME, device_name, &devicename_len);
msg_len = strlen(DEVICE_INFO_UPDATE_FMT) + 32;
msg = (char *)aos_malloc(msg_len);
if (msg == NULL) {
amp_error(MOD_STR, "malloc msg err");
aiot_devinfo_deinit(&devinfo_handle);
goto exit;
}
memset(msg, 0, msg_len);
/* devinfo update message */
res = snprintf(msg, msg_len, DEVICE_INFO_UPDATE_FMT, APPLICATION, MODULE_NAME);
if (res <= 0) {
amp_error(MOD_STR, "topic msg generate err");
aiot_devinfo_deinit(&devinfo_handle);
res = -1;
goto exit;
}
devinfo = aos_malloc(sizeof(aiot_devinfo_msg_t));
if (devinfo == NULL) {
amp_error(MOD_STR, "device devinfo info malloc failed");
aiot_devinfo_deinit(&devinfo_handle);
res = -1;
goto exit;
}
memset(devinfo, 0, sizeof(aiot_devinfo_msg_t));
devinfo->product_key = aos_malloc(IOTX_PRODUCT_KEY_LEN);
if (devinfo->product_key == NULL) {
amp_error(MOD_STR, "device product_key info malloc failed");
aiot_devinfo_deinit(&devinfo_handle);
res = -1;
goto exit;
}
memset(devinfo->product_key, 0, IOTX_PRODUCT_KEY_LEN);
devinfo->device_name = aos_malloc(IOTX_DEVICE_NAME_LEN);
if (devinfo->device_name == NULL) {
amp_error(MOD_STR, "device device_name info malloc failed");
aiot_devinfo_deinit(&devinfo_handle);
res = -1;
goto exit;
}
memset(devinfo->device_name, 0, IOTX_DEVICE_NAME_LEN);
devinfo->data.update.params = aos_malloc(msg_len);
if (devinfo->data.update.params == NULL) {
amp_error(MOD_STR, "device update info malloc failed");
aiot_devinfo_deinit(&devinfo_handle);
res = -1;
goto exit;
}
memset(devinfo->data.update.params, 0, msg_len);
devinfo->type = AIOT_DEVINFO_MSG_UPDATE;
memcpy(devinfo->product_key, product_key, strlen(product_key));
memcpy(devinfo->device_name, device_name, strlen(device_name));
memcpy(devinfo->data.update.params, msg, msg_len);
res = aiot_devinfo_send(devinfo_handle, devinfo);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "aiot_devinfo_send failed");
aiot_devinfo_deinit(&devinfo_handle);
res = -1;
}
exit:
if (msg)
aos_free(msg);
if (devinfo) {
if (devinfo->product_key)
aos_free(devinfo->product_key);
if (devinfo->device_name) {
aos_free(devinfo->device_name);
}
if (devinfo->data.update.params) {
aos_free(devinfo->data.update.params);
}
aos_free(devinfo);
}
return res;
}
| YifuLiu/AliOS-Things | components/py_engine/modules/aliyunIoT/module_aiot_activeinfo.c | C | apache-2.0 | 3,918 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include "aiot_dm_api.h"
#include "aiot_mqtt_api.h"
#include "aiot_state_api.h"
#include "aiot_sysdep_api.h"
#ifdef AOS_COMP_KV
#include "aos/kv.h"
#endif
#include "module_aiot.h"
#include "py/mperrno.h"
#include "py/mpstate.h"
#include "py/runtime.h"
#include "py_defines.h"
#include "py/mpthread.h"
#define MOD_STR "AIOT_DEVICE"
#define OTA_MODE_NAME "system"
static bool linksdk_device_is_inited = false;
static bool linksdk_device_is_used = false;
// ota_service_t pyamp_g_aiot_device_appota_service;
// static ota_store_module_info_t module_info[3];
// extern const char *pyamp_jsapp_version_get(void);
const mp_obj_type_t linksdk_device_type;
typedef enum {
ON_CONNECT = 1,
ON_CLOSE = 2,
ON_DISCONNECT = 3,
ON_EVENT = 4,
ON_SERVICE = 5,
ON_SUBCRIBE = 6,
ON_PROPS = 7,
ON_ERROR = 8,
ON_REPLY = 9,
ON_RAWDATA = 10,
ON_REGISTER = 11,
ON_CB_MAX = 12,
} lk_cb_func_t;
typedef struct {
iot_device_handle_t *iot_device_handle;
char *topic;
char *payload;
char *service_id;
char *params;
int py_cb_ref;
int ret_code;
int topic_len;
int payload_len;
int params_len;
int dm_recv;
uint64_t msg_id;
aiot_mqtt_option_t option;
aiot_mqtt_event_type_t event_type;
aiot_mqtt_recv_type_t recv_type;
aiot_dm_recv_type_t dm_recv_type;
aiot_dev_jscallback_type_t cb_type;
} device_notify_param_t;
typedef struct {
mp_obj_base_t base;
iot_device_handle_t *iot_device_handle;
} linksdk_device_obj_t;
static char *__amp_rawdup(char *raw, size_t len)
{
char *dst;
if (raw == NULL)
return NULL;
dst = aos_malloc(len + 1);
if (dst == NULL)
return NULL;
memcpy(dst, raw, len);
return dst;
}
static char *__amp_strdup(char *src)
{
char *dst;
size_t len = 0;
if (src == NULL) {
return NULL;
}
len = strlen(src);
dst = aos_malloc(len + 1);
if (dst == NULL) {
return NULL;
}
memcpy(dst, src, len);
dst[len] = '\0';
return dst;
}
static void subcribe_cb(void *handle, const aiot_mqtt_recv_t *packet, void *userdata)
{
iot_device_handle_t *iot_device_handle = (iot_device_handle_t *)userdata;
mp_obj_t ret_dict;
switch (packet->type) {
case AIOT_MQTTRECV_PUB:
{
mp_sched_carg_t *carg = make_cargs(MP_SCHED_CTYPE_DICT);
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_STR, packet->data.pub.topic_len, packet->data.pub.topic,
"topic");
make_carg_entry(carg, 1, MP_SCHED_ENTRY_TYPE_STR, packet->data.pub.payload_len, packet->data.pub.payload,
"payload");
mp_obj_t callback = iot_device_handle->callback[ON_SUBCRIBE];
callback_to_python_LoBo(callback, mp_const_none, carg);
break;
}
default:
break;
}
}
/* cb call to python */
static void aiot_device_notify(void *pdata)
{
device_notify_param_t *param = (device_notify_param_t *)pdata;
mp_obj_t dict = MP_OBJ_NULL;
mp_obj_t callback = MP_OBJ_NULL;
if (param->dm_recv) {
switch (param->dm_recv_type) {
case AIOT_DMRECV_PROPERTY_SET:
{
mp_sched_carg_t *carg = make_cargs(MP_SCHED_CTYPE_DICT);
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_INT, param->ret_code, NULL, "code");
make_carg_entry(carg, 1, MP_SCHED_ENTRY_TYPE_INT, param->msg_id, NULL, "msg_id");
make_carg_entry(carg, 2, MP_SCHED_ENTRY_TYPE_INT, param->params_len, NULL, "params_len");
make_carg_entry(carg, 3, MP_SCHED_ENTRY_TYPE_STR, param->params_len, param->params, "params");
callback = param->iot_device_handle->callback[ON_PROPS];
callback_to_python_LoBo(callback, mp_const_none, carg);
aos_free(param->params);
break;
}
case AIOT_DMRECV_ASYNC_SERVICE_INVOKE:
{
mp_sched_carg_t *carg = make_cargs(MP_SCHED_CTYPE_DICT);
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_INT, param->ret_code, NULL, "code");
make_carg_entry(carg, 1, MP_SCHED_ENTRY_TYPE_INT, param->msg_id, NULL, "msg_id");
make_carg_entry(carg, 2, MP_SCHED_ENTRY_TYPE_STR, strlen(param->service_id), param->service_id, "service_id");
make_carg_entry(carg, 3, MP_SCHED_ENTRY_TYPE_INT, param->params_len, NULL, "params_len");
make_carg_entry(carg, 4, MP_SCHED_ENTRY_TYPE_STR, param->params_len, param->params, "params");
callback = param->iot_device_handle->callback[ON_SERVICE];
callback_to_python_LoBo(callback, mp_const_none, carg);
aos_free(param->service_id);
aos_free(param->params);
break;
}
case AIOT_DMRECV_RAW_DATA:
{
mp_sched_carg_t *carg = make_cargs(MP_SCHED_CTYPE_DICT);
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_INT, param->params_len, NULL, "params_len");
make_carg_entry(carg, 1, MP_SCHED_ENTRY_TYPE_STR, param->params_len, param->params, "params");
callback = param->iot_device_handle->callback[ON_RAWDATA];
callback_to_python_LoBo(callback, mp_const_none, carg);
aos_free(param->params);
break;
}
default:
aos_free(param);
return;
}
} else if (param->option == AIOT_MQTTOPT_EVENT_HANDLER) {
switch (param->event_type) {
case AIOT_MQTTEVT_CONNECT:
case AIOT_MQTTEVT_DISCONNECT:
{
mp_sched_carg_t *carg = make_cargs(MP_SCHED_CTYPE_DICT);
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_INT, param->ret_code, NULL, "code");
callback = param->iot_device_handle->callback[param->cb_type];
callback_to_python_LoBo(callback, mp_const_none, carg);
aos_free(param->params);
break;
}
default:
aos_free(param);
return;
}
} else {
switch (param->recv_type) {
case AIOT_MQTTRECV_PUB:
break;
default:
aos_free(param);
return;
}
}
aos_free(param);
}
/* 用户数据接收处理回调函数 */
static void aiot_app_dm_recv_handler(void *dm_handle, const aiot_dm_recv_t *recv, void *userdata)
{
iot_device_handle_t *iot_device_handle = (iot_device_handle_t *)userdata;
device_notify_param_t *param;
amp_debug(MOD_STR, "aiot_app_dm_recv_handler IS CALLED.\r\n");
param = aos_malloc(sizeof(device_notify_param_t));
if (!param) {
amp_error(MOD_STR, "alloc device_notify_param_t fail.\r\n");
return;
}
memset(param, 0, sizeof(device_notify_param_t));
param->dm_recv = 1;
param->dm_recv_type = recv->type;
param->iot_device_handle = iot_device_handle;
switch (recv->type) {
/* 属性上报, 事件上报, 获取期望属性值或者删除期望属性值的应答 */
case AIOT_DMRECV_GENERIC_REPLY:
{
amp_debug(MOD_STR, "msg_id = %d, code = %d, data = %.*s, message = %.*s\r\n",
recv->data.generic_reply.msg_id, recv->data.generic_reply.code, recv->data.generic_reply.data_len,
recv->data.generic_reply.data, recv->data.generic_reply.message_len,
recv->data.generic_reply.message);
}
break;
/* 属性设置 */
case AIOT_DMRECV_PROPERTY_SET:
{
amp_debug(MOD_STR, "msg_id = %ld, params = %.*s\r\n", (unsigned long)recv->data.property_set.msg_id,
recv->data.property_set.params_len, recv->data.property_set.params);
// param->js_cb_ref =
// iot_device_handle->js_cb_ref[AIOT_DEV_JSCALLBACK_ONPROPS_REF];
param->msg_id = recv->data.property_set.msg_id;
param->params_len = recv->data.property_set.params_len;
param->params = __amp_strdup(recv->data.property_set.params);
param->cb_type = AIOT_DEV_JSCALLBACK_ONPROPS_REF;
/* TODO: 以下代码演示如何对来自云平台的属性设置指令进行应答,
* 用户可取消注释查看演示效果 */
// {
// aiot_dm_msg_t msg;
// memset(&msg, 0, sizeof(aiot_dm_msg_t));
// msg.type = AIOT_DMMSG_PROPERTY_SET_REPLY;
// msg.data.property_set_reply.msg_id =
// recv->data.property_set.msg_id;
// msg.data.property_set_reply.code = 200;
// msg.data.property_set_reply.data = "{}";
// int32_t res = aiot_dm_send(dm_handle, &msg);
// if (res < 0) {
// printf("aiot_dm_send failed\r\n");
// }
// }
}
break;
/* 异步服务调用 */
case AIOT_DMRECV_ASYNC_SERVICE_INVOKE:
{
amp_debug(MOD_STR, "msg_id = %ld, service_id = %s, params = %.*s\r\n",
(unsigned long)recv->data.async_service_invoke.msg_id, recv->data.async_service_invoke.service_id,
recv->data.async_service_invoke.params_len, recv->data.async_service_invoke.params);
// param->js_cb_ref =
// iot_device_handle->js_cb_ref[AIOT_DEV_JSCALLBACK_ONSERVICE_REF];
param->msg_id = recv->data.async_service_invoke.msg_id;
param->params_len = recv->data.async_service_invoke.params_len;
param->service_id = __amp_strdup(recv->data.async_service_invoke.service_id);
param->params = __amp_strdup(recv->data.async_service_invoke.params);
param->cb_type = AIOT_DEV_JSCALLBACK_ONPROPS_REF;
/* TODO: 以下代码演示如何对来自云平台的异步服务调用进行应答,
* 用户可取消注释查看演示效果
*
* 注意: 如果用户在回调函数外进行应答, 需要自行保存msg_id,
* 因为回调函数入参在退出回调函数后将被SDK销毁, 不可以再访问到
*/
// {
// aiot_dm_msg_t msg;
// memset(&msg, 0, sizeof(aiot_dm_msg_t));
// msg.type = AIOT_DMMSG_ASYNC_SERVICE_REPLY;
// msg.data.async_service_reply.msg_id =
// recv->data.async_service_invoke.msg_id;
// msg.data.async_service_reply.code = 200;
// msg.data.async_service_reply.service_id =
// "ToggleLightSwitch"; msg.data.async_service_reply.data =
// "{\"dataA\": 20}"; int32_t res = aiot_dm_send(dm_handle,
// &msg); if (res < 0) {
// printf("aiot_dm_send failed\r\n");
// }
// }
}
break;
/* 同步服务调用 */
case AIOT_DMRECV_SYNC_SERVICE_INVOKE:
{
amp_debug(MOD_STR,
"msg_id = %ld, rrpc_id = %s, service_id = %s, params "
"= %.*s\r\n",
(unsigned long)recv->data.sync_service_invoke.msg_id, recv->data.sync_service_invoke.rrpc_id,
recv->data.sync_service_invoke.service_id, recv->data.sync_service_invoke.params_len,
recv->data.sync_service_invoke.params);
/* TODO: 以下代码演示如何对来自云平台的同步服务调用进行应答,
* 用户可取消注释查看演示效果
*
* 注意: 如果用户在回调函数外进行应答,
* 需要自行保存msg_id和rrpc_id字符串,
* 因为回调函数入参在退出回调函数后将被SDK销毁, 不可以再访问到
*/
// {
// aiot_dm_msg_t msg;
// memset(&msg, 0, sizeof(aiot_dm_msg_t));
// msg.type = AIOT_DMMSG_SYNC_SERVICE_REPLY;
// msg.data.sync_service_reply.rrpc_id =
// recv->data.sync_service_invoke.rrpc_id;
// msg.data.sync_service_reply.msg_id =
// recv->data.sync_service_invoke.msg_id;
// msg.data.sync_service_reply.code = 200;
// msg.data.sync_service_reply.service_id =
// "SetLightSwitchTimer"; msg.data.sync_service_reply.data =
// "{}"; int32_t res = aiot_dm_send(dm_handle, &msg); if (res
// <0) {
// printf("aiot_dm_send failed\r\n");
// }
// }
}
break;
/* 下行二进制数据 */
case AIOT_DMRECV_RAW_DATA:
{
amp_debug(MOD_STR, "raw data len = %d\r\n", recv->data.raw_data.data_len);
/* TODO: 以下代码演示如何发送二进制格式数据,
* 若使用需要有相应的数据透传脚本部署在云端 */
// {
// aiot_dm_msg_t msg;
// uint8_t raw_data[] = {0x01, 0x02};
// memset(&msg, 0, sizeof(aiot_dm_msg_t));
// msg.type = AIOT_DMMSG_RAW_DATA;
// msg.data.raw_data.data = raw_data;
// msg.data.raw_data.data_len = sizeof(raw_data);
// aiot_dm_send(dm_handle, &msg);
// }
}
param->params_len = recv->data.raw_data.data_len;
param->params = __amp_rawdup(recv->data.raw_data.data, recv->data.raw_data.data_len);
param->cb_type = ON_RAWDATA;
break;
/* 二进制格式的同步服务调用, 比单纯的二进制数据消息多了个rrpc_id */
case AIOT_DMRECV_RAW_SYNC_SERVICE_INVOKE:
{
amp_debug(MOD_STR, "raw sync service rrpc_id = %s, data_len = %d\r\n",
recv->data.raw_service_invoke.rrpc_id, recv->data.raw_service_invoke.data_len);
}
break;
default:
break;
}
py_task_schedule_call(aiot_device_notify, param);
}
/* cb register */
STATIC mp_obj_t aiot_register_cb(mp_obj_t self_in, mp_obj_t id, mp_obj_t func)
{
int callback_id = mp_obj_get_int(id);
linksdk_device_obj_t *self = self_in;
if (self == NULL) {
return mp_obj_new_int(-1);
}
if (self->iot_device_handle->callback == NULL) {
return mp_obj_new_int(-1);
}
self->iot_device_handle->callback[callback_id] = func;
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_3(native_aiot_register_cb, aiot_register_cb);
/* connect event */
static void aiot_connect_event(iot_device_handle_t *iot_device_handle)
{
int res = 0;
if (iot_device_handle->dm_handle != NULL) {
amp_warn(MOD_STR, "dm_handle is already initialized");
return;
}
/* device model service */
iot_device_handle->dm_handle = aiot_dm_init();
if (iot_device_handle->dm_handle == NULL) {
amp_debug(MOD_STR, "aiot_dm_init failed\r\n");
return;
}
/* 配置MQTT实例句柄 */
aiot_dm_setopt(iot_device_handle->dm_handle, AIOT_DMOPT_MQTT_HANDLE, iot_device_handle->mqtt_handle);
/* 配置消息接收处理回调函数 */
aiot_dm_setopt(iot_device_handle->dm_handle, AIOT_DMOPT_RECV_HANDLER, (void *)aiot_app_dm_recv_handler);
/* 配置回调函数参数 */
aiot_dm_setopt(iot_device_handle->dm_handle, AIOT_DMOPT_USERDATA, iot_device_handle);
/* app device active info report */
res = pyamp_amp_app_devinfo_report(iot_device_handle->mqtt_handle);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "device active info report failed,ret:-0x%04X\r\n", -res);
}
}
static void aiot_mqtt_message_cb(iot_mqtt_message_t *message, void *userdata)
{
amp_debug(MOD_STR, "aiot_mqtt_message_cb IS CALLED\r\n");
iot_mqtt_userdata_t *udata = (iot_mqtt_userdata_t *)userdata;
if (!message || !udata) {
return;
}
device_notify_param_t *param = aos_malloc(sizeof(device_notify_param_t));
if (!param) {
amp_error(MOD_STR, "alloc device notify param fail\r\n");
return;
}
memset(param, 0, sizeof(device_notify_param_t));
param->iot_device_handle = (iot_device_handle_t *)udata->handle;
param->option = message->option;
amp_debug(MOD_STR, "message->option is %d %p\r\n", message->option, param->iot_device_handle);
if (message->option == AIOT_MQTTOPT_EVENT_HANDLER) {
amp_debug(MOD_STR, "message->event.type is %d\r\n", message->event.type);
switch (message->event.type) {
case AIOT_MQTTEVT_CONNECT:
case AIOT_MQTTEVT_RECONNECT:
aiot_connect_event(param->iot_device_handle);
param->ret_code = message->event.code;
param->event_type = message->event.type;
param->cb_type = ON_CONNECT;
break;
case AIOT_MQTTEVT_DISCONNECT:
param->ret_code = message->event.code;
param->event_type = message->event.type;
param->cb_type = ON_DISCONNECT;
break;
default:
aos_free(param);
return;
}
} else if (message->option == AIOT_MQTTOPT_RECV_HANDLER) {
amp_debug(MOD_STR, "message->recv.type is %d\r\n", message->recv.type);
switch (message->recv.type) {
case AIOT_MQTTRECV_PUB:
param->ret_code = message->recv.code;
param->topic_len = message->recv.topic_len;
param->payload_len = message->recv.payload_len;
param->topic = __amp_strdup(message->recv.topic);
param->payload = __amp_strdup(message->recv.payload);
param->recv_type = message->recv.type;
break;
default:
aos_free(param);
return;
}
} else {
aos_free(param);
return;
}
py_task_schedule_call(aiot_device_notify, param);
}
/* dynmic register */
static mp_obj_t aiot_dynreg(mp_obj_t self_in, mp_obj_t data, mp_obj_t cb)
{
int ret = -1;
char *region = NULL;
char *productKey = NULL;
char *deviceName = NULL;
char *productSecret = NULL;
linksdk_device_obj_t *self = self_in;
if (self_in == NULL) {
mp_raise_OSError(ENOENT);
return mp_obj_new_int(ret);
}
if (!mp_obj_is_dict_or_ordereddict(data)) {
amp_error(MOD_STR, "%s param1 type error,param type must be dict\r\n", __func__);
return mp_obj_new_int(-1);
}
mp_obj_t index = mp_obj_new_str_via_qstr("productKey", 10);
productKey = mp_obj_str_get_str(mp_obj_dict_get(data, index));
index = mp_obj_new_str_via_qstr("productSecret", 13);
productSecret = mp_obj_str_get_str(mp_obj_dict_get(data, index));
index = mp_obj_new_str_via_qstr("deviceName", 10);
deviceName = mp_obj_str_get_str(mp_obj_dict_get(data, index));
// Compatible with old usage, use cn-shanghai by default
if (mp_obj_dict_len(data) < 4) {
region = "cn-shanghai";
} else {
index = mp_obj_new_str_via_qstr("region", 6);
region = mp_obj_str_get_str(mp_obj_dict_get(data, index));
}
if (region == NULL || productKey == NULL || productSecret == NULL) {
amp_error(MOD_STR, "Invalid params, please check it. region=%s productKey=%s productSecret=%s deviceName=%d\r\n", region, productKey, productSecret,
deviceName);
return mp_obj_new_int(-1);
}
aos_kv_set(AMP_CUSTOMER_REGION, region, IOTX_REGION_LEN, 1);
aos_kv_set(AMP_CUSTOMER_PRODUCTKEY, productKey, IOTX_PRODUCT_KEY_LEN, 1);
aos_kv_set(AMP_CUSTOMER_DEVICENAME, deviceName, IOTX_DEVICE_NAME_LEN, 1);
aos_kv_set(AMP_CUSTOMER_PRODUCTSECRET, productSecret, IOTX_PRODUCT_SECRET_LEN, 1);
ret = pyamp_aiot_dynreg_http(cb);
if (ret < STATE_SUCCESS) {
amp_debug(MOD_STR, "device dynmic register failed\r\n");
return mp_obj_new_int(ret);
}
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_3(native_aiot_dynreg, aiot_dynreg);
/* device connect task */
static void aiot_device_connect(void *pdata)
{
int res = -1;
device_notify_param_t *param;
// ota_service_t *ota_svc = &pyamp_g_aiot_device_appota_service;
iot_device_handle_t *iot_device_handle = (iot_device_handle_t *)pdata;
iot_mqtt_userdata_t *userdata;
amp_debug(MOD_STR, "start mqtt connect task\r\n");
uint16_t keepaliveSec = 0;
keepaliveSec = iot_device_handle->keepaliveSec;
userdata = aos_malloc(sizeof(iot_mqtt_userdata_t));
if (!userdata) {
amp_error(MOD_STR, "alloc mqtt userdata fail\r\n");
return;
}
memset(userdata, 0, sizeof(iot_mqtt_userdata_t));
userdata->callback = aiot_mqtt_message_cb;
userdata->handle = iot_device_handle;
res = pyamp_aiot_mqtt_client_start(&iot_device_handle->mqtt_handle, keepaliveSec, userdata);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "mqtt client create failed,ret:-0x%04X\r\n", -res);
aos_free(userdata);
aos_free(iot_device_handle);
return;
}
iot_device_handle->g_iot_conn_flag = 1;
iot_device_handle->res = res;
while (!iot_device_handle->g_iot_close_flag) {
aos_msleep(1000);
}
pyamp_aiot_mqtt_client_stop(&iot_device_handle->mqtt_handle);
aos_free(userdata);
iot_device_handle->g_iot_conn_flag = 0;
linksdk_device_is_used = false;
aos_sem_signal(&iot_device_handle->g_iot_close_sem);
aos_task_exit(0);
}
/*************************************************************************************
* Function: native_aiot_create_device
* Input: none
* Output: return socket fd when create socket success,
* return error number when create socket fail
**************************************************************************************/
static mp_obj_t aiot_create_device(mp_obj_t self_in, mp_obj_t data)
{
int res = -1;
void *mqtt_handle = NULL;
const char *region = NULL;
const char *productKey = NULL;
const char *deviceName = NULL;
const char *deviceSecret = NULL;
u_int32_t keepaliveSec = 0;
aos_task_t iot_device_task;
// ota_service_t *ota_svc = &pyamp_g_aiot_device_appota_service;
linksdk_device_obj_t *self = self_in;
if (self_in == NULL) {
mp_raise_OSError(ENOENT);
amp_error(MOD_STR, "aiot_device_connect, self is NULL. \r\n");
return mp_obj_new_int(-1);
}
if (linksdk_device_is_used == true) {
mp_raise_OSError(ENOENT);
return mp_obj_new_int(-1);
} else {
linksdk_device_is_used = true;
}
if (!mp_obj_is_dict_or_ordereddict(data)) {
amp_error(MOD_STR, "%s param1 type error,param type must be dict\r\n", __func__);
goto failed;
}
mp_obj_t index = mp_obj_new_str_via_qstr("productKey", 10);
productKey = mp_obj_str_get_str(mp_obj_dict_get(data, index));
index = mp_obj_new_str_via_qstr("deviceName", 10);
deviceName = mp_obj_str_get_str(mp_obj_dict_get(data, index));
index = mp_obj_new_str_via_qstr("deviceSecret", 12);
deviceSecret = mp_obj_str_get_str(mp_obj_dict_get(data, index));
index = mp_obj_new_str_via_qstr("keepaliveSec", 12);
keepaliveSec = mp_obj_get_int(mp_obj_dict_get(data, index));
// Compatible with old usage, use cn-shanghai by default
if (mp_obj_dict_len(data) < 5) {
region = "cn-shanghai";
} else {
index = mp_obj_new_str_via_qstr("region", 6);
region = mp_obj_str_get_str(mp_obj_dict_get(data, index));
}
if (region == NULL || productKey == NULL || deviceSecret == NULL || deviceName == NULL) {
amp_error(MOD_STR, "Invalid params, please check it. region=%s productKey=%s deviceName=%s deviceSecret=%s keepaliveSec=%d\r\n", region, productKey, deviceName,
deviceSecret, keepaliveSec);
return mp_obj_new_int(-1);
}
/*
memset(ota_svc->pk, 0, sizeof(ota_svc->pk));
memset(ota_svc->dn, 0, sizeof(ota_svc->dn));
memset(ota_svc->ds, 0, sizeof(ota_svc->ds));
memcpy(ota_svc->pk, productKey, strlen(productKey));
memcpy(ota_svc->dn, deviceName, strlen(deviceName));
memcpy(ota_svc->ds, deviceSecret, strlen(deviceSecret));
*/
aos_kv_set(AMP_CUSTOMER_REGION, region, IOTX_REGION_LEN, 1);
aos_kv_set(AMP_CUSTOMER_PRODUCTKEY, productKey, IOTX_PRODUCT_KEY_LEN, 1);
aos_kv_set(AMP_CUSTOMER_DEVICENAME, deviceName, IOTX_DEVICE_NAME_LEN, 1);
aos_kv_set(AMP_CUSTOMER_DEVICESECRET, deviceSecret, IOTX_DEVICE_SECRET_LEN, 1);
self->iot_device_handle->keepaliveSec = keepaliveSec;
res = aos_task_new_ext(&iot_device_task, "amp aiot device task", aiot_device_connect, self->iot_device_handle,
1024 * 4, AOS_DEFAULT_APP_PRI);
if (res != STATE_SUCCESS) {
amp_error(MOD_STR, "iot create task failed.\r\n");
goto failed;
}
return mp_obj_new_int(0);
failed:
linksdk_device_is_used = false;
return mp_obj_new_int(-1);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_aiot_create_device, aiot_create_device);
#if MICROPY_PY_CHANNEL_ENABLE
/*************************************************************************************
* Function: native_aiot_default_device
* Input: none
* Output: return mqtt handler of otaput module
**************************************************************************************/
extern void *otaput_mqtt_handler;
extern int amp_reg_onservice_cb(void *device_handler, void *func);
static void otaput_async_service_notify(void *handler, void *pdata)
{
iot_device_handle_t *iot_device_handler = (iot_device_handle_t *)handler;
aiot_dm_recv_async_service_invoke_t *params = (aiot_dm_recv_async_service_invoke_t *)pdata;
mp_obj_t callback = MP_OBJ_NULL;
mp_sched_carg_t *carg = make_cargs(MP_SCHED_CTYPE_DICT);
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_INT, params->msg_id, NULL, "msg_id");
make_carg_entry(carg, 1, MP_SCHED_ENTRY_TYPE_STR, strlen(params->service_id), params->service_id, "service_id");
make_carg_entry(carg, 2, MP_SCHED_ENTRY_TYPE_INT, params->params_len, NULL, "params_len");
make_carg_entry(carg, 3, MP_SCHED_ENTRY_TYPE_STR, params->params_len, params->params, "params");
if (iot_device_handler->callback[ON_SERVICE] != NULL) {
callback = iot_device_handler->callback[ON_SERVICE];
callback_to_python_LoBo(callback, mp_const_none, carg);
}
}
static mp_obj_t aiot_default_device(mp_obj_t self_in, mp_obj_t func)
{
int res = -1;
linksdk_device_obj_t *self = self_in;
if (self_in == NULL) {
mp_raise_OSError(ENOENT);
amp_error(MOD_STR, "aiot_default_connect, self is NULL. \r\n");
return mp_obj_new_int(-1);
}
if (otaput_mqtt_handler == NULL) {
amp_error(MOD_STR, "aiot_default_connect, otaput_mqtt_handler is NULL. \r\n");
return mp_obj_new_int(-1);
}
self->iot_device_handle->mqtt_handle = otaput_mqtt_handler;
self->iot_device_handle->callback[ON_SERVICE] = func;
amp_reg_onservice_cb(self->iot_device_handle, otaput_async_service_notify);
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_aiot_default_device, aiot_default_device);
#endif
/* post props */
static mp_obj_t aiot_postProps(mp_obj_t self_in, mp_obj_t data)
{
int res = -1;
char *payload_str = NULL;
amp_debug(MOD_STR, "native_aiot_postProps is called.\r\n");
linksdk_device_obj_t *self = self_in;
if (self_in == NULL) {
mp_raise_OSError(ENOENT);
return mp_obj_new_int(res);
}
if (!mp_obj_is_dict_or_ordereddict(data)) {
amp_error(MOD_STR, "%s data type error,param type must be dict\r\n", __func__);
return mp_obj_new_int(-1);
}
mp_obj_t index = mp_obj_new_str_via_qstr("params", 6);
payload_str = mp_obj_str_get_str(mp_obj_dict_get(data, index));
amp_debug(MOD_STR, "PostProps payload is %s\r\n", payload_str);
if (self->iot_device_handle->dm_handle == NULL) {
amp_error(MOD_STR, "*****dm handle is null\r\n");
return mp_obj_new_int(-1);
}
res = pyamp_aiot_app_send_property_post(self->iot_device_handle->dm_handle, payload_str);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "property post failed, res:-0x%04X\r\n", -res);
return mp_obj_new_int(res);
}
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_aiot_postProps, aiot_postProps);
/* post event */
static mp_obj_t aiot_postEvent(mp_obj_t self_in, mp_obj_t data)
{
int res = -1;
char *event_id = NULL;
char *event_payload = NULL;
amp_debug(MOD_STR, "native_aiot_postEvent is called.\r\n");
linksdk_device_obj_t *self = self_in;
if (self_in == NULL) {
mp_raise_OSError(ENOENT);
return mp_obj_new_int(res);
}
if (!mp_obj_is_dict_or_ordereddict(data)) {
amp_warn(MOD_STR, "%s data type error,param type must be dict.\r\n", __func__);
return mp_obj_new_int(-1);
}
mp_obj_t index = mp_obj_new_str_via_qstr("id", 2);
event_id = mp_obj_str_get_str(mp_obj_dict_get(data, index));
index = mp_obj_new_str_via_qstr("params", 6);
mp_obj_t payload_d = mp_obj_dict_get(data, index);
vstr_t vstr;
mp_print_t print;
vstr_init_print(&vstr, 8, &print);
mp_obj_print_helper(&print, payload_d, PRINT_JSON);
mp_obj_t tmp = mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
event_payload = mp_obj_str_get_str(tmp);
amp_debug(MOD_STR, "native_aiot_postEvent event_id=%s event_payload=%s\r\n", event_id, event_payload);
res = pyamp_aiot_app_send_event_post(self->iot_device_handle->dm_handle, event_id, event_payload);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "post event failed!\r\n");
return mp_obj_new_int(res);
}
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_aiot_postEvent, aiot_postEvent);
/* post rawdata */
static mp_obj_t aiot_postRaw(mp_obj_t self_in, mp_obj_t data)
{
int res = -1;
mp_obj_t bytearray = NULL;
linksdk_device_obj_t *self = self_in;
if (self_in == NULL) {
mp_raise_OSError(ENOENT);
return mp_obj_new_int(res);
}
if (!mp_obj_is_dict_or_ordereddict(data)) {
amp_error(MOD_STR, "%s data type error,param type must be dict\r\n", __func__);
return mp_obj_new_int(-1);
}
mp_obj_t index = mp_obj_new_str_via_qstr("param", 5);
bytearray = mp_obj_dict_get(data, index);
if (!bytearray) {
amp_error(MOD_STR, "%s params data type error,param data type must be bytearray\r\n", __func__);
return mp_obj_new_int(-1);
}
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(bytearray, &bufinfo, MP_BUFFER_READ);
if (self->iot_device_handle->dm_handle == NULL)
return mp_obj_new_int(-1);
res = aiot_app_send_rawdata_post(self->iot_device_handle->dm_handle, bufinfo.buf, bufinfo.len);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "property post failed, res:-0x%04X.\r\n", -res);
return mp_obj_new_int(res);
}
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_aiot_postRaw, aiot_postRaw);
/* onprops */
static mp_obj_t aiot_onProps(mp_obj_t self_in, mp_obj_t data)
{
int res = -1;
linksdk_device_obj_t *self = (linksdk_device_obj_t *)self_in;
if (self_in == NULL) {
mp_raise_OSError(ENOENT);
return mp_obj_new_int(res);
}
return mp_obj_new_int(res);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_aiot_onProps, aiot_onProps);
/* onService */
static mp_obj_t aiot_onService(mp_obj_t self_in, mp_obj_t data)
{
int res = 0;
return mp_obj_new_int(res);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_aiot_onService, aiot_onService);
/* get ntp time */
static mp_obj_t hapy_get_ntp_time(mp_obj_t self_in, mp_obj_t cb)
{
int res = -1;
linksdk_device_obj_t *self = self_in;
if (self_in == NULL) {
return mp_obj_new_int(-1);
}
iot_device_handle_t *iot_device_handle = self->iot_device_handle;
if (!iot_device_handle) {
amp_error(MOD_STR, "parameter must be handle\r\n");
return mp_obj_new_int(-1);
}
res = hapy_aiot_amp_ntp_service(iot_device_handle->mqtt_handle, cb);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "device get ntp failed\r\n");
return mp_obj_new_int(res);
}
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_aiot_get_ntp_time, hapy_get_ntp_time);
/* upload File */
static mp_obj_t aiot_uploadFile(size_t n_args, const mp_obj_t *args)
{
int ret = -1;
char *upload_id = NULL;
linksdk_device_obj_t *self = (linksdk_device_obj_t *)MP_OBJ_TO_PTR(args[0]);
mp_obj_t remoteFileName = args[1];
mp_obj_t localFilePath = args[2];
mp_obj_t cb = args[3];
mp_buffer_info_t bufinfo;
iot_device_handle_t *iot_device_handle = self->iot_device_handle;
if (!iot_device_handle) {
amp_error(MOD_STR, "parameter must be handle\r\n");
goto out;
}
char *filename = (char *)mp_obj_str_get_str(remoteFileName);
char *filepath = (char *)mp_obj_str_get_str(localFilePath);
MP_THREAD_GIL_EXIT();
upload_id = pyamp_aiot_upload_mqtt(iot_device_handle->mqtt_handle, filename, filepath, 0, cb);
MP_THREAD_GIL_ENTER();
if (!upload_id) {
amp_error(MOD_STR, "aiot upload file failed!\r\n");
goto out;
}
return mp_obj_new_str(upload_id, strlen(upload_id));
out:
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(native_aiot_uploadFile, 3, aiot_uploadFile);
/* upload Content */
static mp_obj_t aiot_uploadContent(size_t n_args, const mp_obj_t *args)
{
int ret = -1;
char *upload_id = NULL;
linksdk_device_obj_t *self = (linksdk_device_obj_t *)MP_OBJ_TO_PTR(args[0]);
mp_obj_t file_name = args[1];
mp_obj_t data = args[2];
mp_obj_t cb = args[3];
mp_buffer_info_t bufinfo;
iot_device_handle_t *iot_device_handle = self->iot_device_handle;
if (!iot_device_handle) {
amp_error(MOD_STR, "parameter must be handle\r\n");
goto out;
}
char *filename = (char *)mp_obj_str_get_str(file_name);
mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ);
// printf("bufinfo len 0x%x\n", bufinfo.len);
MP_THREAD_GIL_EXIT();
upload_id = pyamp_aiot_upload_mqtt(iot_device_handle->mqtt_handle, filename, bufinfo.buf, bufinfo.len, cb);
MP_THREAD_GIL_ENTER();
if (!upload_id) {
amp_error(MOD_STR, "aiot upload content failed!\r\n");
goto out;
}
return mp_obj_new_str(upload_id, strlen(upload_id));
out:
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(native_aiot_uploadContent, 3, aiot_uploadContent);
/* publish */
static mp_obj_t aiot_publish(mp_obj_t self_in, mp_obj_t data)
{
int res = -1;
const char *topic;
const char *payload;
uint16_t payload_len = 0;
uint8_t qos = 0;
linksdk_device_obj_t *self = (linksdk_device_obj_t *)self_in;
if (self_in == NULL) {
mp_raise_OSError(ENOENT);
return mp_obj_new_int(res);
}
if (!mp_obj_is_dict_or_ordereddict(data)) {
amp_error(MOD_STR, "%s data type error,param type must be dict\r\n", __func__);
return mp_obj_new_int(-1);
}
mp_obj_t index = mp_obj_new_str_via_qstr("topic", 5);
#if MICROPY_PY_CHANNEL_ENABLE
char *device_name = aos_get_device_name();
extern const char *otaput_product_key;
if ((self->iot_device_handle->mqtt_handle == otaput_mqtt_handler) && (NULL != device_name)) {
char topic_hack[100];
unsigned int len = 0;
memset(topic_hack, 0, 100);
/* topic = "/sys/" */
memcpy(topic_hack, "/sys/", 5);
len += 5;
/* topic = "/sys/a1ul4uS7RfV" */
memcpy(topic_hack + len, otaput_product_key, strlen(otaput_product_key));
len += strlen(otaput_product_key);
/* topic = "/sys/a1ul4uS7RfV/" */
memcpy(topic_hack + len, "/", 1);
len += 1;
/* topic = "/sys/a1ul4uS7RfV/haas_30c6f71fxxxx" */
memcpy(topic_hack + len, device_name, strlen(device_name));
len += strlen(device_name);
/* topic = "/sys/a1ul4uS7RfV/haas_30c6f71fxxxx/thing/event/hli_event/post" */
memcpy(topic_hack + len, "/thing/event/hli_event/post", strlen("/thing/event/hli_event/post"));
len += strlen("/thing/event/hli_event/post");
topic = topic_hack;
} else {
topic = mp_obj_str_get_str(mp_obj_dict_get(data, index));
}
#else
topic = mp_obj_str_get_str(mp_obj_dict_get(data, index));
#endif
index = mp_obj_new_str_via_qstr("payload", 7);
payload = mp_obj_str_get_str(mp_obj_dict_get(data, index));
payload_len = strlen(payload);
index = mp_obj_new_str_via_qstr("qos", 3);
qos = mp_obj_get_int(mp_obj_dict_get(data, index));
amp_debug(MOD_STR, "publish topic: %s, payload: %s, payload_len is %d , qos is: %d\r\n", topic, payload,
payload_len, qos);
MP_THREAD_GIL_EXIT();
res = aiot_mqtt_pub(self->iot_device_handle->mqtt_handle, topic, payload, payload_len, qos);
MP_THREAD_GIL_ENTER();
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "aiot app mqtt publish failed\r\n");
return mp_obj_new_int(res);
}
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_aiot_publish, aiot_publish);
/* unsubscribe */
static mp_obj_t aiot_unsubscribe(mp_obj_t self_in, mp_obj_t data)
{
int res = -1;
char *topic;
uint8_t qos = 0;
linksdk_device_obj_t *self = self_in;
if (self_in == NULL) {
mp_raise_OSError(ENOENT);
return mp_obj_new_int(res);
}
if (!mp_obj_is_dict_or_ordereddict(data)) {
amp_error(MOD_STR, "%s data type error,param type must be dict\r\n", __func__);
return mp_obj_new_int(-1);
}
mp_obj_t index = mp_obj_new_str_via_qstr("topic", 5);
topic = mp_obj_str_get_str(mp_obj_dict_get(data, index));
amp_debug(MOD_STR, "unsubscribe topic: %s\r\n", topic);
res = aiot_mqtt_unsub(self->iot_device_handle->mqtt_handle, topic);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "aiot app mqtt unsubscribe failed\r\n");
return mp_obj_new_int(res);
} else {
amp_info(MOD_STR, "unsubcribe topic: %s succeed\r\n", topic);
}
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_aiot_unsubscribe, aiot_unsubscribe);
/* subscribe */
static mp_obj_t aiot_subscribe(mp_obj_t self_in, mp_obj_t data)
{
int res = -1;
char *topic = NULL;
uint32_t qos = 0;
amp_debug(MOD_STR, "native_aiot_subscribe is called\r\n");
linksdk_device_obj_t *self = self_in;
if (self_in == NULL) {
mp_raise_OSError(ENOENT);
return mp_obj_new_int(res);
}
if (!mp_obj_is_dict_or_ordereddict(data)) {
amp_error(MOD_STR, "%s data type error,param type must be dict\r\n", __func__);
return mp_obj_new_int(-1);
}
mp_obj_t index = mp_obj_new_str_via_qstr("topic", 5);
topic = mp_obj_str_get_str(mp_obj_dict_get(data, index));
index = mp_obj_new_str_via_qstr("qos", 3);
qos = mp_obj_get_int(mp_obj_dict_get(data, index));
amp_debug(MOD_STR, "subscribe topic: %s, qos is: %d.\r\n", topic, qos);
res =
aiot_mqtt_sub(self->iot_device_handle->mqtt_handle, topic, subcribe_cb, (uint8_t)qos, self->iot_device_handle);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "aiot app mqtt subscribe failed\r\n");
return mp_obj_new_int(res);
} else {
amp_info(MOD_STR, "subcribe topic: %s succeed\r\n", topic);
}
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_aiot_subscribe, aiot_subscribe);
/*************************************************************************************
* Function: native_aiot_close
* Description: js native addon for
* UDP.close(sock_id)
* Called by: js api
* Input: sock_id: interger
*
* Output: return 0 when UDP.close call ok
* return error number UDP.close call fail
**************************************************************************************/
static mp_obj_t aiot_device_close(mp_obj_t self_in)
{
int res = -1;
linksdk_device_obj_t *self = self_in;
if (self_in == NULL) {
goto out;
}
if (linksdk_device_is_used == false) {
printf("close failed, connect content is not run\n");
res = -1;
goto out;
}
iot_device_handle_t *iot_device_handle = self->iot_device_handle;
if (iot_device_handle->g_iot_conn_flag) {
iot_device_handle->g_iot_close_flag = 1;
aos_sem_wait(&iot_device_handle->g_iot_close_sem, 8000);
iot_device_handle->g_iot_close_flag = 0;
linksdk_device_is_inited = false;
return mp_obj_new_int(0);
}
out:
linksdk_device_is_inited = false;
return mp_obj_new_int(-1);
}
MP_DEFINE_CONST_FUN_OBJ_1(native_aiot_device_close, aiot_device_close);
/* get device handle */
static mp_obj_t get_device_handle(mp_obj_t self_in)
{
int res = -1;
linksdk_device_obj_t *self = self_in;
if (self_in == NULL) {
goto out;
}
iot_device_handle_t *iot_device_handle = self->iot_device_handle;
if (!iot_device_handle) {
amp_error(MOD_STR, "parameter must be handle\r\n");
goto out;
} else {
return mp_obj_new_int((mp_int_t)iot_device_handle);
}
out:
return mp_obj_new_int((mp_int_t)0);
}
MP_DEFINE_CONST_FUN_OBJ_1(native_aiot_get_device_handle, get_device_handle);
/* get device info */
static mp_obj_t aiot_getDeviceInfo(mp_obj_t self_in)
{
int res = -1;
if (self_in == NULL) {
goto out;
}
/* get device tripple info */
char region[IOTX_REGION_LEN + 1] = {0};
char productKey[IOTX_PRODUCT_KEY_LEN + 1] = { 0 };
char productSecret[IOTX_PRODUCT_SECRET_LEN + 1] = { 0 };
char deviceName[IOTX_DEVICE_NAME_LEN + 1] = { 0 };
char deviceSecret[IOTX_DEVICE_SECRET_LEN + 1] = { 0 };
int regionLen = IOTX_REGION_LEN;
int productKeyLen = IOTX_PRODUCT_KEY_LEN;
int productSecretLen = IOTX_PRODUCT_SECRET_LEN;
int deviceNameLen = IOTX_DEVICE_NAME_LEN;
int deviceSecretLen = IOTX_DEVICE_SECRET_LEN;
aos_kv_get(AMP_CUSTOMER_REGION, region, ®ionLen);
aos_kv_get(AMP_CUSTOMER_PRODUCTKEY, productKey, &productKeyLen);
aos_kv_get(AMP_CUSTOMER_PRODUCTSECRET, productSecret, &productSecretLen);
aos_kv_get(AMP_CUSTOMER_DEVICENAME, deviceName, &deviceNameLen);
aos_kv_get(AMP_CUSTOMER_DEVICESECRET, deviceSecret, &deviceSecretLen);
// dict solution
mp_obj_t aiot_deviceinfo_dict = mp_obj_new_dict(5);
mp_obj_dict_store(aiot_deviceinfo_dict, MP_OBJ_NEW_QSTR(qstr_from_str("region")),
mp_obj_new_str(region, strlen(region)));
mp_obj_dict_store(aiot_deviceinfo_dict, MP_OBJ_NEW_QSTR(qstr_from_str("productKey")),
mp_obj_new_str(productKey, strlen(productKey)));
mp_obj_dict_store(aiot_deviceinfo_dict, MP_OBJ_NEW_QSTR(qstr_from_str("productSecret")),
mp_obj_new_str(productSecret, strlen(productSecret)));
mp_obj_dict_store(aiot_deviceinfo_dict, MP_OBJ_NEW_QSTR(qstr_from_str("deviceName")),
mp_obj_new_str(deviceName, strlen(deviceName)));
mp_obj_dict_store(aiot_deviceinfo_dict, MP_OBJ_NEW_QSTR(qstr_from_str("deviceSecret")),
mp_obj_new_str(deviceSecret, strlen(deviceSecret)));
return aiot_deviceinfo_dict;
out:
return mp_obj_new_int((mp_int_t)0);
}
MP_DEFINE_CONST_FUN_OBJ_1(native_aiot_getDeviceInfo, aiot_getDeviceInfo);
STATIC const mp_rom_map_elem_t linkkit_device_locals_dict_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR_on), MP_ROM_PTR(&native_aiot_register_cb) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_connect), MP_ROM_PTR(&native_aiot_create_device) },
#if MICROPY_PY_CHANNEL_ENABLE
{ MP_OBJ_NEW_QSTR(MP_QSTR_default), MP_ROM_PTR(&native_aiot_default_device) },
#endif
{ MP_OBJ_NEW_QSTR(MP_QSTR_getDeviceHandle), MP_ROM_PTR(&native_aiot_get_device_handle) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_getDeviceInfo), MP_ROM_PTR(&native_aiot_getDeviceInfo) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_uploadFile), MP_ROM_PTR(&native_aiot_uploadFile) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_uploadContent), MP_ROM_PTR(&native_aiot_uploadContent) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_register), MP_ROM_PTR(&native_aiot_dynreg) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_subscribe), MP_ROM_PTR(&native_aiot_subscribe) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_unsubscribe), MP_ROM_PTR(&native_aiot_unsubscribe) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_publish), MP_ROM_PTR(&native_aiot_publish) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_postProps), MP_ROM_PTR(&native_aiot_postProps) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_onProps), MP_ROM_PTR(&native_aiot_onProps) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_postRaw), MP_ROM_PTR(&native_aiot_postRaw) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_postEvent), MP_ROM_PTR(&native_aiot_postEvent) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_onService), MP_ROM_PTR(&native_aiot_onService) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_getNtpTime), MP_ROM_PTR(&native_aiot_get_ntp_time) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_end), MP_ROM_PTR(&native_aiot_device_close) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ON_CONNECT), MP_ROM_INT(ON_CONNECT) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ON_DISCONNECT), MP_ROM_INT(ON_DISCONNECT) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ON_SERVICE), MP_ROM_INT(ON_SERVICE) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ON_PROPS), MP_ROM_INT(ON_PROPS) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ON_CLOSE), MP_ROM_INT(ON_CLOSE) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ON_ERROR), MP_ROM_INT(ON_ERROR) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ON_RAWDATA), MP_ROM_INT(ON_RAWDATA) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ON_SUBCRIBE), MP_ROM_INT(ON_SUBCRIBE) },
};
STATIC MP_DEFINE_CONST_DICT(linksdk_device_locals_dict, linkkit_device_locals_dict_table);
STATIC void linksdk_device_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind)
{
linksdk_device_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "aiot_device");
}
STATIC mp_obj_t linksdk_device_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args)
{
if (linksdk_device_is_inited == true) {
amp_error(MOD_STR,
"linksdk_device is limited to one instance running at a "
"time, pls check it\r\n");
return MP_OBJ_NULL;
}
linksdk_device_is_inited = true;
linksdk_device_obj_t *device_obj = m_new_obj(linksdk_device_obj_t);
if (!device_obj) {
mp_raise_OSError(ENOMEM);
return mp_const_none;
}
memset(device_obj, 0, sizeof(linksdk_device_obj_t));
iot_device_handle_t *iot_device_handle = m_new_obj(iot_device_handle_t);
if (!iot_device_handle) {
mp_raise_OSError(ENOMEM);
return mp_const_none;
}
memset(iot_device_handle, 0, sizeof(iot_device_handle_t));
iot_device_handle->callback = m_new0(mp_obj_t, ON_CB_MAX);
aos_sem_new(&iot_device_handle->g_iot_connect_sem, 0);
aos_sem_new(&iot_device_handle->g_iot_close_sem, 0);
device_obj->iot_device_handle = iot_device_handle;
device_obj->base.type = &linksdk_device_type;
return MP_OBJ_FROM_PTR(device_obj);
}
const mp_obj_type_t linksdk_device_type = {
{ &mp_type_type },
.name = MP_QSTR_Device,
.print = linksdk_device_print,
.make_new = linksdk_device_make_new,
.locals_dict = (mp_obj_t)&linksdk_device_locals_dict,
};
| YifuLiu/AliOS-Things | components/py_engine/modules/aliyunIoT/module_aiot_device.c | C | apache-2.0 | 47,590 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include "aiot_dynreg_api.h"
#include "aiot_mqtt_api.h"
#include "aiot_state_api.h"
#include "aiot_sysdep_api.h"
#include "module_aiot.h"
#include "py/runtime.h"
#include "py_defines.h"
// #include "be_inl.h"
#define MOD_STR "AIOT_DYNREG"
/* 位于portfiles/aiot_port文件夹下的系统适配函数集合 */
extern aiot_sysdep_portfile_t g_aiot_sysdep_portfile;
/* 位于external/ali_ca_cert.c中的服务器证书 */
extern const char *ali_ca_cert;
void pyamp_aiot_app_dynreg_recv_handler(void *handle,
const aiot_dynreg_recv_t *packet,
void *userdata)
{
int js_cb_ref = 0;
if (packet->type == AIOT_DYNREGRECV_STATUS_CODE) {
LOGD(MOD_STR, "dynreg rsp code = %d", packet->data.status_code.code);
} else if (packet->type == AIOT_DYNREGRECV_DEVICE_INFO) {
LOGD(MOD_STR, "dynreg DS = %s", packet->data.device_info.device_secret);
aos_kv_set(AMP_CUSTOMER_DEVICESECRET, packet->data.device_info.device_secret,
strlen(packet->data.device_info.device_secret), 1);
mp_sched_carg_t *carg = make_cargs(MP_SCHED_CTYPE_SINGLE);
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_STR, strlen(packet->data.device_info.device_secret),
packet->data.device_info.device_secret, NULL);
callback_to_python_LoBo((mp_obj_t)userdata, mp_const_none, carg);
}
}
int32_t pyamp_aiot_dynreg_http(mp_obj_t cb)
{
int32_t res = STATE_SUCCESS;
char host[100] = { 0 }; /* 用这个数组拼接设备连接的云平台站点全地址, 规则是
${YourProductKey}.iot-as-mqtt.${YourRegionId}.aliyuncs.com" */
uint16_t port = 443; /* 无论设备是否使用TLS连接阿里云平台, 目的端口都是443 */
aiot_sysdep_network_cred_t cred; /* 安全凭据结构体, 如果要用TLS, 这个结构体中配置CA证书等参数 */
/* get device tripple info */
char region[IOTX_REGION_LEN + 1] = { 0 };
char product_key[IOTX_PRODUCT_KEY_LEN + 1] = { 0 };
char product_secret[IOTX_PRODUCT_SECRET_LEN + 1] = { 0 };
char device_name[IOTX_DEVICE_NAME_LEN + 1] = { 0 };
char device_secret[IOTX_DEVICE_SECRET_LEN + 1] = { 0 };
int region_len = IOTX_REGION_LEN;
int productkey_len = IOTX_PRODUCT_KEY_LEN;
int productsecret_len = IOTX_PRODUCT_SECRET_LEN;
int devicename_len = IOTX_DEVICE_NAME_LEN;
int devicesecret_len = IOTX_DEVICE_SECRET_LEN;
aos_kv_get(AMP_CUSTOMER_REGION, region, ®ion_len);
aos_kv_get(AMP_CUSTOMER_PRODUCTKEY, product_key, &productkey_len);
aos_kv_get(AMP_CUSTOMER_PRODUCTSECRET, product_secret, &productsecret_len);
aos_kv_get(AMP_CUSTOMER_DEVICENAME, device_name, &devicename_len);
LOGE(MOD_STR, "dev info pk: %s, ps: %s, dn: %s", product_key, product_secret, device_name);
/* end get device tripple info */
/* 配置SDK的底层依赖 */
aiot_sysdep_set_portfile(&g_aiot_sysdep_portfile);
/* 配置SDK的日志输出 */
// aiot_state_set_logcb(demo_state_logcb);
/* 创建SDK的安全凭据, 用于建立TLS连接 */
memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t));
cred.option = AIOT_SYSDEP_NETWORK_CRED_SVRCERT_CA; /* 使用RSA证书校验MQTT服务端 */
cred.max_tls_fragment = 16384; /* 最大的分片长度为16K, 其它可选值还有4K, 2K, 1K, 0.5K */
cred.sni_enabled = 1; /* TLS建连时, 支持Server Name Indicator */
cred.x509_server_cert = ali_ca_cert; /* 用来验证MQTT服务端的RSA根证书 */
cred.x509_server_cert_len = strlen(ali_ca_cert); /* 用来验证MQTT服务端的RSA根证书长度 */
res = aos_kv_get(AMP_CUSTOMER_DEVICESECRET, device_secret, &devicesecret_len);
if (0 != res || (device_secret[0] == '\0' ||
device_secret[IOTX_DEVICE_SECRET_LEN - 1] != '\0')) {
if (product_secret[0] == '\0') {
LOGE(MOD_STR, "need dynamic register, product secret is null");
return -1;
}
void *dynreg_handle = NULL;
dynreg_handle = aiot_dynreg_init();
if (dynreg_handle == NULL) {
LOGE(MOD_STR, "dynreg handle is null");
aos_task_exit(0);
return -1;
}
/* 配置网络连接的安全凭据, 上面已经创建好了 */
aiot_dynreg_setopt(dynreg_handle, AIOT_DYNREGOPT_NETWORK_CRED, (void *)&cred);
sprintf(host, "iot-auth.%s.aliyuncs.com", region);
/* 配置MQTT服务器地址 */
aiot_dynreg_setopt(dynreg_handle, AIOT_DYNREGOPT_HOST, (void *)host);
/* 配置MQTT服务器端口 */
aiot_dynreg_setopt(dynreg_handle, AIOT_DYNREGOPT_PORT, (void *)&port);
/* 配置设备productKey */
aiot_dynreg_setopt(dynreg_handle, AIOT_DYNREGOPT_PRODUCT_KEY, (void *)product_key);
/* 配置设备productSecret */
aiot_dynreg_setopt(dynreg_handle, AIOT_DYNREGOPT_PRODUCT_SECRET, (void *)product_secret);
/* 配置设备deviceName */
aiot_dynreg_setopt(dynreg_handle, AIOT_DYNREGOPT_DEVICE_NAME, (void *)device_name);
/* 配置DYNREG默认消息接收回调函数 */
aiot_dynreg_setopt(dynreg_handle, AIOT_DYNREGOPT_RECV_HANDLER, (void *)pyamp_aiot_app_dynreg_recv_handler);
/* 配置DYNREG默认消息接收回调函数参数 */
aiot_dynreg_setopt(dynreg_handle, AIOT_DYNREGOPT_USERDATA, cb);
/* 增大DYNREG默认timeout值 */
uint32_t timeout = (2 * 5 * 1000);
aiot_dynreg_setopt(dynreg_handle, AIOT_DYNREGOPT_TIMEOUT_MS, &timeout);
res = aiot_dynreg_send_request(dynreg_handle);
if (res < STATE_SUCCESS) {
LOGE(MOD_STR, "dynamic register send fail res = -0x%04X\n\r", -res);
aiot_dynreg_deinit(&dynreg_handle);
return res;
}
res = aiot_dynreg_recv(dynreg_handle);
if (res < STATE_SUCCESS) {
LOGE(MOD_STR, "dynamic register recv fail res = -0x%04X\n\r", -res);
aiot_dynreg_deinit(&dynreg_handle);
return res;
}
aos_kv_get(AMP_CUSTOMER_DEVICESECRET, device_secret, &devicesecret_len);
res = aiot_dynreg_deinit(&dynreg_handle);
if (res < STATE_SUCCESS) {
LOGE(MOD_STR, "dynamic register deinit fail res = -0x%04X\n\r", -res);
return res;
}
} else {
mp_sched_carg_t *carg = make_cargs(MP_SCHED_CTYPE_SINGLE);
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_STR, strlen(device_secret), device_secret, NULL);
callback_to_python_LoBo(cb, mp_const_none, carg);
LOGD(MOD_STR, "device is already activated");
return STATE_SUCCESS;
}
return STATE_SUCCESS;
}
| YifuLiu/AliOS-Things | components/py_engine/modules/aliyunIoT/module_aiot_dynreg.c | C | apache-2.0 | 6,812 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include "aiot_mqtt_api.h"
#include "aiot_state_api.h"
#include "aiot_subdev_api.h"
#include "aiot_sysdep_api.h"
#ifdef AOS_COMP_KV
#include "aos/kv.h"
#endif
#include "module_aiot.h"
#include "py/mperrno.h"
#include "py/runtime.h"
#include "py_defines.h"
#define MOD_STR "AIOT_GATEWAY"
#define OTA_MODE_NAME "system"
// static ota_service_t pyamp_g_aiot_device_appota_service;
// static ota_store_module_info_t module_info[3];
const mp_obj_type_t linksdk_gateway_type;
typedef enum {
ON_CONNECT = 0,
ON_DISCONNECT = 1,
ON_CLOSE = 2,
ON_SUBCRIBE = 3,
ON_LOGIN = 4,
ON_LOGOUT = 5,
ON_TOPOADD = 6,
ON_TOPOREMOVE = 7,
ON_TOPOGET = 8,
ON_SUBREGISTER = 9,
ON_CB_MAX = 10,
} lk_cb_func_t;
typedef enum {
GATEWAY_TOPO_ADD = 0,
GATEWAY_TOPO_DEL = 1,
GATEWAY_SUBDEV_LOGIN = 2,
GATEWAY_SUBDEV_LOGOUT = 3,
GATEWAY_SUBDEV_REGISTER = 4,
} gateway_funcode_t;
typedef struct {
iot_gateway_handle_t *iot_gateway_handle;
lk_cb_func_t cb_type;
int ret_code;
char *topic;
int topic_len;
char *payload;
int payload_len;
char *params;
int params_len;
uint64_t msg_id;
char *service_id;
aiot_mqtt_option_t option;
aiot_mqtt_event_type_t event_type;
aiot_mqtt_recv_type_t recv_type;
} subdev_notify_param_t;
typedef struct {
mp_obj_base_t base;
mp_uint_t port;
iot_gateway_handle_t *iot_gateway_handle;
} linksdk_gateway_obj_t;
static char *__amp_strdup(const char *src)
{
char *dst;
size_t len = 0;
if (src == NULL) {
return NULL;
}
len = strlen(src);
dst = aos_malloc(len + 1);
if (dst == NULL) {
return NULL;
}
memcpy(dst, src, len);
dst[len] = '\0';
return dst;
}
static void aiot_subdev_packet_dump(const aiot_subdev_recv_t *packet)
{
amp_debug(MOD_STR, "%s: packet->type %d\r\n", __func__, packet->type);
switch (packet->type) {
case AIOT_SUBDEVRECV_TOPO_ADD_REPLY:
case AIOT_SUBDEVRECV_TOPO_DELETE_REPLY:
case AIOT_SUBDEVRECV_TOPO_GET_REPLY:
case AIOT_SUBDEVRECV_BATCH_LOGIN_REPLY:
case AIOT_SUBDEVRECV_BATCH_LOGOUT_REPLY:
case AIOT_SUBDEVRECV_SUB_REGISTER_REPLY:
case AIOT_SUBDEVRECV_PRODUCT_REGISTER_REPLY:
{
amp_debug(MOD_STR, "msgid : %d\r\n", packet->data.generic_reply.msg_id);
amp_debug(MOD_STR, "code : %d\r\n", packet->data.generic_reply.code);
amp_debug(MOD_STR, "product key : %s\r\n", packet->data.generic_reply.product_key);
amp_debug(MOD_STR, "device name : %s\r\n", packet->data.generic_reply.device_name);
amp_debug(MOD_STR, "message : %s\r\n",
(packet->data.generic_reply.message == NULL) ? ("NULL") : (packet->data.generic_reply.message));
amp_debug(MOD_STR, "data : %s\r\n", packet->data.generic_reply.data);
}
break;
case AIOT_SUBDEVRECV_TOPO_CHANGE_NOTIFY:
{
amp_debug(MOD_STR, "msgid : %d\r\n", packet->data.generic_notify.msg_id);
amp_debug(MOD_STR, "product key : %s\r\n", packet->data.generic_notify.product_key);
amp_debug(MOD_STR, "device name : %s\r\n", packet->data.generic_notify.device_name);
amp_debug(MOD_STR, "params : %s\r\n", packet->data.generic_notify.params);
}
break;
default:
break;
}
amp_debug(MOD_STR, "%s exit\r\n", __func__);
}
static void subcribe_cb(void *handle, const aiot_mqtt_recv_t *packet, void *userdata)
{
iot_gateway_handle_t *iot_gateway_handle = (iot_gateway_handle_t *)userdata;
switch (packet->type) {
case AIOT_MQTTRECV_PUB:
{
/* print topic name and topic message */
amp_debug(MOD_STR, "pub, qos: %d, len: %d, topic: %s\r\n", packet->data.pub.qos, packet->data.pub.topic_len,
packet->data.pub.topic);
amp_debug(MOD_STR, "pub, len: %d, payload: %s\r\n", packet->data.pub.payload_len, packet->data.pub.payload);
mp_sched_carg_t *carg = make_cargs(MP_SCHED_CTYPE_DICT);
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_STR, packet->data.pub.topic_len, packet->data.pub.topic,
"topic");
make_carg_entry(carg, 1, MP_SCHED_ENTRY_TYPE_STR, packet->data.pub.payload_len, packet->data.pub.payload,
"payload");
mp_obj_t callback = iot_gateway_handle->callback[ON_SUBCRIBE];
callback_to_python_LoBo(callback, mp_const_none, carg);
break;
}
default:
break;
}
}
static void aiot_subdev_notify(void *pdata)
{
subdev_notify_param_t *param = (subdev_notify_param_t *)pdata;
mp_obj_t dict = MP_OBJ_NULL;
mp_obj_t callback = MP_OBJ_NULL;
switch (param->cb_type) {
case ON_LOGIN:
case ON_LOGOUT:
case ON_TOPOADD:
case ON_TOPOREMOVE:
case ON_SUBREGISTER:
callback = param->iot_gateway_handle->callback[param->cb_type];
callback_to_python_LoBo(callback, MP_OBJ_NEW_SMALL_INT(param->ret_code), NULL);
break;
case ON_TOPOGET:
{
mp_sched_carg_t *carg = make_cargs(MP_SCHED_CTYPE_DICT);
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_INT, param->ret_code, NULL, "code");
make_carg_entry(carg, 1, MP_SCHED_ENTRY_TYPE_STR, strlen(param->params), param->params, "message");
callback = param->iot_gateway_handle->callback[param->cb_type];
callback_to_python_LoBo(callback, mp_const_none, carg);
aos_free(param->params);
break;
}
case ON_CONNECT:
case ON_CLOSE:
case ON_DISCONNECT:
{
mp_sched_carg_t *carg = make_cargs(MP_SCHED_CTYPE_DICT);
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_INT, param->ret_code, NULL, "code");
make_carg_entry(carg, 1, MP_SCHED_ENTRY_TYPE_INT, MP_OBJ_FROM_PTR(param->iot_gateway_handle), NULL,
"handle");
callback = param->iot_gateway_handle->callback[param->cb_type];
callback_to_python_LoBo(callback, mp_const_none, carg);
break;
}
default:
break;
}
aos_free(param);
}
static void aiot_subdev_recv_handler(void *handle, const aiot_subdev_recv_t *packet, void *user_data)
{
iot_gateway_handle_t *iot_gateway_handle = (iot_gateway_handle_t *)user_data;
subdev_notify_param_t *param;
param = aos_malloc(sizeof(subdev_notify_param_t));
if (!param) {
amp_error(MOD_STR, "alloc gateway notify param fail.\r\n");
return;
}
memset(param, 0, sizeof(subdev_notify_param_t));
aiot_subdev_packet_dump(packet);
param->iot_gateway_handle = iot_gateway_handle;
switch (packet->type) {
case AIOT_SUBDEVRECV_TOPO_ADD_REPLY:
param->cb_type = ON_TOPOADD;
param->ret_code = packet->data.generic_reply.code == 200 ? 0 : packet->data.generic_reply.code;
break;
case AIOT_SUBDEVRECV_TOPO_DELETE_REPLY:
param->cb_type = ON_TOPOREMOVE;
param->ret_code = packet->data.generic_reply.code == 200 ? 0 : packet->data.generic_reply.code;
break;
case AIOT_SUBDEVRECV_TOPO_GET_REPLY:
param->cb_type = ON_TOPOGET;
param->ret_code = packet->data.generic_reply.code == 200 ? 0 : packet->data.generic_reply.code;
param->params = __amp_strdup(packet->data.generic_reply.data);
break;
case AIOT_SUBDEVRECV_BATCH_LOGIN_REPLY:
param->cb_type = ON_LOGIN;
param->ret_code = packet->data.generic_reply.code == 200 ? 0 : packet->data.generic_reply.code;
break;
case AIOT_SUBDEVRECV_BATCH_LOGOUT_REPLY:
param->cb_type = ON_LOGOUT;
param->ret_code = packet->data.generic_reply.code == 200 ? 0 : packet->data.generic_reply.code;
break;
case AIOT_SUBDEVRECV_SUB_REGISTER_REPLY:
param->cb_type = ON_SUBREGISTER;
param->ret_code = packet->data.generic_reply.code == 200 ? 0 : packet->data.generic_reply.code;
break;
case AIOT_SUBDEVRECV_PRODUCT_REGISTER_REPLY:
amp_debug(MOD_STR, "msgid : %d\n", packet->data.generic_reply.msg_id);
amp_debug(MOD_STR, "code : %d\n", packet->data.generic_reply.code);
amp_debug(MOD_STR, "product key : %s\n", packet->data.generic_reply.product_key);
amp_debug(MOD_STR, "device name : %s\n", packet->data.generic_reply.device_name);
amp_debug(MOD_STR, "message : %s\n",
(packet->data.generic_reply.message == NULL) ? ("NULL") : (packet->data.generic_reply.message));
amp_debug(MOD_STR, "data : %s\n", packet->data.generic_reply.data);
aos_free(param);
return;
case AIOT_SUBDEVRECV_TOPO_CHANGE_NOTIFY:
amp_debug(MOD_STR, "msgid : %d\n", packet->data.generic_notify.msg_id);
amp_debug(MOD_STR, "product key : %s\n", packet->data.generic_notify.product_key);
amp_debug(MOD_STR, "device name : %s\n", packet->data.generic_notify.device_name);
amp_debug(MOD_STR, "params : %s\n", packet->data.generic_notify.params);
aos_free(param);
return;
default:
{
amp_error(MOD_STR, "%s: unknown type %d\n", __func__, packet->type);
aos_free(param);
return;
}
}
py_task_schedule_call(aiot_subdev_notify, param);
}
static void aiot_mqtt_message_cb(iot_mqtt_message_t *message, void *userdata)
{
iot_mqtt_userdata_t *udata = (iot_mqtt_userdata_t *)userdata;
iot_gateway_handle_t *iot_gateway_handle = (iot_gateway_handle_t *)udata->handle;
subdev_notify_param_t *param;
if (!message || !udata)
return;
amp_debug(MOD_STR, "aiot_mqtt_message_cb IS CALLED\r\n");
param = aos_malloc(sizeof(subdev_notify_param_t));
if (!param) {
amp_error(MOD_STR, "alloc gateway notify param fail\r\n");
return;
}
memset(param, 0, sizeof(subdev_notify_param_t));
param->iot_gateway_handle = iot_gateway_handle;
param->option = message->option;
amp_debug(MOD_STR, "message->option is %d\r\n", message->option);
if (message->option == AIOT_MQTTOPT_EVENT_HANDLER) {
amp_debug(MOD_STR, "message->event.type is %d\r\n", message->event.type);
switch (message->event.type) {
case AIOT_MQTTEVT_CONNECT:
aos_sem_signal(¶m->iot_gateway_handle->g_iot_connect_sem);
aos_free(param);
return;
case AIOT_MQTTEVT_DISCONNECT:
param->cb_type = ON_DISCONNECT;
param->ret_code = message->event.code;
param->event_type = message->event.type;
break;
default:
aos_free(param);
return;
}
} else if (message->option == AIOT_MQTTOPT_RECV_HANDLER) {
amp_debug(MOD_STR, "message->recv.type is %d\r\n", message->recv.type);
switch (message->recv.type) {
case AIOT_MQTTRECV_PUB:
param->ret_code = message->recv.code;
param->topic_len = message->recv.topic_len;
param->payload_len = message->recv.payload_len;
param->topic = __amp_strdup(message->recv.topic);
param->payload = __amp_strdup(message->recv.payload);
param->recv_type = message->recv.type;
break;
default:
aos_free(param);
return;
}
} else {
aos_free(param);
return;
}
py_task_schedule_call(aiot_subdev_notify, param);
}
static void aiot_gateway_connect(void *pdata)
{
int res = -1;
char current_amp_ver[64];
// ota_service_t *ota_svc = &pyamp_g_aiot_device_appota_service;
iot_gateway_handle_t *iot_gateway_handle = (iot_gateway_handle_t *)pdata;
iot_mqtt_userdata_t *userdata;
subdev_notify_param_t *param;
amp_debug(MOD_STR, "start mqtt connect task.\r\n");
uint16_t keepaliveSec = 0;
keepaliveSec = iot_gateway_handle->keepaliveSec;
userdata = aos_malloc(sizeof(iot_mqtt_userdata_t));
if (!userdata) {
amp_error(MOD_STR, "alloc mqtt userdata fail.\r\n");
return;
}
userdata->callback = aiot_mqtt_message_cb;
userdata->handle = iot_gateway_handle;
res = pyamp_aiot_mqtt_client_start(&iot_gateway_handle->mqtt_handle, keepaliveSec, userdata);
if (res < STATE_SUCCESS) {
amp_debug(MOD_STR, "mqtt client create failed\r\n");
aos_free(userdata);
aos_free(iot_gateway_handle);
return;
}
iot_gateway_handle->g_iot_conn_flag = 1;
/* device model service */
iot_gateway_handle->subdev_handle = aiot_subdev_init();
if (iot_gateway_handle->subdev_handle == NULL) {
amp_debug(MOD_STR, "aiot_subdev_init failed\r\n");
aos_free(userdata);
aos_free(iot_gateway_handle);
return;
}
/* set mqtt handle */
aiot_subdev_setopt(iot_gateway_handle->subdev_handle, AIOT_SUBDEVOPT_MQTT_HANDLE, iot_gateway_handle->mqtt_handle);
/* set subdev handler */
aiot_subdev_setopt(iot_gateway_handle->subdev_handle, AIOT_SUBDEVOPT_RECV_HANDLER, aiot_subdev_recv_handler);
/* 配置回调函数参数 */
aiot_subdev_setopt(iot_gateway_handle->subdev_handle, AIOT_SUBDEVOPT_USERDATA, (void *)iot_gateway_handle);
param = aos_malloc(sizeof(subdev_notify_param_t));
if (!param) {
amp_error(MOD_STR, "alloc gateway notify param fail.\r\n");
return;
}
aos_sem_wait(&iot_gateway_handle->g_iot_connect_sem, AOS_WAIT_FOREVER);
/* Make sure gateway related functions can be performed in the CONNECT
* callback */
param->ret_code = 0;
param->iot_gateway_handle = iot_gateway_handle;
param->cb_type = ON_CONNECT;
param->option = AIOT_MQTTOPT_EVENT_HANDLER;
param->event_type = AIOT_MQTTEVT_CONNECT;
py_task_schedule_call(aiot_subdev_notify, param);
/* app gateway active info report */
res = pyamp_amp_app_devinfo_report(iot_gateway_handle->mqtt_handle);
if (res < STATE_SUCCESS)
amp_debug(MOD_STR, "gateway active info report failed\r\n");
while (!iot_gateway_handle->g_iot_close_flag)
aos_msleep(1000);
pyamp_aiot_mqtt_client_stop(&iot_gateway_handle->mqtt_handle);
aos_free(userdata);
iot_gateway_handle->g_iot_conn_flag = 0;
aos_sem_signal(&iot_gateway_handle->g_iot_close_sem);
aos_task_exit(0);
return;
}
/*************************************************************************************
* Function: native_aiot_create_gateway
* Description: js native addon for UDP.createSocket();
* Called by: js api
* Input: none
* Output: return socket fd when create socket success,
* return error number when create socket fail
**************************************************************************************/
static mp_obj_t aiot_create_gateway(mp_obj_t self_in, mp_obj_t data)
{
int res = -1;
void *mqtt_handle = NULL;
const char *region = NULL;
const char *productKey = NULL;
const char *deviceName = NULL;
const char *deviceSecret = NULL;
u_int32_t keepaliveSec = 0;
aos_task_t iot_gateway_task;
iot_gateway_handle_t *iot_gateway_handle = NULL;
// ota_service_t *ota_svc = &pyamp_g_aiot_device_appota_service;
linksdk_gateway_obj_t *self = self_in;
if (self_in == NULL) {
mp_raise_OSError(ENOENT);
return mp_obj_new_int(res);
}
if (!mp_obj_is_dict_or_ordereddict(data)) {
amp_error(MOD_STR, "%s param1 type error,param type must be dict\r\n", __func__);
return mp_obj_new_int(-1);
}
mp_obj_t index = mp_obj_new_str_via_qstr("productKey", 10);
productKey = mp_obj_str_get_str(mp_obj_dict_get(data, index));
index = mp_obj_new_str_via_qstr("deviceName", 10);
deviceName = mp_obj_str_get_str(mp_obj_dict_get(data, index));
index = mp_obj_new_str_via_qstr("deviceSecret", 12);
deviceSecret = mp_obj_str_get_str(mp_obj_dict_get(data, index));
index = mp_obj_new_str_via_qstr("keepaliveSec", 12);
keepaliveSec = mp_obj_get_int(mp_obj_dict_get(data, index));
if (mp_obj_dict_len(data) < 5) {
region = "cn-shanghai";
} else {
index = mp_obj_new_str_via_qstr("region", 6);
region = mp_obj_str_get_str(mp_obj_dict_get(data, index));
}
if (region == NULL || productKey == NULL || deviceSecret == NULL || deviceName == NULL) {
amp_error(MOD_STR, "Invalid params, please check it. region=%s productKey=%s deviceName=%s deviceSecret=%s keepaliveSec=%d\r\n", region, productKey, deviceName,
deviceSecret, keepaliveSec);
return mp_obj_new_int(-1);
}
/*
memset(ota_svc->pk, 0, sizeof(ota_svc->pk));
memset(ota_svc->dn, 0, sizeof(ota_svc->dn));
memset(ota_svc->ds, 0, sizeof(ota_svc->ds));
memcpy(ota_svc->pk, productKey, strlen(productKey));
memcpy(ota_svc->dn, deviceName, strlen(deviceName));
memcpy(ota_svc->ds, deviceSecret, strlen(deviceSecret));
*/
aos_kv_set(AMP_CUSTOMER_REGION, region, IOTX_REGION_LEN, 1);
aos_kv_set(AMP_CUSTOMER_PRODUCTKEY, productKey, IOTX_PRODUCT_KEY_LEN, 1);
aos_kv_set(AMP_CUSTOMER_DEVICENAME, deviceName, IOTX_DEVICE_NAME_LEN, 1);
aos_kv_set(AMP_CUSTOMER_DEVICESECRET, deviceSecret, IOTX_DEVICE_SECRET_LEN, 1);
self->iot_gateway_handle->keepaliveSec = keepaliveSec;
res = aos_task_new_ext(&iot_gateway_task, "amp aiot gateway task", aiot_gateway_connect, self->iot_gateway_handle,
1024 * 5, AOS_DEFAULT_APP_PRI);
if (res != STATE_SUCCESS) {
amp_warn(MOD_STR, "iot create task failed\n");
aos_free(iot_gateway_handle);
goto out;
}
return mp_obj_new_int(0);
out:
return mp_obj_new_int(-1);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_gateway_create_gateway, aiot_create_gateway);
/* aiot_gateway_close */
static mp_obj_t aiot_gateway_close(mp_obj_t self_in)
{
int res = -1;
linksdk_gateway_obj_t *self = self_in;
if (self_in == NULL)
return mp_obj_new_int(res);
iot_gateway_handle_t *iot_gateway_handle = self->iot_gateway_handle;
if (iot_gateway_handle->g_iot_conn_flag) {
iot_gateway_handle->g_iot_close_flag = 1;
aos_sem_wait(&iot_gateway_handle->g_iot_close_sem, 8000);
iot_gateway_handle->g_iot_close_flag = 0;
aos_msleep(10);
}
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_1(native_aiot_gateway_close, aiot_gateway_close);
/* publish */
static mp_obj_t aiot_publish(mp_obj_t self_in, mp_obj_t data)
{
int res = -1;
char *topic;
char *payload;
uint16_t payload_len = 0;
uint8_t qos = 0;
linksdk_gateway_obj_t *self = self_in;
if (self_in == NULL) {
mp_raise_OSError(ENOENT);
return mp_obj_new_int(res);
}
if (!mp_obj_is_dict_or_ordereddict(data)) {
amp_error(MOD_STR, "%s data type error,param type must be dict\r\n", __func__);
return mp_obj_new_int(-1);
}
mp_obj_t index = mp_obj_new_str_via_qstr("topic", 5);
topic = mp_obj_str_get_str(mp_obj_dict_get(data, index));
index = mp_obj_new_str_via_qstr("payload", 7);
payload = mp_obj_str_get_str(mp_obj_dict_get(data, index));
payload_len = strlen(payload);
index = mp_obj_new_str_via_qstr("qos", 3);
qos = mp_obj_get_int(mp_obj_dict_get(data, index));
amp_debug(MOD_STR, "publish topic: %s, payload: %s, qos is: %d\r\n", topic, payload, qos);
res = aiot_mqtt_pub(self->iot_gateway_handle->mqtt_handle, topic, payload, payload_len, qos);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "aiot app mqtt publish failed\r\n");
return mp_obj_new_int(res);
}
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_gateway_publish, aiot_publish);
/* unsubscribe */
static mp_obj_t aiot_unsubscribe(mp_obj_t self_in, mp_obj_t data)
{
int res = -1;
char *topic;
uint32_t qos = 0;
linksdk_gateway_obj_t *self = self_in;
if (self_in == NULL) {
mp_raise_OSError(ENOENT);
return mp_obj_new_int(res);
}
if (!mp_obj_is_dict_or_ordereddict(data)) {
amp_error(MOD_STR, "%s data type error,param type must be dict\r\n", __func__);
return mp_obj_new_int(-1);
}
mp_obj_t index = mp_obj_new_str_via_qstr("topic", 5);
topic = mp_obj_str_get_str(mp_obj_dict_get(data, index));
amp_debug(MOD_STR, "unsubscribe topic: %s\r\n", topic);
res = aiot_mqtt_unsub(self->iot_gateway_handle->mqtt_handle, topic);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "aiot app mqtt unsubscribe failed");
return mp_obj_new_int(res);
}
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_gateway_unsubscribe, aiot_unsubscribe);
/* subscribe */
static mp_obj_t aiot_subscribe(mp_obj_t self_in, mp_obj_t data)
{
int res = -1;
char *topic = NULL;
uint32_t qos = 0;
amp_debug(MOD_STR, "native_aiot_subscribe is called\r\n");
linksdk_gateway_obj_t *self = self_in;
if (self_in == NULL) {
mp_raise_OSError(ENOENT);
return mp_obj_new_int(res);
}
if (!mp_obj_is_dict_or_ordereddict(data)) {
amp_error(MOD_STR, "%s data type error,param type must be dict\r\n", __func__);
return mp_obj_new_int(-1);
}
mp_obj_t index = mp_obj_new_str_via_qstr("topic", 5);
topic = mp_obj_str_get_str(mp_obj_dict_get(data, index));
index = mp_obj_new_str_via_qstr("qos", 3);
qos = mp_obj_get_int(mp_obj_dict_get(data, index));
amp_debug(MOD_STR, "subscribe topic: %s, qos is: %d", topic, qos);
res = aiot_mqtt_sub(self->iot_gateway_handle->mqtt_handle, topic, subcribe_cb, (uint8_t)qos,
self->iot_gateway_handle);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "aiot app mqtt subscribe failed\n");
return mp_obj_new_int(res);
} else {
amp_info(MOD_STR, "subcribe topic: %s succeed\r\n", topic);
}
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_gateway_subscribe, aiot_subscribe);
static mp_obj_t aiot_topo_common(mp_obj_t self_in, mp_obj_t data, gateway_funcode_t funcode)
{
int res = -1;
int i;
const char *productKey;
const char *productSecret;
const char *deviceName;
const char *deviceSecret;
size_t subdev_num;
mp_obj_t *subdev_items = NULL;
aiot_subdev_dev_t *subdev;
int subdev_length = 0;
mp_obj_dict_t *dict_self;
mp_map_elem_t *elem;
linksdk_gateway_obj_t *self = self_in;
if (self_in == NULL) {
mp_raise_OSError(ENOENT);
return mp_obj_new_int(res);
}
mp_obj_list_get(data, &subdev_num, &subdev_items);
if (subdev_items == 0) {
return mp_obj_new_int(-1);
}
subdev_length = subdev_num;
subdev = aos_malloc(subdev_length * sizeof(aiot_subdev_dev_t));
if (subdev == NULL) {
amp_debug(MOD_STR, "sub device malloc failed\r\n");
goto out;
}
memset(subdev, 0, subdev_length * sizeof(aiot_subdev_dev_t));
for (i = 0; i < subdev_num; i++) {
mp_obj_t index = mp_obj_new_str_via_qstr("productKey", 10);
dict_self = MP_OBJ_TO_PTR(subdev_items[i]);
elem = mp_map_lookup(&dict_self->map, index, MP_MAP_LOOKUP);
if (elem != NULL) {
productKey = mp_obj_str_get_str(mp_obj_dict_get(subdev_items[i], index));
subdev[i].product_key = __amp_strdup(productKey);
}
index = mp_obj_new_str_via_qstr("deviceName", 10);
dict_self = MP_OBJ_TO_PTR(subdev_items[i]);
elem = mp_map_lookup(&dict_self->map, index, MP_MAP_LOOKUP);
if (elem != NULL) {
deviceName = mp_obj_str_get_str(mp_obj_dict_get(subdev_items[i], index));
subdev[i].device_name = __amp_strdup(deviceName);
}
index = mp_obj_new_str_via_qstr("deviceSecret", 12);
dict_self = MP_OBJ_TO_PTR(subdev_items[i]);
elem = mp_map_lookup(&dict_self->map, index, MP_MAP_LOOKUP);
if (elem != NULL) {
deviceSecret = mp_obj_str_get_str(mp_obj_dict_get(subdev_items[i], index));
subdev[i].device_secret = __amp_strdup(deviceSecret);
}
index = mp_obj_new_str_via_qstr("productSecret", 13);
dict_self = MP_OBJ_TO_PTR(subdev_items[i]);
elem = mp_map_lookup(&dict_self->map, index, MP_MAP_LOOKUP);
if (elem != NULL) {
productSecret = mp_obj_str_get_str(mp_obj_dict_get(subdev_items[i], index));
subdev[i].product_secret = __amp_strdup(productSecret);
}
}
switch (funcode) {
case GATEWAY_TOPO_ADD:
res = aiot_subdev_send_topo_add(self->iot_gateway_handle->subdev_handle, subdev, subdev_length);
break;
case GATEWAY_TOPO_DEL:
res = aiot_subdev_send_topo_delete(self->iot_gateway_handle->subdev_handle, subdev, subdev_length);
break;
case GATEWAY_SUBDEV_LOGIN:
res = aiot_subdev_send_batch_login(self->iot_gateway_handle->subdev_handle, subdev, subdev_length);
break;
case GATEWAY_SUBDEV_LOGOUT:
res = aiot_subdev_send_batch_logout(self->iot_gateway_handle->subdev_handle, subdev, subdev_length);
break;
case GATEWAY_SUBDEV_REGISTER:
res = aiot_subdev_send_sub_register(self->iot_gateway_handle->subdev_handle, subdev, subdev_length);
break;
}
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "aiot app mqtt publish failed ret = %d.\r\n", res);
goto out;
}
out:
if (subdev) {
for (i = 0; i < subdev_length; i++) {
if (subdev[i].product_key) {
aos_free(subdev[i].product_key);
}
if (subdev[i].device_name) {
aos_free(subdev[i].device_name);
}
if (subdev[i].device_secret) {
aos_free(subdev[i].device_secret);
}
if (subdev[i].product_secret) {
aos_free(subdev[i].product_secret);
}
}
aos_free(subdev);
}
return mp_obj_new_int(res);
}
/* addTopo */
static mp_obj_t aiot_addTopo(mp_obj_t self_in, mp_obj_t data)
{
return aiot_topo_common(self_in, data, GATEWAY_TOPO_ADD);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_gateway_add_topo, aiot_addTopo);
/* removeTopo */
static mp_obj_t aiot_removeTopo(mp_obj_t self_in, mp_obj_t data)
{
return aiot_topo_common(self_in, data, GATEWAY_TOPO_DEL);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_gateway_removeTopo, aiot_removeTopo);
/* login */
static mp_obj_t aiot_login(mp_obj_t self_in, mp_obj_t data)
{
return aiot_topo_common(self_in, data, GATEWAY_SUBDEV_LOGIN);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_gateway_login, aiot_login);
/* logout */
static mp_obj_t aiot_logout(mp_obj_t self_in, mp_obj_t data)
{
return aiot_topo_common(self_in, data, GATEWAY_SUBDEV_LOGOUT);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_gateway_logout, aiot_logout);
/* registerSubDevice */
static mp_obj_t aiot_registerSubDevice(mp_obj_t self_in, mp_obj_t data)
{
return aiot_topo_common(self_in, data, GATEWAY_SUBDEV_REGISTER);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_gateway_register_subDevice, aiot_registerSubDevice);
/* getTop */
static mp_obj_t aiot_getTop(mp_obj_t self_in)
{
int res = -1;
linksdk_gateway_obj_t *self = self_in;
if (self_in == NULL) {
mp_raise_OSError(ENOENT);
return mp_obj_new_int(res);
}
res = aiot_subdev_send_topo_get(self->iot_gateway_handle->subdev_handle);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "aiot get top failed\r\n");
return mp_obj_new_int(res);
}
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_1(native_gateway_get_topo, aiot_getTop);
STATIC mp_obj_t aiot_register_cb(mp_obj_t self_in, mp_obj_t id, mp_obj_t func)
{
int callback_id = mp_obj_get_int(id);
linksdk_gateway_obj_t *self = self_in;
if (self_in == NULL) {
return mp_obj_new_int(-1);
}
if (self->iot_gateway_handle->callback == NULL) {
return mp_obj_new_int(-1);
}
self->iot_gateway_handle->callback[callback_id] = func;
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_3(native_gateway_register_cb, aiot_register_cb);
static mp_obj_t get_gateway_handle(mp_obj_t self_in)
{
linksdk_gateway_obj_t *self = self_in;
if (self_in == NULL) {
goto out;
}
iot_gateway_handle_t *iot_gateway_handle = self->iot_gateway_handle;
if (!iot_gateway_handle) {
amp_warn(MOD_STR, "parameter must be handle\r\n");
goto out;
} else {
return mp_obj_new_int((mp_int_t)iot_gateway_handle);
}
out:
return mp_obj_new_int((mp_int_t)0);
}
MP_DEFINE_CONST_FUN_OBJ_1(native_gateway_get_gateway_handle, get_gateway_handle);
/* get gateway info */
static mp_obj_t aiot_getGatewayInfo(mp_obj_t self_in)
{
int res = -1;
if (self_in == NULL) {
goto out;
}
/* get device tripple info */
char region[IOTX_REGION_LEN + 1] = {0};
char productKey[IOTX_PRODUCT_KEY_LEN + 1] = { 0 };
char productSecret[IOTX_PRODUCT_SECRET_LEN + 1] = { 0 };
char deviceName[IOTX_DEVICE_NAME_LEN + 1] = { 0 };
char deviceSecret[IOTX_DEVICE_SECRET_LEN + 1] = { 0 };
int regionLen = IOTX_REGION_LEN;
int productKeyLen = IOTX_PRODUCT_KEY_LEN;
int productSecretLen = IOTX_PRODUCT_SECRET_LEN;
int deviceNameLen = IOTX_DEVICE_NAME_LEN;
int deviceSecretLen = IOTX_DEVICE_SECRET_LEN;
aos_kv_get(AMP_CUSTOMER_REGION, region, ®ionLen);
aos_kv_get(AMP_CUSTOMER_PRODUCTKEY, productKey, &productKeyLen);
aos_kv_get(AMP_CUSTOMER_PRODUCTSECRET, productSecret, &productSecretLen);
aos_kv_get(AMP_CUSTOMER_DEVICENAME, deviceName, &deviceNameLen);
aos_kv_get(AMP_CUSTOMER_DEVICESECRET, deviceSecret, &deviceSecretLen);
// dict solution
mp_obj_t aiot_gatewayinfo_dict = mp_obj_new_dict(5);
mp_obj_dict_store(aiot_gatewayinfo_dict, MP_OBJ_NEW_QSTR(qstr_from_str("region")),
mp_obj_new_str(region, strlen(region)));
mp_obj_dict_store(aiot_gatewayinfo_dict, MP_OBJ_NEW_QSTR(qstr_from_str("productKey")),
mp_obj_new_str(productKey, strlen(productKey)));
mp_obj_dict_store(aiot_gatewayinfo_dict, MP_OBJ_NEW_QSTR(qstr_from_str("productSecret")),
mp_obj_new_str(productSecret, strlen(productSecret)));
mp_obj_dict_store(aiot_gatewayinfo_dict, MP_OBJ_NEW_QSTR(qstr_from_str("deviceName")),
mp_obj_new_str(deviceName, strlen(deviceName)));
mp_obj_dict_store(aiot_gatewayinfo_dict, MP_OBJ_NEW_QSTR(qstr_from_str("deviceSecret")),
mp_obj_new_str(deviceSecret, strlen(deviceSecret)));
return aiot_gatewayinfo_dict;
out:
return mp_obj_new_int((mp_int_t)0);
}
MP_DEFINE_CONST_FUN_OBJ_1(native_aiot_getGatewayInfo, aiot_getGatewayInfo);
/* dynmic register */
static mp_obj_t hapy_get_ntp_time(mp_obj_t self_in, mp_obj_t cb)
{
int res = -1;
linksdk_gateway_obj_t *self = self_in;
if (self_in == NULL) {
return mp_obj_new_int(-1);
}
iot_gateway_handle_t *iot_gateway_handle = self->iot_gateway_handle;
if (!iot_gateway_handle) {
amp_warn(MOD_STR, "parameter must be handle\r\n");
return mp_obj_new_int(-1);
}
res = hapy_aiot_amp_ntp_service(iot_gateway_handle->mqtt_handle, cb);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "python get ntp time failed\r\n");
return mp_obj_new_int(res);
}
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_gateway_get_ntp_time, hapy_get_ntp_time);
/* upload File */
static mp_obj_t gateway_aiot_uploadFile(size_t n_args, const mp_obj_t *args)
{
int ret = -1;
char *upload_id = NULL;
linksdk_gateway_obj_t *self = (linksdk_gateway_obj_t *)MP_OBJ_TO_PTR(args[0]);
mp_obj_t remoteFileName = args[1];
mp_obj_t localFilePath = args[2];
mp_obj_t cb = args[3];
mp_buffer_info_t bufinfo;
iot_gateway_handle_t *iot_gateway_handle = self->iot_gateway_handle;
if (!iot_gateway_handle) {
amp_error(MOD_STR, "parameter must be handle\r\n");
goto out;
}
char *filename = (char *)mp_obj_str_get_str(remoteFileName);
char *filepath = (char *)mp_obj_str_get_str(localFilePath);
MP_THREAD_GIL_EXIT();
upload_id = pyamp_aiot_upload_mqtt(iot_gateway_handle->mqtt_handle, filename, filepath, 0, cb);
MP_THREAD_GIL_ENTER();
if (!upload_id) {
amp_error(MOD_STR, "aiot upload file failed!\r\n");
goto out;
}
return mp_obj_new_str(upload_id, strlen(upload_id));
out:
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(native_gateway_aiot_uploadFile, 3, gateway_aiot_uploadFile);
/* upload Content */
static mp_obj_t gateway_aiot_uploadContent(size_t n_args, const mp_obj_t *args)
{
int ret = -1;
char *upload_id = NULL;
linksdk_gateway_obj_t *self = (linksdk_gateway_obj_t *)MP_OBJ_TO_PTR(args[0]);
mp_obj_t file_name = args[1];
mp_obj_t data = args[2];
mp_obj_t cb = args[3];
mp_buffer_info_t bufinfo;
iot_gateway_handle_t *iot_gateway_handle = self->iot_gateway_handle;
if (!iot_gateway_handle) {
amp_error(MOD_STR, "parameter must be handle\r\n");
goto out;
}
char *filename = (char *)mp_obj_str_get_str(file_name);
mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ);
MP_THREAD_GIL_EXIT();
upload_id = pyamp_aiot_upload_mqtt(iot_gateway_handle->mqtt_handle, filename, bufinfo.buf, bufinfo.len, cb);
MP_THREAD_GIL_ENTER();
if (!upload_id) {
amp_error(MOD_STR, "aiot upload content failed!\r\n");
goto out;
}
return mp_obj_new_str(upload_id, strlen(upload_id));
out:
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(native_gateway_aiot_uploadContent, 3, gateway_aiot_uploadContent);
STATIC const mp_rom_map_elem_t linkkit_gateway_locals_dict_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR_on), MP_ROM_PTR(&native_gateway_register_cb) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_connect), MP_ROM_PTR(&native_gateway_create_gateway) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_getGatewayHandle), MP_ROM_PTR(&native_gateway_get_gateway_handle) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_getGatewayInfo), MP_ROM_PTR(&native_aiot_getGatewayInfo) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_uploadFile), MP_ROM_PTR(&native_gateway_aiot_uploadFile) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_uploadContent), MP_ROM_PTR(&native_gateway_aiot_uploadContent) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_subscribe), MP_ROM_PTR(&native_gateway_subscribe) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_unsubscribe), MP_ROM_PTR(&native_gateway_unsubscribe) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_publish), MP_ROM_PTR(&native_gateway_publish) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_getNtpTime), MP_ROM_PTR(&native_gateway_get_ntp_time) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_addTopo), MP_ROM_PTR(&native_gateway_add_topo) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_getTopo), MP_ROM_PTR(&native_gateway_get_topo) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_removeTopo), MP_ROM_PTR(&native_gateway_removeTopo) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_login), MP_ROM_PTR(&native_gateway_login) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_logout), MP_ROM_PTR(&native_gateway_logout) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_registerSubDevice), MP_ROM_PTR(&native_gateway_register_subDevice) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_end), MP_ROM_PTR(&native_aiot_gateway_close) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ON_CONNECT), MP_ROM_INT(ON_CONNECT) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ON_DISCONNECT), MP_ROM_INT(ON_DISCONNECT) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ON_CLOSE), MP_ROM_INT(ON_CLOSE) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ON_SUBCRIBE), MP_ROM_INT(ON_SUBCRIBE) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ON_LOGIN), MP_ROM_INT(ON_LOGIN) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ON_LOGOUT), MP_ROM_INT(ON_LOGOUT) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ON_TOPOADD), MP_ROM_INT(ON_TOPOADD) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ON_TOPOGET), MP_ROM_INT(ON_TOPOGET) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ON_TOPOREMOVE), MP_ROM_INT(ON_TOPOREMOVE) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ON_SUBREGISTER), MP_ROM_INT(ON_SUBREGISTER) },
};
STATIC MP_DEFINE_CONST_DICT(linksdk_gateway_locals_dict, linkkit_gateway_locals_dict_table);
STATIC void linksdk_gateway_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind)
{
linksdk_gateway_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "aiot_gateway");
}
STATIC mp_obj_t linksdk_gateway_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args)
{
linksdk_gateway_obj_t *gateway_obj = m_new_obj(linksdk_gateway_obj_t);
if (!gateway_obj) {
mp_raise_OSError(MP_EINVAL);
return mp_const_none;
}
memset(gateway_obj, 0, sizeof(linksdk_gateway_obj_t));
iot_gateway_handle_t *iot_gateway_handle = m_new_obj(iot_gateway_handle_t);
if (!iot_gateway_handle) {
mp_raise_OSError(MP_EINVAL);
return mp_const_none;
}
memset(iot_gateway_handle, 0, sizeof(iot_gateway_handle_t));
iot_gateway_handle->callback = m_new(mp_obj_t, ON_CB_MAX);
aos_sem_new(&iot_gateway_handle->g_iot_connect_sem, 0);
aos_sem_new(&iot_gateway_handle->g_iot_close_sem, 0);
gateway_obj->iot_gateway_handle = iot_gateway_handle;
gateway_obj->base.type = &linksdk_gateway_type;
return MP_OBJ_FROM_PTR(gateway_obj);
}
const mp_obj_type_t linksdk_gateway_type = {
{ &mp_type_type },
.name = MP_QSTR_Gateway,
.print = linksdk_gateway_print,
.make_new = linksdk_gateway_make_new,
.locals_dict = (mp_obj_t)&linksdk_gateway_locals_dict,
};
| YifuLiu/AliOS-Things | components/py_engine/modules/aliyunIoT/module_aiot_gateway.c | C | apache-2.0 | 37,701 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include "aiot_dm_api.h"
#include "aiot_mqtt_api.h"
#include "aiot_state_api.h"
#include "aiot_subdev_api.h"
#include "aiot_sysdep_api.h"
#ifdef AOS_COMP_KV
#include "aos/kv.h"
#endif
#include "py_defines.h"
// #include "be_inl.h"
#include "module_aiot.h"
#ifdef AOS_COMP_UAGENT
#include "uagent.h"
#endif
#define MOD_STR "AIOT_MQTT"
/* 位于portfiles/aiot_port文件夹下的系统适配函数集合 */
extern aiot_sysdep_portfile_t g_aiot_sysdep_portfile;
/* 位于external/ali_ca_cert.c中的服务器证书 */
extern const char *ali_ca_cert;
uint8_t pyamp_g_app_mqtt_process_thread_running = 0;
uint8_t pyamp_g_app_mqtt_recv_thread_running = 0;
uint8_t pyamp_g_app_mqtt_process_thread_exit = 0;
uint8_t pyamp_g_app_mqtt_recv_thread_exit = 0;
static char *__amp_strdup(char *src, int len)
{
char *dst;
if (src == NULL) {
return NULL;
}
dst = aos_malloc(len + 1);
if (dst == NULL) {
return NULL;
}
memcpy(dst, src, len);
dst[len] = '\0';
return dst;
}
/* 执行aiot_mqtt_process的线程, 包含心跳发送和QoS1消息重发 */
void pyamp_aiot_app_mqtt_process_thread(void *args)
{
int32_t res = STATE_SUCCESS;
pyamp_g_app_mqtt_process_thread_exit = 0;
while (pyamp_g_app_mqtt_process_thread_running) {
res = aiot_mqtt_process(args);
if (res == STATE_USER_INPUT_EXEC_DISABLED) {
break;
}
aos_msleep(1000);
}
pyamp_g_app_mqtt_process_thread_exit = 1;
aos_task_exit(0);
return;
}
/* 执行aiot_mqtt_recv的线程, 包含网络自动重连和从服务器收取MQTT消息 */
void pyamp_aiot_app_mqtt_recv_thread(void *args)
{
int32_t res = STATE_SUCCESS;
pyamp_g_app_mqtt_recv_thread_exit = 0;
while (pyamp_g_app_mqtt_recv_thread_running) {
res = aiot_mqtt_recv(args);
if (res < STATE_SUCCESS) {
if (res == STATE_USER_INPUT_EXEC_DISABLED) {
break;
}
aos_msleep(1000);
}
}
pyamp_g_app_mqtt_recv_thread_exit = 1;
aos_task_exit(0);
return;
}
/* MQTT默认消息处理回调, 当SDK从服务器收到MQTT消息时,
* 且无对应用户回调处理时被调用 */
void pyamp_aiot_app_mqtt_recv_handler(void *handle, const aiot_mqtt_recv_t *packet, void *userdata)
{
iot_mqtt_userdata_t *udata = (iot_mqtt_userdata_t *)userdata;
if (!udata || !udata->callback) {
amp_error(MOD_STR, "mqtt_recv_handler userdata is null! recv type is %d!", packet->type);
return;
}
switch (packet->type) {
case AIOT_MQTTRECV_HEARTBEAT_RESPONSE: {
// amp_debug(MOD_STR, "heartbeat response");
/* TODO: 处理服务器对心跳的回应, 一般不处理 */
}
break;
case AIOT_MQTTRECV_SUB_ACK: {
amp_debug(MOD_STR, "suback, res: -0x%04X, packet id: %d, max qos: %d",
-packet->data.sub_ack.res, packet->data.sub_ack.packet_id, packet->data.sub_ack.max_qos);
/* TODO: 处理服务器对订阅请求的回应, 一般不处理 */
}
break;
case AIOT_MQTTRECV_UNSUB_ACK: {
amp_debug(MOD_STR, "unsuback, packet id: %d", packet->data.unsub_ack.packet_id);
/* 处理服务器对取消订阅请求的回应, 一般不处理 */
}
break;
case AIOT_MQTTRECV_PUB: {
amp_debug(MOD_STR, "pub, qos: %d, topic: %.*s", packet->data.pub.qos, packet->data.pub.topic_len, packet->data.pub.topic);
amp_debug(MOD_STR, "pub, payload: %.*s", packet->data.pub.payload_len, packet->data.pub.payload);
/* TODO: 处理服务器下发的业务报文 */
iot_mqtt_message_t message;
memset(&message, 0, sizeof(iot_mqtt_message_t));
if (udata && udata->callback) {
message.option = AIOT_MQTTOPT_RECV_HANDLER;
message.recv.type = packet->type;
message.recv.code = AIOT_MQTT_MESSAGE;
message.recv.topic = __amp_strdup(packet->data.pub.topic, packet->data.pub.topic_len);
message.recv.payload = __amp_strdup(packet->data.pub.payload, packet->data.pub.payload_len);
message.recv.topic_len = packet->data.pub.topic_len;
message.recv.payload_len = packet->data.pub.payload_len;
udata->callback(&message, udata);
aos_free(message.recv.topic);
aos_free(message.recv.payload);
}
}
break;
case AIOT_MQTTRECV_PUB_ACK: {
amp_debug(MOD_STR, "recv puback, packet id: %d\r\n", packet->data.pub_ack.packet_id);
/* TODO: 处理服务器对QoS1上报消息的回应, 一般不处理 */
}
break;
default:
break;
}
}
/* MQTT事件回调函数, 当网络连接/重连/断开时被触发,
* 事件定义见core/aiot_mqtt_api.h */
void pyamp_aiot_app_mqtt_event_handler(void *handle, const aiot_mqtt_event_t *event, void *userdata)
{
iot_mqtt_userdata_t *udata = (iot_mqtt_userdata_t *)userdata;
iot_mqtt_message_t message;
memset(&message, 0, sizeof(iot_mqtt_message_t));
message.option = AIOT_MQTTOPT_EVENT_HANDLER;
message.event.type = event->type;
switch (event->type) {
/* SDK因为用户调用了aiot_mqtt_connect()接口, 与mqtt服务器建立连接已成功
*/
case AIOT_MQTTEVT_CONNECT:
{
amp_debug(MOD_STR, "AIOT_MQTTEVT_CONNECT\r\n");
/* TODO: 处理SDK建连成功, 不可以在这里调用耗时较长的阻塞函数 */
message.event.code = AIOT_MQTT_CONNECT;
}
break;
/* SDK因为网络状况被动断连后, 自动发起重连已成功 */
case AIOT_MQTTEVT_RECONNECT:
{
amp_debug(MOD_STR, "AIOT_MQTTEVT_RECONNECT\r\n");
/* TODO: 处理SDK重连成功, 不可以在这里调用耗时较长的阻塞函数 */
message.event.code = AIOT_MQTT_RECONNECT;
}
break;
/* SDK因为网络的状况而被动断开了连接, network是底层读写失败,
* heartbeat是没有按预期得到服务端心跳应答 */
case AIOT_MQTTEVT_DISCONNECT:
{
char *cause = (event->data.disconnect == AIOT_MQTTDISCONNEVT_NETWORK_DISCONNECT) ? ("network disconnect")
: ("heartbeat disconnect");
amp_debug(MOD_STR, "AIOT_MQTTEVT_DISCONNECT: %s\r\n", cause);
/* TODO: 处理SDK被动断连, 不可以在这里调用耗时较长的阻塞函数 */
message.event.code = AIOT_MQTT_DISCONNECT;
}
break;
default:
{
return;
}
}
if (udata && udata->callback)
udata->callback(&message, udata);
}
/* rawdata 函数演示 */
int32_t aiot_app_send_rawdata_post(void *dm_handle, char *data, int32_t data_len)
{
aiot_dm_msg_t msg;
memset(&msg, 0, sizeof(aiot_dm_msg_t));
msg.type = AIOT_DMMSG_RAW_DATA;
msg.data.raw_data.data = data;
msg.data.raw_data.data_len = data_len;
return aiot_dm_send(dm_handle, &msg);
}
/* 属性上报函数演示 */
int32_t pyamp_aiot_app_send_property_post(void *dm_handle, char *params)
{
aiot_dm_msg_t msg;
memset(&msg, 0, sizeof(aiot_dm_msg_t));
msg.type = AIOT_DMMSG_PROPERTY_POST;
msg.data.property_post.params = params;
return aiot_dm_send(dm_handle, &msg);
}
/* 事件上报函数演示 */
int32_t pyamp_aiot_app_send_event_post(void *dm_handle, char *event_id, char *params)
{
aiot_dm_msg_t msg;
memset(&msg, 0, sizeof(aiot_dm_msg_t));
msg.type = AIOT_DMMSG_EVENT_POST;
msg.data.event_post.event_id = event_id;
msg.data.event_post.params = params;
return aiot_dm_send(dm_handle, &msg);
}
int32_t pyamp_aiot_mqtt_client_start(void **handle, int keepaliveSec, iot_mqtt_userdata_t *userdata)
{
int32_t res = STATE_SUCCESS;
void *mqtt_handle = NULL;
char host[100] = { 0 }; /* 用这个数组拼接设备连接的云平台站点全地址, 规则是
${YourProductKey}.iot-as-mqtt.${YourRegionId}.aliyuncs.com" */
uint16_t port = 443; /* 无论设备是否使用TLS连接阿里云平台, 目的端口都是443 */
aiot_sysdep_network_cred_t cred; /* 安全凭据结构体, 如果要用TLS, 这个结构体中配置CA证书等参数 */
/* get device tripple info */
char region[IOTX_REGION_LEN + 1] = { 0 };
char product_key[IOTX_PRODUCT_KEY_LEN + 1] = { 0 };
char device_name[IOTX_DEVICE_NAME_LEN + 1] = { 0 };
char device_secret[IOTX_DEVICE_SECRET_LEN + 1] = { 0 };
int region_len = IOTX_REGION_LEN;
int productkey_len = IOTX_PRODUCT_KEY_LEN;
int devicename_len = IOTX_DEVICE_NAME_LEN;
int devicesecret_len = IOTX_DEVICE_SECRET_LEN;
aos_kv_get(AMP_CUSTOMER_REGION, region, ®ion_len);
aos_kv_get(AMP_CUSTOMER_PRODUCTKEY, product_key, &productkey_len);
aos_kv_get(AMP_CUSTOMER_DEVICENAME, device_name, &devicename_len);
aos_kv_get(AMP_CUSTOMER_DEVICESECRET, device_secret, &devicesecret_len);
/* end get device tripple info */
/* 配置SDK的底层依赖 */
aiot_sysdep_set_portfile(&g_aiot_sysdep_portfile);
/* 配置SDK的日志输出 */
// aiot_state_set_logcb(demo_state_logcb);
/* 创建SDK的安全凭据, 用于建立TLS连接 */
memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t));
cred.option = AIOT_SYSDEP_NETWORK_CRED_SVRCERT_CA; /* 使用RSA证书校验MQTT服务端 */
cred.max_tls_fragment = 16384; /* 最大的分片长度为16K, 其它可选值还有4K, 2K, 1K, 0.5K */
cred.sni_enabled = 1; /* TLS建连时, 支持Server Name Indicator */
cred.x509_server_cert = ali_ca_cert; /* 用来验证MQTT服务端的RSA根证书 */
cred.x509_server_cert_len = strlen(ali_ca_cert); /* 用来验证MQTT服务端的RSA根证书长度 */
/* 创建1个MQTT客户端实例并内部初始化默认参数 */
mqtt_handle = aiot_mqtt_init();
if (mqtt_handle == NULL) {
amp_debug(MOD_STR, "aiot_mqtt_init failed\r\n");
aos_free(mqtt_handle);
return -1;
}
*handle = mqtt_handle;
/* TODO: 如果以下代码不被注释, 则例程会用TCP而不是TLS连接云平台 */
{
memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t));
cred.option = AIOT_SYSDEP_NETWORK_CRED_NONE;
}
sprintf(host, "%s.iot-as-mqtt.%s.aliyuncs.com", product_key, region);
/* 配置MQTT服务器地址 */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_HOST, (void *)host);
/* 配置MQTT服务器端口 */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PORT, (void *)&port);
/* 配置设备productKey */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PRODUCT_KEY, (void *)product_key);
/* 配置设备deviceName */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_NAME, (void *)device_name);
/* 配置设备deviceSecret */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_SECRET, (void *)device_secret);
/* 配置网络连接的安全凭据, 上面已经创建好了 */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_NETWORK_CRED, (void *)&cred);
/* 配置MQTT心跳间隔 */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_KEEPALIVE_SEC, (void *)&keepaliveSec);
/* 配置回调参数 */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_USERDATA, userdata);
/* 配置MQTT默认消息接收回调函数 */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_RECV_HANDLER, (void *)pyamp_aiot_app_mqtt_recv_handler);
/* 配置MQTT事件回调函数 */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_EVENT_HANDLER, (void *)pyamp_aiot_app_mqtt_event_handler);
/* 与服务器建立MQTT连接 */
res = aiot_mqtt_connect(mqtt_handle);
if (res < STATE_SUCCESS) {
/* 尝试建立连接失败, 销毁MQTT实例, 回收资源 */
aiot_mqtt_deinit(&mqtt_handle);
amp_debug(MOD_STR, "aiot_mqtt_connect failed: -0x%04X\r\n", -res);
aos_task_exit(0);
return -1;
}
/* 创建一个单独的线程, 专用于执行aiot_mqtt_process, 它会自动发送心跳保活,
* 以及重发QoS1的未应答报文 */
pyamp_g_app_mqtt_process_thread_running = 1;
aos_task_t mqtt_process_task;
if (aos_task_new_ext(&mqtt_process_task, "mqtt_process", pyamp_aiot_app_mqtt_process_thread, mqtt_handle, (1024 * 2 + 512),
AOS_DEFAULT_APP_PRI) != 0) {
amp_debug(MOD_STR, "management mqtt process task create failed!\r\n");
aiot_mqtt_deinit(&mqtt_handle);
aos_task_exit(0);
return -1;
}
amp_debug(MOD_STR, "app mqtt process start\r\n");
/* 创建一个单独的线程用于执行aiot_mqtt_recv,
* 它会循环收取服务器下发的MQTT消息, 并在断线时自动重连 */
pyamp_g_app_mqtt_recv_thread_running = 1;
aos_task_t mqtt_rec_task;
if (aos_task_new_ext(&mqtt_rec_task, "mqtt_rec", pyamp_aiot_app_mqtt_recv_thread, mqtt_handle, 1024 * 4,
AOS_DEFAULT_APP_PRI) != 0) {
amp_debug(MOD_STR, "management mqtt rec task create failed!\r\n");
aiot_mqtt_deinit(&mqtt_handle);
aos_task_exit(0);
return -1;
}
amp_debug(MOD_STR, "app mqtt rec start\r\n");
#ifdef AOS_COMP_UAGENT
res = uagent_mqtt_client_set(mqtt_handle);
if (res != 0) {
amp_debug(MOD_STR, "uAgent mqtt handle set failed ret = %d\n", res);
}
res = uagent_ext_comm_start(product_key, device_name);
if (res != 0) {
amp_debug(MOD_STR, "uAgent ext comm start failed ret = %d\n", res);
}
#endif
return STATE_SUCCESS;
}
/* mqtt stop */
int32_t pyamp_aiot_mqtt_client_stop(void **handle)
{
int32_t res = STATE_SUCCESS;
void *mqtt_handle = NULL;
int cnt = 30;
mqtt_handle = *handle;
pyamp_g_app_mqtt_process_thread_running = 0;
pyamp_g_app_mqtt_recv_thread_running = 0;
while (cnt-- > 0) {
if (pyamp_g_app_mqtt_recv_thread_exit && pyamp_g_app_mqtt_process_thread_exit)
break;
aos_msleep(200);
}
/* 断开MQTT连接 */
res = aiot_mqtt_disconnect(mqtt_handle);
if (res < STATE_SUCCESS) {
aiot_mqtt_deinit(&mqtt_handle);
amp_debug(MOD_STR, "aiot_mqtt_disconnect failed: -0x%04X\r\n", -res);
return -1;
}
/* 销毁MQTT实例 */
res = aiot_mqtt_deinit(&mqtt_handle);
if (res < STATE_SUCCESS) {
amp_debug(MOD_STR, "aiot_mqtt_deinit failed: -0x%04X\r\n", -res);
return -1;
}
return res;
}
| YifuLiu/AliOS-Things | components/py_engine/modules/aliyunIoT/module_aiot_mqtt.c | C | apache-2.0 | 14,609 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include "aiot_mqtt_api.h"
#include "aiot_ntp_api.h"
#include "aiot_state_api.h"
#include "aiot_sysdep_api.h"
#include "module_aiot.h"
#include "py/runtime.h"
#include "py_defines.h"
#define MOD_STR "AIOT_NTP"
/* ntp timestamp */
// extern int64_t pyamp_g_ntp_time;
// extern int64_t pyamp_g_up_time;
typedef struct {
mp_obj_t cb;
uint32_t year;
uint32_t month;
uint32_t day;
uint32_t hour;
uint32_t minute;
uint32_t second;
uint32_t msecond;
uint64_t timestamp;
} hapy_aiot_ntp_notify_param_t;
static void aiot_device_ntp_notify(void *pdata)
{
hapy_aiot_ntp_notify_param_t *param = (hapy_aiot_ntp_notify_param_t *)pdata;
mp_sched_carg_t *carg = make_cargs(MP_SCHED_CTYPE_DICT);
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_INT, param->year, NULL, "year");
make_carg_entry(carg, 1, MP_SCHED_ENTRY_TYPE_INT, param->month, NULL, "month");
make_carg_entry(carg, 2, MP_SCHED_ENTRY_TYPE_INT, param->day, NULL, "day");
make_carg_entry(carg, 3, MP_SCHED_ENTRY_TYPE_INT, param->hour, NULL, "hour");
make_carg_entry(carg, 4, MP_SCHED_ENTRY_TYPE_INT, param->minute, NULL, "minute");
make_carg_entry(carg, 5, MP_SCHED_ENTRY_TYPE_INT, param->second, NULL, "second");
make_carg_entry(carg, 6, MP_SCHED_ENTRY_TYPE_INT, param->msecond, NULL, "msecond");
make_carg_entry(carg, 7, MP_SCHED_ENTRY_TYPE_INT, param->timestamp / 1000, NULL, "timestamp");
callback_to_python_LoBo(param->cb, mp_const_none, carg);
aos_free(param);
}
static void aiot_app_ntp_recv_handler(void *handle, const aiot_ntp_recv_t *packet, void *userdata)
{
int res = -1;
hapy_aiot_ntp_notify_param_t *ntp_params = NULL;
switch (packet->type) {
case AIOT_NTPRECV_LOCAL_TIME:
/* print topic name and topic message */
amp_debug(MOD_STR,
"year: %d, month: %d, day: %d, hour: %d, min: %d, sec: %d, "
"msec: %d, timestamp: %d",
packet->data.local_time.year, packet->data.local_time.mon, packet->data.local_time.day,
packet->data.local_time.hour, packet->data.local_time.min, packet->data.local_time.sec,
packet->data.local_time.msec, packet->data.local_time.timestamp);
// pyamp_g_ntp_time = packet->data.local_time.timestamp;
// pyamp_g_up_time = aos_now_ms();
ntp_params = (hapy_aiot_ntp_notify_param_t *)userdata;
ntp_params->year = packet->data.local_time.year;
ntp_params->month = packet->data.local_time.mon;
ntp_params->day = packet->data.local_time.day;
ntp_params->hour = packet->data.local_time.hour;
ntp_params->minute = packet->data.local_time.min;
ntp_params->second = packet->data.local_time.sec;
ntp_params->msecond = packet->data.local_time.msec;
ntp_params->timestamp = packet->data.local_time.timestamp;
break;
default:
if (ntp_params != NULL) {
aos_free(ntp_params);
}
return;
}
py_task_schedule_call(aiot_device_ntp_notify, ntp_params);
res = aiot_ntp_deinit(&handle);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "ntp deinit failed");
}
}
static void aiot_app_ntp_event_handler(void *handle, const aiot_ntp_event_t *event, void *userdata)
{
switch (event->type) {
case AIOT_NTPEVT_INVALID_RESPONSE:
/* print topic name and topic message */
amp_debug(MOD_STR, "ntp receive data invalid");
break;
case AIOT_NTPEVT_INVALID_TIME_FORMAT:
amp_debug(MOD_STR, "ntp receive data error");
break;
default:
break;
}
}
/* ntp service */
int32_t hapy_aiot_amp_ntp_service(void *mqtt_handle, mp_obj_t cb)
{
int32_t res = STATE_SUCCESS;
int32_t time_zone = 8;
void *ntp_handle = NULL;
hapy_aiot_ntp_notify_param_t *ntp_params;
if (mqtt_handle == NULL) {
amp_error(MOD_STR, "ntp service init failed");
return -1;
}
ntp_handle = aiot_ntp_init();
if (ntp_handle == NULL) {
amp_error(MOD_STR, "ntp service init failed");
return -1;
}
res = aiot_ntp_setopt(ntp_handle, AIOT_NTPOPT_MQTT_HANDLE, (void *)mqtt_handle);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "ntp set mqtt handle failed");
aiot_ntp_deinit(&ntp_handle);
return -1;
}
res = aiot_ntp_setopt(ntp_handle, AIOT_NTPOPT_TIME_ZONE, (void *)&time_zone);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "ntp set time zone failed");
aiot_ntp_deinit(&ntp_handle);
return -1;
}
res = aiot_ntp_setopt(ntp_handle, AIOT_NTPOPT_RECV_HANDLER, (void *)aiot_app_ntp_recv_handler);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "ntp set receive handler failed");
aiot_ntp_deinit(&ntp_handle);
return -1;
}
res = aiot_ntp_setopt(ntp_handle, AIOT_NTPOPT_EVENT_HANDLER, (void *)aiot_app_ntp_event_handler);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "ntp set event handler failed");
aiot_ntp_deinit(&ntp_handle);
return -1;
}
ntp_params = aos_malloc(sizeof(hapy_aiot_ntp_notify_param_t));
if (!ntp_params) {
amp_error(MOD_STR, "alloc device_ntp_notify_param_t fail");
return -1;
}
memset(ntp_params, 0, sizeof(hapy_aiot_ntp_notify_param_t));
ntp_params->cb = cb;
res = aiot_ntp_setopt(ntp_handle, AIOT_NTPOPT_USERDATA, ntp_params);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "ntp set user data failed");
aiot_ntp_deinit(&ntp_handle);
aos_free(ntp_params);
return -1;
}
res = aiot_ntp_send_request(ntp_handle);
if (res < STATE_SUCCESS) {
amp_error(MOD_STR, "ntp send request failed");
aiot_ntp_deinit(&ntp_handle);
aos_free(ntp_params);
return -1;
}
return res;
}
| YifuLiu/AliOS-Things | components/py_engine/modules/aliyunIoT/module_aiot_ntp.c | C | apache-2.0 | 5,932 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include "aiot_state_api.h"
#include "aiot_sysdep_api.h"
#include "aiot_dynreg_api.h"
#include "aiot_mqtt_api.h"
#include "module_aiot.h"
#include "aiot_state_api.h"
#include "aiot_sysdep_api.h"
#include "aiot_mqtt_api.h"
#include "aiot_mqtt_upload_api.h"
#include "upload_crc64.h"
#define MOD_STR "AIOT_UPLOAD"
#define MQTT_UPLOAD_RSP_TIMEOUT 2000
#define MQTT_UPLOAD_RETY_COUNT 5
#ifdef M5STACK_CORE2
#define MQTT_UPLOAD_BLOCK_SIZE (10 * 1024)
#else
#define MQTT_UPLOAD_BLOCK_SIZE (2 * 1024)
#endif
/* 位于portfiles/aiot_port文件夹下的系统适配函数集合 */
extern aiot_sysdep_portfile_t g_aiot_sysdep_portfile;
/* 位于external/ali_ca_cert.c中的服务器证书 */
extern const char *ali_ca_cert;
static char *g_data = NULL;
static int32_t g_data_len = 0;
static char *g_file_path = NULL;
static char *get_basename(char *path)
{
char *s1;
char *s2;
s1 = strrchr(path, '/');
s2 = strrchr(path, '\\');
if (s1 && s2)
path = (s1 > s2 ? s1 : s2) + 1;
else if (s1)
path = s1 + 1;
else if (s2)
path = s2 + 1;
return path;
}
static uint32_t get_file_size(char *file_name)
{
uint32_t total_size = 0;
if (file_name == NULL)
return -1;
FILE *fp = fopen(file_name, "r");
if (fp == NULL) {
amp_error(MOD_STR, "open File:%s failed \r\n", file_name);
return -1;
}
fseek(fp, 0, SEEK_END);
total_size = ftell(fp);
fclose(fp);
return total_size;
}
static uint64_t get_file_crc64(char *file_name, char *buf, int32_t buf_len)
{
uint64_t crc = 0;
uint32_t read_default_size = 2048;
uint32_t read_len = 0;
uint8_t data[2048] = {0};
uint32_t read_offset = 0;
if (data != NULL) {
crc = upload_crc64_update(crc, buf, buf_len);
return crc;
}
FILE *fp = fopen(file_name, "r");
fseek(fp, 0, SEEK_END);
uint32_t total_size = ftell(fp);
for (read_offset = 0; total_size != read_offset;) {
fseek(fp, read_offset, SEEK_SET);
read_len = fread(data, sizeof(uint8_t), read_default_size, fp);
crc = upload_crc64_update(crc, data, read_len);
read_offset += read_len;
}
fclose(fp);
return crc;
}
static int32_t aiot_read_data_handler(const aiot_mqtt_upload_recv_t *packet, uint8_t *data, uint32_t size, void *userdata)
{
int32_t read_len = 0;
if (userdata != NULL) {
uint32_t *test_userdata = (uint32_t *)userdata;
amp_debug(MOD_STR, "test_userdata:%d\r\n", *test_userdata);
}
if (packet == NULL) {
return 0;
}
if (packet->desc.code == UPLOAD_FILE_OK) {
if (data != NULL && size != 0) {
uint32_t read_size = size;
FILE *fp;
char *file_name = packet->desc.file_name;
if (g_data != NULL) {
uint32_t offset = packet->desc.file_offset;
if (read_size > g_data_len - offset)
read_len = g_data_len - offset;
else
read_len = read_size;
memcpy(data, g_data + offset, read_len);
} else {
fp = fopen(g_file_path, "r");
uint32_t offset = packet->desc.file_offset;
fseek(fp, offset, SEEK_SET);
read_len = fread(data, sizeof(uint8_t), read_size, fp);
amp_debug(MOD_STR, "Open %s read at: %d,Read_len: %d \r\n", file_name, offset, read_len);
fclose(fp);
}
}
} else {
amp_error(MOD_STR, "Error code:%d, message:%s\r\n", packet->desc.code, packet->desc.message);
}
return read_len;
}
char *pyamp_aiot_upload_mqtt(void *mqtt_handle, char *file_name, char *data, int32_t data_len, mp_obj_t cb)
{
uint32_t file_len = 0;
// char *base_file_name = NULL;
// MQTT Upload File Init.
void *up_handle = aiot_mqtt_upload_init();
aiot_mqtt_upload_setopt(up_handle, AIOT_MQTT_UPLOADOPT_MQTT_HANDLE, mqtt_handle);
/* 如果网络速率比较慢,可以将延迟时间调整的更大 */
uint32_t rsp_timeout = MQTT_UPLOAD_RSP_TIMEOUT;
aiot_mqtt_upload_setopt(up_handle, AIOT_MQTT_UPLOADOPT_RSP_TIMEOUT_MS, &rsp_timeout);
uint32_t rety_count = MQTT_UPLOAD_RETY_COUNT;
aiot_mqtt_upload_setopt(up_handle, AIOT_MQTT_UPLOADOPT_RETRY_COUNT, &rety_count);
/* 如果文件较大时可以调整block_size的大小 */
uint32_t block_size = MQTT_UPLOAD_BLOCK_SIZE;
aiot_mqtt_upload_setopt(up_handle, AIOT_MQTT_UPLOADOPT_DEFAULLT_BLOCK_SIZE, &block_size);
uint32_t timeout_ms = 10*000;
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_RECV_TIMEOUT_MS, (void *)&timeout_ms);
if (file_name != NULL) {
if (data_len != 0) {
g_data = data;
g_data_len = data_len;
file_len = data_len;
} else {
g_data = NULL;
g_data_len = 0;
g_file_path = data;
file_len = get_file_size(g_file_path);
if (file_len < 0)
goto exit;
}
// base_file_name = get_basename(g_file_path);
#ifdef UPlOAD_WITH_CRC
/* 配置上传文件的信息和回调,调用主动发送接口时,不需要配置回调,如果配置了回调参数SDK默认优先使用回调*/
uint32_t test_userdata = 100;
uint64_t crc = get_file_crc64(file_name);
aiot_mqtt_upload_file_opt_t file_option = {
.file_name = file_name,
.file_size = file_len,
.mode = AIOT_MQTT_UPLOAD_FILE_MODE_OVERWRITE,
.digest = &crc,
.read_data_handler = aiot_read_data_handler,
.userdata = &test_userdata
};
amp_debug(MOD_STR, "aiot_mqtt_upload with crc %d\n", crc);
#else
/* 无crc64校验,无userdata传参 */
aiot_mqtt_upload_file_opt_t file_option = {
.file_name = file_name,
.file_size = file_len,
.mode = AIOT_MQTT_UPLOAD_FILE_MODE_OVERWRITE,
.digest = NULL,
.read_data_handler = aiot_read_data_handler,
.userdata = NULL
};
amp_debug(MOD_STR, "aiot_mqtt_upload without crc\n");
#endif
aiot_mqtt_upload_setopt(up_handle, AIOT_MQTT_UPLOADOPT_FILE_OPTION, &file_option);
/* 请求打开上传通道 */
aiot_mqtt_upload_open_stream(up_handle, file_name, NULL);
} else {
amp_error(MOD_STR, "filename should not be null,please check it\n");
goto exit;
}
static aiot_mqtt_upload_result_t result;
while (1) {
result = aiot_mqtt_upload_process(up_handle);
if (result.status == STATE_MQTT_UPLOAD_FINISHED) {
/* 上传成功 */
amp_debug(MOD_STR, "MQTT Upload file(%s) ID(%s) success\r\n", result.file_name, result.uploadid);
break;
} else if (result.status == STATE_MQTT_UPLOAD_FAILED ||
result.status == STATE_MQTT_UPLOAD_FAILED_TIMEOUT ||
result.status == STATE_MQTT_UPLOAD_CANCEL_FAILED) {
/* 上传失败 */
amp_error(MOD_STR, "MQTT Upload file(%s) failed,res:-0x%.4X\r\n", result.file_name, -result.status);
// printf("MQTT Upload file(%s) failed,res:-0x%.4X\r\n", result.file_name, -result.status);
break;
/* 销毁MQTT UPLOAD实例 */
} else if (result.status == STATE_MQTT_UPLOAD_CANCEL_SUCCESS) {
amp_error(MOD_STR, "MQTT Upload file(%s) cancel success,res:-0x%.4X\r\n", result.file_name, -result.status);
break;
} else if (result.status == STATE_MQTT_UPLOAD_FAILED_WHOLE_CHECK) {
/* 云端校验文件的完整性失败 */
amp_error(MOD_STR, "MQTT Upload file(%s) whole file md5 failed,res:-0x%.4X\r\n", result.file_name, -result.status);
break;
}
}
exit:
/* 销毁MQTT实例*/
aiot_mqtt_upload_deinit(&up_handle);
if (result.status == STATE_MQTT_UPLOAD_FINISHED) {
return &result.uploadid;
} else {
return NULL;
}
}
| YifuLiu/AliOS-Things | components/py_engine/modules/aliyunIoT/module_aiot_upload.c | C | apache-2.0 | 8,131 |
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_AUDIO=1)
# Collect audio micropython port source
if(ESP_PLATFORM)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/audio/esp32/modaudio.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/audio/esp32/audio_player.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/audio/esp32/audio_recorder.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/audio/esp32/audio_snd.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/audio/esp32/vfs_stream.c)
else()
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/audio/aos/modaudio.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/audio/aos/audio_player.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/audio/aos/audio_recorder.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/audio/aos/audio_snd.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/audio/aos/audio_tts.c)
endif()
if(ESP_PLATFORM)
# Collect ADF Library Sources
file(GLOB AUDIO_SAL_SRC RELATIVE $ENV{ADF_PATH}/components/audio_sal "*.c")
file(GLOB AUDIO_PIPLINE_SRC RELATIVE $ENV{ADF_PATH}/components/audio_pipeline "*.c")
file(GLOB AUDIO_STREAM_SRC RELATIVE $ENV{ADF_PATH}/components/audio_stream "*.c")
file(GLOB AUDIO_CODEC_SRC RELATIVE $ENV{ADF_PATH}/components/esp-adf-libs/esp_codec "*.c")
file(GLOB AUDIO_BOARD_SRC RELATIVE $ENV{ADF_PATH}/components/audio_board/m5stack_core2 "*.c")
file(GLOB AUDIO_HAL_SRC RELATIVE $ENV{ADF_PATH}/components/audio_hal "*.c")
file(GLOB ESP_DISPATCHER_SRC RELATIVE $ENV{ADF_PATH}/components/esp_dispatcher "*.c")
file(GLOB AUDIO_HAL_DRIVER_SRC RELATIVE $ENV{ADF_PATH}/components/audio_hal/driver/ns4168 "*.c")
endif()
list(APPEND MICROPY_SOURCE_MODULES_PORT
${AUDIO_SAL_SRC}
${AUDIO_PIPLINE_SRC}
${AUDIO_STREAM_SRC}
${AUDIO_CODEC_SRC}
${AUDIO_BOARD_SRC}
${AUDIO_HAL_SRC}
${ESP_DISPATCHER_SRC}
${AUDIO_HAL_DRIVER_SRC}
)
if(ESP_PLATFORM)
# append audio include
list(APPEND MICROPY_INC_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/audio/esp32)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{ADF_PATH}/components/esp-adf-libs/esp_audio/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{ADF_PATH}/components/adf_utils/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{ADF_PATH}/components/audio_hal/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{ADF_PATH}/components/audio_pipeline/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{ADF_PATH}/components/audio_sal/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{ADF_PATH}/components/audio_stream/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{ADF_PATH}/components/esp-adf-libs/audio_misc/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{ADF_PATH}/components/esp-adf-libs/esp_codec/include/codec)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{ADF_PATH}/components/esp-adf-libs/esp_codec/include/processing)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{ADF_PATH}/components/esp-adf-libs/recorder_engine/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{ADF_PATH}/components/audio_board/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{ADF_PATH}/components/audio_board/m5stack_core2)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{ADF_PATH}/components/esp-sr/lib/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{ADF_PATH}/components/esp_dispatcher/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{ADF_PATH}/components/audio_hal/driver/include)
else()
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/uvoice/internal)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/uvoice/include)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/uvoice/application/alicloudtts/include)
endif()
# add_prebuilt_library(esp_audio "$ENV{ADF_PATH}/components/esp-adf-libs/esp_audio/lib/esp32/libesp_audio.a"
# PRIV_REQUIRES esp-adf-libs)
# add_prebuilt_library(esp_codec "$ENV{ADF_PATH}/components/esp-adf-libs/esp_codec/lib/esp32/libesp_codec.a"
# PRIV_REQUIRES esp-adf-libs)
# add_prebuilt_library(esp_processing "$ENV{ADF_PATH}/components/esp-adf-libs/esp_codec/lib/esp32/libesp_processing.a"
# PRIV_REQUIRES esp-adf-libs)
# target_link_libraries(${MICROPY_TARGET} esp_processing esp_audio esp_codec)
# target_link_libraries(${COMPONENT_LIB} INTERFACE "-L$ENV{ADF_PATH}/components/esp-adf-libs/esp_audio/lib/esp32")
# target_link_libraries(${COMPONENT_LIB} INTERFACE "-L$ENV{ADF_PATH}/components/esp-adf-libs/esp_codec/lib/esp32")
# target_link_libraries(${COMPONENT_LIB} PUBLIC esp_processing)
| YifuLiu/AliOS-Things | components/py_engine/modules/audio/CMakeLists.txt | CMake | apache-2.0 | 4,788 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if MICROPY_PY_AUDIO
#include "py/builtin.h"
#include "py/mperrno.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "ulog/ulog.h"
#include "utility.h"
#include "uvoice_init.h"
#include "uvoice_player.h"
#include "uvoice_event.h"
#include "uvoice_types.h"
#define LOG_TAG "UVOICE_PLAYER"
#define PLAYER_CHECK_PARAMS() \
uvoice_player_obj_t *self = (uvoice_player_obj_t *)MP_OBJ_TO_PTR(self_in); \
do { \
if (self == NULL || self->player_obj == NULL) { \
mp_raise_OSError(EINVAL); \
return mp_const_none; \
} \
} while (0)
#define PLAYER_CHECK_RESULT() \
do { \
if (ret != 0) { \
LOGE(LOG_TAG, "%s, %d, player failed with ret=%d", __func__, __LINE__, ret); \
return MP_OBJ_NEW_SMALL_INT(ret); \
} \
} while (0)
extern const mp_obj_type_t uvoice_player_type;
// this is the actual C-structure for our new object
typedef struct {
// base represents some basic information, like type
mp_obj_base_t base;
// a member created by us
char *modName;
uvoice_player_t *player_obj;
int list_playing;
int state;
mp_obj_t callback;
} uvoice_player_obj_t;
enum {
AUDIOPLAYER_STAT_STOP = 0,
AUDIOPLAYER_STAT_PAUSED = 1,
AUDIOPLAYER_STAT_PLAYING = 2,
AUDIOPLAYER_STAT_ERROR = 5,
};
void uvoice_player_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind)
{
uvoice_player_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "modName(%s)", self->modName);
}
STATIC mp_obj_t uvoice_player_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args)
{
uvoice_player_obj_t *uvocie_player_com_obj = m_new_obj(uvoice_player_obj_t);
if (!uvocie_player_com_obj) {
mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("Memory malloc failed"));
}
memset(uvocie_player_com_obj, 0, sizeof(uvoice_player_obj_t));
uvocie_player_com_obj->base.type = &uvoice_player_type;
uvocie_player_com_obj->modName = "uvoice-player";
return MP_OBJ_FROM_PTR(uvocie_player_com_obj);
}
STATIC mp_obj_t uvoice_open(mp_obj_t self_in)
{
uvoice_player_obj_t *self = (uvoice_player_obj_t *)MP_OBJ_TO_PTR(self_in);
if (self == NULL) {
mp_raise_OSError(EINVAL);
}
if (self->player_obj == NULL) {
self->player_obj = uvoice_player_create();
if (self->player_obj == NULL) {
return MP_OBJ_NEW_SMALL_INT(-MP_ENODEV);
}
}
return MP_OBJ_NEW_SMALL_INT(0);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_open_obj, uvoice_open);
STATIC mp_obj_t uvoice_close(mp_obj_t self_in)
{
PLAYER_CHECK_PARAMS();
mp_int_t ret = 0;
if (self->player_obj != NULL) {
self->player_obj->stop();
ret = uvoice_player_release(self->player_obj);
self->player_obj = NULL;
}
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_close_obj, uvoice_close);
STATIC mp_obj_t uvoice_release(mp_obj_t self_in)
{
PLAYER_CHECK_PARAMS();
mp_int_t ret = -1;
if (self->player_obj != NULL) {
self->player_obj->stop();
ret = uvoice_player_release(self->player_obj);
self->player_obj = NULL;
}
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_release_obj, uvoice_release);
STATIC mp_obj_t uvoice_play(size_t n_args, const mp_obj_t *args)
{
mp_int_t ret = 0;
if (n_args < 2) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__, n_args);
return mp_const_none;
}
mp_obj_t self_in = args[0];
PLAYER_CHECK_PARAMS();
if (get_uvoice_state() == false) {
LOGE(LOG_TAG, "snd card not inited");
return MP_OBJ_NEW_SMALL_INT(-MP_EPERM);
}
const char *source = mp_obj_str_get_str(args[1]);
ret = self->player_obj->set_source(source);
PLAYER_CHECK_RESULT();
ret = self->player_obj->start();
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(uvoice_play_obj, 2, uvoice_play);
STATIC mp_obj_t uvoice_stop(mp_obj_t self_in)
{
PLAYER_CHECK_PARAMS();
mp_int_t ret = self->player_obj->stop();
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_stop_obj, uvoice_stop);
STATIC mp_obj_t uvoice_pause(mp_obj_t self_in)
{
PLAYER_CHECK_PARAMS();
mp_int_t ret = self->player_obj->pause();
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_pause_obj, uvoice_pause);
STATIC mp_obj_t uvoice_resume(mp_obj_t self_in)
{
PLAYER_CHECK_PARAMS();
mp_int_t ret = self->player_obj->resume();
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_resume_obj, uvoice_resume);
STATIC mp_obj_t uvoice_complete(mp_obj_t self_in)
{
PLAYER_CHECK_PARAMS();
mp_int_t ret = self->player_obj->complete();
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_complete_obj, uvoice_complete);
STATIC mp_obj_t uvoice_stop_async(mp_obj_t self_in)
{
PLAYER_CHECK_PARAMS();
mp_int_t ret = self->player_obj->stop_async();
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_stop_async_obj, uvoice_stop_async);
STATIC mp_obj_t uvoice_pause_async(mp_obj_t self_in)
{
PLAYER_CHECK_PARAMS();
mp_int_t ret = self->player_obj->pause_async();
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_pause_async_obj, uvoice_pause_async);
STATIC mp_obj_t uvoice_resume_async(mp_obj_t self_in)
{
PLAYER_CHECK_PARAMS();
mp_int_t ret = self->player_obj->resume_async();
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_resume_async_obj, uvoice_resume_async);
STATIC mp_obj_t uvoice_set_source(mp_obj_t self_in, mp_obj_t source_in)
{
PLAYER_CHECK_PARAMS();
char *source = mp_obj_str_get_str(source_in);
mp_int_t ret = self->player_obj->set_source(source);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(uvoice_set_source_obj, uvoice_set_source);
STATIC mp_obj_t uvoice_clr_source(mp_obj_t self_in)
{
PLAYER_CHECK_PARAMS();
mp_int_t ret = self->player_obj->clr_source();
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_clr_source_obj, uvoice_clr_source);
STATIC mp_obj_t uvoice_set_stream(size_t n_args, const mp_obj_t *args)
{
if (n_args < 4) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__, n_args);
return mp_const_none;
}
mp_obj_t self_in = args[0];
PLAYER_CHECK_PARAMS();
media_format_t format = (media_format_t)mp_obj_get_int(args[1]);
int cache_enable = mp_obj_get_int(args[2]);
int cache_size = mp_obj_get_int(args[3]);
mp_int_t ret = self->player_obj->set_stream(format, cache_enable, cache_size);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(uvoice_set_stream_obj, 4, uvoice_set_stream);
STATIC mp_obj_t uvoice_put_stream(mp_obj_t self_in, mp_obj_t buffer_in, mp_obj_t nbytes_in)
{
PLAYER_CHECK_PARAMS();
int nbytes = mp_obj_get_int(nbytes_in);
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(buffer_in, &bufinfo, MP_BUFFER_READ);
const uint8_t *data = (const uint8_t *)bufinfo.buf;
mp_int_t ret = self->player_obj->put_stream(data, bufinfo.len);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_3(uvoice_put_stream_obj, uvoice_put_stream);
STATIC mp_obj_t uvoice_clr_stream(mp_obj_t self_in, mp_obj_t immediate_in)
{
PLAYER_CHECK_PARAMS();
int immediate = mp_obj_get_int(immediate_in);
mp_int_t ret = self->player_obj->clr_stream(immediate);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(uvoice_clr_stream_obj, uvoice_clr_stream);
STATIC mp_obj_t uvoice_set_pcminfo(size_t n_args, const mp_obj_t *args)
{
if (n_args < 5) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__, n_args);
return mp_const_none;
}
mp_obj_t self_in = args[0];
PLAYER_CHECK_PARAMS();
int rate = mp_obj_get_int(args[1]);
int channels = mp_obj_get_int(args[2]);
int bits = mp_obj_get_int(args[3]);
int frames = mp_obj_get_int(args[4]);
mp_int_t ret = self->player_obj->set_pcminfo(rate, channels, bits, frames);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(uvoice_set_pcminfo_obj, 5, uvoice_set_pcminfo);
STATIC mp_obj_t uvoice_getDuration(mp_obj_t self_in)
{
PLAYER_CHECK_PARAMS();
int duration = -1;
int ret = self->player_obj->get_duration(&duration);
PLAYER_CHECK_RESULT();
return MP_OBJ_NEW_SMALL_INT(duration);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_getDuration_obj, uvoice_getDuration);
STATIC mp_obj_t uvoice_getPosition(mp_obj_t self_in)
{
PLAYER_CHECK_PARAMS();
int position = -1;
int ret = self->player_obj->get_position(&position);
PLAYER_CHECK_RESULT();
return MP_OBJ_NEW_SMALL_INT(position);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_getPosition_obj, uvoice_getPosition);
STATIC mp_obj_t uvoice_setVolume(mp_obj_t self_in, mp_obj_t volume_in)
{
PLAYER_CHECK_PARAMS();
int volume = mp_obj_get_int(volume_in);
mp_int_t ret = self->player_obj->set_volume(volume);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(uvoice_setVolume_obj, uvoice_setVolume);
STATIC mp_obj_t uvoice_getVolume(mp_obj_t self_in)
{
PLAYER_CHECK_PARAMS();
int volume = -1;
int ret = self->player_obj->get_volume(&volume);
PLAYER_CHECK_RESULT();
return MP_OBJ_NEW_SMALL_INT(volume);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_getVolume_obj, uvoice_getVolume);
static void uvoice_player_state_notify(void *arg)
{
uvoice_player_obj_t *audioplayer = (uvoice_player_obj_t *)arg;
callback_to_python_LoBo(audioplayer->callback, MP_OBJ_NEW_SMALL_INT(1), NULL);
}
static void uvoice_player_state_cb(uvoice_event_t *event, void *data)
{
uvoice_player_obj_t *audioplayer = (uvoice_player_obj_t *)data;
player_state_t state;
int audioplayer_state = PLAYER_STAT_IDLE;
int ret;
if (!audioplayer)
return;
if (event->type != UVOICE_EV_PLAYER)
return;
if (event->code == UVOICE_CODE_PLAYER_STATE) {
state = event->value;
switch (state) {
case PLAYER_STAT_RUNNING:
case PLAYER_STAT_COMPLETE:
case PLAYER_STAT_RESUME:
audioplayer_state = AUDIOPLAYER_STAT_PLAYING;
break;
case PLAYER_STAT_PAUSED:
audioplayer_state = AUDIOPLAYER_STAT_PAUSED;
break;
case PLAYER_STAT_STOP:
case PLAYER_STAT_IDLE:
case PLAYER_STAT_READY:
audioplayer_state = AUDIOPLAYER_STAT_STOP;
break;
case PLAYER_STAT_ERROR:
audioplayer_state = AUDIOPLAYER_STAT_ERROR;
break;
default:
return;
}
}
if (audioplayer->state == audioplayer_state) {
return;
}
audioplayer->state = audioplayer_state;
py_task_schedule_call(uvoice_player_state_notify, audioplayer);
}
STATIC mp_obj_t uvoice_state_on(size_t n_args, const mp_obj_t *args)
{
int ret = 0;
if (n_args < 2) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__, n_args);
return mp_const_none;
}
mp_obj_t self_in = args[0];
PLAYER_CHECK_PARAMS();
self->callback = args[1];
ret = uvoice_event_register(UVOICE_EV_PLAYER, uvoice_player_state_cb, (void *)self);
if (ret) {
LOGE(LOG_TAG, "register event fail");
return MP_OBJ_NEW_SMALL_INT(ret);
}
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(uvoice_state_on_obj, 2, uvoice_state_on);
STATIC mp_obj_t uvoice_volume_range(mp_obj_t self_in)
{
PLAYER_CHECK_PARAMS();
int max = 100;
int min = 0;
mp_int_t ret = self->player_obj->volume_range(&max, &min);
// dict solution
mp_obj_t volume_dict = mp_obj_new_dict(2);
mp_obj_dict_store(volume_dict, MP_OBJ_NEW_QSTR(qstr_from_str("vol_max")), MP_OBJ_NEW_SMALL_INT(max));
mp_obj_dict_store(volume_dict, MP_OBJ_NEW_QSTR(qstr_from_str("vol_min")), MP_OBJ_NEW_SMALL_INT(min));
return volume_dict;
// mp_obj_t volume[2];
// volume[0] = MP_OBJ_NEW_SMALL_INT(max);
// volume[1] = MP_OBJ_NEW_SMALL_INT(min);
// mp_obj_t volume_tuple = mp_obj_new_tuple(2, volume);
// return volume_tuple;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_volume_range_obj, uvoice_volume_range);
STATIC mp_obj_t uvoice_seekTo(mp_obj_t self_in, mp_obj_t second_in)
{
PLAYER_CHECK_PARAMS();
int second = mp_obj_get_int(second_in);
mp_int_t ret = self->player_obj->seek(second);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(uvoice_seekTo_obj, uvoice_seekTo);
STATIC mp_obj_t uvoice_playback(mp_obj_t self_in, mp_obj_t source_in)
{
PLAYER_CHECK_PARAMS();
char *source = (char *)mp_obj_str_get_str(source_in);
mp_int_t ret = self->player_obj->playback(source);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(uvoice_playback_obj, uvoice_playback);
STATIC mp_obj_t uvoice_wait_complete(mp_obj_t self_in)
{
PLAYER_CHECK_PARAMS();
mp_int_t ret = self->player_obj->wait_complete();
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_wait_complete_obj, uvoice_wait_complete);
STATIC mp_obj_t uvoice_download(mp_obj_t self_in, mp_obj_t name_in)
{
PLAYER_CHECK_PARAMS();
char *name = (char *)mp_obj_str_get_str(name_in);
mp_int_t ret = self->player_obj->download(name);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(uvoice_download_obj, uvoice_download);
STATIC mp_obj_t uvoice_download_abort(mp_obj_t self_in)
{
PLAYER_CHECK_PARAMS();
mp_int_t ret = self->player_obj->download_abort();
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_download_abort_obj, uvoice_download_abort);
STATIC mp_obj_t uvoice_cache_config(mp_obj_t self_in, mp_obj_t config_dict)
{
PLAYER_CHECK_PARAMS();
cache_config_t config = { 0 };
config.place = get_int_from_dict(config_dict, "place");
config.mem_size = get_int_from_dict(config_dict, "mem_size");
const char *file_path = get_str_from_dict(config_dict, "file_path");
strncpy(config.file_path, file_path, strlen(file_path));
mp_int_t ret = self->player_obj->cache_config(&config);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(uvoice_cache_config_obj, uvoice_cache_config);
STATIC mp_obj_t uvoice_set_fade(mp_obj_t self_in, mp_obj_t out_period_in, mp_obj_t in_period_in)
{
PLAYER_CHECK_PARAMS();
int out_period = mp_obj_get_int(out_period_in);
int in_period = mp_obj_get_int(in_period_in);
mp_int_t ret = self->player_obj->set_fade(out_period, in_period);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_3(uvoice_set_fade_obj, uvoice_set_fade);
STATIC mp_obj_t uvoice_set_format(mp_obj_t self_in, mp_obj_t format_in)
{
PLAYER_CHECK_PARAMS();
media_format_t format = (media_format_t)mp_obj_get_int(format_in);
mp_int_t ret = self->player_obj->set_format(format);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(uvoice_set_format_obj, uvoice_set_format);
STATIC mp_obj_t uvoice_set_standby(mp_obj_t self_in, mp_obj_t msec_in)
{
PLAYER_CHECK_PARAMS();
int msec = mp_obj_get_int(msec_in);
mp_int_t ret = self->player_obj->set_standby(msec);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(uvoice_set_standby_obj, uvoice_set_standby);
STATIC mp_obj_t uvoice_eq_enable(mp_obj_t self_in, mp_obj_t enable_in)
{
PLAYER_CHECK_PARAMS();
int enable = mp_obj_get_int(enable_in);
mp_int_t ret = self->player_obj->eq_enable(enable);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(uvoice_eq_enable_obj, uvoice_eq_enable);
STATIC mp_obj_t uvoice_state_dump(mp_obj_t self_in)
{
PLAYER_CHECK_PARAMS();
mp_int_t ret = self->player_obj->state_dump();
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_state_dump_obj, uvoice_state_dump);
STATIC mp_obj_t uvoice_pcmdump_enable(mp_obj_t self_in, mp_obj_t enable_in)
{
PLAYER_CHECK_PARAMS();
int enable = mp_obj_get_int(enable_in);
mp_int_t ret = self->player_obj->pcmdump_enable(enable);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(uvoice_pcmdump_enable_obj, uvoice_pcmdump_enable);
STATIC mp_obj_t uvoice_getState(mp_obj_t self_in)
{
PLAYER_CHECK_PARAMS();
player_state_t state = -1;
mp_int_t ret = self->player_obj->get_state(&state);
if (ret == 0) {
return MP_OBJ_NEW_SMALL_INT(state);
} else {
return MP_OBJ_NEW_SMALL_INT(ret);
}
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_getState_obj, uvoice_getState);
STATIC mp_obj_t uvoice_get_delay(mp_obj_t self_in)
{
PLAYER_CHECK_PARAMS();
int delay_ms;
self->player_obj->get_delay(&delay_ms);
return MP_OBJ_NEW_SMALL_INT(delay_ms);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_get_delay_obj, uvoice_get_delay);
STATIC mp_obj_t uvoice_get_mediainfo(mp_obj_t self_in)
{
PLAYER_CHECK_PARAMS();
media_info_t info = { 0 };
mp_int_t ret = self->player_obj->get_mediainfo(&info);
if (ret != 0) {
LOGE(LOG_TAG, "failed to get mediainfo");
return mp_const_none;
}
// LOGD(LOG_TAG,
// "name=%s, author=%s, album=%s, year=%s, valid=%d, type=%d, "
// "bitrate=%d, media_size=%d, duration=%d, len = %d\n\n",
// info.name, info.author, info.album, info.year, info.valid,
// info.type, info.bitrate, info.media_size, info.duration,
// strlen(info.name));
mp_obj_t mediainfo_dict = mp_obj_new_dict(9);
mp_obj_dict_store(mediainfo_dict, MP_OBJ_NEW_QSTR(qstr_from_str("name")),
mp_obj_new_str(info.name, strlen(info.name)));
mp_obj_dict_store(mediainfo_dict, MP_OBJ_NEW_QSTR(qstr_from_str("author")),
mp_obj_new_str(info.author, strlen(info.author)));
mp_obj_dict_store(mediainfo_dict, MP_OBJ_NEW_QSTR(qstr_from_str("album")),
mp_obj_new_str(info.album, strlen(info.album)));
mp_obj_dict_store(mediainfo_dict, MP_OBJ_NEW_QSTR(qstr_from_str("year")),
mp_obj_new_str(info.year, strlen(info.year)));
mp_obj_dict_store(mediainfo_dict, MP_OBJ_NEW_QSTR(qstr_from_str("valid")), MP_OBJ_NEW_SMALL_INT(info.valid));
mp_obj_dict_store(mediainfo_dict, MP_OBJ_NEW_QSTR(qstr_from_str("type")), MP_OBJ_NEW_SMALL_INT(info.type));
mp_obj_dict_store(mediainfo_dict, MP_OBJ_NEW_QSTR(qstr_from_str("bitrate")), MP_OBJ_NEW_SMALL_INT(info.bitrate));
mp_obj_dict_store(mediainfo_dict, MP_OBJ_NEW_QSTR(qstr_from_str("media_size")),
MP_OBJ_NEW_SMALL_INT(info.media_size));
mp_obj_dict_store(mediainfo_dict, MP_OBJ_NEW_QSTR(qstr_from_str("duration")), MP_OBJ_NEW_SMALL_INT(info.duration));
return mediainfo_dict;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_get_mediainfo_obj, uvoice_get_mediainfo);
STATIC mp_obj_t uvoice_get_cacheinfo(mp_obj_t self_in)
{
PLAYER_CHECK_PARAMS();
int cache_size = -1;
self->player_obj->get_cacheinfo(&cache_size);
return MP_OBJ_NEW_SMALL_INT(cache_size);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_get_cacheinfo_obj, uvoice_get_cacheinfo);
STATIC mp_obj_t uvoice_format_support(mp_obj_t self_in, mp_obj_t format_in)
{
PLAYER_CHECK_PARAMS();
media_format_t format = (media_format_t)mp_obj_get_int(format_in);
mp_int_t ret = self->player_obj->format_support(format);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(uvoice_format_support_obj, uvoice_format_support);
STATIC const mp_rom_map_elem_t uvoice_module_player_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&uvoice_release_obj) },
{ MP_ROM_QSTR(MP_QSTR_open), MP_ROM_PTR(&uvoice_open_obj) },
{ MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&uvoice_close_obj) },
{ MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&uvoice_play_obj) },
{ MP_ROM_QSTR(MP_QSTR_pause), MP_ROM_PTR(&uvoice_pause_obj) },
{ MP_ROM_QSTR(MP_QSTR_resume), MP_ROM_PTR(&uvoice_resume_obj) },
{ MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&uvoice_stop_obj) },
{ MP_ROM_QSTR(MP_QSTR_setVolume), MP_ROM_PTR(&uvoice_setVolume_obj) },
{ MP_ROM_QSTR(MP_QSTR_getVolume), MP_ROM_PTR(&uvoice_getVolume_obj) },
{ MP_ROM_QSTR(MP_QSTR_seekTo), MP_ROM_PTR(&uvoice_seekTo_obj) },
{ MP_ROM_QSTR(MP_QSTR_getState), MP_ROM_PTR(&uvoice_getState_obj) },
{ MP_ROM_QSTR(MP_QSTR_getPosition), MP_ROM_PTR(&uvoice_getPosition_obj) },
{ MP_ROM_QSTR(MP_QSTR_getDuration), MP_ROM_PTR(&uvoice_getDuration_obj) },
{ MP_ROM_QSTR(MP_QSTR_waitComplete), MP_ROM_PTR(&uvoice_wait_complete_obj) },
{ MP_ROM_QSTR(MP_QSTR_on), MP_ROM_PTR(&uvoice_state_on_obj) },
/* audio player state */
{ MP_ROM_QSTR(MP_QSTR_AUDIOPLAYER_STAT_STOP), MP_ROM_INT(AUDIOPLAYER_STAT_STOP) },
{ MP_ROM_QSTR(MP_QSTR_AUDIOPLAYER_STAT_PAUSED), MP_ROM_INT(AUDIOPLAYER_STAT_PAUSED) },
{ MP_ROM_QSTR(MP_QSTR_AUDIOPLAYER_STAT_PLAYING), MP_ROM_INT(AUDIOPLAYER_STAT_PLAYING) },
{ MP_ROM_QSTR(MP_QSTR_AUDIOPLAYER_STAT_ERROR), MP_ROM_INT(AUDIOPLAYER_STAT_ERROR) },
};
STATIC MP_DEFINE_CONST_DICT(uvoice_module_player_globals, uvoice_module_player_globals_table);
const mp_obj_type_t uvoice_player_type = {
.base = { &mp_type_type },
.name = MP_QSTR_Player,
.print = uvoice_player_print,
.make_new = uvoice_player_new,
.locals_dict = (mp_obj_dict_t *)&uvoice_module_player_globals,
};
#endif // MICROPY_PY_AUDIO
| YifuLiu/AliOS-Things | components/py_engine/modules/audio/aos/audio_player.c | C | apache-2.0 | 22,422 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if MICROPY_PY_AUDIO
#include "py/builtin.h"
#include "py/mperrno.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "ulog/ulog.h"
#include "uvoice_init.h"
#include "uvoice_recorder.h"
#include "uvoice_types.h"
#define LOG_TAG "UVOICE_RECORDER"
extern const mp_obj_type_t uvoice_recorder_type;
extern bool g_is_uvoice_inited;
#define RECORDER_CHECK_PARAMS() \
uvocie_recorder_obj_t *self = (uvocie_recorder_obj_t *)MP_OBJ_TO_PTR(self_in); \
do { \
if (self == NULL || self->recorder_obj == NULL) { \
mp_raise_OSError(EINVAL); \
} \
} while (0)
// this is the actual C-structure for our new object
typedef struct {
// base represents some basic information, like type
mp_obj_base_t base;
// a member created by us
char *modName;
uvoice_recorder_t *recorder_obj;
} uvocie_recorder_obj_t;
void uvoice_recorder_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind)
{
uvocie_recorder_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "modName(%s)", self->modName);
}
STATIC mp_obj_t uvoice_recorder_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args)
{
uvocie_recorder_obj_t *uvocie_recorder_obj = m_new_obj(uvocie_recorder_obj_t);
if (!uvocie_recorder_obj) {
mp_raise_OSError(ENOMEM);
return mp_const_none;
}
memset(uvocie_recorder_obj, 0, sizeof(uvocie_recorder_obj_t));
uvocie_recorder_obj->base.type = &uvoice_recorder_type;
uvocie_recorder_obj->modName = "uvoice-recorder";
uvocie_recorder_obj->recorder_obj = NULL;
return MP_OBJ_FROM_PTR(uvocie_recorder_obj);
}
STATIC mp_obj_t uvoice_open(size_t n_args, const mp_obj_t *args)
{
if (n_args < 8) {
LOGE(LOG_TAG, "%s: args list illegal, exepect 8, get = %d\n", __func__, n_args);
return MP_OBJ_NEW_SMALL_INT(-MP_E2BIG);
}
if (get_uvoice_state() == false) {
LOGE(LOG_TAG, "snd card not inited");
return MP_OBJ_NEW_SMALL_INT(-MP_EPERM);
}
uvocie_recorder_obj_t *self = (uvocie_recorder_obj_t *)MP_OBJ_TO_PTR(args[0]);
if (self == NULL) {
LOGE(LOG_TAG, "uvocie_recorder_obj_t NULL");
return MP_OBJ_NEW_SMALL_INT(-MP_EINVAL);
}
if (self->recorder_obj == NULL) {
self->recorder_obj = uvoice_recorder_create();
if (self->recorder_obj == NULL) {
LOGE(LOG_TAG, "open media recorder failed !\n");
return MP_OBJ_NEW_SMALL_INT(-MP_ENODEV);
}
}
media_format_t format = (media_format_t)mp_obj_get_int(args[1]);
int rate = mp_obj_get_int(args[2]);
int channels = mp_obj_get_int(args[3]);
int bits = mp_obj_get_int(args[4]);
int frames = mp_obj_get_int(args[5]);
int bitrate = mp_obj_get_int(args[6]);
const char *sink = mp_obj_is_str(args[7]) ? mp_obj_str_get_str(args[7]) : NULL;
LOGD(LOG_TAG,
"format=%d, rate=%d, channels=%d, bits=%d, frames=%d, bitrate=%d, "
"sink=%s\n",
format, rate, channels, bits, frames, bitrate, sink);
mp_int_t ret = self->recorder_obj->set_sink(format, rate, channels, bits, frames, bitrate, sink);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(uvoice_open_obj, 8, uvoice_open);
STATIC mp_obj_t uvoice_close(mp_obj_t self_in)
{
RECORDER_CHECK_PARAMS();
int ret = -1;
if (self->recorder_obj != NULL) {
ret = self->recorder_obj->stop();
ret = uvoice_recorder_release(self->recorder_obj);
if (ret != 0) {
LOGE(LOG_TAG, "failed to release recorder!\n");
} else {
self->recorder_obj = NULL;
}
}
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_close_obj, uvoice_close);
STATIC mp_obj_t uvoice_set_sink(size_t n_args, const mp_obj_t *args)
{
if (n_args < 8) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__, n_args);
return mp_const_none;
}
mp_obj_t self_in = args[0];
RECORDER_CHECK_PARAMS();
media_format_t format = (media_format_t)mp_obj_get_int(args[1]);
int rate = mp_obj_get_int(args[2]);
int channels = mp_obj_get_int(args[3]);
int bits = mp_obj_get_int(args[4]);
int frames = mp_obj_get_int(args[5]);
int bitrate = mp_obj_get_int(args[6]);
char *sink = mp_obj_is_str(args[7]) ? (char *)mp_obj_str_get_str(args[7]) : NULL;
LOGD(LOG_TAG,
"format=%d, rate=%d, channels=%d, bits=%d, frames=%d, bitrate=%d, "
"sink=%s\n",
format, rate, channels, bits, frames, bitrate, sink);
mp_int_t ret = self->recorder_obj->set_sink(format, rate, channels, bits, frames, bitrate, sink);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(uvoice_set_sink_obj, 8, uvoice_set_sink);
STATIC mp_obj_t uvoice_clr_sink(mp_obj_t self_in)
{
RECORDER_CHECK_PARAMS();
mp_int_t ret = self->recorder_obj->clr_sink();
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_clr_sink_obj, uvoice_clr_sink);
STATIC mp_obj_t uvoice_start(mp_obj_t self_in)
{
RECORDER_CHECK_PARAMS();
mp_int_t ret = self->recorder_obj->start();
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_start_obj, uvoice_start);
STATIC mp_obj_t uvoice_stop(mp_obj_t self_in)
{
RECORDER_CHECK_PARAMS();
mp_int_t ret = self->recorder_obj->stop();
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_stop_obj, uvoice_stop);
STATIC mp_obj_t uvoice_get_stream(mp_obj_t self_in, mp_obj_t buffer_in, mp_obj_t nbytes_in)
{
RECORDER_CHECK_PARAMS();
int nbytes = mp_obj_get_int(nbytes_in);
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(buffer_in, &bufinfo, MP_BUFFER_WRITE);
memset(bufinfo.buf, 0, bufinfo.len);
mp_int_t rsize = self->recorder_obj->get_stream((uint8_t *)bufinfo.buf, nbytes);
return MP_OBJ_NEW_SMALL_INT(rsize);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_3(uvoice_get_stream_obj, uvoice_get_stream);
STATIC mp_obj_t uvoice_get_state(mp_obj_t self_in)
{
RECORDER_CHECK_PARAMS();
recorder_state_t state;
self->recorder_obj->get_state(&state);
return MP_OBJ_NEW_SMALL_INT(state);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_get_state_obj, uvoice_get_state);
STATIC mp_obj_t uvoice_get_position(mp_obj_t self_in)
{
RECORDER_CHECK_PARAMS();
int pos = -1;
mp_int_t ret = self->recorder_obj->get_position(&pos);
return MP_OBJ_NEW_SMALL_INT(pos);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_get_position_obj, uvoice_get_position);
STATIC mp_obj_t uvoice_ns_enable(mp_obj_t self_in, mp_obj_t enable_in)
{
RECORDER_CHECK_PARAMS();
int enable = mp_obj_get_int(enable_in);
mp_int_t ret = self->recorder_obj->ns_enable(enable);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(uvoice_ns_enable_obj, uvoice_ns_enable);
STATIC mp_obj_t uvoice_ec_enable(mp_obj_t self_in, mp_obj_t enable_in)
{
RECORDER_CHECK_PARAMS();
int enable = mp_obj_get_int(enable_in);
mp_int_t ret = self->recorder_obj->ec_enable(enable);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(uvoice_ec_enable_obj, uvoice_ec_enable);
STATIC mp_obj_t uvoice_agc_enable(mp_obj_t self_in, mp_obj_t enable_in)
{
RECORDER_CHECK_PARAMS();
int enable = mp_obj_get_int(enable_in);
mp_int_t ret = self->recorder_obj->agc_enable(enable);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(uvoice_agc_enable_obj, uvoice_agc_enable);
STATIC mp_obj_t uvoice_vad_enable(mp_obj_t self_in, mp_obj_t enable_in)
{
RECORDER_CHECK_PARAMS();
int enable = mp_obj_get_int(enable_in);
mp_int_t ret = self->recorder_obj->vad_enable(enable);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(uvoice_vad_enable_obj, uvoice_vad_enable);
STATIC mp_obj_t uvoice_format_support(mp_obj_t self_in, mp_obj_t format_in)
{
RECORDER_CHECK_PARAMS();
int format = (media_format_t)mp_obj_get_int(format_in);
mp_int_t ret = self->recorder_obj->format_support(format);
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(uvoice_format_support_obj, uvoice_format_support);
STATIC const mp_rom_map_elem_t uvoice_module_recorder_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR_open), MP_ROM_PTR(&uvoice_open_obj) },
{ MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&uvoice_close_obj) },
{ MP_ROM_QSTR(MP_QSTR_start), MP_ROM_PTR(&uvoice_start_obj) },
{ MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&uvoice_stop_obj) },
{ MP_ROM_QSTR(MP_QSTR_getStream), MP_ROM_PTR(&uvoice_get_stream_obj) },
{ MP_ROM_QSTR(MP_QSTR_getState), MP_ROM_PTR(&uvoice_get_state_obj) },
{ MP_ROM_QSTR(MP_QSTR_enableNS), MP_ROM_PTR(&uvoice_ns_enable_obj) },
{ MP_ROM_QSTR(MP_QSTR_enableEC), MP_ROM_PTR(&uvoice_ec_enable_obj) },
{ MP_ROM_QSTR(MP_QSTR_enableAGC), MP_ROM_PTR(&uvoice_agc_enable_obj) },
{ MP_ROM_QSTR(MP_QSTR_enableVAD), MP_ROM_PTR(&uvoice_vad_enable_obj) },
};
STATIC MP_DEFINE_CONST_DICT(uvoice_module_recorder_globals, uvoice_module_recorder_globals_table);
const mp_obj_type_t uvoice_recorder_type = {
.base = { &mp_type_type },
.name = MP_QSTR_Recorder,
.print = uvoice_recorder_print,
.make_new = uvoice_recorder_new,
.locals_dict = (mp_obj_dict_t *)&uvoice_module_recorder_globals,
};
#endif // MICROPY_PY_AUDIO
| YifuLiu/AliOS-Things | components/py_engine/modules/audio/aos/audio_recorder.c | C | apache-2.0 | 9,713 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if MICROPY_PY_AUDIO
#include "py/builtin.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "ulog/ulog.h"
extern int audio_install_codec_driver();
static bool is_uvoice_inited = false;
#define LOG_TAG "uvoice_snd"
bool get_uvoice_state()
{
return is_uvoice_inited;
}
void set_uvoice_state(bool state)
{
is_uvoice_inited = state;
}
void uvoice_snd_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind)
{
}
STATIC mp_obj_t uvoice_snd_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args)
{
return mp_const_none;
}
STATIC mp_obj_t a2sa_uvoice_snd_init(void)
{
if (is_uvoice_inited == true) {
LOGI(LOG_TAG, "snd card already inited");
return MP_OBJ_NEW_SMALL_INT(0);
}
mp_int_t ret = audio_install_codec_driver();
if (ret != 0) {
LOGE(LOG_TAG, "Failed to install codec driver, ret=%d", ret);
return MP_OBJ_NEW_SMALL_INT(ret);
}
ret = uvoice_init();
if (ret != 0) {
LOGE(LOG_TAG, "Failed to init uvoice, ret=%d", ret);
} else {
set_uvoice_state(true);
}
return MP_OBJ_NEW_SMALL_INT(ret);
}
MP_DEFINE_CONST_FUN_OBJ_0(a2sa_uvoice_snd_init_obj, a2sa_uvoice_snd_init);
static mp_int_t audio_uninstall_codec_driver()
{
return 0;
}
STATIC mp_obj_t a2sa_uvoice_snd_deinit(void)
{
mp_int_t ret = audio_uninstall_codec_driver();
if (ret != 0) {
LOGE(LOG_TAG, "Failed to deinit uvoice, ret=%d", ret);
return MP_OBJ_NEW_SMALL_INT(ret);
}
ret = uvoice_free();
if (ret != 0) {
LOGE(LOG_TAG, "Failed to deinit uvoice, ret=%d", ret);
} else {
set_uvoice_state(false);
}
return MP_OBJ_NEW_SMALL_INT(ret);
}
MP_DEFINE_CONST_FUN_OBJ_0(a2sa_uvoice_snd_deinit_obj, a2sa_uvoice_snd_deinit);
STATIC const mp_rom_map_elem_t uvoice_module_snd_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&a2sa_uvoice_snd_init_obj) },
{ MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&a2sa_uvoice_snd_deinit_obj) },
};
STATIC MP_DEFINE_CONST_DICT(uvoice_module_snd_globals, uvoice_module_snd_globals_table);
const mp_obj_type_t uvoice_snd_type = {
.base = { &mp_type_type },
.name = MP_QSTR_Snd,
.print = uvoice_snd_print,
.make_new = uvoice_snd_new,
.locals_dict = (mp_obj_dict_t *)&uvoice_module_snd_globals,
};
#endif // MICROPY_PY_AUDIO
| YifuLiu/AliOS-Things | components/py_engine/modules/audio/aos/audio_snd.c | C | apache-2.0 | 2,427 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if MICROPY_PY_AUDIO
#include "py/builtin.h"
#include "py/mperrno.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "py/stackctrl.h"
#include "ulog/ulog.h"
#include "utility.h"
#include "uvoice_alios.h"
#include "uvoice_event.h"
#include "uvoice_init.h"
#include "uvoice_tts.h"
#include "uvoice_types.h"
#define LOG_TAG "UVOICE_TTS"
#define TTS_CHECK_PARAMS() \
uvocie_tts_obj_t *self = (uvocie_tts_obj_t *)MP_OBJ_TO_PTR(self_in); \
do { \
if (self == NULL || self->tts_obj == NULL) { \
mp_raise_OSError(EINVAL); \
return mp_const_none; \
} \
} while (0)
#define TTS_RECV_CB_URL (0)
#define TTS_RECV_CB_DATA (1)
#define TTS_RECV_CB_EVENT (2)
extern const mp_obj_type_t uvoice_tts_type;
static mp_obj_t callback_url = MP_OBJ_NULL;
static mp_obj_t callback_data = MP_OBJ_NULL;
static mp_obj_t callback_event = MP_OBJ_NULL;
// this is the actual C-structure for our new object
typedef struct {
// base represents some basic information, like type
mp_obj_base_t base;
// a member created by us
char *modName;
uvoice_tts_t *tts_obj;
} uvocie_tts_obj_t;
void uvoice_tts_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind)
{
uvocie_tts_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "modName(%s)", self->modName);
}
STATIC mp_obj_t uvoice_tts_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args)
{
uvocie_tts_obj_t *uvocie_tts_com_obj = m_new_obj(uvocie_tts_obj_t);
if (!uvocie_tts_com_obj) {
mp_raise_OSError(MP_ENOMEM);
return mp_const_none;
}
memset(uvocie_tts_com_obj, 0, sizeof(uvocie_tts_obj_t));
uvocie_tts_com_obj->base.type = &uvoice_tts_type;
uvocie_tts_com_obj->modName = "uvoice-tts";
return MP_OBJ_FROM_PTR(uvocie_tts_com_obj);
}
STATIC mp_int_t alicoud_tts_event(tts_event_e event, char *info)
{
mp_sched_carg_t *carg = make_cargs(MP_SCHED_CTYPE_DICT);
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_INT, event, NULL, "event");
make_carg_entry(carg, 1, MP_SCHED_ENTRY_TYPE_STR, info, info, "info");
callback_to_python_LoBo(callback_event, mp_const_none, carg);
}
STATIC mp_int_t alicloud_tts_recv_data(uint8_t *buffer, mp_int_t nbytes, mp_int_t index)
{
mp_sched_carg_t *carg = make_cargs(MP_SCHED_CTYPE_DICT);
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_BYTES, nbytes, buffer, "buffer");
make_carg_entry(carg, 1, MP_SCHED_ENTRY_TYPE_INT, nbytes, NULL, "nbytes");
make_carg_entry(carg, 2, MP_SCHED_ENTRY_TYPE_INT, index, NULL, "index");
callback_to_python_LoBo(callback_data, mp_const_none, carg);
}
STATIC mp_int_t alicloud_tts_recv_url(char *tts_url)
{
mp_sched_carg_t *carg = make_cargs(MP_SCHED_CTYPE_SINGLE);
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_STR, strlen(tts_url), tts_url, NULL);
callback_to_python_LoBo(callback_url, mp_const_none, carg);
}
STATIC mp_obj_t uvoice_tts_init(mp_obj_t self_in, mp_obj_t aicloud_type_in, mp_obj_t config_in)
{
TTS_CHECK_PARAMS();
tts_aicloud_type_e aicloud_type = (tts_aicloud_type_e)mp_obj_get_int(aicloud_type_in);
tts_config_t config = { 0 };
config.app_key = (char *)get_str_from_dict(config_in, "app_key");
config.token = (char *)get_str_from_dict(config_in, "token");
config.format = (media_format_t)get_int_from_dict(config_in, "format");
config.sample_rate = get_int_from_dict(config_in, "sample_rate");
config.voice = (char *)get_str_from_dict(config_in, "voice");
config.volume = get_int_from_dict(config_in, "volume");
config.speech_rate = get_int_from_dict(config_in, "speech_rate");
config.pitch_rate = get_int_from_dict(config_in, "pitch_rate");
config.text_encode_type = (tts_encode_type_e)get_int_from_dict(config_in, "text_encode_type");
LOGD(LOG_TAG,
"app_key=%s, token=%s, format=%d, sample_rate=%d, voice=%s, "
"volume=%d, speech_rate=%d, pitch_rate=%d, text_encode_type=%d\n",
config.app_key, config.token, config.format, config.sample_rate, config.voice, config.volume,
config.speech_rate, config.pitch_rate, config.text_encode_type);
mp_int_t status = self->tts_obj->tts_init(aicloud_type, &config);
return mp_obj_new_int(status);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_3(uvoice_tts_init_obj, uvoice_tts_init);
static tts_recv_callback_t recv_cb = {
.event = alicoud_tts_event,
.recv_data = alicloud_tts_recv_data,
.recv_url = alicloud_tts_recv_url,
};
STATIC mp_obj_t uvoice_tts_request(size_t n_args, const mp_obj_t *args)
{
if (n_args < 3) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__, n_args);
return mp_const_none;
}
mp_obj_t self_in = args[0];
TTS_CHECK_PARAMS();
char *text = (char *)mp_obj_str_get_str(args[1]);
int recv_type = mp_obj_get_int(args[2]);
LOGD(LOG_TAG, "text=%s, recv_type=%d", text, recv_type);
mp_int_t status = self->tts_obj->tts_request(text, recv_type, &recv_cb);
return mp_obj_new_int(status);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(uvoice_tts_request_obj, 3, uvoice_tts_request);
STATIC mp_obj_t uvoice_tts_stop(mp_obj_t self_in)
{
TTS_CHECK_PARAMS();
mp_int_t status = self->tts_obj->tts_stop();
return mp_obj_new_int(status);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_tts_stop_obj, uvoice_tts_stop);
STATIC mp_obj_t uvoice_create(mp_obj_t self_in)
{
uvocie_tts_obj_t *self = (uvocie_tts_obj_t *)MP_OBJ_TO_PTR(self_in);
if (self == NULL) {
LOGE(LOG_TAG, "uvocie_tts_obj_t NULL");
return mp_const_none;
}
self->tts_obj = uvoice_tts_create();
if (self->tts_obj == NULL) {
LOGE(LOG_TAG, "create tts failed !\n");
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_tts_create_obj, uvoice_create);
STATIC mp_obj_t uvoice_release(mp_obj_t self_in)
{
TTS_CHECK_PARAMS();
mp_int_t status = uvoice_tts_release(self->tts_obj);
callback_url = mp_const_none;
callback_data = mp_const_none;
callback_event = mp_const_none;
return mp_obj_new_int(status);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uvoice_tts_release_obj, uvoice_release);
STATIC mp_obj_t uvoice_tts_set_callback(mp_obj_t self_in, mp_obj_t type_in, mp_obj_t callback_fun)
{
TTS_CHECK_PARAMS();
if (mp_obj_is_fun(callback_fun) == false) {
LOGE(LOG_TAG, "Obj is not function\n");
return mp_const_none;
}
int type = mp_obj_get_int(type_in);
if (type == TTS_RECV_CB_URL) {
callback_url = callback_fun;
} else if (type == TTS_RECV_CB_DATA) {
callback_data = callback_fun;
} else if (type == TTS_RECV_CB_EVENT) {
callback_event = callback_fun;
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_3(uvoice_tts_set_callback_obj, uvoice_tts_set_callback);
STATIC mp_obj_t uvoice_tts_cb_test(mp_obj_t self_in, mp_obj_t type_in)
{
TTS_CHECK_PARAMS();
int type = mp_obj_get_int(type_in);
LOGD(LOG_TAG, "type=%d", type);
if (type == TTS_RECV_CB_URL) {
alicloud_tts_recv_url("test_url");
} else if (type == TTS_RECV_CB_DATA) {
char buf[8] = { 0, 1, 2, 3, 4, 5, 6, 7 };
alicloud_tts_recv_data(buf, 8, 10);
} else if (type == TTS_RECV_CB_EVENT) {
alicoud_tts_event(10, "test_info");
}
return mp_const_none;
}
STATIC const mp_rom_map_elem_t uvoice_module_tts_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&uvoice_tts_stop_obj) },
{ MP_ROM_QSTR(MP_QSTR_open), MP_ROM_PTR(&uvoice_tts_create_obj) },
{ MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&uvoice_tts_release_obj) },
{ MP_ROM_QSTR(MP_QSTR_on), MP_ROM_PTR(&uvoice_tts_set_callback_obj) },
{ MP_ROM_QSTR(MP_QSTR_prepare), MP_ROM_PTR(&uvoice_tts_init_obj) },
{ MP_ROM_QSTR(MP_QSTR_request), MP_ROM_PTR(&uvoice_tts_request_obj) },
{ MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&uvoice_tts_stop_obj) },
{ MP_ROM_QSTR(MP_QSTR_CB_ENUM_URL), MP_ROM_INT(TTS_RECV_CB_URL) },
{ MP_ROM_QSTR(MP_QSTR_CB_ENUM_DATA), MP_ROM_INT(TTS_RECV_CB_DATA) },
{ MP_ROM_QSTR(MP_QSTR_CB_ENUM_EVENT), MP_ROM_INT(TTS_RECV_CB_EVENT) },
};
STATIC MP_DEFINE_CONST_DICT(uvoice_module_tts_globals, uvoice_module_tts_globals_table);
const mp_obj_type_t uvoice_tts_type = {
.base = { &mp_type_type },
.name = MP_QSTR_Tts,
.print = uvoice_tts_print,
.make_new = uvoice_tts_new,
.locals_dict = (mp_obj_dict_t *)&uvoice_module_tts_globals,
};
#endif // MICROPY_PY_AUDIO
| YifuLiu/AliOS-Things | components/py_engine/modules/audio/aos/audio_tts.c | C | apache-2.0 | 8,815 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if MICROPY_PY_AUDIO
#include "py/builtin.h"
#include "py/mperrno.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "ulog/ulog.h"
extern const mp_obj_type_t uvoice_snd_type;
extern const mp_obj_type_t uvoice_player_type;
extern const mp_obj_type_t uvoice_recorder_type;
extern const mp_obj_type_t uvoice_tts_type;
// this is the actual C-structure for our new object
STATIC const mp_rom_map_elem_t uvoice_locals_dict_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_audio) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_Snd), MP_ROM_PTR(&uvoice_snd_type) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_Player), MP_ROM_PTR(&uvoice_player_type) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_Recorder), MP_ROM_PTR(&uvoice_recorder_type) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_Tts), MP_ROM_PTR(&uvoice_tts_type) },
};
STATIC MP_DEFINE_CONST_DICT(uvoice_locals_dict, uvoice_locals_dict_table);
const mp_obj_module_t mp_module_audio = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&uvoice_locals_dict,
};
MP_REGISTER_MODULE(MP_QSTR_audio, mp_module_audio, MICROPY_PY_AUDIO);
#endif // MICROPY_PY_AUDIO
| YifuLiu/AliOS-Things | components/py_engine/modules/audio/aos/modaudio.c | C | apache-2.0 | 1,168 |
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <stdio.h>
#include <string.h>
#if MICROPY_PY_AUDIO
#include "amr_decoder.h"
#include "audio_hal.h"
#include "board.h"
#include "esp_audio.h"
#include "esp_log.h"
#include "http_stream.h"
#include "i2s_stream.h"
#include "mp3_decoder.h"
#include "py/objstr.h"
#include "py/runtime.h"
#include "utility.h"
#include "vfs_stream.h"
#include "wav_decoder.h"
static const char *TAG = "AUDIO_MOD";
typedef struct _audio_player_obj_t {
mp_obj_base_t base;
mp_obj_t callback;
esp_audio_handle_t player;
audio_board_handle_t board;
esp_audio_state_t state;
} audio_player_obj_t;
STATIC const qstr player_info_fields[] = { MP_QSTR_input, MP_QSTR_codec };
STATIC const MP_DEFINE_STR_OBJ(player_info_input_obj, "http|file stream");
STATIC const MP_DEFINE_STR_OBJ(player_info_codec_obj, "mp3|amr");
STATIC MP_DEFINE_ATTRTUPLE(player_info_obj, player_info_fields, 2, (mp_obj_t)&player_info_input_obj,
(mp_obj_t)&player_info_codec_obj);
STATIC mp_obj_t player_info(void)
{
return (mp_obj_t)&player_info_obj;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(audio_player_info_obj, player_info);
STATIC void audio_state_cb(esp_audio_state_t *state, void *ctx)
{
audio_player_obj_t *self = (audio_player_obj_t *)ctx;
memcpy(&self->state, state, sizeof(esp_audio_state_t));
callback_to_python_LoBo(self->callback, MP_OBJ_NEW_SMALL_INT(state->status), NULL);
}
STATIC int _http_stream_event_handle(http_stream_event_msg_t *msg)
{
if (msg->event_id == HTTP_STREAM_RESOLVE_ALL_TRACKS) {
return ESP_OK;
}
if (msg->event_id == HTTP_STREAM_FINISH_TRACK) {
return http_stream_next_track(msg->el);
}
if (msg->event_id == HTTP_STREAM_FINISH_PLAYLIST) {
return http_stream_restart(msg->el);
}
return ESP_OK;
}
STATIC esp_audio_handle_t audio_player_create(audio_player_obj_t *self)
{
// init audio board
audio_board_handle_t board = audio_board_init();
audio_hal_ctrl_codec(board->audio_hal, AUDIO_HAL_CODEC_MODE_BOTH, AUDIO_HAL_CTRL_START);
self->board = board;
// init player
esp_audio_cfg_t cfg = DEFAULT_ESP_AUDIO_CONFIG();
cfg.vol_handle = board->audio_hal;
cfg.vol_set = (audio_volume_set)audio_hal_set_volume;
cfg.vol_get = (audio_volume_get)audio_hal_get_volume;
cfg.resample_rate = 44100;
cfg.prefer_type = ESP_AUDIO_PREFER_MEM;
esp_audio_handle_t player = esp_audio_create(&cfg);
// add input stream
// fatfs stream
vfs_stream_cfg_t fs_reader = VFS_STREAM_CFG_DEFAULT();
fs_reader.type = AUDIO_STREAM_READER;
esp_audio_input_stream_add(player, vfs_stream_init(&fs_reader));
// http stream
http_stream_cfg_t http_cfg = HTTP_STREAM_CFG_DEFAULT();
http_cfg.event_handle = _http_stream_event_handle;
http_cfg.type = AUDIO_STREAM_READER;
http_cfg.enable_playlist_parser = true;
audio_element_handle_t http_stream_reader = http_stream_init(&http_cfg);
esp_audio_input_stream_add(player, http_stream_reader);
// add decoder
// mp3
mp3_decoder_cfg_t mp3_dec_cfg = DEFAULT_MP3_DECODER_CONFIG();
esp_audio_codec_lib_add(player, AUDIO_CODEC_TYPE_DECODER, mp3_decoder_init(&mp3_dec_cfg));
// amr
// amr_decoder_cfg_t amr_dec_cfg = DEFAULT_AMR_DECODER_CONFIG();
// esp_audio_codec_lib_add(player, AUDIO_CODEC_TYPE_DECODER, amr_decoder_init(&amr_dec_cfg));
// wav
wav_decoder_cfg_t wav_dec_cfg = DEFAULT_WAV_DECODER_CONFIG();
esp_audio_codec_lib_add(player, AUDIO_CODEC_TYPE_DECODER, wav_decoder_init(&wav_dec_cfg));
// Create writers and add to esp_audio
i2s_stream_cfg_t i2s_writer = I2S_STREAM_CFG_DEFAULT();
i2s_writer.type = AUDIO_STREAM_WRITER;
i2s_writer.i2s_config.sample_rate = 44100;
esp_audio_output_stream_add(player, i2s_stream_init(&i2s_writer));
return player;
}
STATIC int audio_player_destroy(audio_player_obj_t *self)
{
esp_err_t err = ESP_FAIL;
if (self == NULL) {
return ESP_ERR_INVALID_ARG;
}
err = audio_board_deinit(self->board);
if (err != ESP_OK) {
ESP_LOGE(TAG, "audio_board_deinit Failed");
return err;
} else {
self->board = NULL;
}
err = esp_audio_destroy(self->player);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_audio_destroy Failed");
return err;
} else {
self->player = NULL;
}
return err;
}
STATIC mp_obj_t audio_player_open(mp_obj_t self_in)
{
audio_player_obj_t *self = (audio_player_obj_t *)self_in;
if (self->player == NULL) {
self->player = audio_player_create(self);
}
return mp_obj_new_int(0);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(audio_player_open_obj, audio_player_open);
STATIC mp_obj_t audio_player_close(mp_obj_t self_in)
{
audio_player_obj_t *self = (audio_player_obj_t *)self_in;
int err = ESP_ERR_AUDIO_FAIL;
if (self != NULL) {
err = audio_player_destroy(self);
self->player = NULL;
}
return mp_obj_new_int(err);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(audio_player_close_obj, audio_player_close);
STATIC mp_obj_t audio_player_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args)
{
mp_arg_check_num(n_args, n_kw, 0, 1, false);
audio_player_obj_t *self = m_new_obj_with_finaliser(audio_player_obj_t);
memset(self, 0, sizeof(audio_player_obj_t));
self->base.type = type;
self->callback = mp_const_none;
return MP_OBJ_FROM_PTR(self);
}
STATIC mp_obj_t audio_player_play_helper(audio_player_obj_t *self, mp_uint_t n_args, const mp_obj_t *pos_args,
mp_map_t *kw_args)
{
enum {
ARG_uri,
ARG_pos,
ARG_sync,
};
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_uri, MP_ARG_REQUIRED | MP_ARG_OBJ, { .u_obj = mp_const_none } },
{ MP_QSTR_pos, MP_ARG_INT, { .u_int = 0 } },
{ MP_QSTR_sync, MP_ARG_BOOL, { .u_bool = false } },
};
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);
if (args[ARG_uri].u_obj != mp_const_none) {
const char *uri = mp_obj_str_get_str(args[ARG_uri].u_obj);
int pos = args[ARG_pos].u_int;
esp_audio_state_t state = { 0 };
esp_audio_state_get(self->player, &state);
if (state.status == AUDIO_STATUS_RUNNING || state.status == AUDIO_STATUS_PAUSED) {
esp_audio_stop(self->player, TERMINATION_TYPE_NOW);
int wait = 20;
esp_audio_state_get(self->player, &state);
while (wait-- && (state.status == AUDIO_STATUS_RUNNING || state.status == AUDIO_STATUS_PAUSED)) {
vTaskDelay(pdMS_TO_TICKS(100));
esp_audio_state_get(self->player, &state);
}
}
esp_audio_callback_set(self->player, audio_state_cb, self);
if (args[ARG_sync].u_bool == false) {
self->state.status = AUDIO_STATUS_RUNNING;
self->state.err_msg = ESP_ERR_AUDIO_NO_ERROR;
return mp_obj_new_int(esp_audio_play(self->player, AUDIO_CODEC_TYPE_DECODER, uri, pos));
} else {
return mp_obj_new_int(esp_audio_sync_play(self->player, uri, pos));
}
} else {
return mp_obj_new_int(ESP_ERR_AUDIO_INVALID_PARAMETER);
}
}
STATIC mp_obj_t audio_player_play(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args)
{
return audio_player_play_helper(args[0], n_args - 1, args + 1, kw_args);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(audio_player_play_obj, 1, audio_player_play);
STATIC mp_obj_t audio_player_stop_helper(audio_player_obj_t *self, mp_uint_t n_args, const mp_obj_t *pos_args,
mp_map_t *kw_args)
{
enum {
ARG_termination,
};
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_termination, MP_ARG_INT, { .u_int = TERMINATION_TYPE_NOW } },
};
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);
return mp_obj_new_int(esp_audio_stop(self->player, args[ARG_termination].u_int));
}
STATIC mp_obj_t audio_player_stop(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args)
{
return audio_player_stop_helper(args[0], n_args - 1, args + 1, kw_args);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(audio_player_stop_obj, 1, audio_player_stop);
STATIC mp_obj_t audio_player_pause(mp_obj_t self_in)
{
audio_player_obj_t *self = self_in;
return mp_obj_new_int(esp_audio_pause(self->player));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(audio_player_pause_obj, audio_player_pause);
STATIC mp_obj_t audio_player_resume(mp_obj_t self_in)
{
audio_player_obj_t *self = self_in;
return mp_obj_new_int(esp_audio_resume(self->player));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(audio_player_resume_obj, audio_player_resume);
STATIC mp_obj_t audio_player_seek(mp_obj_t self_in, mp_obj_t seek_time_sec_in)
{
audio_player_obj_t *self = self_in;
int seek_time_sec = mp_obj_get_int(seek_time_sec_in);
return mp_obj_new_int(esp_audio_seek(self->player, seek_time_sec));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(audio_player_seek_obj, audio_player_seek);
STATIC mp_obj_t audio_player_vol_helper(audio_player_obj_t *self, mp_uint_t n_args, const mp_obj_t *pos_args,
mp_map_t *kw_args)
{
enum {
ARG_vol,
};
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_vol, MP_ARG_INT, { .u_int = 0xffff } },
};
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);
if (args[ARG_vol].u_int == 0xffff) {
int vol = 0;
esp_audio_vol_get(self->player, &vol);
return mp_obj_new_int(vol);
} else {
if (args[ARG_vol].u_int >= 0 && args[ARG_vol].u_int <= 100) {
return mp_obj_new_int(esp_audio_vol_set(self->player, args[ARG_vol].u_int));
} else {
return mp_obj_new_int(ESP_ERR_AUDIO_INVALID_PARAMETER);
}
}
}
STATIC mp_obj_t audio_player_vol(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args)
{
return audio_player_vol_helper(args[0], n_args - 1, args + 1, kw_args);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(audio_player_vol_obj, 1, audio_player_vol);
STATIC mp_obj_t audio_player_get_vol(mp_obj_t self_in)
{
audio_player_obj_t *self = self_in;
int vol = 0;
esp_audio_vol_get(self->player, &vol);
return mp_obj_new_int(vol);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(audio_player_get_vol_obj, audio_player_get_vol);
STATIC mp_obj_t audio_player_set_vol(mp_obj_t self_in, mp_obj_t vol)
{
audio_player_obj_t *self = self_in;
int volume = mp_obj_get_int(vol);
return mp_obj_new_int(esp_audio_vol_set(self->player, volume));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(audio_player_set_vol_obj, audio_player_set_vol);
STATIC mp_obj_t audio_player_state(mp_obj_t self_in)
{
audio_player_obj_t *self = self_in;
return mp_obj_new_int(self->state.status);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(audio_player_state_obj, audio_player_state);
STATIC mp_obj_t audio_player_time(mp_obj_t self_in)
{
audio_player_obj_t *self = self_in;
int time = -1;
int err = esp_audio_time_get(self->player, &time);
if (err == ESP_ERR_AUDIO_NO_ERROR) {
return mp_obj_new_int(time);
} else {
return mp_const_none;
}
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(audio_player_time_obj, audio_player_time);
STATIC mp_obj_t audio_player_duration(mp_obj_t self_in)
{
audio_player_obj_t *self = self_in;
int duration = 0;
int err = esp_audio_duration_get(self->player, &duration);
if (err == ESP_ERR_AUDIO_NO_ERROR) {
return mp_obj_new_int(duration);
} else {
return mp_obj_new_int(-err);
}
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(audio_player_duration_obj, audio_player_duration);
STATIC mp_obj_t audio_player_on(mp_obj_t self_in, mp_obj_t callback_in)
{
audio_player_obj_t *self = self_in;
if (self == NULL) {
return mp_obj_new_int(-ESP_ERR_AUDIO_NOT_READY);
} else {
self->callback = callback_in;
return mp_obj_new_int(ESP_ERR_AUDIO_NO_ERROR);
};
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(audio_player_on_obj, audio_player_on);
STATIC const mp_rom_map_elem_t player_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_info), MP_ROM_PTR(&audio_player_info_obj) },
{ MP_ROM_QSTR(MP_QSTR_open), MP_ROM_PTR(&audio_player_open_obj) },
{ MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&audio_player_close_obj) },
{ MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&audio_player_play_obj) },
{ MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&audio_player_stop_obj) },
{ MP_ROM_QSTR(MP_QSTR_pause), MP_ROM_PTR(&audio_player_pause_obj) },
{ MP_ROM_QSTR(MP_QSTR_resume), MP_ROM_PTR(&audio_player_resume_obj) },
{ MP_ROM_QSTR(MP_QSTR_seek), MP_ROM_PTR(&audio_player_seek_obj) },
{ MP_ROM_QSTR(MP_QSTR_vol), MP_ROM_PTR(&audio_player_vol_obj) },
{ MP_ROM_QSTR(MP_QSTR_getVolume), MP_ROM_PTR(&audio_player_get_vol_obj) },
{ MP_ROM_QSTR(MP_QSTR_setVolume), MP_ROM_PTR(&audio_player_set_vol_obj) },
{ MP_ROM_QSTR(MP_QSTR_getState), MP_ROM_PTR(&audio_player_state_obj) },
{ MP_ROM_QSTR(MP_QSTR_getPosition), MP_ROM_PTR(&audio_player_time_obj) },
{ MP_ROM_QSTR(MP_QSTR_getDuration), MP_ROM_PTR(&audio_player_duration_obj) },
{ MP_ROM_QSTR(MP_QSTR_on), MP_ROM_PTR(&audio_player_on_obj) },
// esp_audio_status_t
{ MP_ROM_QSTR(MP_QSTR_STATUS_UNKNOWN), MP_ROM_INT(AUDIO_STATUS_UNKNOWN) },
{ MP_ROM_QSTR(MP_QSTR_STATUS_RUNNING), MP_ROM_INT(AUDIO_STATUS_RUNNING) },
{ MP_ROM_QSTR(MP_QSTR_STATUS_PAUSED), MP_ROM_INT(AUDIO_STATUS_PAUSED) },
{ MP_ROM_QSTR(MP_QSTR_STATUS_STOPPED), MP_ROM_INT(AUDIO_STATUS_STOPPED) },
{ MP_ROM_QSTR(MP_QSTR_STATUS_FINISHED), MP_ROM_INT(AUDIO_STATUS_FINISHED) },
{ MP_ROM_QSTR(MP_QSTR_STATUS_ERROR), MP_ROM_INT(AUDIO_STATUS_ERROR) },
// audio_termination_type
{ MP_ROM_QSTR(MP_QSTR_TERMINATION_NOW), MP_ROM_INT(TERMINATION_TYPE_NOW) },
{ MP_ROM_QSTR(MP_QSTR_TERMINATION_DONE), MP_ROM_INT(TERMINATION_TYPE_DONE) },
};
STATIC MP_DEFINE_CONST_DICT(player_locals_dict, player_locals_dict_table);
const mp_obj_type_t audio_player_type = {
{ &mp_type_type },
.name = MP_QSTR_Player,
.make_new = audio_player_make_new,
.locals_dict = (mp_obj_dict_t *)&player_locals_dict,
};
#endif // MICROPY_PY_AUDIO | YifuLiu/AliOS-Things | components/py_engine/modules/audio/esp32/audio_player.c | C | apache-2.0 | 15,749 |
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <stdio.h>
#include <string.h>
#if MICROPY_PY_AUDIO
#include "amrnb_encoder.h"
#include "amrwb_encoder.h"
#include "audio_hal.h"
#include "audio_pipeline.h"
#include "board.h"
#include "filter_resample.h"
#include "i2s_stream.h"
#include "py/objstr.h"
#include "py/runtime.h"
#include "raw_stream.h"
#include "vfs_stream.h"
#include "wav_encoder.h"
enum {
PCM,
AMR,
AMR_WB,
WAV,
MP3
};
typedef struct _audio_recorder_obj_t {
mp_obj_base_t base;
audio_pipeline_handle_t pipeline;
audio_element_handle_t i2s_stream;
audio_element_handle_t filter;
audio_element_handle_t encoder;
audio_element_handle_t out_stream;
esp_timer_handle_t timer;
mp_obj_t end_cb;
} audio_recorder_obj_t;
STATIC mp_obj_t audio_recorder_stop(mp_obj_t self_in);
STATIC mp_obj_t audio_recorder_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args)
{
mp_arg_check_num(n_args, n_kw, 0, 0, false);
audio_recorder_obj_t *self = m_new_obj_with_finaliser(audio_recorder_obj_t);
self->base.type = type;
return MP_OBJ_FROM_PTR(self);
}
STATIC audio_element_handle_t audio_recorder_create_filter(int encoder_type)
{
rsp_filter_cfg_t rsp_cfg = DEFAULT_RESAMPLE_FILTER_CONFIG();
rsp_cfg.src_rate = 48000;
rsp_cfg.src_ch = 2;
rsp_cfg.dest_ch = 1;
rsp_cfg.task_core = 1;
switch (encoder_type) {
case PCM:
{
rsp_cfg.dest_rate = 16000;
break;
}
case AMR:
{
rsp_cfg.dest_rate = 8000;
break;
}
case AMR_WB:
{
rsp_cfg.dest_rate = 16000;
break;
}
case WAV:
{
rsp_cfg.dest_rate = 16000;
break;
}
default:
break;
}
return rsp_filter_init(&rsp_cfg);
}
STATIC audio_element_handle_t audio_recorder_create_encoder(int encoder_type)
{
audio_element_handle_t encoder = NULL;
switch (encoder_type) {
case AMR:
{
amrnb_encoder_cfg_t amr_enc_cfg = DEFAULT_AMRNB_ENCODER_CONFIG();
amr_enc_cfg.task_core = 1;
encoder = amrnb_encoder_init(&amr_enc_cfg);
break;
}
case AMR_WB:
{
amrwb_encoder_cfg_t amrwb_enc_cfg = DEFAULT_AMRWB_ENCODER_CONFIG();
amrwb_enc_cfg.task_core = 1;
encoder = amrwb_encoder_init(&amrwb_enc_cfg);
break;
}
case WAV:
{
wav_encoder_cfg_t wav_cfg = DEFAULT_WAV_ENCODER_CONFIG();
wav_cfg.task_core = 1;
encoder = wav_encoder_init(&wav_cfg);
break;
}
default:
break;
}
return encoder;
}
STATIC audio_element_handle_t audio_recorder_create_outstream(const char *uri)
{
audio_element_handle_t out_stream = NULL;
if (strstr(uri, "/sdcard/") != NULL || strstr(uri, "/data/") != NULL) {
vfs_stream_cfg_t vfs_cfg = VFS_STREAM_CFG_DEFAULT();
vfs_cfg.type = AUDIO_STREAM_WRITER;
vfs_cfg.task_core = 1;
out_stream = vfs_stream_init(&vfs_cfg);
} else if (strstr(uri, "/spiffs/") != NULL) {
// TODO: spiffs
} else {
raw_stream_cfg_t raw_cfg = RAW_STREAM_CFG_DEFAULT();
raw_cfg.type = AUDIO_STREAM_WRITER;
out_stream = raw_stream_init(&raw_cfg);
}
audio_element_set_uri(out_stream, uri);
return out_stream;
}
STATIC void audio_recorder_create(audio_recorder_obj_t *self, const char *uri, int format, int sample_rate)
{
// init audio board
audio_board_handle_t board_handle = audio_board_init();
audio_hal_ctrl_codec(board_handle->audio_hal, AUDIO_HAL_CODEC_MODE_BOTH, AUDIO_HAL_CTRL_START);
// pipeline
audio_pipeline_cfg_t pipeline_cfg = DEFAULT_AUDIO_PIPELINE_CONFIG();
self->pipeline = audio_pipeline_init(&pipeline_cfg);
// I2S
i2s_stream_cfg_t i2s_cfg = I2S_STREAM_CFG_DEFAULT();
i2s_cfg.type = AUDIO_STREAM_READER;
i2s_cfg.uninstall_drv = false;
i2s_cfg.i2s_config.sample_rate = sample_rate;
i2s_cfg.task_core = 1;
i2s_cfg.i2s_config.mode = I2S_MODE_MASTER | I2S_MODE_RX;
#ifdef M5STACK_CORE2
i2s_cfg.i2s_config.mode |= I2S_MODE_PDM;
#endif
i2s_cfg.i2s_config.channel_format = I2S_CHANNEL_FMT_ONLY_LEFT;
self->i2s_stream = i2s_stream_init(&i2s_cfg);
// filter
// passthrough filter to save cpu load
// self->filter = audio_recorder_create_filter(format);
self->filter = NULL;
// encoder
self->encoder = audio_recorder_create_encoder(format);
// out stream
self->out_stream = audio_recorder_create_outstream(uri);
// register to pipeline
audio_pipeline_register(self->pipeline, self->i2s_stream, "i2s");
if (self->filter) {
audio_pipeline_register(self->pipeline, self->filter, "filter");
}
if (self->encoder) {
audio_pipeline_register(self->pipeline, self->encoder, "encoder");
}
audio_pipeline_register(self->pipeline, self->out_stream, "out");
if (format == WAV) {
audio_element_info_t out_stream_info;
audio_element_getinfo(self->out_stream, &out_stream_info);
out_stream_info.sample_rates = sample_rate;
out_stream_info.channels = 1;
audio_element_setinfo(self->out_stream, &out_stream_info);
}
// link
if (self->filter && self->encoder) {
const char *link_tag[4] = { "i2s", "filter", "encoder", "out" };
audio_pipeline_link(self->pipeline, &link_tag[0], 4);
} else if (self->filter) {
const char *link_tag[3] = { "i2s", "filter", "out" };
audio_pipeline_link(self->pipeline, &link_tag[0], 3);
} else if (self->encoder) {
const char *link_tag[3] = { "i2s", "encoder", "out" };
audio_pipeline_link(self->pipeline, &link_tag[0], 3);
} else {
const char *link_tag[2] = { "i2s", "out" };
audio_pipeline_link(self->pipeline, &link_tag[0], 2);
}
}
static void audio_recorder_maxtime_cb(void *arg)
{
audio_recorder_stop(arg);
audio_recorder_obj_t *self = (audio_recorder_obj_t *)arg;
if (self->end_cb != mp_const_none) {
mp_sched_schedule(self->end_cb, self);
}
}
STATIC mp_obj_t audio_recorder_start(mp_uint_t n_args, const mp_obj_t *args_in, mp_map_t *kw_args)
{
enum {
ARG_uri,
ARG_format,
ARG_maxtime,
ARG_endcb,
ARG_sample_rate
};
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_uri, MP_ARG_REQUIRED | MP_ARG_OBJ, { .u_obj = mp_const_none } },
{ MP_QSTR_format, MP_ARG_INT, { .u_int = PCM } },
{ MP_QSTR_maxtime, MP_ARG_INT, { .u_int = 0 } },
{ MP_QSTR_endcb, MP_ARG_OBJ, { .u_obj = mp_const_none } },
{ MP_QSTR_sr, MP_ARG_INT, { .u_int = 8000 } },
};
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
audio_recorder_obj_t *self = args_in[0];
mp_arg_parse_all(n_args - 1, args_in + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
if (self->pipeline != NULL) {
return mp_obj_new_bool(false);
}
int format = args[ARG_format].u_int;
int sample_rate = args[ARG_sample_rate].u_int;
if (format == AMR_WB) {
sample_rate = 16000;
}
audio_recorder_create(self, mp_obj_str_get_str(args[ARG_uri].u_obj), format, sample_rate);
if (audio_pipeline_run(self->pipeline) == ESP_OK) {
if (args[ARG_maxtime].u_int > 0) {
esp_timer_create_args_t timer_conf = {
.callback = &audio_recorder_maxtime_cb,
.name = "maxtime",
.arg = self,
};
esp_timer_create(&timer_conf, &self->timer);
esp_timer_start_once(self->timer, args[ARG_maxtime].u_int * 1000000);
self->end_cb = args[ARG_endcb].u_obj;
}
return mp_obj_new_bool(true);
} else {
return mp_obj_new_bool(false);
}
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(audio_recorder_start_obj, 1, audio_recorder_start);
STATIC mp_obj_t audio_recorder_stop(mp_obj_t self_in)
{
audio_recorder_obj_t *self = self_in;
if (self->timer) {
esp_timer_stop(self->timer);
esp_timer_delete(self->timer);
self->timer = NULL;
}
if (self->pipeline != NULL) {
audio_pipeline_stop(self->pipeline);
audio_pipeline_wait_for_stop(self->pipeline);
audio_pipeline_deinit(self->pipeline);
} else {
return mp_obj_new_bool(false);
}
self->i2s_stream = NULL;
self->filter = NULL;
self->encoder = NULL;
self->out_stream = NULL;
self->pipeline = NULL;
return mp_obj_new_bool(true);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(audio_recorder_stop_obj, audio_recorder_stop);
STATIC mp_obj_t audio_recorder_is_running(mp_obj_t self_in)
{
audio_recorder_obj_t *self = self_in;
return mp_obj_new_bool(self->pipeline != NULL);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(audio_recorder_is_running_obj, audio_recorder_is_running);
STATIC const mp_rom_map_elem_t recorder_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_start), MP_ROM_PTR(&audio_recorder_start_obj) },
{ MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&audio_recorder_stop_obj) },
{ MP_ROM_QSTR(MP_QSTR_is_running), MP_ROM_PTR(&audio_recorder_is_running_obj) },
{ MP_ROM_QSTR(MP_QSTR_PCM), MP_ROM_INT(PCM) },
{ MP_ROM_QSTR(MP_QSTR_AMR), MP_ROM_INT(AMR) },
{ MP_ROM_QSTR(MP_QSTR_AMR_WB), MP_ROM_INT(AMR_WB) },
{ MP_ROM_QSTR(MP_QSTR_WAV), MP_ROM_INT(WAV) },
{ MP_ROM_QSTR(MP_QSTR_MP3), MP_ROM_INT(MP3) },
};
STATIC MP_DEFINE_CONST_DICT(recorder_locals_dict, recorder_locals_dict_table);
const mp_obj_type_t audio_recorder_type = {
{ &mp_type_type },
.name = MP_QSTR_Recorder,
.make_new = audio_recorder_make_new,
.locals_dict = (mp_obj_dict_t *)&recorder_locals_dict,
};
#endif // MICROPY_PY_AUDIO | YifuLiu/AliOS-Things | components/py_engine/modules/audio/esp32/audio_recorder.c | C | apache-2.0 | 11,062 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if MICROPY_PY_AUDIO
#include "py/builtin.h"
#include "py/obj.h"
#include "py/runtime.h"
#define LOG_TAG "audio_snd"
void audio_snd_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind)
{
}
STATIC mp_obj_t audio_snd_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args)
{
return mp_const_none;
}
STATIC mp_obj_t audio_snd_init(void)
{
mp_int_t ret = 0;
return MP_OBJ_NEW_SMALL_INT(ret);
}
MP_DEFINE_CONST_FUN_OBJ_0(audio_snd_init_obj, audio_snd_init);
STATIC mp_obj_t audio_snd_deinit(void)
{
mp_int_t ret = 0;
return MP_OBJ_NEW_SMALL_INT(ret);
}
MP_DEFINE_CONST_FUN_OBJ_0(audio_snd_deinit_obj, audio_snd_deinit);
STATIC const mp_rom_map_elem_t audio_module_snd_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&audio_snd_init_obj) },
{ MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audio_snd_deinit_obj) },
};
STATIC MP_DEFINE_CONST_DICT(audio_module_snd_globals, audio_module_snd_globals_table);
const mp_obj_type_t audio_snd_type = {
.base = { &mp_type_type },
.name = MP_QSTR_Snd,
.print = audio_snd_print,
.make_new = audio_snd_new,
.locals_dict = (mp_obj_dict_t *)&audio_module_snd_globals,
};
#endif // MICROPY_PY_AUDIO
| YifuLiu/AliOS-Things | components/py_engine/modules/audio/esp32/audio_snd.c | C | apache-2.0 | 1,295 |
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <stdio.h>
#include <string.h>
#if MICROPY_PY_AUDIO
#include "modaudio.h"
#include "py/objstr.h"
#include "py/runtime.h"
#include "esp_audio.h"
#include "audio_mem.h"
const char *verno = "0.5-beta1";
STATIC mp_obj_t audio_mem_info(void)
{
#ifdef CONFIG_SPIRAM_BOOT_INIT
mp_obj_dict_t *dict = mp_obj_new_dict(3);
mp_obj_dict_store(dict, MP_ROM_QSTR(MP_QSTR_mem_total), MP_OBJ_TO_PTR(mp_obj_new_int(esp_get_free_heap_size())));
mp_obj_dict_store(dict, MP_ROM_QSTR(MP_QSTR_inter), MP_OBJ_TO_PTR(mp_obj_new_int(heap_caps_get_free_size(MALLOC_CAP_INTERNAL))));
mp_obj_dict_store(dict, MP_ROM_QSTR(MP_QSTR_dram), MP_OBJ_TO_PTR(mp_obj_new_int(heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT))));
#else
mp_obj_dict_t *dict = mp_obj_new_dict(1);
mp_obj_dict_store(dict, MP_ROM_QSTR(MP_QSTR_mem_total), MP_OBJ_TO_PTR(mp_obj_new_int(esp_get_free_heap_size())));
#endif
return dict;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(audio_mem_info_obj, audio_mem_info);
STATIC mp_obj_t audio_mod_verno(void)
{
return mp_obj_new_str(verno, strlen(verno));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(audio_mod_verno_obj, audio_mod_verno);
extern const mp_obj_type_t audio_snd_type;
extern const mp_obj_type_t audio_player_type;
extern const mp_obj_type_t audio_recorder_type;
STATIC const mp_rom_map_elem_t audio_module_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_audio) },
{ MP_ROM_QSTR(MP_QSTR_mem_info), MP_ROM_PTR(&audio_mem_info_obj) },
{ MP_ROM_QSTR(MP_QSTR_verno), MP_ROM_PTR(&audio_mod_verno_obj) },
{ MP_ROM_QSTR(MP_QSTR_Snd), MP_ROM_PTR(&audio_snd_type) },
{ MP_ROM_QSTR(MP_QSTR_Player), MP_ROM_PTR(&audio_player_type) },
{ MP_ROM_QSTR(MP_QSTR_Recorder), MP_ROM_PTR(&audio_recorder_type) },
// audio_err_t
{ MP_ROM_QSTR(MP_QSTR_AUDIO_OK), MP_ROM_INT(ESP_ERR_AUDIO_NO_ERROR) },
{ MP_ROM_QSTR(MP_QSTR_AUDIO_FAIL), MP_ROM_INT(ESP_ERR_AUDIO_FAIL) },
{ MP_ROM_QSTR(MP_QSTR_AUDIO_NO_INPUT_STREAM), MP_ROM_INT(ESP_ERR_AUDIO_NO_INPUT_STREAM) },
{ MP_ROM_QSTR(MP_QSTR_AUDIO_NO_OUTPUT_STREAM), MP_ROM_INT(ESP_ERR_AUDIO_NO_OUTPUT_STREAM) },
{ MP_ROM_QSTR(MP_QSTR_AUDIO_NO_CODEC), MP_ROM_INT(ESP_ERR_AUDIO_NO_CODEC) },
{ MP_ROM_QSTR(MP_QSTR_AUDIO_HAL_FAIL), MP_ROM_INT(ESP_ERR_AUDIO_HAL_FAIL) },
{ MP_ROM_QSTR(MP_QSTR_AUDIO_MEMORY_LACK), MP_ROM_INT(ESP_ERR_AUDIO_MEMORY_LACK) },
{ MP_ROM_QSTR(MP_QSTR_AUDIO_INVALID_URI), MP_ROM_INT(ESP_ERR_AUDIO_INVALID_URI) },
{ MP_ROM_QSTR(MP_QSTR_AUDIO_INVALID_PATH), MP_ROM_INT(ESP_ERR_AUDIO_INVALID_PATH) },
{ MP_ROM_QSTR(MP_QSTR_AUDIO_INVALID_PARAMETER), MP_ROM_INT(ESP_ERR_AUDIO_INVALID_PARAMETER) },
{ MP_ROM_QSTR(MP_QSTR_AUDIO_NOT_READY), MP_ROM_INT(ESP_ERR_AUDIO_NOT_READY) },
{ MP_ROM_QSTR(MP_QSTR_AUDIO_NOT_SUPPORT), MP_ROM_INT(ESP_ERR_AUDIO_NOT_SUPPORT) },
{ MP_ROM_QSTR(MP_QSTR_AUDIO_TIMEOUT), MP_ROM_INT(ESP_ERR_AUDIO_TIMEOUT) },
{ MP_ROM_QSTR(MP_QSTR_AUDIO_ALREADY_EXISTS), MP_ROM_INT(ESP_ERR_AUDIO_ALREADY_EXISTS) },
{ MP_ROM_QSTR(MP_QSTR_AUDIO_LINK_FAIL), MP_ROM_INT(ESP_ERR_AUDIO_LINK_FAIL) },
{ MP_ROM_QSTR(MP_QSTR_AUDIO_UNKNOWN), MP_ROM_INT(ESP_ERR_AUDIO_UNKNOWN) },
{ MP_ROM_QSTR(MP_QSTR_AUDIO_OPEN), MP_ROM_INT(ESP_ERR_AUDIO_OPEN) },
{ MP_ROM_QSTR(MP_QSTR_AUDIO_INPUT), MP_ROM_INT(ESP_ERR_AUDIO_INPUT) },
{ MP_ROM_QSTR(MP_QSTR_AUDIO_PROCESS), MP_ROM_INT(ESP_ERR_AUDIO_PROCESS) },
{ MP_ROM_QSTR(MP_QSTR_AUDIO_OUTPUT), MP_ROM_INT(ESP_ERR_AUDIO_OUTPUT) },
{ MP_ROM_QSTR(MP_QSTR_AUDIO_CLOSE), MP_ROM_INT(ESP_ERR_AUDIO_CLOSE) },
};
STATIC MP_DEFINE_CONST_DICT(audio_module_globals, audio_module_globals_table);
const mp_obj_module_t mp_module_audio = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&audio_module_globals,
};
MP_REGISTER_MODULE(MP_QSTR_audio, mp_module_audio, MICROPY_PY_AUDIO);
#endif // MICROPY_PY_AUDIO
| YifuLiu/AliOS-Things | components/py_engine/modules/audio/esp32/modaudio.c | C | apache-2.0 | 5,101 |
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 __MODAUDIO_H_
#define __MODAUDIO_H_
#include "py/obj.h"
#endif //__MODAUDIO_H_
| YifuLiu/AliOS-Things | components/py_engine/modules/audio/esp32/modaudio.h | C | apache-2.0 | 1,325 |
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 <fcntl.h>
#include <stdio.h>
#include <string.h>
#include "errno.h"
#if MICROPY_PY_AUDIO
#include <sys/stat.h>
#include <sys/types.h>
#include "audio_element.h"
#include "audio_error.h"
#include "audio_mem.h"
#include "esp_log.h"
#include "extmod/vfs_fat.h"
#include "py/builtin.h"
#include "py/runtime.h"
#include "py/stream.h"
#include "vfs_stream.h"
#include "wav_head.h"
#define FILE_WAV_SUFFIX_TYPE "wav"
#define FILE_OPUS_SUFFIX_TYPE "opus"
#define FILE_AMR_SUFFIX_TYPE "amr"
#define FILE_AMRWB_SUFFIX_TYPE "Wamr"
static const char *TAG = "VFS_STREAM";
// whether to enable file read from LFS, HaaS Python need to set to 1
#define AUDIO_FILE_LFS (1)
typedef enum {
STREAM_TYPE_UNKNOW,
STREAM_TYPE_WAV,
STREAM_TYPE_OPUS,
STREAM_TYPE_AMR,
STREAM_TYPE_AMRWB,
} wr_stream_type_t;
typedef struct vfs_stream {
audio_stream_type_t type;
int block_size;
bool is_open;
#if AUDIO_FILE_LFS
int file;
#else
mp_obj_t file;
#endif
wr_stream_type_t w_type;
} vfs_stream_t;
static wr_stream_type_t get_type(const char *str)
{
char *relt = strrchr(str, '.');
if (relt != NULL) {
relt++;
ESP_LOGD(TAG, "result = %s", relt);
if (strncasecmp(relt, FILE_WAV_SUFFIX_TYPE, 3) == 0) {
return STREAM_TYPE_WAV;
} else if (strncasecmp(relt, FILE_OPUS_SUFFIX_TYPE, 4) == 0) {
return STREAM_TYPE_OPUS;
} else if (strncasecmp(relt, FILE_AMR_SUFFIX_TYPE, 3) == 0) {
return STREAM_TYPE_AMR;
} else if (strncasecmp(relt, FILE_AMRWB_SUFFIX_TYPE, 4) == 0) {
return STREAM_TYPE_AMRWB;
} else {
return STREAM_TYPE_UNKNOW;
}
} else {
return STREAM_TYPE_UNKNOW;
}
}
#if AUDIO_FILE_LFS
static esp_err_t _lfs_open(audio_element_handle_t self)
{
vfs_stream_t *vfs = (vfs_stream_t *)audio_element_getdata(self);
audio_element_info_t info;
char *uri = audio_element_get_uri(self);
if (uri == NULL) {
ESP_LOGE(TAG, "Error, uri is not set");
return ESP_FAIL;
}
ESP_LOGW(TAG, "_lfs_open, uri:%s", uri);
const char *path = NULL;
const char *prefix = "file:/";
if (strstr(uri, prefix) != NULL) {
path = &uri[strlen(prefix)];
}
audio_element_getinfo(self, &info);
if (path == NULL) {
ESP_LOGE(TAG, "Error, uri path[%s] not exist", uri);
return ESP_FAIL;
} else {
struct stat sb = { 0 };
/* check if path exists */
if (vfs->type == AUDIO_STREAM_READER && stat(path, &sb) != 0) {
ESP_LOGE(TAG, "Error, file not exist, path=[%s]", path);
return ESP_FAIL;
} else {
info.total_bytes = sb.st_size;
}
}
if (vfs->is_open) {
ESP_LOGE(TAG, "already opened");
return ESP_FAIL;
}
if (vfs->type == AUDIO_STREAM_READER) {
vfs->file = open(path, O_RDONLY);
ESP_LOGI(TAG, "File size is %d byte,pos:%d", (int)info.total_bytes, (int)info.byte_pos);
} else if (vfs->type == AUDIO_STREAM_WRITER) {
vfs->file = open(path, O_WRONLY | O_CREAT | O_TRUNC);
vfs->w_type = get_type(path);
if (vfs->file > 0 && STREAM_TYPE_WAV == vfs->w_type) {
wav_header_t info = { 0 };
write(vfs->file, &info, sizeof(wav_header_t));
fsync(vfs->file);
} else if (vfs->file > 0 && (STREAM_TYPE_AMR == vfs->w_type)) {
write(vfs->file, "#!AMR\n", 6);
fsync(vfs->file);
} else if (vfs->file > 0 && (STREAM_TYPE_AMRWB == vfs->w_type)) {
write(vfs->file, "#!AMR-WB\n", 9);
fsync(vfs->file);
}
} else {
ESP_LOGE(TAG, "vfs must be Reader or Writer");
return ESP_FAIL;
}
if (vfs->file <= 0) {
ESP_LOGE(TAG, "Failed to open file %s", path);
return ESP_FAIL;
}
vfs->is_open = true;
if (info.byte_pos && lseek(vfs->file, info.byte_pos, SEEK_SET) != 0) {
ESP_LOGE(TAG, "Failed to seek to %d/%d", (int)info.byte_pos, (int)info.total_bytes);
return ESP_FAIL;
}
return audio_element_setinfo(self, &info);
}
static int _lfs_read(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait, void *context)
{
vfs_stream_t *vfs = (vfs_stream_t *)audio_element_getdata(self);
audio_element_info_t info;
audio_element_getinfo(self, &info);
ESP_LOGD(TAG, "read len=%d, pos=%d/%d", len, (int)info.byte_pos, (int)info.total_bytes);
int rlen = read(vfs->file, buffer, len);
if (rlen <= 0) {
ESP_LOGW(TAG, "No more data,ret:%d", rlen);
rlen = 0;
} else {
info.byte_pos += rlen;
audio_element_setinfo(self, &info);
}
return rlen;
}
static int _lfs_write(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait, void *context)
{
vfs_stream_t *vfs = (vfs_stream_t *)audio_element_getdata(self);
audio_element_info_t info;
audio_element_getinfo(self, &info);
int wlen = write(vfs->file, buffer, len);
fsync(vfs->file);
ESP_LOGD(TAG, "write,%d, errno:%d,pos:%d", wlen, errno, (int)info.byte_pos);
if (wlen > 0) {
info.byte_pos += wlen;
audio_element_setinfo(self, &info);
}
return wlen;
}
static esp_err_t _lfs_close(audio_element_handle_t self)
{
vfs_stream_t *vfs = (vfs_stream_t *)audio_element_getdata(self);
if (AUDIO_STREAM_WRITER == vfs->type && vfs->file && STREAM_TYPE_WAV == vfs->w_type) {
wav_header_t *wav_info = (wav_header_t *)audio_malloc(sizeof(wav_header_t));
AUDIO_MEM_CHECK(TAG, wav_info, return ESP_ERR_NO_MEM);
if (lseek(vfs->file, 0, SEEK_SET) != 0) {
ESP_LOGE(TAG, "Error seek file ,line=%d", __LINE__);
}
audio_element_info_t info;
audio_element_getinfo(self, &info);
wav_head_init(wav_info, info.sample_rates, info.bits, info.channels);
wav_head_size(wav_info, (uint32_t)info.byte_pos);
write(vfs->file, wav_info, sizeof(wav_header_t));
fsync(vfs->file);
close(vfs->file);
audio_free(wav_info);
}
if (vfs->is_open) {
close(vfs->file);
vfs->file = -1;
vfs->is_open = false;
}
if (AEL_STATE_PAUSED != audio_element_get_state(self)) {
audio_element_report_info(self);
audio_element_info_t info = { 0 };
audio_element_getinfo(self, &info);
info.byte_pos = 0;
audio_element_setinfo(self, &info);
}
return ESP_OK;
}
#else
static int get_len(mp_obj_t stream)
{
mp_obj_t tell;
mp_load_method(stream, MP_QSTR_tell, &tell);
mp_stream_posix_lseek(stream, 0, SEEK_END);
mp_obj_t len = mp_call_function_1(tell, stream);
mp_stream_posix_lseek(stream, 0, SEEK_SET);
return (int)mp_obj_get_int(len);
}
static esp_err_t _vfs_open(audio_element_handle_t self)
{
vfs_stream_t *vfs = (vfs_stream_t *)audio_element_getdata(self);
audio_element_info_t info;
char *uri = audio_element_get_uri(self);
if (uri == NULL) {
ESP_LOGE(TAG, "Error, uri is not set");
return ESP_FAIL;
}
ESP_LOGW(TAG, "_vfs_open, uri:%s", uri);
const char *path = NULL;
const char *prefix = "file:/";
if (strstr(uri, prefix) != NULL) {
path = &uri[strlen(prefix)];
}
audio_element_getinfo(self, &info);
if (path == NULL) {
ESP_LOGE(TAG, "Error, uri path[%s] not exist", uri);
return ESP_FAIL;
} else {
struct stat sb = { 0 };
/* check if path exists for player */
if ((vfs->type == AUDIO_STREAM_READER) && stat(path, &sb) != 0) {
ESP_LOGE(TAG, "Error, file not exist, path=[%s]", path);
return ESP_FAIL;
}
}
if (vfs->is_open) {
ESP_LOGE(TAG, "already opened");
return ESP_FAIL;
}
if (vfs->type == AUDIO_STREAM_READER) {
mp_obj_t args[2];
args[0] = mp_obj_new_str(path, strlen(path));
args[1] = mp_obj_new_str("rb", strlen("rb"));
vfs->file = mp_vfs_open(2, args, (mp_map_t *)&mp_const_empty_map);
info.total_bytes = get_len(vfs->file);
ESP_LOGI(TAG, "File size is %d byte,pos:%d", (int)info.total_bytes, (int)info.byte_pos);
if (vfs->file != mp_const_none && (info.byte_pos > 0)) {
if (mp_stream_posix_lseek(vfs->file, info.byte_pos, SEEK_SET) != 0) {
ESP_LOGE(TAG, "Error seek file");
return ESP_FAIL;
}
}
} else if (vfs->type == AUDIO_STREAM_WRITER) {
mp_obj_t args[2];
args[0] = mp_obj_new_str(path, strlen(path));
args[1] = mp_obj_new_str("wb", strlen("wb"));
vfs->file = mp_vfs_open(2, args, (mp_map_t *)&mp_const_empty_map);
vfs->w_type = get_type(path);
if (vfs->file != mp_const_none && STREAM_TYPE_WAV == vfs->w_type) {
wav_header_t info = { 0 };
mp_stream_posix_write(vfs->file, &info, sizeof(wav_header_t));
mp_stream_posix_fsync(vfs->file);
} else if (vfs->file != mp_const_none && (STREAM_TYPE_AMR == vfs->w_type)) {
mp_stream_posix_write(vfs->file, "#!AMR\n", 6);
mp_stream_posix_fsync(vfs->file);
} else if (vfs->file != mp_const_none && (STREAM_TYPE_AMRWB == vfs->w_type)) {
mp_stream_posix_write(vfs->file, "#!AMR-WB\n", 9);
mp_stream_posix_fsync(vfs->file);
}
} else {
ESP_LOGE(TAG, "vfs must be Reader or Writer");
return ESP_FAIL;
}
if (vfs->file == mp_const_none) {
ESP_LOGE(TAG, "Failed to open file %s", path);
return ESP_FAIL;
}
vfs->is_open = true;
if (info.byte_pos && mp_stream_posix_lseek(vfs->file, info.byte_pos, SEEK_SET) != 0) {
ESP_LOGE(TAG, "Failed to seek to %d/%d", (int)info.byte_pos, (int)info.total_bytes);
return ESP_FAIL;
}
return audio_element_setinfo(self, &info);
}
static int _vfs_read(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait, void *context)
{
vfs_stream_t *vfs = (vfs_stream_t *)audio_element_getdata(self);
audio_element_info_t info;
audio_element_getinfo(self, &info);
ESP_LOGD(TAG, "read len=%d, pos=%d/%d", len, (int)info.byte_pos, (int)info.total_bytes);
int rlen = mp_stream_posix_read(vfs->file, buffer, len);
if (rlen <= 0) {
ESP_LOGW(TAG, "No more data,ret:%d", rlen);
rlen = 0;
} else {
info.byte_pos += rlen;
audio_element_setinfo(self, &info);
}
return rlen;
}
static int _vfs_write(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait, void *context)
{
vfs_stream_t *vfs = (vfs_stream_t *)audio_element_getdata(self);
audio_element_info_t info;
audio_element_getinfo(self, &info);
int wlen = mp_stream_posix_write(vfs->file, buffer, len);
mp_stream_posix_fsync(vfs->file);
ESP_LOGD(TAG, "mp_stream_posix_write,%d, errno:%d,pos:%d", wlen, errno, (int)info.byte_pos);
if (wlen > 0) {
info.byte_pos += wlen;
audio_element_setinfo(self, &info);
}
return wlen;
}
static esp_err_t _vfs_close(audio_element_handle_t self)
{
vfs_stream_t *vfs = (vfs_stream_t *)audio_element_getdata(self);
if (AUDIO_STREAM_WRITER == vfs->type && vfs->file && STREAM_TYPE_WAV == vfs->w_type) {
wav_header_t *wav_info = (wav_header_t *)audio_malloc(sizeof(wav_header_t));
AUDIO_MEM_CHECK(TAG, wav_info, return ESP_ERR_NO_MEM);
if (mp_stream_posix_lseek(vfs->file, 0, SEEK_SET) != 0) {
ESP_LOGE(TAG, "Error seek file ,line=%d", __LINE__);
}
audio_element_info_t info;
audio_element_getinfo(self, &info);
wav_head_init(wav_info, info.sample_rates, info.bits, info.channels);
wav_head_size(wav_info, (uint32_t)info.byte_pos);
mp_stream_posix_write(vfs->file, wav_info, sizeof(wav_header_t));
mp_stream_posix_fsync(vfs->file);
mp_stream_close(vfs->file);
audio_free(wav_info);
}
if (vfs->is_open) {
mp_obj_t close;
mp_load_method(vfs->file, MP_QSTR_close, &close);
mp_call_function_1(close, vfs->file);
vfs->is_open = false;
}
if (AEL_STATE_PAUSED != audio_element_get_state(self)) {
audio_element_report_info(self);
audio_element_info_t info = { 0 };
audio_element_getinfo(self, &info);
info.byte_pos = 0;
audio_element_setinfo(self, &info);
}
return ESP_OK;
}
#endif
static esp_err_t _vfs_destroy(audio_element_handle_t self)
{
vfs_stream_t *vfs = (vfs_stream_t *)audio_element_getdata(self);
audio_free(vfs);
return ESP_OK;
}
static int _vfs_process(audio_element_handle_t self, char *in_buffer, int in_len)
{
int r_size = audio_element_input(self, in_buffer, in_len);
int w_size = 0;
if (r_size > 0) {
w_size = audio_element_output(self, in_buffer, r_size);
} else {
w_size = r_size;
}
return w_size;
}
audio_element_handle_t vfs_stream_init(vfs_stream_cfg_t *config)
{
audio_element_handle_t el;
vfs_stream_t *vfs = audio_calloc(1, sizeof(vfs_stream_t));
AUDIO_MEM_CHECK(TAG, vfs, return NULL);
audio_element_cfg_t cfg = DEFAULT_AUDIO_ELEMENT_CONFIG();
#if AUDIO_FILE_LFS
cfg.open = _lfs_open;
cfg.close = _lfs_close;
#else
cfg.open = _vfs_open;
cfg.close = _vfs_close;
#endif
cfg.process = _vfs_process;
cfg.destroy = _vfs_destroy;
cfg.task_stack = config->task_stack;
cfg.task_prio = config->task_prio;
cfg.task_core = config->task_core;
cfg.out_rb_size = config->out_rb_size;
cfg.buffer_len = config->buf_sz;
if (cfg.buffer_len == 0) {
cfg.buffer_len = VFS_STREAM_BUF_SIZE;
}
cfg.tag = "file";
vfs->type = config->type;
if (config->type == AUDIO_STREAM_WRITER) {
#if AUDIO_FILE_LFS
cfg.write = _lfs_write;
#else
cfg.write = _vfs_write;
#endif
} else {
#if AUDIO_FILE_LFS
cfg.read = _lfs_read;
#else
cfg.read = _vfs_read;
#endif
}
el = audio_element_init(&cfg);
AUDIO_MEM_CHECK(TAG, el, goto _vfs_init_exit);
audio_element_setdata(el, vfs);
return el;
_vfs_init_exit:
audio_free(vfs);
return NULL;
}
#endif // MICROPY_PY_AUDIO | YifuLiu/AliOS-Things | components/py_engine/modules/audio/esp32/vfs_stream.c | C | apache-2.0 | 15,562 |
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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 _VFS_STREAM_H_
#define _VFS_STREAM_H_
#if MICROPY_PY_AUDIO
#include "audio_element.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief FATFS Stream configurations, if any entry is zero then the configuration will be set to default values
*/
typedef struct {
audio_stream_type_t type; /*!< Stream type */
int buf_sz; /*!< Audio Element Buffer size */
int out_rb_size; /*!< Size of output ringbuffer */
int task_stack; /*!< Task stack size */
int task_core; /*!< Task running in core (0 or 1) */
int task_prio; /*!< Task priority (based on freeRTOS priority) */
} vfs_stream_cfg_t;
#define VFS_STREAM_BUF_SIZE (2048)
#define VFS_STREAM_TASK_STACK (3072)
#define VFS_STREAM_TASK_CORE (0)
#define VFS_STREAM_TASK_PRIO (4)
#define VFS_STREAM_RINGBUFFER_SIZE (8 * 1024)
#define VFS_STREAM_CFG_DEFAULT() \
{ \
.type = AUDIO_STREAM_NONE, \
.buf_sz = VFS_STREAM_BUF_SIZE, \
.out_rb_size = VFS_STREAM_RINGBUFFER_SIZE, \
.task_stack = VFS_STREAM_TASK_STACK, \
.task_core = VFS_STREAM_TASK_CORE, \
.task_prio = VFS_STREAM_TASK_PRIO, \
}
/**
* @brief Create a handle to an Audio Element to stream data from FatFs to another Element
* or get data from other elements written to FatFs, depending on the configuration
* the stream type, either AUDIO_STREAM_READER or AUDIO_STREAM_WRITER.
*
* @param config The configuration
*
* @return The Audio Element handle
*/
audio_element_handle_t vfs_stream_init(vfs_stream_cfg_t *config);
#ifdef __cplusplus
}
#endif
#endif // MICROPY_PY_AUDIO
#endif | YifuLiu/AliOS-Things | components/py_engine/modules/audio/esp32/vfs_stream.h | C | apache-2.0 | 2,996 |
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_AUDIO=1)
# Collect audio micropython port source
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/audio/esp32/modaudio.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/audio/esp32/audio_player.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/audio/esp32/audio_recorder.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/audio/esp32/vfs_stream.c)
# Collect ADF Library Sources
file(GLOB AUDIO_SAL_SRC RELATIVE $ENV{IDF_PATH}/components/audio_sal "*.c")
file(GLOB AUDIO_PIPLINE_SRC RELATIVE $ENV{IDF_PATH}/components/audio_pipeline "*.c")
file(GLOB AUDIO_STREAM_SRC RELATIVE $ENV{IDF_PATH}/components/audio_stream "*.c")
file(GLOB AUDIO_CODEC_SRC RELATIVE $ENV{IDF_PATH}/components/esp-adf-libs/esp_codec "*.c")
file(GLOB AUDIO_BOARD_SRC RELATIVE $ENV{IDF_PATH}/components/audio_board/m5stack_core2 "*.c")
file(GLOB AUDIO_HAL_SRC RELATIVE $ENV{IDF_PATH}/components/audio_hal "*.c")
file(GLOB ESP_DISPATCHER_SRC RELATIVE $ENV{IDF_PATH}/components/esp_dispatcher "*.c")
file(GLOB AUDIO_HAL_DRIVER_SRC RELATIVE $ENV{IDF_PATH}/components/audio_hal/driver/ns4168 "*.c")
list(APPEND MICROPY_SOURCE_MODULES_PORT
${AUDIO_SAL_SRC}
${AUDIO_PIPLINE_SRC}
${AUDIO_STREAM_SRC}
${AUDIO_CODEC_SRC}
${AUDIO_BOARD_SRC}
${AUDIO_HAL_SRC}
${ESP_DISPATCHER_SRC}
${AUDIO_HAL_DRIVER_SRC}
)
# append audio include
list(APPEND MICROPY_INC_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/audio/esp32)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{IDF_PATH}/components/esp-adf-libs/esp_audio/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{IDF_PATH}/components/adf_utils/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{IDF_PATH}/components/audio_hal/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{IDF_PATH}/components/audio_pipeline/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{IDF_PATH}/components/audio_sal/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{IDF_PATH}/components/audio_stream/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{IDF_PATH}/components/esp-adf-libs/audio_misc/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{IDF_PATH}/components/esp-adf-libs/esp_audio/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{IDF_PATH}/components/esp-adf-libs/esp_codec/include/codec)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{IDF_PATH}/components/esp-adf-libs/esp_codec/include/processing)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{IDF_PATH}/components/esp-adf-libs/recorder_engine/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{IDF_PATH}/components/esp-adf-libs/audio_board/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{IDF_PATH}/components/esp-adf-libs/audio_board/m5stack_core2)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{IDF_PATH}/components/esp-adf-libs/esp-sr/lib/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{IDF_PATH}/components/esp-adf-libs/esp_dispatcher/include)
list(APPEND MICROPY_INC_MODULES_PORT $ENV{IDF_PATH}/components/audio_hal/driver/include)
# add_prebuilt_library(esp_audio "$ENV{IDF_PATH}/components/esp-adf-libs/esp_audio/lib/esp32/libesp_audio.a"
# PRIV_REQUIRES esp-adf-libs)
# add_prebuilt_library(esp_codec "$ENV{IDF_PATH}/components/esp-adf-libs/esp_codec/lib/esp32/libesp_codec.a"
# PRIV_REQUIRES esp-adf-libs)
# add_prebuilt_library(esp_processing "$ENV{IDF_PATH}/components/esp-adf-libs/esp_codec/lib/esp32/libesp_processing.a"
# PRIV_REQUIRES esp-adf-libs)
target_link_libraries(${MICROPY_TARGET} "-Wl,--start-group"
esp_processing esp_audio esp_codec "-Wl,--end-group")
| YifuLiu/AliOS-Things | components/py_engine/modules/audio/modaudio.cmake | CMake | apache-2.0 | 3,649 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "modble.h"
#include "bluetooth/addr.h"
#include "ulog/ulog.h"
#define LOG_TAG "BT_GATTS_ADAPTER"
size_t g_attr_num = 0;
gatt_attr_t *g_attrs_list = NULL;
int bt_gatts_adapter_update_user_data(size_t index, uint16_t uuid, uint8_t *data, size_t len);
uint16_t get_16bits_hex_from_string(const char *str)
{
uint16_t ret = 0, tmp = 0, ii = 0, jj = 0;
uint32_t sample_len = strlen("0xAABB");
uint8_t seed[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
if (strlen(str) == sample_len) {
if (strncmp(str, "0x", 2) && strncmp(str, "0X", 2)) {
} else {
for (ii = sample_len - 1; ii >= sample_len - 4; ii--) {
// to uppercase
if (str[ii] >= 'a') {
tmp = str[ii] - ('a' - 'A');
} else {
tmp = str[ii];
}
// char to number
for (jj = 0; jj < sizeof(seed); jj++) {
if (seed[jj] == tmp) {
break;
}
}
ret += jj << ((sample_len - 1 - ii) * 4);
}
}
}
// LOGD(LOG_TAG, "[%s] %s -> 0x%X", __func__, str, ret);
return ret;
}
gatt_perm_en get_attr_perm_from_string(char *str)
{
gatt_perm_en ret = GATT_PERM_NONE;
if (strstr(str, "R")) {
ret |= GATT_PERM_READ;
}
if (strstr(str, "W")) {
ret |= GATT_PERM_WRITE;
}
return ret;
}
gatt_prop_en get_char_perm_from_string(char *str)
{
gatt_prop_en ret = 0;
if (strstr(str, "R")) {
ret |= GATT_CHRC_PROP_READ;
}
if (strstr(str, "W")) {
ret |= GATT_CHRC_PROP_WRITE;
}
return ret;
}
static gatt_service srvc_instance = { 0 };
uuid_t *bt_gatts_declare_16bits_uuid(uint16_t val)
{
struct ut_uuid_16 *uuid = (struct ut_uuid_16 *)malloc(sizeof(struct ut_uuid_16));
uuid->uuid.type = UUID_TYPE_16;
uuid->val = val;
return (uuid_t *)uuid;
}
void bt_gatts_define_gatt_srvc(gatt_attr_t *out, uint16_t uuid)
{
LOGD(LOG_TAG, "[%s] declare service uuid 0x%04x", __func__, uuid);
out->uuid = bt_gatts_declare_16bits_uuid(0x2800); // UUID_GATT_PRIMARY;
out->perm = GATT_PERM_READ;
out->read = out->write = NULL;
out->user_data = (void *)bt_gatts_declare_16bits_uuid(uuid);
}
void bt_gatts_define_gatt_char(gatt_attr_t *out, uint16_t uuid, uint8_t perimt)
{
LOGD(LOG_TAG, "[%s] declare char uuid 0x%04x", __func__, uuid);
struct gatt_char_t *data = (struct gatt_char_t *)malloc(sizeof(struct gatt_char_t));
memset(data, 0, sizeof(struct gatt_char_t));
data->uuid = bt_gatts_declare_16bits_uuid(uuid);
data->value_handle = 0;
data->properties = perimt,
out->uuid = bt_gatts_declare_16bits_uuid(0x2803); // UUID_GATT_CHRC;
out->perm = GATT_PERM_READ;
out->read = out->write = NULL;
out->user_data = (void *)data;
}
void bt_gatts_define_gatt_char_val(gatt_attr_t *out, uint16_t uuid, uint8_t perimt)
{
LOGD(LOG_TAG, "[%s] declare char val uuid 0x%04x", __func__, uuid);
out->uuid = bt_gatts_declare_16bits_uuid(uuid);
out->perm = perimt;
out->read = out->write = NULL;
out->user_data = NULL;
}
void bt_gatts_define_ccc(gatt_attr_t *out)
{
LOGD(LOG_TAG, "[%s] declare ccc ...", __func__);
struct bt_gatt_ccc_t *ccc = (struct bt_gatt_ccc_t *)malloc(sizeof(struct bt_gatt_ccc_t));
memset(ccc, 0, sizeof(struct bt_gatt_ccc_t));
out->uuid = bt_gatts_declare_16bits_uuid(0x2902); // UUID_GATT_CCC;
out->perm = GATT_PERM_READ | GATT_PERM_WRITE;
out->read = out->write = NULL;
out->user_data = (void *)ccc;
}
int bt_gatts_adapter_add_service(amp_bt_host_adapter_gatts_srvc_t *srvc)
{
int ret = 0;
amp_bt_host_adapter_gatt_chars_t *char_list = NULL;
if (srvc) {
g_attrs_list = (gatt_attr_t *)aos_malloc(srvc->attr_cnt * sizeof(gatt_attr_t));
if (!g_attrs_list) {
LOGE(LOG_TAG, "[%s] memory not enough for g_attrs_list", __func__);
return ret;
}
memset(g_attrs_list, 0, srvc->attr_cnt * sizeof(gatt_attr_t));
char_list = srvc->chars;
// declare the service
bt_gatts_define_gatt_srvc(&g_attrs_list[g_attr_num++], get_16bits_hex_from_string(srvc->s_uuid));
while (g_attr_num < srvc->attr_cnt) {
if (char_list->descr_type) {
if (0 == strcmp(char_list->descr_type, "CCC")) {
bt_gatts_define_gatt_char(&g_attrs_list[g_attr_num++],
get_16bits_hex_from_string(char_list->char_uuid),
GATT_CHRC_PROP_NOTIFY | get_char_perm_from_string(char_list->permission));
bt_gatts_define_gatt_char_val(&g_attrs_list[g_attr_num++],
get_16bits_hex_from_string(char_list->char_uuid),
get_attr_perm_from_string(char_list->permission));
bt_gatts_define_ccc(&g_attrs_list[g_attr_num++]);
char_list++;
continue;
} else {
/* CUD, SCC, CPF, CAF*/
LOGW(LOG_TAG, "[%s] unsupported descr type: %s ", __func__, char_list->descr_type);
}
}
bt_gatts_define_gatt_char(&g_attrs_list[g_attr_num++], get_16bits_hex_from_string(char_list->char_uuid),
GATT_CHRC_PROP_NOTIFY | get_char_perm_from_string(char_list->permission));
bt_gatts_define_gatt_char_val(&g_attrs_list[g_attr_num++], get_16bits_hex_from_string(char_list->char_uuid),
get_attr_perm_from_string(char_list->permission));
char_list++;
}
LOGD(LOG_TAG, "[%s] declare service done, total attr: %d(%d)", __func__, g_attr_num, srvc->attr_cnt);
// >=0: handle, <0: error
ret = ble_stack_gatt_registe_service(&srvc_instance, g_attrs_list, srvc->attr_cnt);
LOGD(LOG_TAG, "[%s] add service done with ret %d", __func__, ret);
} else {
LOGE(LOG_TAG, "[%s] srvc is null", __func__);
}
return ret;
}
int bt_gatts_adapter_update_user_data(size_t index, uint16_t uuid_val, uint8_t *data, size_t len)
{
int ret = -1;
int ii;
gatt_attr_t *ptr = NULL;
if (index >= 0 && index < g_attr_num) {
ptr = &(g_attrs_list[index]);
} else {
for (ii = 0; ii < g_attr_num; ii++) {
if (((struct ut_uuid_16 *)(g_attrs_list[ii].uuid))->val == uuid_val) {
ptr = &(g_attrs_list[ii]);
ret = ii;
break;
}
}
}
if (ptr == NULL) {
LOGE(LOG_TAG, "[%s] give up updating as uuid not matched!!", __func__);
return -1;
}
amp_bt_gatts_adapter_usr_data_t *old = (amp_bt_gatts_adapter_usr_data_t *)ptr->user_data;
amp_bt_gatts_adapter_usr_data_t **new = (amp_bt_gatts_adapter_usr_data_t **)&(ptr->user_data);
if (old) {
if (old->data) {
free(old->data);
} else {
LOGE(LOG_TAG, "[%s] old is avaliable, but data is null. should NOT be here!!", __func__);
}
free(old);
}
*new = (amp_bt_gatts_adapter_usr_data_t *)malloc(sizeof(amp_bt_gatts_adapter_usr_data_t));
if (*new) {
(*new)->len = len;
(*new)->data = (uint8_t *)malloc(sizeof(uint8_t) * len);
if ((*new)->data) {
memcpy((*new)->data, data, len);
LOGD(LOG_TAG, "[%s]update user data:%p -> %p", __func__, old, *new);
} else {
free(*new);
LOGE(LOG_TAG, "[%s][%d] memory not enough for new data!", __func__, __LINE__);
}
} else {
LOGE(LOG_TAG, "[%s][%d] memory not enough for new data!", __func__, __LINE__);
}
return ret;
}
static int bt_gatts_adapter_char_get_desc_idx(int start_idx, int16_t uuid)
{
int idx = -1;
int i;
for (i = start_idx; i < g_attr_num; i++) {
if (UUID16(g_attrs_list[i].uuid) == uuid) {
idx = i;
break;
}
if (UUID16(g_attrs_list[i].uuid) == UUID16(UUID_GATT_CHRC)) {
break;
}
}
return idx;
}
int bt_gatts_adapter_update_chars(char *uuid, uint8_t *data, size_t len)
{
amp_bt_gatts_adapter_usr_data_t *old_data = NULL;
int32_t index, ccc_index;
index = bt_gatts_adapter_update_user_data(-1, get_16bits_hex_from_string(uuid), data, len);
LOGD(LOG_TAG, "[%s] index = %d, uuid = %s, len = %d", __func__, index, uuid, len);
if (index < 0) {
return -1;
}
if (index < g_attr_num) {
uint16_t *conn_handle = NULL;
struct bt_gatt_ccc_t *ccc;
ccc_index = bt_gatts_adapter_char_get_desc_idx(index, UUID16(UUID_GATT_CCC));
if (ccc_index < 0) {
LOGE(LOG_TAG, "[%s]ccc not found", __func__);
return -1;
}
ccc = (struct bt_gatt_ccc_t *)g_attrs_list[ccc_index].user_data;
for (int jj = 0; jj < ARRAY_SIZES(ccc->cfg); jj++) {
conn_handle = (uint16_t *)bt_conn_lookup_addr_le(ccc->cfg->id, (const bt_addr_le_t *)&ccc->cfg[jj].peer);
if (conn_handle > 0) {
if (ccc->cfg[0].value) {
ble_stack_gatt_notificate(*conn_handle, g_attrs_list[index].handle, data, len);
}
}
}
}
return 0;
}
void bt_gatts_dump_hex(uint8_t data[], size_t len)
{
printf("\t\tDUMP START: ");
for (int ii = 0; ii < len; ii++) {
printf("%02x ", data[ii]);
}
printf("\n");
}
int bt_gatts_adapter_event_callback(ble_event_en event, void *event_data)
{
switch (event) {
case EVENT_GATT_CHAR_READ:
{
evt_data_gatt_char_read_t *read_data = (evt_data_gatt_char_read_t *)event_data;
for (int ii = 0; ii < g_attr_num; ii++) {
if (g_attrs_list[ii].handle == read_data->char_handle) {
LOGD(LOG_TAG,
"[%s]read request at handle.%d, uuid:0x%04x, "
"offset:%d",
__func__, read_data->char_handle, ((struct ut_uuid_16 *)(g_attrs_list[ii].uuid))->val,
read_data->offset);
amp_bt_gatts_adapter_usr_data_t *data =
(amp_bt_gatts_adapter_usr_data_t *)g_attrs_list[ii].user_data;
if (data) {
if (data->data && data->len) {
bt_gatts_dump_hex(data->data, data->len);
read_data->data = data->data;
// memcpy(read_data->data, data->data,
// data->len);
read_data->len = data->len;
break;
}
}
LOGE(LOG_TAG, "[%s][%d] no data to be read!", __func__, __LINE__);
}
}
}
break;
case EVENT_GATT_CHAR_WRITE:
{
evt_data_gatt_char_write_t *write_data = (evt_data_gatt_char_write_t *)event_data;
for (int ii = 0; ii < g_attr_num; ii++) {
if (g_attrs_list[ii].handle == write_data->char_handle) {
LOGD(LOG_TAG,
"[%s]read request at handle.%d, uuid:0x%04x, "
"offset:%d\n",
__func__, write_data->char_handle, ((struct ut_uuid_16 *)(g_attrs_list[ii].uuid))->val,
write_data->offset);
bt_gatts_adapter_update_user_data(ii, 0, (uint8_t *)write_data->data, write_data->len);
amp_bt_gatts_adapter_usr_data_t *data =
(amp_bt_gatts_adapter_usr_data_t *)g_attrs_list[ii].user_data;
// bt_gatts_dump_hex(data->data, data->len);
native_bt_host_gatts_handle_write((uint8_t *)write_data->data, write_data->len);
break;
}
}
}
break;
case EVENT_GATT_CHAR_CCC_CHANGE:
{
evt_data_gatt_char_ccc_change_t *data = (evt_data_gatt_char_ccc_change_t *)event_data;
for (int ii = 0; ii < g_attr_num; ii++) {
if (g_attrs_list[ii].handle == data->char_handle) {
struct bt_gatt_ccc_t *ccc = (struct bt_gatt_ccc_t *)g_attrs_list[ii].user_data;
LOGD(LOG_TAG, "[%s]ccc-changed at handle.%d 0x%04x, 0x%04x,\n", __func__, data->char_handle,
data->ccc_value, ccc->value);
}
}
}
break;
default:
break;
}
}
| YifuLiu/AliOS-Things | components/py_engine/modules/ble/bt_gatts_adapter.c | C | apache-2.0 | 12,951 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "ulog/ulog.h"
#include "modble.h"
#define LOG_TAG "BT_HOST_ADAPTER"
static void bt_host_adapter_adv_data_destroy(ad_data_t *ad_data, int ad_num);
static int bt_host_adapter_event_callback(ble_event_en event, void *event_data);
extern int bt_gatts_adapter_event_callback(ble_event_en event,
void *event_data);
#ifdef CHIP_HAAS1000
extern int netdev_set_epta_params(int wlan_duration, int bt_duration,
int hw_epta_enable);
#endif
static ble_event_cb_t bt_host_adapter_ble_cb = {
.callback = bt_host_adapter_event_callback,
};
static int bt_host_adapter_char2hex(char c, char *x)
{
if (c >= '0' && c <= '9') {
*x = c - '0';
} else if (c >= 'a' && c <= 'f') {
*x = c - 'a' + 10;
} else if (c >= 'A' && c <= 'F') {
*x = c - 'A' + 10;
} else {
return -1;
}
return 0;
}
static int bt_host_adapter_hex2bin(char *hex, uint8_t *buf)
{
char dec;
int hexlen, i;
hexlen = strlen(hex);
if (hexlen == 0) {
return 0;
}
/* if hexlen is uneven, return failed */
if (hexlen % 2) {
return 0;
}
/* regular hex conversion */
for (i = 0; i < hexlen / 2; i++) {
if (bt_host_adapter_char2hex(hex[2 * i], &dec) < 0) {
return 0;
}
buf[i] = dec << 4;
if (bt_host_adapter_char2hex(hex[2 * i + 1], &dec) < 0) {
return 0;
}
buf[i] += dec;
}
return hexlen / 2;
}
int bt_host_adapter_bin2hex(char *hex, uint8_t *buf, uint8_t buf_len)
{
int i;
if (hex == NULL)
return 0;
hex[0] = 0;
for (i = 0; i < buf_len; i++) {
sprintf(hex + strlen(hex), "%02x", buf[i]);
}
return buf_len * 2;
}
static int bt_host_adapter_addr2hex(char *hex, uint8_t *addr)
{
int i;
if (hex == NULL)
return 0;
hex[0] = 0;
for (i = 0; i < 6; i++) {
sprintf(hex + strlen(hex), "%02x:", addr[5 - i]);
}
hex[17] = 0;
return i * 3 - 1;
}
static int bt_host_adapter_event_callback(ble_event_en event, void *event_data)
{
LOGD(LOG_TAG, "%s, event = %x", __func__, event);
switch (event) {
case EVENT_GAP_CONN_CHANGE:
{
evt_data_gap_conn_change_t *e =
(evt_data_gap_conn_change_t *)event_data;
int32_t connect;
if (e->connected == CONNECTED) {
connect = 1;
#ifdef CHIP_HAAS1000
netdev_set_epta_params(40000, 60000, 0);
#endif
} else {
connect = 0;
}
py_ble_event_notify(e->conn_handle, connect);
}
break;
default:
bt_gatts_adapter_event_callback(event, event_data);
break;
}
return 0;
}
static ad_data_t *bt_host_adapter_adv_data_parse(char *adv_data, int8_t *num)
{
int ad_num;
int i, type, len, adv_len;
ad_data_t *ad_data;
uint8_t adv_bin[31];
if (adv_data == NULL) {
return NULL;
}
adv_len = strlen(adv_data);
if (adv_len == 0 || adv_len > 62) {
return NULL;
}
adv_len = bt_host_adapter_hex2bin(adv_data, adv_bin);
ad_num = 0;
for (i = 0; i < adv_len;) {
len = adv_bin[i];
if (i + len >= adv_len) {
LOGD(LOG_TAG, "%s, wrong data %s", __func__, adv_data);
return NULL;
}
i += len + 1;
ad_num++;
}
if (ad_num == 0) {
return NULL;
}
ad_data = aos_malloc(ad_num * sizeof(ad_data_t));
if (ad_data == NULL) {
return NULL;
}
memset(ad_data, 0, sizeof(ad_num * sizeof(ad_data_t)));
ad_num = 0;
for (i = 0; i < adv_len;) {
len = adv_bin[i];
ad_data[ad_num].len = len - 1;
ad_data[ad_num].type = adv_bin[i + 1];
ad_data[ad_num].data = aos_malloc(len - 1);
if (ad_data[ad_num].data == NULL) {
bt_host_adapter_adv_data_destroy(ad_data, ad_num);
return NULL;
}
memcpy(ad_data[ad_num].data, adv_bin + i + 2, len - 1);
i += len + 1;
ad_num++;
}
if (num) {
*num = ad_num;
}
return ad_data;
}
static void bt_host_adapter_adv_data_destroy(ad_data_t *ad_data, int ad_num)
{
int i;
for (i = 0; i < ad_num; i++) {
if (ad_data[i].data) {
aos_free(ad_data[i].data);
}
}
aos_free(ad_data);
}
int py_bt_host_adapter_init(amp_bt_host_adapter_init_t *init)
{
init_param_t param = { 0 };
int ret = -1;
param.dev_name = init->dev_name;
param.conn_num_max = init->conn_num_max;
param.dev_addr = NULL;
ret = ble_stack_init(¶m);
if (ret != BLE_STACK_OK) {
return -1;
}
#ifdef CHIP_HAAS1000
/* HaaS100/EDU WI-FI/蓝牙共存设置 */
netdev_set_epta_params(40000, 60000, 0);
#endif
ret = ble_stack_event_register(&bt_host_adapter_ble_cb);
if (ret) {
return -1;
}
return ret;
}
int bt_host_adapter_start_adv(amp_bt_host_adapter_adv_start_t *adv_param)
{
adv_param_t param;
int ret;
param.type = adv_param->type;
param.interval_min = adv_param->interval_min;
param.interval_max = adv_param->interval_max;
param.channel_map = adv_param->channel_map;
param.ad_num = 0;
param.sd_num = 0;
param.ad =
bt_host_adapter_adv_data_parse(adv_param->adv_data, &(param.ad_num));
param.sd = bt_host_adapter_adv_data_parse(adv_param->scan_rsp_data,
&(param.sd_num));
param.filter_policy = ADV_FILTER_POLICY_ANY_REQ;
memset(&(param.direct_peer_addr), 0, sizeof(dev_addr_t));
LOGD(LOG_TAG,
"%s, ble_stack_adv_start, type = %d, min = %d, max = %d, ch = %d, "
"ad_num = %d, sd_num = %d, ad[0].type = %d, ad[0].len = %d",
__func__, param.type, param.interval_min, param.interval_max,
param.channel_map, param.ad_num, param.sd_num, param.ad[0].type,
param.ad[0].len);
ret = ble_stack_adv_start(¶m);
LOGD(LOG_TAG, "ble_stack_adv_start ret = %d", ret);
if (param.ad) {
bt_host_adapter_adv_data_destroy(param.ad, param.ad_num);
}
if (param.sd) {
bt_host_adapter_adv_data_destroy(param.sd, param.sd_num);
}
if (ret) {
return -1;
}
return ret;
}
int bt_host_adapter_stop_adv(void)
{
int ret;
ret = ble_stack_adv_stop();
if (ret) {
return -1;
}
return ret;
}
int bt_host_adapter_start_scan(amp_bt_host_adapter_scan_start_t *scan_param)
{
scan_param_t param;
int ret;
param.type = scan_param->type;
param.interval = scan_param->interval;
param.window = scan_param->window;
param.filter_dup = SCAN_FILTER_DUP_DISABLE;
param.scan_filter = SCAN_FILTER_POLICY_ANY_ADV;
LOGD(LOG_TAG, "%s, ble_stack_scan_start, type = %d, int = %d, win = %d",
__func__, param.type, param.interval, param.window);
ret = ble_stack_scan_start(¶m);
LOGD(LOG_TAG, "ble_stack_scan_start ret = %d", ret);
if (ret) {
return -1;
}
return ret;
}
int bt_host_adapter_stop_scan(void)
{
int ret;
ret = ble_stack_scan_stop();
if (ret) {
return -1;
}
return ret;
}
| YifuLiu/AliOS-Things | components/py_engine/modules/ble/bt_host_adapter.c | C | apache-2.0 | 7,406 |